repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
AndroidX/androidx | compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/TextMeasurer.kt | 3 | 16428 | /*
* Copyright 2019 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
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.ui.text.caches.LruCache
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.constrain
import kotlin.math.ceil
/**
* Use cases that converge to this number;
* - Static text is drawn on canvas for legend and labels.
* - Text toggles between enumerated states bold, italic.
* - Multiple texts drawn but only their colors are animated.
*
* If text layout is always called with different inputs, this number is a good stopping point so
* that cache does not becomes unnecessarily large and miss penalty stays low. Of course developers
* should be aware that in a use case like that the cache should explicitly be disabled.
*/
private val DefaultCacheSize = 8
/**
* TextMeasurer is responsible for measuring a text in its entirety so that it's ready to be drawn.
*
* A TextMeasurer instance should be created via `androidx.compose.ui.rememberTextMeasurer` in a
* Composable context to use fallback values from default composition locals.
*
* Text layout is a computationally expensive task. Therefore, this class holds an internal LRU
* Cache of layout input and output pairs to optimize the repeated measure calls that use the same
* input parameters.
*
* Although most input parameters have a direct influence on layout, some parameters like color,
* brush, and shadow can be ignored during layout and set at the end. Using TextMeasurer with
* appropriate [cacheSize] should provide significant improvements while animating
* non-layout-affecting attributes like color.
*
* Moreover, if there is a need to render multiple static texts, you can provide the number of texts
* by [cacheSize] and their layouts should be cached for repeating calls. Be careful that even a
* slight change in input parameters like fontSize, maxLines, an additional character in text would
* create a distinct set of input parameters. As a result, a new layout would be calculated and a
* new set of input and output pair would be placed in LRU Cache, possibly evicting an earlier
* result.
*
* [FontFamily.Resolver], [LayoutDirection], and [Density] are required parameters to construct a
* text layout but they have no safe fallbacks outside of composition. These parameters must be
* provided during the construction of a [TextMeasurer] to be used as default values when they
* are skipped in [TextMeasurer.measure] call.
*
* @param fallbackFontFamilyResolver to be used to load fonts given in [TextStyle] and [SpanStyle]s
* in [AnnotatedString].
* @param fallbackLayoutDirection layout direction of the measurement environment.
* @param fallbackDensity density of the measurement environment. Density controls the scaling
* factor for fonts.
* @param cacheSize Capacity of internal cache inside TextMeasurer. Size unit is the number of
* unique text layout inputs that are measured. Value of this parameter highly depends on the
* consumer use case. Provide a cache size that is in line with how many distinct text layouts are
* going to be calculated by this measurer repeatedly. If you are animating font attributes, or any
* other layout affecting input, cache can be skipped because most repeated measure calls would miss
* the cache.
*/
@ExperimentalTextApi
@Immutable
class TextMeasurer constructor(
private val fallbackFontFamilyResolver: FontFamily.Resolver,
private val fallbackDensity: Density,
private val fallbackLayoutDirection: LayoutDirection,
private val cacheSize: Int = DefaultCacheSize
) {
private val textLayoutCache: TextLayoutCache? = if (cacheSize > 0) {
TextLayoutCache(cacheSize)
} else null
/**
* Creates a [TextLayoutResult] according to given parameters.
*
* This function supports laying out text that consists of multiple paragraphs, includes
* placeholders, wraps around soft line breaks, and might overflow outside the specified size.
*
* Most parameters for text affect the final text layout. One pixel change in [constraints]
* boundaries can displace a word to another line which would cause a chain reaction that
* completely changes how text is rendered.
*
* On the other hand, some attributes only play a role when drawing the created text layout.
* For example text layout can be created completely in black color but we can apply
* [TextStyle.color] later in draw phase. This also means that animating text color shouldn't
* invalidate text layout.
*
* Thus, [textLayoutCache] helps in the process of converting a set of text layout inputs to
* a text layout while ignoring non-layout-affecting attributes. Iterative calls that use the
* same input parameters should benefit from substantial performance improvements.
*
* @param text the text to be laid out
* @param style the [TextStyle] to be applied to the whole text
* @param overflow How visual overflow should be handled.
* @param softWrap Whether the text should break at soft line breaks. If false, the glyphs in
* the text will be positioned as if there was unlimited horizontal space. If [softWrap] is
* false, [overflow] and TextAlign may have unexpected effects.
* @param maxLines An optional maximum number of lines for the text to span, wrapping if
* necessary. If the text exceeds the given number of lines, it will be truncated according to
* [overflow] and [softWrap]. If it is not null, then it must be greater than zero.
* @param placeholders a list of [Placeholder]s that specify ranges of text which will be
* skipped during layout and replaced with [Placeholder]. It's required that the range of each
* [Placeholder] doesn't cross paragraph boundary, otherwise [IllegalArgumentException] is
* thrown.
* @param constraints how wide and tall the text is allowed to be. [Constraints.maxWidth]
* will define the width of the MultiParagraph. [Constraints.maxHeight] helps defining the
* number of lines that fit with ellipsis is true. [Constraints.minWidth] defines the minimum
* width the resulting [TextLayoutResult.size] will report. [Constraints.minHeight] is no-op.
* @param layoutDirection layout direction of the measurement environment. If not specified,
* defaults to the value that was given during initialization of this [TextMeasurer].
* @param density density of the measurement environment. If not specified, defaults to
* the value that was given during initialization of this [TextMeasurer].
* @param fontFamilyResolver to be used to load the font given in [SpanStyle]s. If not
* specified, defaults to the value that was given during initialization of this [TextMeasurer].
* @param skipCache Disables cache optimization if it is passed as true.
*/
@Stable
fun measure(
text: AnnotatedString,
style: TextStyle = TextStyle.Default,
overflow: TextOverflow = TextOverflow.Clip,
softWrap: Boolean = true,
maxLines: Int = Int.MAX_VALUE,
placeholders: List<AnnotatedString.Range<Placeholder>> = emptyList(),
constraints: Constraints = Constraints(),
layoutDirection: LayoutDirection = this.fallbackLayoutDirection,
density: Density = this.fallbackDensity,
fontFamilyResolver: FontFamily.Resolver = this.fallbackFontFamilyResolver,
skipCache: Boolean = false
): TextLayoutResult {
val requestedTextLayoutInput = TextLayoutInput(
text,
style,
placeholders,
maxLines,
softWrap,
overflow,
density,
layoutDirection,
fontFamilyResolver,
constraints
)
val cacheResult = if (!skipCache && textLayoutCache != null) {
textLayoutCache.get(requestedTextLayoutInput)
} else null
return if (cacheResult != null) {
cacheResult.copy(
layoutInput = requestedTextLayoutInput,
size = constraints.constrain(
IntSize(
cacheResult.multiParagraph.width.ceilToInt(),
cacheResult.multiParagraph.height.ceilToInt()
)
)
)
} else {
layout(requestedTextLayoutInput).also {
textLayoutCache?.put(requestedTextLayoutInput, it)
}
}
}
internal companion object {
/**
* Computes the visual position of the glyphs for painting the text.
*
* The text will layout with a width that's as close to its max intrinsic width as possible
* while still being greater than or equal to `minWidth` and less than or equal to
* `maxWidth`.
*/
private fun layout(
textLayoutInput: TextLayoutInput
): TextLayoutResult = with(textLayoutInput) {
val nonNullIntrinsics = MultiParagraphIntrinsics(
annotatedString = text,
style = resolveDefaults(style, layoutDirection),
density = density,
fontFamilyResolver = fontFamilyResolver,
placeholders = placeholders
)
val minWidth = constraints.minWidth
val widthMatters = softWrap ||
overflow == TextOverflow.Ellipsis
val maxWidth = if (widthMatters && constraints.hasBoundedWidth) {
constraints.maxWidth
} else {
Constraints.Infinity
}
// This is a fallback behavior because native text layout doesn't support multiple
// ellipsis in one text layout.
// When softWrap is turned off and overflow is ellipsis, it's expected that each line
// that exceeds maxWidth will be ellipsized.
// For example,
// input text:
// "AAAA\nAAAA"
// maxWidth:
// 3 * fontSize that only allow 3 characters to be displayed each line.
// expected output:
// AA…
// AA…
// Here we assume there won't be any '\n' character when softWrap is false. And make
// maxLines 1 to implement the similar behavior.
val overwriteMaxLines = !softWrap &&
overflow == TextOverflow.Ellipsis
val finalMaxLines = if (overwriteMaxLines) 1 else maxLines
// if minWidth == maxWidth the width is fixed.
// therefore we can pass that value to our paragraph and use it
// if minWidth != maxWidth there is a range
// then we should check if the max intrinsic width is in this range to decide the
// width to be passed to Paragraph
// if max intrinsic width is between minWidth and maxWidth
// we can use it to layout
// else if max intrinsic width is greater than maxWidth, we can only use maxWidth
// else if max intrinsic width is less than minWidth, we should use minWidth
val width = if (minWidth == maxWidth) {
maxWidth
} else {
nonNullIntrinsics.maxIntrinsicWidth.ceilToInt().coerceIn(minWidth, maxWidth)
}
val multiParagraph = MultiParagraph(
intrinsics = nonNullIntrinsics,
constraints = Constraints(maxWidth = width, maxHeight = constraints.maxHeight),
// This is a fallback behavior for ellipsis. Native
maxLines = finalMaxLines,
ellipsis = overflow == TextOverflow.Ellipsis
)
return TextLayoutResult(
layoutInput = textLayoutInput,
multiParagraph = multiParagraph,
size = constraints.constrain(
IntSize(
ceil(multiParagraph.width).toInt(),
ceil(multiParagraph.height).toInt()
)
)
)
}
}
}
/**
* Keeps an LRU layout cache of TextLayoutInput, TextLayoutResult pairs. Any non-layout affecting
* change in TextLayoutInput (color, brush, shadow, TextDecoration) is ignored by this cache.
*
* @param capacity Maximum size of LRU cache. Size unit is the number of [CacheTextLayoutInput]
* and [TextLayoutResult] pairs.
*
* @throws IllegalArgumentException if capacity is not a positive integer.
*/
internal class TextLayoutCache(capacity: Int = DefaultCacheSize) {
private val lruCache = LruCache<CacheTextLayoutInput, TextLayoutResult>(capacity)
fun get(key: TextLayoutInput): TextLayoutResult? {
val resultFromCache = lruCache.get(CacheTextLayoutInput(key)) ?: return null
if (resultFromCache.multiParagraph.intrinsics.hasStaleResolvedFonts) {
// one of the resolved fonts has updated, and this MeasuredText is no longer valid for
// measure or display
return null
}
return resultFromCache
}
fun put(key: TextLayoutInput, value: TextLayoutResult): TextLayoutResult? {
return lruCache.put(CacheTextLayoutInput(key), value)
}
fun remove(key: TextLayoutInput): TextLayoutResult? {
return lruCache.remove(CacheTextLayoutInput(key))
}
}
/**
* Provides custom hashCode and equals function that are only interested in layout affecting
* attributes in TextLayoutInput. Used as a key in [TextLayoutCache].
*/
@Immutable
internal class CacheTextLayoutInput(val textLayoutInput: TextLayoutInput) {
override fun hashCode(): Int = with(textLayoutInput) {
var result = text.hashCode()
result = 31 * result + style.hashCodeLayoutAffectingAttributes()
result = 31 * result + placeholders.hashCode()
result = 31 * result + maxLines
result = 31 * result + softWrap.hashCode()
result = 31 * result + overflow.hashCode()
result = 31 * result + density.hashCode()
result = 31 * result + layoutDirection.hashCode()
result = 31 * result + fontFamilyResolver.hashCode()
result = 31 * result + constraints.maxWidth.hashCode()
result = 31 * result + constraints.maxHeight.hashCode()
return result
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is CacheTextLayoutInput) return false
with(textLayoutInput) {
if (text != other.textLayoutInput.text) return false
if (!style.hasSameLayoutAffectingAttributes(other.textLayoutInput.style)) return false
if (placeholders != other.textLayoutInput.placeholders) return false
if (maxLines != other.textLayoutInput.maxLines) return false
if (softWrap != other.textLayoutInput.softWrap) return false
if (overflow != other.textLayoutInput.overflow) return false
if (density != other.textLayoutInput.density) return false
if (layoutDirection != other.textLayoutInput.layoutDirection) return false
if (fontFamilyResolver !== other.textLayoutInput.fontFamilyResolver) return false
if (constraints.maxWidth != other.textLayoutInput.constraints.maxWidth) return false
if (constraints.maxHeight != other.textLayoutInput.constraints.maxHeight) return false
}
return true
}
} | apache-2.0 | 30fb0a26b6e9222743cc3a7989591583 | 46.747093 | 100 | 0.679859 | 5.225581 | false | false | false | false |
deeplearning4j/deeplearning4j | nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/definitions/implementations/NonZero.kt | 1 | 2822 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.onnx.definitions.implementations
import org.nd4j.autodiff.samediff.SDVariable
import org.nd4j.autodiff.samediff.SameDiff
import org.nd4j.autodiff.samediff.internal.SameDiffOp
import org.nd4j.samediff.frameworkimport.ImportGraph
import org.nd4j.samediff.frameworkimport.hooks.PreImportHook
import org.nd4j.samediff.frameworkimport.hooks.annotations.PreHookRule
import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry
import org.nd4j.shade.protobuf.GeneratedMessageV3
import org.nd4j.shade.protobuf.ProtocolMessageEnum
/**
* A port of non_zero.py from onnx tensorflow for samediff:
* https://github.com/onnx/onnx-tensorflow/blob/master/onnx_tf/handlers/backend/non_zero.py
*
* @author Adam Gibson
*/
@PreHookRule(nodeNames = [],opNames = ["NonZero"],frameworkName = "onnx")
class NonZero : PreImportHook {
override fun doImport(
sd: SameDiff,
attributes: Map<String, Any>,
outputNames: List<String>,
op: SameDiffOp,
mappingRegistry: OpMappingRegistry<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum, GeneratedMessageV3, GeneratedMessageV3>,
importGraph: ImportGraph<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum>,
dynamicVariables: Map<String, GeneratedMessageV3>
): Map<String, List<SDVariable>> {
// Parameter docs below are from the onnx operator docs:
// https://github.com/onnx/onnx/blob/master/docs/Operators.md#non
var inputVariable = sd.getVariable(op.inputsToOp[0])
val condition = sd.neq(inputVariable,sd.zerosLike(inputVariable))
val nonZeroIndices = sd.where(condition)
val outputVar = sd.permute(outputNames[0],nonZeroIndices)
return mapOf(outputVar.name() to listOf(outputVar))
}
} | apache-2.0 | 7e39949130cd64e68a5da50f45b6d887 | 44.532258 | 184 | 0.708363 | 4.243609 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/components/PathFieldComponent.kt | 3 | 2488 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.wizard.ui.components
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.ui.TextBrowseFolderListener
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import org.jetbrains.kotlin.tools.projectWizard.core.Context
import org.jetbrains.kotlin.tools.projectWizard.core.asPath
import org.jetbrains.kotlin.tools.projectWizard.core.entity.SettingValidator
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.componentWithCommentAtBottom
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.withOnUpdatedListener
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import java.nio.file.Path
import java.nio.file.Paths
import javax.swing.JComponent
class PathFieldComponent(
context: Context,
labelText: String? = null,
description: String? = null,
initialValue: Path? = null,
validator: SettingValidator<Path>? = null,
onValueUpdate: (Path, isByUser: Boolean) -> Unit = { _, _ -> }
) : UIComponent<Path>(
context,
labelText,
validator,
onValueUpdate
) {
private val textFieldWithBrowseButton = TextFieldWithBrowseButton().apply {
textField.text = initialValue?.toString().orEmpty()
textField.withOnUpdatedListener { path -> fireValueUpdated(path.trim().asPath()) }
addBrowseFolderListener(
TextBrowseFolderListener(
FileChooserDescriptorFactory.createSingleFolderDescriptor(),
null
)
)
}
fun onUserType(action: () -> Unit) {
textFieldWithBrowseButton.textField.addKeyListener(object : KeyAdapter() {
override fun keyReleased(e: KeyEvent?) = action()
})
}
override val alignTarget: JComponent? get() = textFieldWithBrowseButton
override val uiComponent = componentWithCommentAtBottom(textFieldWithBrowseButton, description)
override fun getValidatorTarget(): JComponent = textFieldWithBrowseButton.textField
override fun updateUiValue(newValue: Path) = safeUpdateUi {
textFieldWithBrowseButton.text = newValue.toString()
}
override fun getUiValue(): Path = Paths.get(textFieldWithBrowseButton.text.trim())
override fun focusOn() {
textFieldWithBrowseButton.textField.requestFocus()
}
} | apache-2.0 | 2fe3e57948aa27216c257bb2400bc38b | 38.507937 | 158 | 0.745177 | 4.926733 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspections/suspiciousEqualsCombination/test.kt | 13 | 801 | object Main {
fun test() {
val type1 = Main
val type = Main
if (type === CONST1 || type == CONST2 && type === CONST3) return
if (type === CONST1 || type == CONST2 && (type === CONST3)) return
if (type === CONST1 || type == CONST2 && !(type === CONST3)) return
if (type === CONST1 || type1 == CONST2 && type === CONST3) return
if (type === CONST1 || type1 == CONST1 && type === CONST3) return
val type2: Main? = null
if (type2 == null || type === type2) return
val type3: Main? = null
if (type3 === null || type == type3) return
val type4: Main? = null
if (type4 == null || type === type2 || type1 == type) return
}
val CONST1 = Main;
val CONST2 = Main;
val CONST3 = Main;
} | apache-2.0 | e8c0360c2e8149c4a0c6c7b62cf1202a | 32.416667 | 75 | 0.506866 | 3.691244 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinCodeFragmentFactory.kt | 1 | 13923 | // 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.DebuggerManagerEx
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.JavaDebuggerEvaluator
import com.intellij.debugger.engine.evaluation.CodeFragmentFactory
import com.intellij.debugger.engine.evaluation.TextWithImports
import com.intellij.debugger.engine.events.DebuggerCommandImpl
import com.intellij.debugger.impl.DebuggerContextImpl
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiTypesUtil
import com.intellij.util.IncorrectOperationException
import com.intellij.util.concurrency.Semaphore
import com.sun.jdi.AbsentInformationException
import com.sun.jdi.InvalidStackFrameException
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.core.util.getKotlinJvmRuntimeMarkerClass
import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.DebugLabelPropertyDescriptorProvider
import org.jetbrains.kotlin.idea.debugger.getContextElement
import org.jetbrains.kotlin.idea.debugger.hopelessAware
import org.jetbrains.kotlin.idea.j2k.J2kPostProcessor
import org.jetbrains.kotlin.idea.j2k.convertToKotlin
import org.jetbrains.kotlin.idea.j2k.j2kText
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.j2k.AfterConversionPass
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded
import org.jetbrains.kotlin.types.KotlinType
import java.util.concurrent.atomic.AtomicReference
class KotlinCodeFragmentFactory : CodeFragmentFactory() {
override fun createCodeFragment(item: TextWithImports, context: PsiElement?, project: Project): JavaCodeFragment {
val contextElement = getContextElement(context)
val codeFragment = KtBlockCodeFragment(project, "fragment.kt", item.text, initImports(item.imports), contextElement)
supplyDebugInformation(item, codeFragment, context)
codeFragment.putCopyableUserData(KtCodeFragment.RUNTIME_TYPE_EVALUATOR) { expression: KtExpression ->
val debuggerContext = DebuggerManagerEx.getInstanceEx(project).context
val debuggerSession = debuggerContext.debuggerSession
if (debuggerSession == null || debuggerContext.suspendContext == null) {
null
} else {
val semaphore = Semaphore()
semaphore.down()
val nameRef = AtomicReference<KotlinType>()
val worker = object : KotlinRuntimeTypeEvaluator(
null, expression, debuggerContext, ProgressManager.getInstance().progressIndicator!!
) {
override fun typeCalculationFinished(type: KotlinType?) {
nameRef.set(type)
semaphore.up()
}
}
debuggerContext.debugProcess?.managerThread?.invoke(worker)
for (i in 0..50) {
ProgressManager.checkCanceled()
if (semaphore.waitFor(20)) break
}
nameRef.get()
}
}
if (contextElement != null && contextElement !is KtElement) {
codeFragment.putCopyableUserData(KtCodeFragment.FAKE_CONTEXT_FOR_JAVA_FILE) {
val emptyFile = createFakeFileWithJavaContextElement("", contextElement)
val debuggerContext = DebuggerManagerEx.getInstanceEx(project).context
val debuggerSession = debuggerContext.debuggerSession
if ((debuggerSession == null || debuggerContext.suspendContext == null) &&
!isUnitTestMode()
) {
LOG.warn("Couldn't create fake context element for java file, debugger isn't paused on breakpoint")
return@putCopyableUserData emptyFile
}
val frameInfo = getFrameInfo(contextElement, debuggerContext) ?: run {
val position = "${debuggerContext.sourcePosition?.file?.name}:${debuggerContext.sourcePosition?.line}"
LOG.warn("Couldn't get info about 'this' and local variables for $position")
return@putCopyableUserData emptyFile
}
val fakeFunctionText = buildString {
append("fun ")
val thisType = frameInfo.thisObject?.asProperty()?.typeReference?.typeElement?.unwrapNullableType()
if (thisType != null) {
append(thisType.text).append('.')
}
append(FAKE_JAVA_CONTEXT_FUNCTION_NAME).append("() {\n")
for (variable in frameInfo.variables) {
val text = variable.asProperty()?.text ?: continue
append(" ").append(text).append("\n")
}
// There should be at least one declaration inside the function (or 'fakeContext' below won't work).
append(" val _debug_context_val = 1\n")
append("}")
}
val fakeFile = createFakeFileWithJavaContextElement(fakeFunctionText, contextElement)
val fakeFunction = fakeFile.declarations.firstOrNull() as? KtFunction
val fakeContext = fakeFunction?.bodyBlockExpression?.statements?.lastOrNull()
return@putCopyableUserData fakeContext ?: emptyFile
}
}
return codeFragment
}
private fun KtTypeElement.unwrapNullableType(): KtTypeElement {
return if (this is KtNullableType) innerType ?: this else this
}
private fun supplyDebugInformation(item: TextWithImports, codeFragment: KtCodeFragment, context: PsiElement?) {
val project = codeFragment.project
val debugProcess = getDebugProcess(project, context) ?: return
DebugLabelPropertyDescriptorProvider(codeFragment, debugProcess).supplyDebugLabels()
@Suppress("MoveVariableDeclarationIntoWhen")
val evaluator = debugProcess.session.xDebugSession?.currentStackFrame?.evaluator
val evaluationType = when (evaluator) {
is KotlinDebuggerEvaluator -> evaluator.getType(item)
is JavaDebuggerEvaluator -> KotlinDebuggerEvaluator.EvaluationType.FROM_JAVA
else -> KotlinDebuggerEvaluator.EvaluationType.UNKNOWN
}
codeFragment.putUserData(EVALUATION_TYPE, evaluationType)
}
private fun getDebugProcess(project: Project, context: PsiElement?): DebugProcessImpl? {
return if (isUnitTestMode()) {
context?.getCopyableUserData(DEBUG_CONTEXT_FOR_TESTS)?.debugProcess
} else {
DebuggerManagerEx.getInstanceEx(project).context.debugProcess
}
}
private fun getFrameInfo(contextElement: PsiElement?, debuggerContext: DebuggerContextImpl): FrameInfo? {
val semaphore = Semaphore()
semaphore.down()
var frameInfo: FrameInfo? = null
val worker = object : DebuggerCommandImpl() {
override fun action() {
try {
val frameProxy = hopelessAware {
if (isUnitTestMode()) {
contextElement?.getCopyableUserData(DEBUG_CONTEXT_FOR_TESTS)?.frameProxy
} else {
debuggerContext.frameProxy
}
}
frameInfo = FrameInfo.from(debuggerContext.project, frameProxy)
} catch (ignored: AbsentInformationException) {
// Debug info unavailable
} catch (ignored: InvalidStackFrameException) {
// Thread is resumed, the frame we have is not valid anymore
} finally {
semaphore.up()
}
}
}
debuggerContext.debugProcess?.managerThread?.invoke(worker)
for (i in 0..50) {
if (semaphore.waitFor(20)) break
}
return frameInfo
}
private fun initImports(imports: String?): String? {
if (imports != null && imports.isNotEmpty()) {
return imports.split(KtCodeFragment.IMPORT_SEPARATOR)
.mapNotNull { fixImportIfNeeded(it) }
.joinToString(KtCodeFragment.IMPORT_SEPARATOR)
}
return null
}
private fun fixImportIfNeeded(import: String): String? {
// skip arrays
if (import.endsWith("[]")) {
return fixImportIfNeeded(import.removeSuffix("[]").trim())
}
// skip primitive types
if (PsiTypesUtil.boxIfPossible(import) != import) {
return null
}
return import
}
override fun createPresentationCodeFragment(item: TextWithImports, context: PsiElement?, project: Project): JavaCodeFragment {
val kotlinCodeFragment = createCodeFragment(item, context, project)
if (PsiTreeUtil.hasErrorElements(kotlinCodeFragment) && kotlinCodeFragment is KtCodeFragment) {
val javaExpression = try {
PsiElementFactory.getInstance(project).createExpressionFromText(item.text, context)
} catch (e: IncorrectOperationException) {
null
}
val importList = try {
kotlinCodeFragment.importsAsImportList()?.let {
(PsiFileFactory.getInstance(project).createFileFromText(
"dummy.java", JavaFileType.INSTANCE, it.text
) as? PsiJavaFile)?.importList
}
} catch (e: IncorrectOperationException) {
null
}
if (javaExpression != null && !PsiTreeUtil.hasErrorElements(javaExpression)) {
var convertedFragment: KtExpressionCodeFragment? = null
project.executeWriteCommand(KotlinDebuggerEvaluationBundle.message("j2k.expression")) {
try {
val (elementResults, _, conversionContext) = javaExpression.convertToKotlin() ?: return@executeWriteCommand
val newText = elementResults.singleOrNull()?.text
val newImports = importList?.j2kText()
if (newText != null) {
convertedFragment = KtExpressionCodeFragment(
project,
kotlinCodeFragment.name,
newText,
newImports,
kotlinCodeFragment.context
)
AfterConversionPass(project, J2kPostProcessor(formatCode = false))
.run(
convertedFragment!!,
conversionContext,
range = null,
onPhaseChanged = null
)
}
} catch (e: Throwable) {
// ignored because text can be invalid
LOG.error("Couldn't convert expression:\n`${javaExpression.text}`", e)
}
}
return convertedFragment ?: kotlinCodeFragment
}
}
return kotlinCodeFragment
}
override fun isContextAccepted(contextElement: PsiElement?): Boolean = runReadAction {
when {
// PsiCodeBlock -> DummyHolder -> originalElement
contextElement is PsiCodeBlock -> isContextAccepted(contextElement.context?.context)
contextElement == null -> false
contextElement.language == KotlinFileType.INSTANCE.language -> true
contextElement.language == JavaFileType.INSTANCE.language -> {
getKotlinJvmRuntimeMarkerClass(contextElement.project, contextElement.resolveScope) != null
}
else -> false
}
}
override fun getFileType(): KotlinFileType = KotlinFileType.INSTANCE
override fun getEvaluatorBuilder() = KotlinEvaluatorBuilder
companion object {
private val LOG = Logger.getInstance(this::class.java)
@get:TestOnly
val DEBUG_CONTEXT_FOR_TESTS: Key<DebuggerContextImpl> = Key.create("DEBUG_CONTEXT_FOR_TESTS")
val EVALUATION_TYPE: Key<KotlinDebuggerEvaluator.EvaluationType> = Key.create("DEBUG_EVALUATION_TYPE")
const val FAKE_JAVA_CONTEXT_FUNCTION_NAME = "_java_locals_debug_fun_"
}
private fun createFakeFileWithJavaContextElement(funWithLocalVariables: String, javaContext: PsiElement): KtFile {
val javaFile = javaContext.containingFile as? PsiJavaFile
val sb = StringBuilder()
javaFile?.packageName?.takeUnless { it.isBlank() }?.let {
sb.append("package ").append(it.quoteIfNeeded()).append("\n")
}
javaFile?.importList?.let { sb.append(it.text).append("\n") }
sb.append(funWithLocalVariables)
return KtPsiFactory(javaContext.project).createAnalyzableFile("fakeFileForJavaContextInDebugger.kt", sb.toString(), javaContext)
}
}
| apache-2.0 | 88b18dbb6f7a19bab57fff147d9dc435 | 43.060127 | 158 | 0.623213 | 5.902077 | false | false | false | false |
fabmax/kool | kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/physics/vehicle/VehicleWorld.kt | 1 | 2312 | package de.fabmax.kool.demo.physics.vehicle
import de.fabmax.kool.physics.*
import de.fabmax.kool.physics.geometry.TriangleMeshGeometry
import de.fabmax.kool.physics.vehicle.VehicleUtils
import de.fabmax.kool.pipeline.deferred.DeferredPipeline
import de.fabmax.kool.pipeline.deferred.deferredPbrShader
import de.fabmax.kool.scene.Node
import de.fabmax.kool.scene.Scene
import de.fabmax.kool.scene.colorMesh
import de.fabmax.kool.scene.geometry.IndexedVertexList
import de.fabmax.kool.scene.group
import de.fabmax.kool.util.Color
class VehicleWorld(val scene: Scene, val physics: PhysicsWorld, val deferredPipeline: DeferredPipeline) {
val defaultMaterial = Material(0.5f)
val groundSimFilterData = FilterData(VehicleUtils.COLLISION_FLAG_GROUND, VehicleUtils.COLLISION_FLAG_GROUND_AGAINST)
val groundQryFilterData = FilterData { VehicleUtils.setupDrivableSurface(this) }
val obstacleSimFilterData = FilterData(VehicleUtils.COLLISION_FLAG_DRIVABLE_OBSTACLE, VehicleUtils.COLLISION_FLAG_DRIVABLE_OBSTACLE_AGAINST)
val obstacleQryFilterData = FilterData { VehicleUtils.setupDrivableSurface(this) }
fun toPrettyMesh(actor: RigidActor, meshColor: Color, rough: Float = 0.8f, metal: Float = 0f): Node = group {
+colorMesh {
generate {
color = meshColor
actor.shapes.forEach { shape ->
withTransform {
transform.mul(shape.localPose)
shape.geometry.generateMesh(this)
}
}
}
shader = deferredPbrShader {
roughness = rough
metallic = metal
}
onUpdate += {
[email protected](actor.transform)
[email protected]()
}
}
}
fun addStaticCollisionBody(mesh: IndexedVertexList): RigidStatic {
val body = RigidStatic().apply {
simulationFilterData = obstacleSimFilterData
queryFilterData = obstacleQryFilterData
attachShape(Shape(TriangleMeshGeometry(mesh), defaultMaterial))
}
physics.addActor(body)
return body
}
fun release() {
physics.clear()
physics.release()
defaultMaterial.release()
}
} | apache-2.0 | 96b29473340157e442b281cad46ecc24 | 37.55 | 144 | 0.664792 | 4.48062 | false | false | false | false |
leafclick/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/ui/GHPRReviewCommentComponent.kt | 1 | 6601 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.comment.ui
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.components.panels.Wrapper
import com.intellij.util.ui.UI
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import icons.GithubIcons
import net.miginfocom.layout.AC
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import org.jetbrains.plugins.github.pullrequest.avatars.GHAvatarIconsProvider
import org.jetbrains.plugins.github.pullrequest.data.service.GHPRReviewServiceAdapter
import org.jetbrains.plugins.github.ui.InlineIconButton
import org.jetbrains.plugins.github.ui.util.HtmlEditorPane
import org.jetbrains.plugins.github.util.GithubUIUtil
import org.jetbrains.plugins.github.util.handleOnEdt
import org.jetbrains.plugins.github.util.successOnEdt
import java.awt.event.ActionListener
import javax.swing.JComponent
import javax.swing.JEditorPane
import javax.swing.JPanel
import javax.swing.text.BadLocationException
import javax.swing.text.Utilities
object GHPRReviewCommentComponent {
fun create(reviewService: GHPRReviewServiceAdapter,
thread: GHPRReviewThreadModel, comment: GHPRReviewCommentModel,
avatarIconsProvider: GHAvatarIconsProvider): JComponent {
val avatarLabel: LinkLabel<*> = LinkLabel.create("") {
comment.authorLinkUrl?.let { BrowserUtil.browse(it) }
}.apply {
icon = avatarIconsProvider.getIcon(comment.authorAvatarUrl)
isFocusable = true
putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
}
val href = comment.authorLinkUrl?.let { """href='${it}'""" }.orEmpty()
//language=HTML
val title = """<a $href>${comment.authorUsername ?: "unknown"}</a> commented ${GithubUIUtil.formatActionDate(comment.dateCreated)}"""
val titlePane: HtmlEditorPane = HtmlEditorPane(title).apply {
foreground = UIUtil.getContextHelpForeground()
putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
}
val textPane: HtmlEditorPane = HtmlEditorPane(comment.body).apply {
putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
}
comment.addChangesListener {
textPane.setBody(comment.body)
}
val editorWrapper = Wrapper()
val editButton = createEditButton(reviewService, comment, editorWrapper, textPane).apply {
isVisible = comment.canBeUpdated
}
val deleteButton = createDeleteButton(reviewService, thread, comment).apply {
isVisible = comment.canBeDeleted
}
val contentPanel = BorderLayoutPanel().andTransparent().addToCenter(textPane).addToBottom(editorWrapper)
return JPanel(null).apply {
isOpaque = false
layout = MigLayout(LC().gridGap("0", "0")
.insets("0", "0", "0", "0")
.fill(),
AC().gap("${UI.scale(8)}"))
add(avatarLabel, CC().pushY())
add(titlePane, CC().minWidth("0").split(3).alignX("left"))
add(editButton, CC().hideMode(3).gapBefore("${UI.scale(12)}"))
add(deleteButton, CC().hideMode(3).gapBefore("${UI.scale(8)}"))
add(contentPanel, CC().newline().skip().grow().push().minWidth("0").minHeight("0"))
}
}
private fun createDeleteButton(reviewService: GHPRReviewServiceAdapter,
thread: GHPRReviewThreadModel,
comment: GHPRReviewCommentModel): JComponent {
val icon = GithubIcons.Delete
val hoverIcon = GithubIcons.DeleteHovered
return InlineIconButton(icon, hoverIcon, tooltip = "Delete").apply {
actionListener = ActionListener {
if (Messages.showConfirmationDialog(this, "Are you sure you want to delete this comment?", "Delete Comment",
Messages.getYesButton(), Messages.getNoButton()) == Messages.YES) {
reviewService.deleteComment(EmptyProgressIndicator(), comment.id)
thread.removeComment(comment)
}
}
}
}
private fun createEditButton(reviewService: GHPRReviewServiceAdapter,
comment: GHPRReviewCommentModel,
editorWrapper: Wrapper,
textPane: JEditorPane): JComponent {
val action = ActionListener {
val linesCount = calcLines(textPane)
val text = StringUtil.repeatSymbol('\n', linesCount - 1)
val model = GHPRSubmittableTextField.Model { newText ->
reviewService.updateComment(EmptyProgressIndicator(), comment.id, newText).successOnEdt {
comment.update(it)
}.handleOnEdt { _, _ ->
editorWrapper.setContent(null)
editorWrapper.revalidate()
}
}
with(model.document) {
runWriteAction {
setText(text)
setReadOnly(true)
}
reviewService.getCommentMarkdownBody(EmptyProgressIndicator(), comment.id).successOnEdt {
runWriteAction {
setReadOnly(false)
setText(it)
}
}
}
val editor = GHPRSubmittableTextField.create(model, "Submit", onCancel = {
editorWrapper.setContent(null)
editorWrapper.revalidate()
})
editorWrapper.setContent(editor)
GithubUIUtil.focusPanel(editor)
}
val icon = AllIcons.General.Inline_edit
val hoverIcon = AllIcons.General.Inline_edit_hovered
return InlineIconButton(icon, hoverIcon, tooltip = "Edit").apply {
actionListener = action
}
}
private fun calcLines(textPane: JEditorPane): Int {
var lineCount = 0
var offset = 0
while (true) {
try {
offset = Utilities.getRowEnd(textPane, offset) + 1
lineCount++
}
catch (e: BadLocationException) {
break
}
}
return lineCount
}
fun factory(thread: GHPRReviewThreadModel, reviewService: GHPRReviewServiceAdapter, avatarIconsProvider: GHAvatarIconsProvider)
: (GHPRReviewCommentModel) -> JComponent {
return { comment ->
create(reviewService, thread, comment, avatarIconsProvider)
}
}
} | apache-2.0 | c749dee1a9207a410db86d685606f5b0 | 36.942529 | 140 | 0.686866 | 4.882396 | false | false | false | false |
idea4bsd/idea4bsd | platform/platform-impl/src/com/intellij/openapi/util/io/fileUtil.kt | 17 | 1973 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.util.io
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.PathUtilRt
import java.io.File
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.PosixFileAttributeView
import java.nio.file.attribute.PosixFilePermission
private val LOG = Logger.getInstance("#com.intellij.openapi.util.io.FileUtil")
val File.systemIndependentPath: String
get() = path.replace(File.separatorChar, '/')
val File.parentSystemIndependentPath: String
get() = parent.replace(File.separatorChar, '/')
// PathUtilRt.getParentPath returns empty string if no parent path, but in Kotlin "null" is better because elvis operator could be used
fun getParentPath(path: String) = StringUtil.nullize(PathUtilRt.getParentPath(path))
fun endsWithSlash(path: String) = path.getOrNull(path.length - 1) == '/'
fun endsWithName(path: String, name: String) = path.endsWith(name) && (path.length == name.length || path.getOrNull(path.length - name.length - 1) == '/')
fun Path.setOwnerPermissions() {
Files.getFileAttributeView(this, PosixFileAttributeView::class.java)?.let {
try {
it.setPermissions(setOf(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE))
}
catch (e: IOException) {
LOG.warn(e)
}
}
} | apache-2.0 | 1128bacc4c84496e36ba4639ded38bcc | 36.961538 | 154 | 0.756716 | 3.977823 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.kt | 1 | 36835 | // 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.introduceVariable
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.codeInsight.template.*
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.impl.FinishMarkAction
import com.intellij.openapi.command.impl.StartMarkAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.refactoring.HelpID
import com.intellij.refactoring.RefactoringActionHandler
import com.intellij.refactoring.introduce.inplace.OccurrencesChooser
import com.intellij.refactoring.util.CommonRefactoringUtil
import com.intellij.util.SmartList
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.analysis.analyzeInContext
import org.jetbrains.kotlin.idea.analysis.computeTypeInfoInContext
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils
import org.jetbrains.kotlin.idea.intentions.ConvertToBlockBodyIntention
import org.jetbrains.kotlin.idea.refactoring.*
import org.jetbrains.kotlin.idea.refactoring.introduce.*
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.application.executeCommand
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.idea.util.psi.patternMatching.KotlinPsiUnifier
import org.jetbrains.kotlin.idea.util.psi.patternMatching.toRange
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.BindingTraceContext
import org.jetbrains.kotlin.resolve.ObservableBindingTrace
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoAfter
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeConstructor
import org.jetbrains.kotlin.types.checker.ClassicTypeCheckerContext
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.types.checker.NewKotlinTypeChecker
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.ifEmpty
import org.jetbrains.kotlin.utils.sure
import kotlin.math.min
object KotlinIntroduceVariableHandler : RefactoringActionHandler {
val INTRODUCE_VARIABLE get() = KotlinBundle.message("introduce.variable")
private val EXPRESSION_KEY = Key.create<Boolean>("EXPRESSION_KEY")
private val REPLACE_KEY = Key.create<Boolean>("REPLACE_KEY")
private val COMMON_PARENT_KEY = Key.create<Boolean>("COMMON_PARENT_KEY")
private var KtExpression.isOccurrence: Boolean by NotNullablePsiCopyableUserDataProperty(Key.create("OCCURRENCE"), false)
private class TypeCheckerImpl(private val project: Project) : KotlinTypeChecker by KotlinTypeChecker.DEFAULT {
private inner class ContextImpl : ClassicTypeCheckerContext(false) {
override fun areEqualTypeConstructors(a: TypeConstructor, b: TypeConstructor): Boolean =
compareDescriptors(project, a.declarationDescriptor, b.declarationDescriptor)
}
override fun equalTypes(a: KotlinType, b: KotlinType): Boolean = with(NewKotlinTypeChecker.Default) {
ContextImpl().equalTypes(a.unwrap(), b.unwrap())
}
}
private class IntroduceVariableContext(
private val expression: KtExpression,
private val nameSuggestions: List<Collection<String>>,
private val allReplaces: List<KtExpression>,
private val commonContainer: PsiElement,
private val commonParent: PsiElement,
private val replaceOccurrence: Boolean,
private val noTypeInference: Boolean,
private val expressionType: KotlinType?,
private val componentFunctions: List<FunctionDescriptor>,
private val bindingContext: BindingContext,
private val resolutionFacade: ResolutionFacade
) {
private val psiFactory = KtPsiFactory(expression)
var propertyRef: KtDeclaration? = null
var reference: SmartPsiElementPointer<KtExpression>? = null
val references = ArrayList<SmartPsiElementPointer<KtExpression>>()
private fun findElementByOffsetAndText(offset: Int, text: String, newContainer: PsiElement): PsiElement? =
newContainer.findElementAt(offset)?.parentsWithSelf?.firstOrNull { (it as? KtExpression)?.text == text }
private fun replaceExpression(expressionToReplace: KtExpression, addToReferences: Boolean): KtExpression {
val isActualExpression = expression == expressionToReplace
val replacement = psiFactory.createExpression(nameSuggestions.single().first())
val substringInfo = expressionToReplace.extractableSubstringInfo
var result = when {
expressionToReplace.isLambdaOutsideParentheses() -> {
val functionLiteralArgument = expressionToReplace.getStrictParentOfType<KtLambdaArgument>()!!
val newCallExpression = functionLiteralArgument.moveInsideParenthesesAndReplaceWith(replacement, bindingContext)
newCallExpression.valueArguments.last().getArgumentExpression()!!
}
substringInfo != null -> substringInfo.replaceWith(replacement)
else -> expressionToReplace.replace(replacement) as KtExpression
}
result = result.removeTemplateEntryBracesIfPossible()
if (addToReferences) {
references.addIfNotNull(SmartPointerManager.createPointer(result))
}
if (isActualExpression) {
reference = SmartPointerManager.createPointer(result)
}
return result
}
private fun runRefactoring(
isVar: Boolean,
expression: KtExpression,
commonContainer: PsiElement,
commonParent: PsiElement,
allReplaces: List<KtExpression>
) {
val initializer = (expression as? KtParenthesizedExpression)?.expression ?: expression
val initializerText = if (initializer.mustBeParenthesizedInInitializerPosition()) "(${initializer.text})" else initializer.text
val varOvVal = if (isVar) "var" else "val"
var property: KtDeclaration = if (componentFunctions.isNotEmpty()) {
buildString {
componentFunctions.indices.joinTo(this, prefix = "$varOvVal (", postfix = ")") { nameSuggestions[it].first() }
append(" = ")
append(initializerText)
}.let { psiFactory.createDestructuringDeclaration(it) }
} else {
buildString {
append("$varOvVal ")
append(nameSuggestions.single().first())
if (noTypeInference) {
val typeToRender = expressionType ?: resolutionFacade.moduleDescriptor.builtIns.anyType
append(": ").append(IdeDescriptorRenderers.SOURCE_CODE.renderType(typeToRender))
}
append(" = ")
append(initializerText)
}.let { psiFactory.createProperty(it) }
}
var anchor = calculateAnchor(commonParent, commonContainer, allReplaces) ?: return
val needBraces = commonContainer !is KtBlockExpression && commonContainer !is KtClassBody && commonContainer !is KtFile
if (!needBraces) {
property = commonContainer.addBefore(property, anchor) as KtDeclaration
commonContainer.addBefore(psiFactory.createNewLine(), anchor)
} else {
var emptyBody: KtExpression = psiFactory.createEmptyBody()
val firstChild = emptyBody.firstChild
emptyBody.addAfter(psiFactory.createNewLine(), firstChild)
if (replaceOccurrence) {
for (replace in allReplaces) {
val exprAfterReplace = replaceExpression(replace, false)
exprAfterReplace.isOccurrence = true
if (anchor == replace) {
anchor = exprAfterReplace
}
}
var oldElement: PsiElement = commonContainer
if (commonContainer is KtWhenEntry) {
val body = commonContainer.expression
if (body != null) {
oldElement = body
}
} else if (commonContainer is KtContainerNode) {
val children = commonContainer.children
for (child in children) {
if (child is KtExpression) {
oldElement = child
}
}
}
//ugly logic to make sure we are working with right actual expression
var actualExpression = reference?.element ?: return
var diff = actualExpression.textRange.startOffset - oldElement.textRange.startOffset
var actualExpressionText = actualExpression.text
val newElement = emptyBody.addAfter(oldElement, firstChild)
var elem: PsiElement? = findElementByOffsetAndText(diff, actualExpressionText, newElement)
if (elem != null) {
reference = SmartPointerManager.createPointer(elem as KtExpression)
}
emptyBody.addAfter(psiFactory.createNewLine(), firstChild)
property = emptyBody.addAfter(property, firstChild) as KtDeclaration
emptyBody.addAfter(psiFactory.createNewLine(), firstChild)
actualExpression = reference?.element ?: return
diff = actualExpression.textRange.startOffset - emptyBody.textRange.startOffset
actualExpressionText = actualExpression.text
emptyBody = anchor.replace(emptyBody) as KtBlockExpression
elem = findElementByOffsetAndText(diff, actualExpressionText, emptyBody)
if (elem != null) {
reference = SmartPointerManager.createPointer(elem as KtExpression)
}
emptyBody.accept(
object : KtTreeVisitorVoid() {
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
if (!expression.isOccurrence) return
expression.isOccurrence = false
references.add(SmartPointerManager.createPointer(expression))
}
})
} else {
val parent = anchor.parent
val copyTo = parent.lastChild
val copyFrom = anchor.nextSibling
property = emptyBody.addAfter(property, firstChild) as KtDeclaration
emptyBody.addAfter(psiFactory.createNewLine(), firstChild)
if (copyFrom != null && copyTo != null) {
emptyBody.addRangeAfter(copyFrom, copyTo, property)
parent.deleteChildRange(copyFrom, copyTo)
}
emptyBody = anchor.replace(emptyBody) as KtBlockExpression
}
for (child in emptyBody.children) {
if (child is KtProperty) {
property = child
}
}
if (commonContainer is KtContainerNode) {
if (commonContainer.parent is KtIfExpression) {
val next = commonContainer.nextSibling
if (next != null) {
val nextnext = next.nextSibling
if (nextnext != null && nextnext.node.elementType == KtTokens.ELSE_KEYWORD) {
if (next is PsiWhiteSpace) {
next.replace(psiFactory.createWhiteSpace())
}
}
}
}
}
}
if (!needBraces) {
for (i in allReplaces.indices) {
val replace = allReplaces[i]
if (if (i != 0) replaceOccurrence else replace.shouldReplaceOccurrence(bindingContext, commonContainer)) {
replaceExpression(replace, true)
} else {
val sibling = PsiTreeUtil.skipSiblingsBackward(replace, PsiWhiteSpace::class.java)
if (sibling == property) {
replace.parent.deleteChildRange(property.nextSibling, replace)
} else {
replace.delete()
}
}
}
}
propertyRef = property
if (noTypeInference) {
ShortenReferences.DEFAULT.process(property)
}
}
fun runRefactoring(isVar: Boolean) {
if (commonContainer !is KtDeclarationWithBody) return runRefactoring(
isVar,
expression,
commonContainer,
commonParent,
allReplaces
)
commonContainer.bodyExpression.sure { "Original body is not found: $commonContainer" }
expression.putCopyableUserData(EXPRESSION_KEY, true)
for (replace in allReplaces) {
replace.substringContextOrThis.putCopyableUserData(REPLACE_KEY, true)
}
commonParent.putCopyableUserData(COMMON_PARENT_KEY, true)
val newDeclaration = ConvertToBlockBodyIntention.convert(commonContainer)
val newCommonContainer = newDeclaration.bodyBlockExpression.sure { "New body is not found: $newDeclaration" }
val newExpression = newCommonContainer.findExpressionByCopyableDataAndClearIt(EXPRESSION_KEY)
val newCommonParent = newCommonContainer.findElementByCopyableDataAndClearIt(COMMON_PARENT_KEY)
val newAllReplaces = (allReplaces zip newCommonContainer.findExpressionsByCopyableDataAndClearIt(REPLACE_KEY)).map {
val (originalReplace, newReplace) = it
originalReplace.extractableSubstringInfo?.let {
originalReplace.apply { extractableSubstringInfo = it.copy(newReplace as KtStringTemplateExpression) }
} ?: newReplace
}
runRefactoring(
isVar,
newExpression ?: return,
newCommonContainer,
newCommonParent ?: return,
newAllReplaces
)
}
}
private fun calculateAnchor(commonParent: PsiElement, commonContainer: PsiElement, allReplaces: List<KtExpression>): PsiElement? {
if (commonParent != commonContainer) return commonParent.parentsWithSelf.firstOrNull { it.parent == commonContainer }
val startOffset = allReplaces.fold(commonContainer.endOffset) { offset, expr ->
min(offset, expr.substringContextOrThis.startOffset)
}
return commonContainer.allChildren.lastOrNull { it.textRange.contains(startOffset) }
}
private fun PsiElement.isAssignmentLHS(): Boolean = parents.any {
KtPsiUtil.isAssignment(it) && (it as KtBinaryExpression).left == this
}
private fun KtExpression.findOccurrences(occurrenceContainer: PsiElement): List<KtExpression> =
toRange().match(occurrenceContainer, KotlinPsiUnifier.DEFAULT).mapNotNull {
val candidate = it.range.elements.first()
if (candidate.isAssignmentLHS()) return@mapNotNull null
when (candidate) {
is KtExpression -> candidate
is KtStringTemplateEntryWithExpression -> candidate.expression
else -> throw KotlinExceptionWithAttachments("Unexpected candidate element ${candidate::class.java}")
.withAttachment("candidate.kt", candidate.text)
}
}
private fun KtExpression.shouldReplaceOccurrence(bindingContext: BindingContext, container: PsiElement?): Boolean {
val effectiveParent = (parent as? KtScriptInitializer)?.parent ?: parent
return isUsedAsExpression(bindingContext) || container != effectiveParent
}
private fun KtElement.getContainer(): KtElement? {
if (this is KtBlockExpression) return this
return (parentsWithSelf.zip(parents)).firstOrNull {
val (place, parent) = it
when (parent) {
is KtContainerNode -> !parent.isBadContainerNode(place)
is KtBlockExpression -> true
is KtWhenEntry -> place == parent.expression
is KtDeclarationWithBody -> parent.bodyExpression == place
is KtClassBody -> true
is KtFile -> true
else -> false
}
}?.second as? KtElement
}
private fun KtContainerNode.isBadContainerNode(place: PsiElement): Boolean = when (val parent = parent) {
is KtIfExpression -> parent.condition == place
is KtLoopExpression -> parent.body != place
is KtArrayAccessExpression -> true
else -> false
}
private fun KtExpression.getOccurrenceContainer(): KtElement? {
var result: KtElement? = null
for ((place, parent) in parentsWithSelf.zip(parents)) {
when {
parent is KtContainerNode && place !is KtBlockExpression && !parent.isBadContainerNode(place) -> result = parent
parent is KtClassBody || parent is KtFile -> return result ?: parent as? KtElement
parent is KtBlockExpression -> result = parent
parent is KtWhenEntry && place !is KtBlockExpression -> result = parent
parent is KtDeclarationWithBody && parent.bodyExpression == place && place !is KtBlockExpression -> result = parent
}
}
return null
}
private fun showErrorHint(project: Project, editor: Editor?, @NlsContexts.DialogMessage message: String) {
CommonRefactoringUtil.showErrorHint(project, editor, message, INTRODUCE_VARIABLE, HelpID.INTRODUCE_VARIABLE)
}
private fun KtExpression.chooseApplicableComponentFunctionsForVariableDeclaration(
haveOccurrencesToReplace: Boolean,
editor: Editor?,
callback: (List<FunctionDescriptor>) -> Unit
) {
if (haveOccurrencesToReplace) return callback(emptyList())
return chooseApplicableComponentFunctions(this, editor, callback = callback)
}
private fun executeMultiDeclarationTemplate(
project: Project,
editor: Editor,
declaration: KtDestructuringDeclaration,
suggestedNames: List<Collection<String>>,
postProcess: (KtDeclaration) -> Unit
) {
StartMarkAction.canStart(editor)?.let { return }
val builder = TemplateBuilderImpl(declaration)
for ((index, entry) in declaration.entries.withIndex()) {
val templateExpression = object : Expression() {
private val lookupItems = suggestedNames[index].map { LookupElementBuilder.create(it) }.toTypedArray()
override fun calculateQuickResult(context: ExpressionContext?) = TextResult(suggestedNames[index].first())
override fun calculateResult(context: ExpressionContext?) = calculateQuickResult(context)
override fun calculateLookupItems(context: ExpressionContext?) = lookupItems
}
builder.replaceElement(entry, templateExpression)
}
val startMarkAction = StartMarkAction.start(editor, project, INTRODUCE_VARIABLE)
editor.caretModel.moveToOffset(declaration.startOffset)
project.executeWriteCommand(INTRODUCE_VARIABLE) {
TemplateManager.getInstance(project).startTemplate(
editor,
builder.buildInlineTemplate(),
object : TemplateEditingAdapter() {
private fun finishMarkAction() = FinishMarkAction.finish(project, editor, startMarkAction)
override fun templateFinished(template: Template, brokenOff: Boolean) {
if (!brokenOff) postProcess(declaration)
finishMarkAction()
}
override fun templateCancelled(template: Template?) = finishMarkAction()
}
)
}
}
private fun doRefactoring(
project: Project,
editor: Editor?,
expression: KtExpression,
container: KtElement,
occurrenceContainer: KtElement,
resolutionFacade: ResolutionFacade,
bindingContext: BindingContext,
isVar: Boolean,
occurrencesToReplace: List<KtExpression>?,
onNonInteractiveFinish: ((KtDeclaration) -> Unit)?
) {
val substringInfo = expression.extractableSubstringInfo
val physicalExpression = expression.substringContextOrThis
val parent = physicalExpression.parent
when {
parent is KtQualifiedExpression -> {
if (parent.receiverExpression != physicalExpression) {
return showErrorHint(project, editor, KotlinBundle.message("cannot.refactor.no.expression"))
}
}
physicalExpression is KtStatementExpression ->
return showErrorHint(project, editor, KotlinBundle.message("cannot.refactor.no.expression"))
parent is KtOperationExpression && parent.operationReference == physicalExpression ->
return showErrorHint(project, editor, KotlinBundle.message("cannot.refactor.no.expression"))
}
PsiTreeUtil.getNonStrictParentOfType(
physicalExpression,
KtTypeReference::class.java,
KtConstructorCalleeExpression::class.java,
KtSuperExpression::class.java,
KtConstructorDelegationReferenceExpression::class.java,
KtAnnotationEntry::class.java
)?.let {
return showErrorHint(project, editor, KotlinBundle.message("cannot.refactor.no.container"))
}
val expressionType = substringInfo?.type ?: bindingContext.getType(physicalExpression) //can be null or error type
val scope = physicalExpression.getResolutionScope(bindingContext, resolutionFacade)
val dataFlowInfo = bindingContext.getDataFlowInfoAfter(physicalExpression)
val bindingTrace = ObservableBindingTrace(BindingTraceContext())
val typeNoExpectedType = substringInfo?.type
?: physicalExpression.computeTypeInfoInContext(scope, physicalExpression, bindingTrace, dataFlowInfo).type
val noTypeInference = expressionType != null
&& typeNoExpectedType != null
&& !TypeCheckerImpl(project).equalTypes(expressionType, typeNoExpectedType)
if (expressionType == null && bindingContext.get(BindingContext.QUALIFIER, physicalExpression) != null) {
return showErrorHint(project, editor, KotlinBundle.message("cannot.refactor.package.expression"))
}
if (expressionType != null && KotlinBuiltIns.isUnit(expressionType)) {
return showErrorHint(project, editor, KotlinBundle.message("cannot.refactor.expression.has.unit.type"))
}
val typeArgumentList = getQualifiedTypeArgumentList(KtPsiUtil.safeDeparenthesize(physicalExpression))
val isInplaceAvailable = editor != null && !ApplicationManager.getApplication().isUnitTestMode
val allOccurrences = occurrencesToReplace ?: expression.findOccurrences(occurrenceContainer)
val callback = Pass<OccurrencesChooser.ReplaceChoice> { replaceChoice ->
val allReplaces = when (replaceChoice) {
OccurrencesChooser.ReplaceChoice.ALL -> allOccurrences
else -> listOf(expression)
}
val replaceOccurrence = substringInfo != null
|| expression.shouldReplaceOccurrence(bindingContext, container)
|| allReplaces.size > 1
val commonParent = if (allReplaces.isNotEmpty()) {
PsiTreeUtil.findCommonParent(allReplaces.map { it.substringContextOrThis }) as KtElement
} else {
expression.parent as KtElement
}
var commonContainer = commonParent as? KtFile ?: commonParent.getContainer()!!
if (commonContainer != container && container.isAncestor(commonContainer, true)) {
commonContainer = container
}
fun postProcess(declaration: KtDeclaration) {
if (typeArgumentList != null) {
val initializer = when (declaration) {
is KtProperty -> declaration.initializer
is KtDestructuringDeclaration -> declaration.initializer
else -> null
} ?: return
runWriteAction { addTypeArgumentsIfNeeded(initializer, typeArgumentList) }
}
if (editor != null && !replaceOccurrence) {
editor.caretModel.moveToOffset(declaration.endOffset)
}
}
physicalExpression.chooseApplicableComponentFunctionsForVariableDeclaration(replaceOccurrence, editor) { componentFunctions ->
val validator = NewDeclarationNameValidator(
commonContainer,
calculateAnchor(commonParent, commonContainer, allReplaces),
NewDeclarationNameValidator.Target.VARIABLES
)
val suggestedNames = if (componentFunctions.isNotEmpty()) {
val collectingValidator = CollectingNameValidator(filter = validator)
componentFunctions.map { suggestNamesForComponent(it, project, collectingValidator) }
} else {
KotlinNameSuggester.suggestNamesByExpressionAndType(
expression,
substringInfo?.type,
bindingContext,
validator,
"value"
).let(::listOf)
}
val introduceVariableContext = IntroduceVariableContext(
expression, suggestedNames, allReplaces, commonContainer, commonParent,
replaceOccurrence, noTypeInference, expressionType, componentFunctions, bindingContext, resolutionFacade
)
project.executeCommand(INTRODUCE_VARIABLE, null) {
runWriteAction { introduceVariableContext.runRefactoring(isVar) }
val property = introduceVariableContext.propertyRef ?: return@executeCommand
if (editor == null) {
onNonInteractiveFinish?.invoke(property)
return@executeCommand
}
editor.caretModel.moveToOffset(property.textOffset)
editor.selectionModel.removeSelection()
if (!isInplaceAvailable) {
postProcess(property)
return@executeCommand
}
PsiDocumentManager.getInstance(project).commitDocument(editor.document)
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document)
when (property) {
is KtProperty -> {
KotlinVariableInplaceIntroducer(
property,
introduceVariableContext.reference?.element,
introduceVariableContext.references.mapNotNull { it.element }.toTypedArray(),
suggestedNames.single(),
isVar,
/*todo*/ false,
expressionType,
noTypeInference,
project,
editor,
::postProcess
).startInplaceIntroduceTemplate()
}
is KtDestructuringDeclaration -> {
executeMultiDeclarationTemplate(project, editor, property, suggestedNames, ::postProcess)
}
else -> throw AssertionError("Unexpected declaration: ${property.getElementTextWithContext()}")
}
}
}
}
if (isInplaceAvailable && occurrencesToReplace == null) {
val chooser = object : OccurrencesChooser<KtExpression>(editor) {
override fun getOccurrenceRange(occurrence: KtExpression): TextRange? {
return occurrence.extractableSubstringInfo?.contentRange ?: occurrence.textRange
}
}
ApplicationManager.getApplication().invokeLater {
chooser.showChooser(expression, allOccurrences, callback)
}
} else {
callback.pass(OccurrencesChooser.ReplaceChoice.ALL)
}
}
private fun PsiElement.isFunExpressionOrLambdaBody(): Boolean {
if (isFunctionalExpression()) return true
val parent = parent as? KtFunction ?: return false
return parent.bodyExpression == this && (parent is KtFunctionLiteral || parent.isFunctionalExpression())
}
private fun KtExpression.getCandidateContainers(
resolutionFacade: ResolutionFacade,
originalContext: BindingContext
): List<Pair<KtElement, KtElement>> {
val physicalExpression = substringContextOrThis
val contentRange = extractableSubstringInfo?.contentRange
val file = physicalExpression.containingKtFile
val references =
physicalExpression.collectDescendantsOfType<KtReferenceExpression> { contentRange == null || contentRange.contains(it.textRange) }
fun isResolvableNextTo(neighbour: KtExpression): Boolean {
val scope = neighbour.getResolutionScope(originalContext, resolutionFacade)
val newContext = physicalExpression.analyzeInContext(scope, neighbour)
val project = file.project
return references.all {
val originalDescriptor = originalContext[BindingContext.REFERENCE_TARGET, it]
if (originalDescriptor is ValueParameterDescriptor && (originalContext[BindingContext.AUTO_CREATED_IT, originalDescriptor] == true)) {
return@all originalDescriptor.containingDeclaration.source.getPsi().isAncestor(neighbour, true)
}
val newDescriptor = newContext[BindingContext.REFERENCE_TARGET, it]
compareDescriptors(project, newDescriptor, originalDescriptor)
}
}
val firstContainer = physicalExpression.getContainer() ?: return emptyList()
val firstOccurrenceContainer = physicalExpression.getOccurrenceContainer() ?: return emptyList()
val containers = SmartList(firstContainer)
val occurrenceContainers = SmartList(firstOccurrenceContainer)
if (!firstContainer.isFunExpressionOrLambdaBody()) return listOf(firstContainer to firstOccurrenceContainer)
val lambdasAndContainers = ArrayList<Pair<KtExpression, KtElement>>().apply {
var container = firstContainer
do {
var lambda: KtExpression = container.getNonStrictParentOfType<KtFunction>()!!
if (lambda is KtFunctionLiteral) lambda = lambda.parent as? KtLambdaExpression ?: return@apply
if (!isResolvableNextTo(lambda)) return@apply
container = lambda.getContainer() ?: return@apply
add(lambda to container)
} while (container.isFunExpressionOrLambdaBody())
}
lambdasAndContainers.mapTo(containers) { it.second }
lambdasAndContainers.mapTo(occurrenceContainers) { it.first.getOccurrenceContainer() }
return ArrayList<Pair<KtElement, KtElement>>().apply {
for ((container, occurrenceContainer) in (containers zip occurrenceContainers)) {
if (occurrenceContainer == null) continue
add(container to occurrenceContainer)
}
}
}
fun doRefactoring(
project: Project,
editor: Editor?,
expressionToExtract: KtExpression?,
isVar: Boolean,
occurrencesToReplace: List<KtExpression>?,
onNonInteractiveFinish: ((KtDeclaration) -> Unit)?
) {
val expression = expressionToExtract?.let { KtPsiUtil.safeDeparenthesize(it) }
?: return showErrorHint(project, editor, KotlinBundle.message("cannot.refactor.no.expression"))
if (expression.isAssignmentLHS()) {
return showErrorHint(project, editor, KotlinBundle.message("cannot.refactor.no.expression"))
}
if (!CommonRefactoringUtil.checkReadOnlyStatus(project, expression)) return
val physicalExpression = expression.substringContextOrThis
val resolutionFacade = physicalExpression.getResolutionFacade()
val bindingContext = resolutionFacade.analyze(physicalExpression, BodyResolveMode.FULL)
fun runWithChosenContainers(container: KtElement, occurrenceContainer: KtElement) {
doRefactoring(
project, editor, expression, container, occurrenceContainer, resolutionFacade, bindingContext,
isVar, occurrencesToReplace, onNonInteractiveFinish
)
}
val candidateContainers = expression.getCandidateContainers(resolutionFacade, bindingContext).ifEmpty {
return showErrorHint(project, editor, KotlinBundle.message("cannot.refactor.no.container"))
}
if (editor == null) {
return candidateContainers.first().let { runWithChosenContainers(it.first, it.second) }
}
if (ApplicationManager.getApplication().isUnitTestMode) {
return candidateContainers.last().let { runWithChosenContainers(it.first, it.second) }
}
chooseContainerElementIfNecessary(candidateContainers, editor,
KotlinBundle.message("text.select.target.code.block"), true, { it.first }) {
runWithChosenContainers(it.first, it.second)
}
}
override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext) {
if (file !is KtFile) return
try {
selectElement(editor, file, listOf(CodeInsightUtils.ElementKind.EXPRESSION)) {
doRefactoring(project, editor, it as KtExpression?, false, null, null)
}
} catch (e: IntroduceRefactoringException) {
showErrorHint(project, editor, e.message!!)
}
}
override fun invoke(project: Project, elements: Array<PsiElement>, dataContext: DataContext) {
//do nothing
}
}
| apache-2.0 | 666b646055ec91b3a67d725e2ed583a4 | 47.403417 | 158 | 0.631682 | 6.318182 | false | false | false | false |
siosio/intellij-community | platform/platform-impl/src/com/intellij/internal/statistic/collectors/fus/os/SystemRuntimeCollector.kt | 1 | 8619 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.collectors.fus.os
import com.intellij.internal.DebugAttachDetector
import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventId1
import com.intellij.internal.statistic.eventLog.events.EventId2
import com.intellij.internal.statistic.eventLog.events.EventId3
import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector
import com.intellij.internal.statistic.utils.StatisticsUtil
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.Version
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.lang.JavaVersion
import com.intellij.util.system.CpuArch
import com.sun.management.OperatingSystemMXBean
import java.lang.management.ManagementFactory
import java.util.*
import kotlin.math.min
import kotlin.math.roundToInt
class SystemRuntimeCollector : ApplicationUsagesCollector() {
override fun getGroup(): EventLogGroup = GROUP
override fun getMetrics(): Set<MetricEvent> {
val result = HashSet<MetricEvent>()
result.add(CORES.metric(StatisticsUtil.getUpperBound(Runtime.getRuntime().availableProcessors(),
intArrayOf(1, 2, 4, 6, 8, 12, 16, 20, 24, 32, 64))))
val osMxBean = ManagementFactory.getOperatingSystemMXBean() as OperatingSystemMXBean
val totalPhysicalMemory = StatisticsUtil.getUpperBound((osMxBean.totalPhysicalMemorySize.toDouble() / (1 shl 30)).roundToInt(),
intArrayOf(1, 2, 4, 8, 12, 16, 24, 32, 48, 64, 128, 256))
result.add(MEMORY_SIZE.metric(totalPhysicalMemory))
var totalSwapSize = (osMxBean.totalSwapSpaceSize.toDouble() / (1 shl 30)).roundToInt()
totalSwapSize = min(totalSwapSize, totalPhysicalMemory)
result.add(SWAP_SIZE.metric(if (totalSwapSize > 0) StatisticsUtil.getNextPowerOfTwo(totalSwapSize) else 0))
try {
val totalSpace = PathManager.getIndexRoot().toFile().totalSpace
if (totalSpace > 0L) {
val indexDirPartitionSize = min(1 shl 14, // currently max available consumer hard drive size is around 16 Tb
StatisticsUtil.getNextPowerOfTwo((totalSpace shr 30).toInt()))
val indexDirPartitionFreeSpace =
((PathManager.getIndexRoot().toFile().usableSpace.toDouble() / totalSpace) * 100).toInt()
result.add(DISK_SIZE.metric(indexDirPartitionSize, indexDirPartitionFreeSpace))
}
} catch (uoe : UnsupportedOperationException) {
// In case of some custom FS
} catch (se : SecurityException) {
// In case of Security Manager denies read of FS attributes
}
for (gc in ManagementFactory.getGarbageCollectorMXBeans()) {
result.add(GC.metric(gc.name))
}
result.add(JVM.metric(
Version(1, JavaVersion.current().feature, 0),
CpuArch.CURRENT.name.toLowerCase(Locale.ENGLISH),
getJavaVendor())
)
val options: HashMap<String, Long> = collectJvmOptions()
for (option in options) {
result.add(JVM_OPTION.metric(option.key, option.value))
}
for (clientProperty in splashClientProperties) {
val value = System.getProperty(clientProperty)
if (value != null) {
result.add(JVM_CLIENT_PROPERTIES.metric(clientProperty, value.toBoolean()))
}
}
result.add(DEBUG_AGENT.metric(DebugAttachDetector.isDebugEnabled()))
return result
}
private fun collectJvmOptions(): HashMap<String, Long> {
val options: HashMap<String, Long> = hashMapOf()
for (argument in ManagementFactory.getRuntimeMXBean().inputArguments) {
val data = convertOptionToData(argument)
if (data != null) {
options[data.first] = data.second
}
}
return options
}
private fun getJavaVendor() : String {
return when {
SystemInfo.isJetBrainsJvm -> "JetBrains"
SystemInfo.isOracleJvm -> "Oracle"
SystemInfo.isIbmJvm -> "IBM"
SystemInfo.isAzulJvm -> "Azul"
else -> "Other"
}
}
companion object {
private val knownOptions = ContainerUtil.newHashSet(
"-Xms", "-Xmx", "-XX:SoftRefLRUPolicyMSPerMB", "-XX:ReservedCodeCacheSize"
)
//No -D prefix is required here
private val splashClientProperties = arrayListOf(
"splash", "nosplash"
)
private val GROUP: EventLogGroup = EventLogGroup("system.runtime", 12)
private val DEBUG_AGENT: EventId1<Boolean> = GROUP.registerEvent("debug.agent", EventFields.Enabled)
private val CORES: EventId1<Int> = GROUP.registerEvent("cores", EventFields.Int("value"))
private val MEMORY_SIZE: EventId1<Int> = GROUP.registerEvent("memory.size", EventFields.Int("gigabytes"))
private val SWAP_SIZE: EventId1<Int> = GROUP.registerEvent("swap.size", EventFields.Int("gigabytes"))
private val DISK_SIZE: EventId2<Int, Int> = GROUP.registerEvent("disk.size",
EventFields.Int("index_partition_size"),
EventFields.Int("index_partition_free"))
private val GC: EventId1<String?> = GROUP.registerEvent("garbage.collector",
EventFields.String(
"name",
arrayListOf("Shenandoah", "G1_Young_Generation", "G1_Old_Generation", "Copy",
"MarkSweepCompact", "PS_MarkSweep", "PS_Scavenge", "ParNew", "ConcurrentMarkSweep")
)
)
private val JVM: EventId3<Version?, String?, String?> = GROUP.registerEvent("jvm",
EventFields.VersionByObject,
EventFields.String("arch", arrayListOf("x86", "x86_64", "arm64", "other", "unknown")),
EventFields.String("vendor", arrayListOf( "JetBrains", "Apple", "Oracle", "Sun", "IBM", "Azul", "Other"))
)
private val JVM_OPTION: EventId2<String?, Long> = GROUP.registerEvent("jvm.option",
EventFields.String("name", arrayListOf("Xmx", "Xms", "SoftRefLRUPolicyMSPerMB", "ReservedCodeCacheSize")),
EventFields.Long("value")
)
private val JVM_CLIENT_PROPERTIES: EventId2<String?, Boolean> = GROUP.registerEvent("jvm.client.properties",
EventFields.String("name", splashClientProperties),
EventFields.Boolean("value")
)
fun convertOptionToData(arg: String): Pair<String, Long>? {
val value = getMegabytes(arg).toLong()
if (value < 0) return null
when {
arg.startsWith("-Xmx") -> {
return "Xmx" to roundDown(value, 512, 750, 1000, 1024, 1500, 2000, 2048, 3000, 4000, 4096, 6000, 8000)
}
arg.startsWith("-Xms") -> {
return "Xms" to roundDown(value, 64, 128, 256, 512)
}
arg.startsWith("-XX:SoftRefLRUPolicyMSPerMB") -> {
return "SoftRefLRUPolicyMSPerMB" to roundDown(value, 50, 100)
}
arg.startsWith("-XX:ReservedCodeCacheSize") -> {
return "ReservedCodeCacheSize" to roundDown(value, 240, 300, 400, 500)
}
else -> {
return null
}
}
}
private fun getMegabytes(s: String): Int {
var num = knownOptions.firstOrNull { s.startsWith(it) }
?.let { s.substring(it.length).toUpperCase().trim() }
if (num == null) return -1
if (num.startsWith("=")) num = num.substring(1)
if (num.last().isDigit()) {
return try {
Integer.parseInt(num)
}
catch (e: Exception) {
-1
}
}
try {
val size = Integer.parseInt(num.substring(0, num.length - 1))
when (num.last()) {
'B' -> return size / (1024 * 1024)
'K' -> return size / 1024
'M' -> return size
'G' -> return size * 1024
}
}
catch (e: Exception) {
return -1
}
return -1
}
fun roundDown(value: Long, vararg steps: Long): Long {
val length = steps.size
if (length == 0 || steps[0] < 0) return -1
var ind = 0
while (ind < length && value >= steps[ind]) {
ind++
}
return if (ind == 0) 0 else steps[ind - 1]
}
}
}
| apache-2.0 | 721823e70c3c8c1ced351cf819525d57 | 40.239234 | 158 | 0.639285 | 4.361842 | false | false | false | false |
siosio/intellij-community | platform/platform-api/src/com/intellij/ui/tabs/JBTabsBorder.kt | 1 | 731 | // 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.ui.tabs
import com.intellij.ui.tabs.impl.JBTabsImpl
import com.intellij.util.ui.JBUI
import java.awt.Component
import java.awt.Insets
import javax.swing.border.Border
abstract class JBTabsBorder(val tabs: JBTabsImpl) : Border {
val thickness: Int
get() = if (tabs.tabPainter == null) JBUI.scale(1) else tabs.tabPainter.getTabTheme().topBorderThickness
override fun getBorderInsets(c: Component?): Insets = JBUI.emptyInsets()
override fun isBorderOpaque(): Boolean {
return true
}
open val effectiveBorder: Insets
get() = JBUI.emptyInsets()
} | apache-2.0 | 505335d65d9263d5165f4af4a64704c4 | 30.826087 | 140 | 0.756498 | 3.888298 | false | false | false | false |
jwren/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/CommitSessionCollector.kt | 3 | 9340 | // 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.vcs.commit
import com.intellij.diff.DiffContext
import com.intellij.diff.DiffExtension
import com.intellij.diff.FrameDiffTool
import com.intellij.diff.actions.impl.OpenInEditorAction
import com.intellij.diff.requests.DiffRequest
import com.intellij.diff.requests.MessageDiffRequest
import com.intellij.diff.tools.util.DiffDataKeys
import com.intellij.diff.util.DiffUserDataKeysEx
import com.intellij.diff.util.DiffUtil
import com.intellij.internal.statistic.StructuredIdeActivity
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.AnActionResult
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys
import com.intellij.openapi.actionSystem.ex.AnActionListener
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.ChangesViewManager
import com.intellij.openapi.vcs.changes.ui.ChangesTree
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.ui.TreeActions
import com.intellij.util.containers.ContainerUtil
import java.awt.event.HierarchyEvent
import java.awt.event.MouseEvent
import java.util.*
import javax.swing.JTree
class CommitSessionCounterUsagesCollector : CounterUsagesCollector() {
companion object {
val GROUP = EventLogGroup("commit.interactions", 3)
val FILES_TOTAL = EventFields.RoundedInt("files_total")
val FILES_INCLUDED = EventFields.RoundedInt("files_included")
val UNVERSIONED_TOTAL = EventFields.RoundedInt("unversioned_total")
val UNVERSIONED_INCLUDED = EventFields.RoundedInt("unversioned_included")
val SESSION = GROUP.registerIdeActivity("session",
startEventAdditionalFields = arrayOf(FILES_TOTAL, FILES_INCLUDED,
UNVERSIONED_TOTAL, UNVERSIONED_INCLUDED),
finishEventAdditionalFields = arrayOf())
val EXCLUDE_FILE = GROUP.registerEvent("exclude.file", EventFields.InputEventByAnAction, EventFields.InputEventByMouseEvent)
val INCLUDE_FILE = GROUP.registerEvent("include.file", EventFields.InputEventByAnAction, EventFields.InputEventByMouseEvent)
val SELECT_FILE = GROUP.registerEvent("select.item", EventFields.InputEventByAnAction, EventFields.InputEventByMouseEvent)
val SHOW_DIFF = GROUP.registerEvent("show.diff")
val CLOSE_DIFF = GROUP.registerEvent("close.diff")
val JUMP_TO_SOURCE = GROUP.registerEvent("jump.to.source", EventFields.InputEventByAnAction)
val COMMIT = GROUP.registerEvent("commit", FILES_INCLUDED, UNVERSIONED_INCLUDED)
val COMMIT_AND_PUSH = GROUP.registerEvent("commit.and.push", FILES_INCLUDED, UNVERSIONED_INCLUDED)
}
override fun getGroup(): EventLogGroup = GROUP
}
@Service(Service.Level.PROJECT)
class CommitSessionCollector(val project: Project) {
companion object {
@JvmStatic
fun getInstance(project: Project): CommitSessionCollector = project.service()
}
private var activity: StructuredIdeActivity? = null
private fun shouldTrackEvents(): Boolean {
val mode = CommitModeManager.getInstance(project).getCurrentCommitMode()
val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.COMMIT_TOOLWINDOW_ID)
return toolWindow != null && mode is CommitMode.NonModalCommitMode && !mode.isToggleMode
}
private fun updateToolWindowState() {
val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.COMMIT_TOOLWINDOW_ID)
val isSessionActive = shouldTrackEvents() && toolWindow?.isVisible == true
if (!isSessionActive) {
finishActivity()
}
else if (activity == null) {
val changesViewManager = ChangesViewManager.getInstance(project) as ChangesViewManager
val commitUi = changesViewManager.commitWorkflowHandler?.ui ?: return
activity = CommitSessionCounterUsagesCollector.SESSION.started(project) {
listOf(
CommitSessionCounterUsagesCollector.FILES_TOTAL.with(commitUi.getDisplayedChanges().size),
CommitSessionCounterUsagesCollector.FILES_INCLUDED.with(commitUi.getIncludedChanges().size),
CommitSessionCounterUsagesCollector.UNVERSIONED_TOTAL.with(commitUi.getDisplayedUnversionedFiles().size),
CommitSessionCounterUsagesCollector.UNVERSIONED_INCLUDED.with(commitUi.getIncludedUnversionedFiles().size)
)
}
}
}
private fun finishActivity() {
activity?.finished()
activity = null
}
fun logFileSelected(event: MouseEvent) {
if (!shouldTrackEvents()) return
CommitSessionCounterUsagesCollector.SELECT_FILE.log(project, null, event)
}
fun logFileSelected(event: AnActionEvent) {
if (!shouldTrackEvents()) return
CommitSessionCounterUsagesCollector.SELECT_FILE.log(project, event, null)
}
fun logInclusionToggle(excluded: Boolean, event: AnActionEvent) {
if (!shouldTrackEvents()) return
if (excluded) {
CommitSessionCounterUsagesCollector.EXCLUDE_FILE.log(project, event, null)
}
else {
CommitSessionCounterUsagesCollector.INCLUDE_FILE.log(project, event, null)
}
}
fun logInclusionToggle(excluded: Boolean, event: MouseEvent) {
if (!shouldTrackEvents()) return
if (excluded) {
CommitSessionCounterUsagesCollector.EXCLUDE_FILE.log(project, null, event)
}
else {
CommitSessionCounterUsagesCollector.INCLUDE_FILE.log(project, null, event)
}
}
fun logCommit(executorId: String?, includedChanges: Int, includedUnversioned: Int) {
if (!shouldTrackEvents()) return
if (executorId == "Git.Commit.And.Push.Executor") {
CommitSessionCounterUsagesCollector.COMMIT_AND_PUSH.log(project, includedChanges, includedUnversioned)
}
else {
CommitSessionCounterUsagesCollector.COMMIT.log(project, includedChanges, includedUnversioned)
}
finishActivity()
updateToolWindowState()
}
fun logDiffViewer(isShown: Boolean) {
if (!shouldTrackEvents()) return
if (isShown) {
CommitSessionCounterUsagesCollector.SHOW_DIFF.log(project)
}
else {
CommitSessionCounterUsagesCollector.CLOSE_DIFF.log(project)
}
}
fun logJumpToSource(event: AnActionEvent) {
if (!shouldTrackEvents()) return
CommitSessionCounterUsagesCollector.JUMP_TO_SOURCE.log(project, event)
}
internal class MyToolWindowManagerListener(val project: Project) : ToolWindowManagerListener {
override fun stateChanged(toolWindowManager: ToolWindowManager) {
getInstance(project).updateToolWindowState()
}
}
internal class MyDiffExtension : DiffExtension() {
private val HierarchyEvent.isShowingChanged get() = (changeFlags and HierarchyEvent.SHOWING_CHANGED.toLong()) != 0L
override fun onViewerCreated(viewer: FrameDiffTool.DiffViewer, context: DiffContext, request: DiffRequest) {
val project = context.project ?: return
if (!DiffUtil.isUserDataFlagSet(DiffUserDataKeysEx.LAST_REVISION_WITH_LOCAL, context)) return
if (request is MessageDiffRequest) return
viewer.component.addHierarchyListener { e ->
if (e.isShowingChanged) {
if (e.component.isShowing) {
getInstance(project).logDiffViewer(true)
}
else {
getInstance(project).logDiffViewer(false)
}
}
}
}
}
/**
* See [com.intellij.internal.statistic.collectors.fus.actions.persistence.ActionsCollectorImpl]
*/
internal class MyAnActionListener : AnActionListener {
private val ourStats: MutableMap<AnActionEvent, Project> = WeakHashMap()
override fun beforeActionPerformed(action: AnAction, event: AnActionEvent) {
val project = event.project ?: return
if (action is OpenInEditorAction) {
val context = event.getData(DiffDataKeys.DIFF_CONTEXT) ?: return
if (!DiffUtil.isUserDataFlagSet(DiffUserDataKeysEx.LAST_REVISION_WITH_LOCAL, context)) return
ourStats[event] = project
}
if (action is TreeActions) {
val component = event.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT) as? JTree ?: return
if (component.getClientProperty(ChangesTree.LOG_COMMIT_SESSION_EVENTS) != true) return
ourStats[event] = project
}
}
override fun afterActionPerformed(action: AnAction, event: AnActionEvent, result: AnActionResult) {
val project = ourStats.remove(event) ?: return
if (!result.isPerformed) return
if (action is OpenInEditorAction) {
getInstance(project).logJumpToSource(event)
}
if (action is TreeActions) {
getInstance(project).logFileSelected(event)
}
}
}
}
| apache-2.0 | 66adbec27607cffaf1f63c69da4da108 | 41.072072 | 158 | 0.745289 | 4.936575 | false | false | false | false |
emilybache/Yatzy-Refactoring-Kata | kotlin/src/main/kotlin/Yatzy.kt | 1 | 6082 |
class Yatzy(d1: Int, d2: Int, d3: Int, d4: Int, _5: Int) {
protected var dice: IntArray = IntArray(5)
init {
dice[0] = d1
dice[1] = d2
dice[2] = d3
dice[3] = d4
dice[4] = _5
}
fun fours(): Int {
var sum: Int = 0
for (at in 0..4) {
if (dice[at] == 4) {
sum += 4
}
}
return sum
}
fun fives(): Int {
var s = 0
var i: Int = 0
while (i < dice.size) {
if (dice[i] == 5)
s = s + 5
i++
}
return s
}
fun sixes(): Int {
var sum = 0
for (at in dice.indices)
if (dice[at] == 6)
sum = sum + 6
return sum
}
companion object {
fun chance(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int): Int {
var total = 0
total += d1
total += d2
total += d3
total += d4
total += d5
return total
}
fun yatzy(vararg dice: Int): Int {
val counts = IntArray(6)
for (die in dice)
counts[die - 1]++
for (i in 0..5)
if (counts[i] == 5)
return 50
return 0
}
fun ones(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int): Int {
var sum = 0
if (d1 == 1) sum++
if (d2 == 1) sum++
if (d3 == 1) sum++
if (d4 == 1) sum++
if (d5 == 1)
sum++
return sum
}
fun twos(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int): Int {
var sum = 0
if (d1 == 2) sum += 2
if (d2 == 2) sum += 2
if (d3 == 2) sum += 2
if (d4 == 2) sum += 2
if (d5 == 2) sum += 2
return sum
}
fun threes(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int): Int {
var s: Int = 0
if (d1 == 3) s += 3
if (d2 == 3) s += 3
if (d3 == 3) s += 3
if (d4 == 3) s += 3
if (d5 == 3) s += 3
return s
}
fun score_pair(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int): Int {
val counts = IntArray(6)
counts[d1 - 1]++
counts[d2 - 1]++
counts[d3 - 1]++
counts[d4 - 1]++
counts[d5 - 1]++
var at: Int
at = 0
while (at != 6) {
if (counts[6 - at - 1] >= 2)
return (6 - at) * 2
at++
}
return 0
}
fun two_pair(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int): Int {
val counts = IntArray(6)
counts[d1 - 1]++
counts[d2 - 1]++
counts[d3 - 1]++
counts[d4 - 1]++
counts[d5 - 1]++
var n = 0
var score = 0
var i = 0
while (i < 6) {
if (counts[6 - i - 1] >= 2) {
n++
score += 6 - i
}
i += 1
}
return if (n == 2)
score * 2
else
0
}
fun four_of_a_kind(_1: Int, _2: Int, d3: Int, d4: Int, d5: Int): Int {
val tallies: IntArray = IntArray(6)
tallies[_1 - 1]++
tallies[_2 - 1]++
tallies[d3 - 1]++
tallies[d4 - 1]++
tallies[d5 - 1]++
for (i in 0..5)
if (tallies[i] >= 4)
return (i + 1) * 4
return 0
}
fun three_of_a_kind(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int): Int {
val t: IntArray = IntArray(6)
t[d1 - 1]++
t[d2 - 1]++
t[d3 - 1]++
t[d4 - 1]++
t[d5 - 1]++
for (i in 0..5)
if (t[i] >= 3)
return (i + 1) * 3
return 0
}
fun smallStraight(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int): Int {
val tallies: IntArray = IntArray(6)
tallies[d1 - 1] += 1
tallies[d2 - 1] += 1
tallies[d3 - 1] += 1
tallies[d4 - 1] += 1
tallies[d5 - 1] += 1
return if (tallies[0] == 1 &&
tallies[1] == 1 &&
tallies[2] == 1 &&
tallies[3] == 1 &&
tallies[4] == 1
) 15 else 0
}
fun largeStraight(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int): Int {
val tallies: IntArray = IntArray(6)
tallies[d1 - 1] += 1
tallies[d2 - 1] += 1
tallies[d3 - 1] += 1
tallies[d4 - 1] += 1
tallies[d5 - 1] += 1
return if (tallies[1] == 1 &&
tallies[2] == 1 &&
tallies[3] == 1 &&
tallies[4] == 1
&& tallies[5] == 1
) 20 else 0
}
fun fullHouse(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int): Int {
val tallies: IntArray
var _2 = false
var i: Int
var _2_at = 0
var _3 = false
var _3_at = 0
tallies = IntArray(6)
tallies[d1 - 1] += 1
tallies[d2 - 1] += 1
tallies[d3 - 1] += 1
tallies[d4 - 1] += 1
tallies[d5 - 1] += 1
i = 0
while (i != 6) {
if (tallies[i] == 2) {
_2 = true
_2_at = i + 1
}
i += 1
}
i = 0
while (i != 6) {
if (tallies[i] == 3) {
_3 = true
_3_at = i + 1
}
i += 1
}
return if (_2 && _3)
_2_at * 2 + _3_at * 3
else
0
}
}
}
| mit | 5f7355fd13190185187fc3ab709c9eea | 24.991453 | 79 | 0.323413 | 3.562976 | false | false | false | false |
GunoH/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/diff/CombinedChangeDiffComponentFactoryProvider.kt | 5 | 2493 | // 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.changes.actions.diff
import com.intellij.diff.tools.combined.*
import com.intellij.openapi.ListSelection
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.vcs.changes.ChangeViewDiffRequestProcessor.Wrapper
import com.intellij.openapi.vcs.changes.ChangeViewDiffRequestProcessor.toListIfNotMany
import com.intellij.openapi.vcs.changes.ui.PresentableChange
class CombinedChangeDiffComponentFactoryProvider : CombinedDiffComponentFactoryProvider {
override fun create(model: CombinedDiffModel): CombinedDiffComponentFactory = MyFactory(model)
private inner class MyFactory(model: CombinedDiffModel) : CombinedDiffComponentFactory(model) {
init {
model.init()
}
override fun createGoToChangeAction(): AnAction = MyGoToChangePopupAction()
private inner class MyGoToChangePopupAction : PresentableGoToChangePopupAction.Default<PresentableChange>() {
val viewer get() = model.context.getUserData(COMBINED_DIFF_VIEWER_KEY)
override fun getChanges(): ListSelection<out PresentableChange> {
val changes =
if (model is CombinedDiffPreviewModel) model.iterateAllChanges().toList()
else model.requests.values.filterIsInstance<PresentableChange>()
val selected = viewer?.getCurrentBlockId() as? CombinedPathBlockId
val selectedIndex = when {
selected != null -> changes.indexOfFirst { it.tag == selected.tag
&& it.fileStatus == selected.fileStatus
&& it.filePath == selected.path }
else -> -1
}
return ListSelection.createAt(changes, selectedIndex)
}
override fun canNavigate(): Boolean {
if (model is CombinedDiffPreviewModel) {
val allChanges = toListIfNotMany(model.iterateAllChanges(), true)
return allChanges == null || allChanges.size > 1
}
return super.canNavigate()
}
override fun onSelected(change: PresentableChange) {
if (model is CombinedDiffPreviewModel && change is Wrapper) {
model.selected = change
}
else {
viewer?.selectDiffBlock(CombinedPathBlockId(change.filePath, change.fileStatus, change.tag), ScrollPolicy.DIFF_BLOCK, true)
}
}
}
}
}
| apache-2.0 | 8ff32da03cbe61c76fb37f003e6890de | 40.55 | 133 | 0.693943 | 5.006024 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/ide/navbar/ui/popup.kt | 2 | 3267 | // 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.ide.actions.OpenInRightSplitAction
import com.intellij.ide.navbar.ide.NavBarVmItem
import com.intellij.ide.navbar.impl.PsiNavBarItem
import com.intellij.ide.navbar.vm.NavBarPopupItem
import com.intellij.ide.navbar.vm.NavBarPopupVm
import com.intellij.ide.navigationToolbar.NavBarListWrapper
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.ui.CollectionListModel
import com.intellij.ui.LightweightHint
import com.intellij.ui.PopupHandler
import com.intellij.ui.popup.HintUpdateSupply
import com.intellij.ui.speedSearch.ListWithFilter
import com.intellij.util.SlowOperations
import com.intellij.util.ui.JBUI
import java.awt.Component
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.JComponent
import javax.swing.JList
internal fun createNavBarPopup(list: JList<NavBarPopupItem>): LightweightHint {
// TODO implement async hint update supply
HintUpdateSupply.installHintUpdateSupply(list) { item ->
SlowOperations.allowSlowOperations(ThrowableComputable {
((item as? NavBarVmItem)?.pointer?.dereference() as? PsiNavBarItem)?.data
})
}
val popupComponent = list.withSpeedSearch()
val popup = object : LightweightHint(popupComponent) {
override fun onPopupCancel() {
HintUpdateSupply.hideHint(list)
}
}
popup.setFocusRequestor(popupComponent)
popup.setForceShowAsPopup(true)
return popup
}
internal fun navBarPopupList(
vm: NavBarPopupVm,
contextComponent: Component,
floating: Boolean,
): JList<NavBarPopupItem> {
val list = ContextJBList<NavBarPopupItem>(contextComponent)
list.model = CollectionListModel(vm.items)
list.cellRenderer = NavBarPopupListCellRenderer(floating)
list.border = JBUI.Borders.empty(5)
list.background = JBUI.CurrentTheme.Popup.BACKGROUND
list.addListSelectionListener {
vm.itemsSelected(list.selectedValuesList)
}
PopupHandler.installPopupMenu(list, NavBarContextMenuActionGroup(), ActionPlaces.NAVIGATION_BAR_POPUP)
list.addMouseListener(object : 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.isPopupTrigger && e.clickCount == 1 && e.button == MouseEvent.BUTTON1) {
vm.complete()
}
}
})
return list
}
private fun JList<NavBarPopupItem>.withSpeedSearch(): JComponent {
val wrapper = NavBarListWrapper(this)
val component = ListWithFilter.wrap(this, wrapper) { item ->
item.presentation.popupText ?: item.presentation.text
} as ListWithFilter<*>
wrapper.updateViewportPreferredSizeIfNeeded() // this fixes IDEA-301848 for some reason
component.setAutoPackHeight(!UISettings.getInstance().showNavigationBarInBottom)
OpenInRightSplitAction.overrideDoubleClickWithOneClick(component)
return component
}
| apache-2.0 | 5b4246a682998b4c133e353c193d0382 | 34.901099 | 120 | 0.775941 | 4.210052 | false | false | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/merge/GitMergeDialog.kt | 3 | 15773 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.merge
import com.intellij.dvcs.DvcsUtil
import com.intellij.ide.ui.laf.darcula.DarculaUIUtil.BW
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.CollectionComboBoxModel
import com.intellij.ui.MutableCollectionComboBoxModel
import com.intellij.ui.ScrollPaneFactory.createScrollPane
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.components.DropDownLink
import com.intellij.ui.components.JBTextArea
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBUI
import git4idea.GitBranch
import git4idea.branch.GitBranchUtil
import git4idea.branch.GitBranchUtil.equalBranches
import git4idea.commands.Git
import git4idea.commands.GitCommand
import git4idea.commands.GitLineHandler
import git4idea.config.GitExecutableManager
import git4idea.config.GitMergeSettings
import git4idea.config.GitVersionSpecialty.NO_VERIFY_SUPPORTED
import git4idea.i18n.GitBundle
import git4idea.merge.dialog.*
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import git4idea.repo.GitRepositoryReader
import git4idea.ui.ComboBoxWithAutoCompletion
import net.miginfocom.layout.AC
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import java.awt.BorderLayout
import java.awt.Insets
import java.awt.event.ItemEvent
import java.awt.event.KeyEvent
import java.util.Collections.synchronizedMap
import java.util.regex.Pattern
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
import javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
internal const val GIT_REF_PROTOTYPE_VALUE = "origin/long-enough-branch-name"
internal fun createRepositoryField(repositories: List<GitRepository>,
defaultRoot: VirtualFile? = null) = ComboBox(CollectionComboBoxModel(repositories)).apply {
item = repositories.find { repo -> repo.root == defaultRoot } ?: repositories.first()
renderer = SimpleListCellRenderer.create("") { DvcsUtil.getShortRepositoryName(it) }
setUI(FlatComboBoxUI(outerInsets = Insets(BW.get(), BW.get(), BW.get(), 0)))
}
internal fun createSouthPanelWithOptionsDropDown(southPanel: JComponent, optionDropDown: DropDownLink<*>) = southPanel.apply {
(southPanel.components[0] as JPanel).apply {
(layout as BorderLayout).hgap = JBUI.scale(5)
add(optionDropDown, BorderLayout.EAST)
}
}
internal fun validateBranchExists(branchField: ComboBoxWithAutoCompletion<String>,
emptyFieldMessage: @NlsContexts.DialogMessage String): ValidationInfo? {
val value = branchField.getText()
if (value.isNullOrEmpty()) {
return ValidationInfo(emptyFieldMessage, branchField)
}
val items = (branchField.model as CollectionComboBoxModel).items
if (items.none { equalBranches(it, value) }) {
return ValidationInfo(GitBundle.message("merge.no.matching.branch.error"), branchField)
}
return null
}
class GitMergeDialog(private val project: Project,
private val defaultRoot: VirtualFile,
private val roots: List<VirtualFile>) : DialogWrapper(project) {
val selectedOptions = mutableSetOf<GitMergeOption>()
private val mergeSettings = project.service<GitMergeSettings>()
private val repositories = DvcsUtil.sortRepositories(GitRepositoryManager.getInstance(project).repositories)
private val allBranches = collectAllBranches()
private val unmergedBranches = synchronizedMap(HashMap<GitRepository, Set<GitBranch>?>())
private val optionInfos = mutableMapOf<GitMergeOption, OptionInfo<GitMergeOption>>()
private val popupBuilder = createPopupBuilder()
private val repositoryField = createRepoField()
private val branchField = createBranchField()
private val commandPanel = createCommandPanel()
private val optionsPanel = GitOptionsPanel(::optionChosen, ::getOptionInfo)
private val commitMsgField = JBTextArea("")
private val commitMsgPanel = createCommitMsgPanel()
private val panel = createPanel()
private val isNoVerifySupported = NO_VERIFY_SUPPORTED.existsIn(GitExecutableManager.getInstance().getVersion(project))
init {
loadUnmergedBranchesInBackground()
updateDialogTitle()
setOKButtonText(GitBundle.message("merge.action.name"))
loadSettings()
updateBranchesField()
// We call pack() manually.
isAutoAdjustable = false
init()
window.minimumSize = JBDimension(200, 60)
updateUi()
validate()
pack()
}
override fun createCenterPanel() = panel
override fun getPreferredFocusedComponent() = branchField
override fun doValidateAll(): List<ValidationInfo> = listOf(::validateBranchField).mapNotNull { it() }
override fun createSouthPanel() = createSouthPanelWithOptionsDropDown(super.createSouthPanel(), createOptionsDropDown())
override fun getHelpId() = "reference.VersionControl.Git.MergeBranches"
override fun doOKAction() {
try {
saveSettings()
}
finally {
super.doOKAction()
}
}
@NlsSafe
fun getCommitMessage(): String = commitMsgField.text
fun getSelectedRoot(): VirtualFile = repositoryField.item.root
fun getSelectedBranch(): GitBranch = tryGetSelectedBranch() ?: error("Unable to find branch: ${branchField.getText().orEmpty()}")
private fun tryGetSelectedBranch() = getSelectedRepository().branches.findBranchByName(branchField.getText().orEmpty())
fun shouldCommitAfterMerge() = !isOptionSelected(GitMergeOption.NO_COMMIT)
private fun saveSettings() {
mergeSettings.branch = branchField.getText()
mergeSettings.options = selectedOptions
}
private fun loadSettings() {
branchField.item = mergeSettings.branch
mergeSettings.options
.filter { option -> option != GitMergeOption.NO_VERIFY || isNoVerifySupported }
.forEach { option -> selectedOptions += option }
}
private fun collectAllBranches() = repositories.associateWith { repo ->
repo.branches
.let { it.localBranches + it.remoteBranches }
.map { it.name }
}
private fun loadUnmergedBranchesInBackground() {
ProgressManager.getInstance().run(
object : Task.Backgroundable(project, GitBundle.message("merge.branch.loading.branches.progress"), true) {
override fun run(indicator: ProgressIndicator) {
val sortedRoots = LinkedHashSet<VirtualFile>(roots.size).apply {
add(defaultRoot)
addAll(roots)
}
sortedRoots.forEach { root ->
val repository = getRepository(root)
loadUnmergedBranchesForRoot(repository)?.let { branches ->
unmergedBranches[repository] = branches
}
}
}
})
}
/**
* ```
* $ git branch --all --format=...
* |refs/heads/master []
* |refs/heads/feature []
* |refs/heads/checked-out []
* |refs/heads/checked-out-by-worktree []
* |refs/remotes/origin/master []
* |refs/remotes/origin/feature []
* |refs/remotes/origin/HEAD [refs/remotes/origin/master]
* ```
*/
@RequiresBackgroundThread
private fun loadUnmergedBranchesForRoot(repository: GitRepository): Set<GitBranch>? {
val root = repository.root
try {
val handler = GitLineHandler(project, root, GitCommand.BRANCH)
handler.addParameters(UNMERGED_BRANCHES_FORMAT, "--no-color", "--all", "--no-merged")
val result = Git.getInstance().runCommand(handler)
result.throwOnError()
val remotes = repository.remotes
return result.output.asSequence()
.mapNotNull { line ->
val matcher = BRANCH_NAME_REGEX.matcher(line)
when {
matcher.matches() -> matcher.group(1)
else -> null
}
}
.mapNotNull { refName -> GitRepositoryReader.parseBranchRef(remotes, refName) }
.toSet()
}
catch (e: Exception) {
LOG.warn("Failed to load unmerged branches for root: ${root}", e)
return null
}
}
private fun validateBranchField(): ValidationInfo? {
val validationInfo = validateBranchExists(branchField, GitBundle.message("merge.no.branch.selected.error"))
if (validationInfo != null) return validationInfo
val selectedBranch = tryGetSelectedBranch() ?: return ValidationInfo(GitBundle.message("merge.no.matching.branch.error"))
val selectedRepository = getSelectedRepository()
val unmergedBranches = unmergedBranches[selectedRepository] ?: return null
val selectedBranchMerged = !unmergedBranches.contains(selectedBranch)
if (selectedBranchMerged) {
return ValidationInfo(GitBundle.message("merge.branch.already.merged", selectedBranch), branchField)
}
return null
}
private fun updateBranchesField() {
var branchToSelect = branchField.item
val branches = splitAndSortBranches(getBranches())
val model = branchField.model as MutableCollectionComboBoxModel
model.update(branches)
if (branchToSelect == null || branchToSelect !in branches) {
val repository = getSelectedRepository()
val currentRemoteBranch = repository.currentBranch?.findTrackedBranch(repository)?.nameForRemoteOperations
branchToSelect = branches.find { branch -> branch == currentRemoteBranch } ?: branches.getOrElse(0) { "" }
}
branchField.item = branchToSelect
branchField.selectAll()
}
private fun splitAndSortBranches(branches: List<@NlsSafe String>): List<@NlsSafe String> {
val local = mutableListOf<String>()
val remote = mutableListOf<String>()
for (branch in branches) {
if (branch.startsWith(REMOTE_REF)) {
remote += branch.substring(REMOTE_REF.length)
}
else {
local += branch
}
}
return GitBranchUtil.sortBranchNames(local) + GitBranchUtil.sortBranchNames(remote)
}
private fun getBranches(): List<@NlsSafe String> {
val repository = getSelectedRepository()
return allBranches[repository] ?: emptyList()
}
private fun getRepository(root: VirtualFile) = repositories.find { repo -> repo.root == root }
?: error("Unable to find repository for root: ${root.presentableUrl}")
private fun getSelectedRepository() = getRepository(getSelectedRoot())
private fun updateDialogTitle() {
val currentBranchName = getSelectedRepository().currentBranchName
title = (if (currentBranchName.isNullOrEmpty())
GitBundle.message("merge.branch.title")
else
GitBundle.message("merge.branch.into.current.title", currentBranchName))
}
private fun createPanel() = JPanel().apply {
layout = MigLayout(LC().insets("0").hideMode(3), AC().grow())
add(commandPanel, CC().growX())
add(optionsPanel, CC().newline().width("100%").alignY("top"))
add(commitMsgPanel, CC().newline().push().grow())
}
private fun showRootField() = roots.size > 1
private fun createCommandPanel() = JPanel().apply {
val colConstraints = if (showRootField())
AC().grow(100f, 0, 2)
else
AC().grow(100f, 1)
layout = MigLayout(
LC()
.fillX()
.insets("0")
.gridGap("0", "0")
.noVisualPadding(),
colConstraints)
if (showRootField()) {
add(repositoryField,
CC()
.gapAfter("0")
.minWidth("${JBUI.scale(135)}px")
.growX())
}
add(createCmdLabel(),
CC()
.gapAfter("0")
.alignY("top")
.minWidth("${JBUI.scale(100)}px"))
add(branchField,
CC()
.alignY("top")
.minWidth("${JBUI.scale(300)}px")
.growX())
}
private fun createRepoField() = createRepositoryField(repositories, defaultRoot).apply {
addItemListener { e ->
if (e.stateChange == ItemEvent.SELECTED && e.item != null) {
updateDialogTitle()
updateBranchesField()
}
}
}
private fun createCmdLabel() = CmdLabel("git merge",
Insets(1, if (showRootField()) 0 else 1, 1, 0),
JBDimension(JBUI.scale(100), branchField.preferredSize.height, true))
private fun createBranchField() = ComboBoxWithAutoCompletion(MutableCollectionComboBoxModel(mutableListOf<String>()),
project).apply {
prototypeDisplayValue = GIT_REF_PROTOTYPE_VALUE
setPlaceholder(GitBundle.message("merge.branch.field.placeholder"))
setUI(FlatComboBoxUI(
outerInsets = Insets(BW.get(), 0, BW.get(), BW.get()),
popupEmptyText = GitBundle.message("merge.branch.popup.empty.text")))
}
private fun createCommitMsgPanel() = JPanel().apply {
layout = MigLayout(LC().insets("0").fill())
isVisible = false
add(JLabel(GitBundle.message("merge.commit.message.label")), CC().alignY("top").wrap())
add(createScrollPane(commitMsgField,
VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED),
CC()
.alignY("top")
.grow()
.push()
.minHeight("${JBUI.scale(75)}px"))
}
private fun createPopupBuilder() = GitOptionsPopupBuilder(
project,
GitBundle.message("merge.options.modify.popup.title"),
::getOptions, ::getOptionInfo, ::isOptionSelected, ::isOptionEnabled, ::optionChosen
)
private fun createOptionsDropDown() = DropDownLink(GitBundle.message("merge.options.modify")) {
popupBuilder.createPopup()
}.apply {
mnemonic = KeyEvent.VK_M
}
private fun isOptionSelected(option: GitMergeOption) = option in selectedOptions
private fun getOptionInfo(option: GitMergeOption) = optionInfos.computeIfAbsent(option) {
OptionInfo(option, option.option, option.description)
}
private fun getOptions(): List<GitMergeOption> = GitMergeOption.values().toMutableList().apply {
if (!isNoVerifySupported) {
remove(GitMergeOption.NO_VERIFY)
}
}
private fun isOptionEnabled(option: GitMergeOption) = selectedOptions.all { it.isOptionSuitable(option) }
private fun optionChosen(option: GitMergeOption) {
if (!isOptionSelected(option)) {
selectedOptions += option
}
else {
selectedOptions -= option
}
updateUi()
validate()
pack()
}
private fun updateUi() {
optionsPanel.rerender(selectedOptions)
updateCommitMessagePanel()
panel.invalidate()
}
private fun updateCommitMessagePanel() {
val useCommitMsg = isOptionSelected(GitMergeOption.COMMIT_MESSAGE)
commitMsgPanel.isVisible = useCommitMsg
if (!useCommitMsg) {
commitMsgField.text = ""
}
}
companion object {
private val LOG = logger<GitMergeDialog>()
/**
* Filter out 'symrefs' (ex: 'remotes/origin/HEAD -> origin/master')
*/
@Suppress("SpellCheckingInspection")
private val UNMERGED_BRANCHES_FORMAT = "--format=%(refname) [%(symref)]"
private val BRANCH_NAME_REGEX = Pattern.compile("(\\S+) \\[]")
@NlsSafe
private const val REMOTE_REF = "remotes/"
}
} | apache-2.0 | c4d57a7e5bb629ef3d99c7cb949bf4f2 | 33.21692 | 131 | 0.702022 | 4.697141 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinAwareJavaGetterRenameProcessor.kt | 1 | 2792 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.refactoring.rename
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiReference
import com.intellij.psi.search.SearchScope
import com.intellij.refactoring.rename.RenameJavaMethodProcessor
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.idea.references.SyntheticPropertyAccessorReference
import org.jetbrains.kotlin.idea.references.SyntheticPropertyAccessorReferenceDescriptorImpl
import org.jetbrains.kotlin.idea.search.canHaveSyntheticGetter
import org.jetbrains.kotlin.idea.search.canHaveSyntheticSetter
import org.jetbrains.kotlin.idea.search.restrictToKotlinSources
import org.jetbrains.kotlin.idea.search.syntheticGetter
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.utils.addToStdlib.cast
import org.jetbrains.kotlin.utils.addToStdlib.filterIsInstanceWithChecker
class KotlinAwareJavaGetterRenameProcessor : RenameJavaMethodProcessor() {
override fun canProcessElement(element: PsiElement) =
super.canProcessElement(element) && element !is KtLightMethod && element.cast<PsiMethod>().canHaveSyntheticGetter
override fun findReferences(
element: PsiElement,
searchScope: SearchScope,
searchInCommentsAndStrings: Boolean
): Collection<PsiReference> {
val getters = super.findReferences(element, searchScope, searchInCommentsAndStrings)
val setters = findSetterReferences(element, searchScope, searchInCommentsAndStrings).orEmpty()
return getters + setters
}
private fun findSetterReferences(
element: PsiElement,
searchScope: SearchScope,
searchInCommentsAndStrings: Boolean
): Collection<PsiReference>? {
val getter = element as? PsiMethod ?: return null
val propertyName = getter.syntheticGetter ?: return null
val containingClass = getter.containingClass ?: return null
val setterName = JvmAbi.setterName(propertyName.asString())
val restrictedToKotlinScope by lazy { searchScope.restrictToKotlinSources() }
return containingClass
.findMethodsByName(setterName, false)
.filter { it.canHaveSyntheticSetter }
.asSequence()
.flatMap {
super.findReferences(it, restrictedToKotlinScope, searchInCommentsAndStrings)
.filterIsInstanceWithChecker<SyntheticPropertyAccessorReference> { accessor -> !accessor.getter }
}
.map {
SyntheticPropertyAccessorReferenceDescriptorImpl(it.expression, getter = true)
}
.toList()
}
}
| apache-2.0 | 5efb1d559484517878bb01fc06388de9 | 47.137931 | 121 | 0.752865 | 5.463796 | false | false | false | false |
vovagrechka/fucking-everything | attic/alraune/alraune-back/src/alraune-back.kt | 1 | 6670 | package alraune.back
//import alraune.back.AlRenderPile_killme.rawHTML
import alraune.shared.AlSharedPile_killme
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.ser.std.StdSerializer
import vgrechka.*
import java.sql.Connection
import javax.servlet.http.HttpServletResponse
import kotlin.reflect.KProperty1
//class AlkRequestContext {
//
//// /**
//// * @return null
//// * - if no session cookie
//// * - if no session with corresponding UUID in DB
//// * - TODO:vgrechka session expiration (results in deletion, so above applies?)
//// *
//// * @bailout if user is banned
//// */
//// val maybeUserWithParams: AlUserWithParams? get() {
//// val clazz = Class.forName("alraune.back.AlRequestContext")
//// val alRequestContext = clazz.getDeclaredMethod("get").invoke(null)
//// val lazyInstance = clazz.getDeclaredField("maybeUserWithParams").get(alRequestContext)
//// return lazyInstance.javaClass.getDeclaredMethod("get").invoke(lazyInstance) as AlUserWithParams?
//// }
////
////
//// val user get() = maybeUserWithParams!!
//
//// var connection by notNullOnce<Connection>()
////
//// fun <T> useConnection(block: () -> T): T {
//// connection = AlGlobalContext.dataSource.connection
//// connection.use {
//// return block()
//// }
//// }
//
//}
//fun insideMarkers(id: AlDomid, content: Renderable? = null, tamperWithAttrs: (Attrs) -> Attrs = {it}): Tag {
// val beginMarker = AlSharedPile_killme.beginContentMarkerForDOMID(id)
// val endMarker = AlSharedPile_killme.endContentMarkerForDOMID(id)
// return kdiv{o->
// o- rawHTML(beginMarker)
// o- kdiv(tamperWithAttrs(Attrs(domid = id))){o->
// o- content
// }
// o- rawHTML(endMarker)
// }
//}
interface FuckingField {
val value: String
fun validate()
fun render(): Renderable
fun noValidation()
}
class FieldContext {
val fields = mutableListOf<FuckingField>()
var hasErrors = false
fun validate() {
for (field in fields)
field.validate()
}
fun noValidation() {
for (field in fields)
field.noValidation()
}
}
//fun declareField(ctx: FieldContext,
// prop: KProperty0<String>,
// title: String,
// validator: (String?) -> ValidationResult,
// fieldType: FieldType = FieldType.TEXT): FuckingField {
// val field = object : FuckingField {
// private var vr by notNullOnce<ValidationResult>()
//
// override val value get() = vr.sanitizedString
//
// override fun noValidation() {
// vr = ValidationResult(sanitizedString = prop.get(), error = null)
// }
//
//// override fun validate() {
//// fun noise(x: String) = AlRequestContext.the.log.debug(x)
//// noise(::declareField.name + ": prop = ${prop.name}")
////
//// vr = validator(prop.get())
//// noise(" vr = $vr")
//// val theError = when {
//// AlRequestContext.the.isPost -> vr.error
//// else -> null
//// }
//// if (theError != null)
//// ctx.hasErrors = true
//// }
//
// override fun render(): Renderable {
// val theError = vr.error
// val id = AlSharedPile.fieldDOMID(name = prop.name)
// return kdiv.className("form-group"){o->
// if (theError != null)
// o.amend(Style(marginBottom = "0"))
// o - klabel(text = title)
// val control = when (fieldType) {
// FieldType.TEXT -> kinput(Attrs(type = "text", id = id, value = vr.sanitizedString, className = "form-control")) {}
// FieldType.TEXTAREA -> ktextarea(Attrs(id = id, rows = 5, className = "form-control"), text = vr.sanitizedString)
// }
// o - kdiv(Style(position = "relative")){o->
// o - control
// if (theError != null) {
// o - kdiv(Style(marginTop = "5px", marginRight = "9px", textAlign = "right", color = "${Color.RED_700}"))
// .text(theError)
// // TODO:vgrechka Shift red circle if control has scrollbar
// o - kdiv(Style(width = "15px", height = "15px", backgroundColor = "${Color.RED_300}",
// borderRadius = "10px", position = "absolute", top = "10px", right = "8px"))
// }
// }
// }
// }
// }
// ctx.fields += field
// return field
//}
interface WithFieldContext {
val fieldCtx: FieldContext
}
//class OrderParamsFields(val data: OrderParamsFormPostData) : WithFieldContext {
// val f = AlFields.order
// val v = AlBackPile
// override val fieldCtx = FieldContext()
//
// val email = declareField(fieldCtx, data::email, f.email.title, v::validateEmail)
// val contactName = declareField(fieldCtx, data::name, f.contactName.title, v::validateName)
// val phone = declareField(fieldCtx, data::phone, f.phone.title, v::validatePhone)
// val documentTitle = declareField(fieldCtx, data::documentTitle, f.documentTitle.title, v::validateDocumentTitle)
// val documentDetails = declareField(fieldCtx, data::documentDetails, f.documentDetails.title, v::validateDocumentDetails, FieldType.TEXTAREA)
// val numPages = declareField(fieldCtx, data::numPages, f.numPages.title, v::validateNumPages)
// val numSources = declareField(fieldCtx, data::numSources, f.numSources.title, v::validateNumSources)
//}
//val rctx get() = AlkRequestContext.the
object AlBackDebug {
// val idToRequestContext = ConcurrentHashMap<String, AlkRequestContext>()
@Volatile var _nextCycling2 = 0
@Volatile var _nextCycling3 = 0
fun nextCycling2(): Int {
val res = _nextCycling2++
if (_nextCycling2 > 1)
_nextCycling2 = 0
return res
}
fun nextCycling3(): Int {
val res = _nextCycling3++
if (_nextCycling3 > 2)
_nextCycling3 = 0
return res
}
}
class PropertyNameSerializer : StdSerializer<KProperty1<*, *>>(KProperty1::class.java, true) {
override fun serialize(value: KProperty1<*, *>, gen: JsonGenerator, provider: SerializerProvider) {
gen.writeString(value.name)
}
}
| apache-2.0 | 0a942d4ea03fbb502e349d75d8dd9601 | 31.222222 | 146 | 0.587406 | 4.022919 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/frame/frameExtFunExtFun.kt | 13 | 1095 | package frameExtFunExtFun
fun main(args: Array<String>) {
Outer().run()
}
class A {
val aProp = 1
fun aMyFun() = 1
}
class Outer {
val outerProp = 1
fun outerMyFun() = 1
fun A.foo() {
val valFoo = 1
class LocalClass {
val lcProp = 1
fun B.test() {
val valTest = 1
lambda {
//Breakpoint!
outerProp + aProp + lcProp + bProp + valFoo + valTest
}
}
fun run() {
B().test()
}
}
LocalClass().run()
}
fun run() {
A().foo()
}
}
class B {
val bProp = 1
fun bMyFun() = 1
}
fun lambda(f: () -> Unit) {
f()
}
// PRINT_FRAME
// EXPRESSION: valFoo
// RESULT: 1: I
// EXPRESSION: valTest
// RESULT: 1: I
// EXPRESSION: aProp
// RESULT: 1: I
// EXPRESSION: outerProp
// RESULT: 1: I
// EXPRESSION: bProp
// RESULT: 1: I
// EXPRESSION: aMyFun()
// RESULT: 1: I
// EXPRESSION: outerMyFun()
// RESULT: 1: I
// EXPRESSION: bMyFun()
// RESULT: 1: I | apache-2.0 | f44e7d582c32f71493ac0e7b62e3b68e | 14.013699 | 73 | 0.468493 | 3.432602 | false | true | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/refactoring/rename/impl/search.kt | 12 | 3261 | // 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.refactoring.rename.impl
import com.intellij.model.Pointer
import com.intellij.model.search.SearchRequest
import com.intellij.model.search.SearchService
import com.intellij.model.search.impl.buildTextUsageQuery
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.psi.search.SearchScope
import com.intellij.refactoring.rename.api.*
import com.intellij.util.Query
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
fun buildQuery(project: Project, target: RenameTarget, options: RenameOptions): Query<UsagePointer> {
return buildUsageQuery(project, target, options).mapping {
ApplicationManager.getApplication().assertReadAccessAllowed()
it.createPointer()
}
}
internal fun buildUsageQuery(project: Project, target: RenameTarget, options: RenameOptions): Query<out RenameUsage> {
ApplicationManager.getApplication().assertReadAccessAllowed()
val queries = ArrayList<Query<out RenameUsage>>()
queries += searchRenameUsages(project, target, options.searchScope)
if (options.textOptions.commentStringOccurrences == true) {
queries += buildTextResultsQueries(project, target, options.searchScope, ReplaceTextTargetContext.IN_COMMENTS_AND_STRINGS)
}
if (options.textOptions.textOccurrences == true) {
queries += buildTextResultsQueries(project, target, options.searchScope, ReplaceTextTargetContext.IN_PLAIN_TEXT)
}
return SearchService.getInstance().merge(queries)
}
private fun searchRenameUsages(project: Project, target: RenameTarget, searchScope: SearchScope): Query<out RenameUsage> {
return SearchService.getInstance().searchParameters(
DefaultRenameUsageSearchParameters(project, target, searchScope)
)
}
private class DefaultRenameUsageSearchParameters(
private val project: Project,
target: RenameTarget,
override val searchScope: SearchScope
) : RenameUsageSearchParameters {
private val pointer: Pointer<out RenameTarget> = target.createPointer()
override fun areValid(): Boolean = pointer.dereference() != null
override fun getProject(): Project = project
override val target: RenameTarget get() = requireNotNull(pointer.dereference())
}
private fun buildTextResultsQueries(project: Project,
target: RenameTarget,
searchScope: SearchScope,
context: ReplaceTextTargetContext): List<Query<out RenameUsage>> {
val replaceTextTargets: Collection<ReplaceTextTarget> = target.textTargets(context)
val result = ArrayList<Query<out RenameUsage>>(replaceTextTargets.size)
for ((searchRequest: SearchRequest, usageTextByName: UsageTextByName) in replaceTextTargets) {
val effectiveSearchScope: SearchScope = searchRequest.searchScope?.let(searchScope::intersectWith) ?: searchScope
val fileUpdater = fileRangeUpdater(usageTextByName)
result += buildTextUsageQuery(project, searchRequest, effectiveSearchScope, context.searchContexts)
.mapping {
TextRenameUsage(it, fileUpdater, context)
}
}
return result
}
| apache-2.0 | b46d972265af8bb6fc2cafe138343123 | 46.955882 | 140 | 0.773076 | 4.881737 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/SimplifyComparisonFix.kt | 3 | 2442 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticWithParameters2
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.inspections.ConstantConditionIfInspection
import org.jetbrains.kotlin.idea.intentions.SimplifyBooleanWithConstantsIntention
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
class SimplifyComparisonFix(element: KtExpression, val value: Boolean) : KotlinQuickFixAction<KtExpression>(element) {
override fun getFamilyName() = KotlinBundle.message("simplify.0.to.1", element.toString(), value)
override fun getText() = KotlinBundle.message("simplify.comparison")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val replacement = KtPsiFactory(element).createExpression("$value")
val result = element.replaced(replacement)
val booleanExpression = result.getNonStrictParentOfType<KtBinaryExpression>()
val simplifyIntention = SimplifyBooleanWithConstantsIntention()
if (booleanExpression != null && simplifyIntention.isApplicableTo(booleanExpression)) {
simplifyIntention.applyTo(booleanExpression, editor)
} else {
simplifyIntention.removeRedundantAssertion(result)
}
val ifExpression = result.getStrictParentOfType<KtIfExpression>()?.takeIf { it.condition == result }
if (ifExpression != null) ConstantConditionIfInspection.applyFixIfSingle(ifExpression)
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val expression = diagnostic.psiElement as? KtExpression ?: return null
val value = (diagnostic as? DiagnosticWithParameters2<*, *, *>)?.b as? Boolean ?: return null
return SimplifyComparisonFix(expression, value)
}
}
} | apache-2.0 | c24f7a2c90f94591fc4cc9a29b02168d | 50.978723 | 158 | 0.764537 | 5.119497 | false | false | false | false |
smmribeiro/intellij-community | plugins/stats-collector/src/com/intellij/stats/completion/logger/LogFileManager.kt | 12 | 1885 | /*
* Copyright 2000-2020 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.stats.completion.logger
import com.intellij.stats.completion.network.assertNotEDT
import com.intellij.stats.completion.storage.FilePathProvider
import java.io.File
class LogFileManager(private val filePathProvider: FilePathProvider, private val chunkSizeLimit: Int = MAX_CHUNK_SIZE) : FileLogger {
private companion object {
const val MAX_CHUNK_SIZE = 30 * 1024
}
private var storage = LineStorage()
override fun printLines(lines: List<String>) {
synchronized(this) {
for (line in lines) {
storage.appendLine(line)
}
if (storage.size > chunkSizeLimit) {
flushImpl()
}
}
}
override fun flush() {
synchronized(this) {
if (storage.size > 0) {
flushImpl()
}
}
}
private fun flushImpl() {
saveDataChunk(storage)
filePathProvider.cleanupOldFiles()
storage = LineStorage()
}
private fun saveDataChunk(storage: LineStorage) {
assertNotEDT()
val dir = filePathProvider.getStatsDataDirectory()
val tmp = File(dir, "tmp_data.gz")
storage.dump(tmp)
tmp.renameTo(filePathProvider.getUniqueFile())
}
} | apache-2.0 | cd34a000c46b45c8eabf81af7283e0a6 | 29.419355 | 133 | 0.65252 | 4.456265 | false | false | false | false |
smmribeiro/intellij-community | plugins/completion-ml-ranking/src/com/intellij/completion/ml/personalization/session/PeriodTracker.kt | 9 | 1354 | // 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.completion.ml.personalization.session
import kotlin.math.max
import kotlin.math.min
class PeriodTracker {
private val durations: MutableList<Long> = mutableListOf()
fun minDuration(currentPeriod: Long?): Long? {
val pastMin = durations.minOrNull()
if (pastMin == null) return currentPeriod
if (currentPeriod != null) {
return min(pastMin, currentPeriod)
}
return pastMin
}
fun maxDuration(currentPeriod: Long?): Long? {
val pastMax = durations.maxOrNull()
if (pastMax == null) return currentPeriod
if (currentPeriod != null) {
return max(pastMax, currentPeriod)
}
return pastMax
}
fun average(currentPeriod: Long?): Double {
if (durations.isEmpty()) return currentPeriod?.toDouble() ?: 0.0
val pastAvg = durations.average()
if (currentPeriod == null) return pastAvg
val n = durations.size
return pastAvg * n / (n + 1) + currentPeriod / (n + 1)
}
fun count(currentPeriod: Long?): Int = durations.size + (if (currentPeriod != null) 1 else 0)
fun totalTime(currentPeriod: Long?): Long = durations.sum() + (currentPeriod ?: 0)
fun addDuration(duration: Long) {
durations.add(duration)
}
} | apache-2.0 | 8e2ff4052156b375420addd811cfddbd | 29.111111 | 140 | 0.688331 | 4.090634 | false | false | false | false |
deviant-studio/energy-meter-scanner | app/src/main/java/ds/meterscanner/mvvm/SimpleAdapter.kt | 1 | 2106 | package ds.meterscanner.mvvm
import android.content.Context
import android.support.v7.util.DiffUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import ds.meterscanner.adapter.DiffCallback
import java.lang.reflect.ParameterizedType
abstract class SimpleAdapter<H : RecyclerView.ViewHolder, D : Any>(
data: List<D> = emptyList()
) : RecyclerView.Adapter<H>() {
lateinit protected var context: Context
var data: List<D> = data
set(value) {
val diffResult = DiffUtil.calculateDiff(DiffCallback(field, value))
field = value
diffResult.dispatchUpdatesTo(this)
}
override fun getItemCount(): Int = data.size
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
context = recyclerView.context
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): H {
val inflater = LayoutInflater.from(parent.context)
val view = inflater.inflate(layoutId, parent, false)
return instantiateHolder(view)
}
override fun onBindViewHolder(holder: H, position: Int) {
val item = getItem(position)
onFillView(holder, item, position)
}
fun getItem(position: Int): D = data[position]
override fun getItemId(position: Int): Long = position.toLong()
protected abstract val layoutId: Int
protected abstract fun onFillView(holder: H, item: D, position: Int): Any
open protected fun instantiateHolder(view: View): H = getHolderType().getConstructor(View::class.java).newInstance(view)
@Suppress("UNCHECKED_CAST")
private fun getHolderType(): Class<H> = getParametrizedType(javaClass).actualTypeArguments[0] as Class<H>
private fun getParametrizedType(clazz: Class<*>): ParameterizedType =
if (clazz.superclass == SimpleAdapter::class.java) { // check that we are at the top of the hierarchy
clazz.genericSuperclass as ParameterizedType
} else {
getParametrizedType(clazz.superclass)
}
}
| mit | ff5db4a78b2d1f98f3a56fddabc7813d | 33.52459 | 124 | 0.707502 | 4.608315 | false | false | false | false |
cmcpasserby/MayaCharm | src/main/kotlin/debugattach/MayaAttachDebuggerProvider.kt | 1 | 3589 | package debugattach
import settings.ApplicationSettings
import utils.pathForPid
import com.intellij.execution.process.ProcessInfo
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UserDataHolder
import com.intellij.xdebugger.attach.*
import com.jetbrains.python.sdk.PythonSdkType
import com.jetbrains.python.sdk.PythonSdkUtil
import javax.swing.Icon
private val mayaPathsKey = Key<MutableMap<Int, String>>("mayaPathsMap")
class MayaAttachDebuggerProvider : XAttachDebuggerProvider {
override fun getPresentationGroup(): XAttachPresentationGroup<ProcessInfo> {
return MayaAttachGroup.INSTANCE
}
override fun getAvailableDebuggers(project: Project, attachHost: XAttachHost, processInfo: ProcessInfo, userData: UserDataHolder): MutableList<XAttachDebugger> {
if (!processInfo.executableName.toLowerCase().contains("maya")) return mutableListOf()
val exePath = processInfo.executableCannonicalPath.let {
if (it.isPresent) it.get() else pathForPid(processInfo.pid) ?: return mutableListOf()
}.toLowerCase()
val currentSdk = ApplicationSettings.INSTANCE.mayaSdkMapping.values.firstOrNull {
exePath.contains(it.mayaPath.toLowerCase())
} ?: return mutableListOf()
val mayaPathMap = userData.getUserData(mayaPathsKey) ?: mutableMapOf()
mayaPathMap[processInfo.pid] = currentSdk.mayaPath
userData.putUserData(mayaPathsKey, mayaPathMap)
PythonSdkUtil.findSdkByPath(currentSdk.mayaPyPath)?.let {
return mutableListOf(MayaAttachDebugger(it, currentSdk))
}
return mutableListOf()
}
override fun isAttachHostApplicable(attachHost: XAttachHost): Boolean = attachHost is LocalAttachHost
}
private class MayaAttachDebugger(sdk: Sdk, private val mayaSdk: ApplicationSettings.SdkInfo) : XAttachDebugger {
private val mySdkHome: String? = sdk.homePath
private val myName: String = "${PythonSdkType.getInstance().getVersionString(sdk)} ($mySdkHome)"
override fun getDebuggerDisplayName(): String {
return myName
}
override fun attachDebugSession(project: Project, attachHost: XAttachHost, processInfo: ProcessInfo) {
val runner = MayaAttachToProcessDebugRunner(project, processInfo.pid, mySdkHome, mayaSdk)
runner.launch()
}
}
private class MayaAttachGroup : XAttachProcessPresentationGroup {
companion object {
val INSTANCE = MayaAttachGroup()
}
override fun getItemDisplayText(project: Project, processInfo: ProcessInfo, userData: UserDataHolder): String {
val mayaPaths = userData.getUserData(mayaPathsKey) ?: return processInfo.executableDisplayName
return mayaPaths[processInfo.pid] ?: processInfo.executableDisplayName
}
override fun getProcessDisplayText(project: Project, info: ProcessInfo, userData: UserDataHolder): String {
return getItemDisplayText(project, info, userData)
}
override fun getItemIcon(project: Project, processInfo: ProcessInfo, userData: UserDataHolder): Icon {
return IconLoader.getIcon("/icons/MayaCharm_ToolWindow.png", this::class.java)
}
override fun getProcessIcon(project: Project, info: ProcessInfo, userData: UserDataHolder): Icon {
return getItemIcon(project, info, userData)
}
override fun getGroupName(): String {
return "Maya"
}
override fun getOrder(): Int {
return -100
}
}
| mit | 28664f8225065e623dc004bc703353a8 | 38.43956 | 165 | 0.744497 | 4.950345 | false | false | false | false |
android/uamp | common/src/main/java/com/example/android/uamp/media/library/JsonSource.kt | 2 | 8741 | /*
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.uamp.media.library
import android.net.Uri
import android.support.v4.media.MediaBrowserCompat.MediaItem
import android.support.v4.media.MediaDescriptionCompat.STATUS_NOT_DOWNLOADED
import android.support.v4.media.MediaMetadataCompat
import com.example.android.uamp.media.extensions.album
import com.example.android.uamp.media.extensions.albumArtUri
import com.example.android.uamp.media.extensions.artist
import com.example.android.uamp.media.extensions.displayDescription
import com.example.android.uamp.media.extensions.displayIconUri
import com.example.android.uamp.media.extensions.displaySubtitle
import com.example.android.uamp.media.extensions.displayTitle
import com.example.android.uamp.media.extensions.downloadStatus
import com.example.android.uamp.media.extensions.duration
import com.example.android.uamp.media.extensions.flag
import com.example.android.uamp.media.extensions.genre
import com.example.android.uamp.media.extensions.id
import com.example.android.uamp.media.extensions.mediaUri
import com.example.android.uamp.media.extensions.title
import com.example.android.uamp.media.extensions.trackCount
import com.example.android.uamp.media.extensions.trackNumber
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.net.URL
import java.util.concurrent.TimeUnit
/**
* Source of [MediaMetadataCompat] objects created from a basic JSON stream.
*
* The definition of the JSON is specified in the docs of [JsonMusic] in this file,
* which is the object representation of it.
*/
internal class JsonSource(private val source: Uri) : AbstractMusicSource() {
companion object {
const val ORIGINAL_ARTWORK_URI_KEY = "com.example.android.uamp.JSON_ARTWORK_URI"
}
private var catalog: List<MediaMetadataCompat> = emptyList()
init {
state = STATE_INITIALIZING
}
override fun iterator(): Iterator<MediaMetadataCompat> = catalog.iterator()
override suspend fun load() {
updateCatalog(source)?.let { updatedCatalog ->
catalog = updatedCatalog
state = STATE_INITIALIZED
} ?: run {
catalog = emptyList()
state = STATE_ERROR
}
}
/**
* Function to connect to a remote URI and download/process the JSON file that corresponds to
* [MediaMetadataCompat] objects.
*/
private suspend fun updateCatalog(catalogUri: Uri): List<MediaMetadataCompat>? {
return withContext(Dispatchers.IO) {
val musicCat = try {
downloadJson(catalogUri)
} catch (ioException: IOException) {
return@withContext null
}
// Get the base URI to fix up relative references later.
val baseUri = catalogUri.toString().removeSuffix(catalogUri.lastPathSegment ?: "")
val mediaMetadataCompats = musicCat.music.map { song ->
// The JSON may have paths that are relative to the source of the JSON
// itself. We need to fix them up here to turn them into absolute paths.
catalogUri.scheme?.let { scheme ->
if (!song.source.startsWith(scheme)) {
song.source = baseUri + song.source
}
if (!song.image.startsWith(scheme)) {
song.image = baseUri + song.image
}
}
val jsonImageUri = Uri.parse(song.image)
val imageUri = AlbumArtContentProvider.mapUri(jsonImageUri)
MediaMetadataCompat.Builder()
.from(song)
.apply {
displayIconUri = imageUri.toString() // Used by ExoPlayer and Notification
albumArtUri = imageUri.toString()
// Keep the original artwork URI for being included in Cast metadata object.
putString(ORIGINAL_ARTWORK_URI_KEY, jsonImageUri.toString())
}
.build()
}.toList()
// Add description keys to be used by the ExoPlayer MediaSession extension when
// announcing metadata changes.
mediaMetadataCompats.forEach { it.description.extras?.putAll(it.bundle) }
mediaMetadataCompats
}
}
/**
* Attempts to download a catalog from a given Uri.
*
* @param catalogUri URI to attempt to download the catalog form.
* @return The catalog downloaded, or an empty catalog if an error occurred.
*/
@Throws(IOException::class)
private fun downloadJson(catalogUri: Uri): JsonCatalog {
val catalogConn = URL(catalogUri.toString())
val reader = BufferedReader(InputStreamReader(catalogConn.openStream()))
return Gson().fromJson(reader, JsonCatalog::class.java)
}
}
/**
* Extension method for [MediaMetadataCompat.Builder] to set the fields from
* our JSON constructed object (to make the code a bit easier to see).
*/
fun MediaMetadataCompat.Builder.from(jsonMusic: JsonMusic): MediaMetadataCompat.Builder {
// The duration from the JSON is given in seconds, but the rest of the code works in
// milliseconds. Here's where we convert to the proper units.
val durationMs = TimeUnit.SECONDS.toMillis(jsonMusic.duration)
id = jsonMusic.id
title = jsonMusic.title
artist = jsonMusic.artist
album = jsonMusic.album
duration = durationMs
genre = jsonMusic.genre
mediaUri = jsonMusic.source
albumArtUri = jsonMusic.image
trackNumber = jsonMusic.trackNumber
trackCount = jsonMusic.totalTrackCount
flag = MediaItem.FLAG_PLAYABLE
// To make things easier for *displaying* these, set the display properties as well.
displayTitle = jsonMusic.title
displaySubtitle = jsonMusic.artist
displayDescription = jsonMusic.album
displayIconUri = jsonMusic.image
// Add downloadStatus to force the creation of an "extras" bundle in the resulting
// MediaMetadataCompat object. This is needed to send accurate metadata to the
// media session during updates.
downloadStatus = STATUS_NOT_DOWNLOADED
// Allow it to be used in the typical builder style.
return this
}
/**
* Wrapper object for our JSON in order to be processed easily by GSON.
*/
class JsonCatalog {
var music: List<JsonMusic> = ArrayList()
}
/**
* An individual piece of music included in our JSON catalog.
* The format from the server is as specified:
* ```
* { "music" : [
* { "title" : // Title of the piece of music
* "album" : // Album title of the piece of music
* "artist" : // Artist of the piece of music
* "genre" : // Primary genre of the music
* "source" : // Path to the music, which may be relative
* "image" : // Path to the art for the music, which may be relative
* "trackNumber" : // Track number
* "totalTrackCount" : // Track count
* "duration" : // Duration of the music in seconds
* "site" : // Source of the music, if applicable
* }
* ]}
* ```
*
* `source` and `image` can be provided in either relative or
* absolute paths. For example:
* ``
* "source" : "https://www.example.com/music/ode_to_joy.mp3",
* "image" : "ode_to_joy.jpg"
* ``
*
* The `source` specifies the full URI to download the piece of music from, but
* `image` will be fetched relative to the path of the JSON file itself. This means
* that if the JSON was at "https://www.example.com/json/music.json" then the image would be found
* at "https://www.example.com/json/ode_to_joy.jpg".
*/
@Suppress("unused")
class JsonMusic {
var id: String = ""
var title: String = ""
var album: String = ""
var artist: String = ""
var genre: String = ""
var source: String = ""
var image: String = ""
var trackNumber: Long = 0
var totalTrackCount: Long = 0
var duration: Long = -1
var site: String = ""
}
| apache-2.0 | c23511e1f341ec78054110df598d2dcb | 37.676991 | 100 | 0.673836 | 4.443823 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/db/dao/BookDao.kt | 1 | 2595 | package com.orgzly.android.db.dao
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.orgzly.android.db.entity.Book
import com.orgzly.android.db.entity.BookAction
@Dao
abstract class BookDao : BaseDao<Book> {
@Query("SELECT * FROM books WHERE id = :id")
abstract fun get(id: Long): Book?
@Query("SELECT * FROM books WHERE name = :name")
abstract fun get(name: String): Book?
@Query("SELECT * FROM books WHERE id = :id")
abstract fun getLiveData(id: Long): LiveData<Book> // null not allowed, use List
@Query("SELECT * FROM books WHERE last_action_type = :type")
abstract fun getWithActionType(type: BookAction.Type): List<Book>
@Insert
abstract fun insertBooks(vararg books: Book): LongArray
@Update
abstract fun updateBooks(vararg book: Book): Int
@Query("UPDATE books SET preface = :preface, title = :title WHERE id = :id")
abstract fun updatePreface(id: Long, preface: String?, title: String?)
@Query("UPDATE books SET last_action_type = :type, last_action_message = :message, last_action_timestamp = :timestamp WHERE id = :id")
abstract fun updateLastAction(id: Long, type: BookAction.Type, message: String, timestamp: Long)
@Query("UPDATE books SET last_action_type = :type, last_action_message = :message, last_action_timestamp = :timestamp, sync_status = :status WHERE id = :id")
abstract fun updateLastActionAndSyncStatus(id: Long, type: BookAction.Type, message: String, timestamp: Long, status: String?): Int
@Query("UPDATE books SET last_action_type = :type, last_action_message = :message, last_action_timestamp = :timestamp, sync_status = :status WHERE last_action_type = :whereType")
abstract fun updateStatusToCanceled(whereType: BookAction.Type, type: BookAction.Type, message: String, timestamp: Long, status: String?): Int
@Query("UPDATE books SET name = :name WHERE id = :id")
abstract fun updateName(id: Long, name: String): Int
@Query("UPDATE books SET is_dummy = :dummy WHERE id = :id")
abstract fun updateDummy(id: Long, dummy: Boolean)
@Query("UPDATE books SET mtime = :mtime, is_modified = 1 WHERE id IN (:ids)")
abstract fun setIsModified(ids: Set<Long>, mtime: Long): Int
@Query("UPDATE books SET is_modified = 0 WHERE id IN (:ids)")
abstract fun setIsNotModified(ids: Set<Long>): Int
fun getOrInsert(name: String): Long =
get(name).let {
it?.id ?: insert(Book(0, name, isDummy = true))
}
}
| gpl-3.0 | 52dd8377596259f733a18103e52e60cb | 40.854839 | 182 | 0.69711 | 3.816176 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-block-logging-bukkit/src/main/kotlin/com/rpkit/blocklog/bukkit/listener/BlockFormListener.kt | 1 | 1175 | package com.rpkit.blocklog.bukkit.listener
import com.rpkit.blocklog.bukkit.RPKBlockLoggingBukkit
import com.rpkit.blocklog.bukkit.block.RPKBlockChangeImpl
import com.rpkit.blocklog.bukkit.block.RPKBlockHistoryProvider
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority.MONITOR
import org.bukkit.event.Listener
import org.bukkit.event.block.BlockFormEvent
class BlockFormListener(private val plugin: RPKBlockLoggingBukkit): Listener {
@EventHandler(priority = MONITOR)
fun onBlockForm(event: BlockFormEvent) {
val blockHistoryProvider = plugin.core.serviceManager.getServiceProvider(RPKBlockHistoryProvider::class)
val blockHistory = blockHistoryProvider.getBlockHistory(event.block)
val blockChange = RPKBlockChangeImpl(
blockHistory = blockHistory,
time = System.currentTimeMillis(),
profile = null,
minecraftProfile = null,
character = null,
from = event.block.type,
to = event.newState.type,
reason = "FORM"
)
blockHistoryProvider.addBlockChange(blockChange)
}
} | apache-2.0 | 676dc0470a1285320d9bbfc56012e4f1 | 36.935484 | 112 | 0.707234 | 4.815574 | false | false | false | false |
ibinti/intellij-community | java/java-analysis-api/src/com/intellij/codeInsight/intention/JvmCommonIntentionActionsFactory.kt | 2 | 6129 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.intention
import com.intellij.lang.Language
import com.intellij.lang.LanguageExtension
import com.intellij.openapi.components.ServiceManager
import com.intellij.psi.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.UClass
import org.jetbrains.uast.UDeclaration
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UastContext
/**
* Extension Point provides language-abstracted code modifications for JVM-based languages.
*
* Each method should return nullable code modification ([IntentionAction]) or list of code modifications which could be empty.
* If method returns `null` or empty list this means that operation on given elements is not supported or not yet implemented for a language.
*
* Every new added method should return `null` or empty list by default and then be overridden in implementations for each language if it is possible.
*
* @since 2017.2
*/
@ApiStatus.Experimental
abstract class JvmCommonIntentionActionsFactory {
open fun createChangeModifierAction(declaration: @JvmCommon PsiModifierListOwner,
@PsiModifier.ModifierConstant modifier: String,
shouldPresent: Boolean): IntentionAction? =
//Fallback if Uast-version of method is overridden
createChangeModifierAction(declaration.asUast<UDeclaration>(), modifier, shouldPresent)
open fun createAddCallableMemberActions(info: MethodInsertionInfo): List<IntentionAction> = emptyList()
open fun createAddBeanPropertyActions(psiClass: @JvmCommon PsiClass,
propertyName: String,
@PsiModifier.ModifierConstant visibilityModifier: String,
propertyType: PsiType,
setterRequired: Boolean,
getterRequired: Boolean): List<IntentionAction> =
//Fallback if Uast-version of method is overridden
createAddBeanPropertyActions(psiClass.asUast<UClass>(), propertyName, visibilityModifier, propertyType, setterRequired, getterRequired)
companion object : LanguageExtension<JvmCommonIntentionActionsFactory>(
"com.intellij.codeInsight.intention.jvmCommonIntentionActionsFactory") {
@JvmStatic
override fun forLanguage(l: Language): JvmCommonIntentionActionsFactory? = super.forLanguage(l)
}
//A fallback to old api
@Deprecated("use or/and override @JvmCommon-version of this method instead")
open fun createChangeModifierAction(declaration: UDeclaration,
@PsiModifier.ModifierConstant modifier: String,
shouldPresent: Boolean): IntentionAction? = null
@Deprecated("use or/and override @JvmCommon-version of this method instead")
open fun createAddBeanPropertyActions(uClass: UClass,
propertyName: String,
@PsiModifier.ModifierConstant visibilityModifier: String,
propertyType: PsiType,
setterRequired: Boolean,
getterRequired: Boolean): List<IntentionAction> = emptyList()
}
@ApiStatus.Experimental
sealed class MethodInsertionInfo(
val targetClass: @JvmCommon PsiClass,
@PsiModifier.ModifierConstant
val modifiers: List<String> = emptyList(),
val typeParams: List<PsiTypeParameter> = emptyList(),
val parameters: List<@JvmCommon PsiParameter> = emptyList()
) {
@Deprecated("use `targetClass`", ReplaceWith("targetClass"))
val containingClass: UClass
get() = targetClass.asUast<UClass>()
companion object {
@JvmStatic
fun constructorInfo(targetClass: @JvmCommon PsiClass, parameters: List<@JvmCommon PsiParameter>) =
Constructor(targetClass = targetClass, parameters = parameters)
@JvmStatic
fun simpleMethodInfo(containingClass: @JvmCommon PsiClass,
methodName: String,
@PsiModifier.ModifierConstant modifier: String,
returnType: PsiType,
parameters: List<@JvmCommon PsiParameter>) =
Method(name = methodName,
modifiers = listOf(modifier),
targetClass = containingClass,
returnType = returnType,
parameters = parameters)
}
class Method(
targetClass: @JvmCommon PsiClass,
val name: String,
modifiers: List<String> = emptyList(),
typeParams: List<@JvmCommon PsiTypeParameter> = emptyList(),
val returnType: PsiType,
parameters: List<@JvmCommon PsiParameter> = emptyList(),
val isAbstract: Boolean = false
) : MethodInsertionInfo(targetClass, modifiers, typeParams, parameters)
class Constructor(
targetClass: @JvmCommon PsiClass,
modifiers: List<String> = emptyList(),
typeParams: List<@JvmCommon PsiTypeParameter> = emptyList(),
parameters: List<@JvmCommon PsiParameter> = emptyList()
) : MethodInsertionInfo(targetClass, modifiers, typeParams, parameters)
}
@Deprecated("remove after kotlin plugin will be ported")
private inline fun <reified T : UElement> PsiElement.asUast(): T = when (this) {
is T -> this
else -> this.let { ServiceManager.getService(project, UastContext::class.java).convertElement(this, null, T::class.java) as T? }
?: throw UnsupportedOperationException("cant convert $this to ${T::class}")
} | apache-2.0 | 544c23784c2cf24fcf733e4369c2b56a | 43.100719 | 150 | 0.686898 | 5.491935 | false | false | false | false |
RocketChat/Rocket.Chat.Android | app/src/main/java/chat/rocket/android/chatrooms/viewmodel/ChatRoomsViewModel.kt | 2 | 8099 | package chat.rocket.android.chatrooms.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import chat.rocket.android.chatrooms.adapter.ItemHolder
import chat.rocket.android.chatrooms.adapter.LoadingItemHolder
import chat.rocket.android.chatrooms.adapter.RoomUiModelMapper
import chat.rocket.android.chatrooms.domain.FetchChatRoomsInteractor
import chat.rocket.android.chatrooms.infrastructure.ChatRoomsRepository
import chat.rocket.android.server.infrastructure.ConnectionManager
import chat.rocket.android.util.livedata.transform
import chat.rocket.android.util.livedata.wrap
import chat.rocket.android.util.retryIO
import chat.rocket.common.RocketChatAuthException
import chat.rocket.common.util.ifNull
import chat.rocket.core.internal.realtime.socket.model.State
import chat.rocket.core.internal.rest.spotlight
import chat.rocket.core.model.SpotlightResult
import com.shopify.livedataktx.distinct
import com.shopify.livedataktx.map
import com.shopify.livedataktx.nonNull
import kotlinx.coroutines.async
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.newSingleThreadContext
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.lang.IllegalArgumentException
import kotlin.coroutines.coroutineContext
class ChatRoomsViewModel(
private val connectionManager: ConnectionManager,
private val interactor: FetchChatRoomsInteractor,
private val repository: ChatRoomsRepository,
private val mapper: RoomUiModelMapper
) : ViewModel() {
private val query = MutableLiveData<Query>()
val loadingState = MutableLiveData<LoadingState>()
private val runContext = newSingleThreadContext("chat-rooms-view-model")
private val client = connectionManager.client
private var loaded = false
var showLastMessage = true
fun getChatRooms(): LiveData<RoomsModel> {
return Transformations.switchMap(query) { query ->
return@switchMap if (query.isSearch()) {
[email protected](runContext) { _, data: MutableLiveData<RoomsModel> ->
val string = (query as Query.Search).query
// debounce, to not query while the user is writing
delay(200)
// TODO - find a better way for cancellation checking
if (!coroutineContext.isActive) return@wrap
val rooms = repository.search(string).let { mapper.map(it, showLastMessage = this.showLastMessage) }
data.postValue(rooms.toMutableList() + LoadingItemHolder())
if (!coroutineContext.isActive) return@wrap
val spotlight = spotlight(query.query)?.let { mapper.map(it, showLastMessage = this.showLastMessage) }
if (!coroutineContext.isActive) return@wrap
spotlight?.let {
data.postValue(rooms.toMutableList() + spotlight)
}.ifNull {
data.postValue(rooms)
}
}
} else {
repository.getChatRooms(query.asSortingOrder())
.nonNull()
.distinct()
.transform(runContext) { rooms ->
val mappedRooms = rooms?.let {
mapper.map(rooms, query.isGrouped(), this.showLastMessage)
}
if (loaded && mappedRooms?.isEmpty() == true) {
loadingState.postValue(LoadingState.Loaded(0))
}
mappedRooms
}
}
}
}
fun getUsersRoomListLocal(string: String): List<ItemHolder<*>> {
val rooms = GlobalScope.async(Dispatchers.IO) {
return@async repository.search(string).let { mapper.map(it, showLastMessage = showLastMessage) }
}
return runBlocking { rooms.await() }
}
fun getUsersRoomListSpotlight(string: String): List<ItemHolder<*>>? {
val rooms = GlobalScope.async(Dispatchers.IO) {
return@async spotlight(string)?.let { mapper.map(it, showLastMessage = showLastMessage) }
}
return runBlocking { rooms.await() }
}
private suspend fun spotlight(query: String): SpotlightResult? {
return try {
retryIO { client.spotlight(query) }
} catch (ex: Exception) {
ex.printStackTrace()
null
}
}
fun getStatus(): MutableLiveData<State> {
return connectionManager.stateLiveData.nonNull().distinct().map { state ->
if (state is State.Connected) fetchRooms()
state
}
}
private fun fetchRooms() {
GlobalScope.launch {
setLoadingState(LoadingState.Loading(repository.count()))
try {
interactor.refreshChatRooms()
setLoadingState(LoadingState.Loaded(repository.count()))
loaded = true
} catch (ex: Exception) {
Timber.d(ex, "Error refreshing chatrooms")
Timber.d(ex, "Message: $ex")
if (ex is RocketChatAuthException) {
setLoadingState(LoadingState.AuthError)
} else {
setLoadingState(LoadingState.Error(repository.count()))
}
}
}
}
fun setQuery(query: Query) {
this.query.value = query
}
private suspend fun setLoadingState(state: LoadingState) {
withContext(Dispatchers.Main) {
loadingState.value = state
}
}
}
typealias RoomsModel = List<ItemHolder<*>>
sealed class LoadingState {
data class Loading(val count: Long) : LoadingState()
data class Loaded(val count: Long) : LoadingState()
data class Error(val count: Long) : LoadingState()
object AuthError : LoadingState()
}
sealed class Query {
data class ByActivity(val grouped: Boolean = false, val unreadOnTop: Boolean = false) : Query()
data class ByName(val grouped: Boolean = false, val unreadOnTop: Boolean = false ) : Query()
data class Search(val query: String) : Query()
}
fun Query.isSearch(): Boolean = this is Query.Search
fun Query.isGrouped(): Boolean {
return when(this) {
is Query.Search -> false
is Query.ByName -> grouped
is Query.ByActivity -> grouped
}
}
fun Query.isUnreadOnTop(): Boolean {
return when(this) {
is Query.Search -> false
is Query.ByName -> unreadOnTop
is Query.ByActivity -> unreadOnTop
}
}
fun Query.asSortingOrder(): ChatRoomsRepository.Order {
return when(this) {
is Query.ByName -> {
if (grouped && !unreadOnTop) {
ChatRoomsRepository.Order.GROUPED_NAME
}
else if(unreadOnTop && !grouped){
ChatRoomsRepository.Order.UNREAD_ON_TOP_NAME
}
else if(unreadOnTop && grouped){
ChatRoomsRepository.Order.UNREAD_ON_TOP_GROUPED_NAME
}
else {
ChatRoomsRepository.Order.NAME
}
}
is Query.ByActivity -> {
if (grouped && !unreadOnTop) {
ChatRoomsRepository.Order.GROUPED_ACTIVITY
}
else if(unreadOnTop && !grouped){
ChatRoomsRepository.Order.UNREAD_ON_TOP_ACTIVITY
}
else if(unreadOnTop && grouped){
ChatRoomsRepository.Order.UNREAD_ON_TOP_GROUPED_ACTIVITY
}
else {
ChatRoomsRepository.Order.ACTIVITY
}
}
else -> throw IllegalArgumentException("Should be ByName or ByActivity")
}
} | mit | 4cfc798db85e16c0735f98a7d3e9c684 | 35.651584 | 122 | 0.62341 | 5.065041 | false | false | false | false |
proxer/ProxerLibAndroid | library/src/main/kotlin/me/proxer/library/api/list/IndustryListEndpoint.kt | 2 | 1334 | package me.proxer.library.api.list
import me.proxer.library.ProxerCall
import me.proxer.library.api.PagingLimitEndpoint
import me.proxer.library.entity.list.IndustryCore
import me.proxer.library.enums.Country
/**
* Endpoint for retrieving a list of industries.
*
* @author Ruben Gees
*/
class IndustryListEndpoint internal constructor(
private val internalApi: InternalApi
) : PagingLimitEndpoint<List<IndustryCore>> {
private var page: Int? = null
private var limit: Int? = null
private var searchStart: String? = null
private var search: String? = null
private var country: Country? = null
override fun page(page: Int?) = this.apply { this.page = page }
override fun limit(limit: Int?) = this.apply { this.limit = limit }
/**
* Sets the query to search for only from the start.
*/
fun searchStart(searchStart: String?) = this.apply { this.searchStart = searchStart }
/**
* Sets the query to search for.
*/
fun search(search: String?) = this.apply { this.search = search }
/**
* Sets the country to filter by.
*/
fun country(country: Country?) = this.apply { this.country = country }
override fun build(): ProxerCall<List<IndustryCore>> {
return internalApi.industryList(searchStart, search, country, page, limit)
}
}
| gpl-3.0 | b05c38f105cac227b5df5ccf36b2145c | 28.644444 | 89 | 0.685157 | 4.092025 | false | false | false | false |
AlexanderDashkov/hpcourse | csc/2016/vsv_1/test/util.client/TaskWorker.kt | 3 | 3310 | package util.client
import communication.CommunicationProtos
import java.io.InputStream
import java.net.Socket
/**
* @author Sergey Voytovich ([email protected]) on 10.04.16
*/
class TaskWorker(private val port: Int, private val clientId: String) {
private val localhost = "localhost"
private var requestId: Long = 0
fun list(): CommunicationProtos.ListTasksResponse {
val request: CommunicationProtos.ServerRequest = getRequestBuilder()
.setList(CommunicationProtos.ListTasks.newBuilder().build())
.build()
val response = writeRequestAndGetResponse(request)
return response.listResponse
}
fun submit(a: CommunicationProtos.Task.Param,
b: CommunicationProtos.Task.Param,
p: CommunicationProtos.Task.Param,
m: CommunicationProtos.Task.Param,
n: Long): CommunicationProtos.SubmitTaskResponse {
val taskRequest = CommunicationProtos.Task.newBuilder()
.setA(toParam(a))
.setB(toParam(b))
.setP(toParam(p))
.setM(toParam(m))
.setN(n)
.build()
val request = getRequestBuilder()
.setSubmit(CommunicationProtos.SubmitTask.newBuilder().setTask(taskRequest))
.build()
val response = writeRequestAndGetResponse(request)
return response.submitResponse
}
fun subscribe(taskId: Int): CommunicationProtos.SubscribeResponse {
val subscribeRequest: CommunicationProtos.Subscribe = CommunicationProtos.Subscribe.newBuilder()
.setTaskId(taskId)
.build()
val request = getRequestBuilder()
.setSubscribe(subscribeRequest)
.build()
val response = writeRequestAndGetResponse(request)
return response.subscribeResponse
}
private fun writeRequestAndGetResponse(_request: CommunicationProtos.ServerRequest): CommunicationProtos.ServerResponse {
val request = CommunicationProtos.WrapperMessage.newBuilder()
.setRequest(_request)
.build()
Socket(localhost, port).use {
it.outputStream.write(request.serializedSize)
request.writeTo(it.outputStream);
val response = getResponse(it.inputStream)
return response
}
}
fun toParam(p: CommunicationProtos.Task.Param): CommunicationProtos.Task.Param {
if (p.hasDependentTaskId()) {
return CommunicationProtos.Task.Param.newBuilder()
.setDependentTaskId(p.value.toInt())
.build()
}
return CommunicationProtos.Task.Param.newBuilder()
.setValue(p.value)
.build()
}
private fun getResponse(ism: InputStream): CommunicationProtos.ServerResponse {
return CommunicationProtos.WrapperMessage.parseDelimitedFrom(ism).response
}
private fun getRequestBuilder(): CommunicationProtos.ServerRequest.Builder {
return CommunicationProtos.ServerRequest.newBuilder()
.setClientId(clientId)
.setRequestId(getNextId())
}
private fun getNextId(): Long {
return ++requestId
}
}
| gpl-2.0 | 3f988b8060d8da8c6f3057c79d378cbc | 34.591398 | 125 | 0.635347 | 5.313002 | false | false | false | false |
wizardofos/Protozoo | extra/exposed/src/main/kotlin/org/jetbrains/exposed/sql/statements/InsertSelectStatement.kt | 1 | 1224 | package org.jetbrains.exposed.sql.statements
import org.jetbrains.exposed.sql.Column
import org.jetbrains.exposed.sql.IColumnType
import org.jetbrains.exposed.sql.Query
import org.jetbrains.exposed.sql.Transaction
import java.sql.PreparedStatement
class InsertSelectStatement(val columns: List<Column<*>>, val selectQuery: Query, val isIgnore: Boolean = false): Statement<Int>(StatementType.INSERT, listOf(columns.first().table)) {
init {
if (columns.isEmpty()) error("Can't insert without provided columns")
val tables = columns.distinctBy { it.table }
if (tables.count() > 1) error("Can't insert to different tables ${tables.joinToString { it.name }} from single select")
if (columns.size != selectQuery.set.fields.size) error("Columns count doesn't equal to query columns count")
}
override fun PreparedStatement.executeInternal(transaction: Transaction): Int? = executeUpdate()
override fun arguments(): Iterable<Iterable<Pair<IColumnType, Any?>>> = selectQuery.arguments()
override fun prepareSQL(transaction: Transaction): String =
transaction.db.dialect.insert(isIgnore, targets.single(), columns, selectQuery.prepareSQL(transaction), transaction)
}
| mit | cc42da5800b138c9181eb1ea44136fb1 | 47.96 | 183 | 0.749183 | 4.402878 | false | false | false | false |
TheFakeMontyOnTheRun/GiovanniTheExplorer | app/src/main/java/br/odb/giovanni/game/Monster.kt | 1 | 1986 | package br.odb.giovanni.game
import android.content.res.Resources
import android.graphics.BitmapFactory
import android.media.MediaPlayer
import br.odb.giovanni.R
import br.odb.giovanni.engine.Constants
class Monster(resources: Resources, private val kill: MediaPlayer) : Actor() {
var actorTarget: Actor? = null
private var timeToMove: Long = 0
init {
animation.addFrame(BitmapFactory.decodeResource(resources, R.drawable.monster_3))
animation.addFrame(BitmapFactory.decodeResource(resources, R.drawable.monster_4))
direction = 3
}
override fun tick(timeInMS: Long) {
super.tick(timeInMS)
timeToMove -= timeInMS
timeToMove = if (timeToMove < 0) {
300
} else {
return
}
val currentX = position.x / Constants.BASE_TILE_WIDTH
val currentY = position.y / Constants.BASE_TILE_HEIGHT
val targetX = actorTarget!!.position.x / Constants.BASE_TILE_WIDTH
val targetY = actorTarget!!.position.y / Constants.BASE_TILE_HEIGHT
val dirX: Float = when {
targetX < currentX -> {
-0.5f
}
targetX > currentX -> {
0.5f
}
else -> {
0f
}
}
val dirY: Float = when {
targetY < currentY -> {
-0.5f
}
targetY > currentY -> {
0.5f
}
else -> {
0f
}
}
//try to move around obstacle
when {
level!!.mayMoveTo(currentX + dirX, currentY + dirY) -> {
move(Constants.BASE_TILE_WIDTH * dirX, Constants.BASE_TILE_HEIGHT * dirY )
}
level!!.mayMoveTo(currentX, currentY + 0.5f) -> {
move(0f, Constants.BASE_TILE_HEIGHT * 0.5f)
}
level!!.mayMoveTo(currentX + 0.5f, currentY) -> {
move(Constants.BASE_TILE_WIDTH * 0.5f, 0.0f)
}
level!!.mayMoveTo(currentX - 0.5f, currentY) -> {
move(Constants.BASE_TILE_WIDTH * -0.5f, 0.0f)
}
level!!.mayMoveTo(currentX, currentY - 0.5f) -> {
move(0f, Constants.BASE_TILE_HEIGHT * 0.5f)
}
}
}
override fun touched(actor: Actor?) {
if (actor is Monster) {
kill.start()
kill()
}
}
public override fun didMove() {}
} | bsd-3-clause | f31682f89be2742632200d1fa3552a09 | 22.939759 | 83 | 0.655589 | 2.959762 | false | false | false | false |
nickthecoder/tickle | tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/EditorActions.kt | 1 | 3624 | /*
Tickle
Copyright (C) 2017 Nick Robinson
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 uk.co.nickthecoder.tickle.editor
import javafx.scene.input.KeyCode
import uk.co.nickthecoder.paratask.gui.ApplicationAction
object EditorActions {
val nameToActionMap = mutableMapOf<String, ApplicationAction>()
val NEW = EditorAction("new", KeyCode.N, control = true, label = "New", tooltip = "Create a New Resource")
val RUN = EditorAction("run", KeyCode.R, control = true, label = "Run", tooltip = "Run the game")
val TEST = EditorAction("test", KeyCode.T, control = true, label = "Test", tooltip = "Test the game")
val RELOAD = EditorAction("reload", KeyCode.F5, label = "Reload", tooltip = "Reload textures, fonts & sounds")
val OPEN = EditorAction("open", KeyCode.O, control = true, label = "Open", tooltip = "Open Resource")
val SAVE = EditorAction("save", KeyCode.S, control = true, label = "Save")
val ACCORDION_ONE = EditorAction("accordion.one", KeyCode.F4)
val ACCORDION_TWO = EditorAction("accordion.two", KeyCode.F5)
val ACCORDION_THREE = EditorAction("accordion.three", KeyCode.F6)
val ACCORDION_FOUR = EditorAction("accordion.four", KeyCode.F7)
val ACCORDION_FIVE = EditorAction("accordion.five", KeyCode.F8)
val SHOW_COSTUME_PICKER = EditorAction("show.costumePicker", KeyCode.CONTEXT_MENU)
val ESCAPE = EditorAction("escape", KeyCode.ESCAPE)
val DELETE = EditorAction("delete", KeyCode.DELETE)
val UNDO = EditorAction("undo", KeyCode.Z, control = true)
val REDO = EditorAction("redo", KeyCode.Z, control = true, shift = true)
val ZOOM_RESET = EditorAction("zoom.reset", KeyCode.DIGIT0, control = true)
val ZOOM_IN1 = EditorAction("zoom.in", KeyCode.PLUS, control = true)
val ZOOM_IN2 = EditorAction("zoom.out", KeyCode.EQUALS, control = true)
val ZOOM_OUT = EditorAction("zoom.out", KeyCode.MINUS, control = true)
val SNAPS_EDIT = EditorAction("snaps.edit", KeyCode.NUMBER_SIGN, control = true, shift = true, tooltip = "Edit Snapping")
val SNAP_TO_GRID_TOGGLE = EditorAction("snap.grid.toggle", KeyCode.NUMBER_SIGN, control = true)
val SNAP_TO_GUIDES_TOGGLE = EditorAction("snap.guides.toggle", KeyCode.G, control = true)
val SNAP_TO_OTHERS_TOGGLE = EditorAction("snap.others.toggle", KeyCode.O, control = true)
val SNAP_ROTATION_TOGGLE = EditorAction("snap.rotation.toggle", KeyCode.R, control = true)
val RESET_ZORDERS = EditorAction("zOrders.reset", KeyCode.Z, control = true, shift = true, label = "Reset All Z-Orders")
val STAMPS = listOf(KeyCode.DIGIT1, KeyCode.DIGIT2, KeyCode.DIGIT3, KeyCode.DIGIT4, KeyCode.DIGIT5, KeyCode.DIGIT6, KeyCode.DIGIT7, KeyCode.DIGIT8, KeyCode.DIGIT9)
.mapIndexed { index, keyCode -> EditorAction("stamp$index", keyCode, control = true) }
val TAB_CLOSE = EditorAction("tab.close", KeyCode.W, control = true, label = "Close Tab")
val RELOAD_SCRIPTS = EditorAction("scripts.reload", KeyCode.F5, label = "Reload Scripts", tooltip = "Reload all scripts")
}
| gpl-3.0 | ec459feb45c23ae87a7a4a2cda2e3492 | 49.333333 | 167 | 0.721302 | 3.884244 | false | true | false | false |
UniversityOfBrightonComputing/iCurves | src/main/kotlin/icurves/util/BezierApproximation.kt | 1 | 20539 | package icurves.util
import icurves.CurvesApp
import icurves.algorithm.ClosedBezierSpline
import javafx.geometry.Point2D
import javafx.scene.paint.Color
import javafx.scene.shape.CubicCurveTo
import javafx.scene.shape.LineTo
import javafx.scene.shape.MoveTo
import javafx.scene.shape.Path
import java.util.*
/**
* The algorithm is adapted from AS3
* http://www.cartogrammar.com/blog/actionscript-curves-update/
*
* @author Almas Baimagambetov ([email protected])
*/
object BezierApproximation {
private val z = 0.5
private val angleFactor = 0.75
fun smoothPath2(originalPoints: MutableList<Point2D>, smoothFactor: Int): List<Path> {
val pair = ClosedBezierSpline.GetCurveControlPoints(originalPoints.toTypedArray())
val points = originalPoints.plus(originalPoints[0])
val result = arrayListOf<Path>()
val firstPt = 0
val lastPt = points.size
for (i in firstPt..lastPt - 2){
val path = Path()
path.elements.add(MoveTo(points[i].x, points[i].y))
val j = if (i == lastPt - 2) 0 else i + 1
path.elements.add(CubicCurveTo(
pair.key[i].x, pair.key[i].y,
pair.value[j].x, pair.value[j].y,
//controlPts[i].second.x, controlPts[i].second.y,
//controlPts[i+1].first.x, controlPts[i+1].first.y,
points[i+1].x, points[i+1].y)
)
path.fill = Color.TRANSPARENT
result.add(path)
}
return result
}
fun smoothPath(points: MutableList<Point2D>, smoothFactor: Int): List<Path> {
// to make a closed cycle
points.add(points[0])
val result = arrayListOf<Path>()
val firstPt = 0
val lastPt = points.size
// store the two control points (of a cubic Bezier curve) for each point
val controlPts = arrayListOf<Pair<Point2D, Point2D>>()
for (i in firstPt until lastPt) {
controlPts.add(Pair(Point2D.ZERO, Point2D.ZERO))
}
// loop through all the points to get curve control points for each
for (i in firstPt until lastPt) {
val prevPoint = if (i-1 < 0) points[points.size-2] else points[i-1]
val currPoint = points[i]
val nextPoint = if (i+1 == points.size) points[1] else points[i+1]
var a = prevPoint.distance(currPoint)
if (a < 0.001) a = .001; // Correct for near-zero distances, a cheap way to prevent division by zero
var b = currPoint.distance(nextPoint)
if (b < 0.001) b = .001;
var c = prevPoint.distance(nextPoint)
if (c < 0.001) c = .001
var cos = (b*b + a*a - c*c) / (2*b*a)
// ensure cos is between -1 and 1 so that Math.acos will work
if (cos < -1)
cos = -1.0
else if (cos > 1)
cos = 1.0
// angle formed by the two sides of the triangle (described by the three points above) adjacent to the current point
val C = Math.acos(cos)
// Duplicate set of points. Start by giving previous and next points values RELATIVE to the current point.
var aPt = Point2D(prevPoint.x-currPoint.x,prevPoint.y-currPoint.y);
var bPt = Point2D(currPoint.x,currPoint.y);
var cPt = Point2D(nextPoint.x-currPoint.x,nextPoint.y-currPoint.y);
/*
We'll be adding adding the vectors from the previous and next points to the current point,
but we don't want differing magnitudes (i.e. line segment lengths) to affect the direction
of the new vector. Therefore we make sure the segments we use, based on the duplicate points
created above, are of equal length. The angle of the new vector will thus bisect angle C
(defined above) and the perpendicular to this is nice for the line tangent to the curve.
The curve control points will be along that tangent line.
*/
if (a > b){
//aPt.normalize(b); // Scale the segment to aPt (bPt to aPt) to the size of b (bPt to cPt) if b is shorter.
aPt = aPt.normalize().multiply(b)
} else if (b > a){
//cPt.normalize(a); // Scale the segment to cPt (bPt to cPt) to the size of a (aPt to bPt) if a is shorter.
cPt = cPt.normalize().multiply(a)
}
// Offset aPt and cPt by the current point to get them back to their absolute position.
aPt = aPt.add(currPoint.x,currPoint.y)
cPt = cPt.add(currPoint.x,currPoint.y)
// Get the sum of the two vectors, which is perpendicular to the line along which our curve control points will lie.
var ax = bPt.x-aPt.x // x component of the segment from previous to current point
var ay = bPt.y-aPt.y
var bx = bPt.x-cPt.x // x component of the segment from next to current point
var by = bPt.y-cPt.y
var rx = ax + bx; // sum of x components
var ry = ay + by;
// Correct for three points in a line by finding the angle between just two of them
if (rx == 0.0 && ry == 0.0){
rx = -bx; // Really not sure why this seems to have to be negative
ry = by;
}
// Switch rx and ry when y or x difference is 0. This seems to prevent the angle from being perpendicular to what it should be.
if (ay == 0.0 && by == 0.0){
rx = 0.0;
ry = 1.0;
} else if (ax == 0.0 && bx == 0.0){
rx = 1.0;
ry = 0.0;
}
val theta = Math.atan2(ry,rx) // angle of the new vector
var controlDist = Math.min(a, b) * z; // Distance of curve control points from current point: a fraction the length of the shorter adjacent triangle side
val controlScaleFactor = C/Math.PI; // Scale the distance based on the acuteness of the angle. Prevents big loops around long, sharp-angled triangles.
controlDist *= ((1.0-angleFactor) + angleFactor*controlScaleFactor); // Mess with this for some fine-tuning
val controlAngle = theta+Math.PI/2; // The angle from the current point to control points: the new vector angle plus 90 degrees (tangent to the curve).
var controlPoint2 = polarToCartesian(controlDist, controlAngle); // Control point 2, curving to the next point.
var controlPoint1 = polarToCartesian(controlDist, controlAngle+Math.PI); // Control point 1, curving from the previous point (180 degrees away from control point 2).
// Offset control points to put them in the correct absolute position
controlPoint1 = controlPoint1.add(currPoint);
controlPoint2 = controlPoint2.add(currPoint);
/*
Haven't quite worked out how this happens, but some control points will be reversed.
In this case controlPoint2 will be farther from the next point than controlPoint1 is.
Check for that and switch them if it's true.
*/
if (controlPoint2.distance(nextPoint) > controlPoint1.distance(nextPoint)){
controlPts[i] = Pair(controlPoint2, controlPoint1) // Add the two control points to the array in reverse order
} else {
controlPts[i] = Pair(controlPoint1, controlPoint2) // Otherwise add the two control points to the array in normal order
}
}
// a b c ab ac ad bc abc abd acd abcd
CurvesApp.getInstance().settings.globalMap["controlPoints"] = controlPts
val straightLines:Boolean = true; // Change to true if you want to use lineTo for straight lines of 3 or more points rather than curves. You'll get straight lines but possible sharp corners!
// Loop through points to draw cubic Bézier curves through the penultimate point, or through the last point if the line is closed.
for (i in firstPt..lastPt - 2){
val path = Path()
path.elements.add(MoveTo(points[i].x, points[i].y))
// Determine if multiple points in a row are in a straight line
val isStraight:Boolean = ( ( i > 0 && Math.atan2(points[i].y-points[i-1].y, points[i].x-points[i-1].x)
== Math.atan2(points[i+1].y-points[i].y, points[i+1].x - points[i].x) )
|| ( i < points.size - 2 && Math.atan2(points[i+2].y-points[i+1].y,points[i+2].x-points[i+1].x)
== Math.atan2(points[i+1].y-points[i].y,points[i+1].x-points[i].x) ) );
if (straightLines && isStraight){
path.elements.add(LineTo(points[i+1].x,points[i+1].y))
} else {
// BezierSegment instance using the current point, its second control point, the next point's first control point, and the next point
// var t = 0.01
// while (t < 1.01) {
//
// val point = getBezierValue(points[i], controlPts[i].second, controlPts[i+1].first, points[i+1], t)
// path.elements.add(LineTo(point.x, point.y))
//
// t += 1.0 / smoothFactor
// }
path.elements.add(CubicCurveTo(
controlPts[i].second.x, controlPts[i].second.y,
controlPts[i+1].first.x, controlPts[i+1].first.y,
points[i+1].x, points[i+1].y)
)
}
path.fill = Color.TRANSPARENT
result.add(path)
}
return result
}
//
// fun pathThruPoints(points: MutableList<Point2D>,
// smoothFactor: Int,
// closedCycle: Boolean = true,
// z: Double = 0.5,
// angleFactor: Double = 0.75): List<Path> {
//
// if (closedCycle)
// points.add(points[0])
//
// val result = ArrayList<Path>()
//
// // Ordinarily, curve calculations will start with the second point and go through the second-to-last point
// var firstPt = 1;
// var lastPt = points.size - 1;
//
// // Check if this is a closed line (the first and last points are the same)
// if (points[0].x == points[points.size-1].x && points[0].y == points[points.size-1].y){
// // Include first and last points in curve calculations
// firstPt = 0
// lastPt = points.size
// }
//
// val controlPts = ArrayList<Pair<Point2D, Point2D>>() // An array to store the two control points (of a cubic Bézier curve) for each point
// for (i in 0..points.size - 1) {
// controlPts.add(Pair(Point2D.ZERO, Point2D.ZERO))
// }
//
// // Loop through all the points (except the first and last if not a closed line) to get curve control points for each.
// for (i in firstPt..lastPt - 1) {
//
// // The previous, current, and next points
// var p0 = if (i-1 < 0) points[points.size-2] else points[i-1]; // If the first point (of a closed line), use the second-to-last point as the previous point
// var p1 = points[i];
// var p2 = if (i+1 == points.size) points[1] else points[i+1]; // If the last point (of a closed line), use the second point as the next point
//
// var a = p0.distance(p1) // Distance from previous point to current point
// if (a < 0.001) a = .001; // Correct for near-zero distances, a cheap way to prevent division by zero
// var b = p1.distance(p2); // Distance from current point to next point
// if (b < 0.001) b = .001;
// var c = p0.distance(p2); // Distance from previous point to next point
// if (c < 0.001) c = .001;
// var cos = (b*b+a*a-c*c)/(2*b*a);
//
//
//
//
//
//
//
//
// // Make sure above value is between -1 and 1 so that Math.acos will work
// if (cos < -1)
// cos = -1.0;
// else if (cos > 1)
// cos = 1.0;
//
// var C = Math.acos(cos); // Angle formed by the two sides of the triangle (described by the three points above) adjacent to the current point
// // Duplicate set of points. Start by giving previous and next points values RELATIVE to the current point.
// var aPt = Point2D(p0.x-p1.x,p0.y-p1.y);
// var bPt = Point2D(p1.x,p1.y);
// var cPt = Point2D(p2.x-p1.x,p2.y-p1.y);
//
// /*
// We'll be adding adding the vectors from the previous and next points to the current point,
// but we don't want differing magnitudes (i.e. line segment lengths) to affect the direction
// of the new vector. Therefore we make sure the segments we use, based on the duplicate points
// created above, are of equal length. The angle of the new vector will thus bisect angle C
// (defined above) and the perpendicular to this is nice for the line tangent to the curve.
// The curve control points will be along that tangent line.
// */
//
// if (a > b){
// //aPt.normalize(b); // Scale the segment to aPt (bPt to aPt) to the size of b (bPt to cPt) if b is shorter.
// aPt = aPt.normalize().multiply(b)
// } else if (b > a){
// //cPt.normalize(a); // Scale the segment to cPt (bPt to cPt) to the size of a (aPt to bPt) if a is shorter.
// cPt = cPt.normalize().multiply(a)
// }
//
// // Offset aPt and cPt by the current point to get them back to their absolute position.
// aPt = aPt.add(p1.x,p1.y);
// cPt = cPt.add(p1.x,p1.y);
//
// // Get the sum of the two vectors, which is perpendicular to the line along which our curve control points will lie.
// var ax = bPt.x-aPt.x; // x component of the segment from previous to current point
// var ay = bPt.y-aPt.y;
// var bx = bPt.x-cPt.x; // x component of the segment from next to current point
// var by = bPt.y-cPt.y;
// var rx = ax + bx; // sum of x components
// var ry = ay + by;
//
// // Correct for three points in a line by finding the angle between just two of them
// if (rx == 0.0 && ry == 0.0){
// rx = -bx; // Really not sure why this seems to have to be negative
// ry = by;
// }
// // Switch rx and ry when y or x difference is 0. This seems to prevent the angle from being perpendicular to what it should be.
// if (ay == 0.0 && by == 0.0){
// rx = 0.0;
// ry = 1.0;
// } else if (ax == 0.0 && bx == 0.0){
// rx = 1.0;
// ry = 0.0;
// }
//
// //var r = Math.sqrt(rx*rx+ry*ry); // length of the summed vector - not being used, but there it is anyway
// var theta = Math.atan2(ry,rx); // angle of the new vector
//
// var controlDist = Math.min(a,b)*z; // Distance of curve control points from current point: a fraction the length of the shorter adjacent triangle side
// var controlScaleFactor = C/Math.PI; // Scale the distance based on the acuteness of the angle. Prevents big loops around long, sharp-angled triangles.
//
// controlDist *= ((1.0-angleFactor) + angleFactor*controlScaleFactor); // Mess with this for some fine-tuning
//
// var controlAngle = theta+Math.PI/2; // The angle from the current point to control points: the new vector angle plus 90 degrees (tangent to the curve).
//
//
// var controlPoint2 = polarToCartesian(controlDist, controlAngle); // Control point 2, curving to the next point.
// var controlPoint1 = polarToCartesian(controlDist, controlAngle+Math.PI); // Control point 1, curving from the previous point (180 degrees away from control point 2).
//
// // Offset control points to put them in the correct absolute position
// controlPoint1 = controlPoint1.add(p1.x,p1.y);
// controlPoint2 = controlPoint2.add(p1.x,p1.y);
//
// /*
// Haven't quite worked out how this happens, but some control points will be reversed.
// In this case controlPoint2 will be farther from the next point than controlPoint1 is.
// Check for that and switch them if it's true.
// */
// if (controlPoint2.distance(p2) > controlPoint1.distance(p2)){
// controlPts[i] = Pair(controlPoint2,controlPoint1); // Add the two control points to the array in reverse order
// } else {
// controlPts[i] = Pair(controlPoint1,controlPoint2); // Otherwise add the two control points to the array in normal order
// }
//
// // Uncomment to draw lines showing where the control points are.
// /*
// g.moveTo(p1.x,p1.y);
// g.lineTo(controlPoint2.x,controlPoint2.y);
// g.moveTo(p1.x,p1.y);
// g.lineTo(controlPoint1.x,controlPoint1.y);
// */
// }
//
//
// //
// // CURVE CONSTRUCTION VIA ELEMENTS
// //
//
// //path.elements.add(MoveTo(points[0].x, points[0].y))
//
//
//
// var straightLines:Boolean = true; // Change to true if you want to use lineTo for straight lines of 3 or more points rather than curves. You'll get straight lines but possible sharp corners!
//
// // Loop through points to draw cubic Bézier curves through the penultimate point, or through the last point if the line is closed.
// for (i in firstPt..lastPt - 2){
//
// val path = Path()
//
// path.elements.add(MoveTo(points[i].x, points[i].y))
//
// // Determine if multiple points in a row are in a straight line
// var isStraight:Boolean = ( ( i > 0 && Math.atan2(points[i].y-points[i-1].y, points[i].x-points[i-1].x)
// == Math.atan2(points[i+1].y-points[i].y, points[i+1].x - points[i].x) )
// || ( i < points.size - 2 && Math.atan2(points[i+2].y-points[i+1].y,points[i+2].x-points[i+1].x)
// == Math.atan2(points[i+1].y-points[i].y,points[i+1].x-points[i].x) ) );
//
// if (straightLines && isStraight){
// path.elements.add(LineTo(points[i+1].x,points[i+1].y))
// } else {
//
// // BezierSegment instance using the current point, its second control point, the next point's first control point, and the next point
// //var bezier:BezierSegment = new BezierSegment(points[i], controlPts[i].second, controlPts[i+1].first, points[i+1]);
//
// // Construct the curve out of 100 segments (adjust number for less/more detail)
//
// var t = 0.01
// while (t < 1.01) {
//
// val point = getBezierValue(points[i], controlPts[i].second, controlPts[i+1].first, points[i+1], t)
// path.elements.add(LineTo(point.x, point.y))
//
// t += 1.0 / smoothFactor
// }
// }
//
// path.fill = Color.TRANSPARENT
// result.add(path)
// }
//
// // moveTo
// // lineTo * 10 * numPoints
// // closePath
//
// //println("Path elements: ${path.elements}")
//
//// if (closedCycle)
//// path.elements.add(ClosePath())
//
// //path.fill = Color.TRANSPARENT
//
// return result
// }
/**
* Polar to Cartesian conversion.
*/
private fun polarToCartesian(len: Double, angle: Double): Point2D {
return Point2D(len * Math.cos(angle), len * Math.sin(angle))
}
/**
* Cubic bezier equation from
* http://stackoverflow.com/questions/5634460/quadratic-bezier-curve-calculate-point
*/
private fun getBezierValue(p1: Point2D, p2: Point2D, p3: Point2D, p4: Point2D, t: Double): Point2D {
val x = Math.pow(1 - t, 3.0) * p1.x + 3 * t * Math.pow(1 - t, 2.0) * p2.x + 3 * t*t * (1 - t) * p3.x + t*t*t*p4.x
val y = Math.pow(1 - t, 3.0) * p1.y + 3 * t * Math.pow(1 - t, 2.0) * p2.y + 3 * t*t * (1 - t) * p3.y + t*t*t*p4.y
return Point2D(x, y)
}
} | mit | 9547a66a0d890565a28d8293d513d94e | 42.054507 | 200 | 0.568903 | 3.71222 | false | false | false | false |
daemontus/jafra | src/test/kotlin/com/github/daemontus/jafra/MasterTerminatorTest.kt | 1 | 8569 | package com.github.daemontus.jafra
import org.junit.Test
import java.util.concurrent.BlockingQueue
import java.util.concurrent.LinkedBlockingQueue
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
open class MockMasterMessenger : TokenMessenger {
var mc: Int = 0
val queue: BlockingQueue<Token> = LinkedBlockingQueue<Token>()
@Synchronized
override fun sendToNextAsync(token: Token) {
mc += 1
queue.add(token)
}
override fun receiveFromPrevious(): Token = queue.take()
override fun isMaster() = true
}
class MasterTerminatorTest {
@Test(timeout = 2000)
fun complexTest() {
var flag = 1
var count = 0
val comm = object : MockMasterMessenger() {
override fun receiveFromPrevious(): Token {
val t = queue.take()
if (t.flag == 2) {
return t
} else {
//we use dirty flag first to simulate the environment that received the messages
return Token(Math.min(t.flag + flag, 1), t.count + count) //2 because 2 messages are sent
}
}
}
val terminator = Terminator.createNew(comm)
terminator.messageSent()
count++ //message created in system
terminator.messageReceived() //message received
Thread(Runnable {
try {
Thread.sleep(100)
count-- //pair for first message Sent
terminator.messageSent()
terminator.setDone()
Thread.sleep(100)
count++ //message created in system
terminator.messageReceived() //message received
Thread.sleep(100)
count-- //pair for second message Sent
Thread.sleep(100)
flag = 0
terminator.setDone()
} catch (e: InterruptedException) {
e.printStackTrace()
}
}).start()
terminator.waitForTermination()
assertTrue(comm.queue.isEmpty())
assertTrue(comm.mc > 2) //this can cycle for quite a long time, so we just know it's going to be a big number
}
@Test(timeout = 1000)
fun receivedMessagesAfterStart() {
var flag = 1
val comm = object : MockMasterMessenger() {
override fun receiveFromPrevious(): Token {
val t = queue.take()
if (t.flag == 2) {
return t
} else {
//we use dirty flag first to simulate the environment that received the messages
return Token(Math.min(t.flag + flag, 1), t.count + 2) //2 because 2 messages are sent
}
}
}
val terminator = Terminator.createNew(comm)
Thread(Runnable {
try {
Thread.sleep(200)
terminator.messageReceived()
Thread.sleep(100)
terminator.messageReceived()
Thread.sleep(100)
flag = 0
terminator.setDone()
} catch (e: InterruptedException) {
e.printStackTrace()
}
}).start()
terminator.waitForTermination()
assertTrue(comm.queue.isEmpty())
assertEquals(2, comm.mc)
}
@Test(timeout = 1000)
fun sentMessagesAfterStart() {
var flag = 1
val comm = object : MockMasterMessenger() {
override fun receiveFromPrevious(): Token {
val t = queue.take()
if (t.flag == 2) {
return t
} else {
//we use dirty flag first to simulate the environment that received the messages
return Token(Math.min(t.flag + flag, 1), t.count - 2) //2 because 2 messages are sent
}
}
}
val terminator = Terminator.createNew(comm)
Thread(object : Runnable {
override fun run() {
try {
Thread.sleep(50)
terminator.messageSent()
Thread.sleep(50)
terminator.messageSent()
flag = 0
terminator.setDone()
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
}).start()
terminator.waitForTermination()
assertTrue(comm.queue.isEmpty())
assertEquals(2, comm.mc)
}
@Test(timeout = 1000)
fun receiveMessagesBeforeDone() {
//we don't need to simulate flags here, since message send does not modify environment flags
val comm = object : MockMasterMessenger() {
override fun receiveFromPrevious(): Token {
val token = queue.take()
if (token.flag == 2) return token
return Token(token.flag, token.count + 2) // +2 for two sent messages
}
}
//receive and finish work before start
val terminator = Terminator.createNew(comm)
terminator.messageReceived()
Thread.sleep(100)
terminator.messageReceived()
terminator.setDone()
terminator.waitForTermination()
assertEquals(2, comm.mc)
assertTrue(comm.queue.isEmpty())
//receive before start and finish after start
val terminator2 = Terminator.createNew(comm)
terminator2.messageReceived()
Thread(object : Runnable {
override fun run() {
Thread.sleep(400)
terminator2.setDone()
}
}).start()
Thread.sleep(100)
terminator2.messageReceived()
terminator2.waitForTermination()
//only one message is needed to conclude termination, since
//environment is clean and probe is sent only at the first setDone
assertEquals(4, comm.mc)
assertTrue(comm.queue.isEmpty())
}
@Test(timeout = 1000)
fun sendMessagesBeforeDone() {
val comm = object : MockMasterMessenger() {
var flag: Int = 1
override fun receiveFromPrevious(): Token {
val t = queue.take()
if (t.flag == 2) {
return t
} else {
//we use dirty flag first to simulate the environment that received the messages
val r = Token(Math.min(t.flag + flag, 1), t.count - 2) //2 because 2 messages are sent
flag = 0
return r
}
}
}
val terminator = Terminator.createNew(comm)
terminator.messageSent()
Thread.sleep(100)
terminator.messageSent()
terminator.setDone()
terminator.waitForTermination()
assertTrue(comm.queue.isEmpty())
assertEquals(0, comm.flag)
//one with dirty flag, second to verify, last as poison pill
assertEquals(3, comm.mc)
}
@Test(timeout = 1000)
fun wrongUse() {
val comm = MockMasterMessenger()
val terminator = Terminator.createNew(comm)
terminator.setDone()
//terminator not working
assertFailsWith(IllegalStateException::class) {
terminator.setDone()
}
assertFailsWith(IllegalStateException::class) {
terminator.messageSent()
}
terminator.waitForTermination()
//terminator finalized
assertFailsWith(IllegalStateException::class) {
terminator.setDone()
}
assertFailsWith(IllegalStateException::class) {
terminator.messageSent()
}
assertFailsWith(IllegalStateException::class) {
terminator.messageReceived()
}
assertFailsWith(IllegalStateException::class) {
terminator.waitForTermination()
}
}
@Test(timeout = 1000)
fun noMessages() {
//In case there are no other messages, terminator should finish after first onDone call
//It should send exactly two tokens - one for termination check, second as poison pill
val comm = MockMasterMessenger()
val terminator = Terminator.createNew(comm)
terminator.setDone()
terminator.waitForTermination()
assertEquals(2, comm.mc)
assertTrue(comm.queue.isEmpty())
}
} | mit | d56fa21e66242d75f4641a6e1dc4b2e3 | 28.860627 | 117 | 0.549072 | 5.296044 | false | false | false | false |
XiaoQiWen/KRefreshLayout | app_kotlin/src/main/kotlin/gorden/krefreshlayout/demo/ui/SampleActivity.kt | 1 | 2709 | package gorden.krefreshlayout.demo.ui
import android.app.Activity
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.FragmentManager
import gorden.krefreshlayout.demo.R
import gorden.krefreshlayout.demo.ui.fragment.*
import kotlinx.android.synthetic.main.activity_sample.*
class SampleActivity : AppCompatActivity() {
private var mFragment:ISampleFragment? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sample)
text_title.text = intent.getStringExtra("name")
btn_back.setOnClickListener {
finish()
}
btn_setting.setOnClickListener {
val intent = Intent("SettingActivity")
intent.putExtra("header",mFragment?.headerPosition)
intent.putExtra("pincontent",mFragment?.pinContent)
intent.putExtra("keepheader",mFragment?.keepHeaderWhenRefresh)
intent.putExtra("durationoffset",mFragment?.durationOffset)
intent.putExtra("refreshtime",mFragment?.refreshTime)
startActivityForResult(intent,612)
}
val position = intent.getIntExtra("position",0)
val manager:FragmentManager = supportFragmentManager
when(position){
0-> mFragment = SampleAFragment()
1-> mFragment = SampleBFragment()
2-> mFragment = SampleCFragment()
3-> mFragment = SampleDFragment()
4-> mFragment = SampleEFragment()
5-> mFragment = SampleFFragment()
6-> mFragment = SampleGFragment()
7-> mFragment = SampleHFragment()
8-> mFragment = SampleIFragment()
9-> mFragment = SampleJFragment()
else ->mFragment = SampleAFragment()
}
manager.beginTransaction().replace(R.id.frame_content,mFragment).commit()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 612&&resultCode == Activity.RESULT_OK){
mFragment?.headerPosition = data!!.getIntExtra("header",mFragment!!.headerPosition)
mFragment?.pinContent = data.getBooleanExtra("pincontent",mFragment!!.pinContent)
mFragment?.keepHeaderWhenRefresh = data.getBooleanExtra("keepheader",mFragment!!.keepHeaderWhenRefresh)
mFragment?.durationOffset = data.getLongExtra("durationoffset",mFragment!!.durationOffset)
mFragment?.refreshTime = data.getLongExtra("refreshtime",mFragment!!.refreshTime)
}
}
}
| apache-2.0 | 064d8cbf87d7460db8c4b1fa6bf39867 | 40.045455 | 115 | 0.676264 | 4.961538 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/PerdaoCommand.kt | 1 | 1768 | package net.perfectdreams.loritta.morenitta.commands.vanilla.images
import net.perfectdreams.loritta.morenitta.commands.AbstractCommand
import net.perfectdreams.loritta.morenitta.commands.CommandContext
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.perfectdreams.loritta.morenitta.api.commands.Command
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
import net.perfectdreams.loritta.morenitta.LorittaBot
class PerdaoCommand(loritta: LorittaBot) : AbstractCommand(loritta, "perdao", listOf("perdão"), net.perfectdreams.loritta.common.commands.CommandCategory.IMAGES) {
companion object {
val TEMPLATE by lazy { ImageIO.read(File(Constants.ASSETS_FOLDER, "perdao.png")) }
}
override fun getDescriptionKey() = LocaleKeyData("commands.command.forgive.description")
override fun getExamplesKey() = Command.SINGLE_IMAGE_EXAMPLES_KEY
// TODO: Fix Usage
override fun needsToUploadFiles(): Boolean {
return true
}
override suspend fun run(context: CommandContext,locale: BaseLocale) {
val contextImage = context.getImageAt(0) ?: run { Constants.INVALID_IMAGE_REPLY.invoke(context); return; }
// RULE OF THREE!!11!
// larguraOriginal - larguraDoContextImage
// alturaOriginal - X
val newHeight = (contextImage.width * TEMPLATE.height) / TEMPLATE.width
val scaledTemplate = TEMPLATE.getScaledInstance(contextImage.width, Math.max(newHeight, 1), BufferedImage.SCALE_SMOOTH)
contextImage.graphics.drawImage(scaledTemplate, 0, contextImage.height - scaledTemplate.getHeight(null), null)
context.sendFile(contextImage, "perdao.png", context.getAsMention(true))
}
} | agpl-3.0 | 453a3c44bbefff7dede13d73343c8a71 | 42.121951 | 163 | 0.804188 | 3.988713 | false | false | false | false |
eugeis/ee | ee-design_json/src/test/kotlin/ee/design/json/JsonToDesignMain.kt | 1 | 904 | package ee.design.json
import ee.design.appendTypes
import org.slf4j.LoggerFactory
import java.nio.file.Paths
object JsonToDesignMain {
private val log = LoggerFactory.getLogger(javaClass)
@JvmStatic
fun main(args: Array<String>) {
val json = JsonToDesign(mutableMapOf(),
mutableMapOf("rel.self" to "Link", "Href" to "Link", "AspectId" to "n.String", "ETag" to "n.String",
"Errors" to "n.String", "TenantId" to "n.String", "TypeId" to "n.String"),
mutableSetOf("AspectId", "ETag", "Errors", "TenantId", "TypeId"))
val alreadyGeneratedTypes = mutableMapOf<String, String>()
val buffer = StringBuffer()
val dslTypes = json.toDslTypes(Paths.get("/home/z000ru5y/dev/s2r/cdm/cdm_schema.json"))
buffer.appendTypes(log, dslTypes, alreadyGeneratedTypes)
log.info(buffer.toString())
}
} | apache-2.0 | 1233da6d7ed7a5b3f57363191ba9c1f9 | 33.807692 | 116 | 0.644912 | 3.674797 | false | false | false | false |
kotlintest/kotlintest | kotest-extensions/kotest-extensions-http/src/commonMain/kotlin/io/kotest/extensions/http/parser.kt | 1 | 1009 | package io.kotest.extensions.http
import io.ktor.client.HttpClient
import io.ktor.client.request.HttpRequestBuilder
import io.ktor.client.request.header
import io.ktor.client.request.request
import io.ktor.client.request.url
import io.ktor.client.statement.HttpResponse
import io.ktor.http.HttpMethod
fun parseHttpRequest(lines: List<String>): HttpRequestBuilder {
val builder = HttpRequestBuilder()
val method = HttpMethod.DefaultMethods.find { lines[0].startsWith(it.value) } ?: HttpMethod.Get
builder.method = method
val url = lines[0].removePrefix(method.value).trim()
builder.url(url)
lines.drop(1).takeWhile { it.isNotBlank() }.map {
val (key, value) = it.split(':')
builder.header(key, value)
}
val body = lines.drop(1).dropWhile { it.isNotBlank() }.joinToString("\n").trim()
builder.body = body
return builder
}
suspend fun runRequest(req: HttpRequestBuilder): HttpResponse {
val client = HttpClient()
return client.request<HttpResponse>(req)
}
| apache-2.0 | 9a25d57f5716126fadb3f461c660ae64 | 28.676471 | 98 | 0.735382 | 3.836502 | false | false | false | false |
FurhatRobotics/example-skills | FortuneTeller/src/main/kotlin/furhatos/app/fortuneteller/gestures/gestures.kt | 1 | 1919 | package furhatos.app.fortuneteller.gestures
import furhatos.gestures.BasicParams
import furhatos.gestures.defineGesture
val cSmile = defineGesture("cSmile") {
frame(0.5, persist = true) {
BasicParams.BLINK_LEFT to 1.0
BasicParams.BLINK_RIGHT to 1.0
}
}
fun rollHead(strength: Double = 1.0, duration: Double = 1.0) =
defineGesture("rollHead") {
frame(0.4, duration) {
BasicParams.NECK_ROLL to strength
}
reset(duration + 0.1)
}
val FallAsleep = defineGesture("FallAsleep") {
frame(0.5, persist = true) {
BasicParams.BLINK_LEFT to 1.0
BasicParams.BLINK_RIGHT to 1.0
}
}
val MySmile = defineGesture("MySmile") {
frame(0.32, 0.72) {
BasicParams.SMILE_CLOSED to 2.0
}
frame(0.2, 0.72) {
BasicParams.BROW_UP_LEFT to 4.0
BasicParams.BROW_UP_RIGHT to 4.0
}
frame(0.16, 0.72) {
BasicParams.BLINK_LEFT to 1.0
BasicParams.BLINK_RIGHT to 0.1
}
reset(1.04)
}
val TripleBlink = defineGesture("TripleBlink") {
frame(0.1, 0.3) {
BasicParams.BLINK_LEFT to 1.0
BasicParams.BLINK_RIGHT to 1.0
}
frame(0.3, 0.5) {
BasicParams.BLINK_LEFT to 0.1
BasicParams.BLINK_RIGHT to 0.1
}
frame(0.5, 0.7) {
BasicParams.BLINK_LEFT to 1.0
BasicParams.BLINK_RIGHT to 1.0
}
frame(0.7, 0.9) {
BasicParams.BLINK_LEFT to 0.1
BasicParams.BLINK_RIGHT to 0.1
BasicParams.BROW_UP_LEFT to 2.0
BasicParams.BROW_UP_RIGHT to 2.0
}
frame(0.9, 1.1) {
BasicParams.BLINK_LEFT to 1.0
BasicParams.BLINK_RIGHT to 1.0
}
frame(1.1, 1.4) {
BasicParams.BLINK_LEFT to 0.1
BasicParams.BLINK_RIGHT to 0.1
}
frame(1.4, 1.5) {
BasicParams.BROW_UP_LEFT to 0
BasicParams.BROW_UP_RIGHT to 0
}
reset(1.5)
} | mit | b4954fae98518f03badd4d4e2877dd31 | 23.935065 | 62 | 0.586764 | 3.269165 | false | false | false | false |
Ph1b/MaterialAudiobookPlayer | app/src/main/kotlin/de/ph1b/audiobook/features/GalleryPicker.kt | 1 | 1084 | package de.ph1b.audiobook.features
import android.app.Activity
import android.content.Intent
import com.bluelinelabs.conductor.Controller
import de.ph1b.audiobook.data.Book2
import de.ph1b.audiobook.features.bookOverview.EditCoverDialogController
import javax.inject.Inject
private const val REQUEST_CODE = 7
class GalleryPicker
@Inject constructor() {
private var pickForBookId: Book2.Id? = null
fun pick(bookId: Book2.Id, controller: Controller) {
pickForBookId = bookId
val intent = Intent(Intent.ACTION_PICK)
.setType("image/*")
controller.startActivityForResult(intent, REQUEST_CODE)
}
fun parse(requestCode: Int, resultCode: Int, data: Intent?): EditCoverDialogController.Arguments? {
if (requestCode != REQUEST_CODE) {
return null
}
return if (resultCode == Activity.RESULT_OK) {
val imageUri = data?.data
val bookId = pickForBookId
if (imageUri == null || bookId == null) {
null
} else {
EditCoverDialogController.Arguments(imageUri, bookId)
}
} else {
null
}
}
}
| lgpl-3.0 | c94f40d0239b65dc17b4bbc83246d7f7 | 26.1 | 101 | 0.702952 | 4.02974 | false | false | false | false |
facebook/litho | litho-testing/src/main/java/com/facebook/litho/testing/ThreadLooperController.kt | 1 | 4058 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho.testing
import android.os.Looper
import com.facebook.litho.ComponentTree
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.BlockingQueue
import org.robolectric.Shadows
import org.robolectric.annotation.LooperMode
import org.robolectric.shadows.ShadowLooper
/**
* Helper class extracting looper functionality from [BackgroundLayoutLooperRule] that can be reused
* in other TestRules
*/
class ThreadLooperController(
val layoutLooper: ShadowLooper =
Shadows.shadowOf(
Whitebox.invokeMethod<Any>(ComponentTree::class.java, "getDefaultLayoutThreadLooper")
as Looper)
) : BaseThreadLooperController {
private lateinit var messageQueue: BlockingQueue<Message>
private var isInitialized = false
override fun init() {
messageQueue = ArrayBlockingQueue(100)
val layoutLooperThread = LayoutLooperThread(layoutLooper, messageQueue)
layoutLooperThread.start()
isInitialized = true
}
override fun clean() {
if (!isInitialized) {
return
}
quitSync()
if (ShadowLooper.looperMode() != LooperMode.Mode.PAUSED) {
layoutLooper.quitUnchecked()
}
isInitialized = false
}
private fun quitSync() {
val semaphore = TimeOutSemaphore(0)
messageQueue.add(Message(MessageType.QUIT, semaphore))
semaphore.acquire()
}
/**
* Runs one task on the background thread, blocking until it completes successfully or throws an
* exception.
*/
override fun runOneTaskSync() {
val semaphore = TimeOutSemaphore(0)
messageQueue.add(Message(MessageType.DRAIN_ONE, semaphore))
semaphore.acquire()
}
/**
* Runs through all tasks on the background thread, blocking until it completes successfully or
* throws an exception.
*/
override fun runToEndOfTasksSync() {
val semaphore = TimeOutSemaphore(0)
messageQueue.add(Message(MessageType.DRAIN_ALL, semaphore))
semaphore.acquire()
}
override fun runToEndOfTasksAsync(): TimeOutSemaphore? {
val semaphore = TimeOutSemaphore(0)
messageQueue.add(Message(MessageType.DRAIN_ALL, semaphore))
return semaphore
}
}
enum class MessageType {
DRAIN_ONE,
DRAIN_ALL,
QUIT
}
class Message constructor(val messageType: MessageType, val semaphore: TimeOutSemaphore)
@SuppressWarnings("CatchGeneralException")
private class LayoutLooperThread(layoutLooper: ShadowLooper, messages: BlockingQueue<Message>) :
Thread(
Runnable {
var keepGoing = true
while (keepGoing) {
val message: Message =
try {
messages.take()
} catch (e: InterruptedException) {
throw RuntimeException(e)
}
try {
when (message.messageType) {
MessageType.DRAIN_ONE -> {
layoutLooper.runOneTask()
message.semaphore.release()
}
MessageType.DRAIN_ALL -> {
layoutLooper.runToEndOfTasks()
message.semaphore.release()
}
MessageType.QUIT -> {
keepGoing = false
message.semaphore.release()
}
}
} catch (e: Exception) {
message.semaphore.setException(e)
message.semaphore.release()
}
}
})
| apache-2.0 | a3e42a00c5245a8cff3a13d14414d2b3 | 29.511278 | 100 | 0.659685 | 4.83671 | false | false | false | false |
facebook/litho | sample/src/main/java/com/facebook/samples/litho/kotlin/bordereffects/NiceColor.kt | 1 | 992 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.samples.litho.kotlin.bordereffects
object NiceColor {
val RED: Int
get() = 0xffee4035.toInt()
val ORANGE: Int
get() = 0xfff37736.toInt()
val YELLOW: Int
get() = 0xfffdf498.toInt()
val GREEN: Int
get() = 0xff7bc043.toInt()
val BLUE: Int
get() = 0xff0392cf.toInt()
val MAGENTA: Int
get() = 0xffba02cf.toInt()
}
| apache-2.0 | 3bd3b08eedb901bf1fcc0a1cbb6379d8 | 25.810811 | 75 | 0.699597 | 3.620438 | false | false | false | false |
square/leakcanary | shark/src/test/java/shark/LeakTraceRenderingTest.kt | 2 | 9521 | package shark
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import shark.FilteringLeakingObjectFinder.LeakingObjectFilter
import shark.HeapObject.HeapInstance
import shark.ReferencePattern.InstanceFieldPattern
import shark.ReferencePattern.StaticFieldPattern
import shark.ValueHolder.ReferenceHolder
import java.io.File
class LeakTraceRenderingTest {
@get:Rule
var testFolder = TemporaryFolder()
private lateinit var hprofFile: File
@Before
fun setUp() {
hprofFile = testFolder.newFile("temp.hprof")
}
@Test fun rendersSimplePath() {
hprofFile.dump {
"GcRoot" clazz {
staticField["leak"] = "Leaking" watchedInstance {}
}
}
val analysis = hprofFile.checkForLeaks<HeapAnalysisSuccess>()
analysis renders """
┬───
│ GC Root: System class
│
├─ GcRoot class
│ Leaking: UNKNOWN
│ ↓ static GcRoot.leak
│ ~~~~
╰→ Leaking instance
Leaking: YES (ObjectWatcher was watching this because its lifecycle has ended)
key = 39efcc1a-67bf-2040-e7ab-3fc9f94731dc
watchDurationMillis = 25000
retainedDurationMillis = 10000
"""
}
@Test fun rendersDeobfuscatedSimplePath() {
hprofFile.dump {
"a" clazz {
staticField["b.c"] = "Leaking" watchedInstance {}
}
}
val proguardMappingText = """
GcRoot -> a:
type leak -> b.c
""".trimIndent()
val reader = ProguardMappingReader(proguardMappingText.byteInputStream(Charsets.UTF_8))
val analysis = hprofFile.checkForLeaks<HeapAnalysisSuccess>(
proguardMapping = reader.readProguardMapping()
)
analysis renders """
┬───
│ GC Root: System class
│
├─ GcRoot class
│ Leaking: UNKNOWN
│ ↓ static GcRoot.leak
│ ~~~~
╰→ Leaking instance
Leaking: YES (ObjectWatcher was watching this because its lifecycle has ended)
key = 39efcc1a-67bf-2040-e7ab-3fc9f94731dc
watchDurationMillis = 25000
retainedDurationMillis = 10000
"""
}
@Test fun rendersLeakingWithReason() {
hprofFile.dump {
"GcRoot" clazz {
staticField["instanceA"] = "ClassA" instance {
field["instanceB"] = "ClassB" instance {
field["leak"] = "Leaking" watchedInstance {}
}
}
}
}
val analysis =
hprofFile.checkForLeaks<HeapAnalysisSuccess>(
objectInspectors = listOf(object : ObjectInspector {
override fun inspect(
reporter: ObjectReporter
) {
reporter.whenInstanceOf("ClassB") {
leakingReasons += "because reasons"
}
}
}), leakingObjectFinder = FilteringLeakingObjectFinder(listOf(LeakingObjectFilter { heapObject ->
heapObject is HeapInstance && heapObject instanceOf "ClassB"
}))
)
analysis renders """
┬───
│ GC Root: System class
│
├─ GcRoot class
│ Leaking: UNKNOWN
│ ↓ static GcRoot.instanceA
│ ~~~~~~~~~
├─ ClassA instance
│ Leaking: UNKNOWN
│ ↓ ClassA.instanceB
│ ~~~~~~~~~
╰→ ClassB instance
Leaking: YES (because reasons)
"""
}
@Test fun rendersLabelsOnAllNodes() {
hprofFile.dump {
"GcRoot" clazz {
staticField["leak"] = "Leaking" watchedInstance {}
}
}
val analysis = hprofFile.checkForLeaks<HeapAnalysisSuccess>(
objectInspectors = listOf(object : ObjectInspector {
override fun inspect(
reporter: ObjectReporter
) {
reporter.labels += "¯\\_(ツ)_/¯"
}
})
)
analysis renders """
┬───
│ GC Root: System class
│
├─ GcRoot class
│ Leaking: UNKNOWN
│ ¯\_(ツ)_/¯
│ ↓ static GcRoot.leak
│ ~~~~
╰→ Leaking instance
Leaking: YES (ObjectWatcher was watching this because its lifecycle has ended)
¯\_(ツ)_/¯
key = 39efcc1a-67bf-2040-e7ab-3fc9f94731dc
watchDurationMillis = 25000
retainedDurationMillis = 10000
"""
}
@Test fun rendersExclusion() {
hprofFile.dump {
"GcRoot" clazz {
staticField["instanceA"] = "ClassA" instance {
field["leak"] = "Leaking" watchedInstance {}
}
}
}
val analysis =
hprofFile.checkForLeaks<HeapAnalysisSuccess>(
referenceMatchers = listOf(
LibraryLeakReferenceMatcher(pattern = InstanceFieldPattern("ClassA", "leak"))
)
)
analysis rendersLibraryLeak """
┬───
│ GC Root: System class
│
├─ GcRoot class
│ Leaking: UNKNOWN
│ ↓ static GcRoot.instanceA
│ ~~~~~~~~~
├─ ClassA instance
│ Leaking: UNKNOWN
│ Library leak match: instance field ClassA#leak
│ ↓ ClassA.leak
│ ~~~~
╰→ Leaking instance
Leaking: YES (ObjectWatcher was watching this because its lifecycle has ended)
key = 39efcc1a-67bf-2040-e7ab-3fc9f94731dc
watchDurationMillis = 25000
retainedDurationMillis = 10000
"""
}
@Test fun rendersRootExclusion() {
hprofFile.dump {
"GcRoot" clazz {
staticField["leak"] = "Leaking" watchedInstance {}
}
}
val analysis =
hprofFile.checkForLeaks<HeapAnalysisSuccess>(
referenceMatchers = listOf(
LibraryLeakReferenceMatcher(pattern = StaticFieldPattern("GcRoot", "leak"))
)
)
analysis rendersLibraryLeak """
┬───
│ GC Root: System class
│
├─ GcRoot class
│ Leaking: UNKNOWN
│ Library leak match: static field GcRoot#leak
│ ↓ static GcRoot.leak
│ ~~~~
╰→ Leaking instance
Leaking: YES (ObjectWatcher was watching this because its lifecycle has ended)
key = 39efcc1a-67bf-2040-e7ab-3fc9f94731dc
watchDurationMillis = 25000
retainedDurationMillis = 10000
"""
}
@Test fun rendersArray() {
hprofFile.dump {
"GcRoot" clazz {
staticField["array"] = objectArray("Leaking" watchedInstance {})
}
}
val analysis =
hprofFile.checkForLeaks<HeapAnalysisSuccess>()
analysis renders """
┬───
│ GC Root: System class
│
├─ GcRoot class
│ Leaking: UNKNOWN
│ ↓ static GcRoot.array
│ ~~~~~
├─ java.lang.Object[] array
│ Leaking: UNKNOWN
│ ↓ Object[0]
│ ~~~
╰→ Leaking instance
Leaking: YES (ObjectWatcher was watching this because its lifecycle has ended)
key = 39efcc1a-67bf-2040-e7ab-3fc9f94731dc
watchDurationMillis = 25000
retainedDurationMillis = 10000
"""
}
@Test fun rendersThread() {
hprofFile.writeJavaLocalLeak(threadClass = "MyThread", threadName = "kroutine")
val analysis =
hprofFile.checkForLeaks<HeapAnalysisSuccess>(
objectInspectors = ObjectInspectors.jdkDefaults
)
analysis renders """
┬───
│ GC Root: Thread object
│
├─ MyThread instance
│ Leaking: UNKNOWN
│ Thread name: 'kroutine'
│ ↓ MyThread<Java Local>
│ ~~~~~~~~~~~~
╰→ Leaking instance
Leaking: YES (ObjectWatcher was watching this because its lifecycle has ended)
key = 39efcc1a-67bf-2040-e7ab-3fc9f94731dc
watchDurationMillis = 25000
retainedDurationMillis = 10000
"""
}
@Test fun renderFieldFromSuperClass() {
hprofFile.dump {
val leakingInstance = "Leaking" watchedInstance {}
val parentClassId =
clazz("com.ParentClass", fields = listOf("leak" to ReferenceHolder::class))
val childClassId = clazz("com.ChildClass", superclassId = parentClassId)
"GcRoot" clazz {
staticField["child"] = instance(childClassId, listOf(leakingInstance))
}
}
val analysis =
hprofFile.checkForLeaks<HeapAnalysisSuccess>()
analysis renders """
┬───
│ GC Root: System class
│
├─ GcRoot class
│ Leaking: UNKNOWN
│ ↓ static GcRoot.child
│ ~~~~~
├─ com.ChildClass instance
│ Leaking: UNKNOWN
│ ↓ ParentClass.leak
│ ~~~~
╰→ Leaking instance
Leaking: YES (ObjectWatcher was watching this because its lifecycle has ended)
key = 39efcc1a-67bf-2040-e7ab-3fc9f94731dc
watchDurationMillis = 25000
retainedDurationMillis = 10000
"""
}
private infix fun HeapAnalysisSuccess.renders(expectedString: String) {
assertThat(applicationLeaks[0].leakTraces.first().toString()).isEqualTo(
expectedString.trimIndent()
)
}
private infix fun HeapAnalysisSuccess.rendersLibraryLeak(expectedString: String) {
assertThat(libraryLeaks[0].leakTraces.first().toString()).isEqualTo(
expectedString.trimIndent()
)
}
}
| apache-2.0 | 08356a272fb71ccdde189184bc892fac | 26.592145 | 105 | 0.595642 | 4.690806 | false | false | false | false |
albertoruibal/karballo | karballo-common/src/main/kotlin/karballo/evaluation/Evaluator.kt | 1 | 2108 | package karballo.evaluation
import karballo.Board
import karballo.Color
import karballo.bitboard.AttacksInfo
import karballo.bitboard.BitboardAttacks
import karballo.util.StringUtils
abstract class Evaluator {
var bbAttacks: BitboardAttacks = BitboardAttacks.getInstance()
/**
* Board evaluator
*/
abstract fun evaluate(b: Board, ai: AttacksInfo): Int
fun formatOE(value: Int): String {
return StringUtils.padLeft(o(value).toString(), 8) + " " + StringUtils.padLeft(e(value).toString(), 8)
}
companion object {
val W = Color.W
val B = Color.B
val NO_VALUE = Short.MAX_VALUE.toInt()
val MATE = 30000
val KNOWN_WIN = 20000
val DRAW = 0
val PAWN_OPENING = 80
val PAWN = 100
val KNIGHT = 325
val BISHOP = 325
val ROOK = 500
val QUEEN = 975
val PIECE_VALUES = intArrayOf(0, PAWN, KNIGHT, BISHOP, ROOK, QUEEN)
val PIECE_VALUES_OE = intArrayOf(0, oe(PAWN_OPENING, PAWN), oe(KNIGHT, KNIGHT), oe(BISHOP, BISHOP), oe(ROOK, ROOK), oe(QUEEN, QUEEN))
val BISHOP_PAIR = oe(50, 50) // Bonus by having two bishops in different colors
val GAME_PHASE_MIDGAME = 1000
val GAME_PHASE_ENDGAME = 0
val NON_PAWN_MATERIAL_ENDGAME_MIN = QUEEN + ROOK
val NON_PAWN_MATERIAL_MIDGAME_MAX = 3 * KNIGHT + 3 * BISHOP + 4 * ROOK + 2 * QUEEN
/**
* Merges two short Opening - Ending values in one int
*/
fun oe(opening: Int, endgame: Int): Int {
return (opening shl 16) + endgame
}
/**
* Get the "Opening" part
*/
fun o(oe: Int): Int {
return oe + 0x8000 shr 16
}
/**
* Get the "Endgame" part
*/
fun e(oe: Int): Int {
return (oe and 0xffff).toShort().toInt()
}
/**
* Shift right each part by factor positions
*/
fun oeShr(factor: Int, oeValue: Int): Int {
return oe(o(oeValue) shr factor, e(oeValue) shr factor)
}
}
} | mit | 599e69701334bac72524fa2e97ec2833 | 27.5 | 141 | 0.570209 | 3.889299 | false | false | false | false |
xfournet/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/fixtures/NavigationBarFixture.kt | 8 | 1867 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.fixtures
import com.intellij.ide.actions.ViewNavigationBarAction
import com.intellij.openapi.actionSystem.ActionManager
import org.fest.swing.core.Robot
import javax.swing.JPanel
class NavigationBarFixture(private val myRobot: Robot, val myPanel: JPanel, private val myIdeFrame: IdeFrameFixture) :
ComponentFixture<NavigationBarFixture, JPanel>(NavigationBarFixture::class.java, myRobot, myPanel) {
private val VIEW_NAV_BAR_ACTION = "ViewNavigationBar"
fun show() {
if (!isShowing()) myIdeFrame.invokeMainMenu(VIEW_NAV_BAR_ACTION)
}
fun hide() {
if (isShowing()) myIdeFrame.invokeMainMenu(VIEW_NAV_BAR_ACTION)
}
fun isShowing(): Boolean {
val action = ActionManager.getInstance().getAction(VIEW_NAV_BAR_ACTION) as ViewNavigationBarAction
return action.isSelected(null)
}
companion object {
fun createNavigationBarFixture(robot: Robot, ideFrame: IdeFrameFixture): NavigationBarFixture {
val navBarPanel = robot.finder()
.find(ideFrame.target()) { component -> component is JPanel && isNavBar(component) } as JPanel
return NavigationBarFixture(robot, navBarPanel, ideFrame)
}
fun isNavBar(navBarPanel: JPanel): Boolean = navBarPanel.name == "navbar"
}
} | apache-2.0 | c5a2a9dc503a039d061cb01ccee7e1c9 | 35.627451 | 118 | 0.750937 | 4.301843 | false | false | false | false |
Kotlin/dokka | buildSrc/src/main/kotlin/org/jetbrains/ValidatePublications.kt | 1 | 3159 | package org.jetbrains
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.ProjectDependency
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.findByType
open class ValidatePublications : DefaultTask() {
init {
group = "verification"
project.tasks.named("check") {
dependsOn(this@ValidatePublications)
}
}
@TaskAction
fun validatePublicationConfiguration() {
project.subprojects.forEach { subProject ->
val publishing = subProject.extensions.findByType<PublishingExtension>() ?: return@forEach
publishing.publications
.filterIsInstance<MavenPublication>()
.filter { it.version == project.dokkaVersion }
.forEach { _ ->
checkProjectDependenciesArePublished(subProject)
subProject.assertPublicationVersion()
}
}
}
private fun checkProjectDependenciesArePublished(project: Project) {
val implementationDependencies = project.findDependenciesByName("implementation")
val apiDependencies = project.findDependenciesByName("api")
val allDependencies = implementationDependencies + apiDependencies
allDependencies
.filterIsInstance<ProjectDependency>()
.forEach { projectDependency ->
val publishing = projectDependency.dependencyProject.extensions.findByType<PublishingExtension>()
?: throw UnpublishedProjectDependencyException(
project = project, dependencyProject = projectDependency.dependencyProject
)
val isPublished = publishing.publications.filterIsInstance<MavenPublication>()
.any { it.version == project.dokkaVersion }
if (!isPublished) {
throw UnpublishedProjectDependencyException(project, projectDependency.dependencyProject)
}
}
}
private fun Project.findDependenciesByName(name: String): Set<Dependency> {
return configurations.findByName(name)?.allDependencies.orEmpty()
}
private fun Project.assertPublicationVersion() {
val versionTypeMatchesPublicationChannels = publicationChannels.all { publicationChannel ->
publicationChannel.acceptedDokkaVersionTypes.any { acceptedVersionType ->
acceptedVersionType == dokkaVersionType
}
}
if (!versionTypeMatchesPublicationChannels) {
throw AssertionError("Wrong version $dokkaVersion for configured publication channels $publicationChannels")
}
}
private class UnpublishedProjectDependencyException(
project: Project, dependencyProject: Project
): GradleException(
"Published project ${project.path} cannot depend on unpublished project ${dependencyProject.path}"
)
}
| apache-2.0 | 1374a3abecb68504ff10900b252f34d6 | 38.987342 | 120 | 0.679012 | 5.93797 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/actions/styling/BlockQuoteAddAction.kt | 1 | 7375 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.actions.styling
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.util.Condition
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.vladsch.md.nav.actions.handlers.util.CaretContextInfo
import com.vladsch.md.nav.actions.styling.util.DisabledConditionBuilder
import com.vladsch.md.nav.psi.element.MdBlockQuote
import com.vladsch.md.nav.psi.element.MdHeaderElement
import com.vladsch.md.nav.psi.util.BlockQuotePrefix
import com.vladsch.md.nav.psi.util.MdPsiImplUtil
import com.vladsch.md.nav.psi.util.MdTokenSets
import com.vladsch.md.nav.psi.util.MdTypes
import com.vladsch.plugin.util.psi.isTypeOf
import com.vladsch.plugin.util.toInt
import kotlin.math.max
class BlockQuoteAddAction : BlockQuoteItemAction() {
override fun getElementCondition(haveSelection: Boolean): Condition<PsiElement> {
//noinspection ReturnOfInnerClass
return Condition { element ->
element.node != null /*&& TokenTypeSets.BLOCK_ELEMENTS.contains(element.node.elementType)*/ && (
haveSelection || (
(element.node.elementType != MdTypes.PARAGRAPH_BLOCK || !MdPsiImplUtil.isFirstIndentedBlock(element, false))
&& !element.isTypeOf(MdTokenSets.LIST_BLOCK_ITEM_ELEMENT_TYPES)
)
)
}
}
override fun canPerformAction(element: PsiElement?, conditionBuilder: DisabledConditionBuilder?): Boolean {
var useElement = element
while (useElement?.node != null && !useElement.isTypeOf(MdTokenSets.BLOCK_ELEMENT_SET)) useElement = useElement.parent
val enabled = useElement?.node != null && useElement.isTypeOf(MdTokenSets.BLOCK_ELEMENT_SET)
conditionBuilder?.and(enabled, if (useElement?.node != null) "Not block element at caret" else "No element at caret")
return enabled
}
override fun performAction(element: PsiElement, editContext: CaretContextInfo, adjustCaret: Boolean) {
if (canPerformAction(element, null)) {
var useElement: PsiElement? = element
while (useElement?.node != null
&& !useElement.isTypeOf(MdTokenSets.BLOCK_ELEMENT_SET)) {
useElement = useElement.parent
}
if (useElement is PsiFile) return
// collapse to the innermost block quote that is a single child
while (useElement != null && useElement.children.size == 1
&& useElement is MdBlockQuote && useElement.lastChild is MdBlockQuote) {
useElement = useElement.lastChild
}
if (useElement == null) return
// append a quote level
val parentPrefixes = MdPsiImplUtil.getBlockPrefixes(useElement.parent, null, editContext)
val elementPrefixes = MdPsiImplUtil.getBlockPrefixes(useElement, parentPrefixes, editContext)
val blockQuotePrefix = BlockQuotePrefix.create(true, ">", ">")
val prefixes =
if (parentPrefixes.last() == elementPrefixes.last()) {
// append block quote at end of prefixes
parentPrefixes.append(blockQuotePrefix).finalizePrefixes(editContext)
} else {
// insert before the elementPrefix
parentPrefixes.append(blockQuotePrefix).append(elementPrefixes.last()).finalizePrefixes(editContext)
}
// only include tail blank line if it is part of the block quote already in existence
val includeTailBlankLine = useElement.node.elementType === MdTypes.BLOCK_QUOTE
val wrappingLines = editContext.lineAppendable
if (useElement.node.elementType == MdTypes.VERBATIM) {
wrappingLines.append(useElement.text)
wrappingLines.removeExtraBlankLines(1, 0)
MdPsiImplUtil.adjustLinePrefix(useElement, wrappingLines, editContext)
} else {
if (useElement is MdHeaderElement) {
wrappingLines.append(useElement.text)
MdPsiImplUtil.adjustLinePrefix(useElement, wrappingLines, editContext)
} else {
for (child in useElement.children) {
val textLines = MdPsiImplUtil.linesForWrapping(child, false, true, true, editContext)
wrappingLines.append(textLines, true)
}
}
}
// Fix: #320
if (wrappingLines.lineCount == 0) {
// no text just prefixes
wrappingLines.append(parentPrefixes.childPrefix)
}
wrappingLines.line()
val isFirstIndentedChild = MdPsiImplUtil.isFirstIndentedBlock(element, false)
val prefixedLines = wrappingLines.copyAppendable()
MdPsiImplUtil.addLinePrefix(prefixedLines, prefixes, isFirstIndentedChild, true)
var caretLine = editContext.caretLine - (editContext.offsetLineNumber(editContext.preEditOffset(useElement.node.startOffset)) ?: 0)
val postEditNodeStart = editContext.postEditNodeStart(useElement.node)
val startOffset = editContext.offsetLineStart(postEditNodeStart) ?: return
var endOffset = editContext.postEditNodeEnd(useElement.node)
if (!includeTailBlankLine) {
val lastLeafChild = MdPsiImplUtil.lastLeafChild(useElement.node)
if (lastLeafChild.elementType === MdTypes.BLANK_LINE) {
// remove the last line
endOffset = editContext.postEditNodeStart(lastLeafChild)
}
}
// FIX: this needs to take unterminated lines into account
if (caretLine >= wrappingLines.lineCountWithPending) {
caretLine = max(0, wrappingLines.lineCountWithPending - 1)
}
val originalPrefixLen = wrappingLines[caretLine].length - wrappingLines[caretLine].length
val finalPrefixLen = prefixedLines[caretLine].length - wrappingLines[caretLine].length
val logPos = editContext.editor.caretModel.primaryCaret.logicalPosition
val prefixedText = prefixedLines.toSequence(editContext.styleSettings.KEEP_BLANK_LINES, true)
editContext.document.replaceString(startOffset, endOffset, prefixedText)
if (adjustCaret) {
editContext.editor.caretModel.primaryCaret.moveToLogicalPosition(LogicalPosition(logPos.line, logPos.column + if (logPos.column >= originalPrefixLen) finalPrefixLen - originalPrefixLen else 0, logPos.leansForward))
if (editContext.editor.caretModel.primaryCaret.hasSelection() || useElement.isTypeOf(MdTokenSets.LIST_BLOCK_ELEMENT_TYPES)) {
val spaceDelta = (editContext.charSequence.safeCharAt(postEditNodeStart + 1) == ' ').toInt()
editContext.editor.caretModel.primaryCaret.setSelection(postEditNodeStart + 1 + spaceDelta, postEditNodeStart + prefixedText.length - (postEditNodeStart - startOffset))
}
}
}
}
}
| apache-2.0 | e012742bc171e8354da700a6ccd5a53c | 50.93662 | 230 | 0.658983 | 5.267857 | false | false | false | false |
quarkusio/quarkus | extensions/panache/hibernate-orm-panache-kotlin/runtime/src/test/kotlin/io/quarkus/hibernate/orm/panache/kotlin/runtime/TestAnalogs.kt | 1 | 6796 | package io.quarkus.hibernate.orm.panache.kotlin.runtime
import io.quarkus.gizmo.Gizmo
import io.quarkus.hibernate.orm.panache.kotlin.PanacheCompanionBase
import io.quarkus.hibernate.orm.panache.kotlin.PanacheEntityBase
import io.quarkus.hibernate.orm.panache.kotlin.PanacheQuery
import io.quarkus.hibernate.orm.panache.kotlin.PanacheRepository
import io.quarkus.panache.common.deployment.ByteCodeType
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassReader.SKIP_CODE
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes
import kotlin.reflect.KClass
import io.quarkus.hibernate.orm.panache.PanacheEntityBase as JavaPanacheEntityBase
import io.quarkus.hibernate.orm.panache.PanacheQuery as JavaPanacheQuery
import io.quarkus.hibernate.orm.panache.PanacheRepository as JavaPanacheRepository
val OBJECT = ByteCodeType(Object::class.java)
class TestAnalogs {
@Test
fun testPanacheQuery() {
compare(map(JavaPanacheQuery::class), map(PanacheQuery::class))
}
@Test
fun testPanacheRepository() {
compare(map(JavaPanacheRepository::class), map(PanacheRepository::class))
}
@Test
fun testPanacheRepositoryBase() {
compare(map(JavaPanacheRepository::class), map(PanacheRepository::class), listOf("findByIdOptional"))
}
@Test
fun testPanacheEntityBase() {
val javaMethods = map(JavaPanacheEntityBase::class).methods
val kotlinMethods = map(PanacheEntityBase::class).methods
val companionMethods = map(
PanacheCompanionBase::class,
ByteCodeType(PanacheEntityBase::class.java)
).methods
val implemented = mutableListOf<Method>()
javaMethods
.forEach {
if (!it.isStatic()) {
if (it in kotlinMethods) {
kotlinMethods -= it
implemented += it
}
} else {
if (it in companionMethods) {
companionMethods -= it
implemented += it
}
}
}
javaMethods.removeIf {
it.name.endsWith("Optional") || it in implemented
}
// methods("javaMethods", javaMethods)
// methods("kotlinMethods", kotlinMethods)
// methods("companionMethods", companionMethods)
assertTrue(javaMethods.isEmpty(), "New methods not implemented: \n${javaMethods.byLine()}")
assertTrue(kotlinMethods.isEmpty(), "Old methods not removed: \n${kotlinMethods.byLine()}")
assertTrue(companionMethods.isEmpty(), "Old methods not removed: \n${companionMethods.byLine()}")
}
private fun map(type: KClass<*>, erasedType: ByteCodeType? = null): AnalogVisitor {
return AnalogVisitor(erasedType).also { node ->
ClassReader(type.bytes()).accept(node, SKIP_CODE)
}
}
private fun KClass<*>.bytes() =
java.classLoader.getResourceAsStream(qualifiedName.toString().replace(".", "/") + ".class")
private fun compare(javaClass: AnalogVisitor, kotlinClass: AnalogVisitor, allowList: List<String> = listOf()) {
val javaMethods = javaClass.methods
val kotlinMethods = kotlinClass.methods
val implemented = mutableListOf<Method>()
javaMethods
.forEach {
if (it in kotlinMethods) {
kotlinMethods -= it
implemented += it
}
}
javaMethods.removeIf {
it.name.endsWith("Optional") ||
it.name in allowList ||
it in implemented
}
// methods("javaMethods", javaMethods)
// methods("kotlinMethods", kotlinMethods)
assertTrue(javaMethods.isEmpty(), "New methods not implemented: \n${javaMethods.byLine()}")
assertTrue(kotlinMethods.isEmpty(), "Old methods not removed: ${kotlinMethods.byLine()}")
}
@Suppress("unused")
private fun methods(label: String, methods: List<Method>) {
println("$label: ")
methods.toSortedSet(compareBy { it.toString() })
.forEach {
println(it)
}
}
}
private fun <E> List<E>.byLine(): String {
val map = map { it.toString() }
return map
.joinToString("\n")
}
class AnalogVisitor(val erasedType: ByteCodeType? = null) : ClassVisitor(Gizmo.ASM_API_VERSION) {
val methods = mutableListOf<Method>()
override fun visitMethod(
access: Int,
name: String,
descriptor: String,
signature: String?,
exceptions: Array<out String>?
): MethodVisitor? {
if (name != "<init>") {
val type = descriptor.substringAfterLast(")").trim()
var parameters = descriptor.substring(
descriptor.indexOf("("),
descriptor.lastIndexOf(")") + 1
)
erasedType?.let { type ->
parameters = parameters.replace(type.descriptor(), OBJECT.descriptor())
}
methods += Method(access, name, type, parameters)
}
return super.visitMethod(access, name, descriptor, signature, exceptions)
}
}
class Method(val access: Int, val name: String, val type: String, val parameters: String) {
fun isStatic() = access.matches(Opcodes.ACC_STATIC)
override fun toString(): String {
return (if (isStatic()) "static " else "") + "fun ${name}$parameters" +
(if (type.isNotBlank()) ": $type" else "") // +
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Method) return false
if (name != other.name) return false
if (parameters != other.parameters) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + type.hashCode()
result = 31 * result + parameters.hashCode()
return result
}
}
fun Int.matches(mask: Int) = (this and mask) == mask
fun Int.accDecode(): List<String> {
val decode: MutableList<String> = ArrayList()
val values: MutableMap<String, Int> = LinkedHashMap()
try {
for (f in Opcodes::class.java.declaredFields) {
if (f.name.startsWith("ACC_")) {
values[f.name] = f.getInt(Opcodes::class.java)
}
}
} catch (e: IllegalAccessException) {
throw RuntimeException(e.message, e)
}
for ((key, value) in values) {
if (this.matches(value)) {
decode.add(key)
}
}
return decode
}
| apache-2.0 | ba9e4dcbb8ed2c98c1e7c243974f846d | 33.323232 | 115 | 0.614479 | 4.735889 | false | true | false | false |
herbeth1u/VNDB-Android | app/src/main/java/com/booboot/vndbandroid/extensions/EditText.kt | 1 | 1353 | package com.booboot.vndbandroid.extensions
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
import android.widget.TextView
import androidx.core.view.isVisible
import com.booboot.vndbandroid.R
import com.google.android.material.textfield.TextInputLayout
fun TextInputLayout.showCustomError(message: String, errorView: TextView) = apply {
error = " "
errorView.text = message
errorView.isVisible = true
}
fun TextInputLayout.hideCustomError(errorView: TextView) = apply {
error = null
errorView.isVisible = false
}
fun EditText.setTextChangedListener(onTextChanged: (String) -> Unit): TextWatcher {
val textWatcher = object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(text: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) {
text?.let { onTextChanged(it.toString()) }
}
}
removeTextChangedListener()
setTag(R.id.tagTextWatcher, textWatcher)
addTextChangedListener(textWatcher)
return textWatcher
}
fun EditText.removeTextChangedListener() {
val oldTextWatcher = getTag(R.id.tagTextWatcher) as? TextWatcher
removeTextChangedListener(oldTextWatcher)
} | gpl-3.0 | 79a5c438b6517cbf81d5e856d24d9bcf | 29.088889 | 97 | 0.734664 | 4.586441 | false | false | false | false |
paronos/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/database/models/MangaCategory.kt | 6 | 409 | package eu.kanade.tachiyomi.data.database.models
class MangaCategory {
var id: Long? = null
var manga_id: Long = 0
var category_id: Int = 0
companion object {
fun create(manga: Manga, category: Category): MangaCategory {
val mc = MangaCategory()
mc.manga_id = manga.id!!
mc.category_id = category.id!!
return mc
}
}
}
| apache-2.0 | aa8fdba57f3e09c6e72445060b3a73e0 | 18.47619 | 69 | 0.567237 | 4.09 | false | false | false | false |
http4k/http4k | http4k-contract/src/main/kotlin/org/http4k/contract/openapi/v2/OpenApi2SecurityRenderer.kt | 1 | 2213 | package org.http4k.contract.openapi.v2
import org.http4k.contract.openapi.Render
import org.http4k.contract.openapi.RenderModes
import org.http4k.contract.openapi.SecurityRenderer
import org.http4k.contract.openapi.rendererFor
import org.http4k.contract.security.ApiKeySecurity
import org.http4k.contract.security.BasicAuthSecurity
import org.http4k.contract.security.ImplicitOAuthSecurity
/**
* Compose the supported Security models
*/
val OpenApi2SecurityRenderer = SecurityRenderer(ApiKeySecurity.renderer, BasicAuthSecurity.renderer, ImplicitOAuthSecurity.renderer)
val ApiKeySecurity.Companion.renderer
get() = rendererFor<ApiKeySecurity<*>> {
object : RenderModes {
override fun <NODE> full(): Render<NODE> = {
obj(it.name to obj(
"type" to string("apiKey"),
"in" to string(it.param.meta.location),
"name" to string(it.param.meta.name)
))
}
override fun <NODE> ref(): Render<NODE> = { obj(it.name to array(emptyList())) }
}
}
val BasicAuthSecurity.Companion.renderer
get() = rendererFor<BasicAuthSecurity> {
object : RenderModes {
override fun <NODE> full(): Render<NODE> = {
obj(it.name to obj(
"type" to string("basic")
))
}
override fun <NODE> ref(): Render<NODE> = { obj(it.name to array(emptyList())) }
}
}
val ImplicitOAuthSecurity.Companion.renderer
get() = rendererFor<ImplicitOAuthSecurity> {
object : RenderModes {
override fun <NODE> full(): Render<NODE> = {
obj(it.name to
obj(
listOfNotNull(
"type" to string("oauth2"),
"flow" to string("implicit"),
"authorizationUrl" to string(it.authorizationUrl.toString())
) + it.extraFields.map { it.key to string(it.value) }
)
)
}
override fun <NODE> ref(): Render<NODE> = { obj(it.name to array(emptyList())) }
}
}
| apache-2.0 | 2d9a443965d91dce4a0dacca30507398 | 35.278689 | 132 | 0.572526 | 4.417166 | false | false | false | false |
http4k/http4k | http4k-format/moshi/src/main/kotlin/org/http4k/format/adapters.kt | 1 | 2277 | package org.http4k.format
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import org.http4k.events.Event
import java.lang.reflect.Type
import kotlin.reflect.KClass
/**
* Convenience class to create Moshi Adapter Factory
*/
open class SimpleMoshiAdapterFactory(vararg typesToAdapters: Pair<String, (Moshi) -> JsonAdapter<*>>) :
JsonAdapter.Factory {
private val mappings = typesToAdapters.toMap()
override fun create(type: Type, annotations: Set<Annotation>, moshi: Moshi) =
mappings[Types.getRawType(type).typeName]?.let { it(moshi) }
}
/**
* Convenience function to create Moshi Adapter.
*/
inline fun <reified T : JsonAdapter<K>, reified K> adapter(noinline fn: (Moshi) -> T) = K::class.java.name to fn
/**
* Convenience function to create Moshi Adapter Factory for a simple Moshi Adapter
*/
inline fun <reified K> JsonAdapter<K>.asFactory() = SimpleMoshiAdapterFactory(K::class.java.name to { this })
/**
* Convenience function to add a custom adapter.
*/
inline fun <reified T : JsonAdapter<K>, reified K> Moshi.Builder.addTyped(fn: T): Moshi.Builder =
add(K::class.java, fn)
/**
* This adapter factory will capture ALL instances of a particular superclass/interface.
*/
abstract class IsAnInstanceOfAdapter<T : Any>(private val clazz: KClass<T>): JsonAdapter.Factory {
override fun create(type: Type, annotations: Set<Annotation>, moshi: Moshi) =
with(Types.getRawType(type)) {
when {
isA(clazz.java) -> moshi.adapter(clazz.java)
else -> null
}
}
private fun Class<*>?.isA(testCase: Class<*>): Boolean =
this?.let { testCase != this && testCase.isAssignableFrom(this) } ?: false
}
/**
* These adapters are the edge case adapters for dealing with Moshi
*/
object ThrowableAdapter : IsAnInstanceOfAdapter<Throwable>(Throwable::class)
object MapAdapter : IsAnInstanceOfAdapter<Map<*, *>>(Map::class)
object ListAdapter : IsAnInstanceOfAdapter<List<*>>(List::class)
object EventAdapter : JsonAdapter.Factory {
override fun create(p0: Type, p1: MutableSet<out Annotation>, p2: Moshi) =
if (p0.typeName == Event::class.java.typeName) p2.adapter(Any::class.java) else null
}
| apache-2.0 | a4d1659e89f4ad5070cff9ca0941e2b8 | 32.985075 | 112 | 0.703996 | 3.939446 | false | false | false | false |
http4k/http4k | src/docs/guide/reference/clients/example_http.kt | 1 | 1643 | package guide.reference.clients
import org.apache.hc.client5.http.config.RequestConfig
import org.apache.hc.client5.http.cookie.StandardCookieSpec
import org.apache.hc.client5.http.impl.classic.HttpClients
import org.http4k.client.ApacheAsyncClient
import org.http4k.client.ApacheClient
import org.http4k.core.BodyMode
import org.http4k.core.Method.GET
import org.http4k.core.Request
import kotlin.concurrent.thread
fun main() {
// standard client
val client = ApacheClient()
val request = Request(GET, "http://httpbin.org/get").query("location", "John Doe")
val response = client(request)
println("SYNC")
println(response.status)
println(response.bodyString())
// streaming client
val streamingClient = ApacheClient(responseBodyMode = BodyMode.Stream)
val streamingRequest = Request(GET, "http://httpbin.org/stream/100")
println("STREAM")
println(streamingClient(streamingRequest).bodyString())
// async supporting clients can be passed a callback...
val asyncClient = ApacheAsyncClient()
asyncClient(Request(GET, "http://httpbin.org/stream/5")) {
println("ASYNC")
println(it.status)
println(it.bodyString())
}
// ... but must be closed
thread {
Thread.sleep(500)
asyncClient.close()
}
// custom configured client
val customClient = ApacheClient(
client = HttpClients.custom().setDefaultRequestConfig(
RequestConfig.custom()
.setRedirectsEnabled(false)
.setCookieSpec(StandardCookieSpec.IGNORE)
.build()
)
.build()
)
}
| apache-2.0 | 335ddafef8ca724517e8650340926fdb | 30 | 86 | 0.682897 | 4.180662 | false | true | false | false |
premisedata/cameraview | demo/src/main/kotlin/com/otaliastudios/cameraview/demo/CameraActivity.kt | 1 | 14325 | package com.otaliastudios.cameraview.demo
import android.animation.ValueAnimator
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.graphics.*
import android.os.Bundle
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.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.otaliastudios.cameraview.*
import com.otaliastudios.cameraview.controls.Facing
import com.otaliastudios.cameraview.controls.Mode
import com.otaliastudios.cameraview.controls.Preview
import com.otaliastudios.cameraview.filter.Filters
import com.otaliastudios.cameraview.frame.Frame
import com.otaliastudios.cameraview.frame.FrameProcessor
import java.io.ByteArrayOutputStream
import java.io.File
import java.util.*
class CameraActivity : AppCompatActivity(), View.OnClickListener, OptionView.Callback {
companion object {
private val LOG = CameraLogger.create("DemoApp")
private const val USE_FRAME_PROCESSOR = false
private const val DECODE_BITMAP = false
}
private val camera: CameraView by lazy { findViewById(R.id.camera) }
private val controlPanel: ViewGroup by lazy { findViewById(R.id.controls) }
private var captureTime: Long = 0
private var currentFilter = 0
private val allFilters = Filters.values()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_camera)
CameraLogger.setLogLevel(CameraLogger.LEVEL_VERBOSE)
camera.setLifecycleOwner(this)
camera.addCameraListener(Listener())
if (USE_FRAME_PROCESSOR) {
camera.addFrameProcessor(object : FrameProcessor {
private var lastTime = System.currentTimeMillis()
override fun process(frame: Frame) {
val newTime = frame.time
val delay = newTime - lastTime
lastTime = newTime
LOG.v("Frame delayMillis:", delay, "FPS:", 1000 / delay)
if (DECODE_BITMAP) {
if (frame.format == ImageFormat.NV21
&& frame.dataClass == ByteArray::class.java) {
val data = frame.getData<ByteArray>()
val yuvImage = YuvImage(data,
frame.format,
frame.size.width,
frame.size.height,
null)
val jpegStream = ByteArrayOutputStream()
yuvImage.compressToJpeg(Rect(0, 0,
frame.size.width,
frame.size.height), 100, jpegStream)
val jpegByteArray = jpegStream.toByteArray()
val bitmap = BitmapFactory.decodeByteArray(jpegByteArray,
0, jpegByteArray.size)
bitmap.toString()
}
}
}
})
}
findViewById<View>(R.id.edit).setOnClickListener(this)
findViewById<View>(R.id.capturePicture).setOnClickListener(this)
findViewById<View>(R.id.capturePictureSnapshot).setOnClickListener(this)
findViewById<View>(R.id.captureVideo).setOnClickListener(this)
findViewById<View>(R.id.captureVideoSnapshot).setOnClickListener(this)
findViewById<View>(R.id.toggleCamera).setOnClickListener(this)
findViewById<View>(R.id.changeFilter).setOnClickListener(this)
val group = controlPanel.getChildAt(0) as ViewGroup
val watermark = findViewById<View>(R.id.watermark)
val options: List<Option<*>> = listOf(
// Layout
Option.Width(), Option.Height(),
// Engine and preview
Option.Mode(), Option.Engine(), Option.Preview(),
// Some controls
Option.Flash(), Option.WhiteBalance(), Option.Hdr(),
Option.PictureMetering(), Option.PictureSnapshotMetering(),
Option.PictureFormat(),
// Video recording
Option.PreviewFrameRate(), Option.VideoCodec(), Option.Audio(), Option.AudioCodec(),
// Gestures
Option.Pinch(), Option.HorizontalScroll(), Option.VerticalScroll(),
Option.Tap(), Option.LongTap(),
// Watermarks
Option.OverlayInPreview(watermark),
Option.OverlayInPictureSnapshot(watermark),
Option.OverlayInVideoSnapshot(watermark),
// Frame Processing
Option.FrameProcessingFormat(),
// Other
Option.Grid(), Option.GridColor(), Option.UseDeviceOrientation()
)
val dividers = listOf(
// Layout
false, true,
// Engine and preview
false, false, true,
// Some controls
false, false, false, false, false, true,
// Video recording
false, false, false, true,
// Gestures
false, false, false, false, true,
// Watermarks
false, false, true,
// Frame Processing
true,
// Other
false, false, true
)
for (i in options.indices) {
val view = OptionView<Any>(this)
view.setOption(options[i] as Option<Any>, this)
view.setHasDivider(dividers[i])
group.addView(view, MATCH_PARENT, WRAP_CONTENT)
}
controlPanel.viewTreeObserver.addOnGlobalLayoutListener {
BottomSheetBehavior.from(controlPanel).state = BottomSheetBehavior.STATE_HIDDEN
}
// Animate the watermark just to show we record the animation in video snapshots
val animator = ValueAnimator.ofFloat(1f, 0.8f)
animator.duration = 300
animator.repeatCount = ValueAnimator.INFINITE
animator.repeatMode = ValueAnimator.REVERSE
animator.addUpdateListener { animation ->
val scale = animation.animatedValue as Float
watermark.scaleX = scale
watermark.scaleY = scale
watermark.rotation = watermark.rotation + 2
}
animator.start()
}
private fun message(content: String, important: Boolean) {
if (important) {
LOG.w(content)
Toast.makeText(this, content, Toast.LENGTH_LONG).show()
} else {
LOG.i(content)
Toast.makeText(this, content, Toast.LENGTH_SHORT).show()
}
}
private inner class Listener : CameraListener() {
override fun onCameraOpened(options: CameraOptions) {
val group = controlPanel.getChildAt(0) as ViewGroup
for (i in 0 until group.childCount) {
val view = group.getChildAt(i) as OptionView<*>
view.onCameraOpened(camera, options)
}
}
override fun onCameraError(exception: CameraException) {
super.onCameraError(exception)
message("Got CameraException #" + exception.reason, true)
}
override fun onPictureTaken(result: PictureResult) {
super.onPictureTaken(result)
if (camera.isTakingVideo) {
message("Captured while taking video. Size=" + result.size, false)
return
}
// This can happen if picture was taken with a gesture.
val callbackTime = System.currentTimeMillis()
if (captureTime == 0L) captureTime = callbackTime - 300
LOG.w("onPictureTaken called! Launching activity. Delay:", callbackTime - captureTime)
PicturePreviewActivity.pictureResult = result
val intent = Intent(this@CameraActivity, PicturePreviewActivity::class.java)
intent.putExtra("delay", callbackTime - captureTime)
startActivity(intent)
captureTime = 0
LOG.w("onPictureTaken called! Launched activity.")
}
override fun onVideoTaken(result: VideoResult) {
super.onVideoTaken(result)
LOG.w("onVideoTaken called! Launching activity.")
VideoPreviewActivity.videoResult = result
val intent = Intent(this@CameraActivity, VideoPreviewActivity::class.java)
startActivity(intent)
LOG.w("onVideoTaken called! Launched activity.")
}
override fun onVideoRecordingStart() {
super.onVideoRecordingStart()
LOG.w("onVideoRecordingStart!")
}
override fun onVideoRecordingEnd() {
super.onVideoRecordingEnd()
message("Video taken. Processing...", false)
LOG.w("onVideoRecordingEnd!")
}
override fun onExposureCorrectionChanged(newValue: Float, bounds: FloatArray, fingers: Array<PointF>?) {
super.onExposureCorrectionChanged(newValue, bounds, fingers)
message("Exposure correction:$newValue", false)
}
override fun onZoomChanged(newValue: Float, bounds: FloatArray, fingers: Array<PointF>?) {
super.onZoomChanged(newValue, bounds, fingers)
message("Zoom:$newValue", false)
}
}
override fun onClick(view: View) {
when (view.id) {
R.id.edit -> edit()
R.id.capturePicture -> capturePicture()
R.id.capturePictureSnapshot -> capturePictureSnapshot()
R.id.captureVideo -> captureVideo()
R.id.captureVideoSnapshot -> captureVideoSnapshot()
R.id.toggleCamera -> toggleCamera()
R.id.changeFilter -> changeCurrentFilter()
}
}
override fun onBackPressed() {
val b = BottomSheetBehavior.from(controlPanel)
if (b.state != BottomSheetBehavior.STATE_HIDDEN) {
b.state = BottomSheetBehavior.STATE_HIDDEN
return
}
super.onBackPressed()
}
private fun edit() {
BottomSheetBehavior.from(controlPanel).state = BottomSheetBehavior.STATE_COLLAPSED
}
private fun capturePicture() {
if (camera.mode == Mode.VIDEO) return run {
message("Can't take HQ pictures while in VIDEO mode.", false)
}
if (camera.isTakingPicture) return
captureTime = System.currentTimeMillis()
message("Capturing picture...", false)
camera.takePicture()
}
private fun capturePictureSnapshot() {
if (camera.isTakingPicture) return
if (camera.preview != Preview.GL_SURFACE) return run {
message("Picture snapshots are only allowed with the GL_SURFACE preview.", true)
}
captureTime = System.currentTimeMillis()
message("Capturing picture snapshot...", false)
camera.takePictureSnapshot()
}
private fun captureVideo() {
if (camera.mode == Mode.PICTURE) return run {
message("Can't record HQ videos while in PICTURE mode.", false)
}
if (camera.isTakingPicture || camera.isTakingVideo) return
message("Recording for 5 seconds...", true)
camera.takeVideo(File(filesDir, "video.mp4"), 5000)
}
private fun captureVideoSnapshot() {
if (camera.isTakingVideo) return run {
message("Already taking video.", false)
}
if (camera.preview != Preview.GL_SURFACE) return run {
message("Video snapshots are only allowed with the GL_SURFACE preview.", true)
}
message("Recording snapshot for 5 seconds...", true)
camera.takeVideoSnapshot(File(filesDir, "video.mp4"), 5000)
}
private fun toggleCamera() {
if (camera.isTakingPicture || camera.isTakingVideo) return
when (camera.toggleFacing()) {
Facing.BACK -> message("Switched to back camera!", false)
Facing.FRONT -> message("Switched to front camera!", false)
}
}
private fun changeCurrentFilter() {
if (camera.preview != Preview.GL_SURFACE) return run {
message("Filters are supported only when preview is Preview.GL_SURFACE.", true)
}
if (currentFilter < allFilters.size - 1) {
currentFilter++
} else {
currentFilter = 0
}
val filter = allFilters[currentFilter]
message(filter.toString(), false)
// Normal behavior:
camera.filter = filter.newInstance()
// To test MultiFilter:
// DuotoneFilter duotone = new DuotoneFilter();
// duotone.setFirstColor(Color.RED);
// duotone.setSecondColor(Color.GREEN);
// camera.setFilter(new MultiFilter(duotone, filter.newInstance()));
}
override fun <T : Any> onValueChanged(option: Option<T>, value: T, name: String): Boolean {
if (option is Option.Width || option is Option.Height) {
val preview = camera.preview
val wrapContent = value as Int == WRAP_CONTENT
if (preview == Preview.SURFACE && !wrapContent) {
message("The SurfaceView preview does not support width or height changes. " +
"The view will act as WRAP_CONTENT by default.", true)
return false
}
}
option.set(camera, value)
BottomSheetBehavior.from(controlPanel).state = BottomSheetBehavior.STATE_HIDDEN
message("Changed " + option.name + " to " + name, false)
return true
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String?>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
val valid = grantResults.all { it == PERMISSION_GRANTED }
if (valid && !camera.isOpened) {
camera.open()
}
}
}
| apache-2.0 | 35d5e04584a5195f827e8e1ac702f8e2 | 40.642442 | 116 | 0.601745 | 5.164023 | false | false | false | false |
asarkar/spring | hazelcast-learning/src/main/kotlin/org/asarkar/cache/CacheConfiguration.kt | 1 | 5634 | package org.asarkar.cache
import com.hazelcast.cache.impl.HazelcastServerCachingProvider
import com.hazelcast.client.cache.impl.HazelcastClientCachingProvider
import com.hazelcast.client.config.ClientConfig
import com.hazelcast.config.Config
import com.hazelcast.config.EvictionPolicy
import com.hazelcast.config.NearCacheConfig
import com.hazelcast.core.Hazelcast
import com.hazelcast.core.HazelcastInstance
import org.slf4j.LoggerFactory
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration
import javax.annotation.PreDestroy
import javax.cache.CacheManager
import javax.cache.configuration.FactoryBuilder
import javax.cache.configuration.MutableCacheEntryListenerConfiguration
import javax.cache.configuration.MutableConfiguration
import javax.cache.event.CacheEntryCreatedListener
import javax.cache.event.CacheEntryEvent
import javax.cache.expiry.AccessedExpiryPolicy
import javax.cache.expiry.Duration
@Configuration
@ComponentScan
class CacheConfiguration {
@Configuration
@ConditionalOnProperty("KUBERNETES_SERVICE_HOST")
class ClientCacheConfiguration {
private val logger = LoggerFactory.getLogger(ClientCacheConfiguration::class.java)
init {
logger.info("Hazelcast running in client mode")
}
@Bean
fun hazelcastClientConfig(): ClientConfig {
return ClientConfig().apply {
networkConfig.kubernetesConfig
.setEnabled(true)
.setProperty("service-dns", "hazelcast.default.svc.cluster.local")
val ncc = getNearCacheConfig(RandApp.RAND_CACHE) ?: NearCacheConfig(RandApp.RAND_CACHE)
// This is useful when the in-memory format of the Near Cache is different from the backing data structure.
// This setting has no meaning on Hazelcast clients, since they have no local entries.
ncc.isCacheLocalEntries = false
ncc.evictionConfig.evictionPolicy = EvictionPolicy.LRU
ncc.evictionConfig.size = 10
// When this setting is enabled, a Hazelcast instance with a Near Cache listens for cluster-wide changes
// on the entries of the backing data structure and invalidates its corresponding Near Cache entries.
// Changes done on the local Hazelcast instance always invalidate the Near Cache immediately.
ncc.isInvalidateOnChange = true
addNearCacheConfig(ncc)
setProperty("hazelcast.logging.type", "slf4j")
}
}
@Bean
fun jCacheManager(hazelcast: HazelcastInstance): CacheManager {
val cachingProvider = HazelcastClientCachingProvider.createCachingProvider(hazelcast)
return cachingProvider.cacheManager.apply {
createCache(RandApp.RAND_CACHE, cacheConfig(false))
}
}
}
@Configuration
@ConditionalOnProperty(name = ["KUBERNETES_SERVICE_HOST"], matchIfMissing = true)
class ServerCacheConfiguration {
private val logger = LoggerFactory.getLogger(ServerCacheConfiguration::class.java)
init {
logger.info("Hazelcast running in server mode")
}
@PreDestroy
fun shutdown() {
Hazelcast.shutdownAll();
}
@Bean
fun jCacheManager(hazelcast: HazelcastInstance): CacheManager {
val cachingProvider = HazelcastServerCachingProvider.createCachingProvider(hazelcast)
return cachingProvider.cacheManager.apply {
createCache(RandApp.RAND_CACHE, cacheConfig(true))
}
}
@Bean
fun hazelcastConfig(): Config {
return Config().apply {
setProperty("hazelcast.logging.type", "slf4j")
networkConfig.join.multicastConfig.isEnabled = true
networkConfig.join.kubernetesConfig.isEnabled = false
}
}
}
companion object {
fun cacheConfig(server: Boolean): MutableConfiguration<Any, Int> {
return MutableConfiguration<Any, Int>()
.setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(Duration.ONE_MINUTE)).apply {
// Hazelcast Docker container doesn't have listener class on its classpath
if (server) {
addCacheEntryListenerConfiguration(
MutableCacheEntryListenerConfiguration(
FactoryBuilder.factoryOf(
RandCacheEntryCreatedListener()
), null, false, true
)
)
}
}
}
class RandCacheEntryCreatedListener : CacheEntryCreatedListener<Any, Int>, java.io.Serializable {
companion object {
private const val serialVersionUID: Long = 123
private val logger = LoggerFactory.getLogger(RandCacheEntryCreatedListener::class.java)
}
override fun onCreated(events: MutableIterable<CacheEntryEvent<out Any, out Int>>) {
events.forEach(this::logEvent)
}
private fun logEvent(e: CacheEntryEvent<out Any, out Int>) {
logger.info("Cache entry type: {}, key: {}, value: {}", e.eventType, e.key, e.value)
}
}
}
} | gpl-3.0 | 56255b14cecc987d3178c52cce37c4d9 | 41.689394 | 123 | 0.654242 | 5.454017 | false | true | false | false |
czyzby/gdx-setup | src/main/kotlin/com/github/czyzby/setup/data/templates/unofficial/noise4j.kt | 2 | 7131 | package com.github.czyzby.setup.data.templates.unofficial
import com.github.czyzby.setup.data.libs.unofficial.Noise4J
import com.github.czyzby.setup.data.project.Project
import com.github.czyzby.setup.data.templates.Template
import com.github.czyzby.setup.views.ProjectTemplate
@ProjectTemplate
class Noise4JTemplate : Template {
override val id = "noise4jTemplate"
private lateinit var mainClass: String
override val width: String
get() = mainClass + ".SIZE * 2"
override val height: String
get() = mainClass + ".SIZE * 2"
override val description: String
get() = "Project template included simple launchers and an `ApplicationAdapter` extension that draws random maps created using [Noise4J](https://github.com/czyzby/noise4j)."
override fun apply(project: Project) {
mainClass = project.basic.mainClass
super.apply(project)
// Including noise4j dependency:
Noise4J().initiate(project)
}
override fun getApplicationListenerContent(project: Project): String = """package ${project.basic.rootPackage};
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.github.czyzby.noise4j.map.Grid;
import com.github.czyzby.noise4j.map.generator.cellular.CellularAutomataGenerator;
import com.github.czyzby.noise4j.map.generator.noise.NoiseGenerator;
import com.github.czyzby.noise4j.map.generator.room.RoomType.DefaultRoomType;
import com.github.czyzby.noise4j.map.generator.room.dungeon.DungeonGenerator;
import com.github.czyzby.noise4j.map.generator.util.Generators;
/** {@link com.badlogic.gdx.ApplicationListener} implementation shared by all platforms. */
public class ${project.basic.mainClass} extends ApplicationAdapter {
/** Size of the generated maps. */
public static final int SIZE = 200;
private Grid grid = new Grid(SIZE);
private Batch batch;
private Texture texture;
private Pixmap pixmap;
@Override
public void create() {
pixmap = new Pixmap(SIZE, SIZE, Format.RGBA8888);
batch = new SpriteBatch();
// Adding event listener - recreating map on click:
Gdx.input.setInputProcessor(new InputAdapter() {
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
rollMap();
return true;
}
});
// Creating a random map:
rollMap();
}
@Override
public void render() {
Gdx.gl.glClearColor(0f, 0f, 0f, 1f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(texture, 0f, 0f, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.end();
}
@Override
public void dispose() {
batch.dispose();
texture.dispose();
pixmap.dispose();
}
private void rollMap() {
// Clearing all grid values:
grid.set(0f);
// Choosing map generator:
float test = MathUtils.random();
if (test < 0.25f) {
createNoiseMap();
} else if (test < 0.50f) {
createCellularMap();
} else if (test < 0.75f) {
createSimpleDungeonMap();
} else {
createDungeonMap();
}
createTexture();
}
/** Uses NoiseGenerator to create a height map. */
private void createNoiseMap() {
NoiseGenerator noiseGenerator = new NoiseGenerator();
// The first value is the radius, the second is the modifier. Ensuring that the biggest regions have the highest
// modifier allows to generate interesting maps with smooth transitions between regions.
noiseStage(noiseGenerator, 32, 0.45f);
noiseStage(noiseGenerator, 16, 0.25f);
noiseStage(noiseGenerator, 8, 0.15f);
noiseStage(noiseGenerator, 4, 0.1f);
noiseStage(noiseGenerator, 2, 0.05f);
}
private void noiseStage(NoiseGenerator noiseGenerator, int radius, float modifier) {
noiseGenerator.setRadius(radius); // Radius of a single sector.
noiseGenerator.setModifier(modifier); // The max value added to a single cell.
// Seed ensures randomness, can be saved if you feel the need to generate the same map in the future.
noiseGenerator.setSeed(Generators.rollSeed());
noiseGenerator.generate(grid);
}
/** Uses CellularAutomataGenerator to create a cave-like map. */
private void createCellularMap() {
CellularAutomataGenerator cellularGenerator = new CellularAutomataGenerator();
cellularGenerator.setAliveChance(0.5f); // 50% of cells will start as filled.
cellularGenerator.setIterationsAmount(4); // The more iterations, the smoother the map.
cellularGenerator.generate(grid);
}
/** Uses DungeonGenerator to create a simple wall-corridor-room type of map. */
private void createSimpleDungeonMap() {
DungeonGenerator dungeonGenerator = new DungeonGenerator();
dungeonGenerator.setRoomGenerationAttempts(500); // The bigger it is, the more rooms are likely to appear.
dungeonGenerator.setMaxRoomSize(21); // Max room size, should be odd.
dungeonGenerator.setTolerance(5); // Max difference between width and height.
dungeonGenerator.setMinRoomSize(5); // Min room size, should be odd.
dungeonGenerator.generate(grid);
}
/** Uses DungeonGenerator to create a wall-corridor-room type of map with different room types. */
private void createDungeonMap() {
DungeonGenerator dungeonGenerator = new DungeonGenerator();
dungeonGenerator.setRoomGenerationAttempts(500); // The bigger it is, the more rooms are likely to appear.
dungeonGenerator.setMaxRoomSize(25); // Max room size, should be odd.
dungeonGenerator.setTolerance(5); // Max difference between width and height.
dungeonGenerator.setMinRoomSize(9); // Min room size, should be odd.
dungeonGenerator.addRoomTypes(DefaultRoomType.values()); // Adding different room types.
dungeonGenerator.generate(grid);
}
private void createTexture() {
// Destroying previous texture:
if (texture != null) {
texture.dispose();
}
// Drawing on pixmap according to grid's values:
Color color = new Color();
for (int x = 0; x < grid.getWidth(); x++) {
for (int y = 0; y < grid.getHeight(); y++) {
float cell = grid.get(x, y);
color.set(cell, cell, cell, 1f);
pixmap.drawPixel(x, y, Color.rgba8888(color));
}
} // Creating a new texture with the values from pixmap:
texture = new Texture(pixmap);
}
}"""
}
| unlicense | bed020cb34eaadf29252a20f09e7a73e | 40.459302 | 181 | 0.673959 | 4.345521 | false | false | false | false |
GlimpseFramework/glimpse-framework | api/src/main/kotlin/glimpse/Angle.kt | 1 | 2651 | package glimpse
/**
* Two-dimensional angle.
*
* @property deg Angle measure in degrees.
* @property rad Angle measure in radians.
*/
data class Angle private constructor(val deg: Float, val rad: Float) : Comparable<Angle> {
companion object {
/**
* Null angle.
*/
val NULL = Angle(0f, 0f)
/**
* Full angle.
*/
val FULL = Angle(360f, (2.0 * Math.PI).toFloat())
/**
* Straight angle.
*/
val STRAIGHT = FULL / 2f
/**
* Right angle.
*/
val RIGHT = STRAIGHT / 2f
/**
* Creates [Angle] from degrees.
*/
fun fromDeg(deg: Float) = Angle(deg, (deg * Math.PI / 180.0).toFloat())
/**
* Creates [Angle] from radians.
*/
fun fromRad(rad: Float) = Angle((rad * 180.0 / Math.PI).toFloat(), rad)
}
/**
* Returns a string representation of the [Angle].
*/
override fun toString() = "%.1f\u00B0".format(deg)
/**
* Returns an angle opposite to this angle.
*/
operator fun unaryMinus() = Angle(-deg, -rad)
/**
* Returns a sum of this angle and the [other] angle.
*/
operator fun plus(other: Angle) = Angle(deg + other.deg, rad + other.rad)
/**
* Returns a difference of this angle and the [other] angle.
*/
operator fun minus(other: Angle) = Angle(deg - other.deg, rad - other.rad)
/**
* Returns a product of this angle and a [number].
*/
operator fun times(number: Float) = Angle(deg * number, rad * number)
/**
* Returns a quotient of this angle and a [number].
*/
operator fun div(number: Float) = Angle(deg / number, rad / number)
/**
* Returns a quotient of this angle and the [other] angle.
*/
operator fun div(other: Angle) = rad / other.rad
/**
* Returns a remainder of dividing this angle by the [other] angle.
*/
operator fun mod(other: Angle) = (deg % other.deg).degrees
/**
* Returns a range of angles.
*/
operator fun rangeTo(other: Angle) = AnglesRange(this, other)
/**
* Returns an angle coterminal to this angle, closest to [other] angle in clockwise direction.
*/
infix fun clockwiseFrom(other: Angle) =
other - (other - this) % FULL - if (other < this) FULL else NULL
/**
* Returns an angle coterminal to this angle, closest to [other] angle in counter-clockwise direction.
*/
infix fun counterClockwiseFrom(other: Angle) =
other + (this - other) % FULL + if (other > this) FULL else NULL
/**
* Compares this angle to the [other] angle.
*
* Returns zero if this angle is equal to the [other] angle,
* a negative number if it is less than [other],
* or a positive number if it is greater than [other].
*/
override operator fun compareTo(other: Angle) = rad.compareTo(other.rad)
}
| apache-2.0 | ce3b34492ed28399367c874e0dae68b2 | 23.321101 | 103 | 0.63825 | 3.322055 | false | false | false | false |
vilnius/tvarkau-vilniu | app/src/main/java/lt/vilnius/tvarkau/api/ApiError.kt | 1 | 4055 | package lt.vilnius.tvarkau.api
import com.google.gson.FieldNamingPolicy
import com.google.gson.GsonBuilder
import retrofit2.HttpException
import retrofit2.Response
import timber.log.Timber
import java.io.IOException
import java.nio.charset.Charset
class ApiError : RuntimeException {
val errorType: ErrorType
val retrofitResponse: Response<*>?
val validationErrors: List<ApiValidationError>
var responseCode: Int = BaseResponse.REPOSE_CODE_OK
private set
var response: BaseResponse? = null
private set
val httpStatusCode: Int
private var apiMessage: String? = null
constructor(cause: Throwable) : super(cause) {
errorType = ErrorType.SYSTEM
retrofitResponse = null
validationErrors = emptyList()
httpStatusCode = 500
}
constructor(httpException: HttpException) : super(httpException) {
errorType = ErrorType.SERVER
retrofitResponse = httpException.response()
validationErrors = emptyList()
parseApiResponse(httpException)
httpStatusCode = httpException.code()
}
constructor(response: BaseResponse) : super(response.message) {
this.response = response
validationErrors = response.errors
responseCode = response.code
apiMessage = response.message
retrofitResponse = null
errorType = when {
response.isValidationError -> ErrorType.VALIDATION
else -> ErrorType.API
}
this.httpStatusCode = 400
}
private fun parseApiResponse(httpException: HttpException) {
try {
response = extractBaseResponse(httpException)
responseCode = response!!.code
apiMessage = response!!.message
} catch (ignored: RuntimeException) {
val url = httpException.response().raw().request().url()
Timber.w("Failed parse response from url: $url")
}
}
val firstErrorMessage: String?
get() = validationErrors.firstOrNull()?.value ?: apiErrorMessage
val firstValidationErrorField: String
get() = validationErrors.firstOrNull()?.field ?: ""
/**
* @see ErrorType.VALIDATION
*/
val isValidationError: Boolean
get() = errorType == ErrorType.VALIDATION
/**
* @see ErrorType.API
*/
val isApiError: Boolean
get() = errorType == ErrorType.API
/**
* @see ErrorType.SERVER
*/
val isServerError: Boolean
get() = errorType == ErrorType.SERVER
/**
* @see ErrorType.SYSTEM
*/
val isSystemError: Boolean
get() = errorType == ErrorType.SYSTEM
val apiErrorMessage: String?
get() = apiMessage
enum class ErrorType {
/**
* Unexpected IO errors
*/
SYSTEM,
/**
* Unexpected server errors without response body (basically 5xx)
*/
SERVER,
/**
* Api errors (2xx - 4xx) with error body
*/
API,
/**
* Special case of validation Api error
*/
VALIDATION,
}
companion object {
fun extractBaseResponse(httpException: HttpException): BaseResponse {
val body = httpException.response().errorBody() ?: throw IOException("No body")
val source = body.source()
source.request(Long.MAX_VALUE)
val buffer = source.buffer()
val charset = body.contentType()?.charset(UTF_8) ?: UTF_8
val gson = GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create()
return gson.fromJson(buffer.clone().readString(charset), BaseResponse::class.java)
}
fun of(error: Throwable): ApiError {
return when (error) {
is ApiError -> error
is HttpException -> ApiError(error)
else -> ApiError(error)
}
}
val UTF_8: Charset = Charset.forName("UTF-8")
}
}
| mit | 3420c62242b20e81e3cab6602ea44a8f | 26.585034 | 94 | 0.606658 | 5.225515 | false | false | false | false |
tipsy/javalin | javalin-openapi/src/main/java/io/javalin/plugin/openapi/ui/ReDocRenderer.kt | 1 | 1931 | package io.javalin.plugin.openapi.ui
import io.javalin.core.util.OptionalDependency
import io.javalin.core.util.Util
import io.javalin.http.Context
import io.javalin.http.Handler
import io.javalin.plugin.openapi.OpenApiOptions
import io.javalin.plugin.openapi.annotations.OpenApi
class ReDocOptions @JvmOverloads constructor(
path: String,
internal val optionsObject: RedocOptionsObject = RedocOptionsObject()
) : OpenApiUiOptions<ReDocOptions>(path) {
override val defaultTitle = "ReDoc"
}
internal class ReDocRenderer(private val openApiOptions: OpenApiOptions) : Handler {
@OpenApi(ignore = true)
override fun handle(ctx: Context) {
val reDocOptions = openApiOptions.reDoc!!
val docsPath = openApiOptions.getFullDocumentationUrl(ctx)
ctx.html(createReDocHtml(ctx, docsPath, reDocOptions))
}
}
private fun createReDocHtml(ctx: Context, docsPath: String, redocOptions: ReDocOptions): String {
val publicBasePath = Util.getWebjarPublicPath(ctx, OptionalDependency.REDOC)
val options = redocOptions.optionsObject
return """
|<!DOCTYPE html>
|<html>
| <head>
| <title>${redocOptions.createTitle()}</title>
| <!-- Needed for adaptive design -->
| <meta charset="utf-8"/>
| <meta name="viewport" content="width=device-width, initial-scale=1">
| <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
| <!-- ReDoc doesn't change outer page styles -->
| <style>body{margin:0;padding:0;}</style>
| </head>
| <body>
| <redoc id='redoc'></redoc>
| <script src="$publicBasePath/bundles/redoc.standalone.js"></script>
| <script>
| window.onload = () => {
| Redoc.init('$docsPath', ${options.json()}, document.getElementById('redoc'))
| }
| </script>
| </body>
|</html>
|""".trimMargin()
}
| apache-2.0 | 2ed3a470b0bb4c2d69a97519bb67a1bc | 34.109091 | 121 | 0.675816 | 3.643396 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/shop_type/CheckShopType.kt | 1 | 3020 | package de.westnordost.streetcomplete.quests.shop_type
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression
import de.westnordost.streetcomplete.data.meta.*
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.mapdata.Element
import de.westnordost.streetcomplete.data.osm.mapdata.MapDataWithGeometry
import de.westnordost.streetcomplete.data.osm.osmquests.OsmElementQuestType
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.CITIZEN
class CheckShopType : OsmElementQuestType<ShopTypeAnswer> {
private val disusedShops by lazy { """
nodes, ways, relations with (
shop = vacant
or ${isKindOfShopExpression("disused")}
) and (
older today -1 years
or ${LAST_CHECK_DATE_KEYS.joinToString(" or ") { "$it < today -1 years" }}
)
""".toElementFilterExpression() }
/* elements tagged like "shop=ice_cream + disused:amenity=bank" should not appear as quests.
* This is arguably a tagging mistake, but that mistake should not lead to all the tags of
* this element being cleared when the quest is answered */
private val shops by lazy { """
nodes, ways, relations with ${isKindOfShopExpression()}
""".toElementFilterExpression() }
override val commitMessage = "Check if vacant shop is still vacant"
override val wikiLink = "Key:disused:"
override val icon = R.drawable.ic_quest_check_shop
override val questTypeAchievements = listOf(CITIZEN)
override fun getTitle(tags: Map<String, String>) = R.string.quest_shop_vacant_type_title
override fun getApplicableElements(mapData: MapDataWithGeometry): Iterable<Element> =
mapData.filter { isApplicableTo(it) }
override fun isApplicableTo(element: Element): Boolean =
disusedShops.matches(element) && !shops.matches(element)
override fun createForm() = ShopTypeForm()
override fun applyAnswerTo(answer: ShopTypeAnswer, changes: StringMapChangesBuilder) {
when (answer) {
is IsShopVacant -> {
changes.updateCheckDate()
}
is ShopType -> {
changes.deleteCheckDates()
if (!answer.tags.containsKey("shop")) {
changes.deleteIfExists("shop")
}
for ((key, _) in changes.getPreviousEntries()) {
// also deletes all "disused:" keys
val isOkToRemove =
KEYS_THAT_SHOULD_BE_REMOVED_WHEN_SHOP_IS_REPLACED.any { it.matches(key) }
if (isOkToRemove && !answer.tags.containsKey(key)) {
changes.delete(key)
}
}
for ((key, value) in answer.tags) {
changes.addOrModify(key, value)
}
}
}
}
}
| gpl-3.0 | 83cacb06e2f01ddbd8549e3774741c47 | 38.736842 | 97 | 0.646358 | 4.801272 | false | false | false | false |
ben-upsilon/up | up/src/main/java/ben/upsilon/up/done/BlankFragment.kt | 1 | 3250 | package ben.upsilon.up.done
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import ben.upsilon.up.R
/**
* A simple [Fragment] subclass.
* Activities that contain this fragment must implement the
* [BlankFragment.OnFragmentInteractionListener] interface
* to handle interaction events.
* Use the [BlankFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class BlankFragment : Fragment() {
// TODO: Rename and change types of parameters
private var mParam1: String? = null
private var mParam2: String? = null
private var mListener: OnFragmentInteractionListener? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (arguments != null) {
mParam1 = arguments?.getString(ARG_PARAM1)
mParam2 = arguments?.getString(ARG_PARAM2)
}
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
// wtf.text="$mParam1 +++ $mParam2"
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_blank, container, false)
}
// TODO: Rename method, update argument and hook method into UI event
fun onButtonPressed(uri: Uri) {
if (mListener != null) {
mListener!!.onFragmentInteraction(uri)
}
}
override fun onDetach() {
super.onDetach()
mListener = null
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
*
*
* See the Android Training lesson [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) for more information.
*/
interface OnFragmentInteractionListener {
// TODO: Update argument type and name
fun onFragmentInteraction(uri: Uri)
}
companion object {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private val ARG_PARAM1 = "param1"
private val ARG_PARAM2 = "param2"
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
* @param param1 Parameter 1.
* *
* @param param2 Parameter 2.
* *
* @return A new instance of fragment BlankFragment.
*/
// TODO: Rename and change types and number of parameters
fun newInstance(param1: String, param2: String): BlankFragment {
val fragment = BlankFragment()
val args = Bundle()
args.putString(ARG_PARAM1, param1)
args.putString(ARG_PARAM2, param2)
fragment.arguments = args
return fragment
}
}
}// Required empty public constructor
| cc0-1.0 | d6150d7f4ca4ca0da8104c82f54b191b | 31.5 | 172 | 0.666462 | 4.843517 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/text/LiteralTextRenderer.kt | 1 | 3911 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.text
import org.lanternpowered.api.text.BlockDataText
import org.lanternpowered.api.text.EntityDataText
import org.lanternpowered.api.text.KeybindText
import org.lanternpowered.api.text.ScoreText
import org.lanternpowered.api.text.SelectorText
import org.lanternpowered.api.text.StorageDataText
import org.lanternpowered.api.text.Text
import org.lanternpowered.api.text.TranslatableText
import org.lanternpowered.api.text.emptyText
import org.lanternpowered.api.text.literalTextBuilderOf
import org.lanternpowered.api.text.textOf
import org.lanternpowered.api.text.translation.Translator
import org.lanternpowered.api.util.optional.orNull
import java.text.MessageFormat
/**
* A [LanternTextRenderer] that renders all the [Text] components in their literal form.
*/
class LiteralTextRenderer(
private val translator: Translator
) : LanternTextRenderer<FormattedTextRenderContext>() {
override fun renderKeybindIfNeeded(text: KeybindText, context: FormattedTextRenderContext): Text? =
literalTextBuilderOf("[${text.keybind()}]")
.applyStyleAndChildren(text, context).build()
override fun renderSelectorIfNeeded(text: SelectorText, context: FormattedTextRenderContext): Text? =
literalTextBuilderOf(text.pattern())
.applyStyleAndChildren(text, context).build()
override fun renderScoreIfNeeded(text: ScoreText, context: FormattedTextRenderContext): Text? {
val value = text.value()
if (value != null)
return literalTextBuilderOf(value).applyStyleAndChildren(text, context).build()
val scoreboard = context.scoreboard ?: return emptyText()
val objective = scoreboard.getObjective(text.objective()).orNull() ?: return emptyText()
var name = text.name()
// This shows the readers own score
if (name == "*") {
name = context.player?.name ?: ""
if (name.isEmpty())
return emptyText()
}
val score = objective.getScore(textOf(name)).orNull() ?: return emptyText()
return literalTextBuilderOf(score.score.toString()).applyStyleAndChildren(text, context).build()
}
// TODO: Lookup the actual data from the blocks, entities, etc.
override fun renderBlockNbtIfNeeded(text: BlockDataText, context: FormattedTextRenderContext): Text? =
literalTextBuilderOf("[${text.nbtPath()}] @ ${text.pos().asString()}")
.applyStyleAndChildren(text, context).build()
override fun renderEntityNbtIfNeeded(text: EntityDataText, context: FormattedTextRenderContext): Text? =
literalTextBuilderOf("[${text.nbtPath()}] @ ${text.selector()}")
.applyStyleAndChildren(text, context).build()
override fun renderStorageNbtIfNeeded(text: StorageDataText, context: FormattedTextRenderContext): Text? =
literalTextBuilderOf("[${text.nbtPath()}] @ ${text.storage()}")
.applyStyleAndChildren(text, context).build()
override fun renderTranslatableIfNeeded(text: TranslatableText, context: FormattedTextRenderContext): Text? {
val format = this.translate(text.key(), context)
if (format != null)
return super.renderTranslatableIfNeeded(text, context)
return literalTextBuilderOf(text.key())
.applyStyleAndChildren(text, context).build()
}
override fun translate(key: String, context: FormattedTextRenderContext): MessageFormat? =
this.translator.translate(key, context.locale)
}
| mit | 7020a7f0add22ce607b110e8f0b5c791 | 45.559524 | 113 | 0.707747 | 4.88875 | false | false | false | false |
cempo/SimpleTodoList | app/src/main/java/com/makeevapps/simpletodolist/viewmodel/DateTimePickerViewModel.kt | 1 | 2964 | package com.makeevapps.simpletodolist.viewmodel
import android.arch.lifecycle.ViewModel
import android.databinding.ObservableBoolean
import android.databinding.ObservableField
import android.os.Bundle
import com.makeevapps.simpletodolist.App
import com.makeevapps.simpletodolist.Keys.KEY_ALL_DAY
import com.makeevapps.simpletodolist.Keys.KEY_DUE_DATE_IN_MILLIS
import com.makeevapps.simpletodolist.datasource.preferences.PreferenceManager
import com.makeevapps.simpletodolist.utils.DateUtils
import com.makeevapps.simpletodolist.utils.extension.asString
import com.makeevapps.simpletodolist.utils.extension.toEndDay
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.subjects.BehaviorSubject
import java.util.*
import javax.inject.Inject
class DateTimePickerViewModel : ViewModel() {
@Inject
lateinit var preferenceManager: PreferenceManager
val timeText = ObservableField<String>()
val allDay = ObservableBoolean()
internal val calendar: BehaviorSubject<Calendar> = BehaviorSubject.create()
private val compositeDisposable = CompositeDisposable()
private val is24HoursFormat: Boolean
init {
App.component.inject(this)
is24HoursFormat = preferenceManager.is24HourFormat()
compositeDisposable.add(calendar.subscribe({
val timeString = calendar.value.time?.let {
if (is24HoursFormat) {
it.asString(DateUtils.TIME_24H_FORMAT)
} else {
it.asString(DateUtils.TIME_12H_FORMAT)
}
}
timeText.set(timeString)
}))
}
/**
* Init logic
* */
fun initData(arguments: Bundle) {
val longDate = arguments.getLong(KEY_DUE_DATE_IN_MILLIS)
val oldDate = if (longDate > 0) Date(longDate) else null
val allDay = arguments.getBoolean(KEY_ALL_DAY, true)
val tempCalendar = Calendar.getInstance()
if (oldDate != null) {
tempCalendar.time = oldDate
this.allDay.set(allDay)
} else {
tempCalendar.time = DateUtils.endCurrentDayDate()
this.allDay.set(true)
}
calendar.onNext(tempCalendar)
}
fun setDateToCalendar(year: Int, monthOfYear: Int, dayOfMonth: Int) {
val tempCalendar = calendar.value
tempCalendar.set(Calendar.YEAR, year)
tempCalendar.set(Calendar.MONTH, monthOfYear)
tempCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
calendar.onNext(tempCalendar)
}
fun setTimeToCalendar(date: Date?) {
if (date != null) {
val tempCalendar = Calendar.getInstance()
tempCalendar.time = date
calendar.onNext(tempCalendar)
allDay.set(false)
} else {
calendar.onNext(calendar.value.toEndDay())
allDay.set(true)
}
}
override fun onCleared() {
compositeDisposable.clear()
}
} | mit | 73374b73418102e664d3a5eef079fa87 | 31.944444 | 79 | 0.673414 | 4.712242 | false | false | false | false |
AlbRoehm/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/preferences/AuthenticationPreferenceFragment.kt | 1 | 8815 | package com.habitrpg.android.habitica.ui.fragments.preferences
import android.app.ProgressDialog
import android.app.Service
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.DialogInterface
import android.content.SharedPreferences
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
import android.support.v7.preference.EditTextPreference
import android.support.v7.preference.Preference
import android.support.v7.preference.PreferenceCategory
import android.view.LayoutInflater
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.Toast
import com.habitrpg.android.habitica.HabiticaApplication
import com.habitrpg.android.habitica.HabiticaBaseApplication
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.events.commands.OpenGemPurchaseFragmentCommand
import com.habitrpg.android.habitica.extensions.layoutInflater
import com.habitrpg.android.habitica.helpers.QrCodeManager
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.ui.views.subscriptions.SubscriptionDetailsView
import org.greenrobot.eventbus.EventBus
import rx.Observable
import rx.functions.Action1
class AuthenticationPreferenceFragment: BasePreferencesFragment() {
override var user: User? = null
set(value) {
field = value
updateUserFields()
}
override fun onCreate(savedInstanceState: Bundle?) {
HabiticaBaseApplication.getComponent().inject(this)
super.onCreate(savedInstanceState)
}
private fun updateUserFields() {
configurePreference(findPreference("login_name"), user?.authentication?.localAuthentication?.username)
configurePreference(findPreference("email"), user?.authentication?.localAuthentication?.email)
}
private fun configurePreference(preference: Preference?, value: String?) {
preference?.summary = value
}
override fun setupPreferences() {
updateUserFields()
}
override fun onPreferenceTreeClick(preference: Preference): Boolean {
when (preference.key) {
"login_name" -> showLoginNameDialog()
"email" -> showEmailDialog()
"change_password" -> showChangePasswordDialog()
"subscription_status" -> {
if (user != null && user!!.purchased != null && user!!.purchased.plan != null) {
val plan = user!!.purchased.plan
if (plan.isActive) {
showSubscriptionStatusDialog()
return super.onPreferenceTreeClick(preference)
}
}
EventBus.getDefault().post(OpenGemPurchaseFragmentCommand())
}
"reset_account" -> showAccountResetConfirmation()
"delete_account" -> showAccountDeleteConfirmation()
else -> {
val clipMan = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
clipMan.primaryClip = ClipData.newPlainText(preference.key, preference.summary)
Toast.makeText(activity, "Copied " + preference.key + " to clipboard.", Toast.LENGTH_SHORT).show()
}
}
return super.onPreferenceTreeClick(preference)
}
private fun showChangePasswordDialog() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
private fun showEmailDialog() {
val inflater = context.layoutInflater
val view = inflater.inflate(R.layout.dialog_edittext_confirm_pw, null)
val emailEditText = view.findViewById<EditText>(R.id.editText)
emailEditText.setText(user?.authentication?.localAuthentication?.email)
val passwordEditText = view.findViewById<EditText>(R.id.passwordEditText)
val dialog = AlertDialog.Builder(context)
.setTitle(R.string.change_email)
.setPositiveButton(R.string.change) { thisDialog, _ ->
thisDialog.dismiss()
userRepository.updateEmail(emailEditText.text.toString(), passwordEditText.text.toString())
.subscribe(Action1 {
configurePreference(findPreference("email"), emailEditText.text.toString())
}, RxErrorHandler.handleEmptyError())
}
.setNegativeButton(R.string.action_cancel) { thisDialog, _ -> thisDialog.dismiss() }
.create()
dialog.setView(view)
dialog.show()
}
private fun showLoginNameDialog() {
val inflater = context.layoutInflater
val view = inflater.inflate(R.layout.dialog_edittext_confirm_pw, null)
val loginNameEditText = view.findViewById<EditText>(R.id.editText)
loginNameEditText.setText(user?.authentication?.localAuthentication?.username)
val passwordEditText = view.findViewById<EditText>(R.id.passwordEditText)
val dialog = AlertDialog.Builder(context)
.setTitle(R.string.change_login_name)
.setPositiveButton(R.string.change) { thisDialog, _ ->
thisDialog.dismiss()
userRepository.updateLoginName(loginNameEditText.text.toString(), passwordEditText.text.toString())
.subscribe(Action1 {
configurePreference(findPreference("login_name"), loginNameEditText.text.toString())
}, RxErrorHandler.handleEmptyError())
}
.setNegativeButton(R.string.action_cancel) { thisDialog, _ -> thisDialog.dismiss() }
.create()
dialog.setView(view)
dialog.show()
}
private fun showAccountDeleteConfirmation() {
val input = EditText(context)
val lp = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT)
input.layoutParams = lp
val dialog = AlertDialog.Builder(context)
.setTitle(R.string.delete_account)
.setMessage(R.string.delete_account_description)
.setPositiveButton(R.string.delete_account_confirmation) { thisDialog, _ ->
thisDialog.dismiss()
deleteAccount(input.text.toString())
}
.setNegativeButton(R.string.nevermind) { thisDialog, _ -> thisDialog.dismiss() }
.create()
dialog.setOnShowListener { _ -> dialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(context, R.color.red_10)) }
dialog.setView(input)
dialog.show()
}
private fun deleteAccount(password: String) {
val dialog = ProgressDialog.show(context, context.getString(R.string.deleting_account), null, true)
userRepository.deleteAccount(password).subscribe({ _ ->
HabiticaApplication.logout(context)
activity.finish()
}) { throwable ->
dialog.dismiss()
RxErrorHandler.reportError(throwable)
}
}
private fun showAccountResetConfirmation() {
val dialog = AlertDialog.Builder(context)
.setTitle(R.string.reset_account)
.setMessage(R.string.reset_account_description)
.setPositiveButton(R.string.reset_account_confirmation) { thisDialog, _ ->
thisDialog.dismiss()
resetAccount()
}
.setNegativeButton(R.string.nevermind) { thisDialog, _ -> thisDialog.dismiss() }
.create()
dialog.setOnShowListener { _ -> dialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(context, R.color.red_10)) }
dialog.show()
}
private fun resetAccount() {
val dialog = ProgressDialog.show(context, context.getString(R.string.resetting_account), null, true)
userRepository.resetAccount().subscribe({ _ -> dialog.dismiss() }) { throwable ->
dialog.dismiss()
RxErrorHandler.reportError(throwable)
}
}
private fun showSubscriptionStatusDialog() {
val view = SubscriptionDetailsView(context)
view.setPlan(user?.purchased?.plan)
val dialog = AlertDialog.Builder(context)
.setView(view)
.setTitle(R.string.subscription_status)
.setPositiveButton(R.string.close) { dialogInterface, _ -> dialogInterface.dismiss() }.create()
dialog.show()
}
} | gpl-3.0 | a5c0d4eccff92be2fcd9f67183342334 | 44.443299 | 153 | 0.653205 | 5.182246 | false | false | false | false |
noseblowhorn/krog | src/main/kotlin/eu/fizzystuff/krog/scenes/MainScreenScene.kt | 1 | 3619 | package eu.fizzystuff.krog.scenes
import com.google.common.collect.ImmutableList
import com.google.inject.Guice
import com.google.inject.Inject
import com.google.inject.Injector
import com.googlecode.lanterna.input.KeyStroke
import com.googlecode.lanterna.screen.AbstractScreen
import com.googlecode.lanterna.terminal.Terminal
import eu.fizzystuff.krog.main.KrogModule
import eu.fizzystuff.krog.scenes.mainscreen.AddActionPoints
import eu.fizzystuff.krog.scenes.mainscreen.NpcAI
import eu.fizzystuff.krog.scenes.aspects.MainMapDrawingComponent
import eu.fizzystuff.krog.scenes.mainscreen.input.ExitGame
import eu.fizzystuff.krog.scenes.mainscreen.input.PlayerCharacterMovement
import eu.fizzystuff.krog.scenes.visibility.RaycastingVisibilityStrategy
import eu.fizzystuff.krog.model.PlayerCharacter
import eu.fizzystuff.krog.model.WorldState
import eu.fizzystuff.krog.scenes.aspects.MessageBufferDrawingComponent
import eu.fizzystuff.krog.ui.MessageBuffer
class MainScreenScene public @Inject constructor(val injector: Injector,
val mainMapDrawingComponent: MainMapDrawingComponent,
val messageBufferDrawingComponent: MessageBufferDrawingComponent,
val terminal: Terminal,
val messageBuffer: MessageBuffer,
val screen: AbstractScreen) : Scene() {
override fun run(): SceneTransition? {
while(true) {
draw()
acceptInput(terminal.readInput())
val sceneTransition = tick()
if (sceneTransition != null) {
return sceneTransition
}
}
}
override fun destroy() {
}
var inputNodes: List<InputNode> = listOf()
var logicNodes: List<LogicNode> = listOf()
override fun init() {
calculateVisibility()
inputNodes = ImmutableList.of(injector.getInstance(PlayerCharacterMovement::class.java),
injector.getInstance(ExitGame::class.java))
logicNodes = ImmutableList.of(injector.getInstance(AddActionPoints::class.java),
injector.getInstance(NpcAI::class.java))
}
fun draw() {
messageBufferDrawingComponent.draw(0, 0, ImmutableList.of(messageBuffer.poll(80), messageBuffer.poll(80)))
mainMapDrawingComponent.draw(0, 2)
screen.refresh()
}
fun acceptInput(input: KeyStroke): SceneTransition? {
inputNodes.map { x -> x.process(input) }
calculateVisibility()
return null
}
fun tick(): SceneTransition? {
while (true) {
logicNodes.map { x -> x.process() }
if (PlayerCharacter.instance.actionPoints >= PlayerCharacter.instance.actionCost) {
break
}
}
if (messageBuffer.size() > 160) {
return SceneTransition(MainScreenMessageBufferScene::class.java)
}
return null
}
private fun calculateVisibility() {
val visibilityMap = RaycastingVisibilityStrategy().calculateVisibility(WorldState.instance.currentDungeonLevel,
PlayerCharacter.instance.x, PlayerCharacter.instance.y, 4)
for (x in 0..WorldState.instance.currentDungeonLevel.width - 1) {
for (y in 0..WorldState.instance.currentDungeonLevel.height - 1) {
WorldState.instance.currentDungeonLevel.setVisible(x, y, visibilityMap[x][y])
}
}
}
} | apache-2.0 | 50fefe20fcebf4fb0ef74a154c600adf | 35.2 | 119 | 0.647693 | 4.903794 | false | false | false | false |
faceofcat/Tesla-Powered-Thingies | src/main/kotlin/net/ndrei/teslapoweredthingies/common/TeslaFakePlayer.kt | 1 | 1630 | package net.ndrei.teslapoweredthingies.common
import com.mojang.authlib.GameProfile
import net.minecraft.entity.Entity
import net.minecraft.item.ItemStack
import net.minecraft.util.EnumHand
import net.minecraft.world.WorldServer
import net.minecraftforge.common.util.FakePlayer
import java.lang.ref.WeakReference
import java.util.*
class TeslaFakePlayer(world: WorldServer, name: GameProfile) : FakePlayer(world, name) {
fun setItemInUse(stack: ItemStack) {
this.setHeldItem(EnumHand.MAIN_HAND, stack)
this.setHeldItem(EnumHand.OFF_HAND, ItemStack.EMPTY)
this.activeHand = EnumHand.MAIN_HAND
}
fun resetTicksSinceLastSwing() {
this.ticksSinceLastSwing = Int.MAX_VALUE
}
override fun attackTargetEntityWithCurrentItem(targetEntity: Entity?) {
this.resetTicksSinceLastSwing()
super.attackTargetEntityWithCurrentItem(targetEntity)
}
override fun getDistanceSq(x: Double, y: Double, z: Double) = 0.0
override fun getDistance(x: Double, y: Double, z: Double) = 0.0
// override fun getSoundVolume() = 0.0f
companion object {
private val PROFILE = GameProfile(UUID.fromString("225F6E4B-5BAE-4BDA-9B88-2397DEFD95EB"), "[TESLA_THINGIES]")
private var PLAYER: WeakReference<TeslaFakePlayer>? = null
fun getPlayer(world: WorldServer): TeslaFakePlayer {
var ret: TeslaFakePlayer? = if (PLAYER != null) PLAYER!!.get() else null
if (ret == null) {
ret = TeslaFakePlayer(world, PROFILE)
PLAYER = WeakReference(ret)
}
return ret
}
}
}
| mit | d923a35443a6de9d48bccb928d3425af | 34.434783 | 118 | 0.692638 | 4.085213 | false | false | false | false |
faceofcat/Tesla-Powered-Thingies | src/main/kotlin/net/ndrei/teslapoweredthingies/machines/animalfarm/VanillaGenericAnimal.kt | 1 | 3981 | package net.ndrei.teslapoweredthingies.machines.animalfarm
import com.google.common.collect.Lists
import net.minecraft.entity.passive.EntityAnimal
import net.minecraft.entity.passive.EntityCow
import net.minecraft.entity.passive.EntityMooshroom
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.init.Blocks
import net.minecraft.init.Items
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraftforge.common.IShearable
/**
* Created by CF on 2017-07-07.
*/
open class VanillaGenericAnimal(override val animal: EntityAnimal)
: IAnimalWrapper {
override fun breedable(): Boolean {
val animal = this.animal
return !animal.isInLove && !animal.isChild && animal.growingAge == 0
}
override fun isFood(stack: ItemStack): Boolean {
return this.animal.isBreedingItem(stack)
}
override fun canMateWith(wrapper: IAnimalWrapper): Boolean {
return this.breedable() && wrapper.breedable() && this.animal.javaClass == wrapper.animal.javaClass
}
override fun mate(player: EntityPlayer, stack: ItemStack, wrapper: IAnimalWrapper): Int {
val consumedFood: Int
val neededFood = 2 * this.getFoodNeededForMating(stack)
consumedFood = if (stack.count < neededFood) {
0
} else if (!this.canMateWith(wrapper) || !this.isFood(stack)) {
0
} else {
this.animal.setInLove(player)
wrapper.animal.setInLove(player)
neededFood
}
return consumedFood
}
protected open fun getFoodNeededForMating(stack: ItemStack): Int {
return 1
}
override fun shearable(): Boolean {
return this.animal !is EntityMooshroom && this.animal is IShearable
}
override fun canBeShearedWith(stack: ItemStack): Boolean {
if (stack.isEmpty || stack.item !== Items.SHEARS) {
return false
}
var isShearable = false
val animal = this.animal
if (this.shearable() && animal is IShearable) {
val shearable = animal as IShearable
isShearable = shearable.isShearable(stack, animal.entityWorld, animal.position)
}
return isShearable
}
override fun shear(stack: ItemStack, fortune: Int): List<ItemStack> {
var result: List<ItemStack> = Lists.newArrayList<ItemStack>()
val animal = this.animal
if (animal is IShearable) {
val shearable = animal as IShearable
if (shearable.isShearable(stack, animal.entityWorld, animal.position)) {
result = shearable.onSheared(stack, animal.entityWorld, animal.position, fortune)
}
}
return result
}
override fun canBeMilked(): Boolean {
val animal = this.animal
return animal is EntityCow && !animal.isChild
}
override fun milk(): ItemStack {
return if (this.canBeMilked())
ItemStack(Items.MILK_BUCKET, 1)
else
ItemStack.EMPTY
}
override fun canBeBowled(): Boolean {
val animal = this.animal
return animal is EntityMooshroom && !animal.isChild
}
override fun bowl(): ItemStack {
return if (this.canBeBowled())
ItemStack(Items.MUSHROOM_STEW, 1)
else
ItemStack.EMPTY
}
companion object {
fun populateFoodItems(food: MutableList<Item>) {
// cows / mooshrooms
food.add(Items.WHEAT)
// chicken
food.add(Items.WHEAT_SEEDS)
food.add(Items.BEETROOT_SEEDS)
food.add(Items.PUMPKIN_SEEDS)
food.add(Items.MELON_SEEDS)
// pigs
food.add(Items.CARROT)
food.add(Items.POTATO)
food.add(Items.BEETROOT)
food.add(Items.GOLDEN_CARROT)
food.add(Item.getItemFromBlock(Blocks.HAY_BLOCK))
food.add(Items.APPLE)
}
}
}
| mit | 1492b1b761efb0847f5f9418bc23770e | 30.346457 | 107 | 0.62949 | 4.257754 | false | false | false | false |
timusus/Shuttle | app/src/main/java/com/simplecity/amp_library/ui/screens/album/list/AlbumListPresenter.kt | 1 | 2480 | package com.simplecity.amp_library.ui.screens.album.list
import android.annotation.SuppressLint
import com.simplecity.amp_library.data.AlbumsRepository
import com.simplecity.amp_library.model.AlbumArtist
import com.simplecity.amp_library.ui.common.Presenter
import com.simplecity.amp_library.ui.screens.album.list.AlbumListContract.View
import com.simplecity.amp_library.ui.screens.album.menu.AlbumMenuContract
import com.simplecity.amp_library.ui.screens.album.menu.AlbumMenuPresenter
import com.simplecity.amp_library.utils.LogUtils
import com.simplecity.amp_library.utils.sorting.SortManager
import io.reactivex.android.schedulers.AndroidSchedulers
import javax.inject.Inject
class AlbumsPresenter @Inject constructor(
private val albumsRepository: AlbumsRepository,
private val sortManager: SortManager,
private val albumsMenuPresenter: AlbumMenuPresenter
) : Presenter<View>(), AlbumListContract.Presenter, AlbumMenuContract.Presenter by albumsMenuPresenter {
private var albums = mutableListOf<AlbumArtist>()
override fun bindView(view: View) {
super.bindView(view)
albumsMenuPresenter.bindView(view)
}
override fun unbindView(view: View) {
super.unbindView(view)
albumsMenuPresenter.unbindView(view)
}
@SuppressLint("CheckResult")
override fun loadAlbums(scrollToTop: Boolean) {
addDisposable(albumsRepository.getAlbums()
.map { albumArtists ->
val albumArtists = albumArtists.toMutableList()
sortManager.sortAlbums(albumArtists)
if (!sortManager.artistsAscending) {
albumArtists.reverse()
}
albumArtists
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ albumArtists ->
this.albums - albumArtists
view?.setData(albumArtists)
},
{ error -> LogUtils.logException(TAG, "refreshAdapterItems error", error) }
))
}
override fun setAlbumsSortOrder(order: Int) {
sortManager.artistsSortOrder = order
loadAlbums(true)
view?.invalidateOptionsMenu()
}
override fun setAlbumsAscending(ascending: Boolean) {
sortManager.artistsAscending = ascending
loadAlbums(true)
view?.invalidateOptionsMenu()
}
companion object {
const val TAG = "AlbumPresenter"
}
} | gpl-3.0 | 340f9ad02bb01950ff11e424a251bd87 | 33.943662 | 104 | 0.686694 | 4.930417 | false | false | false | false |
googlesamples/mlkit | android/material-showcase/app/src/main/java/com/google/mlkit/md/StaticObjectDetectionActivity.kt | 1 | 16485 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.google.mlkit.md
import android.animation.AnimatorInflater
import android.animation.AnimatorSet
import android.app.Activity
import android.content.Intent
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.PointF
import android.graphics.Rect
import android.graphics.RectF
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.MainThread
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.chip.Chip
import com.google.common.collect.ImmutableList
import com.google.mlkit.md.productsearch.BottomSheetScrimView
import com.google.mlkit.md.objectdetection.DetectedObjectInfo
import com.google.mlkit.md.objectdetection.StaticObjectDotView
import com.google.mlkit.md.productsearch.PreviewCardAdapter
import com.google.mlkit.md.productsearch.Product
import com.google.mlkit.md.productsearch.ProductAdapter
import com.google.mlkit.md.productsearch.SearchEngine
import com.google.mlkit.md.productsearch.SearchedObject
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.objects.defaults.ObjectDetectorOptions
import com.google.mlkit.vision.objects.DetectedObject
import com.google.mlkit.vision.objects.ObjectDetection
import com.google.mlkit.vision.objects.ObjectDetector
import java.io.IOException
import java.lang.NullPointerException
import java.util.TreeMap
/** Demonstrates the object detection and visual search workflow using static image. */
class StaticObjectDetectionActivity : AppCompatActivity(), View.OnClickListener {
private val searchedObjectMap = TreeMap<Int, SearchedObject>()
private var loadingView: View? = null
private var bottomPromptChip: Chip? = null
private var inputImageView: ImageView? = null
private var previewCardCarousel: RecyclerView? = null
private var dotViewContainer: ViewGroup? = null
private var bottomSheetBehavior: BottomSheetBehavior<View>? = null
private var bottomSheetScrimView: BottomSheetScrimView? = null
private var bottomSheetTitleView: TextView? = null
private var productRecyclerView: RecyclerView? = null
private var inputBitmap: Bitmap? = null
private var searchedObjectForBottomSheet: SearchedObject? = null
private var dotViewSize: Int = 0
private var detectedObjectNum = 0
private var currentSelectedObjectIndex = 0
private var detector: ObjectDetector? = null
private var searchEngine: SearchEngine? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
searchEngine = SearchEngine(applicationContext)
setContentView(R.layout.activity_static_object)
loadingView = findViewById<View>(R.id.loading_view).apply {
setOnClickListener(this@StaticObjectDetectionActivity)
}
bottomPromptChip = findViewById(R.id.bottom_prompt_chip)
inputImageView = findViewById(R.id.input_image_view)
previewCardCarousel = findViewById<RecyclerView>(R.id.card_recycler_view).apply {
setHasFixedSize(true)
layoutManager = LinearLayoutManager(this@StaticObjectDetectionActivity, RecyclerView.HORIZONTAL, false)
addItemDecoration(
CardItemDecoration(
resources
)
)
}
dotViewContainer = findViewById(R.id.dot_view_container)
dotViewSize = resources.getDimensionPixelOffset(R.dimen.static_image_dot_view_size)
setUpBottomSheet()
findViewById<View>(R.id.close_button).setOnClickListener(this)
findViewById<View>(R.id.photo_library_button).setOnClickListener(this)
detector = ObjectDetection.getClient(
ObjectDetectorOptions.Builder()
.setDetectorMode(ObjectDetectorOptions.SINGLE_IMAGE_MODE)
.enableMultipleObjects()
.build()
)
intent.data?.let(::detectObjects)
}
override fun onDestroy() {
super.onDestroy()
try {
detector?.close()
} catch (e: IOException) {
Log.e(TAG, "Failed to close the detector!", e)
}
searchEngine?.shutdown()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == Utils.REQUEST_CODE_PHOTO_LIBRARY && resultCode == Activity.RESULT_OK) {
data?.data?.let(::detectObjects)
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
override fun onBackPressed() {
if (bottomSheetBehavior?.state != BottomSheetBehavior.STATE_HIDDEN) {
bottomSheetBehavior?.setState(BottomSheetBehavior.STATE_HIDDEN)
} else {
super.onBackPressed()
}
}
override fun onClick(view: View) {
when (view.id) {
R.id.close_button -> onBackPressed()
R.id.photo_library_button -> Utils.openImagePicker(this)
R.id.bottom_sheet_scrim_view -> bottomSheetBehavior?.state = BottomSheetBehavior.STATE_HIDDEN
}
}
private fun showSearchResults(searchedObject: SearchedObject) {
searchedObjectForBottomSheet = searchedObject
val productList = searchedObject.productList
bottomSheetTitleView?.text = resources
.getQuantityString(
R.plurals.bottom_sheet_title, productList.size, productList.size
)
productRecyclerView?.adapter = ProductAdapter(productList)
bottomSheetBehavior?.peekHeight = (inputImageView?.parent as View).height / 2
bottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
}
private fun setUpBottomSheet() {
bottomSheetBehavior = BottomSheetBehavior.from(findViewById<View>(R.id.bottom_sheet)).apply {
setBottomSheetCallback(
object : BottomSheetBehavior.BottomSheetCallback() {
override fun onStateChanged(bottomSheet: View, newState: Int) {
Log.d(TAG, "Bottom sheet new state: $newState")
bottomSheetScrimView?.visibility =
if (newState == BottomSheetBehavior.STATE_HIDDEN) View.GONE else View.VISIBLE
}
override fun onSlide(bottomSheet: View, slideOffset: Float) {
if (java.lang.Float.isNaN(slideOffset)) {
return
}
val collapsedStateHeight = bottomSheetBehavior!!.peekHeight.coerceAtMost(bottomSheet.height)
val searchedObjectForBottomSheet = searchedObjectForBottomSheet
?: return
bottomSheetScrimView?.updateWithThumbnailTranslate(
searchedObjectForBottomSheet.getObjectThumbnail(),
collapsedStateHeight,
slideOffset,
bottomSheet
)
}
}
)
state = BottomSheetBehavior.STATE_HIDDEN
}
bottomSheetScrimView = findViewById<BottomSheetScrimView>(R.id.bottom_sheet_scrim_view).apply {
setOnClickListener(this@StaticObjectDetectionActivity)
}
bottomSheetTitleView = findViewById(R.id.bottom_sheet_title)
productRecyclerView = findViewById<RecyclerView>(R.id.product_recycler_view)?.apply {
setHasFixedSize(true)
layoutManager = LinearLayoutManager(this@StaticObjectDetectionActivity)
adapter = ProductAdapter(ImmutableList.of())
}
}
private fun detectObjects(imageUri: Uri) {
inputImageView?.setImageDrawable(null)
bottomPromptChip?.visibility = View.GONE
previewCardCarousel?.adapter = PreviewCardAdapter(ImmutableList.of()) { showSearchResults(it) }
previewCardCarousel?.clearOnScrollListeners()
dotViewContainer?.removeAllViews()
currentSelectedObjectIndex = 0
try {
inputBitmap = Utils.loadImage(
this, imageUri,
MAX_IMAGE_DIMENSION
)
} catch (e: IOException) {
Log.e(TAG, "Failed to load file: $imageUri", e)
showBottomPromptChip("Failed to load file!")
return
}
inputImageView?.setImageBitmap(inputBitmap)
loadingView?.visibility = View.VISIBLE
val image = InputImage.fromBitmap(inputBitmap!!, 0)
detector?.process(image)
?.addOnSuccessListener { objects -> onObjectsDetected(BitmapInputInfo(inputBitmap!!), objects) }
?.addOnFailureListener { onObjectsDetected(BitmapInputInfo(inputBitmap!!), ImmutableList.of()) }
}
@MainThread
private fun onObjectsDetected(image: InputInfo, objects: List<DetectedObject>) {
detectedObjectNum = objects.size
Log.d(TAG, "Detected objects num: $detectedObjectNum")
if (detectedObjectNum == 0) {
loadingView?.visibility = View.GONE
showBottomPromptChip(getString(R.string.static_image_prompt_detected_no_results))
} else {
searchedObjectMap.clear()
for (i in objects.indices) {
searchEngine?.search(DetectedObjectInfo(objects[i], i, image)) { detectedObject, products ->
onSearchCompleted(detectedObject, products)
}
}
}
}
private fun onSearchCompleted(detectedObject: DetectedObjectInfo, productList: List<Product>) {
Log.d(TAG, "Search completed for object index: ${detectedObject.objectIndex}")
searchedObjectMap[detectedObject.objectIndex] = SearchedObject(resources, detectedObject, productList)
if (searchedObjectMap.size < detectedObjectNum) {
// Hold off showing the result until the search of all detected objects completes.
return
}
showBottomPromptChip(getString(R.string.static_image_prompt_detected_results))
loadingView?.visibility = View.GONE
previewCardCarousel?.adapter =
PreviewCardAdapter(ImmutableList.copyOf(searchedObjectMap.values)) { showSearchResults(it) }
previewCardCarousel?.addOnScrollListener(
object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
Log.d(TAG, "New card scroll state: $newState")
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
for (i in 0 until recyclerView.childCount) {
val childView = recyclerView.getChildAt(i)
if (childView.x >= 0) {
val cardIndex = recyclerView.getChildAdapterPosition(childView)
if (cardIndex != currentSelectedObjectIndex) {
selectNewObject(cardIndex)
}
break
}
}
}
}
})
for (searchedObject in searchedObjectMap.values) {
val dotView = createDotView(searchedObject)
dotView.setOnClickListener {
if (searchedObject.objectIndex == currentSelectedObjectIndex) {
showSearchResults(searchedObject)
} else {
selectNewObject(searchedObject.objectIndex)
showSearchResults(searchedObject)
previewCardCarousel!!.smoothScrollToPosition(searchedObject.objectIndex)
}
}
dotViewContainer?.addView(dotView)
val animatorSet = AnimatorInflater.loadAnimator(this, R.animator.static_image_dot_enter) as AnimatorSet
animatorSet.setTarget(dotView)
animatorSet.start()
}
}
private fun createDotView(searchedObject: SearchedObject): StaticObjectDotView {
val viewCoordinateScale: Float
val horizontalGap: Float
val verticalGap: Float
val inputImageView = inputImageView ?: throw NullPointerException()
val inputBitmap = inputBitmap ?: throw NullPointerException()
val inputImageViewRatio = inputImageView.width.toFloat() / inputImageView.height
val inputBitmapRatio = inputBitmap.width.toFloat() / inputBitmap.height
if (inputBitmapRatio <= inputImageViewRatio) { // Image content fills height
viewCoordinateScale = inputImageView.height.toFloat() / inputBitmap.height
horizontalGap = (inputImageView.width - inputBitmap.width * viewCoordinateScale) / 2
verticalGap = 0f
} else { // Image content fills width
viewCoordinateScale = inputImageView.width.toFloat() / inputBitmap.width
horizontalGap = 0f
verticalGap = (inputImageView.height - inputBitmap.height * viewCoordinateScale) / 2
}
val boundingBox = searchedObject.boundingBox
val boxInViewCoordinate = RectF(
boundingBox.left * viewCoordinateScale + horizontalGap,
boundingBox.top * viewCoordinateScale + verticalGap,
boundingBox.right * viewCoordinateScale + horizontalGap,
boundingBox.bottom * viewCoordinateScale + verticalGap
)
val initialSelected = searchedObject.objectIndex == 0
val dotView = StaticObjectDotView(this, initialSelected)
val layoutParams = FrameLayout.LayoutParams(dotViewSize, dotViewSize)
val dotCenter = PointF(
(boxInViewCoordinate.right + boxInViewCoordinate.left) / 2,
(boxInViewCoordinate.bottom + boxInViewCoordinate.top) / 2
)
layoutParams.setMargins(
(dotCenter.x - dotViewSize / 2f).toInt(),
(dotCenter.y - dotViewSize / 2f).toInt(),
0,
0
)
dotView.layoutParams = layoutParams
return dotView
}
private fun selectNewObject(objectIndex: Int) {
val dotViewToDeselect = dotViewContainer!!.getChildAt(currentSelectedObjectIndex) as StaticObjectDotView
dotViewToDeselect.playAnimationWithSelectedState(false)
currentSelectedObjectIndex = objectIndex
val selectedDotView = dotViewContainer!!.getChildAt(currentSelectedObjectIndex) as StaticObjectDotView
selectedDotView.playAnimationWithSelectedState(true)
}
private fun showBottomPromptChip(message: String) {
bottomPromptChip?.visibility = View.VISIBLE
bottomPromptChip?.text = message
}
private class CardItemDecoration constructor(resources: Resources) : RecyclerView.ItemDecoration() {
private val cardSpacing: Int = resources.getDimensionPixelOffset(R.dimen.preview_card_spacing)
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val adapterPosition = parent.getChildAdapterPosition(view)
outRect.left = if (adapterPosition == 0) cardSpacing * 2 else cardSpacing
val adapter = parent.adapter ?: return
if (adapterPosition == adapter.itemCount - 1) {
outRect.right = cardSpacing
}
}
}
companion object {
private const val TAG = "StaticObjectActivity"
private const val MAX_IMAGE_DIMENSION = 1024
}
}
| apache-2.0 | e4eb2c9be8d53a7537c175b441ad4724 | 41.929688 | 116 | 0.662117 | 5.554245 | false | false | false | false |
colriot/anko | dsl/testData/functional/sdk15/ViewTest.kt | 2 | 46931 | object `$$Anko$Factories$Sdk15View` {
val GESTURE_OVERLAY_VIEW = { ctx: Context -> android.gesture.GestureOverlayView(ctx) }
val EXTRACT_EDIT_TEXT = { ctx: Context -> android.inputmethodservice.ExtractEditText(ctx) }
val G_L_SURFACE_VIEW = { ctx: Context -> android.opengl.GLSurfaceView(ctx) }
val SURFACE_VIEW = { ctx: Context -> android.view.SurfaceView(ctx) }
val TEXTURE_VIEW = { ctx: Context -> android.view.TextureView(ctx) }
val VIEW = { ctx: Context -> android.view.View(ctx) }
val VIEW_STUB = { ctx: Context -> android.view.ViewStub(ctx) }
val ADAPTER_VIEW_FLIPPER = { ctx: Context -> android.widget.AdapterViewFlipper(ctx) }
val ANALOG_CLOCK = { ctx: Context -> android.widget.AnalogClock(ctx) }
val AUTO_COMPLETE_TEXT_VIEW = { ctx: Context -> android.widget.AutoCompleteTextView(ctx) }
val BUTTON = { ctx: Context -> android.widget.Button(ctx) }
val CALENDAR_VIEW = { ctx: Context -> android.widget.CalendarView(ctx) }
val CHECK_BOX = { ctx: Context -> android.widget.CheckBox(ctx) }
val CHECKED_TEXT_VIEW = { ctx: Context -> android.widget.CheckedTextView(ctx) }
val CHRONOMETER = { ctx: Context -> android.widget.Chronometer(ctx) }
val DATE_PICKER = { ctx: Context -> android.widget.DatePicker(ctx) }
val DIALER_FILTER = { ctx: Context -> android.widget.DialerFilter(ctx) }
val DIGITAL_CLOCK = { ctx: Context -> android.widget.DigitalClock(ctx) }
val EDIT_TEXT = { ctx: Context -> android.widget.EditText(ctx) }
val EXPANDABLE_LIST_VIEW = { ctx: Context -> android.widget.ExpandableListView(ctx) }
val IMAGE_BUTTON = { ctx: Context -> android.widget.ImageButton(ctx) }
val IMAGE_VIEW = { ctx: Context -> android.widget.ImageView(ctx) }
val LIST_VIEW = { ctx: Context -> android.widget.ListView(ctx) }
val MULTI_AUTO_COMPLETE_TEXT_VIEW = { ctx: Context -> android.widget.MultiAutoCompleteTextView(ctx) }
val NUMBER_PICKER = { ctx: Context -> android.widget.NumberPicker(ctx) }
val PROGRESS_BAR = { ctx: Context -> android.widget.ProgressBar(ctx) }
val QUICK_CONTACT_BADGE = { ctx: Context -> android.widget.QuickContactBadge(ctx) }
val RADIO_BUTTON = { ctx: Context -> android.widget.RadioButton(ctx) }
val RATING_BAR = { ctx: Context -> android.widget.RatingBar(ctx) }
val SEARCH_VIEW = { ctx: Context -> android.widget.SearchView(ctx) }
val SEEK_BAR = { ctx: Context -> android.widget.SeekBar(ctx) }
val SLIDING_DRAWER = { ctx: Context -> android.widget.SlidingDrawer(ctx, null) }
val SPACE = { ctx: Context -> android.widget.Space(ctx) }
val SPINNER = { ctx: Context -> android.widget.Spinner(ctx) }
val STACK_VIEW = { ctx: Context -> android.widget.StackView(ctx) }
val SWITCH = { ctx: Context -> android.widget.Switch(ctx) }
val TAB_HOST = { ctx: Context -> android.widget.TabHost(ctx) }
val TAB_WIDGET = { ctx: Context -> android.widget.TabWidget(ctx) }
val TEXT_VIEW = { ctx: Context -> android.widget.TextView(ctx) }
val TIME_PICKER = { ctx: Context -> android.widget.TimePicker(ctx) }
val TOGGLE_BUTTON = { ctx: Context -> android.widget.ToggleButton(ctx) }
val TWO_LINE_LIST_ITEM = { ctx: Context -> android.widget.TwoLineListItem(ctx) }
val VIDEO_VIEW = { ctx: Context -> android.widget.VideoView(ctx) }
val VIEW_FLIPPER = { ctx: Context -> android.widget.ViewFlipper(ctx) }
val ZOOM_BUTTON = { ctx: Context -> android.widget.ZoomButton(ctx) }
val ZOOM_CONTROLS = { ctx: Context -> android.widget.ZoomControls(ctx) }
}
inline fun ViewManager.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView({})
inline fun ViewManager.gestureOverlayView(init: android.gesture.GestureOverlayView.() -> Unit): android.gesture.GestureOverlayView {
return ankoView(`$$Anko$Factories$Sdk15View`.GESTURE_OVERLAY_VIEW) { init() }
}
inline fun Context.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView({})
inline fun Context.gestureOverlayView(init: android.gesture.GestureOverlayView.() -> Unit): android.gesture.GestureOverlayView {
return ankoView(`$$Anko$Factories$Sdk15View`.GESTURE_OVERLAY_VIEW) { init() }
}
inline fun Activity.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView({})
inline fun Activity.gestureOverlayView(init: android.gesture.GestureOverlayView.() -> Unit): android.gesture.GestureOverlayView {
return ankoView(`$$Anko$Factories$Sdk15View`.GESTURE_OVERLAY_VIEW) { init() }
}
inline fun ViewManager.extractEditText(): android.inputmethodservice.ExtractEditText = extractEditText({})
inline fun ViewManager.extractEditText(init: android.inputmethodservice.ExtractEditText.() -> Unit): android.inputmethodservice.ExtractEditText {
return ankoView(`$$Anko$Factories$Sdk15View`.EXTRACT_EDIT_TEXT) { init() }
}
inline fun ViewManager.gLSurfaceView(): android.opengl.GLSurfaceView = gLSurfaceView({})
inline fun ViewManager.gLSurfaceView(init: android.opengl.GLSurfaceView.() -> Unit): android.opengl.GLSurfaceView {
return ankoView(`$$Anko$Factories$Sdk15View`.G_L_SURFACE_VIEW) { init() }
}
inline fun ViewManager.surfaceView(): android.view.SurfaceView = surfaceView({})
inline fun ViewManager.surfaceView(init: android.view.SurfaceView.() -> Unit): android.view.SurfaceView {
return ankoView(`$$Anko$Factories$Sdk15View`.SURFACE_VIEW) { init() }
}
inline fun ViewManager.textureView(): android.view.TextureView = textureView({})
inline fun ViewManager.textureView(init: android.view.TextureView.() -> Unit): android.view.TextureView {
return ankoView(`$$Anko$Factories$Sdk15View`.TEXTURE_VIEW) { init() }
}
inline fun ViewManager.view(): android.view.View = view({})
inline fun ViewManager.view(init: android.view.View.() -> Unit): android.view.View {
return ankoView(`$$Anko$Factories$Sdk15View`.VIEW) { init() }
}
inline fun ViewManager.viewStub(): android.view.ViewStub = viewStub({})
inline fun ViewManager.viewStub(init: android.view.ViewStub.() -> Unit): android.view.ViewStub {
return ankoView(`$$Anko$Factories$Sdk15View`.VIEW_STUB) { init() }
}
inline fun ViewManager.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper({})
inline fun ViewManager.adapterViewFlipper(init: android.widget.AdapterViewFlipper.() -> Unit): android.widget.AdapterViewFlipper {
return ankoView(`$$Anko$Factories$Sdk15View`.ADAPTER_VIEW_FLIPPER) { init() }
}
inline fun Context.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper({})
inline fun Context.adapterViewFlipper(init: android.widget.AdapterViewFlipper.() -> Unit): android.widget.AdapterViewFlipper {
return ankoView(`$$Anko$Factories$Sdk15View`.ADAPTER_VIEW_FLIPPER) { init() }
}
inline fun Activity.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper({})
inline fun Activity.adapterViewFlipper(init: android.widget.AdapterViewFlipper.() -> Unit): android.widget.AdapterViewFlipper {
return ankoView(`$$Anko$Factories$Sdk15View`.ADAPTER_VIEW_FLIPPER) { init() }
}
inline fun ViewManager.analogClock(): android.widget.AnalogClock = analogClock({})
inline fun ViewManager.analogClock(init: android.widget.AnalogClock.() -> Unit): android.widget.AnalogClock {
return ankoView(`$$Anko$Factories$Sdk15View`.ANALOG_CLOCK) { init() }
}
inline fun ViewManager.autoCompleteTextView(): android.widget.AutoCompleteTextView = autoCompleteTextView({})
inline fun ViewManager.autoCompleteTextView(init: android.widget.AutoCompleteTextView.() -> Unit): android.widget.AutoCompleteTextView {
return ankoView(`$$Anko$Factories$Sdk15View`.AUTO_COMPLETE_TEXT_VIEW) { init() }
}
inline fun ViewManager.button(): android.widget.Button = button({})
inline fun ViewManager.button(init: android.widget.Button.() -> Unit): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk15View`.BUTTON) { init() }
}
inline fun ViewManager.button(text: CharSequence?): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk15View`.BUTTON) {
setText(text)
}
}
inline fun ViewManager.button(text: CharSequence?, init: android.widget.Button.() -> Unit): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk15View`.BUTTON) {
init()
setText(text)
}
}
inline fun ViewManager.button(text: Int): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk15View`.BUTTON) {
setText(text)
}
}
inline fun ViewManager.button(text: Int, init: android.widget.Button.() -> Unit): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk15View`.BUTTON) {
init()
setText(text)
}
}
inline fun ViewManager.calendarView(): android.widget.CalendarView = calendarView({})
inline fun ViewManager.calendarView(init: android.widget.CalendarView.() -> Unit): android.widget.CalendarView {
return ankoView(`$$Anko$Factories$Sdk15View`.CALENDAR_VIEW) { init() }
}
inline fun Context.calendarView(): android.widget.CalendarView = calendarView({})
inline fun Context.calendarView(init: android.widget.CalendarView.() -> Unit): android.widget.CalendarView {
return ankoView(`$$Anko$Factories$Sdk15View`.CALENDAR_VIEW) { init() }
}
inline fun Activity.calendarView(): android.widget.CalendarView = calendarView({})
inline fun Activity.calendarView(init: android.widget.CalendarView.() -> Unit): android.widget.CalendarView {
return ankoView(`$$Anko$Factories$Sdk15View`.CALENDAR_VIEW) { init() }
}
inline fun ViewManager.checkBox(): android.widget.CheckBox = checkBox({})
inline fun ViewManager.checkBox(init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) { init() }
}
inline fun ViewManager.checkBox(text: CharSequence?): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) {
setText(text)
}
}
inline fun ViewManager.checkBox(text: CharSequence?, init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) {
init()
setText(text)
}
}
inline fun ViewManager.checkBox(text: Int): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) {
setText(text)
}
}
inline fun ViewManager.checkBox(text: Int, init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) {
init()
setText(text)
}
}
inline fun ViewManager.checkBox(text: CharSequence?, checked: Boolean): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) {
setText(text)
setChecked(checked)
}
}
inline fun ViewManager.checkBox(text: CharSequence?, checked: Boolean, init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) {
init()
setText(text)
setChecked(checked)
}
}
inline fun ViewManager.checkBox(text: Int, checked: Boolean): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) {
setText(text)
setChecked(checked)
}
}
inline fun ViewManager.checkBox(text: Int, checked: Boolean, init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) {
init()
setText(text)
setChecked(checked)
}
}
inline fun ViewManager.checkedTextView(): android.widget.CheckedTextView = checkedTextView({})
inline fun ViewManager.checkedTextView(init: android.widget.CheckedTextView.() -> Unit): android.widget.CheckedTextView {
return ankoView(`$$Anko$Factories$Sdk15View`.CHECKED_TEXT_VIEW) { init() }
}
inline fun ViewManager.chronometer(): android.widget.Chronometer = chronometer({})
inline fun ViewManager.chronometer(init: android.widget.Chronometer.() -> Unit): android.widget.Chronometer {
return ankoView(`$$Anko$Factories$Sdk15View`.CHRONOMETER) { init() }
}
inline fun ViewManager.datePicker(): android.widget.DatePicker = datePicker({})
inline fun ViewManager.datePicker(init: android.widget.DatePicker.() -> Unit): android.widget.DatePicker {
return ankoView(`$$Anko$Factories$Sdk15View`.DATE_PICKER) { init() }
}
inline fun Context.datePicker(): android.widget.DatePicker = datePicker({})
inline fun Context.datePicker(init: android.widget.DatePicker.() -> Unit): android.widget.DatePicker {
return ankoView(`$$Anko$Factories$Sdk15View`.DATE_PICKER) { init() }
}
inline fun Activity.datePicker(): android.widget.DatePicker = datePicker({})
inline fun Activity.datePicker(init: android.widget.DatePicker.() -> Unit): android.widget.DatePicker {
return ankoView(`$$Anko$Factories$Sdk15View`.DATE_PICKER) { init() }
}
inline fun ViewManager.dialerFilter(): android.widget.DialerFilter = dialerFilter({})
inline fun ViewManager.dialerFilter(init: android.widget.DialerFilter.() -> Unit): android.widget.DialerFilter {
return ankoView(`$$Anko$Factories$Sdk15View`.DIALER_FILTER) { init() }
}
inline fun Context.dialerFilter(): android.widget.DialerFilter = dialerFilter({})
inline fun Context.dialerFilter(init: android.widget.DialerFilter.() -> Unit): android.widget.DialerFilter {
return ankoView(`$$Anko$Factories$Sdk15View`.DIALER_FILTER) { init() }
}
inline fun Activity.dialerFilter(): android.widget.DialerFilter = dialerFilter({})
inline fun Activity.dialerFilter(init: android.widget.DialerFilter.() -> Unit): android.widget.DialerFilter {
return ankoView(`$$Anko$Factories$Sdk15View`.DIALER_FILTER) { init() }
}
inline fun ViewManager.digitalClock(): android.widget.DigitalClock = digitalClock({})
inline fun ViewManager.digitalClock(init: android.widget.DigitalClock.() -> Unit): android.widget.DigitalClock {
return ankoView(`$$Anko$Factories$Sdk15View`.DIGITAL_CLOCK) { init() }
}
inline fun ViewManager.editText(): android.widget.EditText = editText({})
inline fun ViewManager.editText(init: android.widget.EditText.() -> Unit): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk15View`.EDIT_TEXT) { init() }
}
inline fun ViewManager.editText(text: CharSequence?): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk15View`.EDIT_TEXT) {
setText(text)
}
}
inline fun ViewManager.editText(text: CharSequence?, init: android.widget.EditText.() -> Unit): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk15View`.EDIT_TEXT) {
init()
setText(text)
}
}
inline fun ViewManager.editText(text: Int): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk15View`.EDIT_TEXT) {
setText(text)
}
}
inline fun ViewManager.editText(text: Int, init: android.widget.EditText.() -> Unit): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk15View`.EDIT_TEXT) {
init()
setText(text)
}
}
inline fun ViewManager.expandableListView(): android.widget.ExpandableListView = expandableListView({})
inline fun ViewManager.expandableListView(init: android.widget.ExpandableListView.() -> Unit): android.widget.ExpandableListView {
return ankoView(`$$Anko$Factories$Sdk15View`.EXPANDABLE_LIST_VIEW) { init() }
}
inline fun Context.expandableListView(): android.widget.ExpandableListView = expandableListView({})
inline fun Context.expandableListView(init: android.widget.ExpandableListView.() -> Unit): android.widget.ExpandableListView {
return ankoView(`$$Anko$Factories$Sdk15View`.EXPANDABLE_LIST_VIEW) { init() }
}
inline fun Activity.expandableListView(): android.widget.ExpandableListView = expandableListView({})
inline fun Activity.expandableListView(init: android.widget.ExpandableListView.() -> Unit): android.widget.ExpandableListView {
return ankoView(`$$Anko$Factories$Sdk15View`.EXPANDABLE_LIST_VIEW) { init() }
}
inline fun ViewManager.imageButton(): android.widget.ImageButton = imageButton({})
inline fun ViewManager.imageButton(init: android.widget.ImageButton.() -> Unit): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_BUTTON) { init() }
}
inline fun ViewManager.imageButton(imageDrawable: android.graphics.drawable.Drawable?): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_BUTTON) {
setImageDrawable(imageDrawable)
}
}
inline fun ViewManager.imageButton(imageDrawable: android.graphics.drawable.Drawable?, init: android.widget.ImageButton.() -> Unit): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_BUTTON) {
init()
setImageDrawable(imageDrawable)
}
}
inline fun ViewManager.imageButton(imageResource: Int): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_BUTTON) {
setImageResource(imageResource)
}
}
inline fun ViewManager.imageButton(imageResource: Int, init: android.widget.ImageButton.() -> Unit): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_BUTTON) {
init()
setImageResource(imageResource)
}
}
inline fun ViewManager.imageView(): android.widget.ImageView = imageView({})
inline fun ViewManager.imageView(init: android.widget.ImageView.() -> Unit): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_VIEW) { init() }
}
inline fun ViewManager.imageView(imageDrawable: android.graphics.drawable.Drawable?): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_VIEW) {
setImageDrawable(imageDrawable)
}
}
inline fun ViewManager.imageView(imageDrawable: android.graphics.drawable.Drawable?, init: android.widget.ImageView.() -> Unit): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_VIEW) {
init()
setImageDrawable(imageDrawable)
}
}
inline fun ViewManager.imageView(imageResource: Int): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_VIEW) {
setImageResource(imageResource)
}
}
inline fun ViewManager.imageView(imageResource: Int, init: android.widget.ImageView.() -> Unit): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_VIEW) {
init()
setImageResource(imageResource)
}
}
inline fun ViewManager.listView(): android.widget.ListView = listView({})
inline fun ViewManager.listView(init: android.widget.ListView.() -> Unit): android.widget.ListView {
return ankoView(`$$Anko$Factories$Sdk15View`.LIST_VIEW) { init() }
}
inline fun Context.listView(): android.widget.ListView = listView({})
inline fun Context.listView(init: android.widget.ListView.() -> Unit): android.widget.ListView {
return ankoView(`$$Anko$Factories$Sdk15View`.LIST_VIEW) { init() }
}
inline fun Activity.listView(): android.widget.ListView = listView({})
inline fun Activity.listView(init: android.widget.ListView.() -> Unit): android.widget.ListView {
return ankoView(`$$Anko$Factories$Sdk15View`.LIST_VIEW) { init() }
}
inline fun ViewManager.multiAutoCompleteTextView(): android.widget.MultiAutoCompleteTextView = multiAutoCompleteTextView({})
inline fun ViewManager.multiAutoCompleteTextView(init: android.widget.MultiAutoCompleteTextView.() -> Unit): android.widget.MultiAutoCompleteTextView {
return ankoView(`$$Anko$Factories$Sdk15View`.MULTI_AUTO_COMPLETE_TEXT_VIEW) { init() }
}
inline fun ViewManager.numberPicker(): android.widget.NumberPicker = numberPicker({})
inline fun ViewManager.numberPicker(init: android.widget.NumberPicker.() -> Unit): android.widget.NumberPicker {
return ankoView(`$$Anko$Factories$Sdk15View`.NUMBER_PICKER) { init() }
}
inline fun Context.numberPicker(): android.widget.NumberPicker = numberPicker({})
inline fun Context.numberPicker(init: android.widget.NumberPicker.() -> Unit): android.widget.NumberPicker {
return ankoView(`$$Anko$Factories$Sdk15View`.NUMBER_PICKER) { init() }
}
inline fun Activity.numberPicker(): android.widget.NumberPicker = numberPicker({})
inline fun Activity.numberPicker(init: android.widget.NumberPicker.() -> Unit): android.widget.NumberPicker {
return ankoView(`$$Anko$Factories$Sdk15View`.NUMBER_PICKER) { init() }
}
inline fun ViewManager.progressBar(): android.widget.ProgressBar = progressBar({})
inline fun ViewManager.progressBar(init: android.widget.ProgressBar.() -> Unit): android.widget.ProgressBar {
return ankoView(`$$Anko$Factories$Sdk15View`.PROGRESS_BAR) { init() }
}
inline fun ViewManager.quickContactBadge(): android.widget.QuickContactBadge = quickContactBadge({})
inline fun ViewManager.quickContactBadge(init: android.widget.QuickContactBadge.() -> Unit): android.widget.QuickContactBadge {
return ankoView(`$$Anko$Factories$Sdk15View`.QUICK_CONTACT_BADGE) { init() }
}
inline fun ViewManager.radioButton(): android.widget.RadioButton = radioButton({})
inline fun ViewManager.radioButton(init: android.widget.RadioButton.() -> Unit): android.widget.RadioButton {
return ankoView(`$$Anko$Factories$Sdk15View`.RADIO_BUTTON) { init() }
}
inline fun ViewManager.ratingBar(): android.widget.RatingBar = ratingBar({})
inline fun ViewManager.ratingBar(init: android.widget.RatingBar.() -> Unit): android.widget.RatingBar {
return ankoView(`$$Anko$Factories$Sdk15View`.RATING_BAR) { init() }
}
inline fun ViewManager.searchView(): android.widget.SearchView = searchView({})
inline fun ViewManager.searchView(init: android.widget.SearchView.() -> Unit): android.widget.SearchView {
return ankoView(`$$Anko$Factories$Sdk15View`.SEARCH_VIEW) { init() }
}
inline fun Context.searchView(): android.widget.SearchView = searchView({})
inline fun Context.searchView(init: android.widget.SearchView.() -> Unit): android.widget.SearchView {
return ankoView(`$$Anko$Factories$Sdk15View`.SEARCH_VIEW) { init() }
}
inline fun Activity.searchView(): android.widget.SearchView = searchView({})
inline fun Activity.searchView(init: android.widget.SearchView.() -> Unit): android.widget.SearchView {
return ankoView(`$$Anko$Factories$Sdk15View`.SEARCH_VIEW) { init() }
}
inline fun ViewManager.seekBar(): android.widget.SeekBar = seekBar({})
inline fun ViewManager.seekBar(init: android.widget.SeekBar.() -> Unit): android.widget.SeekBar {
return ankoView(`$$Anko$Factories$Sdk15View`.SEEK_BAR) { init() }
}
inline fun ViewManager.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer({})
inline fun ViewManager.slidingDrawer(init: android.widget.SlidingDrawer.() -> Unit): android.widget.SlidingDrawer {
return ankoView(`$$Anko$Factories$Sdk15View`.SLIDING_DRAWER) { init() }
}
inline fun Context.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer({})
inline fun Context.slidingDrawer(init: android.widget.SlidingDrawer.() -> Unit): android.widget.SlidingDrawer {
return ankoView(`$$Anko$Factories$Sdk15View`.SLIDING_DRAWER) { init() }
}
inline fun Activity.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer({})
inline fun Activity.slidingDrawer(init: android.widget.SlidingDrawer.() -> Unit): android.widget.SlidingDrawer {
return ankoView(`$$Anko$Factories$Sdk15View`.SLIDING_DRAWER) { init() }
}
inline fun ViewManager.space(): android.widget.Space = space({})
inline fun ViewManager.space(init: android.widget.Space.() -> Unit): android.widget.Space {
return ankoView(`$$Anko$Factories$Sdk15View`.SPACE) { init() }
}
inline fun ViewManager.spinner(): android.widget.Spinner = spinner({})
inline fun ViewManager.spinner(init: android.widget.Spinner.() -> Unit): android.widget.Spinner {
return ankoView(`$$Anko$Factories$Sdk15View`.SPINNER) { init() }
}
inline fun Context.spinner(): android.widget.Spinner = spinner({})
inline fun Context.spinner(init: android.widget.Spinner.() -> Unit): android.widget.Spinner {
return ankoView(`$$Anko$Factories$Sdk15View`.SPINNER) { init() }
}
inline fun Activity.spinner(): android.widget.Spinner = spinner({})
inline fun Activity.spinner(init: android.widget.Spinner.() -> Unit): android.widget.Spinner {
return ankoView(`$$Anko$Factories$Sdk15View`.SPINNER) { init() }
}
inline fun ViewManager.stackView(): android.widget.StackView = stackView({})
inline fun ViewManager.stackView(init: android.widget.StackView.() -> Unit): android.widget.StackView {
return ankoView(`$$Anko$Factories$Sdk15View`.STACK_VIEW) { init() }
}
inline fun Context.stackView(): android.widget.StackView = stackView({})
inline fun Context.stackView(init: android.widget.StackView.() -> Unit): android.widget.StackView {
return ankoView(`$$Anko$Factories$Sdk15View`.STACK_VIEW) { init() }
}
inline fun Activity.stackView(): android.widget.StackView = stackView({})
inline fun Activity.stackView(init: android.widget.StackView.() -> Unit): android.widget.StackView {
return ankoView(`$$Anko$Factories$Sdk15View`.STACK_VIEW) { init() }
}
inline fun ViewManager.switch(): android.widget.Switch = switch({})
inline fun ViewManager.switch(init: android.widget.Switch.() -> Unit): android.widget.Switch {
return ankoView(`$$Anko$Factories$Sdk15View`.SWITCH) { init() }
}
inline fun ViewManager.tabHost(): android.widget.TabHost = tabHost({})
inline fun ViewManager.tabHost(init: android.widget.TabHost.() -> Unit): android.widget.TabHost {
return ankoView(`$$Anko$Factories$Sdk15View`.TAB_HOST) { init() }
}
inline fun Context.tabHost(): android.widget.TabHost = tabHost({})
inline fun Context.tabHost(init: android.widget.TabHost.() -> Unit): android.widget.TabHost {
return ankoView(`$$Anko$Factories$Sdk15View`.TAB_HOST) { init() }
}
inline fun Activity.tabHost(): android.widget.TabHost = tabHost({})
inline fun Activity.tabHost(init: android.widget.TabHost.() -> Unit): android.widget.TabHost {
return ankoView(`$$Anko$Factories$Sdk15View`.TAB_HOST) { init() }
}
inline fun ViewManager.tabWidget(): android.widget.TabWidget = tabWidget({})
inline fun ViewManager.tabWidget(init: android.widget.TabWidget.() -> Unit): android.widget.TabWidget {
return ankoView(`$$Anko$Factories$Sdk15View`.TAB_WIDGET) { init() }
}
inline fun Context.tabWidget(): android.widget.TabWidget = tabWidget({})
inline fun Context.tabWidget(init: android.widget.TabWidget.() -> Unit): android.widget.TabWidget {
return ankoView(`$$Anko$Factories$Sdk15View`.TAB_WIDGET) { init() }
}
inline fun Activity.tabWidget(): android.widget.TabWidget = tabWidget({})
inline fun Activity.tabWidget(init: android.widget.TabWidget.() -> Unit): android.widget.TabWidget {
return ankoView(`$$Anko$Factories$Sdk15View`.TAB_WIDGET) { init() }
}
inline fun ViewManager.textView(): android.widget.TextView = textView({})
inline fun ViewManager.textView(init: android.widget.TextView.() -> Unit): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk15View`.TEXT_VIEW) { init() }
}
inline fun ViewManager.textView(text: CharSequence?): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk15View`.TEXT_VIEW) {
setText(text)
}
}
inline fun ViewManager.textView(text: CharSequence?, init: android.widget.TextView.() -> Unit): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk15View`.TEXT_VIEW) {
init()
setText(text)
}
}
inline fun ViewManager.textView(text: Int): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk15View`.TEXT_VIEW) {
setText(text)
}
}
inline fun ViewManager.textView(text: Int, init: android.widget.TextView.() -> Unit): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk15View`.TEXT_VIEW) {
init()
setText(text)
}
}
inline fun ViewManager.timePicker(): android.widget.TimePicker = timePicker({})
inline fun ViewManager.timePicker(init: android.widget.TimePicker.() -> Unit): android.widget.TimePicker {
return ankoView(`$$Anko$Factories$Sdk15View`.TIME_PICKER) { init() }
}
inline fun Context.timePicker(): android.widget.TimePicker = timePicker({})
inline fun Context.timePicker(init: android.widget.TimePicker.() -> Unit): android.widget.TimePicker {
return ankoView(`$$Anko$Factories$Sdk15View`.TIME_PICKER) { init() }
}
inline fun Activity.timePicker(): android.widget.TimePicker = timePicker({})
inline fun Activity.timePicker(init: android.widget.TimePicker.() -> Unit): android.widget.TimePicker {
return ankoView(`$$Anko$Factories$Sdk15View`.TIME_PICKER) { init() }
}
inline fun ViewManager.toggleButton(): android.widget.ToggleButton = toggleButton({})
inline fun ViewManager.toggleButton(init: android.widget.ToggleButton.() -> Unit): android.widget.ToggleButton {
return ankoView(`$$Anko$Factories$Sdk15View`.TOGGLE_BUTTON) { init() }
}
inline fun ViewManager.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem({})
inline fun ViewManager.twoLineListItem(init: android.widget.TwoLineListItem.() -> Unit): android.widget.TwoLineListItem {
return ankoView(`$$Anko$Factories$Sdk15View`.TWO_LINE_LIST_ITEM) { init() }
}
inline fun Context.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem({})
inline fun Context.twoLineListItem(init: android.widget.TwoLineListItem.() -> Unit): android.widget.TwoLineListItem {
return ankoView(`$$Anko$Factories$Sdk15View`.TWO_LINE_LIST_ITEM) { init() }
}
inline fun Activity.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem({})
inline fun Activity.twoLineListItem(init: android.widget.TwoLineListItem.() -> Unit): android.widget.TwoLineListItem {
return ankoView(`$$Anko$Factories$Sdk15View`.TWO_LINE_LIST_ITEM) { init() }
}
inline fun ViewManager.videoView(): android.widget.VideoView = videoView({})
inline fun ViewManager.videoView(init: android.widget.VideoView.() -> Unit): android.widget.VideoView {
return ankoView(`$$Anko$Factories$Sdk15View`.VIDEO_VIEW) { init() }
}
inline fun ViewManager.viewFlipper(): android.widget.ViewFlipper = viewFlipper({})
inline fun ViewManager.viewFlipper(init: android.widget.ViewFlipper.() -> Unit): android.widget.ViewFlipper {
return ankoView(`$$Anko$Factories$Sdk15View`.VIEW_FLIPPER) { init() }
}
inline fun Context.viewFlipper(): android.widget.ViewFlipper = viewFlipper({})
inline fun Context.viewFlipper(init: android.widget.ViewFlipper.() -> Unit): android.widget.ViewFlipper {
return ankoView(`$$Anko$Factories$Sdk15View`.VIEW_FLIPPER) { init() }
}
inline fun Activity.viewFlipper(): android.widget.ViewFlipper = viewFlipper({})
inline fun Activity.viewFlipper(init: android.widget.ViewFlipper.() -> Unit): android.widget.ViewFlipper {
return ankoView(`$$Anko$Factories$Sdk15View`.VIEW_FLIPPER) { init() }
}
inline fun ViewManager.zoomButton(): android.widget.ZoomButton = zoomButton({})
inline fun ViewManager.zoomButton(init: android.widget.ZoomButton.() -> Unit): android.widget.ZoomButton {
return ankoView(`$$Anko$Factories$Sdk15View`.ZOOM_BUTTON) { init() }
}
inline fun ViewManager.zoomControls(): android.widget.ZoomControls = zoomControls({})
inline fun ViewManager.zoomControls(init: android.widget.ZoomControls.() -> Unit): android.widget.ZoomControls {
return ankoView(`$$Anko$Factories$Sdk15View`.ZOOM_CONTROLS) { init() }
}
inline fun Context.zoomControls(): android.widget.ZoomControls = zoomControls({})
inline fun Context.zoomControls(init: android.widget.ZoomControls.() -> Unit): android.widget.ZoomControls {
return ankoView(`$$Anko$Factories$Sdk15View`.ZOOM_CONTROLS) { init() }
}
inline fun Activity.zoomControls(): android.widget.ZoomControls = zoomControls({})
inline fun Activity.zoomControls(init: android.widget.ZoomControls.() -> Unit): android.widget.ZoomControls {
return ankoView(`$$Anko$Factories$Sdk15View`.ZOOM_CONTROLS) { init() }
}
object `$$Anko$Factories$Sdk15ViewGroup` {
val APP_WIDGET_HOST_VIEW = { ctx: Context -> _AppWidgetHostView(ctx) }
val WEB_VIEW = { ctx: Context -> _WebView(ctx) }
val ABSOLUTE_LAYOUT = { ctx: Context -> _AbsoluteLayout(ctx) }
val FRAME_LAYOUT = { ctx: Context -> _FrameLayout(ctx) }
val GALLERY = { ctx: Context -> _Gallery(ctx) }
val GRID_LAYOUT = { ctx: Context -> _GridLayout(ctx) }
val GRID_VIEW = { ctx: Context -> _GridView(ctx) }
val HORIZONTAL_SCROLL_VIEW = { ctx: Context -> _HorizontalScrollView(ctx) }
val IMAGE_SWITCHER = { ctx: Context -> _ImageSwitcher(ctx) }
val LINEAR_LAYOUT = { ctx: Context -> _LinearLayout(ctx) }
val RADIO_GROUP = { ctx: Context -> _RadioGroup(ctx) }
val RELATIVE_LAYOUT = { ctx: Context -> _RelativeLayout(ctx) }
val SCROLL_VIEW = { ctx: Context -> _ScrollView(ctx) }
val TABLE_LAYOUT = { ctx: Context -> _TableLayout(ctx) }
val TABLE_ROW = { ctx: Context -> _TableRow(ctx) }
val TEXT_SWITCHER = { ctx: Context -> _TextSwitcher(ctx) }
val VIEW_ANIMATOR = { ctx: Context -> _ViewAnimator(ctx) }
val VIEW_SWITCHER = { ctx: Context -> _ViewSwitcher(ctx) }
}
inline fun ViewManager.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView({})
inline fun ViewManager.appWidgetHostView(init: _AppWidgetHostView.() -> Unit): android.appwidget.AppWidgetHostView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.APP_WIDGET_HOST_VIEW) { init() }
}
inline fun Context.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView({})
inline fun Context.appWidgetHostView(init: _AppWidgetHostView.() -> Unit): android.appwidget.AppWidgetHostView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.APP_WIDGET_HOST_VIEW) { init() }
}
inline fun Activity.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView({})
inline fun Activity.appWidgetHostView(init: _AppWidgetHostView.() -> Unit): android.appwidget.AppWidgetHostView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.APP_WIDGET_HOST_VIEW) { init() }
}
inline fun ViewManager.webView(): android.webkit.WebView = webView({})
inline fun ViewManager.webView(init: _WebView.() -> Unit): android.webkit.WebView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.WEB_VIEW) { init() }
}
inline fun Context.webView(): android.webkit.WebView = webView({})
inline fun Context.webView(init: _WebView.() -> Unit): android.webkit.WebView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.WEB_VIEW) { init() }
}
inline fun Activity.webView(): android.webkit.WebView = webView({})
inline fun Activity.webView(init: _WebView.() -> Unit): android.webkit.WebView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.WEB_VIEW) { init() }
}
inline fun ViewManager.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout({})
inline fun ViewManager.absoluteLayout(init: _AbsoluteLayout.() -> Unit): android.widget.AbsoluteLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.ABSOLUTE_LAYOUT) { init() }
}
inline fun Context.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout({})
inline fun Context.absoluteLayout(init: _AbsoluteLayout.() -> Unit): android.widget.AbsoluteLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.ABSOLUTE_LAYOUT) { init() }
}
inline fun Activity.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout({})
inline fun Activity.absoluteLayout(init: _AbsoluteLayout.() -> Unit): android.widget.AbsoluteLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.ABSOLUTE_LAYOUT) { init() }
}
inline fun ViewManager.frameLayout(): android.widget.FrameLayout = frameLayout({})
inline fun ViewManager.frameLayout(init: _FrameLayout.() -> Unit): android.widget.FrameLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.FRAME_LAYOUT) { init() }
}
inline fun Context.frameLayout(): android.widget.FrameLayout = frameLayout({})
inline fun Context.frameLayout(init: _FrameLayout.() -> Unit): android.widget.FrameLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.FRAME_LAYOUT) { init() }
}
inline fun Activity.frameLayout(): android.widget.FrameLayout = frameLayout({})
inline fun Activity.frameLayout(init: _FrameLayout.() -> Unit): android.widget.FrameLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.FRAME_LAYOUT) { init() }
}
inline fun ViewManager.gallery(): android.widget.Gallery = gallery({})
inline fun ViewManager.gallery(init: _Gallery.() -> Unit): android.widget.Gallery {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GALLERY) { init() }
}
inline fun Context.gallery(): android.widget.Gallery = gallery({})
inline fun Context.gallery(init: _Gallery.() -> Unit): android.widget.Gallery {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GALLERY) { init() }
}
inline fun Activity.gallery(): android.widget.Gallery = gallery({})
inline fun Activity.gallery(init: _Gallery.() -> Unit): android.widget.Gallery {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GALLERY) { init() }
}
inline fun ViewManager.gridLayout(): android.widget.GridLayout = gridLayout({})
inline fun ViewManager.gridLayout(init: _GridLayout.() -> Unit): android.widget.GridLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GRID_LAYOUT) { init() }
}
inline fun Context.gridLayout(): android.widget.GridLayout = gridLayout({})
inline fun Context.gridLayout(init: _GridLayout.() -> Unit): android.widget.GridLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GRID_LAYOUT) { init() }
}
inline fun Activity.gridLayout(): android.widget.GridLayout = gridLayout({})
inline fun Activity.gridLayout(init: _GridLayout.() -> Unit): android.widget.GridLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GRID_LAYOUT) { init() }
}
inline fun ViewManager.gridView(): android.widget.GridView = gridView({})
inline fun ViewManager.gridView(init: _GridView.() -> Unit): android.widget.GridView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GRID_VIEW) { init() }
}
inline fun Context.gridView(): android.widget.GridView = gridView({})
inline fun Context.gridView(init: _GridView.() -> Unit): android.widget.GridView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GRID_VIEW) { init() }
}
inline fun Activity.gridView(): android.widget.GridView = gridView({})
inline fun Activity.gridView(init: _GridView.() -> Unit): android.widget.GridView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GRID_VIEW) { init() }
}
inline fun ViewManager.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView({})
inline fun ViewManager.horizontalScrollView(init: _HorizontalScrollView.() -> Unit): android.widget.HorizontalScrollView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.HORIZONTAL_SCROLL_VIEW) { init() }
}
inline fun Context.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView({})
inline fun Context.horizontalScrollView(init: _HorizontalScrollView.() -> Unit): android.widget.HorizontalScrollView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.HORIZONTAL_SCROLL_VIEW) { init() }
}
inline fun Activity.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView({})
inline fun Activity.horizontalScrollView(init: _HorizontalScrollView.() -> Unit): android.widget.HorizontalScrollView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.HORIZONTAL_SCROLL_VIEW) { init() }
}
inline fun ViewManager.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher({})
inline fun ViewManager.imageSwitcher(init: _ImageSwitcher.() -> Unit): android.widget.ImageSwitcher {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.IMAGE_SWITCHER) { init() }
}
inline fun Context.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher({})
inline fun Context.imageSwitcher(init: _ImageSwitcher.() -> Unit): android.widget.ImageSwitcher {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.IMAGE_SWITCHER) { init() }
}
inline fun Activity.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher({})
inline fun Activity.imageSwitcher(init: _ImageSwitcher.() -> Unit): android.widget.ImageSwitcher {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.IMAGE_SWITCHER) { init() }
}
inline fun ViewManager.linearLayout(): android.widget.LinearLayout = linearLayout({})
inline fun ViewManager.linearLayout(init: _LinearLayout.() -> Unit): android.widget.LinearLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.LINEAR_LAYOUT) { init() }
}
inline fun Context.linearLayout(): android.widget.LinearLayout = linearLayout({})
inline fun Context.linearLayout(init: _LinearLayout.() -> Unit): android.widget.LinearLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.LINEAR_LAYOUT) { init() }
}
inline fun Activity.linearLayout(): android.widget.LinearLayout = linearLayout({})
inline fun Activity.linearLayout(init: _LinearLayout.() -> Unit): android.widget.LinearLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.LINEAR_LAYOUT) { init() }
}
inline fun ViewManager.radioGroup(): android.widget.RadioGroup = radioGroup({})
inline fun ViewManager.radioGroup(init: _RadioGroup.() -> Unit): android.widget.RadioGroup {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.RADIO_GROUP) { init() }
}
inline fun Context.radioGroup(): android.widget.RadioGroup = radioGroup({})
inline fun Context.radioGroup(init: _RadioGroup.() -> Unit): android.widget.RadioGroup {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.RADIO_GROUP) { init() }
}
inline fun Activity.radioGroup(): android.widget.RadioGroup = radioGroup({})
inline fun Activity.radioGroup(init: _RadioGroup.() -> Unit): android.widget.RadioGroup {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.RADIO_GROUP) { init() }
}
inline fun ViewManager.relativeLayout(): android.widget.RelativeLayout = relativeLayout({})
inline fun ViewManager.relativeLayout(init: _RelativeLayout.() -> Unit): android.widget.RelativeLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.RELATIVE_LAYOUT) { init() }
}
inline fun Context.relativeLayout(): android.widget.RelativeLayout = relativeLayout({})
inline fun Context.relativeLayout(init: _RelativeLayout.() -> Unit): android.widget.RelativeLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.RELATIVE_LAYOUT) { init() }
}
inline fun Activity.relativeLayout(): android.widget.RelativeLayout = relativeLayout({})
inline fun Activity.relativeLayout(init: _RelativeLayout.() -> Unit): android.widget.RelativeLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.RELATIVE_LAYOUT) { init() }
}
inline fun ViewManager.scrollView(): android.widget.ScrollView = scrollView({})
inline fun ViewManager.scrollView(init: _ScrollView.() -> Unit): android.widget.ScrollView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.SCROLL_VIEW) { init() }
}
inline fun Context.scrollView(): android.widget.ScrollView = scrollView({})
inline fun Context.scrollView(init: _ScrollView.() -> Unit): android.widget.ScrollView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.SCROLL_VIEW) { init() }
}
inline fun Activity.scrollView(): android.widget.ScrollView = scrollView({})
inline fun Activity.scrollView(init: _ScrollView.() -> Unit): android.widget.ScrollView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.SCROLL_VIEW) { init() }
}
inline fun ViewManager.tableLayout(): android.widget.TableLayout = tableLayout({})
inline fun ViewManager.tableLayout(init: _TableLayout.() -> Unit): android.widget.TableLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TABLE_LAYOUT) { init() }
}
inline fun Context.tableLayout(): android.widget.TableLayout = tableLayout({})
inline fun Context.tableLayout(init: _TableLayout.() -> Unit): android.widget.TableLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TABLE_LAYOUT) { init() }
}
inline fun Activity.tableLayout(): android.widget.TableLayout = tableLayout({})
inline fun Activity.tableLayout(init: _TableLayout.() -> Unit): android.widget.TableLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TABLE_LAYOUT) { init() }
}
inline fun ViewManager.tableRow(): android.widget.TableRow = tableRow({})
inline fun ViewManager.tableRow(init: _TableRow.() -> Unit): android.widget.TableRow {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TABLE_ROW) { init() }
}
inline fun Context.tableRow(): android.widget.TableRow = tableRow({})
inline fun Context.tableRow(init: _TableRow.() -> Unit): android.widget.TableRow {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TABLE_ROW) { init() }
}
inline fun Activity.tableRow(): android.widget.TableRow = tableRow({})
inline fun Activity.tableRow(init: _TableRow.() -> Unit): android.widget.TableRow {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TABLE_ROW) { init() }
}
inline fun ViewManager.textSwitcher(): android.widget.TextSwitcher = textSwitcher({})
inline fun ViewManager.textSwitcher(init: _TextSwitcher.() -> Unit): android.widget.TextSwitcher {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TEXT_SWITCHER) { init() }
}
inline fun Context.textSwitcher(): android.widget.TextSwitcher = textSwitcher({})
inline fun Context.textSwitcher(init: _TextSwitcher.() -> Unit): android.widget.TextSwitcher {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TEXT_SWITCHER) { init() }
}
inline fun Activity.textSwitcher(): android.widget.TextSwitcher = textSwitcher({})
inline fun Activity.textSwitcher(init: _TextSwitcher.() -> Unit): android.widget.TextSwitcher {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TEXT_SWITCHER) { init() }
}
inline fun ViewManager.viewAnimator(): android.widget.ViewAnimator = viewAnimator({})
inline fun ViewManager.viewAnimator(init: _ViewAnimator.() -> Unit): android.widget.ViewAnimator {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.VIEW_ANIMATOR) { init() }
}
inline fun Context.viewAnimator(): android.widget.ViewAnimator = viewAnimator({})
inline fun Context.viewAnimator(init: _ViewAnimator.() -> Unit): android.widget.ViewAnimator {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.VIEW_ANIMATOR) { init() }
}
inline fun Activity.viewAnimator(): android.widget.ViewAnimator = viewAnimator({})
inline fun Activity.viewAnimator(init: _ViewAnimator.() -> Unit): android.widget.ViewAnimator {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.VIEW_ANIMATOR) { init() }
}
inline fun ViewManager.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher({})
inline fun ViewManager.viewSwitcher(init: _ViewSwitcher.() -> Unit): android.widget.ViewSwitcher {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.VIEW_SWITCHER) { init() }
}
inline fun Context.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher({})
inline fun Context.viewSwitcher(init: _ViewSwitcher.() -> Unit): android.widget.ViewSwitcher {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.VIEW_SWITCHER) { init() }
}
inline fun Activity.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher({})
inline fun Activity.viewSwitcher(init: _ViewSwitcher.() -> Unit): android.widget.ViewSwitcher {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.VIEW_SWITCHER) { init() }
} | apache-2.0 | c4bf7cf46cad4b908fbfb4b77efec698 | 49.957655 | 161 | 0.736635 | 4.23871 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/viewmodels/SubtitlesModel.kt | 1 | 8726 | package org.videolan.vlc.viewmodels
import android.content.Context
import android.net.Uri
import androidx.databinding.Observable
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import androidx.lifecycle.*
import kotlinx.coroutines.Job
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.videolan.tools.FileUtils
import org.videolan.resources.util.NoConnectivityException
import org.videolan.tools.Settings
import org.videolan.vlc.R
import org.videolan.resources.opensubtitles.OpenSubtitle
import org.videolan.vlc.gui.dialogs.State
import org.videolan.vlc.gui.dialogs.SubtitleItem
import org.videolan.vlc.repository.ExternalSubRepository
import org.videolan.resources.opensubtitles.OpenSubtitleRepository
import org.videolan.tools.CoroutineContextProvider
import org.videolan.tools.putSingle
import java.io.File
import java.util.*
private const val LAST_USED_LANGUAGES = "last_used_subtitles"
class SubtitlesModel(private val context: Context, private val mediaUri: Uri, val coroutineContextProvider: CoroutineContextProvider = CoroutineContextProvider()): ViewModel() {
val observableSearchName = ObservableField<String>()
val observableSearchEpisode = ObservableField<String>()
val observableSearchSeason = ObservableField<String>()
val observableSearchLanguage = ObservableField<List<String>>()
private var previousSearchLanguage: List<String>? = null
val manualSearchEnabled = ObservableBoolean(false)
val isApiLoading = ObservableBoolean(false)
val observableMessage = ObservableField<String>()
private val apiResultLiveData: MutableLiveData<List<OpenSubtitle>> = MutableLiveData()
private val downloadedLiveData = Transformations.map(ExternalSubRepository.getInstance(context).getDownloadedSubtitles(mediaUri)) {
it.map { SubtitleItem(it.idSubtitle, mediaUri, it.subLanguageID, it.movieReleaseName, State.Downloaded, "") }
}
private val downloadingLiveData = ExternalSubRepository.getInstance(context).downloadingSubtitles
val result: MediatorLiveData<List<SubtitleItem>> = MediatorLiveData()
val history: MediatorLiveData<List<SubtitleItem>> = MediatorLiveData()
private var searchJob: Job? = null
init {
observableSearchLanguage.addOnPropertyChangedCallback(object: Observable.OnPropertyChangedCallback() {
override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
if (observableSearchLanguage.get() != previousSearchLanguage) {
previousSearchLanguage = observableSearchLanguage.get()
saveLastUsedLanguage(observableSearchLanguage.get() ?: listOf())
search(!manualSearchEnabled.get())
}
}
})
history.apply {
addSource(downloadedLiveData) {
viewModelScope.launch {
value = merge(it, downloadingLiveData.value?.values?.filter { it.mediaUri == mediaUri })
}
}
addSource(downloadingLiveData) {
viewModelScope.launch {
value = merge(downloadedLiveData.value, it?.values?.filter { it.mediaUri == mediaUri })
}
}
}
result.apply {
addSource(apiResultLiveData) {
viewModelScope.launch {
value = updateListState(it, history.value)
}
}
addSource(history) {
viewModelScope.launch {
value = updateListState(apiResultLiveData.value, it)
}
}
}
}
private suspend fun merge(downloadedResult: List<SubtitleItem>?, downloadingResult: List<SubtitleItem>?): List<SubtitleItem> = withContext(coroutineContextProvider.Default) {
downloadedResult.orEmpty() + downloadingResult?.toList().orEmpty()
}
private suspend fun updateListState(apiResultLiveData: List<OpenSubtitle>?, history: List<SubtitleItem>?): MutableList<SubtitleItem> = withContext(coroutineContextProvider.Default) {
val list = mutableListOf<SubtitleItem>()
apiResultLiveData?.forEach { openSubtitle ->
val exist = history?.find { it.idSubtitle == openSubtitle.idSubtitle }
val state = exist?.state ?: State.NotDownloaded
list.add(SubtitleItem(openSubtitle.idSubtitle, mediaUri, openSubtitle.subLanguageID, openSubtitle.movieReleaseName, state, openSubtitle.zipDownloadLink))
}
list
}
fun onCheckedChanged(isChecked: Boolean) {
if (manualSearchEnabled.get() == isChecked) return
manualSearchEnabled.set(isChecked)
isApiLoading.set(false)
apiResultLiveData.postValue(listOf())
searchJob?.cancel()
observableMessage.set("")
if (!isChecked) search(true)
}
private suspend fun getSubtitleByName(name: String, episode: Int?, season: Int?, languageIds: List<String>?): List<OpenSubtitle> {
return OpenSubtitleRepository.getInstance().queryWithName(name ,episode, season, languageIds)
}
private suspend fun getSubtitleByHash(movieByteSize: Long, movieHash: String?, languageIds: List<String>?): List<OpenSubtitle> {
return OpenSubtitleRepository.getInstance().queryWithHash(movieByteSize, movieHash, languageIds)
}
fun onRefresh() {
if (manualSearchEnabled.get() && observableSearchName.get().isNullOrEmpty()) {
isApiLoading.set(false)
// As it's already false we need to notify it to
// disable refreshing animation
isApiLoading.notifyChange()
return
}
search(!manualSearchEnabled.get())
}
fun search(byHash: Boolean) {
searchJob?.cancel()
isApiLoading.set(true)
observableMessage.set("")
apiResultLiveData.postValue(listOf())
searchJob = viewModelScope.launch {
try {
val subs = if (byHash) {
withContext(coroutineContextProvider.IO) {
val videoFile = File(mediaUri.path)
val hash = FileUtils.computeHash(videoFile)
val fileLength = videoFile.length()
getSubtitleByHash(fileLength, hash, observableSearchLanguage.get())
}
} else {
observableSearchName.get()?.let {
getSubtitleByName(it, observableSearchEpisode.get()?.toInt(), observableSearchSeason.get()?.toInt(), observableSearchLanguage.get())
} ?: listOf()
}
if (isActive) apiResultLiveData.postValue(subs)
if (subs.isEmpty()) observableMessage.set(context.getString(R.string.no_result))
} catch (e: Exception) {
if (e is NoConnectivityException)
observableMessage.set(context.getString(R.string.no_internet_connection))
else
observableMessage.set(context.getString(R.string.some_error_occurred))
} finally {
isApiLoading.set(false)
}
}
}
fun deleteSubtitle(mediaPath: String, idSubtitle: String) {
ExternalSubRepository.getInstance(context).deleteSubtitle(mediaPath, idSubtitle)
}
fun getLastUsedLanguage() : List<String> {
val language = try {
Locale.getDefault().isO3Language
} catch (e: MissingResourceException) {
"eng"
}
return Settings.getInstance(context).getStringSet(LAST_USED_LANGUAGES, setOf(language))?.map { it.getCompliantLanguageID() } ?: emptyList()
}
fun saveLastUsedLanguage(lastUsedLanguages: List<String>) = Settings.getInstance(context).putSingle(LAST_USED_LANGUAGES, lastUsedLanguages)
class Factory(private val context: Context, private val mediaUri: Uri): ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return SubtitlesModel(context.applicationContext, mediaUri) as T
}
}
// Locale ID Control, because of OpenSubtitle support of ISO639-2 codes
// e.g. French ID can be 'fra' or 'fre', OpenSubtitles considers 'fre' but Android Java Locale provides 'fra'
private fun String.getCompliantLanguageID() = when(this) {
"fra" -> "fre"
"deu" -> "ger"
"zho" -> "chi"
"ces" -> "cze"
"fas" -> "per"
"nld" -> "dut"
"ron" -> "rum"
"slk" -> "slo"
else -> this
}
}
| gpl-2.0 | 25b50c09f59f8162c236990ae1e4c05a | 41.359223 | 187 | 0.65895 | 5.209552 | false | false | false | false |
cout970/Magneticraft | src/main/kotlin/com/cout970/magneticraft/misc/fluid/Utilities.kt | 2 | 1485 | package com.cout970.magneticraft.misc.fluid
import net.minecraftforge.fluids.FluidStack
import net.minecraftforge.fluids.capability.IFluidHandler
import net.minecraftforge.fluids.capability.IFluidTankProperties
/**
* Created by cout970 on 2017/08/29.
*/
object VoidFluidHandler : IFluidHandler {
override fun drain(resource: FluidStack?, doDrain: Boolean): FluidStack? = null
override fun drain(maxDrain: Int, doDrain: Boolean): FluidStack? = null
override fun fill(resource: FluidStack?, doFill: Boolean): Int = resource?.amount ?: 0
override fun getTankProperties(): Array<IFluidTankProperties> = arrayOf(VoidFluidTankProperties)
}
object VoidFluidTankProperties : IFluidTankProperties {
override fun canDrainFluidType(fluidStack: FluidStack?): Boolean = false
override fun getContents(): FluidStack? = null
override fun canFillFluidType(fluidStack: FluidStack?): Boolean = true
override fun getCapacity(): Int = 16000
override fun canFill(): Boolean = true
override fun canDrain(): Boolean = false
}
fun IFluidHandler.fillFromTank(max: Int, tank: IFluidHandler): Int {
val canDrain = tank.drain(max, false)
if (canDrain != null) {
val result = fill(canDrain, false)
if (result > 0) {
val drained = tank.drain(result, true)
return fill(drained, true)
}
}
return 0
}
fun IFluidHandler.isEmpty(): Boolean {
return tankProperties.none { it.contents != null }
} | gpl-2.0 | b6b56cc5d2d5d5504bd250716839f7ce | 28.137255 | 100 | 0.715152 | 4.432836 | false | false | false | false |
jonalmeida/focus-android | app/src/main/java/org/mozilla/focus/searchsuggestions/SearchSuggestionsFetcher.kt | 1 | 3240 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.searchsuggestions
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import mozilla.components.browser.search.SearchEngine
import mozilla.components.browser.search.suggestions.SearchSuggestionClient
import okhttp3.OkHttpClient
import okhttp3.Request
import org.mozilla.focus.utils.debounce
import kotlin.coroutines.CoroutineContext
class SearchSuggestionsFetcher(searchEngine: SearchEngine) : CoroutineScope {
private var job = Job()
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
data class SuggestionResult(val query: String, val suggestions: List<String>)
private var client: SearchSuggestionClient? = null
private var httpClient = OkHttpClient()
private val fetchChannel = Channel<String>(capacity = Channel.UNLIMITED)
private val _results = MutableLiveData<SuggestionResult>()
val results: LiveData<SuggestionResult> = _results
var canProvideSearchSuggestions = false
private set
init {
updateSearchEngine(searchEngine)
launch(IO) {
debounce(THROTTLE_AMOUNT, fetchChannel)
.consumeEach { getSuggestions(it) }
}
}
fun requestSuggestions(query: String) {
if (query.isBlank()) { _results.value = SuggestionResult(query, listOf()); return }
fetchChannel.offer(query)
}
fun updateSearchEngine(searchEngine: SearchEngine) {
canProvideSearchSuggestions = searchEngine.canProvideSearchSuggestions
client = if (canProvideSearchSuggestions) SearchSuggestionClient(searchEngine, { fetch(it) }) else null
}
private suspend fun getSuggestions(query: String) = coroutineScope {
val suggestions = try {
client?.getSuggestions(query) ?: listOf()
} catch (ex: SearchSuggestionClient.ResponseParserException) {
listOf<String>()
} catch (ex: SearchSuggestionClient.FetchException) {
listOf<String>()
}
launch(Main) {
_results.value = SuggestionResult(query, suggestions)
}
}
private fun fetch(url: String): String? {
httpClient.dispatcher().queuedCalls()
.filter { it.request().tag() == REQUEST_TAG }
.forEach { it.cancel() }
val request = Request.Builder()
.tag(REQUEST_TAG)
.url(url)
.build()
return httpClient.newCall(request).execute().body()?.string() ?: ""
}
companion object {
private const val REQUEST_TAG = "searchSuggestionFetch"
private const val THROTTLE_AMOUNT: Long = 100
}
}
| mpl-2.0 | 808dd56d281ac2a1c8fa4d31e8440e18 | 33.83871 | 111 | 0.699074 | 4.886878 | false | false | false | false |
BOINC/boinc | android/BOINC/app/src/main/java/edu/berkeley/boinc/rpc/Project.kt | 2 | 14626 | /*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2020 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.rpc
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.os.Parcel
import android.os.Parcelable
import androidx.core.os.ParcelCompat.readBoolean
import androidx.core.os.ParcelCompat.writeBoolean
import java.util.*
data class Project(
var masterURL: String = "",
var projectDir: String = "",
var resourceShare: Float = 0f,
var projectName: String = "",
var userName: String = "",
var teamName: String = "",
var hostVenue: String = "",
var hostId: Int = 0,
val guiURLs: MutableList<GuiUrl?> = mutableListOf(),
var userTotalCredit: Double = 0.0,
var userExpAvgCredit: Double = 0.0,
/**
* As reported by server
*/
var hostTotalCredit: Double = 0.0,
/**
* As reported by server
*/
var hostExpAvgCredit: Double = 0.0,
var diskUsage: Double = 0.0,
var noOfRPCFailures: Int = 0,
var masterFetchFailures: Int = 0,
/**
* Earliest time to contact any server
*/
var minRPCTime: Double = 0.0,
var downloadBackoff: Double = 0.0,
var uploadBackoff: Double = 0.0,
var cpuShortTermDebt: Double = 0.0,
var cpuLongTermDebt: Double = 0.0,
var cpuBackoffTime: Double = 0.0,
var cpuBackoffInterval: Double = 0.0,
var cudaDebt: Double = 0.0,
var cudaShortTermDebt: Double = 0.0,
var cudaBackoffTime: Double = 0.0,
var cudaBackoffInterval: Double = 0.0,
var atiDebt: Double = 0.0,
var atiShortTermDebt: Double = 0.0,
var atiBackoffTime: Double = 0.0,
var atiBackoffInterval: Double = 0.0,
var durationCorrectionFactor: Double = 0.0,
/**
* Need to contact scheduling server. Encodes the reason for the request.
*/
var scheduledRPCPending: Int = 0,
var projectFilesDownloadedTime: Double = 0.0,
var lastRPCTime: Double = 0.0,
/**
* Need to fetch and parse the master URL
*/
var masterURLFetchPending: Boolean = false,
var nonCPUIntensive: Boolean = false,
var suspendedViaGUI: Boolean = false,
var doNotRequestMoreWork: Boolean = false,
var schedulerRPCInProgress: Boolean = false,
var attachedViaAcctMgr: Boolean = false,
var detachWhenDone: Boolean = false,
var ended: Boolean = false,
var trickleUpPending: Boolean = false,
var noCPUPref: Boolean = false,
var noCUDAPref: Boolean = false,
var noATIPref: Boolean = false
) : Parcelable {
val name: String?
get() = if (projectName.isEmpty()) masterURL else projectName
private constructor(parcel: Parcel) :
this(masterURL = parcel.readString() ?: "", projectDir = parcel.readString() ?: "",
resourceShare = parcel.readFloat(), projectName = parcel.readString() ?: "",
userName = parcel.readString() ?: "", teamName = parcel.readString() ?: "",
hostVenue = parcel.readString() ?: "", hostId = parcel.readInt(),
userTotalCredit = parcel.readDouble(), userExpAvgCredit = parcel.readDouble(),
hostTotalCredit = parcel.readDouble(), hostExpAvgCredit = parcel.readDouble(),
diskUsage = parcel.readDouble(), noOfRPCFailures = parcel.readInt(),
masterFetchFailures = parcel.readInt(), minRPCTime = parcel.readDouble(),
downloadBackoff = parcel.readDouble(), uploadBackoff = parcel.readDouble(),
cpuShortTermDebt = parcel.readDouble(), cpuBackoffTime = parcel.readDouble(),
cpuBackoffInterval = parcel.readDouble(), cudaDebt = parcel.readDouble(),
cudaShortTermDebt = parcel.readDouble(), cudaBackoffTime = parcel.readDouble(),
cudaBackoffInterval = parcel.readDouble(), atiDebt = parcel.readDouble(),
atiShortTermDebt = parcel.readDouble(), atiBackoffTime = parcel.readDouble(),
atiBackoffInterval = parcel.readDouble(), durationCorrectionFactor = parcel.readDouble(),
scheduledRPCPending = parcel.readInt(), projectFilesDownloadedTime = parcel.readDouble(),
lastRPCTime = parcel.readDouble(), masterURLFetchPending = readBoolean(parcel),
nonCPUIntensive = readBoolean(parcel), suspendedViaGUI = readBoolean(parcel),
doNotRequestMoreWork = readBoolean(parcel), schedulerRPCInProgress = readBoolean(parcel),
attachedViaAcctMgr = readBoolean(parcel), detachWhenDone = readBoolean(parcel),
ended = readBoolean(parcel), trickleUpPending = readBoolean(parcel),
noCPUPref = readBoolean(parcel), noCUDAPref = readBoolean(parcel), noATIPref = readBoolean(parcel),
guiURLs = arrayListOf<GuiUrl?>().apply { if (VERSION.SDK_INT >= VERSION_CODES.TIRAMISU) {
parcel.readList(this as MutableList<GuiUrl?>, GuiUrl::class.java.classLoader, GuiUrl::class.java)
} else {
@Suppress("DEPRECATION")
parcel.readList(this as MutableList<*>, GuiUrl::class.java.classLoader)
}
})
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return other is Project && other.resourceShare.compareTo(resourceShare) == 0 && hostId == other.hostId &&
other.userTotalCredit.compareTo(userTotalCredit) == 0 && other.userExpAvgCredit.compareTo(userExpAvgCredit) == 0 &&
other.hostTotalCredit.compareTo(hostTotalCredit) == 0 && other.hostExpAvgCredit.compareTo(hostExpAvgCredit) == 0 &&
other.diskUsage.compareTo(diskUsage) == 0 && noOfRPCFailures == other.noOfRPCFailures &&
masterFetchFailures == other.masterFetchFailures && other.minRPCTime.compareTo(minRPCTime) == 0 &&
other.downloadBackoff.compareTo(downloadBackoff) == 0 && other.uploadBackoff.compareTo(uploadBackoff) == 0 &&
other.cpuShortTermDebt.compareTo(cpuShortTermDebt) == 0 && other.cpuLongTermDebt.compareTo(cpuLongTermDebt) == 0 &&
other.cpuBackoffTime.compareTo(cpuBackoffTime) == 0 && other.cpuBackoffInterval.compareTo(cpuBackoffInterval) == 0 &&
other.cudaDebt.compareTo(cudaDebt) == 0 && other.cudaShortTermDebt.compareTo(cudaShortTermDebt) == 0 &&
other.cudaBackoffTime.compareTo(cudaBackoffTime) == 0 && other.cudaBackoffInterval.compareTo(cudaBackoffInterval) == 0 &&
other.atiDebt.compareTo(atiDebt) == 0 && other.atiShortTermDebt.compareTo(atiShortTermDebt) == 0 &&
other.atiBackoffTime.compareTo(atiBackoffTime) == 0 && other.atiBackoffInterval.compareTo(atiBackoffInterval) == 0 &&
other.durationCorrectionFactor.compareTo(durationCorrectionFactor) == 0 &&
masterURLFetchPending == other.masterURLFetchPending && scheduledRPCPending == other.scheduledRPCPending &&
nonCPUIntensive == other.nonCPUIntensive && suspendedViaGUI == other.suspendedViaGUI &&
doNotRequestMoreWork == other.doNotRequestMoreWork && schedulerRPCInProgress == other.schedulerRPCInProgress &&
attachedViaAcctMgr == other.attachedViaAcctMgr && detachWhenDone == other.detachWhenDone &&
ended == other.ended && trickleUpPending == other.trickleUpPending &&
other.projectFilesDownloadedTime.compareTo(projectFilesDownloadedTime) == 0 &&
other.lastRPCTime.compareTo(lastRPCTime) == 0 && noCPUPref == other.noCPUPref &&
noCUDAPref == other.noCUDAPref && noATIPref == other.noATIPref &&
masterURL.equals(other.masterURL, ignoreCase = true) && projectDir == other.projectDir &&
projectName == other.projectName && userName.equals(other.userName, ignoreCase = true) &&
teamName == other.teamName && hostVenue == other.hostVenue && guiURLs == other.guiURLs
}
override fun hashCode() = Objects.hash(
masterURL.lowercase(Locale.ROOT), projectDir, resourceShare,
projectName, userName.lowercase(Locale.ROOT), teamName, hostVenue, hostId, guiURLs,
userTotalCredit, userExpAvgCredit, hostTotalCredit, hostExpAvgCredit, diskUsage,
noOfRPCFailures, masterFetchFailures, minRPCTime, downloadBackoff, uploadBackoff,
cpuShortTermDebt, cpuLongTermDebt, cpuBackoffTime, cpuBackoffInterval, cudaDebt,
cudaShortTermDebt, cudaBackoffTime, cudaBackoffInterval, atiDebt, atiShortTermDebt,
atiBackoffTime, atiBackoffInterval, durationCorrectionFactor, masterURLFetchPending,
scheduledRPCPending, nonCPUIntensive, suspendedViaGUI, doNotRequestMoreWork,
schedulerRPCInProgress, attachedViaAcctMgr, detachWhenDone, ended, trickleUpPending,
projectFilesDownloadedTime, lastRPCTime, noCPUPref, noCUDAPref, noATIPref)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(masterURL)
dest.writeString(projectDir)
dest.writeFloat(resourceShare)
dest.writeString(projectName)
dest.writeString(userName)
dest.writeString(teamName)
dest.writeString(hostVenue)
dest.writeInt(hostId)
dest.writeDouble(userTotalCredit)
dest.writeDouble(userExpAvgCredit)
dest.writeDouble(hostTotalCredit)
dest.writeDouble(hostExpAvgCredit)
dest.writeDouble(diskUsage)
dest.writeInt(noOfRPCFailures)
dest.writeInt(masterFetchFailures)
dest.writeDouble(minRPCTime)
dest.writeDouble(downloadBackoff)
dest.writeDouble(uploadBackoff)
dest.writeDouble(cpuShortTermDebt)
dest.writeDouble(cpuBackoffTime)
dest.writeDouble(cpuBackoffInterval)
dest.writeDouble(cudaDebt)
dest.writeDouble(cudaShortTermDebt)
dest.writeDouble(cudaBackoffTime)
dest.writeDouble(cudaBackoffInterval)
dest.writeDouble(atiDebt)
dest.writeDouble(atiShortTermDebt)
dest.writeDouble(atiBackoffTime)
dest.writeDouble(atiBackoffInterval)
dest.writeDouble(durationCorrectionFactor)
dest.writeInt(scheduledRPCPending)
dest.writeDouble(projectFilesDownloadedTime)
dest.writeDouble(lastRPCTime)
writeBoolean(dest, masterURLFetchPending)
writeBoolean(dest, nonCPUIntensive)
writeBoolean(dest, suspendedViaGUI)
writeBoolean(dest, doNotRequestMoreWork)
writeBoolean(dest, schedulerRPCInProgress)
writeBoolean(dest, attachedViaAcctMgr)
writeBoolean(dest, detachWhenDone)
writeBoolean(dest, ended)
writeBoolean(dest, trickleUpPending)
writeBoolean(dest, noCPUPref)
writeBoolean(dest, noCUDAPref)
writeBoolean(dest, noATIPref)
dest.writeList(guiURLs.toList())
}
object Fields {
const val PROJECT_DIR = "project_dir"
const val RESOURCE_SHARE = "resource_share"
const val USER_NAME = "user_name"
const val TEAM_NAME = "team_name"
const val HOST_VENUE = "host_venue"
const val HOSTID = "hostid"
const val USER_TOTAL_CREDIT = "user_total_credit"
const val USER_EXPAVG_CREDIT = "user_expavg_credit"
const val HOST_TOTAL_CREDIT = "host_total_credit"
const val HOST_EXPAVG_CREDIT = "host_expavg_credit"
const val NRPC_FAILURES = "nrpc_failures"
const val MASTER_FETCH_FAILURES = "master_fetch_failures"
const val MIN_RPC_TIME = "min_rpc_time"
const val DOWNLOAD_BACKOFF = "download_backoff"
const val UPLOAD_BACKOFF = "upload_backoff"
const val CPU_BACKOFF_TIME = "cpu_backoff_time"
const val CPU_BACKOFF_INTERVAL = "cpu_backoff_interval"
const val CUDA_DEBT = "cuda_debt"
const val CUDA_SHORT_TERM_DEBT = "cuda_short_term_debt"
const val CUDA_BACKOFF_TIME = "cuda_backoff_time"
const val CUDA_BACKOFF_INTERVAL = "cuda_backoff_interval"
const val ATI_DEBT = "ati_debt"
const val ATI_SHORT_TERM_DEBT = "ati_short_term_debt"
const val ATI_BACKOFF_TIME = "ati_backoff_time"
const val ATI_BACKOFF_INTERVAL = "ati_backoff_interval"
const val DURATION_CORRECTION_FACTOR = "duration_correction_factor"
const val MASTER_URL_FETCH_PENDING = "master_url_fetch_pending"
const val SCHED_RPC_PENDING = "sched_rpc_pending"
const val SUSPENDED_VIA_GUI = "suspended_via_gui"
const val DONT_REQUEST_MORE_WORK = "dont_request_more_work"
const val SCHEDULER_RPC_IN_PROGRESS = "scheduler_rpc_in_progress"
const val ATTACHED_VIA_ACCT_MGR = "attached_via_acct_mgr"
const val DETACH_WHEN_DONE = "detach_when_done"
const val ENDED = "ended"
const val TRICKLE_UP_PENDING = "trickle_up_pending"
const val PROJECT_FILES_DOWNLOADED_TIME = "project_files_downloaded_time"
const val LAST_RPC_TIME = "last_rpc_time"
const val NO_CPU_PREF = "no_cpu_pref"
const val NO_CUDA_PREF = "no_cuda_pref"
const val NO_ATI_PREF = "no_ati_pref"
const val DISK_USAGE = "disk_usage"
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<Project> = object : Parcelable.Creator<Project> {
override fun createFromParcel(parcel: Parcel) = Project(parcel)
override fun newArray(size: Int) = arrayOfNulls<Project>(size)
}
}
}
| lgpl-3.0 | 79c74aabaf253b44a9ff8ee5dee1d9ff | 52.575092 | 137 | 0.653425 | 4.828656 | false | false | false | false |
bozaro/git-as-svn | src/main/kotlin/svnserver/server/command/GetLocationsCmd.kt | 1 | 3559 | /*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.server.command
import org.tmatesoft.svn.core.SVNErrorCode
import org.tmatesoft.svn.core.SVNErrorMessage
import org.tmatesoft.svn.core.SVNException
import svnserver.parser.SvnServerWriter
import svnserver.repository.VcsCopyFrom
import svnserver.server.SessionContext
import java.io.IOException
import java.util.*
/**
* <pre>
* get-locations
* params: ( path:string peg-rev:number ( rev:number ... ) )
* Before sending response, server sends location entries, ending with "done".
* location-entry: ( rev:number abs-path:number ) | done
* response: ( )
</pre> *
*
* @author a.navrotskiy
*/
class GetLocationsCmd : BaseCmd<GetLocationsCmd.Params>() {
override val arguments: Class<out Params>
get() {
return Params::class.java
}
@Throws(IOException::class, SVNException::class)
override fun processCommand(context: SessionContext, args: Params) {
val writer: SvnServerWriter = context.writer
val sortedRevs: IntArray = args.revs.copyOf(args.revs.size)
Arrays.sort(sortedRevs)
var fullPath: String = context.getRepositoryPath(args.path)
var lastChange: Int? = context.branch.getLastChange(fullPath, args.pegRev)
if (lastChange == null) {
writer.word("done")
throw SVNException(SVNErrorMessage.create(SVNErrorCode.FS_NOT_FOUND, "File not found: " + fullPath + "@" + args.pegRev))
}
for (i in sortedRevs.indices.reversed()) {
val revision: Int = sortedRevs[i]
if (revision > args.pegRev) {
writer.word("done")
throw SVNException(SVNErrorMessage.create(SVNErrorCode.FS_NOT_FOUND, "File not found: " + fullPath + "@" + args.pegRev + " at revision " + revision))
}
while ((lastChange != null) && (revision < lastChange)) {
val change: Int? = context.branch.getLastChange(fullPath, lastChange - 1)
if (change != null) {
lastChange = change
continue
}
val copyFrom: VcsCopyFrom? = context.branch.getRevisionInfo(lastChange).getCopyFrom(fullPath)
if (copyFrom == null || !context.canRead(copyFrom.path)) {
lastChange = null
break
}
lastChange = copyFrom.revision
fullPath = copyFrom.path
}
if (lastChange == null) break
if (revision >= lastChange) {
writer
.listBegin()
.number(revision.toLong())
.string(fullPath)
.listEnd()
}
}
writer
.word("done")
writer
.listBegin()
.word("success")
.listBegin()
.listEnd()
.listEnd()
}
@Throws(IOException::class, SVNException::class)
override fun permissionCheck(context: SessionContext, args: Params) {
context.checkRead(context.getRepositoryPath(args.path))
}
class Params constructor(val path: String, val pegRev: Int, val revs: IntArray)
}
| gpl-2.0 | 67b3d15062cef332da6eaf515018763c | 37.684783 | 165 | 0.604664 | 4.372236 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/input/SwipeComponent.kt | 1 | 4039 | package com.soywiz.korge.input
import com.soywiz.korge.view.*
import com.soywiz.korma.geom.*
import kotlin.math.*
data class SwipeInfo(
var dx: Double = 0.0,
var dy: Double = 0.0,
var direction: SwipeDirection
) {
fun setTo(dx: Double, dy: Double, direction: SwipeDirection): SwipeInfo {
this.dx = dx
this.dy = dy
this.direction = direction
return this
}
}
enum class SwipeDirection {
LEFT, RIGHT, TOP, BOTTOM
}
/**
* This methods lets you specify a [callback] to execute when swipe event is triggered.
* @property threshold a threshold for dx or dy after which a swipe event should be triggered.
* Negative [threshold] means a swipe event should be triggered only after [onUp] mouse event.
* [threshold] is set to -1 by default.
* @property direction a direction for which a swipe event should be triggered.
* [direction] is set to null by default, which means a swipe event should be triggered for any direction.
* @property callback a callback to execute
*/
fun <T : View> T.onSwipe(
threshold: Double = -1.0,
direction: SwipeDirection? = null,
callback: suspend Views.(SwipeInfo) -> Unit
): T {
var register = false
var sx = 0.0
var sy = 0.0
var cx = 0.0
var cy = 0.0
var movedLeft = false
var movedRight = false
var movedTop = false
var movedBottom = false
val view = this
val mousePos = Point()
val swipeInfo = SwipeInfo(0.0, 0.0, SwipeDirection.TOP)
fun views() = view.stage!!.views
fun updateMouse() {
val views = views()
mousePos.setTo(
views.nativeMouseX,
views.nativeMouseY
)
}
fun updateCoordinates() {
if (mousePos.x < cx) movedLeft = true
if (mousePos.x > cx) movedRight = true
if (mousePos.y < cy) movedTop = true
if (mousePos.y > cy) movedBottom = true
cx = mousePos.x
cy = mousePos.y
}
suspend fun triggerEvent(direction: SwipeDirection) {
register = false
views().callback(swipeInfo.setTo(cx - sx, cy - sy, direction))
}
suspend fun checkPositionOnMove() {
if (threshold < 0) return
val curDirection = when {
sx - cx > threshold && !movedRight -> SwipeDirection.LEFT
cx - sx > threshold && !movedLeft -> SwipeDirection.RIGHT
sy - cy > threshold && !movedBottom -> SwipeDirection.TOP
cy - sy > threshold && !movedTop -> SwipeDirection.BOTTOM
else -> return
}
if (direction == null || direction == curDirection) {
triggerEvent(curDirection)
}
}
suspend fun checkPositionOnUp() {
if (threshold >= 0) return
val horDiff = abs(cx - sx)
val verDiff = abs(cy - sy)
val curDirection = when {
horDiff >= verDiff && cx < sx && !movedRight -> SwipeDirection.LEFT
horDiff >= verDiff && cx > sx && !movedLeft -> SwipeDirection.RIGHT
horDiff <= verDiff && cy < sy && !movedBottom -> SwipeDirection.TOP
horDiff <= verDiff && cy > sy && !movedTop -> SwipeDirection.BOTTOM
else -> return
}
if (direction == null || direction == curDirection) {
triggerEvent(curDirection)
}
}
this.mouse {
onDown {
updateMouse()
register = true
sx = mousePos.x
sy = mousePos.y
cx = sx
cy = sy
movedLeft = false
movedRight = false
movedTop = false
movedBottom = false
}
onMoveAnywhere {
if (register) {
updateMouse()
updateCoordinates()
checkPositionOnMove()
}
}
onUpAnywhere {
if (register) {
updateMouse()
updateCoordinates()
register = false
checkPositionOnUp()
}
}
}
return this
}
| apache-2.0 | 37826f36a086673b1e8dea8f9f362b4d | 28.698529 | 106 | 0.566229 | 4.443344 | false | false | false | false |
JavaProphet/JASM | src/main/java/com/protryon/jasm/Field.kt | 1 | 472 | package com.protryon.jasm
class Field(val parent: Klass, var type: JType, var name: String) {
var isPublic = false
var isPrivate = false
var isProtected = false
var isStatic = false
var isFinal = false
var isVolatile = false
var isTransient = false
var isSynthetic = false
var isEnum = false
var constantValue: Constant<*>? = null
// set for created methods in things like stdlib or unincluded libs
var isDummy = false
}
| gpl-3.0 | c42113222a4853aaf092ab2579734b8f | 25.222222 | 71 | 0.680085 | 4.411215 | false | false | false | false |
openstreetview/android | app/src/androidTest/java/com/telenav/osv/ui/fragment/settings/DistanceUnitViewModelTest.kt | 1 | 3173 | package com.telenav.osv.ui.fragment.settings
import android.Manifest
import android.content.Context
import android.view.View
import android.widget.RadioGroup
import androidx.preference.PreferenceViewHolder
import androidx.test.InstrumentationRegistry
import androidx.test.annotation.UiThreadTest
import androidx.test.rule.GrantPermissionRule
import com.telenav.osv.R
import com.telenav.osv.application.ApplicationPreferences
import com.telenav.osv.application.KVApplication
import com.telenav.osv.application.PreferenceTypes
import com.telenav.osv.ui.fragment.settings.custom.RadioGroupPreference
import com.telenav.osv.ui.fragment.settings.viewmodel.DistanceUnitViewModel
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.mockito.MockitoAnnotations
class DistanceUnitViewModelTest {
private lateinit var viewModel: DistanceUnitViewModel
private lateinit var context: Context
private lateinit var appPrefs: ApplicationPreferences
@Before
fun setUp() {
GrantPermissionRule.grant(Manifest.permission.CAMERA)
context = InstrumentationRegistry.getTargetContext()
val app = InstrumentationRegistry.getTargetContext().applicationContext as KVApplication
MockitoAnnotations.initMocks(this)
appPrefs = ApplicationPreferences(app)
viewModel = DistanceUnitViewModel(app, appPrefs)
}
@Test
@UiThreadTest
fun testDistanceUnitClick() {
val preference = getGroupPreference()
val checkedChangeListener = preference.onCheckedChangeListener
var preferenceChanged = false
preference.onCheckedChangeListener = (RadioGroup.OnCheckedChangeListener { radioGroup, i ->
preferenceChanged = true
checkedChangeListener.onCheckedChanged(radioGroup, i)
})
preference.onBindViewHolder(PreferenceViewHolder.createInstanceForTests(View.inflate(context, R.layout.settings_item_radio_group, null)))
preference.radioButtonList[0].isChecked = false
preference.radioButtonList[0].isChecked = true
Assert.assertTrue(preferenceChanged)
val distanceUnitTag = preference.radioButtonList[0].tag as Int
Assert.assertEquals(distanceUnitTag == DistanceUnitViewModel.TAG_METRIC, appPrefs.getBooleanPreference(PreferenceTypes.K_DISTANCE_UNIT_METRIC))
}
@Test
@UiThreadTest
fun testStoredDistanceUnitCheckedWhenDisplayingTheList() {
val preference = getGroupPreference()
for (radioButton in preference.radioButtonList) {
if (radioButton.isChecked) {
val distanceUnitTag = radioButton.tag as Int
Assert.assertEquals(distanceUnitTag == DistanceUnitViewModel.TAG_METRIC, appPrefs.getBooleanPreference(PreferenceTypes.K_DISTANCE_UNIT_METRIC))
return
}
}
Assert.assertTrue(false)
}
private fun getGroupPreference(): RadioGroupPreference {
viewModel.settingsDataObservable
viewModel.start()
val settingsGroups = viewModel.settingsDataObservable.value!!
return settingsGroups[0].getPreference(context) as RadioGroupPreference
}
} | lgpl-3.0 | 03caead4693984986822fc1a2b8119f2 | 40.763158 | 159 | 0.756697 | 5.350759 | false | true | false | false |
lare96/luna | plugins/api/event/InterceptUseItem.kt | 1 | 845 | package api.event
import io.luna.game.event.impl.ItemOnItemEvent
import io.luna.game.event.impl.ItemOnObjectEvent
/**
* A model that intercepts [ItemOnItemEvent]s and [ItemOnObjectEvent]s.
*
* @author lare96
*/
class InterceptUseItem(private val id: Int) {
/**
* Intercepts an [ItemOnItemEvent]. **Will match both ways!**
*/
fun onItem(itemId: Int, action: ItemOnItemEvent.() -> Unit) {
val matcher = Matcher.get<ItemOnItemEvent, Pair<Int, Int>>()
matcher[id to itemId] = { action(this) }
matcher[itemId to id] = { action(this) }
}
/**
* Intercepts an [ItemOnObjectEvent].
*/
fun onObject(objectId: Int, action: ItemOnObjectEvent.() -> Unit) {
val matcher = Matcher.get<ItemOnObjectEvent, Pair<Int, Int>>()
matcher[id to objectId] = { action(this) }
}
} | mit | c8c7791631f1f81328bd98e2b2e64070 | 28.172414 | 71 | 0.64142 | 3.738938 | false | false | false | false |
cossacklabs/themis | docs/examples/android/app/src/main/java/com/cossacklabs/themis/android/example/MainActivitySecureMessage.kt | 1 | 2379 | package com.cossacklabs.themis.android.example
import android.os.Bundle
import android.util.Base64
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.cossacklabs.themis.PrivateKey
import com.cossacklabs.themis.PublicKey
import com.cossacklabs.themis.SecureMessage
import java.nio.charset.StandardCharsets
import java.util.*
class MainActivitySecureMessage : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Check secure message
try {
secureMessageLocal()
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun secureMessageLocal() {
val charset = StandardCharsets.UTF_8
val clientPrivateKey = "UkVDMgAAAC1EvnquAPUxxwJsoJxoMAkEF7c06Fo7dVwnWPnmNX5afyjEEGmG"
val serverPublicKey = "VUVDMgAAAC1FJv/DAmg8/L1Pl5l6ypyRqXUU9xQQaAgzfRZ+/gsjqgEdwXhc"
val message = "some weird message here"
val privateKey = PrivateKey(Base64.decode(clientPrivateKey.toByteArray(charset(charset.name())), Base64.NO_WRAP))
val publicKey = PublicKey(Base64.decode(serverPublicKey.toByteArray(charset(charset.name())), Base64.NO_WRAP))
Log.d("SMC", "privateKey1 = " + Arrays.toString(privateKey.toByteArray()))
Log.d("SMC", "publicKey1 = " + Arrays.toString(publicKey.toByteArray()))
val sm = SecureMessage(privateKey, publicKey)
val wrappedMessage = sm.wrap(message.toByteArray(charset(charset.name())))
val encodedMessage = Base64.encodeToString(wrappedMessage, Base64.NO_WRAP)
Log.d("SMC", "EncodedMessage = $encodedMessage")
val wrappedMessageFromB64 = Base64.decode(encodedMessage, Base64.NO_WRAP)
val decodedMessage = String(sm.unwrap(wrappedMessageFromB64), charset)
Log.d("SMC", "DecodedMessageFromOwnCode = $decodedMessage")
val encodedMessageFromExternal = "ICcEJksAAAAAAQFADAAAABAAAAAXAAAAFi/vBAb2fiNBqf3a6wgyVoMAdPXpJ14ZYxk/oaUcwSmKnNgmRzaH7JkIQBvFChAVK9tF"
val wrappedMessageFromB64External = Base64.decode(encodedMessageFromExternal, Base64.NO_WRAP)
val decodedMessageExternal = String(sm.unwrap(wrappedMessageFromB64External), charset)
Log.d("SMC", "DecodedMessageFromExternal = $decodedMessageExternal")
}
}
| apache-2.0 | 5ee15a74dc00403ed23ef4e080485222 | 49.617021 | 143 | 0.738966 | 3.682663 | false | false | false | false |
AlexLandau/semlang | kotlin/semlang-transforms/src/main/kotlin/RenamingStrategy.kt | 1 | 653 | package net.semlang.transforms
typealias RenamingStrategy = (name: String, allNamesPresent: Set<String>) -> String
object RenamingStrategies {
fun getKeywordAvoidingStrategy(keywords: Set<String>): RenamingStrategy {
return fun(varName: String, allVarNamesPresent: Set<String>): String {
if (!keywords.contains(varName)) {
return varName
}
var suffix = 1
var newName = varName + suffix
while (allVarNamesPresent.contains(newName)) {
suffix += 1
newName = varName + suffix
}
return newName
}
}
}
| apache-2.0 | c4e49d41e09e2aeb9174171974e976b2 | 31.65 | 83 | 0.584992 | 5.062016 | false | false | false | false |
Devifish/ReadMe | app/src/main/java/cn/devifish/readme/view/adapter/BookDetailRecyclerAdapter.kt | 1 | 3378 | package cn.devifish.readme.view.adapter
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cn.devifish.readme.R
import cn.devifish.readme.entity.Book
import cn.devifish.readme.provider.BookProvider
import cn.devifish.readme.service.BookService
import cn.devifish.readme.util.RxJavaUtil
import cn.devifish.readme.view.base.BaseRecyclerAdapter
import cn.devifish.readme.view.base.BaseViewHolder
import kotlinx.android.synthetic.main.header_book_detail.view.*
import kotlinx.android.synthetic.main.list_item_stack.view.*
import java.text.SimpleDateFormat
/**
* Created by zhang on 2017/8/3.
* 书籍详情列表适配器
*/
class BookDetailRecyclerAdapter(val book: Book) : BaseRecyclerAdapter<Any, BaseViewHolder<Any>>() {
private val bookProvider = BookProvider.getInstance().create(BookService::class.java)
companion object {
val TYPE_DETAIL = 0
val TYPE_BETTER = 1
val TYPE_NORMAL = 2
}
override fun getItemViewType(position: Int): Int {
when (position) {
0 -> return TYPE_DETAIL
1 -> return TYPE_BETTER
else -> return TYPE_NORMAL
}
}
override fun onCreateView(group: ViewGroup, viewType: Int): BaseViewHolder<Any> {
val layoutInflater = LayoutInflater.from(group.context)
when (viewType) {
TYPE_DETAIL -> {
val view = layoutInflater.inflate(R.layout.header_book_detail, group, false)
return BookDetailHolder(view)
}
TYPE_BETTER -> {
val view = layoutInflater.inflate(R.layout.list_item_stack, group, false)
return BetterBookHolder(view)
}
TYPE_NORMAL -> {
}
}
val view = layoutInflater.inflate(R.layout.header_book_detail, group, false)
return BookDetailHolder(view)
}
override fun onBindView(holder: BaseViewHolder<Any>, position: Int) {
when (getItemViewType(position)) {
TYPE_DETAIL -> (holder as BookDetailHolder).bind(book)
TYPE_BETTER -> (holder as BetterBookHolder).bind(book)
TYPE_NORMAL -> {
}
}
}
override fun getItemCount(): Int = if (super.getItemCount() < 2) 2 else super.getItemCount()
inner class BookDetailHolder(itemView: View) : BaseViewHolder<Any>(itemView) {
@SuppressLint("SimpleDateFormat")
override fun bind(m: Any) {
val context = itemView.context
RxJavaUtil.getObservable(bookProvider.getBookDetail((m as Book)._id!!))
.subscribe { bookDetail ->
itemView.serial_info.text = context.getString(if (bookDetail.isSerial) R.string.book_serial else R.string.book_end)
itemView.update.text = SimpleDateFormat("yyyy-MM-dd").format(bookDetail.updated)
itemView.chapter_count.text = context.getString(R.string.book_chapterCount, bookDetail.chaptersCount.toString())
itemView.book_intro.text = bookDetail.longIntro
}
}
}
inner class BetterBookHolder(itemView: View) : BaseViewHolder<Any>(itemView) {
override fun bind(m: Any) {
itemView.name.text = "更多书籍"
}
}
} | apache-2.0 | 79a247ee72233b32e8d22fd5b74b1e67 | 33.214286 | 139 | 0.642005 | 4.387435 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/splashscreen/SplashScreenView.kt | 2 | 1210 | package abi43_0_0.expo.modules.splashscreen
import android.annotation.SuppressLint
import android.content.Context
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
// this needs to stay for versioning to work
/* ktlint-disable no-unused-imports */
import expo.modules.splashscreen.SplashScreenImageResizeMode
/* ktlint-enable no-unused-imports */
@SuppressLint("ViewConstructor")
class SplashScreenView(
context: Context
) : RelativeLayout(context) {
val imageView: ImageView = ImageView(context).also { view ->
view.layoutParams = LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT
)
}
init {
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
isClickable = true
addView(imageView)
}
fun configureImageViewResizeMode(resizeMode: SplashScreenImageResizeMode) {
imageView.scaleType = resizeMode.scaleType
when (resizeMode) {
SplashScreenImageResizeMode.NATIVE -> {}
SplashScreenImageResizeMode.CONTAIN -> {
imageView.adjustViewBounds = true
}
SplashScreenImageResizeMode.COVER -> {}
}
}
}
| bsd-3-clause | 9ae9202d1b3c29d230a76a919669fb30 | 27.809524 | 115 | 0.753719 | 4.801587 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/SurveyQuestion.kt | 1 | 1763 | package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.common.Entity
import com.vimeo.networking2.enums.SurveyQuestionType
import com.vimeo.networking2.enums.asEnum
/**
* A representation of a user-facing survey question. Questions are expected to be presented to a user with
* a series of multiple-choice responses to select as an answer.
*
* @param analyticsId The id that should be used when logging this [SurveyQuestion].
* @param resourceKey A globally unique identifier.
* @param titleEmoji A unicode emoji character in “surrogate pair” representation (e.g. \uD83D\uDC4B).
* @param question The survey question that the user should be asked. This string will be localized.
* @param rawType The type of the survey question. See [SurveyQuestion.type].
* @param responseChoices A list of [SurveyResponseChoices][SurveyResponseChoice] to present to a user as valid
* answers to the question. The order of this list will be randomized by the Vimeo api.
*
*/
@JsonClass(generateAdapter = true)
data class SurveyQuestion(
@Json(name = "analytics_id")
val analyticsId: String? = null,
@Json(name = "resource_key")
val resourceKey: String? = null,
@Json(name = "title_emoji")
val titleEmoji: String? = null,
@Json(name = "title")
val question: String? = null,
@Json(name = "type")
val rawType: String? = null,
@Json(name = "answers")
val responseChoices: List<SurveyResponseChoice>? = null
) : Entity {
override val identifier: String? = resourceKey
}
/**
* @see SurveyQuestionType
* @see SurveyQuestion.rawType
*/
val SurveyQuestion.type: SurveyQuestionType
get() = rawType.asEnum(SurveyQuestionType.UNKNOWN)
| mit | 41b071bf371c437c56c394945e829486 | 32.826923 | 111 | 0.736214 | 4.025172 | false | false | false | false |
SimpleMobileTools/Simple-Commons | commons/src/main/kotlin/com/simplemobiletools/commons/views/MyTextInputLayout.kt | 1 | 2268 | package com.simplemobiletools.commons.views
import android.content.Context
import android.content.res.ColorStateList
import android.util.AttributeSet
import com.google.android.material.textfield.TextInputLayout
import com.simplemobiletools.commons.extensions.adjustAlpha
import com.simplemobiletools.commons.extensions.value
import com.simplemobiletools.commons.helpers.HIGHER_ALPHA
import com.simplemobiletools.commons.helpers.MEDIUM_ALPHA
class MyTextInputLayout : TextInputLayout {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
// we need to use reflection to make some colors work well
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
try {
editText!!.setTextColor(textColor)
editText!!.backgroundTintList = ColorStateList.valueOf(accentColor)
val hintColor = if (editText!!.value.isEmpty()) textColor.adjustAlpha(HIGHER_ALPHA) else textColor
val defaultTextColor = TextInputLayout::class.java.getDeclaredField("defaultHintTextColor")
defaultTextColor.isAccessible = true
defaultTextColor.set(this, ColorStateList(arrayOf(intArrayOf(0)), intArrayOf(hintColor)))
val focusedTextColor = TextInputLayout::class.java.getDeclaredField("focusedTextColor")
focusedTextColor.isAccessible = true
focusedTextColor.set(this, ColorStateList(arrayOf(intArrayOf(0)), intArrayOf(accentColor)))
val defaultHintTextColor = textColor.adjustAlpha(MEDIUM_ALPHA)
val boxColorState = ColorStateList(
arrayOf(
intArrayOf(android.R.attr.state_active),
intArrayOf(android.R.attr.state_focused)
),
intArrayOf(
defaultHintTextColor,
accentColor
)
)
setBoxStrokeColorStateList(boxColorState)
defaultTextColor.set(this, ColorStateList(arrayOf(intArrayOf(0)), intArrayOf(defaultHintTextColor)))
} catch (e: Exception) {
}
}
}
| gpl-3.0 | f235d3b4fd14fcca2fd3c070622b170e | 43.470588 | 112 | 0.694885 | 5.349057 | false | false | false | false |
androidx/androidx | compose/ui/ui-text/samples/src/main/java/androidx/compose/ui/text/samples/VisualTransformationSamples.kt | 3 | 2808 | /*
* Copyright 2019 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.samples
import androidx.annotation.Sampled
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.input.OffsetMapping
import androidx.compose.ui.text.input.TransformedText
@Sampled
fun passwordFilter(text: AnnotatedString): TransformedText {
return TransformedText(
AnnotatedString("*".repeat(text.text.length)),
/**
* [OffsetMapping.Identity] is a predefined [OffsetMapping] that can be used for the
* transformation that does not change the character count.
*/
OffsetMapping.Identity
)
}
@Sampled
fun creditCardFilter(text: AnnotatedString): TransformedText {
// Making XXXX-XXXX-XXXX-XXXX string.
val trimmed = if (text.text.length >= 16) text.text.substring(0..15) else text.text
var out = ""
for (i in trimmed.indices) {
out += trimmed[i]
if (i % 4 == 3 && i != 15) out += "-"
}
/**
* The offset translator should ignore the hyphen characters, so conversion from
* original offset to transformed text works like
* - The 4th char of the original text is 5th char in the transformed text.
* - The 13th char of the original text is 15th char in the transformed text.
* Similarly, the reverse conversion works like
* - The 5th char of the transformed text is 4th char in the original text.
* - The 12th char of the transformed text is 10th char in the original text.
*/
val creditCardOffsetTranslator = object : OffsetMapping {
override fun originalToTransformed(offset: Int): Int {
if (offset <= 3) return offset
if (offset <= 7) return offset + 1
if (offset <= 11) return offset + 2
if (offset <= 16) return offset + 3
return 19
}
override fun transformedToOriginal(offset: Int): Int {
if (offset <= 4) return offset
if (offset <= 9) return offset - 1
if (offset <= 14) return offset - 2
if (offset <= 19) return offset - 3
return 16
}
}
return TransformedText(AnnotatedString(out), creditCardOffsetTranslator)
}
| apache-2.0 | f8905d41136d60fa1479f8517a41f751 | 35.947368 | 92 | 0.665242 | 4.408163 | false | false | false | false |
DemonWav/StatCraft | src/main/kotlin/com/demonwav/statcraft/listeners/OnFireListener.kt | 1 | 3631 | /*
* StatCraft Bukkit Plugin
*
* Copyright (c) 2016 Kyle Wood (DemonWav)
* https://www.demonwav.com
*
* MIT License
*/
package com.demonwav.statcraft.listeners
import com.demonwav.statcraft.StatCraft
import com.demonwav.statcraft.querydsl.QOnFire
import org.bukkit.ChatColor
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.event.entity.EntityCombustByBlockEvent
import org.bukkit.event.entity.EntityCombustByEntityEvent
import org.bukkit.event.entity.EntityCombustEvent
import org.bukkit.event.entity.EntityDamageEvent
import org.bukkit.potion.PotionEffectType
import java.util.HashMap
import java.util.UUID
class OnFireListener(private val plugin: StatCraft) : Listener {
private val lastSource = HashMap<UUID, String>()
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
fun onFire(event: EntityDamageEvent) {
if (event.entity is Player) {
val cause = event.cause
if (cause == EntityDamageEvent.DamageCause.FIRE_TICK) {
val uuid = event.entity.uniqueId
val worldName = event.entity.world.name
val source = lastSource[uuid]
plugin.threadManager.schedule<QOnFire>(
uuid, worldName,
{ o, clause, id, worldId ->
clause.columns(o.id, o.worldId, o.source, o.time).values(id, worldId, source, 1).execute()
}, { o, clause, id, worldId ->
clause.where(o.id.eq(id), o.worldId.eq(worldId), o.source.eq(source)).set(o.time, o.time.add(1)).execute()
}
)
}
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
fun onCombust(event: EntityCombustEvent) {
if (!plugin.config.stats.onFireAnnounce) {
return
}
if (event.entity is Player) {
val uuid = event.entity.uniqueId
if (System.currentTimeMillis() / 1000 - plugin.getLastFireTime(uuid) > 60) {
val giveWarning = (event.entity as Player).activePotionEffects.any { it.type == PotionEffectType.FIRE_RESISTANCE }
if (giveWarning) {
event.entity.server.broadcastMessage(
ChatColor.RED.toString() +
plugin.config.stats.onFireAnnounceMessage.replace(
"~".toRegex(),
(event.entity as Player).displayName + ChatColor.RED)
)
plugin.setLastFireTime(uuid, (System.currentTimeMillis() / 1000).toInt())
}
}
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
fun onCombustByBlock(event: EntityCombustByBlockEvent) {
if (event.entity is Player) {
val player = event.entity as Player
lastSource[player.uniqueId] = "BLOCK"
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
fun onCombustByEntity(event: EntityCombustByEntityEvent) {
if (event.entity is Player) {
val player = event.entity as Player
if (event.combuster is Player) {
val id = plugin.databaseManager.getPlayerId(event.combuster.uniqueId) ?: return
lastSource.put(player.uniqueId, id.toString())
} else {
lastSource.put(player.uniqueId, event.combuster.name)
}
}
}
}
| mit | d3585524f8c911520174bf7ed7cabe93 | 36.05102 | 130 | 0.613054 | 4.449755 | false | false | false | false |
codehz/container | app/src/main/java/one/codehz/container/DetailActivity.kt | 1 | 6866 | package one.codehz.container
import android.app.Activity
import android.app.ActivityManager
import android.app.ActivityOptions
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.support.design.widget.CollapsingToolbarLayout
import android.support.design.widget.TabLayout
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.graphics.Palette
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.ImageView
import com.lody.virtual.os.VUserHandle
import one.codehz.container.base.BaseActivity
import one.codehz.container.ext.get
import one.codehz.container.ext.setBackground
import one.codehz.container.ext.systemService
import one.codehz.container.ext.virtualCore
import one.codehz.container.fragment.BasicDetailFragment
import one.codehz.container.fragment.ComponentDetailFragment
import one.codehz.container.models.AppModel
class DetailActivity : BaseActivity(R.layout.application_detail) {
companion object {
val RESULT_DELETE_APK = 1
val REQUEST_USER = 0
val REQUEST_USER_FOR_SHORTCUT = 1
fun launch(context: Activity, appModel: AppModel, iconView: View, startFn: (Intent, Bundle) -> Unit) {
startFn(Intent(context, DetailActivity::class.java).apply {
action = Intent.ACTION_VIEW
data = Uri.Builder().scheme("container").authority("detail").appendPath(appModel.packageName).build()
}, ActivityOptions.makeSceneTransitionAnimation(context, iconView, "app_icon").toBundle())
}
}
val package_name: String by lazy { intent.data.path.substring(1) }
val model by lazy { AppModel(this, virtualCore.findApp(package_name)) }
val iconView by lazy<ImageView> { this[R.id.icon] }
val viewPager by lazy<ViewPager> { this[R.id.viewPager] }
val tabLayout by lazy<TabLayout> { this[R.id.tabs] }
val collapsingToolbar by lazy<CollapsingToolbarLayout> { this[R.id.collapsing_toolbar] }
var bgcolor = 0
val handler = Handler()
inner class DetailPagerAdapter : FragmentPagerAdapter(supportFragmentManager) {
override fun getItem(position: Int) = when (position) {
0 -> BasicDetailFragment(model) {
it.setBackground(bgcolor)
it.show()
}
1 -> ComponentDetailFragment(model) {
it.setBackground(bgcolor)
it.show()
}
else -> throw IllegalArgumentException()
}
override fun getPageTitle(position: Int) = when (position) {
0 -> getString(R.string.basic_info)!!
1 -> getString(R.string.component_filter)!!
else -> throw IllegalArgumentException()
}
override fun getCount() = 2
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setResult(Activity.RESULT_CANCELED)
postponeEnterTransition()
supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
setDisplayShowHomeEnabled(true)
}
iconView.setImageDrawable(model.icon)
Palette.from(model.icon.bitmap).apply { maximumColorCount(1) }.generate { palette ->
try {
val (main_color) = palette.swatches
val dark_color = Color.HSVToColor(floatArrayOf(0f, 0f, 0f).apply { Color.colorToHSV(main_color.rgb, this) }.apply { this[2] *= 0.8f })
window.statusBarColor = dark_color
window.navigationBarColor = dark_color
bgcolor = dark_color
collapsingToolbar.background = ColorDrawable(main_color.rgb)
setTaskDescription(ActivityManager.TaskDescription(getString(R.string.task_detail_prefix, model.name), model.icon.bitmap, dark_color))
} catch (e: Exception) {
e.printStackTrace()
} finally {
startPostponedEnterTransition()
}
}
tabLayout.setupWithViewPager(viewPager)
with(viewPager) {
adapter = DetailPagerAdapter()
}
collapsingToolbar.title = model.name
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.detail_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
finishAfterTransition()
true
}
R.id.run -> {
LoadingActivity.launch(this, model, VUserHandle.USER_OWNER, iconView)
true
}
R.id.run_as -> {
startActivityForResult(Intent(this, UserSelectorActivity::class.java), REQUEST_USER)
true
}
R.id.uninstall -> {
setResult(RESULT_DELETE_APK, intent)
finishAfterTransition()
true
}
R.id.send_to_desktop -> {
startActivityForResult(Intent(this, UserSelectorActivity::class.java), REQUEST_USER_FOR_SHORTCUT)
true
}
else -> false
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
REQUEST_USER -> if (resultCode == Activity.RESULT_OK) {
data!!
handler.post {
LoadingActivity.launch(this, model, data.getIntExtra(UserSelectorActivity.KEY_USER_ID, 0), iconView)
}
}
REQUEST_USER_FOR_SHORTCUT -> if (resultCode == Activity.RESULT_OK) {
data!!
sendBroadcast(Intent("com.android.launcher.action.INSTALL_SHORTCUT").apply {
val size = systemService<ActivityManager>(Context.ACTIVITY_SERVICE).launcherLargeIconSize
val scaledIcon = Bitmap.createScaledBitmap(model.icon.bitmap, size, size, false)
putExtra(Intent.EXTRA_SHORTCUT_INTENT, Intent(this@DetailActivity, VLoadingActivity::class.java).apply {
this.data = Uri.Builder().scheme("container").authority("launch").appendPath(model.packageName).fragment(data.getIntExtra(UserSelectorActivity.KEY_USER_ID, 0).toString()).build()
})
putExtra(Intent.EXTRA_SHORTCUT_NAME, model.name)
putExtra(Intent.EXTRA_SHORTCUT_ICON, scaledIcon)
putExtra("duplicate", false)
})
}
}
}
} | gpl-3.0 | 1695803879497647d5fd5ae1814fd90c | 38.465517 | 202 | 0.631809 | 4.77801 | false | false | false | false |
teobaranga/T-Tasks | t-tasks/src/main/java/com/teo/ttasks/LateInit.kt | 1 | 721 | package com.teo.ttasks
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
open class LateInit<T : Any>(
private val getter: FieldHolder<T>.() -> T = { field },
private val setter: FieldHolder<T>.(T) -> Unit = { field = it }
) : ReadWriteProperty<Any?, T> {
private val fieldHolder = FieldHolder<T>()
override fun getValue(thisRef: Any?, property: KProperty<*>) = fieldHolder.getter()
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = fieldHolder.setter(value)
class FieldHolder<T : Any> {
lateinit var field: T
/** Check if the backing field has been initialized. */
fun isInitialized() = ::field.isInitialized
}
}
| apache-2.0 | a87c4c71b69788de0a94c165f069dbef | 30.347826 | 102 | 0.669903 | 4.12 | false | false | false | false |
anlun/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/debugger/config/DebuggerConfigurable.kt | 1 | 5423 | package org.jetbrains.haskell.debugger.config
import com.intellij.openapi.options.Configurable
import javax.swing.JComponent
import com.intellij.openapi.ui.ComboBox
import javax.swing.DefaultComboBoxModel
import com.intellij.ui.DocumentAdapter
import javax.swing.event.DocumentEvent
import java.awt.event.ItemListener
import java.awt.event.ItemEvent
import javax.swing.JPanel
import java.awt.GridBagLayout
import org.jetbrains.haskell.util.gridBagConstraints
import java.awt.Insets
import javax.swing.JLabel
import org.jetbrains.haskell.util.setConstraints
import java.awt.GridBagConstraints
import javax.swing.Box
import javax.swing.JCheckBox
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import org.jetbrains.haskell.debugger.utils.UIUtils
import javax.swing.JButton
import javax.swing.AbstractAction
import java.awt.event.ActionEvent
/**
* Manages debugger settings. Creates additional section in IDEA Settings and tracks changes appeared there to obtain
* debugger settings. The settings are as follows:
* 1) user can select what debugger he would like to use
* 2) user can switch ':trace' command off
*
* @author Habibullin Marat
*/
public class DebuggerConfigurable() : Configurable {
companion object {
private val ITEM_GHCI = "GHCi"
private val ITEM_REMOTE = "Remote"
private val TRACE_CHECKBOX_LABEL = "Switch off ':trace' command"
private val PRINT_DEBUG_OUTPUT_LABEL = "Print debugger output to stdout"
}
private val selectDebuggerComboBox: ComboBox = ComboBox(DefaultComboBoxModel(arrayOf(ITEM_GHCI, ITEM_REMOTE)))
private val remoteDebuggerPathField: TextFieldWithBrowseButton = TextFieldWithBrowseButton()
private val traceSwitchOffCheckBox: JCheckBox = JCheckBox(TRACE_CHECKBOX_LABEL, false)
private val printDebugOutputCheckBox: JCheckBox = JCheckBox(PRINT_DEBUG_OUTPUT_LABEL, false)
private var isModified = false
override fun getDisplayName(): String? = "Haskell debugger"
override fun getHelpTopic(): String? = null
/**
* Creates UI for settings page
*/
override fun createComponent(): JComponent? {
remoteDebuggerPathField.addBrowseFolderListener(
"Select remote debugger executable",
null,
null,
FileChooserDescriptorFactory.createSingleLocalFileDescriptor())
val itemListener = object : ItemListener {
override fun itemStateChanged(e: ItemEvent) {
isModified = true
}
}
val docListener : DocumentAdapter = object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent?) {
isModified = true
}
};
selectDebuggerComboBox.addItemListener(itemListener)
remoteDebuggerPathField.getTextField()!!.getDocument()!!.addDocumentListener(docListener)
traceSwitchOffCheckBox.addItemListener(itemListener)
printDebugOutputCheckBox.addItemListener(itemListener)
val result = JPanel(GridBagLayout())
UIUtils.addLabeledControl(result, 0, "Prefered debugger:", selectDebuggerComboBox, false)
UIUtils.addLabeledControl(result, 1, "Remote debugger path:", remoteDebuggerPathField)
result.add(traceSwitchOffCheckBox, gridBagConstraints {
anchor = GridBagConstraints.LINE_START
gridx = 0;
gridwidth = 2;
gridy = 2;
})
result.add(printDebugOutputCheckBox, gridBagConstraints {
anchor = GridBagConstraints.LINE_START
gridx = 0;
gridwidth = 2;
gridy = 3;
})
result.add(JPanel(), gridBagConstraints { gridx = 0; gridy = 4; weighty = 10.0 })
return result
}
override fun isModified(): Boolean = isModified
/**
* Actions performed when user press "Apply" button. Here we obtain settings and need to set them in some global
* debug settings object
*/
override fun apply() {
val ghciSelected = selectDebuggerComboBox.getSelectedIndex() == 0
val remotePath = remoteDebuggerPathField.getTextField()!!.getText()
val traceSwitchedOff = traceSwitchOffCheckBox.isSelected()
val printDebugOutput = printDebugOutputCheckBox.isSelected()
val state = HaskellDebugSettings.getInstance().getState()
state.debuggerType = if (ghciSelected) HaskellDebugSettings.Companion.DebuggerType.GHCI else HaskellDebugSettings.Companion.DebuggerType.REMOTE
state.remoteDebuggerPath = remotePath
state.traceOff = traceSwitchedOff
state.printDebugOutput = printDebugOutput
isModified = false
}
/**
* Actions performed when user press "Reset" button. Here we need to reset appropriate properties in global
* debug settings object
*/
override fun reset() {
val state = HaskellDebugSettings.getInstance().getState()
selectDebuggerComboBox.setSelectedIndex(if (state.debuggerType == HaskellDebugSettings.Companion.DebuggerType.GHCI) 0 else 1)
traceSwitchOffCheckBox.setSelected(state.traceOff)
remoteDebuggerPathField.getTextField()!!.setText(state.remoteDebuggerPath)
printDebugOutputCheckBox.setSelected(state.printDebugOutput)
isModified = false
}
override fun disposeUIResources() {}
} | apache-2.0 | 5ec1f87b1de94b0b9c31e5d5859b3ca5 | 39.781955 | 151 | 0.716209 | 5.306262 | false | false | false | false |
Etik-Tak/backend | src/main/kotlin/dk/etiktak/backend/controller/rest/RecommendationRestController.kt | 1 | 6878 | // Copyright (c) 2017, Daniel Andersen ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* Rest controller responsible for handling product labels.
*/
package dk.etiktak.backend.controller.rest
import dk.etiktak.backend.controller.rest.json.add
import dk.etiktak.backend.model.recommendation.RecommendationScore
import dk.etiktak.backend.model.user.Client
import dk.etiktak.backend.security.CurrentlyLoggedClient
import dk.etiktak.backend.service.client.ClientService
import dk.etiktak.backend.service.company.CompanyService
import dk.etiktak.backend.service.infochannel.InfoChannelService
import dk.etiktak.backend.service.product.ProductCategoryService
import dk.etiktak.backend.service.product.ProductLabelService
import dk.etiktak.backend.service.product.ProductService
import dk.etiktak.backend.service.product.ProductTagService
import dk.etiktak.backend.service.recommendation.RecommendationService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import java.util.*
@RestController
@RequestMapping("/service/recommendation")
class RecommendationRestController @Autowired constructor(
private val recommendationService: RecommendationService,
private val productService: ProductService,
private val productCategoryService: ProductCategoryService,
private val productLabelService: ProductLabelService,
private val productTagService: ProductTagService,
private val companyService: CompanyService,
private val infoChannelService: InfoChannelService,
private val clientService: ClientService) : BaseRestController() {
@RequestMapping(value = "/", method = arrayOf(RequestMethod.GET))
fun getRecommendation(
@CurrentlyLoggedClient loggedClient: Client,
@RequestParam productUuid: String): HashMap<String, Any> {
val client = clientService.getByUuid(loggedClient.uuid) ?: return notFoundMap("Client")
val product = productService.getProductByUuid(productUuid) ?: return notFoundMap("Product")
val recommendations = recommendationService.getRecommendations(client, product)
return okMap().add(recommendations)
}
@RequestMapping(value = "/create/", method = arrayOf(RequestMethod.POST))
fun createRecommendation(
@CurrentlyLoggedClient loggedClient: Client,
@RequestParam infoChannelUuid: String,
@RequestParam summary: String,
@RequestParam score: String,
@RequestParam(required = false) infoSourceReferenceUrlList: List<String>,
@RequestParam(required = false) productUuid: String? = null,
@RequestParam(required = false) productCategoryUuid: String? = null,
@RequestParam(required = false) productLabelUuid: String? = null,
@RequestParam(required = false) productTagUuid: String? = null,
@RequestParam(required = false) companyUuid: String? = null): HashMap<String, Any> {
val client = clientService.getByUuid(loggedClient.uuid) ?: return notFoundMap("Client")
val infoChannel = infoChannelService.getInfoChannelByUuid(infoChannelUuid) ?: return notFoundMap("Info channel")
val scoreType = RecommendationScore.valueOf(score)
// Create product recommendation
productUuid?.let {
val product = productService.getProductByUuid(productUuid) ?: return notFoundMap("Product")
val recommendation = recommendationService.createRecommendation(client, infoChannel, summary, scoreType, product, infoSourceReferenceUrlList)
return okMap().add(recommendation)
}
// Create product category recommendation
productCategoryUuid?.let {
val productCategory = productCategoryService.getProductCategoryByUuid(productCategoryUuid) ?: return notFoundMap("Product category")
val recommendation = recommendationService.createRecommendation(client, infoChannel, summary, scoreType, productCategory, infoSourceReferenceUrlList)
return okMap().add(recommendation)
}
// Create product label recommendation
productLabelUuid?.let {
val productLabel = productLabelService.getProductLabelByUuid(productLabelUuid) ?: return notFoundMap("Product label")
val recommendation = recommendationService.createRecommendation(client, infoChannel, summary, scoreType, productLabel, infoSourceReferenceUrlList)
return okMap().add(recommendation)
}
// Create product tag recommendation
productTagUuid?.let {
val productTag = productTagService.getProductTagByUuid(productTagUuid) ?: return notFoundMap("Product tag")
val recommendation = recommendationService.createRecommendation(client, infoChannel, summary, scoreType, productTag, infoSourceReferenceUrlList)
return okMap().add(recommendation)
}
// Create company recommendation
companyUuid?.let {
val company = companyService.getCompanyByUuid(companyUuid) ?: return notFoundMap("Company")
val recommendation = recommendationService.createRecommendation(client, infoChannel, summary, scoreType, company, infoSourceReferenceUrlList)
return okMap().add(recommendation)
}
return illegalInvocationMap("None of the required parameters set")
}
}
| bsd-3-clause | 7b69c825d804255bce455ea2b11d6128 | 52.734375 | 161 | 0.74731 | 5.373438 | false | false | false | false |
czyzby/ktx | graphics/src/test/kotlin/ktx/graphics/GraphicsTest.kt | 2 | 4192 | package ktx.graphics
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.backends.lwjgl.LwjglNativesLoader
import com.badlogic.gdx.files.FileHandle
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.graphics.glutils.FrameBuffer
import com.badlogic.gdx.graphics.glutils.ShaderProgram
import com.badlogic.gdx.math.Matrix4
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.spy
import com.nhaarman.mockitokotlin2.verify
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Test
import java.io.File
/**
* Tests general utilities related to libGDX graphics API.
*/
class GraphicsTest {
@Test
fun `should begin and end Batch`() {
val batch = mock<Batch>()
batch.use {
verify(batch).begin()
assertSame(batch, it)
verify(batch, never()).end()
}
verify(batch).end()
verify(batch, never()).projectionMatrix = any()
}
@Test
fun `should set projection matrix`() {
val batch = mock<Batch>()
val matrix = Matrix4((0..15).map { it.toFloat() }.toFloatArray())
batch.use(matrix) {
verify(batch).projectionMatrix = matrix
verify(batch).begin()
assertSame(batch, it)
verify(batch, never()).end()
}
verify(batch).end()
}
@Test
fun `should use Batch exactly once`() {
val batch = mock<Batch>()
val variable: Int
batch.use {
variable = 42
}
assertEquals(42, variable)
}
@Test
fun `should set projection matrix if a camera is passed`() {
val batch = mock<Batch>()
val camera = OrthographicCamera()
batch.use(camera) {
verify(batch).projectionMatrix = camera.combined
verify(batch).begin()
assertSame(batch, it)
verify(batch, never()).end()
}
verify(batch).end()
}
@Test
fun `should use Batch with camera exactly once`() {
val batch = mock<Batch>()
val variable: Int
batch.use(OrthographicCamera()) {
variable = 42
}
assertEquals(42, variable)
}
@Test
fun `should begin with provided projection matrix`() {
val batch = mock<Batch>()
val matrix = Matrix4(FloatArray(16) { it.toFloat() })
batch.begin(projectionMatrix = matrix)
verify(batch).projectionMatrix = matrix
verify(batch).begin()
}
@Test
fun `should use Batch with projection matrix exactly once`() {
val batch = mock<Batch>()
val variable: Int
batch.use(Matrix4()) {
variable = 42
}
assertEquals(42, variable)
}
@Test
fun `should begin with provided camera combined matrix`() {
val batch = mock<Batch>()
val camera = OrthographicCamera()
batch.begin(camera = camera)
verify(batch).projectionMatrix = camera.combined
verify(batch).begin()
}
@Test
fun `should bind ShaderProgram`() {
val shaderProgram = mock<ShaderProgram>()
shaderProgram.use {
verify(shaderProgram).bind()
assertSame(shaderProgram, it)
}
}
@Test
fun `should use ShaderProgram exactly once`() {
val shaderProgram = mock<ShaderProgram>()
val variable: Int
shaderProgram.use {
variable = 42
}
assertEquals(42, variable)
}
@Test
fun `should begin and end FrameBuffer`() {
val frameBuffer = mock<FrameBuffer>()
frameBuffer.use {
verify(frameBuffer).begin()
assertSame(frameBuffer, it)
verify(frameBuffer, never()).end()
}
verify(frameBuffer).end()
}
@Test
fun `should use FrameBuffer exactly once`() {
val frameBuffer = mock<FrameBuffer>()
val variable: Int
frameBuffer.use {
variable = 42
}
assertEquals(42, variable)
}
@Test
fun `should take screenshot`() {
LwjglNativesLoader.load()
Gdx.gl = mock()
Gdx.graphics = mock {
on { backBufferHeight } doReturn 4
on { backBufferWidth } doReturn 4
}
val fileHandle = spy(FileHandle(File.createTempFile("screenshot", ".png")))
takeScreenshot(fileHandle)
verify(fileHandle).write(false)
}
}
| cc0-1.0 | 40dd9da87617750772b139468ad6c1e4 | 21.659459 | 79 | 0.665792 | 4.105779 | false | true | false | false |
telegram-bots/telegram-channels-feed | tg/src/main/kotlin/com/github/telegram_bots/channels_feed/tg/service/ChannelRepository.kt | 1 | 1824 | package com.github.telegram_bots.channels_feed.tg.service
import com.github.telegram_bots.channels_feed.tg.domain.Channel
import io.reactivex.Completable
import io.reactivex.Flowable
import org.davidmoten.rx.jdbc.Database
import org.springframework.stereotype.Repository
@Repository
class ChannelRepository(private val db: Database) {
fun update(channel: Channel): Completable {
return db
.update(
"""
| UPDATE channels
| SET telegram_id = ?, hash = ?, url = ?, name = ?, created_at = to_timestamp(?),
| last_post_id = CASE WHEN ? > last_post_id OR last_post_id IS NULL THEN ? ELSE last_post_id END
| WHERE id = ?
""".trimMargin()
)
.parameters(
channel.telegramId,
channel.hash,
channel.url,
channel.name,
channel.createdAt.epochSecond,
channel.lastPostId,
channel.lastPostId,
channel.id
)
.complete()
}
fun list(): Flowable<Channel> {
return db.select("""SELECT * FROM channels ORDER BY last_post_id DESC""").get(::Channel)
}
fun listNeedToUpdate(): Flowable<Channel> {
return db
.select(
"""
| SELECT * FROM channels
| WHERE extract(DAY FROM created_at) = extract(DAY FROM now())
| AND extract(MONTH FROM created_at) != extract(MONTH FROM now())
""".trimMargin()
)
.get(::Channel)
}
}
| mit | c2e38391031691baeb5c3db64b399dff | 36.22449 | 120 | 0.479715 | 5.181818 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/ApplicationConstants.kt | 1 | 1446 | package de.westnordost.streetcomplete
object ApplicationConstants {
const val NAME = "StreetComplete"
const val USER_AGENT = NAME + " " + BuildConfig.VERSION_NAME
const val QUESTTYPE_TAG_KEY = NAME + ":quest_type"
const val MAX_DOWNLOADABLE_AREA_IN_SQKM = 12.0
const val MIN_DOWNLOADABLE_AREA_IN_SQKM = 0.1
const val DATABASE_NAME = "streetcomplete.db"
const val QUEST_TILE_ZOOM = 16
const val NOTE_MIN_ZOOM = 15
/** a "best before" duration for quests. Quests will not be downloaded again for any tile
* before the time expired */
const val REFRESH_QUESTS_AFTER = 3L * 24 * 60 * 60 * 1000 // 3 days in ms
/** the duration after which quests (and quest meta data) will be deleted from the database if
* unsolved and not refreshed in the meantime */
const val DELETE_UNSOLVED_QUESTS_AFTER = 14L * 24 * 60 * 60 * 1000 // 14 days in ms
/** the max age of the undo history - one cannot undo changes older than X */
const val MAX_QUEST_UNDO_HISTORY_AGE = 24L * 60 * 60 * 1000 // 1 day in ms
const val AVATARS_CACHE_DIRECTORY = "osm_user_avatars"
const val SC_PHOTO_SERVICE_URL = "https://westnordost.de/streetcomplete/photo-upload/" // must have trailing /
const val ATTACH_PHOTO_QUALITY = 80
const val ATTACH_PHOTO_MAXWIDTH = 1280 // WXGA
const val ATTACH_PHOTO_MAXHEIGHT = 1280 // WXGA
const val NOTIFICATIONS_CHANNEL_DOWNLOAD = "downloading"
}
| gpl-3.0 | ea9ed2f7e707400439fc4429ef9f334e | 39.166667 | 114 | 0.686722 | 3.805263 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/secondaryConstructors/callFromPrimaryWithNamedArgs.kt | 5 | 249 | open class A(val result: String) {
constructor(x: Int = 11, y: Int = 22, z: Int = 33) : this("$x$y$z")
}
class B() : A(y = 44)
fun box(): String {
val result = B().result
if (result != "114433") return "fail: $result"
return "OK"
} | apache-2.0 | f9406a5fe19d7b5899720262ac20adf8 | 21.727273 | 71 | 0.550201 | 2.736264 | false | false | false | false |
MrSugarCaney/DirtyArrows | src/main/kotlin/nl/sugcube/dirtyarrows/util/Entities.kt | 1 | 990 | package nl.sugcube.dirtyarrows.util
import org.bukkit.entity.Arrow
import org.bukkit.entity.Entity
import org.bukkit.entity.EntityType
import kotlin.math.sqrt
/**
* The diameter of the entity based on width and height.
*/
val Entity.diameter: Double
get() = sqrt(width * width + height * height)
/**
* Respawns an arrow in the same direction as this arrow.
*
* @return The spawned arrow.
*/
fun Arrow.respawnArrow(): Arrow {
val landedArrow = this
landedArrow.remove()
return landedArrow.world.spawnEntity(landedArrow.location, EntityType.ARROW).apply {
val createdArrow = this as Arrow
createdArrow.velocity = landedArrow.velocity
createdArrow.isCritical = landedArrow.isCritical
createdArrow.pickupStatus = landedArrow.pickupStatus
createdArrow.knockbackStrength = landedArrow.knockbackStrength
createdArrow.fireTicks = landedArrow.fireTicks
createdArrow.shooter = [email protected]
} as Arrow
} | gpl-3.0 | d47f9a49196e2951e4ad8177abea70ce | 30.967742 | 88 | 0.736364 | 4.323144 | false | false | false | false |
spkingr/50-android-kotlin-projects-in-100-days | ProjectViewPager/app/src/main/java/me/liuqingwen/android/projectviewpager/MainActivity.kt | 1 | 3375 | package me.liuqingwen.android.projectviewpager
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.view.ViewPager
import android.view.View
import kotlinx.android.synthetic.main.layout_activity_main.*
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.*
class MainActivity : AppCompatActivity(), AnkoLogger
{
companion object
{
const val PREFERENCE_NAME = "project_view_pager"
private const val NO_PAGES_NEXT_TIME = "no_pages_next_time"
}
private val pages by lazy(LazyThreadSafetyMode.NONE) { arrayListOf(Page("4.1 Jelly Bean", this.getString(R.string.android_4), R.drawable.android4),
Page("5.0 Lollipop", this.getString(R.string.android_5), R.drawable.android5),
Page("6.0 Marshmallow", this.getString(R.string.android_6), R.drawable.android6),
Page("7.0 Nougat", this.getString(R.string.android_7), R.drawable.android7),
Page("8.0 Oreo", this.getString(R.string.android_8), R.drawable.android8)) }
private val pagerAdapter by lazy(LazyThreadSafetyMode.NONE) { ViewPagerAdapter(this.supportFragmentManager, this.pages) }
private val preference by lazy(LazyThreadSafetyMode.NONE) { this.getSharedPreferences(MainActivity.PREFERENCE_NAME, Context.MODE_PRIVATE) }
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.layout_activity_main)
this.initUI()
this.init()
}
private fun initUI()
{
this.checkBox.visibility = View.INVISIBLE
this.imageButton.visibility = View.INVISIBLE
}
private fun init()
{
if (this.preference.getBoolean(MainActivity.NO_PAGES_NEXT_TIME, false))
{
this.startActivity<AppActivity>()
this.finish()
return
}
this.viewPager.adapter = this.pagerAdapter
this.layoutTabs.setupWithViewPager(this.viewPager)
this.viewPager.addOnPageChangeListener(object:ViewPager.SimpleOnPageChangeListener(){
override fun onPageSelected(position: Int)
{
super.onPageSelected(position)
if (position >= [email protected] - 1 && [email protected] != View.VISIBLE)
{
[email protected] = View.VISIBLE
[email protected] = View.VISIBLE
[email protected] {
val noViewPager = [email protected]
val editor = [email protected]()
editor.putBoolean(MainActivity.NO_PAGES_NEXT_TIME, noViewPager)
editor.apply()
[email protected]<AppActivity>()
[email protected]()
}
}
}
})
}
}
| mit | c8a841d238954dc37c10114d51a1e627 | 43.407895 | 152 | 0.591704 | 5.144817 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.