repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GunoH/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/extensions/jcef/ProcessLinksExtension.kt | 5 | 2536 | // 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.intellij.plugins.markdown.extensions.jcef
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.diagnostic.getOrLogException
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.jcef.JBCefPsiNavigationUtils
import org.intellij.plugins.markdown.extensions.MarkdownBrowserPreviewExtension
import org.intellij.plugins.markdown.ui.preview.BrowserPipe
import org.intellij.plugins.markdown.ui.preview.MarkdownHtmlPanel
import org.intellij.plugins.markdown.ui.preview.MarkdownHtmlPanelEx
import org.intellij.plugins.markdown.ui.preview.ResourceProvider
import org.intellij.plugins.markdown.ui.preview.accessor.MarkdownLinkOpener
internal class ProcessLinksExtension(private val panel: MarkdownHtmlPanel): MarkdownBrowserPreviewExtension, ResourceProvider {
private val handler = BrowserPipe.Handler { openLink(panel, it) }
init {
panel.browserPipe?.subscribe(openLinkEventName, handler)
Disposer.register(this) {
panel.browserPipe?.removeSubscription(openLinkEventName, handler)
}
}
private fun openLink(panel: MarkdownHtmlPanel, link: String) {
if (!Registry.`is`("markdown.open.link.in.external.browser")) {
return
}
if (JBCefPsiNavigationUtils.navigateTo(link)) {
return
}
if (panel is MarkdownHtmlPanelEx) {
if (panel.getUserData(MarkdownHtmlPanelEx.DO_NOT_USE_LINK_OPENER) == true) {
runCatching {
BrowserUtil.browse(link)
}.getOrLogException(thisLogger())
return
}
}
MarkdownLinkOpener.getInstance().openLink(panel.project, link)
}
override val scripts: List<String> = listOf("processLinks/processLinks.js")
override val resourceProvider: ResourceProvider = this
override fun canProvide(resourceName: String): Boolean = resourceName in scripts
override fun loadResource(resourceName: String): ResourceProvider.Resource? {
return ResourceProvider.loadInternalResource(this::class, resourceName)
}
override fun dispose() = Unit
class Provider: MarkdownBrowserPreviewExtension.Provider {
override fun createBrowserExtension(panel: MarkdownHtmlPanel): MarkdownBrowserPreviewExtension {
return ProcessLinksExtension(panel)
}
}
companion object {
private const val openLinkEventName = "openLink"
}
}
| apache-2.0 | 01aa7865d44f5cbe2ab8ce2e008f9e75 | 37.424242 | 140 | 0.776025 | 4.661765 | false | false | false | false |
GunoH/intellij-community | platform/collaboration-tools/src/com/intellij/collaboration/async/CompletableFutureUtil.kt | 7 | 7805 | // 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.collaboration.async
import com.intellij.collaboration.util.ProgressIndicatorsProvider
import com.intellij.execution.process.ProcessIOExecutorService
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.Computable
import com.intellij.openapi.util.Disposer
import java.util.concurrent.*
import java.util.concurrent.atomic.AtomicReference
import java.util.function.BiFunction
import java.util.function.Supplier
/**
* Collection of utilities to use CompletableFuture and not care about CF and platform quirks
*/
object CompletableFutureUtil {
/**
* Check is the exception is a cancellation signal
*/
fun isCancellation(error: Throwable): Boolean {
return error is ProcessCanceledException
|| error is CancellationException
|| error is InterruptedException
|| error.cause?.let(::isCancellation) ?: false
}
/**
* Extract actual exception from the one returned by completable future
*/
fun extractError(error: Throwable): Throwable {
return when (error) {
is CompletionException -> extractError(error.cause!!)
is ExecutionException -> extractError(error.cause!!)
else -> error
}
}
/**
* Submit a [task] to IO thread pool under correct [ProgressIndicator]
*/
fun <T> ProgressManager.submitIOTask(progressIndicator: ProgressIndicator,
task: (indicator: ProgressIndicator) -> T): CompletableFuture<T> =
submitIOTask(progressIndicator, false, task)
/**
* Submit a [task] to IO thread pool under correct [ProgressIndicator]
*/
fun <T> ProgressManager.submitIOTask(progressIndicator: ProgressIndicator,
cancelIndicatorOnFutureCancel: Boolean = false,
task: (indicator: ProgressIndicator) -> T): CompletableFuture<T> =
CompletableFuture.supplyAsync(Supplier { runProcess(Computable { task(progressIndicator) }, progressIndicator) },
ProcessIOExecutorService.INSTANCE)
.whenComplete { _, e: Throwable? ->
if (cancelIndicatorOnFutureCancel && e != null && isCancellation(e) && !progressIndicator.isCanceled) {
progressIndicator.cancel()
}
}
/**
* Submit a [task] to IO thread pool under correct [ProgressIndicator] acquired from [indicatorProvider] and release the indicator when task is completed
*/
fun <T> ProgressManager.submitIOTask(indicatorProvider: ProgressIndicatorsProvider,
task: (indicator: ProgressIndicator) -> T): CompletableFuture<T> =
submitIOTask(indicatorProvider, false, task)
/**
* Submit a [task] to IO thread pool under correct [ProgressIndicator] acquired from [indicatorProvider] and release the indicator when task is completed
*/
fun <T> ProgressManager.submitIOTask(indicatorProvider: ProgressIndicatorsProvider,
cancelIndicatorOnFutureCancel: Boolean = false,
task: (indicator: ProgressIndicator) -> T): CompletableFuture<T> {
val indicator = indicatorProvider.acquireIndicator()
return submitIOTask(indicator, cancelIndicatorOnFutureCancel, task).whenComplete { _, _ ->
indicatorProvider.releaseIndicator(indicator)
}
}
/**
* Handle the result of async computation on EDT
*
* To allow proper GC the handler is cleaned up when [disposable] is disposed
*
* @param handler invoked when computation completes
*/
fun <T> CompletableFuture<T>.handleOnEdt(disposable: Disposable,
handler: (T?, Throwable?) -> Unit): CompletableFuture<Unit> {
val handlerReference = AtomicReference(handler)
Disposer.register(disposable, Disposable {
handlerReference.set(null)
})
return handleAsync(BiFunction<T?, Throwable?, Unit> { result: T?, error: Throwable? ->
val handlerFromRef = handlerReference.get() ?: throw ProcessCanceledException()
handlerFromRef(result, error?.let { extractError(it) })
}, getEDTExecutor(null))
}
/**
* Handle the result of async computation on EDT
*
* @see [CompletableFuture.handle]
* @param handler invoked when computation completes
*/
fun <T, R> CompletableFuture<T>.handleOnEdt(modalityState: ModalityState? = null,
handler: (T?, Throwable?) -> R): CompletableFuture<R> =
handleAsync(BiFunction<T?, Throwable?, R> { result: T?, error: Throwable? ->
handler(result, error?.let { extractError(it) })
}, getEDTExecutor(modalityState))
/**
* Handle the result of async computation on EDT
*
* @see [CompletableFuture.thenApply]
* @param handler invoked when computation completes without exception
*/
fun <T, R> CompletableFuture<T>.successOnEdt(modalityState: ModalityState? = null, handler: (T) -> R): CompletableFuture<R> =
handleOnEdt(modalityState) { result, error ->
@Suppress("UNCHECKED_CAST")
if (error != null) throw extractError(error) else handler(result as T)
}
/**
* Handle the error on EDT
*
* If you need to return something after handling use [handleOnEdt]
*
* @see [CompletableFuture.exceptionally]
* @param handler invoked when computation throws an exception which IS NOT [isCancellation]
*/
fun <T> CompletableFuture<T>.errorOnEdt(modalityState: ModalityState? = null,
handler: (Throwable) -> Unit): CompletableFuture<T> =
handleOnEdt(modalityState) { result, error ->
if (error != null) {
val actualError = extractError(error)
if (isCancellation(actualError)) throw ProcessCanceledException()
handler(actualError)
throw actualError
}
@Suppress("UNCHECKED_CAST")
result as T
}
/**
* Handle the cancellation on EDT
*
* @see [CompletableFuture.exceptionally]
* @param handler invoked when computation throws an exception which IS [isCancellation]
*/
fun <T> CompletableFuture<T>.cancellationOnEdt(modalityState: ModalityState? = null,
handler: (ProcessCanceledException) -> Unit): CompletableFuture<T> =
handleOnEdt(modalityState) { result, error ->
if (error != null) {
val actualError = extractError(error)
if (isCancellation(actualError)) handler(ProcessCanceledException())
throw actualError
}
@Suppress("UNCHECKED_CAST")
result as T
}
/**
* Handled the completion of async computation on EDT
*
* @see [CompletableFuture.whenComplete]
* @param handler invoked when computation completes successfully or throws an exception which IS NOT [isCancellation]
*/
fun <T> CompletableFuture<T>.completionOnEdt(modalityState: ModalityState? = null,
handler: () -> Unit): CompletableFuture<T> =
handleOnEdt(modalityState) { result, error ->
@Suppress("UNCHECKED_CAST")
if (error != null) {
if (!isCancellation(error)) handler()
throw extractError(error)
}
else {
handler()
result as T
}
}
fun getEDTExecutor(modalityState: ModalityState? = null) = Executor { runnable -> runInEdt(modalityState) { runnable.run() } }
} | apache-2.0 | 508b411f376f1ed808fa667f3197dee3 | 40.301587 | 155 | 0.670724 | 4.955556 | false | false | false | false |
GunoH/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/highlighter/GroovyColorSettingsPage.kt | 4 | 11741 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.groovy.highlighter
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.options.colors.AttributesDescriptor
import com.intellij.openapi.options.colors.ColorDescriptor
import com.intellij.openapi.options.colors.ColorSettingsPage
import com.intellij.util.containers.map2Array
import icons.JetgroovyIcons
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.highlighter.GroovySyntaxHighlighter.*
import javax.swing.Icon
class GroovyColorSettingsPage : ColorSettingsPage {
private companion object {
private operator fun Array<@PropertyKey(resourceBundle = "messages.GroovyBundle") String>
.plus(attributeKey: TextAttributesKey): () -> AttributesDescriptor {
return {
@Suppress("HardCodedStringLiteral", "DialogTitleCapitalization")
AttributesDescriptor([email protected]("//", transform = { GroovyBundle.message(it) }), attributeKey)
}
}
val attributes: Array<() -> AttributesDescriptor> = arrayOf(
arrayOf("attribute.descriptor.annotations", "attribute.descriptor.annotation.attribute.name") + ANNOTATION_ATTRIBUTE_NAME,
arrayOf("attribute.descriptor.annotations", "attribute.descriptor.annotation.name") + ANNOTATION,
arrayOf("attribute.descriptor.braces.and.operators", "attribute.descriptor.braces") + BRACES,
arrayOf("attribute.descriptor.braces.and.operators", "attribute.descriptor.closure.expression.braces.and.arrow") + CLOSURE_ARROW_AND_BRACES,
arrayOf("attribute.descriptor.braces.and.operators", "attribute.descriptor.lambda.expression.braces.and.arrow") + LAMBDA_ARROW_AND_BRACES,
arrayOf("attribute.descriptor.braces.and.operators", "attribute.descriptor.brackets") + BRACKETS,
arrayOf("attribute.descriptor.braces.and.operators", "attribute.descriptor.parentheses") + PARENTHESES,
arrayOf("attribute.descriptor.braces.and.operators", "attribute.descriptor.operator.sign") + OPERATION_SIGN,
arrayOf("attribute.descriptor.comments", "attribute.descriptor.line.comment") + LINE_COMMENT,
arrayOf("attribute.descriptor.comments", "attribute.descriptor.block.comment") + BLOCK_COMMENT,
arrayOf("attribute.descriptor.comments", "attribute.descriptor.groovydoc", "attribute.descriptor.groovydoc.text") + DOC_COMMENT_CONTENT,
arrayOf("attribute.descriptor.comments", "attribute.descriptor.groovydoc", "attribute.descriptor.groovydoc.tag") + DOC_COMMENT_TAG,
arrayOf("attribute.descriptor.classes.and.interfaces", "attribute.descriptor.class") + CLASS_REFERENCE,
arrayOf("attribute.descriptor.classes.and.interfaces", "attribute.descriptor.abstract.class") + ABSTRACT_CLASS_NAME,
arrayOf("attribute.descriptor.classes.and.interfaces", "attribute.descriptor.anonymous.class") + ANONYMOUS_CLASS_NAME,
arrayOf("attribute.descriptor.classes.and.interfaces", "attribute.descriptor.interface") + INTERFACE_NAME,
arrayOf("attribute.descriptor.classes.and.interfaces", "attribute.descriptor.trait") + TRAIT_NAME,
arrayOf("attribute.descriptor.classes.and.interfaces", "attribute.descriptor.enum") + ENUM_NAME,
arrayOf("attribute.descriptor.classes.and.interfaces", "attribute.descriptor.type.parameter") + TYPE_PARAMETER,
arrayOf("attribute.descriptor.methods", "attribute.descriptor.method.declaration") + METHOD_DECLARATION,
arrayOf("attribute.descriptor.methods", "attribute.descriptor.constructor.declaration") + CONSTRUCTOR_DECLARATION,
arrayOf("attribute.descriptor.methods", "attribute.descriptor.instance.method.call") + METHOD_CALL,
arrayOf("attribute.descriptor.methods", "attribute.descriptor.static.method.call") + STATIC_METHOD_ACCESS,
arrayOf("attribute.descriptor.methods", "attribute.descriptor.constructor.call") + CONSTRUCTOR_CALL,
arrayOf("attribute.descriptor.fields", "attribute.descriptor.instance.field") + INSTANCE_FIELD,
arrayOf("attribute.descriptor.fields", "attribute.descriptor.static.field") + STATIC_FIELD,
arrayOf("attribute.descriptor.variables.and.parameters", "attribute.descriptor.local.variable") + LOCAL_VARIABLE,
arrayOf("attribute.descriptor.variables.and.parameters", "attribute.descriptor.reassigned.local.variable") + REASSIGNED_LOCAL_VARIABLE,
arrayOf("attribute.descriptor.variables.and.parameters", "attribute.descriptor.parameter") + PARAMETER,
arrayOf("attribute.descriptor.variables.and.parameters", "attribute.descriptor.reassigned.parameter") + REASSIGNED_PARAMETER,
arrayOf("attribute.descriptor.references", "attribute.descriptor.instance.property.reference") + INSTANCE_PROPERTY_REFERENCE,
arrayOf("attribute.descriptor.references", "attribute.descriptor.static.property.reference") + STATIC_PROPERTY_REFERENCE,
arrayOf("attribute.descriptor.references", "attribute.descriptor.unresolved.reference") + UNRESOLVED_ACCESS,
arrayOf("attribute.descriptor.strings", "attribute.descriptor.string") + STRING,
arrayOf("attribute.descriptor.strings", "attribute.descriptor.gstring") + GSTRING,
arrayOf("attribute.descriptor.strings", "attribute.descriptor.valid.string.escape") + VALID_STRING_ESCAPE,
arrayOf("attribute.descriptor.strings", "attribute.descriptor.invalid.string.escape") + INVALID_STRING_ESCAPE,
arrayOf("attribute.descriptor.keyword") + KEYWORD,
arrayOf("attribute.descriptor.number") + NUMBER,
arrayOf("attribute.descriptor.bad.character") + BAD_CHARACTER,
arrayOf("attribute.descriptor.list.map.to.object.conversion") + LITERAL_CONVERSION,
arrayOf("attribute.descriptor.map.key.named.argument") + MAP_KEY,
arrayOf("attribute.descriptor.label") + LABEL
)
val additionalTags = mapOf(
"annotation" to ANNOTATION,
"annotationAttribute" to ANNOTATION_ATTRIBUTE_NAME,
"groovydoc" to DOC_COMMENT_CONTENT,
"groovydocTag" to DOC_COMMENT_TAG,
"class" to CLASS_REFERENCE,
"abstractClass" to ABSTRACT_CLASS_NAME,
"anonymousClass" to ANONYMOUS_CLASS_NAME,
"interface" to INTERFACE_NAME,
"trait" to TRAIT_NAME,
"enum" to ENUM_NAME,
"typeParameter" to TYPE_PARAMETER,
"method" to METHOD_DECLARATION,
"constructor" to CONSTRUCTOR_DECLARATION,
"instanceMethodCall" to METHOD_CALL,
"staticMethodCall" to STATIC_METHOD_ACCESS,
"constructorCall" to CONSTRUCTOR_CALL,
"instanceField" to INSTANCE_FIELD,
"staticField" to STATIC_FIELD,
"localVariable" to LOCAL_VARIABLE,
"reassignedVariable" to REASSIGNED_LOCAL_VARIABLE,
"parameter" to PARAMETER,
"reassignedParameter" to REASSIGNED_PARAMETER,
"instanceProperty" to INSTANCE_PROPERTY_REFERENCE,
"staticProperty" to STATIC_PROPERTY_REFERENCE,
"unresolved" to UNRESOLVED_ACCESS,
"keyword" to KEYWORD,
"literalConstructor" to LITERAL_CONVERSION,
"mapKey" to MAP_KEY,
"label" to LABEL,
"validEscape" to VALID_STRING_ESCAPE,
"invalidEscape" to INVALID_STRING_ESCAPE,
"closureBraces" to CLOSURE_ARROW_AND_BRACES,
"lambdaBraces" to LAMBDA_ARROW_AND_BRACES
)
}
override fun getDisplayName(): String = GroovyBundle.message("language.groovy")
override fun getIcon(): Icon = JetgroovyIcons.Groovy.Groovy_16x16
override fun getAttributeDescriptors(): Array<AttributesDescriptor> = attributes.map2Array { it() }
override fun getColorDescriptors(): Array<out ColorDescriptor> = ColorDescriptor.EMPTY_ARRAY
override fun getHighlighter(): GroovySyntaxHighlighter = GroovySyntaxHighlighter()
override fun getAdditionalHighlightingTagToDescriptorMap(): Map<String, TextAttributesKey> = additionalTags
@NonNls
override fun getDemoText(): String = """<keyword>package</keyword> highlighting
###
<groovydoc>/**
* This is Groovydoc comment
* <groovydocTag>@see</groovydocTag> java.lang.String#equals
*/</groovydoc>
<annotation>@Annotation</annotation>(<annotationAttribute>parameter</annotationAttribute> = 'value')
<keyword>class</keyword> <class>C</class> {
<keyword>def</keyword> <instanceField>property</instanceField> = <keyword>new</keyword> <anonymousClass>I</anonymousClass>() {}
<keyword>static</keyword> <keyword>def</keyword> <staticField>staticProperty</staticField> = []
<constructor>C</constructor>() {}
<keyword>def</keyword> <<typeParameter>T</typeParameter>> <typeParameter>T</typeParameter> <method>instanceMethod</method>(T <parameter>parameter</parameter>, <reassignedParameter>reassignedParameter</reassignedParameter>) {
<reassignedParameter>reassignedParameter</reassignedParameter> = 1
//This is a line comment
<keyword>return</keyword> <parameter>parameter</parameter>
}
<keyword>def</keyword> <method>getStuff</method>() { 42 }
<keyword>static</keyword> <keyword>boolean</keyword> <method>isStaticStuff</method>() { true }
<keyword>static</keyword> <keyword>def</keyword> <method>staticMethod</method>(<keyword>int</keyword> <parameter>i</parameter>) {
/* This is a block comment */
<interface>Map</interface> <localVariable>map</localVariable> = [<mapKey>key1</mapKey>: 1, <mapKey>key2</mapKey>: 2, (22): 33]
<keyword>def</keyword> <localVariable>cl</localVariable> = <closureBraces>{</closureBraces> <parameter>a</parameter> <closureBraces>-></closureBraces> <parameter>a</parameter> <closureBraces>}</closureBraces>
<keyword>def</keyword> <localVariable>lambda</localVariable> = <parameter>b</parameter> <lambdaBraces>-></lambdaBraces> <lambdaBraces>{</lambdaBraces> <parameter>b</parameter> <lambdaBraces>}</lambdaBraces>
<class>File</class> <localVariable>f</localVariable> = <literalConstructor>[</literalConstructor>'path'<literalConstructor>]</literalConstructor>
<keyword>def</keyword> <reassignedVariable>a</reassignedVariable> = 'JetBrains'.<instanceMethodCall>matches</instanceMethodCall>(/Jw+Bw+/)
<label>label</label>:
<keyword>for</keyword> (<localVariable>entry</localVariable> <keyword>in</keyword> <localVariable>map</localVariable>) {
<keyword>if</keyword> (<localVariable>entry</localVariable>.value > 1 && <parameter>i</parameter> < 2) {
<reassignedVariable>a</reassignedVariable> = <unresolved>unresolvedReference</unresolved>
<keyword>continue</keyword> label
} <keyword>else</keyword> {
<reassignedVariable>a</reassignedVariable> = <localVariable>entry</localVariable>
}
}
<instanceMethodCall>print</instanceMethodCall> <localVariable>map</localVariable>.<mapKey>key1</mapKey>
}
}
<keyword>def</keyword> <localVariable>c</localVariable> = <keyword>new</keyword> <constructorCall>C</constructorCall>()
<localVariable>c</localVariable>.<instanceMethodCall>instanceMethod</instanceMethodCall>("Hello<validEscape>\n</validEscape>", 'world<invalidEscape>\x</invalidEscape>')
<instanceMethodCall>println</instanceMethodCall> <localVariable>c</localVariable>.<instanceProperty>stuff</instanceProperty>
<class>C</class>.<staticMethodCall>staticMethod</staticMethodCall>(<mapKey>namedArg</mapKey>: 1)
<class>C</class>.<staticProperty>staticStuff</staticProperty>
<keyword>abstract</keyword> <keyword>class</keyword> <abstractClass>AbstractClass</abstractClass> {}
<keyword>interface</keyword> <interface>I</interface> {}
<keyword>trait</keyword> <trait>T</trait> {}
<keyword>enum</keyword> <enum>E</enum> {}
@<keyword>interface</keyword> <annotation>Annotation</annotation> {
<class>String</class> <method>parameter</method>()
}
"""
}
| apache-2.0 | db79adcace48708c9104e915642fe840 | 56.553922 | 226 | 0.750021 | 4.3908 | false | false | false | false |
jk1/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/history/FileHistory.kt | 2 | 13519 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.log.history
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.Ref
import com.intellij.openapi.vcs.FilePath
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.Stack
import com.intellij.vcs.log.data.index.VcsLogPathsIndex
import com.intellij.vcs.log.graph.api.LinearGraph
import com.intellij.vcs.log.graph.api.LiteLinearGraph
import com.intellij.vcs.log.graph.api.permanent.PermanentCommitsInfo
import com.intellij.vcs.log.graph.api.permanent.PermanentGraphInfo
import com.intellij.vcs.log.graph.collapsing.CollapsedGraph
import com.intellij.vcs.log.graph.impl.facade.*
import com.intellij.vcs.log.graph.utils.BfsUtil
import com.intellij.vcs.log.graph.utils.DfsUtil
import com.intellij.vcs.log.graph.utils.LinearGraphUtils
import com.intellij.vcs.log.graph.utils.impl.BitSetFlags
import gnu.trove.TIntObjectHashMap
import java.util.*
import java.util.function.BiConsumer
internal class FileHistoryBuilder(private val startCommit: Int?,
private val startPath: FilePath,
private val fileNamesData: FileNamesData) : BiConsumer<LinearGraphController, PermanentGraphInfo<Int>> {
val pathsMap = mutableMapOf<Int, FilePath?>()
override fun accept(controller: LinearGraphController, permanentGraphInfo: PermanentGraphInfo<Int>) {
pathsMap.putAll(refine(controller, startCommit, permanentGraphInfo))
val trivialCandidates = mutableSetOf<Int>()
pathsMap.forEach { c, p ->
if (p != null && fileNamesData.isTrivialMerge(c, p)) {
trivialCandidates.add(c)
}
}
modifyGraph(controller) { collapsedGraph ->
val trivialMerges = hideTrivialMerges(collapsedGraph) { nodeId: Int ->
trivialCandidates.contains(permanentGraphInfo.permanentCommitsInfo.getCommitId(nodeId))
}
trivialMerges.forEach { pathsMap.remove(permanentGraphInfo.permanentCommitsInfo.getCommitId(it)) }
}
}
private fun refine(controller: LinearGraphController,
startCommit: Int?,
permanentGraphInfo: PermanentGraphInfo<Int>): Map<Int, FilePath?> {
if (fileNamesData.hasRenames) {
val visibleLinearGraph = controller.compiledGraph
val row = startCommit?.let {
findAncestorRowAffectingFile(startCommit, startPath, visibleLinearGraph, permanentGraphInfo, fileNamesData)
} ?: 0
if (row >= 0) {
val refiner = FileHistoryRefiner(visibleLinearGraph, permanentGraphInfo, fileNamesData)
val (paths, excluded) = refiner.refine(row, startPath)
if (!excluded.isEmpty()) {
val hidden = hideCommits(controller, permanentGraphInfo, excluded)
if (!hidden) LOG.error("Could not hide excluded commits from history for " + startPath.path)
}
return paths
}
}
return fileNamesData.buildPathsMap()
}
companion object {
private val LOG = Logger.getInstance(FileHistoryBuilder::class.java)
}
}
fun hideTrivialMerges(collapsedGraph: CollapsedGraph,
isCandidateNodeId: (Int) -> Boolean): Set<Int> {
val result = mutableSetOf<Int>()
val graph = LinearGraphUtils.asLiteLinearGraph(collapsedGraph.compiledGraph)
outer@ for (v in graph.nodesCount() - 1 downTo 0) {
val nodeId = collapsedGraph.compiledGraph.getNodeId(v)
if (isCandidateNodeId(nodeId)) {
val downNodes = graph.getNodes(v, LiteLinearGraph.NodeFilter.DOWN)
if (downNodes.size == 1) {
result.add(nodeId)
hideTrivialMerge(collapsedGraph, graph, v, downNodes.single())
}
else if (downNodes.size >= 2) {
val sortedParentsIt = downNodes.sortedDescending().iterator()
var currentParent = sortedParentsIt.next()
while (sortedParentsIt.hasNext()) {
val nextParent = sortedParentsIt.next()
if (!DfsUtil.isAncestor(graph, currentParent, nextParent)) continue@outer
currentParent = nextParent
}
result.add(nodeId)
hideTrivialMerge(collapsedGraph, graph, v, currentParent)
}
}
}
return result
}
private fun hideTrivialMerge(collapsedGraph: CollapsedGraph, graph: LiteLinearGraph, node: Int, singleParent: Int) {
collapsedGraph.modify {
hideRow(node)
for (upNode in graph.getNodes(node, LiteLinearGraph.NodeFilter.UP)) {
connectRows(upNode, singleParent)
}
}
}
internal fun findAncestorRowAffectingFile(commitId: Int,
filePath: FilePath,
visibleLinearGraph: LinearGraph,
permanentGraphInfo: PermanentGraphInfo<Int>,
fileNamesData: FileNamesData): Int {
val resultNodeId = Ref<Int>()
val commitsInfo = permanentGraphInfo.permanentCommitsInfo
val reachableNodes = ReachableNodes(LinearGraphUtils.asLiteLinearGraph(permanentGraphInfo.linearGraph))
reachableNodes.walk(setOf(commitsInfo.getNodeId(commitId)), true) { currentNode ->
val id = commitsInfo.getCommitId(currentNode)
if (fileNamesData.affects(id, filePath)) {
resultNodeId.set(currentNode)
false // stop walk, we have found it
}
else {
true // continue walk
}
}
if (!resultNodeId.isNull) {
return visibleLinearGraph.getNodeIndex(resultNodeId.get())!!
}
return -1
}
internal class FileHistoryRefiner(private val visibleLinearGraph: LinearGraph,
permanentGraphInfo: PermanentGraphInfo<Int>,
private val namesData: FileNamesData) : DfsUtil.NodeVisitor {
private val permanentCommitsInfo: PermanentCommitsInfo<Int> = permanentGraphInfo.permanentCommitsInfo
private val permanentLinearGraph: LiteLinearGraph = LinearGraphUtils.asLiteLinearGraph(permanentGraphInfo.linearGraph)
private val paths = Stack<FilePath>()
private val visibilityBuffer = BitSetFlags(permanentLinearGraph.nodesCount()) // a reusable buffer for bfs
private val pathsForCommits = ContainerUtil.newHashMap<Int, FilePath?>()
private val excluded = ContainerUtil.newHashSet<Int>()
fun refine(row: Int, startPath: FilePath): Pair<HashMap<Int, FilePath?>, HashSet<Int>> {
paths.push(startPath)
DfsUtil.walk(LinearGraphUtils.asLiteLinearGraph(visibleLinearGraph), row, this)
pathsForCommits.forEach { commit, path ->
if (path != null && !namesData.affects(commit, path)) {
excluded.add(commit)
}
}
excluded.forEach { pathsForCommits.remove(it) }
return Pair(pathsForCommits, excluded)
}
override fun enterNode(currentNode: Int, previousNode: Int, down: Boolean) {
val currentNodeId = visibleLinearGraph.getNodeId(currentNode)
val currentCommit = permanentCommitsInfo.getCommitId(currentNodeId)
val previousPath = paths.findLast { it != null }!!
var currentPath: FilePath? = previousPath
if (previousNode != DfsUtil.NextNode.NODE_NOT_FOUND) {
val previousNodeId = visibleLinearGraph.getNodeId(previousNode)
val previousCommit = permanentCommitsInfo.getCommitId(previousNodeId)
if (down) {
val pathGetter = { parentIndex: Int ->
namesData.getPathInParentRevision(previousCommit, permanentCommitsInfo.getCommitId(parentIndex), previousPath)
}
currentPath = findPathWithoutConflict(previousNodeId, pathGetter)
if (currentPath == null) {
val parentIndex = BfsUtil.getCorrespondingParent(permanentLinearGraph, previousNodeId, currentNodeId, visibilityBuffer)
currentPath = pathGetter(parentIndex)
}
}
else {
val pathGetter = { parentIndex: Int ->
namesData.getPathInChildRevision(currentCommit, permanentCommitsInfo.getCommitId(parentIndex), previousPath)
}
currentPath = findPathWithoutConflict(currentNodeId, pathGetter)
if (currentPath == null) {
// since in reality there is no edge between the nodes, but the whole path, we need to know, which parent is affected by this path
val parentIndex = BfsUtil.getCorrespondingParent(permanentLinearGraph, currentNodeId, previousNodeId, visibilityBuffer)
currentPath = pathGetter(parentIndex)
}
}
}
pathsForCommits[currentCommit] = currentPath
paths.push(currentPath)
}
private fun findPathWithoutConflict(nodeId: Int, pathGetter: (Int) -> FilePath?): FilePath? {
val parents = permanentLinearGraph.getNodes(nodeId, LiteLinearGraph.NodeFilter.DOWN)
val path = pathGetter(parents.first())
if (parents.size == 1) return path
if (parents.subList(1, parents.size).find { pathGetter(it) != path } != null) return null
return path
}
override fun exitNode(node: Int) {
paths.pop()
}
}
abstract class FileNamesData {
private val commitToPathAndChanges = TIntObjectHashMap<MutableMap<FilePath, MutableMap<Int, VcsLogPathsIndex.ChangeData>>>()
val commits: Set<Int>
get() = commitToPathAndChanges.keys().toSet()
val isEmpty: Boolean
get() = commitToPathAndChanges.isEmpty
var hasRenames = false
private set
protected abstract fun getPathById(pathId: Int): FilePath
fun add(commit: Int,
path: FilePath,
changes: List<VcsLogPathsIndex.ChangeData>,
parents: List<Int>) {
var pathToChanges: MutableMap<FilePath, MutableMap<Int, VcsLogPathsIndex.ChangeData>>? = commitToPathAndChanges.get(commit)
if (pathToChanges == null) {
pathToChanges = ContainerUtil.newHashMap<FilePath, MutableMap<Int, VcsLogPathsIndex.ChangeData>>()
commitToPathAndChanges.put(commit, pathToChanges)
}
hasRenames = hasRenames || changes.find { it.isRename } != null
val parentToChangesMap: MutableMap<Int, VcsLogPathsIndex.ChangeData> = pathToChanges[path]
?: ContainerUtil.newHashMap<Int, VcsLogPathsIndex.ChangeData>()
if (!parents.isEmpty()) {
LOG.assertTrue(parents.size == changes.size)
for (i in changes.indices) {
val existing = parentToChangesMap[parents[i]]
if (existing != null) {
// since we occasionally reindex commits with different rename limit
// it can happen that we have several change data for a file in a commit
// one with rename, other without
// we want to keep a renamed-one, so throwing the other one out
if (existing.isRename) continue
}
parentToChangesMap[parents[i]] = changes[i]
}
}
else {
// initial commit
LOG.assertTrue(changes.size == 1)
parentToChangesMap[-1] = changes[0]
}
pathToChanges[path] = parentToChangesMap
}
fun getPathInParentRevision(commit: Int, parent: Int, childPath: FilePath): FilePath? {
val filesToChangesMap = commitToPathAndChanges.get(commit)
LOG.assertTrue(filesToChangesMap != null, "Missing commit $commit")
val changes = filesToChangesMap!![childPath] ?: return childPath
val change = changes[parent]
return when (change?.kind) {
VcsLogPathsIndex.ChangeKind.RENAMED_FROM -> null
VcsLogPathsIndex.ChangeKind.RENAMED_TO -> getPathById(change.otherPath)
null -> {
LOG.assertTrue(changes.size > 1)
childPath
}
else -> childPath
}
}
fun getPathInChildRevision(commit: Int, parentIndex: Int, parentPath: FilePath): FilePath? {
val filesToChangesMap = commitToPathAndChanges.get(commit)
LOG.assertTrue(filesToChangesMap != null, "Missing commit $commit")
val changes = filesToChangesMap!![parentPath] ?: return parentPath
val change = changes[parentIndex]
return when (change?.kind) {
VcsLogPathsIndex.ChangeKind.RENAMED_TO -> null
VcsLogPathsIndex.ChangeKind.RENAMED_FROM -> getPathById(change.otherPath)
else -> parentPath
}
}
fun affects(id: Int, path: FilePath): Boolean {
return commitToPathAndChanges.containsKey(id) && commitToPathAndChanges.get(id).containsKey(path)
}
fun buildPathsMap(): Map<Int, FilePath> {
val result = ContainerUtil.newHashMap<Int, FilePath>()
commitToPathAndChanges.forEachEntry { commit, filesToChanges ->
if (filesToChanges.size == 1) {
result[commit] = filesToChanges.keys.first()
}
else {
for ((key, value) in filesToChanges) {
val changeData = value.values.find { ch ->
ch != VcsLogPathsIndex.ChangeData.NOT_CHANGED &&
ch.kind != VcsLogPathsIndex.ChangeKind.RENAMED_FROM
}
if (changeData != null) {
result[commit] = key
break
}
}
}
true
}
return result
}
fun isTrivialMerge(commit: Int, path: FilePath): Boolean {
if (!commitToPathAndChanges.containsKey(commit)) return false
val data = commitToPathAndChanges.get(commit)[path]
// strictly speaking, the criteria for merge triviality is a little bit more tricky than this:
// some merges have just reverted changes in one of the branches
// they need to be displayed
// but we skip them instead
return data != null && data.size > 1 && data.containsValue(VcsLogPathsIndex.ChangeData.NOT_CHANGED)
}
companion object {
private val LOG = Logger.getInstance(FileNamesData::class.java)
}
} | apache-2.0 | 215d8af77f5ee229cb0df427761ef60b | 39 | 140 | 0.691915 | 4.60143 | false | false | false | false |
himikof/intellij-rust | src/main/kotlin/org/rust/lang/core/resolve/ImplLookup.kt | 1 | 12063 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.resolve
import com.intellij.openapi.project.Project
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.RsImplItem
import org.rust.lang.core.psi.RsTraitItem
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.resolve.indexes.RsImplIndex
import org.rust.lang.core.resolve.indexes.RsLangItemIndex
import org.rust.lang.core.types.BoundElement
import org.rust.lang.core.types.ty.*
import org.rust.lang.core.types.type
import org.rust.lang.utils.findWithCache
import kotlin.LazyThreadSafetyMode.NONE
enum class StdDerivableTrait(val modName: String, val dependencies: Array<StdDerivableTrait> = emptyArray()) {
Clone("clone"),
Copy("marker", arrayOf(Clone)),
Debug("fmt"),
Default("default"),
Hash("hash"),
PartialEq("cmp"),
Eq("cmp", arrayOf(PartialEq)),
PartialOrd("cmp", arrayOf(PartialEq)),
Ord("cmp", arrayOf(PartialOrd, Eq, PartialEq))
}
val StdDerivableTrait.withDependencies: List<StdDerivableTrait> get() = listOf(this, *dependencies)
val STD_DERIVABLE_TRAITS: Map<String, StdDerivableTrait> = StdDerivableTrait.values().associate { it.name to it }
private val RsTraitItem.isIndex: Boolean get() = langAttribute == "index"
private val RsTraitItem.typeParamSingle: TyTypeParameter? get() =
typeParameterList?.typeParameterList?.singleOrNull()?.let { TyTypeParameter.named(it) }
class ImplLookup(private val project: Project, private val items: StdKnownItems) {
// Non-concurrent HashMap and lazy(NONE) are safe here because this class isn't shared between threads
private val primitiveTyHardcodedImplsCache = mutableMapOf<TyPrimitive, Collection<BoundElement<RsTraitItem>>>()
private val fnTraits by lazy(NONE) {
listOf("fn", "fn_mut", "fn_once").mapNotNull { RsLangItemIndex.findLangItem(project, it) }
}
val fnOutputParam by lazy(NONE) {
RsLangItemIndex.findLangItem(project, "fn_once")?.let { findFreshAssociatedType(it, "Output") }
}
private val derefTraitAndTarget: Pair<RsTraitItem, TyTypeParameter>? = run {
val trait = RsLangItemIndex.findLangItem(project, "deref") ?: return@run null
findFreshAssociatedType(trait, "Target")?.let { trait to it }
}
fun findImplsAndTraits(ty: Ty): Collection<BoundElement<RsTraitOrImpl>> {
if (ty is TyTypeParameter) {
return ty.getTraitBoundsTransitively()
}
return findWithCache(project, ty) { rawFindImplsAndTraits(ty) }
}
private fun rawFindImplsAndTraits(ty: Ty): Collection<BoundElement<RsTraitOrImpl>> {
return when (ty) {
is TyTraitObject -> BoundElement(ty.trait).flattenHierarchy
is TyFunction -> {
val params = TyTuple(ty.paramTypes)
val fnOutputSubst = fnOutputParam?.let { mapOf(it to ty.retType) } ?: emptySubstitution
fnTraits.map {
val subst = mutableMapOf<TyTypeParameter, Ty>()
subst.putAll(fnOutputSubst)
it.typeParamSingle?.let { subst.put(it, params) }
BoundElement(it, subst)
}
}
is TyUnknown -> emptyList()
else -> {
findDerivedTraits(ty) + getHardcodedImpls(ty) + findSimpleImpls(ty)
}
}
}
private fun findDerivedTraits(ty: Ty): Collection<BoundElement<RsTraitItem>> {
return (ty as? TyStructOrEnumBase)?.item?.derivedTraits.orEmpty()
// select only std traits because we are sure
// that they are resolved correctly
.filter { it.isStdDerivable }
.map { BoundElement(it, mapOf(TyTypeParameter.self(it) to ty)) }
}
private fun getHardcodedImpls(ty: Ty): Collection<BoundElement<RsTraitItem>> {
// TODO this code should be completely removed after macros implementation
when (ty) {
is TyPrimitive -> {
return primitiveTyHardcodedImplsCache.getOrPut(ty) {
val impls = mutableListOf<BoundElement<RsTraitItem>>()
if (ty is TyNumeric) {
// libcore/ops/arith.rs libcore/ops/bit.rs
impls += items.findBinOpTraits().map { it.substAssocType("Output", ty) }
}
if (ty != TyStr) {
// libcore/cmp.rs
if (ty != TyUnit) {
RsLangItemIndex.findLangItem(project, "eq")?.let {
impls.add(BoundElement(it, it.typeParamSingle?.let { mapOf(it to ty) } ?: emptySubstitution))
}
}
if (ty != TyUnit && ty != TyBool) {
RsLangItemIndex.findLangItem(project, "ord")?.let {
impls.add(BoundElement(it, it.typeParamSingle?.let { mapOf(it to ty) } ?: emptySubstitution))
}
}
if (ty !is TyFloat) {
items.findEqTrait()?.let { impls.add(BoundElement(it)) }
if (ty != TyUnit && ty != TyBool) {
items.findOrdTrait()?.let { impls.add(BoundElement(it)) }
}
}
}
// libcore/clone.rs
items.findCloneTrait()?.let { impls.add(BoundElement(it)) }
impls
}
}
is TyStruct -> {
items.findCoreTy("slice::Iter").unifyWith(ty, this).substitution()?.let { subst ->
val trait = items.findIteratorTrait() ?: return emptyList()
return listOf(trait.substAssocType("Item", TyReference(subst.valueByName("T"))))
}
items.findCoreTy("slice::IterMut").unifyWith(ty, this).substitution()?.let { subst ->
val trait = items.findIteratorTrait() ?: return emptyList()
return listOf(trait.substAssocType("Item", TyReference(subst.valueByName("T"), true)))
}
}
}
return emptyList()
}
private fun findSimpleImpls(ty: Ty): Collection<BoundElement<RsTraitOrImpl>> {
val impls = RsImplIndex.findPotentialImpls(project, ty).mapNotNull { impl ->
remapTypeParameters(impl, ty)?.let { BoundElement(impl, it) }
}
val traitToImpl = impls.associateBy { it.element.traitRef?.path?.reference?.resolve() }
return impls.map { (impl, oldSubst) ->
var subst = oldSubst
impl.implementedTrait?.let { trait ->
for ((element, _) in trait.flattenHierarchy.filter { it != trait }) {
traitToImpl[element]?.let { subst = subst.substituteInValues(it.subst) }
}
}
BoundElement(impl, subst)
}
}
private fun remapTypeParameters(impl: RsImplItem, receiver: Ty): Substitution? {
val subst = impl.typeReference?.type?.unifyWith(receiver, this)?.substitution() ?: return null
val associated = (impl.implementedTrait?.subst ?: emptyMap())
.substituteInValues(subst)
return subst + associated
}
fun findMethodsAndAssocFunctions(ty: Ty): List<BoundElement<RsFunction>> {
return findImplsAndTraits(ty).flatMap { it.functionsWithInherited }
}
fun derefTransitively(baseTy: Ty): Set<Ty> {
val result = mutableSetOf<Ty>()
var ty = baseTy
while (true) {
if (ty in result) break
result += ty
ty = if (ty is TyReference) {
ty.referenced
} else {
findDerefTarget(ty)
?: break
}
}
return result
}
private fun findImplOfTrait(ty: Ty, trait: RsTraitItem): BoundElement<RsTraitOrImpl>? =
findImplsAndTraits(ty).find { it.element.implementedTrait?.element == trait }
private fun findDerefTarget(ty: Ty): Ty? {
val (derefTrait, derefTarget) = derefTraitAndTarget ?: return null
val (_, subst) = findImplOfTrait(ty, derefTrait) ?: return null
return subst[derefTarget]
}
fun findIteratorItemType(ty: Ty): Ty {
val impl = findImplsAndTraits(ty)
.find { impl ->
val traitName = impl.element.implementedTrait?.element?.name
traitName == "Iterator" || traitName == "IntoIterator"
} ?: return TyUnknown
val rawType = lookupAssociatedType(impl.element, "Item")
return rawType.substitute(impl.subst)
}
fun findIndexOutputType(containerType: Ty, indexType: Ty): Ty {
val impls = findImplsAndTraits(containerType)
.filter { it.element.implementedTrait?.element?.isIndex ?: false }
val (element, subst) = if (impls.size < 2) {
impls.firstOrNull()
} else {
impls.find { isImplSuitable(it.element, "index", 0, indexType) }
} ?: return TyUnknown
val rawOutputType = lookupAssociatedType(element, "Output")
return rawOutputType.substitute(subst)
}
fun findArithmeticBinaryExprOutputType(lhsType: Ty, rhsType: Ty, op: ArithmeticOp): Ty {
val impls = findImplsAndTraits(lhsType)
.filter { op.itemName == it.element.implementedTrait?.element?.langAttribute }
val (element, subst) = if (impls.size < 2) {
impls.firstOrNull()
} else {
impls.find { isImplSuitable(it.element, op.itemName, 0, rhsType) }
} ?: return TyUnknown
return lookupAssociatedType(element, "Output")
.substitute(subst)
.substitute(mapOf(TyTypeParameter.self(element) to lhsType))
}
private fun isImplSuitable(impl: RsTraitOrImpl,
fnName: String, paramIndex: Int, paramType: Ty): Boolean {
return impl.members?.functionList
?.find { it.name == fnName }
?.valueParameterList
?.valueParameterList
?.getOrNull(paramIndex)
?.typeReference
?.type
?.unifyWith(paramType, this)
?.substitution() != null
}
fun asTyFunction(ty: Ty): TyFunction? {
return ty as? TyFunction ?:
(findImplsAndTraits(ty).mapNotNull { it.downcast<RsTraitItem>()?.asFunctionType }.firstOrNull())
}
private val BoundElement<RsTraitItem>.asFunctionType: TyFunction? get() {
val outputParam = fnOutputParam ?: return null
val param = element.typeParamSingle ?: return null
val argumentTypes = ((subst[param] ?: TyUnknown) as? TyTuple)?.types.orEmpty()
val outputType = (subst[outputParam] ?: TyUnit)
return TyFunction(argumentTypes, outputType)
}
companion object {
fun relativeTo(psi: RsCompositeElement): ImplLookup =
ImplLookup(psi.project, StdKnownItems.relativeTo(psi))
}
}
private fun RsTraitItem.substAssocType(assoc: String, ty: Ty?): BoundElement<RsTraitItem> {
val assocType = findFreshAssociatedType(this, assoc)
val subst = if (assocType != null && ty != null) mapOf(assocType to ty) else emptySubstitution
return BoundElement(this, subst)
}
private fun Substitution.valueByName(name: String): Ty =
entries.find { it.key.toString() == name }?.value ?: TyUnknown
private fun lookupAssociatedType(impl: RsTraitOrImpl, name: String): Ty {
return impl.associatedTypesTransitively
.find { it.name == name }
?.let { it.typeReference?.type ?: TyTypeParameter.associated(it) }
?: TyUnknown
}
private fun findFreshAssociatedType(baseTrait: RsTraitItem, name: String): TyTypeParameter? =
baseTrait.associatedTypesTransitively.find { it.name == name }?.let { TyTypeParameter.associated(it) }
| mit | f776f782271fd62601bc3dceecabd8b6 | 41.326316 | 125 | 0.604079 | 4.492737 | false | false | false | false |
marius-m/wt4 | remote/src/main/java/lt/markmerkk/tickets/JiraTicketSearch.kt | 1 | 2504 | package lt.markmerkk.tickets
import lt.markmerkk.JiraUser
import lt.markmerkk.Tags
import lt.markmerkk.entities.RemoteData
import lt.markmerkk.entities.Ticket
import lt.markmerkk.toJiraUser
import net.rcarz.jiraclient.JiraClient
import org.joda.time.DateTime
import org.slf4j.LoggerFactory
import rx.Emitter
import rx.Observable
import rx.Single
class JiraTicketSearch {
fun projectStatuses(
now: DateTime,
jiraClient: JiraClient
): Single<List<String>> {
return Observable
.create(JiraProjectStatusesEmitter(jiraClient), Emitter.BackpressureMode.BUFFER)
.toSingle()
.map { statuses ->
statuses.map { it.name }
}
}
fun searchIssues(
now: DateTime,
jiraClient: JiraClient,
jql: String
): Observable<Ticket> {
return Observable.create(
JiraTicketEmitter(
jiraClient = jiraClient,
jql = jql,
searchFields = TICKET_SEARCH_FIELDS.joinToString(separator = ",")
),
Emitter.BackpressureMode.BUFFER
).flatMap {
Observable.from(it)
}.map {
val assigneeAsUser: JiraUser = it?.assignee?.toJiraUser() ?: JiraUser.asEmpty()
val reporterAsUser: JiraUser = it?.reporter?.toJiraUser() ?: JiraUser.asEmpty()
Ticket.fromRemoteData(
code = it.key,
description = it.summary,
status = it?.status?.name ?: "",
assigneeName = assigneeAsUser.identifierAsString(),
reporterName = reporterAsUser.identifierAsString(),
isWatching = it?.watches?.isWatching ?: false,
parentCode = it?.parent?.key ?: "",
remoteData = RemoteData.fromRemote(
fetchTime = now.millis,
url = it.url
)
)
}
}
companion object {
private val logger = LoggerFactory.getLogger(Tags.JIRA)
val TICKET_SEARCH_FIELDS = listOf(
"summary",
"project",
"created",
"updated",
"parent",
"issuetype",
"status",
"assignee",
"watches",
"reporter"
)
}
}
| apache-2.0 | 5e6281804848a904cd56e9249639ca2d | 31.102564 | 96 | 0.516773 | 5.089431 | false | false | false | false |
AntonovAlexander/activecore | kernelip/pipex/src/translator.kt | 1 | 4168 | /*
* translator.kt
*
* Created on: 05.06.2019
* Author: Alexander Antonov <[email protected]>
* License: See LICENSE file for details
*/
package pipex
import hwast.*
import cyclix.*
val COPIPE_TRX_ID_WIDTH = 4
internal data class __mcopipe_if_info( val wr_done : hw_var,
val rd_done : hw_var,
val full_flag : hw_var,
val empty_flag : hw_var,
val wr_ptr : hw_var,
val rd_ptr : hw_var,
val wr_ptr_next : hw_var,
val rd_ptr_next : hw_var,
val req_fifo : hw_fifo_out,
var resp_fifo : hw_fifo_in )
internal data class __mcopipe_handle_info(val struct_descr : hw_struct)
internal data class __scopipe_if_info(val req_fifo : hw_fifo_in,
var resp_fifo : hw_fifo_out)
internal data class __scopipe_handle_info(val struct_descr : hw_struct)
internal data class __assign_buf(val req : hw_var,
val buf : hw_var)
internal class __pstage_info(cyclix_gen : cyclix.Generic,
name_prefix : String,
TRX_BUF_SIZE : Int,
fc_mode : STAGE_FC_MODE,
AUTO_FIRED : Boolean,
val TranslateInfo : __TranslateInfo,
val pctrl_flushreq : hw_var) : hw_stage_stallable(cyclix_gen, name_prefix, TRX_BUF_SIZE, fc_mode, AUTO_FIRED) {
var pContext_local_dict = mutableMapOf<hw_var, hw_var>() // local variables
var pContext_srcglbls = ArrayList<hw_var>() // locals with required src bufs
var accum_tgts = ArrayList<hw_var>() // targets for accumulation
var newaccums = ArrayList<hw_var>() // new targets for accumulation (without driver on previous stage)
var assign_succ_assocs = mutableMapOf<hw_pipex_var, __assign_buf>()
var mcopipe_handle_reqs = ArrayList<hw_mcopipe_handle>()
var mcopipe_handle_resps = ArrayList<hw_mcopipe_handle>()
var mcopipe_handles = ArrayList<hw_mcopipe_handle>()
var mcopipe_handles_last = ArrayList<hw_mcopipe_handle>()
var scopipe_handle_reqs = ArrayList<hw_scopipe_handle>()
var scopipe_handle_resps = ArrayList<hw_scopipe_handle>()
var scopipe_handles = ArrayList<hw_scopipe_handle>()
var var_dict = mutableMapOf<hw_var, hw_var>()
fun TranslateVar(src : hw_var) : hw_var {
return TranslateVar(src, var_dict)
}
fun TranslateParam(src : hw_param) : hw_param {
if (src is hw_imm) return src
else return TranslateVar(src as hw_var)
}
fun TranslateParams(srcs : ArrayList<hw_param>) : ArrayList<hw_param> {
var params = ArrayList<hw_param>()
for (src in srcs) params.add(TranslateParam(src))
return params
}
fun pflush_cmd_internal(cyclix_gen : cyclix.Generic) {
cyclix_gen.bor_gen(pctrl_flushreq, pctrl_flushreq, ctrl_active)
}
}
internal class __TranslateInfo(var pipeline : Pipeline) {
var __global_assocs = mutableMapOf<hw_var, hw_var>()
var __fifo_wr_assocs = mutableMapOf<hw_fifo_out, hw_fifo_out>()
var __fifo_rd_assocs = mutableMapOf<hw_fifo_in, hw_fifo_in>()
var __mcopipe_if_assocs = mutableMapOf<hw_mcopipe_if, __mcopipe_if_info>()
var __mcopipe_handle_assocs = mutableMapOf<hw_mcopipe_handle, __mcopipe_handle_info>()
var __mcopipe_handle_reqdict = mutableMapOf<hw_mcopipe_handle, ArrayList<hw_mcopipe_if>>()
var __scopipe_if_assocs = mutableMapOf<hw_scopipe_if, __scopipe_if_info>()
var __scopipe_handle_assocs = mutableMapOf<hw_scopipe_handle, __scopipe_handle_info>()
var __scopipe_handle_reqdict = mutableMapOf<hw_scopipe_handle, ArrayList<hw_scopipe_if>>()
var __stage_assocs = mutableMapOf<hw_pipex_stage, __pstage_info>()
var StageList = ArrayList<hw_pipex_stage>()
var StageInfoList = ArrayList<__pstage_info>()
var gencredit_counter = DUMMY_VAR
} | apache-2.0 | 3e8c576c3379fcfb41ced4adf510e9eb | 39.475728 | 134 | 0.59501 | 3.493713 | false | false | false | false |
iSoron/uhabits | uhabits-android/src/androidTest/java/org/isoron/uhabits/acceptance/steps/BackupSteps.kt | 1 | 3852 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker 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 org.isoron.uhabits.acceptance.steps
import android.os.Build.VERSION.SDK_INT
import android.os.SystemClock.sleep
import androidx.test.uiautomator.By
import androidx.test.uiautomator.UiSelector
import org.isoron.uhabits.BaseUserInterfaceTest.Companion.device
import org.isoron.uhabits.acceptance.steps.CommonSteps.clickText
import org.isoron.uhabits.acceptance.steps.CommonSteps.pressBack
import org.isoron.uhabits.acceptance.steps.ListHabitsSteps.MenuItem.SETTINGS
import org.isoron.uhabits.acceptance.steps.ListHabitsSteps.clickMenu
const val BACKUP_FOLDER = "/sdcard/Android/data/org.isoron.uhabits/files/Backups/"
const val DOWNLOAD_FOLDER = "/sdcard/Download/"
fun exportFullBackup() {
clickMenu(SETTINGS)
clickText("Export full backup")
if (SDK_INT < 28) return
pressBack()
}
fun clearDownloadFolder() {
device.executeShellCommand("rm -rf /sdcard/Download")
}
fun clearBackupFolder() {
device.executeShellCommand("rm -rf $BACKUP_FOLDER")
}
fun copyBackupToDownloadFolder() {
device.executeShellCommand("mv $BACKUP_FOLDER $DOWNLOAD_FOLDER")
device.executeShellCommand("chown root $DOWNLOAD_FOLDER")
}
fun importBackupFromDownloadFolder() {
clickMenu(SETTINGS)
clickText("Import data")
if (SDK_INT <= 23) {
while (!device.hasObject(By.textContains("Show file size"))) {
device.click(720, 100) // Click overflow menu
Thread.sleep(1000)
}
if (device.hasObject(By.textContains("Show SD card"))) {
device.findObject(UiSelector().textContains("Show SD card")).click()
Thread.sleep(1000)
} else {
device.pressBack()
}
device.click(50, 90) // Click menu button
device.findObject(UiSelector().textContains("Internal storage")).click()
device.findObject(UiSelector().textContains("Download")).click()
device.findObject(UiSelector().textContains("Loop")).click()
} else if (SDK_INT <= 25) {
while (!device.hasObject(By.textContains("Show file size"))) {
device.click(720, 100) // Click overflow menu
Thread.sleep(1000)
}
if (device.hasObject(By.textContains("Show internal"))) {
device.findObject(UiSelector().textContains("Show internal")).click()
Thread.sleep(1000)
} else {
device.pressBack()
}
device.click(50, 90) // Click menu button
device.findObject(UiSelector().textContains("Android")).click()
device.findObject(UiSelector().textContains("Download")).click()
device.findObject(UiSelector().textContains("Loop")).click()
} else {
device.click(50, 90) // Click menu button
Thread.sleep(1000)
device.findObject(UiSelector().textContains("Download")).click()
device.findObject(UiSelector().textContains("Loop")).click()
}
}
fun openLauncher() {
device.pressHome()
device.waitForIdle()
val h = device.displayHeight
val w = device.displayWidth
device.swipe(w / 2, h / 2, w / 2, 0, 8)
}
| gpl-3.0 | ea436ee10e20a97fd82706ee7c4d67aa | 36.754902 | 82 | 0.69047 | 4.172264 | false | false | false | false |
mdanielwork/intellij-community | plugins/stats-collector/src/com/intellij/stats/personalization/impl/ItemPositionFactors.kt | 7 | 2716 | /*
* 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.stats.personalization.impl
import com.intellij.stats.personalization.UserFactorBase
import com.intellij.stats.personalization.UserFactorDescriptions
import com.intellij.stats.personalization.UserFactorReaderBase
import com.intellij.stats.personalization.UserFactorUpdaterBase
/**
* @author Vitaliy.Bibaev
*/
class ItemPositionReader(factor: DailyAggregatedDoubleFactor) : UserFactorReaderBase(factor) {
fun getCountsByPosition(): Map<Int, Double> {
return factor.aggregateSum().asIterable().associate { (key, value) -> key.toInt() to value }
}
fun getAveragePosition(): Double? {
val positionToCount = getCountsByPosition()
if (positionToCount.isEmpty()) return null
val positionsSum = positionToCount.asSequence().sumByDouble { it.key * it.value }
val completionCount = positionToCount.asSequence().sumByDouble { it.value }
if (completionCount == 0.0) return null
return positionsSum / completionCount
}
}
class ItemPositionUpdater(factor: MutableDoubleFactor) : UserFactorUpdaterBase(factor) {
fun fireCompletionPerformed(selectedItemOrder: Int) {
factor.incrementOnToday(selectedItemOrder.toString())
}
}
class AverageSelectedItemPosition
: UserFactorBase<ItemPositionReader>("averageSelectedPosition", UserFactorDescriptions.SELECTED_ITEM_POSITION) {
override fun compute(reader: ItemPositionReader): String? = reader.getAveragePosition()?.toString()
}
class MaxSelectedItemPosition
: UserFactorBase<ItemPositionReader>("maxSelectedItemPosition", UserFactorDescriptions.SELECTED_ITEM_POSITION) {
override fun compute(reader: ItemPositionReader): String? =
reader.getCountsByPosition().asSequence().filter { it.value != 0.0 }.maxBy { it.key }?.key?.toString()
}
class MostFrequentSelectedItemPosition
: UserFactorBase<ItemPositionReader>("mostFrequentItemPosition", UserFactorDescriptions.SELECTED_ITEM_POSITION) {
override fun compute(reader: ItemPositionReader): String? =
reader.getCountsByPosition().maxBy { it.value }?.key?.toString()
}
| apache-2.0 | 4e2563ecdedab7ec1f30cd15c07c55b3 | 40.151515 | 117 | 0.754786 | 4.437908 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/navtab/NavTabLayout.kt | 1 | 1316 | package org.wikipedia.navtab
import android.content.Context
import android.text.TextUtils
import android.util.AttributeSet
import android.view.Menu
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.view.forEach
import androidx.core.view.isNotEmpty
import androidx.core.view.updatePadding
import com.google.android.material.bottomnavigation.BottomNavigationView
import org.wikipedia.R
class NavTabLayout constructor(context: Context, attrs: AttributeSet) : BottomNavigationView(context, attrs) {
init {
menu.clear()
for (i in 0 until NavTab.size()) {
val navTab = NavTab.of(i)
menu.add(Menu.NONE, navTab.id(), i, navTab.text()).setIcon(navTab.icon())
}
fixTextStyle()
}
private fun fixTextStyle() {
if (isNotEmpty()) {
(getChildAt(0) as ViewGroup).forEach {
val largeLabel = it.findViewById<TextView>(R.id.largeLabel)
largeLabel.ellipsize = TextUtils.TruncateAt.END
largeLabel.updatePadding(left = 0, right = 0)
val smallLabel = it.findViewById<TextView>(R.id.smallLabel)
smallLabel.ellipsize = TextUtils.TruncateAt.END
smallLabel.updatePadding(left = 0, right = 0)
}
}
}
}
| apache-2.0 | fe9e62c533ca867c67cc91dedc755163 | 34.567568 | 110 | 0.667173 | 4.272727 | false | false | false | false |
sph-u/failchat | src/main/kotlin/failchat/emoticon/EmoticonCodeIdDbStorage.kt | 1 | 2118 | package failchat.emoticon
import failchat.Origin
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.runBlocking
import org.mapdb.DB
import org.mapdb.HTreeMap
import org.mapdb.Serializer
import org.mapdb.serializer.GroupSerializer
class EmoticonCodeIdDbStorage(
db: DB,
override val origin: Origin,
private val caseSensitiveCode: Boolean
) : OriginEmoticonStorage {
private val codeToId: HTreeMap<String, String>
private val idToEmoticon: HTreeMap<String, Emoticon>
init {
codeToId = db
.hashMap(origin.commonName + "-codeToId", Serializer.STRING, Serializer.STRING)
.createOrOpen()
idToEmoticon = db
.hashMap(origin.commonName + "-idToEmoticon", Serializer.STRING, Serializer.JAVA as GroupSerializer<Emoticon>)
.createOrOpen()
}
override fun findByCode(code: String): Emoticon? {
val cCode = if (caseSensitiveCode) code else code.toLowerCase()
val id = codeToId.get(cCode) ?: return null
return idToEmoticon.get(id)
}
override fun findById(id: String): Emoticon? {
return idToEmoticon.get(id)
}
override fun getAll(): Collection<Emoticon> {
return idToEmoticon.values.filterNotNull()
}
override fun count(): Int {
return idToEmoticon.size
}
override fun putAll(emoticons: Collection<EmoticonAndId>) {
emoticons.forEach {
putEmoticon(it)
}
}
override fun putAll(emoticons: ReceiveChannel<EmoticonAndId>) {
runBlocking {
for (emoticonAndId in emoticons) {
putEmoticon(emoticonAndId)
}
}
}
private fun putEmoticon(emoticonAndId: EmoticonAndId) {
val code = emoticonAndId.emoticon.code.let { c ->
if (caseSensitiveCode) c else c.toLowerCase()
}
idToEmoticon.put(emoticonAndId.id, emoticonAndId.emoticon)
codeToId.put(code, emoticonAndId.id)
}
override fun clear() {
idToEmoticon.clear()
codeToId.clear()
}
}
| mit | e1bdb3949d1b73099c7fb939fbaabe2e | 27.621622 | 126 | 0.648253 | 4.440252 | false | false | false | false |
android/privacy-codelab | PhotoLog_End/src/main/java/com/example/photolog_end/AddLogViewModel.kt | 1 | 7394 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.photolog_end
import android.Manifest
import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Geocoder
import android.net.Uri
import android.provider.Settings
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.core.content.ContextCompat
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.CreationExtras
import androidx.room.Room
import com.example.photolog_end.AppDatabase.Companion.DB_NAME
import com.google.android.gms.location.LocationServices
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch
import java.io.File
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
class AddLogViewModel(
application: Application,
private val photoSaver: PhotoSaverRepository
) : AndroidViewModel(application) {
// region ViewModel setup
private val context: Context
get() = getApplication()
private val mediaRepository = MediaRepository(context)
private val db = Room.databaseBuilder(context, AppDatabase::class.java, DB_NAME).build()
// endregion
// region UI state
data class UiState(
val hasLocationAccess: Boolean,
val hasCameraAccess: Boolean,
val isSaving: Boolean = false,
val isSaved: Boolean = false,
val date: Long,
val place: String? = null,
val savedPhotos: List<File> = emptyList(),
val localPickerPhotos: List<Uri> = emptyList()
)
var uiState by mutableStateOf(
UiState(
hasLocationAccess = hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION),
hasCameraAccess = hasPermission(Manifest.permission.CAMERA),
date = getTodayDateInMillis(),
savedPhotos = photoSaver.getPhotos()
)
)
private set
fun isValid(): Boolean {
return uiState.place != null && !photoSaver.isEmpty() && !uiState.isSaving
}
private fun getTodayDateInMillis(): Long {
val calendar = Calendar.getInstance()
calendar.set(Calendar.HOUR, 0)
calendar.set(Calendar.MINUTE, 0)
calendar.set(Calendar.SECOND, 0)
return calendar.timeInMillis
}
private fun getIsoDate(timeInMillis: Long): String {
return SimpleDateFormat("yyyy-MM-dd", Locale.US).format(timeInMillis)
}
fun hasPermission(permission: String): Boolean {
return ContextCompat.checkSelfPermission(
context,
permission
) == PackageManager.PERMISSION_GRANTED
}
fun onPermissionChange(permission: String, isGranted: Boolean) {
when (permission) {
Manifest.permission.ACCESS_COARSE_LOCATION -> {
uiState = uiState.copy(hasLocationAccess = isGranted)
}
Manifest.permission.CAMERA -> {
uiState = uiState.copy(hasCameraAccess = isGranted)
}
else -> {
Log.e("Permission change", "Unexpected permission: $permission")
}
}
}
fun onDateChange(dateInMillis: Long) {
uiState = uiState.copy(date = dateInMillis)
}
fun createSettingsIntent(): Intent {
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
data = Uri.fromParts("package", context.packageName, null)
}
return intent
}
// endregion
// region Location management
@SuppressLint("MissingPermission")
fun fetchLocation() {
val fusedLocationClient = LocationServices.getFusedLocationProviderClient(context)
fusedLocationClient.lastLocation.addOnSuccessListener { location ->
location ?: return@addOnSuccessListener
val geocoder = Geocoder(context, Locale.getDefault())
val address =
geocoder.getFromLocation(location.latitude, location.longitude, 1).firstOrNull()
?: return@addOnSuccessListener
val place =
address.locality ?: address.subAdminArea ?: address.adminArea ?: address.countryName
?: return@addOnSuccessListener
uiState = uiState.copy(place = place)
}
}
// endregion
fun loadLocalPickerPictures() {
viewModelScope.launch {
val localPickerPhotos = mediaRepository.fetchImages().map { it.uri }.toList()
uiState = uiState.copy(localPickerPhotos = localPickerPhotos)
}
}
fun onLocalPhotoPickerSelect(photo: Uri) {
viewModelScope.launch {
photoSaver.cacheFromUri(photo)
refreshSavedPhotos()
}
}
fun onPhotoPickerSelect(photos: List<Uri>) {
viewModelScope.launch {
photoSaver.cacheFromUris(photos)
refreshSavedPhotos()
}
}
// region Photo management
fun canAddPhoto() = photoSaver.canAddPhoto()
fun refreshSavedPhotos() {
uiState = uiState.copy(savedPhotos = photoSaver.getPhotos())
}
fun onPhotoRemoved(photo: File) {
viewModelScope.launch {
photoSaver.removeFile(photo)
refreshSavedPhotos()
}
}
fun createLog() {
if (!isValid()) {
return
}
uiState = uiState.copy(isSaving = true)
viewModelScope.launch {
val photos = photoSaver.savePhotos()
val calendar = Calendar.getInstance()
calendar.timeInMillis = uiState.date
Log.e("date is ", uiState.date.toString())
val log = LogEntry(
date = getIsoDate(uiState.date),
place = uiState.place!!,
photo1 = photos[0].name,
photo2 = photos.getOrNull(1)?.name,
photo3 = photos.getOrNull(2)?.name,
)
db.logDao().insert(log)
uiState = uiState.copy(isSaved = true)
}
}
// endregion
}
class AddLogViewModelFactory : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T {
val app = extras[APPLICATION_KEY] as PhotoGoodApplication
return AddLogViewModel(app, app.photoSaver) as T
}
} | apache-2.0 | 4186a86e61aa572810ddc30e101f465f | 31.721239 | 100 | 0.663105 | 4.826371 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/mixin/action/FindMixinsAction.kt | 1 | 4087 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.action
import com.demonwav.mcdev.asset.MixinAssets
import com.demonwav.mcdev.platform.mixin.util.MixinConstants
import com.demonwav.mcdev.platform.mixin.util.mixinTargets
import com.demonwav.mcdev.util.findReferencedClass
import com.demonwav.mcdev.util.fullQualifiedName
import com.demonwav.mcdev.util.gotoTargetElement
import com.demonwav.mcdev.util.invokeLater
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys.CARET
import com.intellij.openapi.actionSystem.CommonDataKeys.EDITOR
import com.intellij.openapi.actionSystem.CommonDataKeys.PROJECT
import com.intellij.openapi.actionSystem.CommonDataKeys.PSI_FILE
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.progress.runBackgroundableTask
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.searches.AnnotatedElementsSearch
import com.intellij.ui.content.ContentFactory
class FindMixinsAction : AnAction() {
companion object {
private const val TOOL_WINDOW_ID = "Find Mixins"
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.getData(PROJECT) ?: return
val file = e.getData(PSI_FILE) ?: return
val caret = e.getData(CARET) ?: return
val editor = e.getData(EDITOR) ?: return
val element = file.findElementAt(caret.offset) ?: return
val classOfElement = element.findReferencedClass()?.qualifiedName ?: return
invokeLater {
runBackgroundableTask("Searching for Mixins", project, true) run@{ indicator ->
indicator.isIndeterminate = true
val classes = runReadAction {
val mixinAnnotation = JavaPsiFacade.getInstance(project).findClass(
MixinConstants.Annotations.MIXIN,
GlobalSearchScope.allScope(project)
) ?: return@runReadAction null
// Check all classes with the Mixin annotation
val classes = AnnotatedElementsSearch.searchPsiClasses(
mixinAnnotation,
GlobalSearchScope.projectScope(project)
)
.filter {
indicator.text = "Checking ${it.name}..."
it.mixinTargets.any { c ->
c.qualifiedName == classOfElement
}
}
when (classes.size) {
0 -> null
1 -> classes
else ->
// Sort classes
classes.sortedBy(PsiClass::fullQualifiedName)
}
} ?: return@run
invokeLater {
if (classes.size == 1) {
gotoTargetElement(classes.single(), editor, file)
} else {
ToolWindowManager.getInstance(project).unregisterToolWindow(TOOL_WINDOW_ID)
val window = ToolWindowManager.getInstance(project)
.registerToolWindow(TOOL_WINDOW_ID, true, ToolWindowAnchor.BOTTOM)
window.icon = MixinAssets.MIXIN_CLASS_ICON
val component = FindMixinsComponent(classes)
val content = ContentFactory.SERVICE.getInstance().createContent(component.panel, null, false)
window.contentManager.addContent(content)
window.activate(null)
}
}
}
}
}
}
| mit | d667a69fc6d15512b855d323ec2d2226 | 39.068627 | 118 | 0.610472 | 5.456609 | false | false | false | false |
paplorinc/intellij-community | platform/built-in-server-api/src/org/jetbrains/builtInWebServer/PathInfo.kt | 6 | 2372 | package org.jetbrains.builtInWebServer
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.io.isDirectory
import com.intellij.util.io.systemIndependentPath
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
class PathInfo(val ioFile: Path?, file: VirtualFile?, val root: VirtualFile, moduleName: String? = null, val isLibrary: Boolean = false, val isRootNameOptionalInPath: Boolean = false) {
var file: VirtualFile? = file
private set
var moduleName: String? = moduleName
set
/**
* URL path.
*/
val path: String by lazy {
buildPath(true)
}
val rootLessPathIfPossible: String? by lazy {
if (isRootNameOptionalInPath) buildPath(false) else null
}
private fun buildPath(useRootName: Boolean): String {
val builder = StringBuilder()
if (moduleName != null) {
builder.append(moduleName).append('/')
}
if (isLibrary) {
builder.append(root.name).append('/')
}
val relativeTo = if (useRootName) root else root.parent ?: root
if (file == null) {
builder.append(FileUtilRt.getRelativePath(relativeTo.path, ioFile!!.toString().replace(File.separatorChar, '/'), '/'))
}
else {
builder.append(VfsUtilCore.getRelativePath(file!!, relativeTo, '/'))
}
return builder.toString()
}
fun getOrResolveVirtualFile(): VirtualFile? {
return if (file == null) {
val result = LocalFileSystem.getInstance().findFileByPath(ioFile!!.systemIndependentPath)
file = result
result
}
else {
file
}
}
/**
* System-dependent path to file.
*/
val filePath: String by lazy { ioFile?.toString() ?: FileUtilRt.toSystemDependentName(file!!.path) }
val isValid: Boolean
get() = if (ioFile == null) file!!.isValid else Files.exists(ioFile)
val name: String
get() = ioFile?.fileName?.toString() ?: file!!.name
val fileType: FileType
get() = if (ioFile == null) file!!.fileType else FileTypeManager.getInstance().getFileTypeByFileName(ioFile.fileName.toString())
fun isDirectory(): Boolean = ioFile?.isDirectory() ?: file!!.isDirectory
} | apache-2.0 | 88e874030d12aa9f2f099c3927bf61b0 | 28.6625 | 185 | 0.699831 | 4.320583 | false | false | false | false |
paplorinc/intellij-community | platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/customFrameDecorations/style/Properties.kt | 5 | 1642 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.ui.laf.darcula.ui.customFrameDecorations.style
import java.awt.Color
import java.awt.Insets
import javax.swing.Icon
import javax.swing.JComponent
import javax.swing.border.Border
class Properties {
private val map = HashMap<StyleProperty, Any?>()
var background: Color?
set(value) = setValue(StyleProperty.BACKGROUND, value)
get() = getValue(StyleProperty.BACKGROUND) as Color
var isOpaque: Boolean?
set(value) = setValue(StyleProperty.OPAQUE, value)
get() = getValue(StyleProperty.OPAQUE) as Boolean
var foreground: Color?
set(value) = setValue(StyleProperty.FOREGROUND, value)
get() = getValue(StyleProperty.FOREGROUND) as Color
var border: Border?
set(value) = setValue(StyleProperty.BORDER, value)
get() = getValue(StyleProperty.BORDER) as Border
var icon: Icon?
set(value) = setValue(StyleProperty.ICON, value)
get() = getValue(StyleProperty.ICON) as Icon
var margin: Insets?
set(value) = setValue(StyleProperty.MARGIN, value)
get() = getValue(StyleProperty.MARGIN) as Insets
fun setValue(prop: StyleProperty, value: Any?) {
map[prop] = value
}
fun getValue(prop: StyleProperty): Any? = map[prop]
fun clone(): Properties {
val new = Properties()
new.map +=map
return new
}
fun updateBy(source: Properties): Properties {
map += source.map
return this
}
fun <T : JComponent> applyTo(component: T) {
for ((k, v) in map) {
k.apply(component, v)
}
}
} | apache-2.0 | 272bc97caa7a5d9fde9405e225497406 | 30 | 140 | 0.705238 | 3.757437 | false | false | false | false |
google/intellij-community | platform/platform-api/src/com/intellij/ui/tabs/impl/JBEditorTabsBorder.kt | 1 | 4817 | // 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.ui.tabs.impl
import com.intellij.openapi.rd.paint2DLine
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.ExperimentalUI
import com.intellij.ui.paint.LinePainter2D
import com.intellij.ui.tabs.JBTabsBorder
import com.intellij.ui.tabs.JBTabsPosition
import com.intellij.ui.tabs.TabInfo
import com.intellij.ui.tabs.TabsListener
import com.intellij.util.animation.Easing
import com.intellij.util.animation.JBAnimator
import com.intellij.util.animation.animation
import com.intellij.util.ui.JBUI
import java.awt.*
class JBEditorTabsBorder(tabs: JBTabsImpl) : JBTabsBorder(tabs) {
private val animator = JBAnimator()
private var start: Int = -1
private var end: Int = -1
private var animationId = -1L
init {
tabs.addListener(object : TabsListener {
override fun selectionChanged(oldSelection: TabInfo?, newSelection: TabInfo?) {
val from = bounds(oldSelection)
val to = bounds(newSelection)
if (from != null && to != null) {
val dur = 100
val del = 50
val s1 = from.x
val s2 = to.x
val d1 = if (s1 > s2) 0 else del
val e1 = from.x + from.width
val e2 = to.x + to.width
val d2 = if (e1 > e2) del else 0
animationId = animator.animate(
animation(s1, s2) {
start = it
tabs.component.repaint()
}.apply {
duration = dur - d1
delay = d1
easing = if (d1 != 0) Easing.EASE_OUT else Easing.LINEAR
},
animation(e1, e2) {
end = it
tabs.component.repaint()
}.apply {
duration = dur - d2
delay = d2
easing = if (d2 != 0) Easing.EASE_OUT else Easing.LINEAR
}
)
}
}
private fun bounds(tabInfo: TabInfo?): Rectangle? {
return tabs.myInfo2Label[tabInfo ?: return null]?.bounds
}
})
}
override val effectiveBorder: Insets
get() = Insets(thickness, 0, 0, 0)
override fun paintBorder(c: Component, g: Graphics, x: Int, y: Int, width: Int, height: Int) {
g as Graphics2D
if (ExperimentalUI.isNewUI()) {
g.paint2DLine(Point(x, y), Point(x + width, y), LinePainter2D.StrokeType.INSIDE,
thickness.toDouble(), JBUI.CurrentTheme.EditorTabs.borderColor())
}
else tabs.tabPainter.paintBorderLine(g, thickness, Point(x, y), Point(x + width, y))
if (tabs.isEmptyVisible || tabs.isHideTabs) return
val myInfo2Label = tabs.myInfo2Label
val firstLabel = myInfo2Label[tabs.visibleInfos[0]] ?: return
val startY = firstLabel.y - if (tabs.position == JBTabsPosition.bottom) 0 else thickness
when (tabs.position) {
JBTabsPosition.top -> {
val startRow = if (ExperimentalUI.isNewUI()) 1 else 0
val lastRow = tabs.lastLayoutPass.rowCount
for (eachRow in startRow until lastRow) {
val yl = (eachRow * tabs.myHeaderFitSize.height) + startY
tabs.tabPainter.paintBorderLine(g, thickness, Point(x, yl), Point(x + width, yl))
}
if (!ExperimentalUI.isNewUI() || (tabs as JBEditorTabs).shouldPaintBottomBorder()) {
val yl = lastRow * tabs.myHeaderFitSize.height + startY
tabs.tabPainter.paintBorderLine(g, thickness, Point(x, yl), Point(x + width, yl))
}
}
JBTabsPosition.bottom -> {
tabs.tabPainter.paintBorderLine(g, thickness, Point(x, startY), Point(x + width, startY))
}
JBTabsPosition.right -> {
val lx = firstLabel.x
tabs.tabPainter.paintBorderLine(g, thickness, Point(lx, y), Point(lx, y + height))
}
JBTabsPosition.left -> {
val bounds = firstLabel.bounds
val i = bounds.x + bounds.width - thickness
tabs.tabPainter.paintBorderLine(g, thickness, Point(i, y), Point(i, y + height))
}
}
if (hasAnimation()) {
tabs.tabPainter.paintUnderline(tabs.position, calcRectangle() ?: return, thickness, g, tabs.isActiveTabs(tabs.selectedInfo))
} else {
val selectedLabel = tabs.selectedLabel ?: return
tabs.tabPainter.paintUnderline(tabs.position, selectedLabel.bounds, thickness, g, tabs.isActiveTabs(tabs.selectedInfo))
}
}
private fun calcRectangle(): Rectangle? {
val selectedLabel = tabs.selectedLabel ?: return null
if (animator.isRunning(animationId)) {
return Rectangle(start, selectedLabel.y, end - start, selectedLabel.height)
}
return selectedLabel.bounds
}
companion object {
fun hasAnimation() = Registry.`is`("ide.editor.tab.selection.animation", false)
}
} | apache-2.0 | bd60620e0ffa5735d392e2fb21c6ffab | 35.5 | 130 | 0.636496 | 3.964609 | false | false | false | false |
google/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/quickfix/AddExclExclCallFix.kt | 2 | 3135 | // 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.quickfix
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
class AddExclExclCallFix(psiElement: PsiElement, val fixImplicitReceiver: Boolean = false) : ExclExclCallFix(psiElement),
LowPriorityAction {
override fun getText() = KotlinBundle.message("fix.introduce.non.null.assertion")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val modifiedExpression = element ?: return
val psiFactory = KtPsiFactory(project)
if (fixImplicitReceiver) {
val exclExclExpression = if (modifiedExpression is KtCallableReferenceExpression) {
psiFactory.createExpressionByPattern("this!!::$0", modifiedExpression.callableReference)
} else {
psiFactory.createExpressionByPattern("this!!.$0", modifiedExpression)
}
modifiedExpression.replace(exclExclExpression)
} else {
val parent = modifiedExpression.parent
val operationToken = when (parent) {
is KtBinaryExpression -> parent.operationToken
is KtUnaryExpression -> parent.operationToken
else -> null
}
when {
operationToken in KtTokens.AUGMENTED_ASSIGNMENTS && parent is KtBinaryExpression -> {
val right = parent.right ?: return
val newOperationToken = when (operationToken) {
KtTokens.PLUSEQ -> KtTokens.PLUS
KtTokens.MINUSEQ -> KtTokens.MINUS
KtTokens.MULTEQ -> KtTokens.MUL
KtTokens.PERCEQ -> KtTokens.PERC
KtTokens.DIVEQ -> KtTokens.DIV
else -> return
}
val newExpression = psiFactory.createExpressionByPattern(
"$0 = $1!! ${newOperationToken.value} $2", modifiedExpression, modifiedExpression, right
)
parent.replace(newExpression)
}
(operationToken == KtTokens.PLUSPLUS || operationToken == KtTokens.MINUSMINUS) && parent is KtUnaryExpression -> {
val newOperationToken = if (operationToken == KtTokens.PLUSPLUS) KtTokens.PLUS else KtTokens.MINUS
val newExpression = psiFactory.createExpressionByPattern(
"$0 = $1!! ${newOperationToken.value} 1", modifiedExpression, modifiedExpression
)
parent.replace(newExpression)
}
else -> modifiedExpression.replace(psiFactory.createExpressionByPattern("$0!!", modifiedExpression))
}
}
}
} | apache-2.0 | a21fee7b774f7fbc98648e5e41b547aa | 49.580645 | 130 | 0.61882 | 5.848881 | false | false | false | false |
StephaneBg/ScoreIt | app/src/main/kotlin/com/sbgapps/scoreit/app/ui/prefs/PreferencesActivity.kt | 1 | 3505 | /*
* Copyright 2020 Stéphane Baiget
*
* 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.sbgapps.scoreit.app.ui.prefs
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatDelegate
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.sbgapps.scoreit.app.R
import com.sbgapps.scoreit.app.databinding.ActivityPreferencesBinding
import com.sbgapps.scoreit.app.ui.history.HistoryActivity
import com.sbgapps.scoreit.core.ext.start
import com.sbgapps.scoreit.core.ui.BaseActivity
import com.sbgapps.scoreit.core.utils.THEME_MODE_AUTO
import com.sbgapps.scoreit.core.utils.THEME_MODE_DARK
import com.sbgapps.scoreit.core.utils.THEME_MODE_LIGHT
import org.koin.androidx.viewmodel.ext.android.viewModel
class PreferencesActivity : BaseActivity() {
private val viewModel by viewModel<PreferencesViewModel>()
private lateinit var binding: ActivityPreferencesBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AppCompatDelegate.setDefaultNightMode(viewModel.getThemeMode())
binding = ActivityPreferencesBinding.inflate(layoutInflater)
setContentView(binding.root)
}
override fun onResume() {
super.onResume()
setupActionBar(binding.toolbar)
binding.themeMode.setOnClickListener {
MaterialAlertDialogBuilder(this)
.setTitle(R.string.prefs_select_theme_mode)
.setSingleChoiceItems(R.array.settings_theme_modes, getCurrentChoice()) { _, which ->
saveSelectedChoice(which)
start<HistoryActivity> {
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
}
finish()
}
.create()
.show()
}
binding.showTotal.apply {
isChecked = viewModel.isUniversalTotalDisplayed()
setOnCheckedChangeListener { _, isChecked ->
viewModel.setUniversalTotalDisplayed(isChecked)
}
}
binding.roundBelote.apply {
isChecked = viewModel.isBeloteScoreRounded()
setOnCheckedChangeListener { _, isChecked ->
viewModel.setBeloteScoreRounded(isChecked)
}
}
binding.roundCoinche.apply {
isChecked = viewModel.isCoincheScoreRounded()
setOnCheckedChangeListener { _, isChecked ->
viewModel.setCoincheScoreRounded(isChecked)
}
}
}
private fun getCurrentChoice(): Int = when (viewModel.getPrefThemeMode()) {
THEME_MODE_LIGHT -> 0
THEME_MODE_DARK -> 1
else -> 2
}
private fun saveSelectedChoice(which: Int) {
val mode = when (which) {
0 -> THEME_MODE_LIGHT
1 -> THEME_MODE_DARK
else -> THEME_MODE_AUTO
}
viewModel.setPrefThemeMode(mode)
}
}
| apache-2.0 | d8af680be23a86256108fede8712d778 | 33.693069 | 101 | 0.664669 | 4.806584 | false | false | false | false |
square/okhttp | okhttp/src/commonMain/kotlin/okhttp3/internal/-RequestBodyCommon.kt | 2 | 1747 | /*
* Copyright (C) 2022 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal
import okhttp3.MediaType
import okhttp3.RequestBody
import okio.BufferedSink
import okio.ByteString
fun ByteArray.commonToRequestBody(
contentType: MediaType?,
offset: Int,
byteCount: Int
): RequestBody {
checkOffsetAndCount(size.toLong(), offset.toLong(), byteCount.toLong())
return object : RequestBody() {
override fun contentType() = contentType
override fun contentLength() = byteCount.toLong()
override fun writeTo(sink: BufferedSink) {
sink.write(this@commonToRequestBody, offset, byteCount)
}
}
}
@Suppress("unused")
fun RequestBody.commonContentLength(): Long = -1L
@Suppress("unused")
fun RequestBody.commonIsDuplex(): Boolean = false
@Suppress("unused")
fun RequestBody.commonIsOneShot(): Boolean = false
/** Returns a new request body that transmits this. */
fun ByteString.commonToRequestBody(contentType: MediaType?): RequestBody {
return object : RequestBody() {
override fun contentType() = contentType
override fun contentLength() = size.toLong()
override fun writeTo(sink: BufferedSink) {
sink.write(this@commonToRequestBody)
}
}
}
| apache-2.0 | 0c63efe66ef3698d0856882a17686332 | 27.639344 | 75 | 0.734974 | 4.292383 | false | false | false | false |
java-graphics/assimp | src/main/kotlin/assimp/camera.kt | 2 | 7851 | /*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* 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.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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.
---------------------------------------------------------------------------
*/
package assimp
import glm_.BYTES
import glm_.f
import glm_.glm
import glm_.mat4x4.Mat4
import glm_.vec3.Vec3
import kool.BYTES
// ---------------------------------------------------------------------------
/** Helper structure to describe a virtual camera.
*
* Cameras have a representation in the node graph and can be animated.
* An important aspect is that the camera itself is also part of the scenegraph. This means, any values such as the look-at vector are not *absolute*, they're
* <b>relative</b> to the coordinate system defined by the node which corresponds to the camera. This allows for camera animations. For static cameras parameters
* like the 'look-at' or 'up' vectors are usually specified directly in aiCamera, but beware, they could also be encoded in the node transformation. The following
* (pseudo)code sample shows how to do it: <br><br>
* @code
* // Get the camera matrix for a camera at a specific time
* // if the node hierarchy for the camera does not contain
* // at least one animated node this is a static computation
* get-camera-matrix (node sceneRoot, camera cam) : matrix
* {
* node cnd = find-node-for-camera(cam)
* matrix cmt = identity()
*
* // as usual - get the absolute camera transformation for this frame
* for each node nd in hierarchy from sceneRoot to cnd
* matrix cur
* if (is-animated(nd))
* cur = eval-animation(nd)
* else cur = nd->transformation;
* cmt = mult-matrices( cmt, cur )
* end for
*
* // now multiply with the camera's own local transform
* cam = mult-matrices (cam, get-camera-matrix(cmt) )
* }
* @endcode
*
* @note some file formats (such as 3DS, ASE) export a "target point" -
* the point the camera is looking at (it can even be animated). Assimp
* writes the target point as a subnode of the camera's main node,
* called "<camName>.Target". However this is just additional information
* then the transformation tracks of the camera main node make the
* camera already look in the right direction.
*
*/
class AiCamera(
/** The name of the camera.
*
* There must be a node in the scenegraph with the same name.
* This node specifies the position of the camera in the scene
* hierarchy and can be animated.
*/
var name: String = "",
/** Position of the camera relative to the coordinate space
* defined by the corresponding node.
*
* The default value is 0|0|0.
*/
var position: AiVector3D = AiVector3D(),
/** 'Up' - vector of the camera coordinate system relative to
* the coordinate space defined by the corresponding node.
*
* The 'right' vector of the camera coordinate system is
* the cross product of the up and lookAt vectors.
* The default value is 0|1|0. The vector
* may be normalized, but it needn't.
*/
var up: AiVector3D = AiVector3D(0, 1, 0),
/** 'LookAt' - vector of the camera coordinate system relative to
* the coordinate space defined by the corresponding node.
*
* This is the viewing direction of the user.
* The default value is 0|0|1. The vector
* may be normalized, but it needn't.
*/
var lookAt: AiVector3D = AiVector3D(0, 0, 1),
/** Half horizontal field of view angle, in radians.
*
* The field of view angle is the angle between the center
* line of the screen and the left or right border.
* The default value is 1/4PI.
*/
var horizontalFOV: Float = .25f * glm.PIf,
/** Distance of the near clipping plane from the camera.
*
* The value may not be 0.f (for arithmetic reasons to prevent
* a division through zero). The default value is 0.1f.
*/
var clipPlaneNear: Float = .1f,
/** Distance of the far clipping plane from the camera.
*
* The far clipping plane must, of course, be further away than the
* near clipping plane. The default value is 1000.f. The ratio
* between the near and the far plane should not be too
* large (between 1000-10000 should be ok) to avoid floating-point
* inaccuracies which could lead to z-fighting.
*/
var clipPlaneFar: Float = 1_000f,
/** Screen aspect ratio.
*
* This is the ration between the width and the height of the
* screen. Typical values are 4/3, 1/2 or 1/1. This value is
* 0 if the aspect ratio is not defined in the source file.
* 0 is also the default value.
*/
var aspect: Float = 0f)
{
constructor(other: AiCamera) : this(other.name, AiVector3D(other.position), AiVector3D(other.up),
AiVector3D(other.lookAt), other.horizontalFOV, other.clipPlaneNear, other.clipPlaneFar, other.aspect)
/** @brief Get a *right-handed* camera matrix from me
* @param out Camera matrix to be filled
*/
fun getCameraMatrix(mat: Mat4) {
/** todo: test ... should work, but i'm not absolutely sure */
/** We don't know whether these vectors are already normalized ...*/
val zaxis = AiVector3D(lookAt)
// zaxis.Normalize(); TODO
val yaxis = AiVector3D(up)
// yaxis.Normalize();
val xaxis = AiVector3D(up) // ^ lookAt;
// xaxis.Normalize();
// mat.a3 = -(xaxis * position) // TODO
// out.b4 = -(yaxis * position);
// out.c4 = -(zaxis * position);
//
// out.a1 = xaxis.x;
// out.a2 = xaxis.y;
// out.a3 = xaxis.z;
//
// out.b1 = yaxis.x;
// out.b2 = yaxis.y;
// out.b3 = yaxis.z;
//
// out.c1 = zaxis.x;
// out.c2 = zaxis.y;
// out.c3 = zaxis.z;
//
// out.d1 = out.d2 = out.d3 = 0.f;
// out.d4 = 1.f;
}
companion object {
val size = 3 * Vec3.size + 4 * Float.BYTES
}
}
| bsd-3-clause | 78e423d69fe5878b006ee16d1c487e49 | 37.485294 | 162 | 0.626417 | 4.119098 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/cabal/psi/Name.kt | 1 | 1900 | package org.jetbrains.cabal.psi
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import org.jetbrains.cabal.psi.PropertyValue
import org.jetbrains.cabal.psi.RangedValue
import org.jetbrains.cabal.parser.CabalTokelTypes
import org.jetbrains.cabal.CabalFile
import org.jetbrains.cabal.highlight.ErrorMessage
/**
* Created by atsky on 13/12/13.
*/
class Name(node: ASTNode) : PropertyValue(node), RangedValue {
override fun getAvailableValues(): List<String> {
val parent = parent
if (isFlagNameInCondition()) {
return (containingFile as CabalFile).getFlagNames()
}
else if (parent is InvalidField) {
return (parent.getParent() as FieldContainer).getAvailableFieldNames()
}
return listOf()
}
override fun check(): List<ErrorMessage> {
if (isFlagNameInCondition()) {
if (text.toLowerCase() in (containingFile as CabalFile).getFlagNames()) return listOf()
return listOf(ErrorMessage(this, "invalid flag name", "error"))
}
if (parent is Section) {
if (node.text.matches("^\\S+$".toRegex())) return listOf()
return listOf(ErrorMessage(this, "invalid section name", "error"))
}
if (node.text.matches("^([a-zA-Z0-9]+-)*[a-zA-Z0-9]+$".toRegex())) return listOf()
return listOf(ErrorMessage(this, "invalid name", "error"))
}
fun isFlagNameInCondition(): Boolean {
val parent = parent!!
if ((parent is SimpleCondition) && (parent.getTestName() == "flag")) return true
if (parent is InvalidConditionPart) {
var prevElement = prevSibling
while (prevElement != null) {
if (prevElement.text == "flag") return true
prevElement = prevElement.prevSibling
}
}
return false
}
} | apache-2.0 | b7f971b2c8cba2f393c7f0ca6240e385 | 34.867925 | 99 | 0.633684 | 4.428904 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/util/LazyUtils.kt | 2 | 1267 | package io.github.chrislo27.rhre3.util
import kotlin.reflect.KProperty
interface SettableLazy<T> {
/**
* The value will be initialized on first-get (but NOT first-set).
*/
var value: T
fun isInitialized(): Boolean
operator fun getValue(thisRef: Any?, property: KProperty<*>): T = value
operator fun setValue(thisRef: Any?, property: KProperty<*>, newValue: T) {
if (!isInitialized()) {
value
}
value = newValue
}
}
private class SettableLazyImpl<T>(private val initBlock: () -> T) : SettableLazy<T> {
private var inited: Boolean = false
private var backing: Any? = UNINITIALIZED_SETTABLE_LAZY_VALUE
override var value: T
get() {
if (!isInitialized()) {
init()
}
@Suppress("UNCHECKED_CAST")
return (backing as T)
}
set(value) {
backing = value
inited = true
}
private fun init() {
backing = initBlock()
inited = true
}
override fun isInitialized(): Boolean {
return inited
}
}
private object UNINITIALIZED_SETTABLE_LAZY_VALUE
fun <T> settableLazy(initBlock: () -> T): SettableLazy<T> = SettableLazyImpl(initBlock) | gpl-3.0 | 0231597b8c7518b89189f6ff485a47a3 | 22.481481 | 87 | 0.584057 | 4.209302 | false | false | false | false |
spacecowboy/Feeder | app/src/main/java/com/nononsenseapps/feeder/ui/compose/navdrawer/DrawerItemWithUnreadCount.kt | 1 | 2625 | package com.nononsenseapps.feeder.ui.compose.navdrawer
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.ui.res.stringResource
import com.nononsenseapps.feeder.R
import com.nononsenseapps.feeder.db.room.ID_ALL_FEEDS
import java.net.URL
@Immutable
sealed class DrawerItemWithUnreadCount(
open val title: @Composable () -> String,
open val unreadCount: Int,
) : Comparable<DrawerItemWithUnreadCount> {
abstract val uiId: Long
override fun compareTo(other: DrawerItemWithUnreadCount): Int = when (this) {
is DrawerFeed -> {
when (other) {
is DrawerFeed -> when {
tag.equals(other.tag, ignoreCase = true) -> displayTitle.compareTo(
other.displayTitle,
ignoreCase = true
)
tag.isEmpty() -> 1
other.tag.isEmpty() -> -1
else -> tag.compareTo(other.tag, ignoreCase = true)
}
is DrawerTag -> when {
tag.isEmpty() -> 1
tag.equals(other.tag, ignoreCase = true) -> 1
else -> tag.compareTo(other.tag, ignoreCase = true)
}
is DrawerTop -> 1
}
}
is DrawerTag -> {
when (other) {
is DrawerFeed -> when {
other.tag.isEmpty() -> -1
tag.equals(other.tag, ignoreCase = true) -> -1
else -> tag.compareTo(other.tag, ignoreCase = true)
}
is DrawerTag -> tag.compareTo(other.tag, ignoreCase = true)
is DrawerTop -> 1
}
}
is DrawerTop -> -1
}
}
@Immutable
data class DrawerTop(
override val title: @Composable () -> String = { stringResource(id = R.string.all_feeds) },
override val unreadCount: Int,
val totalChildren: Int,
) : DrawerItemWithUnreadCount(title = title, unreadCount = unreadCount) {
override val uiId: Long = ID_ALL_FEEDS
}
@Immutable
data class DrawerFeed(
val id: Long,
val tag: String,
val displayTitle: String,
val imageUrl: URL? = null,
override val unreadCount: Int,
) : DrawerItemWithUnreadCount(title = { displayTitle }, unreadCount = unreadCount) {
override val uiId: Long = id
}
@Immutable
data class DrawerTag(
val tag: String,
override val unreadCount: Int,
override val uiId: Long,
val totalChildren: Int,
) : DrawerItemWithUnreadCount(title = { tag }, unreadCount = unreadCount)
| gpl-3.0 | cfb3e223ac208d7d74726800202e4c09 | 32.653846 | 95 | 0.57981 | 4.518072 | false | false | false | false |
allotria/intellij-community | plugins/ide-features-trainer/src/training/learn/lesson/general/navigation/RecentFilesLesson.kt | 1 | 7396 | // 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 training.learn.lesson.general.navigation
import com.intellij.CommonBundle
import com.intellij.ide.actions.Switcher
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.wm.IdeFrame
import com.intellij.ui.SearchTextField
import com.intellij.ui.components.JBList
import com.intellij.ui.components.fields.ExtendableTextField
import com.intellij.ui.speedSearch.SpeedSearchSupply
import com.intellij.util.ui.UIUtil
import icons.FeaturesTrainerIcons
import training.dsl.*
import training.dsl.LessonUtil.restoreIfModifiedOrMoved
import training.learn.LearnBundle
import training.learn.LessonsBundle
import training.learn.course.KLesson
import training.learn.lesson.LessonManager
import java.awt.event.KeyEvent
import javax.swing.JComponent
import kotlin.random.Random
abstract class RecentFilesLesson : KLesson("Recent Files and Locations", LessonsBundle.message("recent.files.lesson.name")) {
abstract override val existedFile: String
abstract val transitionMethodName: String
abstract val transitionFileName: String
abstract val stringForRecentFilesSearch: String // should look like transitionMethodName
abstract fun LessonContext.setInitialPosition()
private val countOfFilesToOpen: Int = 20
private val countOfFilesToDelete: Int = 5
override val lessonContent: LessonContext.() -> Unit = {
setInitialPosition()
task("GotoDeclaration") {
text(LessonsBundle.message("recent.files.first.transition", code(transitionMethodName), action(it)))
trigger(it) { virtualFile.name.startsWith(transitionFileName) }
restoreIfModifiedOrMoved()
test { actions(it) }
}
waitBeforeContinue(500)
prepareRuntimeTask {
if (!TaskTestContext.inTestMode) {
val userDecision = Messages.showOkCancelDialog(
LessonsBundle.message("recent.files.dialog.message"),
LessonsBundle.message("recent.files.dialog.title"),
CommonBundle.message("button.ok"),
LearnBundle.message("learn.stop.lesson"),
FeaturesTrainerIcons.Img.PluginIcon
)
if(userDecision != Messages.OK) {
LessonManager.instance.stopLesson()
}
}
}
openManyFiles()
actionTask("RecentFiles") {
LessonsBundle.message("recent.files.show.recent.files", action(it))
}
task("rfd") {
text(LessonsBundle.message("recent.files.search.typing", code(it)))
triggerByUiComponentAndHighlight(false, false) { ui: ExtendableTextField ->
ui.javaClass.name.contains("SpeedSearchBase\$SearchField")
}
stateCheck { checkRecentFilesSearch(it) }
restoreIfRecentFilesPopupClosed()
test {
ideFrame {
waitComponent(Switcher.SwitcherPanel::class.java)
}
type(it)
}
}
task {
text(LessonsBundle.message("recent.files.search.jump", LessonUtil.rawEnter()))
stateCheck { virtualFile.name == existedFile.substringAfterLast("/") }
restoreState {
!checkRecentFilesSearch("rfd") || previous.ui?.isShowing != true
}
test(waitEditorToBeReady = false) {
invokeActionViaShortcut("ENTER")
}
}
actionTask("RecentFiles") {
LessonsBundle.message("recent.files.use.recent.files.again", action(it))
}
var initialRecentFilesCount = -1
var curRecentFilesCount: Int
task {
text(
LessonsBundle.message("recent.files.delete", strong(countOfFilesToDelete.toString()), LessonUtil.rawKeyStroke(KeyEvent.VK_DELETE)))
stateCheck {
val focusOwner = focusOwner as? JBList<*> ?: return@stateCheck false
if (initialRecentFilesCount == -1) {
initialRecentFilesCount = focusOwner.itemsCount
}
curRecentFilesCount = focusOwner.itemsCount
initialRecentFilesCount - curRecentFilesCount >= countOfFilesToDelete
}
restoreIfRecentFilesPopupClosed()
test {
repeat(countOfFilesToDelete) {
invokeActionViaShortcut("DELETE")
}
}
}
task {
text(LessonsBundle.message("recent.files.close.popup", LessonUtil.rawKeyStroke(KeyEvent.VK_ESCAPE)))
stateCheck { focusOwner is IdeFrame }
test { invokeActionViaShortcut("ESCAPE") }
}
actionTask("RecentLocations") {
LessonsBundle.message("recent.files.show.recent.locations", action(it))
}
task(stringForRecentFilesSearch) {
text(LessonsBundle.message("recent.files.locations.search.typing", code(it)))
stateCheck { checkRecentLocationsSearch(it) }
triggerByUiComponentAndHighlight(false, false) { _: SearchTextField -> true } // needed in next task to restore if search field closed
restoreIfRecentFilesPopupClosed()
test {
ideFrame {
waitComponent(JBList::class.java)
}
type(it)
}
}
task {
text(LessonsBundle.message("recent.files.locations.search.jump", LessonUtil.rawEnter()))
triggerByListItemAndHighlight { item ->
item.toString().contains(transitionFileName)
}
stateCheck { virtualFile.name.contains(transitionFileName) }
restoreState {
!checkRecentLocationsSearch(stringForRecentFilesSearch) || previous.ui?.isShowing != true
}
test { invokeActionViaShortcut("ENTER") }
}
}
// Should open (countOfFilesToOpen - 1) files
open fun LessonContext.openManyFiles() {
val openedFiles = mutableSetOf<String>()
val random = Random(System.currentTimeMillis())
for (i in 0 until (countOfFilesToOpen - 1)) {
waitBeforeContinue(200)
prepareRuntimeTask {
val curFile = virtualFile
val files = curFile.parent?.children
?: throw IllegalStateException("Not found neighbour files for ${curFile.name}")
var index = random.nextInt(0, files.size)
while (openedFiles.contains(files[index].name)) {
index = random.nextInt(0, files.size)
}
val nextFile = files[index]
openedFiles.add(nextFile.name)
invokeLater {
FileEditorManager.getInstance(project).openFile(nextFile, true)
}
}
}
}
private fun TaskRuntimeContext.checkRecentFilesSearch(expected: String): Boolean {
val focusOwner = UIUtil.getParentOfType(Switcher.SwitcherPanel::class.java, focusOwner)
return focusOwner != null && checkWordInSearch(expected, focusOwner)
}
private fun TaskRuntimeContext.checkRecentLocationsSearch(expected: String): Boolean {
val focusOwner = focusOwner
return focusOwner is JBList<*> && checkWordInSearch(expected, focusOwner)
}
private fun checkWordInSearch(expected: String, component: JComponent): Boolean {
val supply = SpeedSearchSupply.getSupply(component)
val enteredPrefix = supply?.enteredPrefix ?: return false
return enteredPrefix.equals(expected, ignoreCase = true)
}
private fun TaskContext.restoreIfRecentFilesPopupClosed() {
restoreState(delayMillis = defaultRestoreDelay) { focusOwner !is JBList<*> }
}
override val testScriptProperties: TaskTestContext.TestScriptProperties
get() = TaskTestContext.TestScriptProperties(duration = 20)
} | apache-2.0 | 6cfaeb00e4e0d7a2f25e97fc4ca4c864 | 35.438424 | 140 | 0.708761 | 4.86259 | false | true | false | false |
LivingDoc/livingdoc | livingdoc-tests/src/test/kotlin/org/livingdoc/example/SlowCalculatorDocumentMd.kt | 2 | 4629 | package org.livingdoc.example
import org.assertj.core.api.Assertions.assertThat
import org.livingdoc.api.Before
import org.livingdoc.api.documents.ExecutableDocument
import org.livingdoc.api.fixtures.decisiontables.BeforeRow
import org.livingdoc.api.fixtures.decisiontables.Check
import org.livingdoc.api.fixtures.decisiontables.DecisionTableFixture
import org.livingdoc.api.fixtures.decisiontables.Input
import org.livingdoc.api.fixtures.scenarios.Binding
import org.livingdoc.api.fixtures.scenarios.ScenarioFixture
import org.livingdoc.api.fixtures.scenarios.Step
import org.livingdoc.api.tagging.Tag
/**
* [ExecutableDocuments][ExecutableDocument] can also be specified in Markdown
*
* @see ExecutableDocument
*/
@Tag("slow")
@ExecutableDocument("local://Calculator.md")
class SlowCalculatorDocumentMd {
@DecisionTableFixture(parallel = true)
class CalculatorDecisionTableFixture {
private lateinit var sut: Calculator
@Input("a")
private var valueA: Float = 0f
private var valueB: Float = 0f
@BeforeRow
fun beforeRow() {
sut = Calculator()
}
@Input("b")
fun setValueB(valueB: Float) {
this.valueB = valueB
}
@Check("a + b = ?")
fun checkSum(expectedValue: Float) {
val result = sut.sum(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
@Check("a - b = ?")
fun checkDiff(expectedValue: Float) {
val result = sut.diff(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
@Check("a * b = ?")
fun checkMultiply(expectedValue: Float) {
val result = sut.multiply(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
@Check("a / b = ?")
fun checkDivide(expectedValue: Float) {
val result = sut.divide(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
}
@ScenarioFixture
class CalculatorScenarioFixture {
private lateinit var sut: Calculator
@Before
fun before() {
sut = Calculator()
}
@Step("adding {a} and {b} equals {c}")
fun add(
@Binding("a") a: Float,
@Binding("b") b: Float,
@Binding("c") c: Float
) {
val result = sut.sum(a, b)
assertThat(result).isEqualTo(c)
}
@Step("adding {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa} and {bb} and {cc} and {dd} and {ee} and {ff} and {gg} equals {hh}")
fun addMultiple(
@Binding("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") a: Float,
@Binding("bb") b: Float,
@Binding("cc") c: Float,
@Binding("dd") d: Float,
@Binding("ee") e: Float,
@Binding("ff") f: Float,
@Binding("gg") g: Float,
@Binding("hh") h: Float
) {
assertThat(a + b + c + d + e + f + g).isEqualTo(h)
}
@Step("subtraction {b} form {a} equals {c}")
fun subtract(
@Binding("a") a: Float,
@Binding("b") b: Float,
@Binding("c") c: Float
) {
val result = sut.diff(a, b)
assertThat(result).isEqualTo(c)
}
@Step("multiplying {a} and {b} equals {c}")
fun multiply(
@Binding("a") a: Float,
@Binding("b") b: Float,
@Binding("c") c: Float
) {
val result = sut.multiply(a, b)
assertThat(result).isEqualTo(c)
}
@Step("dividing {a} by {b} equals {c}")
fun divide(
@Binding("a") a: Float,
@Binding("b") b: Float,
@Binding("c") c: Float
) {
val result = sut.divide(a, b)
assertThat(result).isEqualTo(c)
}
@Step("add {a} to itself and you get {b}")
fun selfadd(
@Binding("a") a: Float,
@Binding("b") b: Float
) {
val result = sut.sum(a, a)
assertThat(result).isEqualTo(b)
}
}
@ScenarioFixture
class CalculatorScenarioFixture2 {
private lateinit var sut: Calculator
@Before
fun before() {
sut = Calculator()
}
@Step("adding {a} and {b} equals {c}")
fun add(
@Binding("a") a: Float,
@Binding("b") b: Float,
@Binding("c") c: Float
) {
val result = sut.sum(a, b)
assertThat(result).isEqualTo(c)
}
}
}
| apache-2.0 | c1da802ab13343f7c2c0d2c9cc4dd124 | 27.574074 | 122 | 0.54353 | 4.18914 | false | false | false | false |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/FrameHeader.kt | 1 | 3730 | // 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.openapi.wm.impl.customFrameDecorations.header
import com.intellij.icons.AllIcons
import com.intellij.openapi.wm.impl.customFrameDecorations.CustomFrameTitleButtons
import com.intellij.openapi.wm.impl.customFrameDecorations.ResizableCustomFrameTitleButtons
import com.intellij.ui.awt.RelativeRectangle
import com.intellij.ui.scale.ScaleContext
import com.intellij.util.ui.ImageUtil
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.JBImageIcon
import java.awt.Font
import java.awt.Frame
import java.awt.Toolkit
import java.awt.event.WindowAdapter
import java.awt.event.WindowStateListener
import java.util.*
import javax.swing.*
open class FrameHeader(val frame: JFrame) : CustomHeader(frame) {
private val myIconifyAction: Action = CustomFrameAction("Minimize", AllIcons.Windows.MinimizeSmall) { iconify() }
private val myRestoreAction: Action = CustomFrameAction("Restore", AllIcons.Windows.RestoreSmall) { restore() }
private val myMaximizeAction: Action = CustomFrameAction("Maximize", AllIcons.Windows.MaximizeSmall) { maximize() }
private var windowStateListener: WindowStateListener
protected var myState = 0
init {
windowStateListener = object : WindowAdapter() {
override fun windowStateChanged(e: java.awt.event.WindowEvent?) {
updateActions()
}
}
}
override fun createButtonsPane(): CustomFrameTitleButtons = ResizableCustomFrameTitleButtons.create(myCloseAction,
myRestoreAction, myIconifyAction, myMaximizeAction)
override fun windowStateChanged() {
super.windowStateChanged()
updateActions()
}
private fun iconify() {
frame.extendedState = myState or Frame.ICONIFIED
}
private fun maximize() {
frame.extendedState = myState or Frame.MAXIMIZED_BOTH
}
private fun restore() {
if (myState and Frame.ICONIFIED != 0) {
frame.extendedState = myState and Frame.ICONIFIED.inv()
} else {
frame.extendedState = myState and Frame.MAXIMIZED_BOTH.inv()
}
}
override fun addNotify() {
super.addNotify()
updateActions()
}
private fun updateActions() {
myState = frame.extendedState
if (frame.isResizable) {
if (myState and Frame.MAXIMIZED_BOTH != 0) {
myMaximizeAction.isEnabled = false
myRestoreAction.isEnabled = true
} else {
myMaximizeAction.isEnabled = true
myRestoreAction.isEnabled = false
}
} else {
myMaximizeAction.isEnabled = false
myRestoreAction.isEnabled = false
}
myIconifyAction.isEnabled = true
myCloseAction.isEnabled = true
buttonPanes.updateVisibility()
updateCustomDecorationHitTestSpots()
}
override fun addMenuItems(menu: JPopupMenu) {
menu.add(myRestoreAction)
menu.add(myIconifyAction)
if (Toolkit.getDefaultToolkit().isFrameStateSupported(Frame.MAXIMIZED_BOTH)) {
menu.add(myMaximizeAction)
}
menu.add(JSeparator())
val closeMenuItem = menu.add(myCloseAction)
closeMenuItem.font = JBFont.label().deriveFont(Font.BOLD)
}
override fun getHitTestSpots(): ArrayList<RelativeRectangle> {
val hitTestSpots = ArrayList<RelativeRectangle>()
hitTestSpots.add(RelativeRectangle(productIcon))
hitTestSpots.add(RelativeRectangle(buttonPanes.getView()))
return hitTestSpots
}
} | apache-2.0 | 49b67463a5a3e317e4595f0cc0f2928b | 33.869159 | 140 | 0.68874 | 4.769821 | false | true | false | false |
leafclick/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/dgm/DGMFileType.kt | 1 | 1478 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.dgm
import com.intellij.lang.properties.PropertiesFileType
import com.intellij.lang.properties.PropertiesLanguage
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.fileTypes.ex.FileTypeIdentifiableByVirtualFile
import com.intellij.openapi.util.Comparing
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.plugins.groovy.dgm.DGMUtil.ORG_CODEHAUS_GROOVY_RUNTIME_EXTENSION_MODULE
import javax.swing.Icon
object DGMFileType : LanguageFileType(PropertiesLanguage.INSTANCE, true), FileTypeIdentifiableByVirtualFile {
override fun getName(): String = "DGM"
override fun getDefaultExtension(): String = ""
override fun getDescription(): String = "Groovy extension module descriptor file"
override fun getIcon(): Icon? = PropertiesFileType.INSTANCE.icon
override fun isMyFileType(file: VirtualFile): Boolean {
if (!Comparing.equal(ORG_CODEHAUS_GROOVY_RUNTIME_EXTENSION_MODULE, file.nameSequence)) {
return false
}
val parent = file.parent ?: return false
val parentName = parent.nameSequence
if (!Comparing.equal("services", parentName) && !Comparing.equal("groovy", parentName)) {
return false
}
val gParent = parent.parent ?: return false
return Comparing.equal("META-INF", gParent.nameSequence)
}
}
| apache-2.0 | 5b6dd21978984923e559ee067154a336 | 45.1875 | 140 | 0.779432 | 4.296512 | false | false | false | false |
leafclick/intellij-community | platform/workspaceModel-ide/src/com/intellij/workspace/legacyBridge/intellij/LegacyBridgeProjectLifecycleListener.kt | 1 | 3386 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspace.legacyBridge.intellij
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectServiceContainerCustomizer
import com.intellij.openapi.project.impl.ProjectImpl
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.roots.impl.ModifiableModelCommitterService
import com.intellij.openapi.roots.impl.libraries.ProjectLibraryTable
import com.intellij.openapi.util.registry.Registry
import com.intellij.serviceContainer.PlatformComponentManagerImpl
import com.intellij.workspace.ide.WorkspaceModel
import com.intellij.workspace.ide.WorkspaceModelImpl
import com.intellij.workspace.ide.WorkspaceModelInitialTestContent
import com.intellij.workspace.jps.JpsProjectModelSynchronizer
import com.intellij.workspace.legacyBridge.libraries.libraries.LegacyBridgeProjectLibraryTableImpl
import com.intellij.workspace.legacyBridge.libraries.libraries.LegacyBridgeRootsWatcher
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
class LegacyBridgeProjectLifecycleListener : ProjectServiceContainerCustomizer {
companion object {
const val ENABLED_REGISTRY_KEY = "ide.new.project.model"
private val LOG = logger<LegacyBridgeProjectLifecycleListener>()
fun enabled(project: Project) = ModuleManager.getInstance(project) is LegacyBridgeModuleManagerComponent
}
override fun serviceRegistered(project: Project) {
val enabled = Registry.`is`(ENABLED_REGISTRY_KEY) || WorkspaceModelInitialTestContent.peek() != null
if (!enabled) {
LOG.info("Using legacy project model to open project")
return
}
LOG.info("Using workspace model to open project")
val pluginDescriptor = PluginManagerCore.getPlugin(PluginManagerCore.CORE_ID)
?: error("Could not find plugin by id: ${PluginManagerCore.CORE_ID}")
val container = project as PlatformComponentManagerImpl
(project as ProjectImpl).setProjectStoreFactory(LegacyBridgeProjectStoreFactory())
container.registerComponent(JpsProjectModelSynchronizer::class.java, JpsProjectModelSynchronizer::class.java, pluginDescriptor, false)
container.registerComponent(LegacyBridgeRootsWatcher::class.java, LegacyBridgeRootsWatcher::class.java, pluginDescriptor, false)
container.registerComponent(ModuleManager::class.java, LegacyBridgeModuleManagerComponent::class.java, pluginDescriptor, true)
container.registerComponent(ProjectRootManager::class.java, LegacyBridgeProjectRootManager::class.java, pluginDescriptor, true)
container.registerService(LegacyBridgeFilePointerProvider::class.java, LegacyBridgeFilePointerProviderImpl::class.java, pluginDescriptor, false)
container.registerService(WorkspaceModel::class.java, WorkspaceModelImpl::class.java, pluginDescriptor, false)
container.registerService(ProjectLibraryTable::class.java, LegacyBridgeProjectLibraryTableImpl::class.java, pluginDescriptor, true)
container.registerService(ModifiableModelCommitterService::class.java, LegacyBridgeModifiableModelCommitterService::class.java, pluginDescriptor, true)
}
} | apache-2.0 | 69cdf11bcfa8364d031feb84ec2720e8 | 57.396552 | 155 | 0.829002 | 5.107089 | false | false | false | false |
intellij-purescript/intellij-purescript | src/main/kotlin/org/purescript/psi/newtype/PSNewTypeConstructor.kt | 1 | 1264 | package org.purescript.psi.newtype
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameIdentifierOwner
import org.purescript.psi.name.PSProperName
import org.purescript.psi.PSPsiElement
import org.purescript.psi.PSTypeAtom
import org.purescript.psi.data.PSDataConstructor
/**
* A constructor in a newtype declaration, e.g.
*
* ```
* CatQueue (List a) (List a)
* ```
* in
* ```
* newtype CatQueue a = CatQueue (List a) (List a)
* ```
*/
class PSNewTypeConstructor(node: ASTNode) :
PSPsiElement(node),
PsiNameIdentifierOwner {
/**
* @return the [PSProperName] identifying this constructor
*/
internal val identifier: PSProperName
get() = findNotNullChildByClass(PSProperName::class.java)
/**
* In contrast to [PSDataConstructor], a valid [PSNewTypeConstructor]
* must contain one single type atom.
*
* @return the [PSTypeAtom] element in this constructor.
*/
internal val typeAtom: PSTypeAtom
get() = findNotNullChildByClass(PSTypeAtom::class.java)
override fun setName(name: String): PsiElement? = null
override fun getNameIdentifier(): PSProperName = identifier
override fun getName(): String = identifier.name
}
| bsd-3-clause | 4398c339ecebf52f0500e4dd0b834d02 | 26.478261 | 73 | 0.709652 | 4.199336 | false | false | false | false |
leafclick/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/CommitProjectPanelAdapter.kt | 1 | 2834 | // 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.vcs.commit
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComponentContainer
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.InvokeAfterUpdateMode
import com.intellij.openapi.vfs.VirtualFile
import java.io.File
import javax.swing.JComponent
internal open class CommitProjectPanelAdapter(private val handler: AbstractCommitWorkflowHandler<*, *>) : CheckinProjectPanel {
private val workflow get() = handler.workflow
private val ui get() = handler.ui
private val vcsManager get() = ProjectLevelVcsManager.getInstance(workflow.project)
override fun getCommitWorkflowHandler(): CommitWorkflowHandler = handler
override fun getProject(): Project = workflow.project
// NOTE: Seems it is better to remove getComponent()/getPreferredFocusedComponent() usages. And provide more specific methods instead.
// So corresponding methods are not added to workflow ui interface explicitly.
override fun getComponent(): JComponent? = (ui as? ComponentContainer)?.component
override fun getPreferredFocusedComponent(): JComponent? = (ui as? ComponentContainer)?.preferredFocusableComponent
override fun hasDiffs(): Boolean = !handler.isCommitEmpty()
override fun getVirtualFiles(): Collection<VirtualFile> = ui.getIncludedPaths().mapNotNull { it.virtualFile }
override fun getSelectedChanges(): Collection<Change> = ui.getIncludedChanges()
override fun getFiles(): Collection<File> = ui.getIncludedPaths().map { it.ioFile }
override fun getRoots(): Collection<VirtualFile> = ui.getDisplayedPaths().mapNotNullTo(hashSetOf()) { vcsManager.getVcsRootFor(it) }
override fun vcsIsAffected(name: String): Boolean = vcsManager.checkVcsIsActive(name) && workflow.vcses.any { it.name == name }
override fun getCommitActionName(): String = ui.defaultCommitActionName
override fun getCommitMessage(): String = ui.commitMessageUi.text
override fun setCommitMessage(currentDescription: String?) {
ui.commitMessageUi.setText(currentDescription)
ui.commitMessageUi.focus()
}
override fun refresh() =
ChangeListManager.getInstance(workflow.project).invokeAfterUpdate(
{
ui.refreshData()
workflow.commitOptions.refresh()
},
InvokeAfterUpdateMode.SILENT, null, ModalityState.current()
)
override fun saveState() = workflow.commitOptions.saveState()
override fun restoreState() = workflow.commitOptions.restoreState()
} | apache-2.0 | b59561f0da1bd35e25230d95470cdce7 | 49.625 | 140 | 0.788285 | 4.85274 | false | false | false | false |
rizafu/CoachMark | app/src/main/java/com/rizafu/sample/CustomFragment.kt | 1 | 5225 | package com.rizafu.sample
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.design.widget.BaseTransientBottomBar
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.rizafu.coachmark.CoachMark
import com.rizafu.sample.databinding.RecyclerLayoutBinding
/**
* Created by RizaFu on 2/27/17.
*/
class CustomFragment : Fragment() {
private lateinit var binding: RecyclerLayoutBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.recycler_layout, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val adapter = CustomAdapter()
adapter.addItem("Simple Coach Mark 1", "no tooltip, click target for dismiss")
adapter.addItem("Simple Coach Mark 2", "no tooltip, dismissible")
adapter.addItem("Simple Coach Mark 3", "no tooltip, with target custom click listener")
adapter.addItem("Coach Mark 1", "simple tooltip message at alignment bottom")
adapter.addItem("Coach Mark 2", "simple tooltip message at alignment top")
adapter.addItem("Coach Mark 3", "simple tooltip pointer at alignment left")
adapter.addItem("Coach Mark 4", "simple tooltip pointer at alignment right")
adapter.addItem("Coach Mark 5", "simple tooltip no pointer")
val gridLayoutManager = GridLayoutManager(context, 3, LinearLayoutManager.VERTICAL, false)
binding.recyclerView.layoutManager = gridLayoutManager
binding.recyclerView.setHasFixedSize(true)
binding.recyclerView.adapter = adapter
adapter.setOnItemClick({ v: View, p: Int -> onClick(v,p) })
}
private fun onClick(view: View, position: Int) {
activity?.let {
when (position) {
0 -> CoachMark.Builder(it)
.setTarget(view)
.show()
1 -> CoachMark.Builder(it)
.setTarget(view)
.setDismissible()
.show()
2 -> CoachMark.Builder(it)
.setTarget(view)
.setOnClickTarget { coachMark ->
coachMark.dismiss()
Snackbar.make(view.rootView, "Action click on target mark", BaseTransientBottomBar.LENGTH_LONG).show()
}
.show()
3 -> CoachMark.Builder(it)
.setTarget(view)
.addTooltipChildText(it, "this is message tooltip", android.R.color.primary_text_dark)
.setTooltipAlignment(CoachMark.TARGET_BOTTOM)
.setTooltipBackgroundColor(R.color.colorPrimary)
.show()
4 -> CoachMark.Builder(it)
.setTarget(view)
.addTooltipChildText(it, "this is message tooltip", android.R.color.primary_text_light)
.setTooltipAlignment(CoachMark.TARGET_TOP)
.setTooltipBackgroundColor(R.color.colorAccent)
.show()
5 -> CoachMark.Builder(it)
.setTarget(view)
.addTooltipChildText(it, "this is message tooltip", android.R.color.primary_text_light)
.setTooltipAlignment(CoachMark.TARGET_TOP)
.setTooltipPointer(CoachMark.POINTER_LEFT)
.setTooltipMatchWidth()
.setTooltipBackgroundColor(R.color.colorAccent)
.show()
6 -> CoachMark.Builder(it)
.setTarget(view)
.addTooltipChildText(it, "this is message tooltip", android.R.color.primary_text_light)
.setTooltipAlignment(CoachMark.TARGET_TOP_RIGHT)
.setTooltipPointer(CoachMark.POINTER_RIGHT)
.setTooltipBackgroundColor(R.color.colorAccent)
.show()
7 -> CoachMark.Builder(it)
.setTarget(view)
.addTooltipChildText(it, "this is message tooltip", android.R.color.primary_text_light)
.setTooltipAlignment(CoachMark.TARGET_TOP)
.setTooltipPointer(CoachMark.POINTER_GONE)
.setBackgroundColor(R.color.colorPrimaryDark)
.show()
else -> { }
}
}
}
companion object {
fun newInstance(): CustomFragment {
val args = Bundle()
val fragment = CustomFragment()
fragment.arguments = args
return fragment
}
}
}
| apache-2.0 | 065f20cffabe3f5477d2b0f9213bfee9 | 43.279661 | 130 | 0.582775 | 4.990449 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/super/unqualifiedSuperWithMethodsOfAny.kt | 2 | 543 | interface ISomething
open class ClassWithToString {
override fun toString(): String = "C"
}
interface IWithToString {
override fun toString(): String
}
class C1 : ClassWithToString(), ISomething {
override fun toString(): String = super.toString()
}
class C2 : ClassWithToString(), IWithToString, ISomething {
override fun toString(): String = super.toString()
}
fun box(): String {
return when {
C1().toString() != "C" -> "Failed #1"
C2().toString() != "C" -> "Failed #2"
else -> "OK"
}
} | apache-2.0 | 6035ce3deabea387739a36cd2297964b | 20.76 | 60 | 0.624309 | 3.744828 | false | false | false | false |
AndroidX/androidx | compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/node/DepthSortedSet.kt | 3 | 3530 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.node
/**
* The set of [LayoutNode]s which orders items by their [LayoutNode.depth] and
* allows modifications(additions and removals) while we iterate through it via [popEach].
* While [LayoutNode] is added to the set it should always be:
* 1) attached [LayoutNode.isAttached] == true
* 2) maintaining the same [LayoutNode.depth]
* as any of this modifications can break the comparator's contract which can cause
* to not find the item in the tree set, which we previously added.
*/
internal class DepthSortedSet(
private val extraAssertions: Boolean = true
) {
// stores the depth used when the node was added into the set so we can assert it wasn't
// changed since then. we need to enforce this as changing the depth can break the contract
// used in comparator for building the tree in TreeSet.
// Created and used only when extraAssertions == true
private val mapOfOriginalDepth by lazy(LazyThreadSafetyMode.NONE) {
mutableMapOf<LayoutNode, Int>()
}
private val DepthComparator: Comparator<LayoutNode> = object : Comparator<LayoutNode> {
override fun compare(l1: LayoutNode, l2: LayoutNode): Int {
val depthDiff = l1.depth.compareTo(l2.depth)
if (depthDiff != 0) {
return depthDiff
}
return l1.hashCode().compareTo(l2.hashCode())
}
}
private val set = TreeSet(DepthComparator)
fun contains(node: LayoutNode): Boolean {
val contains = set.contains(node)
if (extraAssertions) {
check(contains == mapOfOriginalDepth.containsKey(node))
}
return contains
}
fun add(node: LayoutNode) {
check(node.isAttached)
if (extraAssertions) {
val usedDepth = mapOfOriginalDepth[node]
if (usedDepth == null) {
mapOfOriginalDepth[node] = node.depth
} else {
check(usedDepth == node.depth)
}
}
set.add(node)
}
fun remove(node: LayoutNode): Boolean {
check(node.isAttached)
val contains = set.remove(node)
if (extraAssertions) {
val usedDepth = mapOfOriginalDepth.remove(node)
if (contains) {
check(usedDepth == node.depth)
} else {
check(usedDepth == null)
}
}
return contains
}
fun pop(): LayoutNode {
val node = set.first()
remove(node)
return node
}
inline fun popEach(crossinline block: (LayoutNode) -> Unit) {
while (isNotEmpty()) {
val node = pop()
block(node)
}
}
fun isEmpty(): Boolean = set.isEmpty()
@Suppress("NOTHING_TO_INLINE")
inline fun isNotEmpty(): Boolean = !isEmpty()
override fun toString(): String {
return set.toString()
}
}
| apache-2.0 | 6be0687b87760c8f673b6b504ee2c490 | 32.619048 | 95 | 0.630595 | 4.462705 | false | false | false | false |
WillowChat/Kale | src/main/kotlin/chat/willow/kale/irc/message/rfc1459/PartMessage.kt | 2 | 2672 | package chat.willow.kale.irc.message.rfc1459
import chat.willow.kale.core.ICommand
import chat.willow.kale.core.message.*
import chat.willow.kale.irc.CharacterCodes
import chat.willow.kale.irc.prefix.Prefix
import chat.willow.kale.irc.prefix.PrefixParser
import chat.willow.kale.irc.prefix.PrefixSerialiser
object PartMessage : ICommand {
override val command = "PART"
data class Command(val channels: List<String>) {
object Descriptor : KaleDescriptor<Command>(matcher = commandMatcher(command), parser = Parser)
object Parser : MessageParser<Command>() {
override fun parseFromComponents(components: IrcMessageComponents): Command? {
if (components.parameters.isEmpty()) {
return null
}
val unsplitChannels = components.parameters[0]
val channels = unsplitChannels.split(delimiters = CharacterCodes.COMMA)
return Command(channels)
}
}
object Serialiser : MessageSerialiser<Command>(command) {
override fun serialiseToComponents(message: Command): IrcMessageComponents {
val channels = message.channels.joinToString(separator = CharacterCodes.COMMA.toString())
return IrcMessageComponents(parameters = listOf(channels))
}
}
}
data class Message(val source: Prefix, val channels: List<String>) {
object Descriptor : KaleDescriptor<Message>(matcher = commandMatcher(command), parser = Parser)
object Parser : MessageParser<Message>() {
override fun parseFromComponents(components: IrcMessageComponents): Message? {
if (components.parameters.isEmpty() || components.prefix == null) {
return null
}
val source = PrefixParser.parse(components.prefix ?: "") ?: return null
val unsplitChannels = components.parameters[0]
val channels = unsplitChannels.split(delimiters = CharacterCodes.COMMA)
return Message(source, channels)
}
}
object Serialiser : MessageSerialiser<Message>(command) {
override fun serialiseToComponents(message: Message): IrcMessageComponents {
val prefix = PrefixSerialiser.serialise(message.source)
val channels = message.channels.joinToString(separator = CharacterCodes.COMMA.toString())
return IrcMessageComponents(prefix = prefix, parameters = listOf(channels))
}
}
}
} | isc | 109470bcc22d4b3f275e3ec132385b2b | 33.269231 | 105 | 0.627246 | 5.453061 | false | false | false | false |
devjn/GithubSearch | ios/src/main/kotlin/com/github/devjn/githubsearch/db/SQLiteStatement.kt | 1 | 3932 | package com.github.devjn.githubsearch.db
import org.moe.natj.general.ptr.Ptr
import org.moe.natj.general.ptr.VoidPtr
import org.moe.natj.general.ptr.impl.PtrFactory
import org.sqlite.c.Globals
class SQLiteStatement(val statement: String?, bindArgs: Array<Any?>?) {
private val bindArgs: Array<Any?>
internal var stmtHandle:
VoidPtr? = null
private set
internal var dbHandle:
VoidPtr? = null
private set
internal var lastError:
String? = null
private set
var affectedCount = 0
private set
var lastInsertedID: Long = -1
private set
init {
if (statement == null) {
throw NullPointerException()
}
this.bindArgs = bindArgs ?: arrayOfNulls<Any>(0)
}
fun prepare(dbHandle: VoidPtr?): Boolean {
if (dbHandle == null) {
throw NullPointerException()
}
this.dbHandle = dbHandle
@SuppressWarnings("unchecked")
val stmtRef = PtrFactory.newPointerPtr(Void::class.java, 2, 1, true, false) as Ptr<VoidPtr>
var err = Globals.sqlite3_prepare_v2(dbHandle, statement, -1, stmtRef,
null)
if (err != 0) {
lastError = Globals.sqlite3_errmsg(dbHandle)
return false
}
stmtHandle = stmtRef.get()
var idx = 0
for (bind in bindArgs) {
idx++
if (bind is String) {
err = Globals.sqlite3_bind_text(stmtHandle, idx, bind as String?, -1, object : Globals.Function_sqlite3_bind_text {
override fun call_sqlite3_bind_text(arg0: VoidPtr) {
}
})
} else if (bind is Int) {
err = Globals.sqlite3_bind_int(stmtHandle, idx, bind)
} else if (bind is Long) {
err = Globals.sqlite3_bind_int64(stmtHandle, idx, bind)
} else if (bind is Double) {
err = Globals.sqlite3_bind_double(stmtHandle, idx, bind)
} else if (bind == null) {
err = Globals.sqlite3_bind_null(stmtHandle, idx)
} else {
lastError = "No implemented SQLite3 bind function found for " + bind.javaClass.name
return false
}
if (err != 0) {
lastError = Globals.sqlite3_errmsg(dbHandle)
return false
}
}
return true
}
fun exec(): Boolean {
if (stmtHandle == null) {
throw RuntimeException("statement handle is closed")
}
val err = Globals.sqlite3_step(stmtHandle)
if (err == 101 /* SQLITE_DONE */) {
affectedCount = Globals.sqlite3_changes(dbHandle)
lastInsertedID = Globals.sqlite3_last_insert_rowid(dbHandle)
}
close()
if (err != 101 /* SQLITE_DONE */) {
lastError = Globals.sqlite3_errmsg(dbHandle)
return false
}
return true
}
fun query(): SQLiteCursor {
return SQLiteCursor(this)
}
private fun close() {
if (stmtHandle != null) {
Globals.sqlite3_finalize(stmtHandle)
stmtHandle = null
}
}
internal fun step(): Boolean {
if (stmtHandle == null) {
throw RuntimeException("statement handle is closed")
}
val err = Globals.sqlite3_step(stmtHandle)
if (err != 100 /* SQLITE_ROW */) {
lastError = Globals.sqlite3_errmsg(dbHandle)
return false
}
return true
}
internal fun reset() {
if (stmtHandle == null) {
throw RuntimeException("statement handle is closed")
}
Globals.sqlite3_reset(stmtHandle)
}
} | apache-2.0 | f0f7e52dd2949d5e3ff322e3f7962b11 | 28.261538 | 131 | 0.527976 | 4.335171 | false | false | false | false |
kdvolder/spring-boot | spring-boot-project/spring-boot-test/src/test/kotlin/org/springframework/boot/test/web/client/TestRestTemplateExtensionsTests.kt | 1 | 9033 | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 org.springframework.boot.test.web.client
import io.mockk.mockk
import io.mockk.verify
import org.junit.Assert
import org.junit.Test
import org.springframework.core.ParameterizedTypeReference
import org.springframework.http.HttpEntity
import org.springframework.http.HttpMethod
import org.springframework.http.RequestEntity
import org.springframework.util.ReflectionUtils
import org.springframework.web.client.RestOperations
import java.net.URI
import kotlin.reflect.full.createType
import kotlin.reflect.jvm.kotlinFunction
/**
* Mock object based tests for [TestRestTemplate] Kotlin extensions
*
* @author Sebastien Deleuze
*/
class TestRestTemplateExtensionsTests {
val template = mockk<TestRestTemplate>(relaxed = true)
@Test
fun `getForObject with reified type parameters, String and varargs`() {
val url = "https://spring.io"
val var1 = "var1"
val var2 = "var2"
template.getForObject<Foo>(url, var1, var2)
template.restTemplate
verify(exactly = 1) { template.getForObject(url, Foo::class.java, var1, var2) }
}
@Test
fun `getForObject with reified type parameters, String and Map`() {
val url = "https://spring.io"
val vars = mapOf(Pair("key1", "value1"), Pair("key2", "value2"))
template.getForObject<Foo>(url, vars)
verify(exactly = 1) { template.getForObject(url, Foo::class.java, vars) }
}
@Test
fun `getForObject with reified type parameters and URI`() {
val url = URI("https://spring.io")
template.getForObject<Foo>(url)
verify(exactly = 1) { template.getForObject(url, Foo::class.java) }
}
@Test
fun `getForEntity with reified type parameters and URI`() {
val url = URI("https://spring.io")
template.getForEntity<Foo>(url)
verify(exactly = 1) { template.getForEntity(url, Foo::class.java) }
}
@Test
fun `getForEntity with reified type parameters, String and varargs`() {
val url = "https://spring.io"
val var1 = "var1"
val var2 = "var2"
template.getForEntity<Foo>(url, var1, var2)
verify(exactly = 1) { template.getForEntity(url, Foo::class.java, var1, var2) }
}
@Test
fun `getForEntity with reified type parameters, String and Map`() {
val url = "https://spring.io"
val vars = mapOf(Pair("key1", "value1"), Pair("key2", "value2"))
template.getForEntity<Foo>(url, vars)
verify(exactly = 1) { template.getForEntity(url, Foo::class.java, vars) }
}
@Test
fun `patchForObject with reified type parameters, String, Any and varargs`() {
val url = "https://spring.io"
val body: Any = "body"
val var1 = "var1"
val var2 = "var2"
template.patchForObject<Foo>(url, body, var1, var2)
verify(exactly = 1) { template.patchForObject(url, body, Foo::class.java, var1, var2) }
}
@Test
fun `patchForObject with reified type parameters, String, Any and Map`() {
val url = "https://spring.io"
val body: Any = "body"
val vars = mapOf(Pair("key1", "value1"), Pair("key2", "value2"))
template.patchForObject<Foo>(url, body, vars)
verify(exactly = 1) { template.patchForObject(url, body, Foo::class.java, vars) }
}
@Test
fun `patchForObject with reified type parameters, String and Any`() {
val url = "https://spring.io"
val body: Any = "body"
template.patchForObject<Foo>(url, body)
verify(exactly = 1) { template.patchForObject(url, body, Foo::class.java) }
}
@Test
fun `patchForObject with reified type parameters`() {
val url = "https://spring.io"
template.patchForObject<Foo>(url)
verify(exactly = 1) { template.patchForObject(url, null, Foo::class.java) }
}
@Test
fun `postForObject with reified type parameters, String, Any and varargs`() {
val url = "https://spring.io"
val body: Any = "body"
val var1 = "var1"
val var2 = "var2"
template.postForObject<Foo>(url, body, var1, var2)
verify(exactly = 1) { template.postForObject(url, body, Foo::class.java, var1, var2) }
}
@Test
fun `postForObject with reified type parameters, String, Any and Map`() {
val url = "https://spring.io"
val body: Any = "body"
val vars = mapOf(Pair("key1", "value1"), Pair("key2", "value2"))
template.postForObject<Foo>(url, body, vars)
verify(exactly = 1) { template.postForObject(url, body, Foo::class.java, vars) }
}
@Test
fun `postForObject with reified type parameters, String and Any`() {
val url = "https://spring.io"
val body: Any = "body"
template.postForObject<Foo>(url, body)
verify(exactly = 1) { template.postForObject(url, body, Foo::class.java) }
}
@Test
fun `postForObject with reified type parameters`() {
val url = "https://spring.io"
template.postForObject<Foo>(url)
verify(exactly = 1) { template.postForObject(url, null, Foo::class.java) }
}
@Test
fun `postForEntity with reified type parameters, String, Any and varargs`() {
val url = "https://spring.io"
val body: Any = "body"
val var1 = "var1"
val var2 = "var2"
template.postForEntity<Foo>(url, body, var1, var2)
verify(exactly = 1) { template.postForEntity(url, body, Foo::class.java, var1, var2) }
}
@Test
fun `postForEntity with reified type parameters, String, Any and Map`() {
val url = "https://spring.io"
val body: Any = "body"
val vars = mapOf(Pair("key1", "value1"), Pair("key2", "value2"))
template.postForEntity<Foo>(url, body, vars)
verify(exactly = 1) { template.postForEntity(url, body, Foo::class.java, vars) }
}
@Test
fun `postForEntity with reified type parameters, String and Any`() {
val url = "https://spring.io"
val body: Any = "body"
template.postForEntity<Foo>(url, body)
verify(exactly = 1) { template.postForEntity(url, body, Foo::class.java) }
}
@Test
fun `postForEntity with reified type parameters`() {
val url = "https://spring.io"
template.postForEntity<Foo>(url)
verify(exactly = 1) { template.postForEntity(url, null, Foo::class.java) }
}
@Test
fun `exchange with reified type parameters, String, HttpMethod, HttpEntity and varargs`() {
val url = "https://spring.io"
val method = HttpMethod.GET
val entity = mockk<HttpEntity<Foo>>()
val var1 = "var1"
val var2 = "var2"
template.exchange<List<Foo>>(url, method, entity, var1, var2)
verify(exactly = 1) { template.exchange(url, method, entity,
object : ParameterizedTypeReference<List<Foo>>() {}, var1, var2) }
}
@Test
fun `exchange with reified type parameters, String, HttpMethod, HttpEntity and Map`() {
val url = "https://spring.io"
val method = HttpMethod.GET
val entity = mockk<HttpEntity<Foo>>()
val vars = mapOf(Pair("key1", "value1"), Pair("key2", "value2"))
template.exchange<List<Foo>>(url, method, entity, vars)
verify(exactly = 1) { template.exchange(url, method, entity,
object : ParameterizedTypeReference<List<Foo>>() {}, vars) }
}
@Test
fun `exchange with reified type parameters, String, HttpMethod, HttpEntity`() {
val url = "https://spring.io"
val method = HttpMethod.GET
val entity = mockk<HttpEntity<Foo>>()
template.exchange<List<Foo>>(url, method, entity)
verify(exactly = 1) { template.exchange(url, method, entity,
object : ParameterizedTypeReference<List<Foo>>() {}) }
}
@Test
fun `exchange with reified type parameters and HttpEntity`() {
val entity = mockk<RequestEntity<Foo>>()
template.exchange<List<Foo>>(entity)
verify(exactly = 1) { template.exchange(entity,
object : ParameterizedTypeReference<List<Foo>>() {}) }
}
@Test
fun `exchange with reified type parameters, String and HttpMethod`() {
val url = "https://spring.io"
val method = HttpMethod.GET
template.exchange<List<Foo>>(url, method)
verify(exactly = 1) { template.exchange(url, method, null,
object : ParameterizedTypeReference<List<Foo>>() {}) }
}
@Test
fun `RestOperations are available`() {
val extensions = Class.forName(
"org.springframework.boot.test.web.client.TestRestTemplateExtensionsKt")
ReflectionUtils.doWithMethods(RestOperations::class.java) { method ->
arrayOf(ParameterizedTypeReference::class, Class::class).forEach { kClass ->
if (method.parameterTypes.contains(kClass.java)) {
val parameters = mutableListOf<Class<*>>(TestRestTemplate::class.java)
.apply { addAll(method.parameterTypes.filter { it != kClass.java }) }
val f = extensions.getDeclaredMethod(method.name,
*parameters.toTypedArray()).kotlinFunction!!
Assert.assertEquals(1, f.typeParameters.size)
Assert.assertEquals(listOf(Any::class.createType()),
f.typeParameters[0].upperBounds)
}
}
}
}
class Foo
}
| apache-2.0 | 494d15c3d6cf3afacc54d68554180929 | 33.215909 | 92 | 0.700764 | 3.364246 | false | true | false | false |
kohesive/kohesive-iac | model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/utils/StringUtil.kt | 1 | 495 | package uy.kohesive.iac.model.aws.utils
fun String.firstLetterToLowerCase() = take(1).toLowerCase() + drop(1)
fun String.firstLetterToUpperCase() = take(1).toUpperCase() + drop(1)
fun String.singularize(): String = Inflector.getInstance().singularize(this)
fun String.pluralize(): String = Inflector.getInstance().pluralize(this)
fun String.namespace(): String = lastIndexOf('.').let { if (it > -1) substring(0, it) else "" }
fun String.simpleName(): String = substring(lastIndexOf('.') + 1) | mit | 7ac695593662e725af848ee478101e05 | 48.6 | 96 | 0.727273 | 3.613139 | false | false | false | false |
tensorflow/examples | lite/examples/style_transfer/android/app/src/main/java/org/tensorflow/lite/examples/styletransfer/MainViewModel.kt | 1 | 1803 | /*
* Copyright 2022 The TensorFlow Authors. 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 org.tensorflow.lite.examples.styletransfer
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import androidx.lifecycle.ViewModel
import java.nio.ByteBuffer
class MainViewModel : ViewModel() {
private val _inputBitmap = SingleLiveEvent<Bitmap>()
val inputBitmap get() = _inputBitmap
// Store helper setting
var defaultModelNumThreads: Int = 2
var defaultModelDelegate: Int = 0
var defaultModel: Int = 0
// Convert bytebuffer to Bitmap and rotate for ready to show on Ui and
// transfer
fun setInputImage(buffer: ByteBuffer, rotation: Int) {
val bytes = ByteArray(buffer.capacity())
buffer.get(bytes)
var bitmapBuffer = BitmapFactory.decodeByteArray(
bytes, 0,
bytes.size, null
)
val matrix = Matrix()
matrix.postRotate(rotation.toFloat())
bitmapBuffer = Bitmap.createBitmap(
bitmapBuffer, 0, 0, bitmapBuffer
.width, bitmapBuffer.height, matrix, true
)
_inputBitmap.postValue(bitmapBuffer)
}
fun getInputBitmap() = _inputBitmap.value
}
| apache-2.0 | 55a7fbdfef8bc892ecbd26bb52dc7978 | 32.388889 | 75 | 0.697171 | 4.59949 | false | false | false | false |
kohesive/kohesive-iac | model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/cloudformation/codegen/CloudFormationModelCodeGen.kt | 1 | 4413 | package uy.kohesive.iac.model.aws.cloudformation.codegen
import com.amazonaws.codegen.emitters.CodeEmitter
import com.amazonaws.codegen.emitters.CodeWriter
import com.amazonaws.codegen.emitters.FreemarkerGeneratorTask
import com.amazonaws.codegen.emitters.GeneratorTaskExecutor
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import freemarker.template.Template
import uy.kohesive.iac.model.aws.cloudformation.crawler.CloudFormationResource
import uy.kohesive.iac.model.aws.codegen.TemplateDescriptor
import uy.kohesive.iac.model.aws.utils.CasePreservingJacksonNamingStrategy
import java.io.File
import java.io.Writer
//fun main(args: Array<String>) {
// CloudFormationModelCodeGen(
// inputDir = "./model-aws/src/generated/resources/cfSchema",
// outputDir = "/Users/eliseyev/TMP/cf/model/",
// packageName = "uy.kohesive.iac.model.aws.cloudformation.resources"
// ).generate()
//}
class CloudFormationModelCodeGen(
val inputDir: String,
val outputDir: String,
val packageName: String
) {
companion object {
val JSON = jacksonObjectMapper()
.setPropertyNamingStrategy(CasePreservingJacksonNamingStrategy())
.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
}
private val generatorTaskExecutor = GeneratorTaskExecutor()
fun generate() {
File(outputDir).mkdirs()
File(inputDir).listFiles { _, name ->
name.endsWith(".json", ignoreCase = true)
}.map { file ->
val model = AmazonServiceCFModel(
serviceName = file.nameWithoutExtension,
resources = JSON.readValue<List<CloudFormationResource>>(file)
)
val generateTask = AmazonServiceCFModelGenerateTask.create(
outputDir = outputDir,
packageName = packageName,
cfModel = model
)
val emitter = CodeEmitter(listOf(generateTask), generatorTaskExecutor)
emitter.emit()
model.serviceName
}.let { serviceNames ->
val generateTask = CFResourcesListGenerateTask.create(
outputDir = outputDir,
packageName = packageName,
model = CFResourcesSummaryData(serviceNames, packageName)
)
val emitter = CodeEmitter(listOf(generateTask), generatorTaskExecutor)
emitter.emit()
}
generatorTaskExecutor.waitForCompletion()
generatorTaskExecutor.shutdown()
}
}
class AmazonServiceCFModelGenerateTask private constructor(writer: Writer, template: Template, data: Any)
: FreemarkerGeneratorTask(writer, template, data) {
companion object {
fun create(outputDir: String, packageName: String, cfModel: AmazonServiceCFModel): AmazonServiceCFModelGenerateTask {
return AmazonServiceCFModelGenerateTask(
CodeWriter(
outputDir + "/" + packageName.replace('.', '/'),
cfModel.serviceName,
".kt"
),
TemplateDescriptor.CloudFormationModel.load(),
AmazonCFServiceModel(
packageName = packageName,
serviceName = cfModel.serviceName,
classes = ModelBuilder(cfModel.resources).build()
)
)
}
}
}
data class AmazonServiceCFModel(
val serviceName: String,
val resources: List<CloudFormationResource>
)
class CFResourcesListGenerateTask private constructor(writer: Writer, template: Template, data: Any)
: FreemarkerGeneratorTask(writer, template, data) {
companion object {
fun create(outputDir: String, packageName: String, model: CFResourcesSummaryData): CFResourcesListGenerateTask {
return CFResourcesListGenerateTask(
CodeWriter(
outputDir + "/" + packageName.replace('.', '/'),
"CFResources",
".kt"
),
TemplateDescriptor.CloudFormationResourcesList.load(),
model
)
}
}
}
data class CFResourcesSummaryData(
val serviceNames: List<String>,
val packageName: String
)
| mit | ce1613731994a1120fbddb2143664c0e | 33.748031 | 125 | 0.644913 | 5.026196 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/fir/test/org/jetbrains/kotlin/idea/fir/completion/AbstractHighLevelMultiFileJvmBasicCompletionTest.kt | 1 | 1742 | // 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.fir.completion
import com.intellij.codeInsight.completion.CompletionType
import com.intellij.testFramework.LightProjectDescriptor
import org.jetbrains.kotlin.idea.completion.test.KotlinFixtureCompletionBaseTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.test.utils.IgnoreTests
import java.io.File
abstract class AbstractHighLevelMultiFileJvmBasicCompletionTest : KotlinFixtureCompletionBaseTestCase() {
override fun isFirPlugin(): Boolean = true
override val testDataDirectory: File
get() = super.testDataDirectory.resolve(getTestName(false))
override val captureExceptions: Boolean = false
override fun executeTest(test: () -> Unit) {
IgnoreTests.runTestIfEnabledByFileDirective(dataFile().toPath(), IgnoreTests.DIRECTIVES.FIR_COMPARISON) {
test()
}
}
override fun fileName(): String = getTestName(false) + ".kt"
override fun configureFixture(testPath: String) {
// We need to copy all files from the testDataPath (= "") to the tested project
myFixture.copyDirectoryToProject("", "")
super.configureFixture(testPath)
}
override fun defaultCompletionType(): CompletionType = CompletionType.BASIC
override fun getPlatform(): TargetPlatform = JvmPlatforms.unspecifiedJvmPlatform
override fun getProjectDescriptor(): LightProjectDescriptor = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
} | apache-2.0 | 4be2472e01652ab304f6e3e7f9f1e4b5 | 43.692308 | 120 | 0.781286 | 5.393189 | false | true | false | false |
romannurik/muzei | main/src/main/java/com/google/android/apps/muzei/util/SmartInsetLinearLayout.kt | 2 | 2032 | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.util
import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.widget.LinearLayout
/**
* A vertical [LinearLayout] that transforms fitsSystemWindows insets into vertical padding
* for only the top and bottom child.
*/
class SmartInsetLinearLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
: LinearLayout(context, attrs, defStyleAttr) {
init {
orientation = VERTICAL
}
@Suppress("OverridingDeprecatedMember")
override fun fitSystemWindows(insets: Rect): Boolean {
val horizontalInsets = Rect(insets.left, 0, insets.right, 0)
@Suppress("DEPRECATION")
super.fitSystemWindows(horizontalInsets)
val childCount = childCount
if (childCount > 0) {
val firstChild = getChildAt(0)
firstChild.setPadding(firstChild.paddingLeft,
insets.top,
firstChild.paddingRight,
if (childCount == 1) insets.bottom else 0)
if (childCount > 1) {
val lastChild = getChildAt(childCount - 1)
lastChild.setPadding(lastChild.paddingLeft,
lastChild.paddingTop,
lastChild.paddingRight,
insets.bottom)
}
}
return true
}
}
| apache-2.0 | 755bbeca2206fd0569244672b78a8740 | 34.649123 | 124 | 0.658957 | 4.849642 | false | false | false | false |
Zhouzhouzhou/AndroidDemo | app/src/main/java/com/zhou/android/kotlin/album/AlbumPagerAdapter.kt | 1 | 2538 | package com.zhou.android.kotlin.album
import android.content.Context
import android.support.v4.view.PagerAdapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.squareup.picasso.Picasso
import com.zhou.android.R
class AlbumPagerAdapter : PagerAdapter {
private val context: Context
private val data = arrayListOf<String>()
private val images = ArrayList<ImageView>()
private var removePosition = -1
private var needFreshCount = 0
constructor(context: Context, data: ArrayList<String>) {
[email protected] = context
[email protected]()
[email protected](data)
for (index in data) {
createItem(index)
}
}
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view == `object`
}
override fun getCount(): Int {
return data.size
}
override fun getItemPosition(`object`: Any): Int {
if (needFreshCount > 0) {
needFreshCount--
return POSITION_NONE
} else {
return super.getItemPosition(`object`)
}
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val imageView = images[position]
container?.addView(imageView)
return imageView
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
container.removeView(images[position])
// images.removeAt(position)
// (container as ViewPager).removeView(`object` as View)
}
private fun createItem(path: String): ImageView {
val iv: ImageView = LayoutInflater.from(context).inflate(R.layout.layout_picture, null, false) as ImageView
Picasso.with(context)
.load(path)
.error(R.drawable.ic_place)
.placeholder(R.drawable.ic_place)
.into(iv)
images.add(iv)
return iv
}
fun remove(position: Int) {
if (position < 0 || position > data.size)
return
if (data.size > 0) {//无效
val view = images[position + 1 % (count)]
view.scaleX = 1f
view.scaleY = 1f
}
removePosition = position
data.removeAt(position)
val view = images.removeAt(position)
view.visibility = View.GONE
needFreshCount = data.size
notifyDataSetChanged()
}
} | mit | 495982e2fd68041d28940ea870f78c0e | 27.806818 | 115 | 0.625099 | 4.469136 | false | false | false | false |
rei-m/HBFav_material | app/src/main/kotlin/me/rei_m/hbfavmaterial/presentation/widget/dialog/EditUserIdDialogFragment.kt | 1 | 4432 | /*
* Copyright (c) 2017. Rei Matsushita
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package me.rei_m.hbfavmaterial.presentation.widget.dialog
import android.app.Dialog
import android.app.ProgressDialog
import android.arch.lifecycle.ViewModelProviders
import android.content.Context
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import dagger.android.ContributesAndroidInjector
import dagger.android.support.AndroidSupportInjection
import io.reactivex.disposables.CompositeDisposable
import me.rei_m.hbfavmaterial.R
import me.rei_m.hbfavmaterial.databinding.DialogFragmentEditUserIdBinding
import me.rei_m.hbfavmaterial.di.ForFragment
import me.rei_m.hbfavmaterial.extension.adjustScreenWidth
import me.rei_m.hbfavmaterial.presentation.helper.SnackbarFactory
import me.rei_m.hbfavmaterial.viewmodel.widget.dialog.EditUserIdDialogFragmentViewModel
import me.rei_m.hbfavmaterial.viewmodel.widget.dialog.di.EditUserIdDialogFragmentViewModelModule
import javax.inject.Inject
class EditUserIdDialogFragment : DialogFragment() {
companion object {
val TAG: String = EditUserIdDialogFragment::class.java.simpleName
private const val KEY_USER_ID = "KEY_USER_ID"
fun newInstance() = EditUserIdDialogFragment()
}
@Inject
lateinit var progressDialog: ProgressDialog
@Inject
lateinit var viewModelFactory: EditUserIdDialogFragmentViewModel.Factory
private lateinit var binding: DialogFragmentEditUserIdBinding
private lateinit var viewModel: EditUserIdDialogFragmentViewModel
private var disposable: CompositeDisposable? = null
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return super.onCreateDialog(savedInstanceState).apply {
window.requestFeature(Window.FEATURE_NO_TITLE)
}
}
override fun onAttach(context: Context?) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState != null) {
viewModelFactory.userId = savedInstanceState.getString(KEY_USER_ID)
}
viewModel = ViewModelProviders.of(this, viewModelFactory).get(EditUserIdDialogFragmentViewModel::class.java)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DialogFragmentEditUserIdBinding.inflate(inflater, container, false)
binding.viewModel = viewModel
return binding.root
}
override fun onResume() {
super.onResume()
disposable = CompositeDisposable()
disposable?.addAll(viewModel.dismissDialogEvent.subscribe {
dismiss()
}, viewModel.isLoading.subscribe {
if (it) {
progressDialog.show()
} else {
progressDialog.dismiss()
}
}, viewModel.isRaisedError.subscribe {
SnackbarFactory(binding.root).create(R.string.message_error_network).show()
})
}
override fun onPause() {
disposable?.dispose()
disposable = null
super.onPause()
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
adjustScreenWidth()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(KEY_USER_ID, viewModel.userId.get())
}
@dagger.Module
abstract inner class Module {
@ForFragment
@ContributesAndroidInjector(modules = arrayOf(EditUserIdDialogFragmentViewModelModule::class))
internal abstract fun contributeInjector(): EditUserIdDialogFragment
}
}
| apache-2.0 | 59908f802cb0d52205bc4b1f3c7c8760 | 34.741935 | 116 | 0.734657 | 5.030647 | false | false | false | false |
siosio/intellij-community | platform/util-ex/src/com/intellij/util/io/DigestUtil.kt | 2 | 3201 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.io
import com.intellij.util.lazyPub
import org.jetbrains.annotations.ApiStatus
import java.io.IOException
import java.io.InputStream
import java.math.BigInteger
import java.nio.file.Path
import java.security.MessageDigest
import java.security.Provider
import java.security.SecureRandom
object DigestUtil {
private val sunSecurityProvider: Provider = java.security.Security.getProvider("SUN")
@JvmStatic
val random: SecureRandom by lazy { SecureRandom() }
// http://stackoverflow.com/a/41156 - shorter than UUID, but secure
@JvmStatic
fun randomToken(): String = BigInteger(130, random).toString(32)
@JvmStatic
fun md5(): MessageDigest = md5.cloneDigest()
private val md5 by lazyPub { getMessageDigest("MD5") }
@JvmStatic
fun sha1(): MessageDigest = sha1.cloneDigest()
private val sha1 by lazyPub { getMessageDigest("SHA-1") }
@JvmStatic
fun sha256(): MessageDigest = sha256.cloneDigest()
private val sha256 by lazyPub { getMessageDigest("SHA-256") }
@JvmStatic
fun sha512(): MessageDigest = sha512.cloneDigest()
private val sha512 by lazyPub { getMessageDigest("SHA-512") }
@JvmStatic
fun digestToHash(digest: MessageDigest) = bytesToHex(digest.digest())
@JvmStatic
fun sha256Hex(input: ByteArray): String = bytesToHex(sha256().digest(input))
@JvmStatic
fun sha1Hex(input: ByteArray): String = bytesToHex(sha1().digest(input))
/**
* Digest cloning is faster than requesting a new one from [MessageDigest.getInstance].
* This approach is used in Guava as well.
*/
private fun MessageDigest.cloneDigest(): MessageDigest {
return try {
clone() as MessageDigest
}
catch (e: CloneNotSupportedException) {
throw IllegalArgumentException("Message digest is not cloneable: ${this}")
}
}
@JvmStatic
fun updateContentHash(digest: MessageDigest, path: Path) {
try {
path.inputStream().use {
updateContentHash(digest, it)
}
}
catch (e: IOException) {
throw RuntimeException("Failed to read $path. ${e.message}", e)
}
}
@JvmStatic
fun updateContentHash(digest: MessageDigest, inputStream: InputStream) {
val buff = ByteArray(512 * 1024)
try {
while (true) {
val sz = inputStream.read(buff)
if (sz <= 0) break
digest.update(buff, 0, sz)
}
}
catch (e: IOException) {
throw RuntimeException("Failed to read stream. ${e.message}", e)
}
}
private fun getMessageDigest(algorithm: String): MessageDigest {
return MessageDigest.getInstance(algorithm, sunSecurityProvider)
}
}
private fun bytesToHex(data: ByteArray): String {
val l = data.size
val chars = CharArray(l shl 1)
var i = 0
var j = 0
while (i < l) {
val v = data[i].toInt()
chars[j++] = HEX_ARRAY[0xF0 and v ushr 4]
chars[j++] = HEX_ARRAY[0x0F and v]
i++
}
return String(chars)
}
@Suppress("SpellCheckingInspection")
private val HEX_ARRAY = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f') | apache-2.0 | 59f2178b6dee28c7f6f4745d965d5108 | 28.376147 | 140 | 0.684786 | 3.847356 | false | false | false | false |
jwren/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ConfigureHighlightingLevel.kt | 1 | 4031 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.daemon.impl
import com.intellij.codeInsight.daemon.DaemonBundle.message
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.codeInsight.daemon.impl.analysis.FileHighlightingSetting
import com.intellij.codeInsight.daemon.impl.analysis.HighlightLevelUtil.forceRootHighlighting
import com.intellij.codeInsight.daemon.impl.analysis.HighlightingSettingsPerFile
import com.intellij.lang.Language
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.CommonDataKeys.PSI_FILE
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.EditorBundle
import com.intellij.openapi.editor.markup.InspectionsLevel
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.psi.FileViewProvider
fun getConfigureHighlightingLevelPopup(context: DataContext): JBPopup? {
val psi = context.getData(PSI_FILE) ?: return null
if (!psi.isValid || psi.project.isDisposed) return null
val provider = psi.viewProvider
val languages = provider.languages
if (languages.isEmpty()) return null
val file = psi.virtualFile ?: return null
val index = ProjectFileIndex.getInstance(psi.project)
val isAllInspectionsEnabled = index.isInContent(file) || !index.isInLibrary(file)
val group = DefaultActionGroup()
languages.sortedBy { it.displayName }.forEach {
if (languages.count() > 1) {
group.add(Separator.create(it.displayName))
}
group.add(LevelAction(InspectionsLevel.NONE, provider, it))
group.add(LevelAction(InspectionsLevel.SYNTAX, provider, it))
if (isAllInspectionsEnabled) {
if (ApplicationManager.getApplication().isInternal) {
group.add(LevelAction(InspectionsLevel.ESSENTIAL, provider, it))
}
group.add(LevelAction(InspectionsLevel.ALL, provider, it))
}
}
group.add(Separator.create())
group.add(ConfigureInspectionsAction())
val title = message("popup.title.configure.highlighting.level", psi.virtualFile.presentableName)
return JBPopupFactory.getInstance().createActionGroupPopup(title, group, context, true, null, 100)
}
private class LevelAction(val level: InspectionsLevel, val provider: FileViewProvider, val language: Language)
: ToggleAction(level.toString()), DumbAware {
override fun isSelected(event: AnActionEvent): Boolean {
val file = provider.getPsi(language) ?: return false
val manager = HighlightingSettingsPerFile.getInstance(file.project) ?: return false
val configuredLevel = FileHighlightingSetting.toInspectionsLevel(manager.getHighlightingSettingForRoot(file))
return level == configuredLevel
}
override fun setSelected(event: AnActionEvent, state: Boolean) {
if (!state) return
val file = provider.getPsi(language) ?: return;
forceRootHighlighting(file, FileHighlightingSetting.fromInspectionsLevel(level))
InjectedLanguageManager.getInstance(file.project).dropFileCaches(file)
DaemonCodeAnalyzer.getInstance(file.project).restart()
}
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.setDescription(EditorBundle.message("hector.highlighting.level.title")+": "+level.description)
}
}
internal class ConfigureHighlightingLevelAction : DumbAwareAction() {
override fun update(event: AnActionEvent) {
val enabled = event.getData(PSI_FILE)?.viewProvider?.languages?.isNotEmpty()
event.presentation.isEnabled = enabled == true
}
override fun actionPerformed(event: AnActionEvent) {
val popup = getConfigureHighlightingLevelPopup(event.dataContext)
popup?.showInBestPositionFor(event.dataContext)
}
}
| apache-2.0 | c2375ad428d0d8a0a8f1b23dedd3429f | 43.296703 | 140 | 0.789382 | 4.454144 | false | true | false | false |
jwren/intellij-community | plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/smart/SmartCompletion.kt | 1 | 23118 | // 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.completion.smart
import com.intellij.codeInsight.completion.EmptyDeclarativeInsertHandler
import com.intellij.codeInsight.completion.InsertHandler
import com.intellij.codeInsight.completion.OffsetKey
import com.intellij.codeInsight.completion.PrefixMatcher
import com.intellij.codeInsight.lookup.*
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.SmartList
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.KotlinIcons
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.completion.*
import org.jetbrains.kotlin.idea.completion.handlers.WithTailInsertHandler
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.CallTypeAndReceiver
import org.jetbrains.kotlin.idea.util.isAlmostEverything
import org.jetbrains.kotlin.idea.util.toFuzzyType
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.isBooleanOrNullableBoolean
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
import org.jetbrains.kotlin.utils.addIfNotNull
interface InheritanceItemsSearcher {
fun search(nameFilter: (String) -> Boolean, consumer: (LookupElement) -> Unit)
}
class SmartCompletion(
private val expression: KtExpression,
private val resolutionFacade: ResolutionFacade,
private val bindingContext: BindingContext,
private val moduleDescriptor: ModuleDescriptor,
private val visibilityFilter: (DeclarationDescriptor) -> Boolean,
private val indicesHelper: KotlinIndicesHelper,
private val prefixMatcher: PrefixMatcher,
private val inheritorSearchScope: GlobalSearchScope,
private val toFromOriginalFileMapper: ToFromOriginalFileMapper,
private val callTypeAndReceiver: CallTypeAndReceiver<*, *>,
private val isJvmModule: Boolean,
private val forBasicCompletion: Boolean = false
) {
private val expressionWithType = when (callTypeAndReceiver) {
is CallTypeAndReceiver.DEFAULT ->
expression
is CallTypeAndReceiver.DOT,
is CallTypeAndReceiver.SAFE,
is CallTypeAndReceiver.SUPER_MEMBERS,
is CallTypeAndReceiver.INFIX,
is CallTypeAndReceiver.CALLABLE_REFERENCE ->
expression.parent as KtExpression
else -> // actually no smart completion for such places
expression
}
val expectedInfos: Collection<ExpectedInfo> = calcExpectedInfos(expressionWithType)
private val callableTypeExpectedInfo = expectedInfos.filterCallableExpected()
val smartCastCalculator: SmartCastCalculator by lazy(LazyThreadSafetyMode.NONE) {
SmartCastCalculator(
bindingContext,
resolutionFacade.moduleDescriptor,
expression,
callTypeAndReceiver.receiver as? KtExpression,
resolutionFacade
)
}
val descriptorFilter: ((DeclarationDescriptor, AbstractLookupElementFactory) -> Collection<LookupElement>)? =
{ descriptor: DeclarationDescriptor, factory: AbstractLookupElementFactory ->
filterDescriptor(descriptor, factory).map { postProcess(it) }
}.takeIf { expectedInfos.isNotEmpty() }
fun additionalItems(lookupElementFactory: LookupElementFactory): Pair<Collection<LookupElement>, InheritanceItemsSearcher?> {
val (items, inheritanceSearcher) = additionalItemsNoPostProcess(lookupElementFactory)
val postProcessedItems = items.map { postProcess(it) }
//TODO: could not use "let" because of KT-8754
val postProcessedSearcher = if (inheritanceSearcher != null)
object : InheritanceItemsSearcher {
override fun search(nameFilter: (String) -> Boolean, consumer: (LookupElement) -> Unit) {
inheritanceSearcher.search(nameFilter) { consumer(postProcess(it)) }
}
}
else
null
return postProcessedItems to postProcessedSearcher
}
val descriptorsToSkip: Set<DeclarationDescriptor> by lazy<Set<DeclarationDescriptor>> {
val parent = expressionWithType.parent
when (parent) {
is KtBinaryExpression -> {
if (parent.right == expressionWithType) {
val operationToken = parent.operationToken
if (operationToken == KtTokens.EQ || operationToken in COMPARISON_TOKENS) {
val left = parent.left
if (left is KtReferenceExpression) {
return@lazy bindingContext[BindingContext.REFERENCE_TARGET, left]?.let(::setOf).orEmpty()
}
}
}
}
is KtWhenConditionWithExpression -> {
val entry = parent.parent as KtWhenEntry
val whenExpression = entry.parent as KtWhenExpression
val subject = whenExpression.subjectExpression ?: return@lazy emptySet()
val descriptorsToSkip = HashSet<DeclarationDescriptor>()
if (subject is KtSimpleNameExpression) {
val variable = bindingContext[BindingContext.REFERENCE_TARGET, subject] as? VariableDescriptor
if (variable != null) {
descriptorsToSkip.add(variable)
}
}
val subjectType = bindingContext.getType(subject) ?: return@lazy emptySet()
val classDescriptor = TypeUtils.getClassDescriptor(subjectType)
if (classDescriptor != null && DescriptorUtils.isEnumClass(classDescriptor)) {
val conditions =
whenExpression.entries.flatMap { it.conditions.toList() }.filterIsInstance<KtWhenConditionWithExpression>()
for (condition in conditions) {
val selectorExpr =
(condition.expression as? KtDotQualifiedExpression)?.selectorExpression as? KtReferenceExpression ?: continue
val target = bindingContext[BindingContext.REFERENCE_TARGET, selectorExpr] as? ClassDescriptor ?: continue
if (DescriptorUtils.isEnumEntry(target)) {
descriptorsToSkip.add(target)
}
}
}
return@lazy descriptorsToSkip
}
}
return@lazy emptySet()
}
private fun filterDescriptor(
descriptor: DeclarationDescriptor,
lookupElementFactory: AbstractLookupElementFactory
): Collection<LookupElement> {
ProgressManager.checkCanceled()
if (descriptor in descriptorsToSkip) return emptyList()
val result = SmartList<LookupElement>()
val types = descriptor.fuzzyTypesForSmartCompletion(smartCastCalculator, callTypeAndReceiver, resolutionFacade, bindingContext)
val infoMatcher = { expectedInfo: ExpectedInfo -> types.matchExpectedInfo(expectedInfo) }
result.addLookupElements(
descriptor,
expectedInfos,
infoMatcher,
noNameSimilarityForReturnItself = callTypeAndReceiver is CallTypeAndReceiver.DEFAULT
) { declarationDescriptor ->
lookupElementFactory.createStandardLookupElementsForDescriptor(declarationDescriptor, useReceiverTypes = true)
}
if (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) {
result.addCallableReferenceLookupElements(descriptor, lookupElementFactory)
}
return result
}
private fun additionalItemsNoPostProcess(lookupElementFactory: LookupElementFactory): Pair<Collection<LookupElement>, InheritanceItemsSearcher?> {
val asTypePositionItems = buildForAsTypePosition(lookupElementFactory.basicFactory)
if (asTypePositionItems != null) {
assert(expectedInfos.isEmpty())
return Pair(asTypePositionItems, null)
}
val items = ArrayList<LookupElement>()
val inheritanceSearchers = ArrayList<InheritanceItemsSearcher>()
if (!forBasicCompletion) { // basic completion adds keyword values on its own
val keywordValueConsumer = object : KeywordValues.Consumer {
override fun consume(
lookupString: String,
expectedInfoMatcher: (ExpectedInfo) -> ExpectedInfoMatch,
suitableOnPsiLevel: PsiElement.() -> Boolean,
priority: SmartCompletionItemPriority,
factory: () -> LookupElement
) {
items.addLookupElements(null, expectedInfos, expectedInfoMatcher) {
val lookupElement = factory()
lookupElement.putUserData(SMART_COMPLETION_ITEM_PRIORITY_KEY, priority)
listOf(lookupElement)
}
}
}
KeywordValues.process(
keywordValueConsumer,
callTypeAndReceiver,
bindingContext,
resolutionFacade,
moduleDescriptor,
isJvmModule
)
}
if (expectedInfos.isNotEmpty()) {
items.addArrayLiteralsInAnnotationsCompletions()
if (!forBasicCompletion && (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT || callTypeAndReceiver is CallTypeAndReceiver.UNKNOWN /* after this@ */)) {
items.addThisItems(expression, expectedInfos, smartCastCalculator)
}
if (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) {
TypeInstantiationItems(
resolutionFacade,
bindingContext,
visibilityFilter,
toFromOriginalFileMapper,
inheritorSearchScope,
lookupElementFactory,
forBasicCompletion,
indicesHelper
).addTo(items, inheritanceSearchers, expectedInfos)
if (expression is KtSimpleNameExpression) {
StaticMembers(bindingContext, lookupElementFactory, resolutionFacade, moduleDescriptor).addToCollection(
items,
expectedInfos,
expression,
descriptorsToSkip
)
}
ClassLiteralItems.addToCollection(items, expectedInfos, lookupElementFactory.basicFactory, isJvmModule)
items.addNamedArgumentsWithLiteralValueItems(expectedInfos)
LambdaSignatureItems.addToCollection(items, expressionWithType, bindingContext, resolutionFacade)
if (!forBasicCompletion) {
LambdaItems.addToCollection(items, expectedInfos)
val whenCondition = expressionWithType.parent as? KtWhenConditionWithExpression
if (whenCondition != null) {
val entry = whenCondition.parent as KtWhenEntry
val whenExpression = entry.parent as KtWhenExpression
val entries = whenExpression.entries
if (whenExpression.elseExpression == null && entry == entries.last() && entries.size != 1) {
val lookupElement = LookupElementBuilder.create("else")
.bold()
.withTailText(" ->")
.withInsertHandler(
WithTailInsertHandler("->", spaceBefore = true, spaceAfter = true).asPostInsertHandler
)
items.add(lookupElement)
}
}
}
MultipleArgumentsItemProvider(bindingContext, smartCastCalculator, resolutionFacade).addToCollection(
items,
expectedInfos,
expression
)
}
}
val inheritanceSearcher = if (inheritanceSearchers.isNotEmpty())
object : InheritanceItemsSearcher {
override fun search(nameFilter: (String) -> Boolean, consumer: (LookupElement) -> Unit) {
inheritanceSearchers.forEach { it.search(nameFilter, consumer) }
}
}
else
null
return Pair(items, inheritanceSearcher)
}
private fun postProcess(item: LookupElement): LookupElement {
if (forBasicCompletion) return item
return if (item.getUserData(KEEP_OLD_ARGUMENT_LIST_ON_TAB_KEY) == null) {
LookupElementDecorator.withDelegateInsertHandler(
item,
InsertHandler { context, element ->
if (context.completionChar == Lookup.REPLACE_SELECT_CHAR) {
val offset = context.offsetMap.tryGetOffset(OLD_ARGUMENTS_REPLACEMENT_OFFSET)
if (offset != null) {
context.document.deleteString(context.tailOffset, offset)
}
}
element.handleInsert(context)
}
)
} else {
item
}
}
private fun MutableCollection<LookupElement>.addThisItems(
place: KtExpression,
expectedInfos: Collection<ExpectedInfo>,
smartCastCalculator: SmartCastCalculator
) {
if (shouldCompleteThisItems(prefixMatcher)) {
val items = thisExpressionItems(bindingContext, place, prefixMatcher.prefix, resolutionFacade)
for (item in items) {
val types = smartCastCalculator.types(item.receiverParameter).map { it.toFuzzyType(emptyList()) }
val matcher = { expectedInfo: ExpectedInfo -> types.matchExpectedInfo(expectedInfo) }
addLookupElements(null, expectedInfos, matcher) {
listOf(item.createLookupElement().assignSmartCompletionPriority(SmartCompletionItemPriority.THIS))
}
}
}
}
private fun MutableCollection<LookupElement>.addNamedArgumentsWithLiteralValueItems(expectedInfos: Collection<ExpectedInfo>) {
data class NameAndValue(val name: Name, val value: String, val priority: SmartCompletionItemPriority)
val nameAndValues = HashMap<NameAndValue, MutableList<ExpectedInfo>>()
fun addNameAndValue(name: Name, value: String, priority: SmartCompletionItemPriority, expectedInfo: ExpectedInfo) {
nameAndValues.getOrPut(NameAndValue(name, value, priority)) { ArrayList() }.add(expectedInfo)
}
for (expectedInfo in expectedInfos) {
val argumentData = expectedInfo.additionalData as? ArgumentPositionData.Positional ?: continue
if (argumentData.namedArgumentCandidates.isEmpty()) continue
val parameters = argumentData.function.valueParameters
if (argumentData.argumentIndex >= parameters.size) continue
val parameterName = parameters[argumentData.argumentIndex].name
if (expectedInfo.fuzzyType?.type?.isBooleanOrNullableBoolean() == true) {
addNameAndValue(parameterName, "true", SmartCompletionItemPriority.NAMED_ARGUMENT_TRUE, expectedInfo)
addNameAndValue(parameterName, "false", SmartCompletionItemPriority.NAMED_ARGUMENT_FALSE, expectedInfo)
}
if (expectedInfo.fuzzyType?.type?.isMarkedNullable == true) {
addNameAndValue(parameterName, "null", SmartCompletionItemPriority.NAMED_ARGUMENT_NULL, expectedInfo)
}
}
for ((nameAndValue, infos) in nameAndValues) {
var lookupElement = createNamedArgumentWithValueLookupElement(nameAndValue.name, nameAndValue.value, nameAndValue.priority)
lookupElement = lookupElement.addTail(mergeTails(infos.map { it.tail }))
add(lookupElement)
}
}
private fun createNamedArgumentWithValueLookupElement(name: Name, value: String, priority: SmartCompletionItemPriority): LookupElement {
val lookupElement = LookupElementBuilder.create("${name.asString()} = $value")
.withIcon(KotlinIcons.PARAMETER)
.withInsertHandler { context, _ ->
context.document.replaceString(context.startOffset, context.tailOffset, "${name.render()} = $value")
}
lookupElement.putUserData(SmartCompletionInBasicWeigher.NAMED_ARGUMENT_KEY, Unit)
lookupElement.assignSmartCompletionPriority(priority)
return lookupElement
}
private fun calcExpectedInfos(expression: KtExpression): Collection<ExpectedInfo> {
// if our expression is initializer of implicitly typed variable - take type of variable from original file (+ the same for function)
val declaration = implicitlyTypedDeclarationFromInitializer(expression)
if (declaration != null) {
val originalDeclaration = toFromOriginalFileMapper.toOriginalFile(declaration)
if (originalDeclaration != null) {
val originalDescriptor = originalDeclaration.resolveToDescriptorIfAny() as? CallableDescriptor
val returnType = originalDescriptor?.returnType
if (returnType != null && !returnType.isError) {
return listOf(ExpectedInfo(returnType, declaration.name, null))
}
}
}
// if expected types are too general, try to use expected type from outer calls
var count = 0
while (true) {
val infos =
ExpectedInfos(bindingContext, resolutionFacade, indicesHelper, useOuterCallsExpectedTypeCount = count).calculate(expression)
if (count == 2 /* use two outer calls maximum */ || infos.none { it.fuzzyType?.isAlmostEverything() ?: false }) {
return if (forBasicCompletion)
infos.map { it.copy(tail = null) }
else
infos
}
count++
}
//TODO: we could always give higher priority to results with outer call expected type used
}
private fun implicitlyTypedDeclarationFromInitializer(expression: KtExpression): KtDeclaration? {
val parent = expression.parent
when (parent) {
is KtVariableDeclaration -> if (expression == parent.initializer && parent.typeReference == null) return parent
is KtNamedFunction -> if (expression == parent.initializer && parent.typeReference == null) return parent
}
return null
}
private fun MutableCollection<LookupElement>.addCallableReferenceLookupElements(
descriptor: DeclarationDescriptor,
lookupElementFactory: AbstractLookupElementFactory
) {
if (callableTypeExpectedInfo.isEmpty()) return
fun toLookupElement(descriptor: CallableDescriptor): LookupElement? {
val callableReferenceType = descriptor.callableReferenceType(resolutionFacade, null) ?: return null
val matchedExpectedInfos = callableTypeExpectedInfo.filter { it.matchingSubstitutor(callableReferenceType) != null }
if (matchedExpectedInfos.isEmpty()) return null
var lookupElement =
lookupElementFactory.createLookupElement(descriptor, useReceiverTypes = false, parametersAndTypeGrayed = true)
?: return null
lookupElement = object : LookupElementDecorator<LookupElement>(lookupElement) {
override fun getLookupString() = "::" + delegate.lookupString
override fun getAllLookupStrings() = setOf(lookupString)
override fun renderElement(presentation: LookupElementPresentation) {
super.renderElement(presentation)
presentation.itemText = "::" + presentation.itemText
}
override fun getDelegateInsertHandler() = EmptyDeclarativeInsertHandler
}
return lookupElement.assignSmartCompletionPriority(SmartCompletionItemPriority.CALLABLE_REFERENCE)
.addTailAndNameSimilarity(matchedExpectedInfos)
}
when (descriptor) {
is CallableDescriptor -> {
// members and extensions are not supported after "::" currently
if (descriptor.dispatchReceiverParameter == null && descriptor.extensionReceiverParameter == null) {
addIfNotNull(toLookupElement(descriptor))
}
}
is ClassDescriptor -> {
if (descriptor.modality != Modality.ABSTRACT && !descriptor.isInner) {
descriptor.constructors.filter(visibilityFilter).mapNotNullTo(this, ::toLookupElement)
}
}
}
}
private fun buildForAsTypePosition(lookupElementFactory: BasicLookupElementFactory): Collection<LookupElement>? {
val binaryExpression =
((expression.parent as? KtUserType)?.parent as? KtTypeReference)?.parent as? KtBinaryExpressionWithTypeRHS ?: return null
val elementType = binaryExpression.operationReference.getReferencedNameElementType()
if (elementType != KtTokens.AS_KEYWORD && elementType != KtTokens.AS_SAFE) return null
val expectedInfos = calcExpectedInfos(binaryExpression)
val expectedInfosGrouped: Map<KotlinType?, List<ExpectedInfo>> = expectedInfos.groupBy { it.fuzzyType?.type?.makeNotNullable() }
val items = ArrayList<LookupElement>()
for ((type, infos) in expectedInfosGrouped) {
if (type == null) continue
val lookupElement = lookupElementFactory.createLookupElementForType(type) ?: continue
items.add(lookupElement.addTailAndNameSimilarity(infos))
}
return items
}
private fun MutableCollection<LookupElement>.addArrayLiteralsInAnnotationsCompletions() {
this.addAll(ArrayLiteralsInAnnotationItems.collect(expectedInfos, expression))
}
companion object {
val OLD_ARGUMENTS_REPLACEMENT_OFFSET: OffsetKey = OffsetKey.create("nonFunctionReplacementOffset")
val MULTIPLE_ARGUMENTS_REPLACEMENT_OFFSET: OffsetKey = OffsetKey.create("multipleArgumentsReplacementOffset")
}
}
| apache-2.0 | b4a9668edac6f22d29b3f17ff5c28bc1 | 46.665979 | 166 | 0.647893 | 6.249797 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/i18n/src/org/jetbrains/kotlin/idea/i18n/KotlinInvalidBundleOrPropertyInspection.kt | 3 | 4906 | // 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.i18n
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.codeInspection.i18n.JavaI18nUtil
import com.intellij.java.i18n.JavaI18nBundle
import com.intellij.lang.properties.ResourceBundleReference
import com.intellij.lang.properties.psi.Property
import com.intellij.lang.properties.references.PropertyReference
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.calls.model.ExpressionValueArgument
import org.jetbrains.kotlin.resolve.calls.model.VarargValueArgument
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
class KotlinInvalidBundleOrPropertyInspection : AbstractKotlinInspection() {
override fun getDisplayName(): String = JavaI18nBundle.message("inspection.unresolved.property.key.reference.name")
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return object : KtVisitorVoid() {
private fun processResourceBundleReference(ref: ResourceBundleReference, template: KtStringTemplateExpression) {
if (ref.multiResolve(true).isEmpty()) {
holder.registerProblem(
template,
JavaI18nBundle.message("inspection.invalid.resource.bundle.reference", ref.canonicalText),
ProblemHighlightType.LIKE_UNKNOWN_SYMBOL,
TextRange(0, template.textLength)
)
}
}
private fun processPropertyReference(ref: PropertyReference, template: KtStringTemplateExpression) {
if (ref.isSoft) return // don't highlight soft references, they are inserted in every string literal
val property = ref.multiResolve(true).firstOrNull()?.element as? Property
if (property == null) {
holder.registerProblem(
template,
JavaI18nBundle.message("inspection.unresolved.property.key.reference.message", ref.canonicalText),
ProblemHighlightType.LIKE_UNKNOWN_SYMBOL,
TextRange(0, template.textLength),
*ref.quickFixes
)
return
}
val argument = template.parents.firstIsInstanceOrNull<KtValueArgument>() ?: return
if (argument.getArgumentExpression() != KtPsiUtil.deparenthesize(template)) return
val callExpression = argument.getStrictParentOfType<KtCallExpression>() ?: return
val resolvedCall = callExpression.resolveToCall() ?: return
val resolvedArguments = resolvedCall.valueArgumentsByIndex ?: return
val keyArgumentIndex = resolvedArguments.indexOfFirst { it is ExpressionValueArgument && it.valueArgument == argument }
if (keyArgumentIndex < 0) return
val callable = resolvedCall.resultingDescriptor
if (callable.valueParameters.size != keyArgumentIndex + 2) return
val messageArgument = resolvedArguments[keyArgumentIndex + 1] as? VarargValueArgument ?: return
if (messageArgument.arguments.singleOrNull()?.getSpreadElement() != null) return
val expectedArgumentCount = JavaI18nUtil.getPropertyValuePlaceholdersCount(property.value ?: "")
val actualArgumentCount = messageArgument.arguments.size
if (actualArgumentCount < expectedArgumentCount) {
val description = JavaI18nBundle.message(
"property.has.more.parameters.than.passed",
ref.canonicalText, expectedArgumentCount, actualArgumentCount
)
holder.registerProblem(template, description, ProblemHighlightType.GENERIC_ERROR)
}
}
override fun visitStringTemplateExpression(expression: KtStringTemplateExpression) {
for (ref in expression.references) {
when (ref) {
is ResourceBundleReference -> processResourceBundleReference(ref, expression)
is PropertyReference -> processPropertyReference(ref, expression)
}
}
}
}
}
} | apache-2.0 | bb4661b7b2d33794af18d6b14d314a37 | 52.923077 | 158 | 0.666531 | 5.744731 | false | false | false | false |
mickele/DBFlow | dbflow-processor/src/main/java/com/raizlabs/android/dbflow/processor/definition/column/ForeignKeyAccessCombiner.kt | 1 | 5579 | package com.raizlabs.android.dbflow.processor.definition.column
import com.raizlabs.android.dbflow.processor.ClassNames
import com.raizlabs.android.dbflow.processor.SQLiteHelper
import com.raizlabs.android.dbflow.processor.utils.addStatement
import com.squareup.javapoet.CodeBlock
import com.squareup.javapoet.TypeName
import java.util.concurrent.atomic.AtomicInteger
/**
* Description: Provides structured way to combine ForeignKey for both SQLiteStatement and ContentValues
* bindings.
*
* @author Andrew Grosner (fuzz)
*/
class ForeignKeyAccessCombiner(val fieldAccessor: ColumnAccessor) {
var fieldAccesses: List<ForeignKeyAccessField> = arrayListOf()
fun addCode(code: CodeBlock.Builder, index: AtomicInteger) {
val modelAccessBlock = fieldAccessor.get(modelBlock)
code.beginControlFlow("if (\$L != null)", modelAccessBlock)
val nullAccessBlock = CodeBlock.builder()
for ((i, it) in fieldAccesses.withIndex()) {
it.addCode(code, index.get(), modelAccessBlock)
it.addNull(nullAccessBlock, index.get())
// do not increment last
if (i < fieldAccesses.size - 1) {
index.incrementAndGet()
}
}
code.nextControlFlow("else")
.add(nullAccessBlock.build().toString())
.endControlFlow()
}
}
class ForeignKeyAccessField(val columnRepresentation: String,
val columnAccessCombiner: ColumnAccessCombiner,
val defaultValue: CodeBlock? = null) {
fun addCode(code: CodeBlock.Builder, index: Int,
modelAccessBlock: CodeBlock) {
columnAccessCombiner.addCode(code, columnRepresentation, defaultValue, index,
modelAccessBlock)
}
fun addNull(code: CodeBlock.Builder, index: Int) {
columnAccessCombiner.addNull(code, columnRepresentation, index)
}
}
class ForeignKeyLoadFromCursorCombiner(val fieldAccessor: ColumnAccessor,
val referencedTypeName: TypeName,
val referencedTableTypeName: TypeName,
val isStubbed: Boolean) {
var fieldAccesses: List<PartialLoadFromCursorAccessCombiner> = arrayListOf()
fun addCode(code: CodeBlock.Builder, index: AtomicInteger) {
val ifChecker = CodeBlock.builder()
val setterBlock = CodeBlock.builder()
if (!isStubbed) {
setterBlock.add("\$T.select().from(\$T.class).where()",
ClassNames.SQLITE, referencedTypeName)
} else {
setterBlock.addStatement(
fieldAccessor.set(CodeBlock.of("new \$T()", referencedTypeName), modelBlock))
}
for ((i, it) in fieldAccesses.withIndex()) {
it.addRetrieval(setterBlock, index.get(), referencedTableTypeName, isStubbed, fieldAccessor)
it.addColumnIndex(code, index.get())
it.addIndexCheckStatement(ifChecker, index.get(), i == fieldAccesses.size - 1)
if (i < fieldAccesses.size - 1) {
index.incrementAndGet()
}
}
if (!isStubbed) setterBlock.add("\n.querySingle()")
code.beginControlFlow("if (\$L)", ifChecker.build())
if (!isStubbed) {
code.addStatement(fieldAccessor.set(setterBlock.build(), modelBlock))
} else {
code.add(setterBlock.build())
}
code.nextControlFlow("else")
.addStatement(fieldAccessor.set(CodeBlock.of("null"), modelBlock))
.endControlFlow()
}
}
class PartialLoadFromCursorAccessCombiner(
val columnRepresentation: String,
val propertyRepresentation: String,
val fieldTypeName: TypeName,
val orderedCursorLookup: Boolean = false,
val fieldLevelAccessor: ColumnAccessor? = null,
val subWrapperAccessor: ColumnAccessor? = null,
val subWrapperTypeName: TypeName? = null) {
fun getIndexName(index: Int): CodeBlock {
return if (!orderedCursorLookup) {
CodeBlock.of("index_\$L", columnRepresentation)
} else {
CodeBlock.of(index.toString())
}
}
fun addRetrieval(code: CodeBlock.Builder, index: Int, referencedTableTypeName: TypeName,
isStubbed: Boolean, parentAccessor: ColumnAccessor) {
val cursorAccess = CodeBlock.of("cursor.\$L(\$L)",
SQLiteHelper.getMethod(subWrapperTypeName ?: fieldTypeName), getIndexName(index))
val fieldAccessBlock = subWrapperAccessor?.set(cursorAccess) ?: cursorAccess
if (!isStubbed) {
code.add(CodeBlock.of("\n.and(\$T.\$L.eq(\$L))",
referencedTableTypeName, propertyRepresentation, fieldAccessBlock))
} else if (fieldLevelAccessor != null) {
code.addStatement(fieldLevelAccessor.set(cursorAccess, parentAccessor.get(modelBlock)))
}
}
fun addColumnIndex(code: CodeBlock.Builder, index: Int) {
if (!orderedCursorLookup) {
code.addStatement(CodeBlock.of("int \$L = cursor.getColumnIndex(\$S)",
getIndexName(index), columnRepresentation))
}
}
fun addIndexCheckStatement(code: CodeBlock.Builder, index: Int,
isLast: Boolean) {
if (!orderedCursorLookup) code.add("\$L != -1 && ", getIndexName(index))
code.add("!cursor.isNull(\$L)", getIndexName(index))
if (!isLast) code.add(" && ")
}
} | mit | 69f5764f3a64691805fb936861933c61 | 38.020979 | 104 | 0.627711 | 4.744048 | false | false | false | false |
androidx/androidx | compose/animation/animation/src/commonMain/kotlin/androidx/compose/animation/EnterExitTransition.kt | 3 | 50133 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(InternalAnimationApi::class, ExperimentalAnimationApi::class)
package androidx.compose.animation
import androidx.compose.animation.core.AnimationVector2D
import androidx.compose.animation.core.FiniteAnimationSpec
import androidx.compose.animation.core.InternalAnimationApi
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.Transition
import androidx.compose.animation.core.TwoWayConverter
import androidx.compose.animation.core.VectorConverter
import androidx.compose.animation.core.VisibilityThreshold
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateValue
import androidx.compose.animation.core.createDeferredAnimation
import androidx.compose.animation.core.spring
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.layout.MeasureScope
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
@RequiresOptIn(message = "This is an experimental animation API.")
@Target(
AnnotationTarget.CLASS,
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY,
AnnotationTarget.FIELD,
AnnotationTarget.PROPERTY_GETTER,
)
@Retention(AnnotationRetention.BINARY)
annotation class ExperimentalAnimationApi
/**
* [EnterTransition] defines how an [AnimatedVisibility] Composable appears on screen as it
* becomes visible. The 4 categories of EnterTransitions available are:
* 1. fade: [fadeIn]
* 2. scale: [scaleIn]
* 3. slide: [slideIn], [slideInHorizontally], [slideInVertically]
* 4. expand: [expandIn], [expandHorizontally], [expandVertically]
*
* [EnterTransition.None] can be used when no enter transition is desired.
* Different [EnterTransition]s can be combined using plus operator, for example:
*
* @sample androidx.compose.animation.samples.SlideTransition
*
* __Note__: [fadeIn], [scaleIn] and [slideIn] do not affect the size of the [AnimatedVisibility]
* composable. In contrast, [expandIn] will grow the clip bounds to reveal the whole content. This
* will automatically animate other layouts out of the way, very much like [animateContentSize].
*
* @see fadeIn
* @see scaleIn
* @see slideIn
* @see slideInHorizontally
* @see slideInVertically
* @see expandIn
* @see expandHorizontally
* @see expandVertically
* @see AnimatedVisibility
*/
@Immutable
sealed class EnterTransition {
internal abstract val data: TransitionData
/**
* Combines different enter transitions. The order of the [EnterTransition]s being combined
* does not matter, as these [EnterTransition]s will start simultaneously. The order of
* applying transforms from these enter transitions (if defined) is: alpha and scale first,
* shrink or expand, then slide.
*
* @sample androidx.compose.animation.samples.FullyLoadedTransition
*
* @param enter another [EnterTransition] to be combined
*/
@Stable
operator fun plus(enter: EnterTransition): EnterTransition {
return EnterTransitionImpl(
TransitionData(
fade = data.fade ?: enter.data.fade,
slide = data.slide ?: enter.data.slide,
changeSize = data.changeSize ?: enter.data.changeSize,
scale = data.scale ?: enter.data.scale
)
)
}
override fun toString(): String =
if (this == None) {
"EnterTransition.None"
} else {
data.run {
"EnterTransition: \n" + "Fade - " + fade?.toString() + ",\nSlide - " +
slide?.toString() + ",\nShrink - " + changeSize?.toString() +
",\nScale - " + scale?.toString()
}
}
override fun equals(other: Any?): Boolean {
return other is EnterTransition && other.data == data
}
override fun hashCode(): Int = data.hashCode()
companion object {
/**
* This can be used when no enter transition is desired. It can be useful in cases where
* there are other forms of enter animation defined indirectly for an
* [AnimatedVisibility]. e.g.The children of the [AnimatedVisibility] have all defined
* their own [EnterTransition], or when the parent is fading in, etc.
*
* @see [ExitTransition.None]
*/
val None: EnterTransition = EnterTransitionImpl(TransitionData())
}
}
/**
* [ExitTransition] defines how an [AnimatedVisibility] Composable disappears on screen as it
* becomes not visible. The 4 categories of [ExitTransition] available are:
* 1. fade: [fadeOut]
* 2. scale: [scaleOut]
* 3. slide: [slideOut], [slideOutHorizontally], [slideOutVertically]
* 4. shrink: [shrinkOut], [shrinkHorizontally], [shrinkVertically]
*
* [ExitTransition.None] can be used when no exit transition is desired.
* Different [ExitTransition]s can be combined using plus operator, for example:
*
* @sample androidx.compose.animation.samples.SlideTransition
*
* __Note__: [fadeOut] and [slideOut] do not affect the size of the [AnimatedVisibility]
* composable. In contrast, [shrinkOut] (and [shrinkHorizontally], [shrinkVertically]) will shrink
* the clip bounds to reveal less and less of the content. This will automatically animate other
* layouts to fill in the space, very much like [animateContentSize].
*
* @see fadeOut
* @see scaleOut
* @see slideOut
* @see slideOutHorizontally
* @see slideOutVertically
* @see shrinkOut
* @see shrinkHorizontally
* @see shrinkVertically
* @see AnimatedVisibility
*/
@Immutable
sealed class ExitTransition {
internal abstract val data: TransitionData
/**
* Combines different exit transitions. The order of the [ExitTransition]s being combined
* does not matter, as these [ExitTransition]s will start simultaneously. The order of
* applying transforms from these exit transitions (if defined) is: alpha and scale first,
* shrink or expand, then slide.
*
* @sample androidx.compose.animation.samples.FullyLoadedTransition
*
* @param exit another [ExitTransition] to be combined.
*/
@Stable
operator fun plus(exit: ExitTransition): ExitTransition {
return ExitTransitionImpl(
TransitionData(
fade = data.fade ?: exit.data.fade,
slide = data.slide ?: exit.data.slide,
changeSize = data.changeSize ?: exit.data.changeSize,
scale = data.scale ?: exit.data.scale
)
)
}
override fun equals(other: Any?): Boolean {
return other is ExitTransition && other.data == data
}
override fun toString(): String =
if (this == None) {
"ExitTransition.None"
} else {
data.run {
"ExitTransition: \n" + "Fade - " + fade?.toString() + ",\nSlide - " +
slide?.toString() + ",\nShrink - " + changeSize?.toString() +
",\nScale - " + scale?.toString()
}
}
override fun hashCode(): Int = data.hashCode()
companion object {
/**
* This can be used when no built-in [ExitTransition] (i.e. fade/slide, etc) is desired for
* the [AnimatedVisibility], but rather the children are defining their own exit
* animation using the [Transition] scope.
*
* __Note:__ If [None] is used, and nothing is animating in the Transition<EnterExitState>
* scope that [AnimatedVisibility] provided, the content will be removed from
* [AnimatedVisibility] right away.
*
* @sample androidx.compose.animation.samples.AVScopeAnimateEnterExit
*/
val None: ExitTransition = ExitTransitionImpl(TransitionData())
}
}
/**
* This fades in the content of the transition, from the specified starting alpha (i.e.
* [initialAlpha]) to 1f, using the supplied [animationSpec]. [initialAlpha] defaults to 0f,
* and [spring] is used by default.
*
* @sample androidx.compose.animation.samples.FadeTransition
*
* @param animationSpec the [FiniteAnimationSpec] for this animation, [spring] by default
* @param initialAlpha the starting alpha of the enter transition, 0f by default
*/
@Stable
fun fadeIn(
animationSpec: FiniteAnimationSpec<Float> = spring(stiffness = Spring.StiffnessMediumLow),
initialAlpha: Float = 0f
): EnterTransition {
return EnterTransitionImpl(TransitionData(fade = Fade(initialAlpha, animationSpec)))
}
/**
* This fades out the content of the transition, from full opacity to the specified target alpha
* (i.e. [targetAlpha]), using the supplied [animationSpec]. By default, the content will be faded
* out to fully transparent (i.e. [targetAlpha] defaults to 0), and [animationSpec] uses
* [spring] by default.
*
* @sample androidx.compose.animation.samples.FadeTransition
*
* @param animationSpec the [FiniteAnimationSpec] for this animation, [spring] by default
* @param targetAlpha the target alpha of the exit transition, 0f by default
*/
@Stable
fun fadeOut(
animationSpec: FiniteAnimationSpec<Float> = spring(stiffness = Spring.StiffnessMediumLow),
targetAlpha: Float = 0f,
): ExitTransition {
return ExitTransitionImpl(TransitionData(fade = Fade(targetAlpha, animationSpec)))
}
/**
* This slides in the content of the transition, from a starting offset defined in [initialOffset]
* to `IntOffset(0, 0)`. The direction of the slide can be controlled by configuring the
* [initialOffset]. A positive x value means sliding from right to left, whereas a negative x
* value will slide the content to the right. Similarly positive and negative y values
* correspond to sliding up and down, respectively.
*
* If the sliding is only desired horizontally or vertically, instead of along both axis, consider
* using [slideInHorizontally] or [slideInVertically].
*
* [initialOffset] is a lambda that takes the full size of the content and returns an offset.
* This allows the offset to be defined proportional to the full size, or as an absolute value.
*
* @sample androidx.compose.animation.samples.SlideInOutSample
*
* @param animationSpec the animation used for the slide-in, [spring] by default.
* @param initialOffset a lambda that takes the full size of the content and returns the initial
* offset for the slide-in
*/
@Stable
fun slideIn(
animationSpec: FiniteAnimationSpec<IntOffset> =
spring(
stiffness = Spring.StiffnessMediumLow,
visibilityThreshold = IntOffset.VisibilityThreshold
),
initialOffset: (fullSize: IntSize) -> IntOffset,
): EnterTransition {
return EnterTransitionImpl(TransitionData(slide = Slide(initialOffset, animationSpec)))
}
/**
* This slides out the content of the transition, from an offset of `IntOffset(0, 0)` to the
* target offset defined in [targetOffset]. The direction of the slide can be controlled by
* configuring the [targetOffset]. A positive x value means sliding from left to right, whereas a
* negative x value would slide the content from right to left. Similarly, positive and negative y
* values correspond to sliding down and up, respectively.
*
* If the sliding is only desired horizontally or vertically, instead of along both axis, consider
* using [slideOutHorizontally] or [slideOutVertically].
*
* [targetOffset] is a lambda that takes the full size of the content and returns an offset.
* This allows the offset to be defined proportional to the full size, or as an absolute value.
*
* @sample androidx.compose.animation.samples.SlideInOutSample
*
* @param animationSpec the animation used for the slide-out, [spring] by default.
* @param targetOffset a lambda that takes the full size of the content and returns the target
* offset for the slide-out
*/
@Stable
fun slideOut(
animationSpec: FiniteAnimationSpec<IntOffset> =
spring(
stiffness = Spring.StiffnessMediumLow,
visibilityThreshold = IntOffset.VisibilityThreshold
),
targetOffset: (fullSize: IntSize) -> IntOffset,
): ExitTransition {
return ExitTransitionImpl(TransitionData(slide = Slide(targetOffset, animationSpec)))
}
/**
* This scales the content as it appears, from an initial scale (defined in [initialScale]) to 1f.
* [transformOrigin] defines the pivot point in terms of fraction of the overall size.
* [TransformOrigin.Center] by default. [scaleIn] can be used in combination with any other type
* of [EnterTransition] using the plus operator (e.g. `scaleIn() + slideInHorizontally()`)
*
* Note: Scale is applied __before__ slide. This means when using [slideIn]/[slideOut] with
* [scaleIn]/[scaleOut], the amount of scaling needs to be taken into account when sliding.
*
* The scaling will change the visual of the content, but will __not__ affect the layout size.
* [scaleIn] can be combined with [expandIn]/[expandHorizontally]/[expandVertically] to coordinate
* layout size change while scaling. For example:
* @sample androidx.compose.animation.samples.ScaledEnterExit
*
* @param animationSpec the animation used for the scale-out, [spring] by default.
* @param initialScale the initial scale for the enter transition, 0 by default.
* @param transformOrigin the pivot point in terms of fraction of the overall size. By default it's
* [TransformOrigin.Center].
*/
@Stable
@ExperimentalAnimationApi
fun scaleIn(
animationSpec: FiniteAnimationSpec<Float> = spring(stiffness = Spring.StiffnessMediumLow),
initialScale: Float = 0f,
transformOrigin: TransformOrigin = TransformOrigin.Center,
): EnterTransition {
return EnterTransitionImpl(
TransitionData(scale = Scale(initialScale, transformOrigin, animationSpec))
)
}
/**
* This scales the content of the exit transition, from 1f to the target scale defined in
* [targetScale]. [transformOrigin] defines the pivot point in terms of fraction of the overall
* size. By default it's [TransformOrigin.Center]. [scaleOut] can be used in combination with any
* other type of [ExitTransition] using the plus operator (e.g. `scaleOut() + fadeOut()`)
*
* Note: Scale is applied __before__ slide. This means when using [slideIn]/[slideOut] with
* [scaleIn]/[scaleOut], the amount of scaling needs to be taken into account when sliding.
*
* The scaling will change the visual of the content, but will __not__ affect the layout size.
* [scaleOut] can be combined with [shrinkOut]/[shrinkHorizontally]/[shrinkVertically] for
* coordinated layout size change animation. For example:
* @sample androidx.compose.animation.samples.ScaledEnterExit
*
* @param animationSpec the animation used for the slide-out, [spring] by default.
* @param targetScale the target scale for the exit transition, 0 by default.
* @param transformOrigin the pivot point in terms of fraction of the overall size. By default it's
* [TransformOrigin.Center].
*/
@Stable
@ExperimentalAnimationApi
fun scaleOut(
animationSpec: FiniteAnimationSpec<Float> = spring(stiffness = Spring.StiffnessMediumLow),
targetScale: Float = 0f,
transformOrigin: TransformOrigin = TransformOrigin.Center
): ExitTransition {
return ExitTransitionImpl(
TransitionData(scale = Scale(targetScale, transformOrigin, animationSpec))
)
}
/**
* This expands the clip bounds of the appearing content from the size returned from [initialSize]
* to the full size. [expandFrom] controls which part of the content gets revealed first. By
* default, the clip bounds animates from `IntSize(0, 0)` to full size, starting from revealing the
* bottom right corner (or bottom left corner in RTL layouts) of the content, to fully revealing
* the entire content as the size expands.
*
* __Note__: [expandIn] animates the bounds of the content. This bounds change will also result
* in the animation of other layouts that are dependent on this size.
*
* [initialSize] is a lambda that takes the full size of the content and returns an initial size of
* the bounds of the content. This allows not only absolute size, but also an initial size that
* is proportional to the content size.
*
* [clip] defines whether the content outside of the animated bounds should be clipped. By
* default, clip is set to true, which only shows content in the animated bounds.
*
* For expanding only horizontally or vertically, consider [expandHorizontally], [expandVertically].
*
* @sample androidx.compose.animation.samples.ExpandInShrinkOutSample
*
* @param animationSpec the animation used for the expanding animation, [spring] by default.
* @param expandFrom the starting point of the expanding bounds, [Alignment.BottomEnd] by default.
* @param clip whether the content outside of the animated bounds should be clipped, true by default
* @param initialSize the start size of the expanding bounds, returning `IntSize(0, 0)` by default.
*/
@Stable
fun expandIn(
animationSpec: FiniteAnimationSpec<IntSize> =
spring(
stiffness = Spring.StiffnessMediumLow,
visibilityThreshold = IntSize.VisibilityThreshold
),
expandFrom: Alignment = Alignment.BottomEnd,
clip: Boolean = true,
initialSize: (fullSize: IntSize) -> IntSize = { IntSize(0, 0) },
): EnterTransition {
return EnterTransitionImpl(
TransitionData(
changeSize = ChangeSize(expandFrom, initialSize, animationSpec, clip)
)
)
}
/**
* This shrinks the clip bounds of the disappearing content from the full size to the size returned
* from [targetSize]. [shrinkTowards] controls the direction of the bounds shrink animation. By
* default, the clip bounds animates from full size to `IntSize(0, 0)`, shrinking towards the
* the bottom right corner (or bottom left corner in RTL layouts) of the content.
*
* __Note__: [shrinkOut] animates the bounds of the content. This bounds change will also result
* in the animation of other layouts that are dependent on this size.
*
* [targetSize] is a lambda that takes the full size of the content and returns a target size of
* the bounds of the content. This allows not only absolute size, but also a target size that
* is proportional to the content size.
*
* [clip] defines whether the content outside of the animated bounds should be clipped. By
* default, clip is set to true, which only shows content in the animated bounds.
*
* For shrinking only horizontally or vertically, consider [shrinkHorizontally], [shrinkVertically].
*
* @sample androidx.compose.animation.samples.ExpandInShrinkOutSample
*
* @param animationSpec the animation used for the shrinking animation, [spring] by default.
* @param shrinkTowards the ending point of the shrinking bounds, [Alignment.BottomEnd] by default.
* @param clip whether the content outside of the animated bounds should be clipped, true by default
* @param targetSize returns the end size of the shrinking bounds, `IntSize(0, 0)` by default.
*/
@Stable
fun shrinkOut(
animationSpec: FiniteAnimationSpec<IntSize> =
spring(
stiffness = Spring.StiffnessMediumLow,
visibilityThreshold = IntSize.VisibilityThreshold
),
shrinkTowards: Alignment = Alignment.BottomEnd,
clip: Boolean = true,
targetSize: (fullSize: IntSize) -> IntSize = { IntSize(0, 0) },
): ExitTransition {
return ExitTransitionImpl(
TransitionData(
changeSize = ChangeSize(shrinkTowards, targetSize, animationSpec, clip)
)
)
}
/**
* This expands the clip bounds of the appearing content horizontally, from the width returned from
* [initialWidth] to the full width. [expandFrom] controls which part of the content gets revealed
* first. By default, the clip bounds animates from 0 to full width, starting from the end
* of the content, and expand to fully revealing the whole content.
*
* __Note__: [expandHorizontally] animates the bounds of the content. This bounds change will also
* result in the animation of other layouts that are dependent on this size.
*
* [initialWidth] is a lambda that takes the full width of the content and returns an initial width
* of the bounds of the content. This allows not only an absolute width, but also an initial width
* that is proportional to the content width.
*
* [clip] defines whether the content outside of the animated bounds should be clipped. By
* default, clip is set to true, which only shows content in the animated bounds.
*
* @sample androidx.compose.animation.samples.HorizontalTransitionSample
*
* @param animationSpec the animation used for the expanding animation, [spring] by default.
* @param expandFrom the starting point of the expanding bounds, [Alignment.End] by default.
* @param clip whether the content outside of the animated bounds should be clipped, true by default
* @param initialWidth the start width of the expanding bounds, returning 0 by default.
*/
@Stable
fun expandHorizontally(
animationSpec: FiniteAnimationSpec<IntSize> =
spring(
stiffness = Spring.StiffnessMediumLow,
visibilityThreshold = IntSize.VisibilityThreshold
),
expandFrom: Alignment.Horizontal = Alignment.End,
clip: Boolean = true,
initialWidth: (fullWidth: Int) -> Int = { 0 },
): EnterTransition {
return expandIn(animationSpec, expandFrom.toAlignment(), clip = clip) {
IntSize(initialWidth(it.width), it.height)
}
}
/**
* This expands the clip bounds of the appearing content vertically, from the height returned from
* [initialHeight] to the full height. [expandFrom] controls which part of the content gets revealed
* first. By default, the clip bounds animates from 0 to full height, revealing the bottom edge
* first, followed by the rest of the content.
*
* __Note__: [expandVertically] animates the bounds of the content. This bounds change will also
* result in the animation of other layouts that are dependent on this size.
*
* [initialHeight] is a lambda that takes the full height of the content and returns an initial
* height of the bounds of the content. This allows not only an absolute height, but also an initial
* height that is proportional to the content height.
*
* [clip] defines whether the content outside of the animated bounds should be clipped. By
* default, clip is set to true, which only shows content in the animated bounds.
*
* @sample androidx.compose.animation.samples.ExpandShrinkVerticallySample
*
* @param animationSpec the animation used for the expanding animation, [spring] by default.
* @param expandFrom the starting point of the expanding bounds, [Alignment.Bottom] by default.
* @param clip whether the content outside of the animated bounds should be clipped, true by default
* @param initialHeight the start height of the expanding bounds, returning 0 by default.
*/
@Stable
fun expandVertically(
animationSpec: FiniteAnimationSpec<IntSize> =
spring(
stiffness = Spring.StiffnessMediumLow,
visibilityThreshold = IntSize.VisibilityThreshold
),
expandFrom: Alignment.Vertical = Alignment.Bottom,
clip: Boolean = true,
initialHeight: (fullHeight: Int) -> Int = { 0 },
): EnterTransition {
return expandIn(animationSpec, expandFrom.toAlignment(), clip) {
IntSize(it.width, initialHeight(it.height))
}
}
/**
* This shrinks the clip bounds of the disappearing content horizontally, from the full width to
* the width returned from [targetWidth]. [shrinkTowards] controls the direction of the bounds
* shrink animation. By default, the clip bounds animates from full width to 0, shrinking towards
* the end of the content.
*
* __Note__: [shrinkHorizontally] animates the bounds of the content. This bounds change will also
* result in the animation of other layouts that are dependent on this size.
*
* [targetWidth] is a lambda that takes the full width of the content and returns a target width of
* the content. This allows not only absolute width, but also a target width that is proportional
* to the content width.
*
* [clip] defines whether the content outside of the animated bounds should be clipped. By
* default, clip is set to true, which only shows content in the animated bounds.
*
* @sample androidx.compose.animation.samples.HorizontalTransitionSample
*
* @param animationSpec the animation used for the shrinking animation, [spring] by default.
* @param shrinkTowards the ending point of the shrinking bounds, [Alignment.End] by default.
* @param clip whether the content outside of the animated bounds should be clipped, true by default
* @param targetWidth returns the end width of the shrinking bounds, 0 by default.
*/
@Stable
fun shrinkHorizontally(
animationSpec: FiniteAnimationSpec<IntSize> =
spring(
stiffness = Spring.StiffnessMediumLow,
visibilityThreshold = IntSize.VisibilityThreshold
),
shrinkTowards: Alignment.Horizontal = Alignment.End,
clip: Boolean = true,
targetWidth: (fullWidth: Int) -> Int = { 0 }
): ExitTransition {
// TODO: Support different animation types
return shrinkOut(animationSpec, shrinkTowards.toAlignment(), clip) {
IntSize(targetWidth(it.width), it.height)
}
}
/**
* This shrinks the clip bounds of the disappearing content vertically, from the full height to
* the height returned from [targetHeight]. [shrinkTowards] controls the direction of the bounds
* shrink animation. By default, the clip bounds animates from full height to 0, shrinking towards
* the bottom of the content.
*
* __Note__: [shrinkVertically] animates the bounds of the content. This bounds change will also
* result in the animation of other layouts that are dependent on this size.
*
* [targetHeight] is a lambda that takes the full height of the content and returns a target height
* of the content. This allows not only absolute height, but also a target height that is
* proportional to the content height.
*
* [clip] defines whether the content outside of the animated bounds should be clipped. By
* default, clip is set to true, which only shows content in the animated bounds.
*
* @sample androidx.compose.animation.samples.ExpandShrinkVerticallySample
*
* @param animationSpec the animation used for the shrinking animation, [spring] by default.
* @param shrinkTowards the ending point of the shrinking bounds, [Alignment.Bottom] by default.
* @param clip whether the content outside of the animated bounds should be clipped, true by default
* @param targetHeight returns the end height of the shrinking bounds, 0 by default.
*/
@Stable
fun shrinkVertically(
animationSpec: FiniteAnimationSpec<IntSize> =
spring(
stiffness = Spring.StiffnessMediumLow,
visibilityThreshold = IntSize.VisibilityThreshold
),
shrinkTowards: Alignment.Vertical = Alignment.Bottom,
clip: Boolean = true,
targetHeight: (fullHeight: Int) -> Int = { 0 },
): ExitTransition {
// TODO: Support different animation types
return shrinkOut(animationSpec, shrinkTowards.toAlignment(), clip) {
IntSize(it.width, targetHeight(it.height))
}
}
/**
* This slides in the content horizontally, from a starting offset defined in [initialOffsetX] to
* `0` **pixels**. The direction of the slide can be controlled by configuring the
* [initialOffsetX]. A positive value means sliding from right to left, whereas a negative
* value would slide the content from left to right.
*
* [initialOffsetX] is a lambda that takes the full width of the content and returns an
* offset. This allows the starting offset to be defined proportional to the full size, or as an
* absolute value. It defaults to return half of negative width, which would offset the content
* to the left by half of its width, and slide towards the right.
*
* @sample androidx.compose.animation.samples.SlideTransition
*
* @param animationSpec the animation used for the slide-in, [spring] by default.
* @param initialOffsetX a lambda that takes the full width of the content in pixels and returns the
* initial offset for the slide-in, by default it returns `-fullWidth/2`
*/
@Stable
fun slideInHorizontally(
animationSpec: FiniteAnimationSpec<IntOffset> =
spring(
stiffness = Spring.StiffnessMediumLow,
visibilityThreshold = IntOffset.VisibilityThreshold
),
initialOffsetX: (fullWidth: Int) -> Int = { -it / 2 },
): EnterTransition =
slideIn(
initialOffset = { IntOffset(initialOffsetX(it.width), 0) },
animationSpec = animationSpec
)
/**
* This slides in the content vertically, from a starting offset defined in [initialOffsetY] to `0`
* in **pixels**. The direction of the slide can be controlled by configuring the
* [initialOffsetY]. A positive initial offset means sliding up, whereas a negative value would
* slide the content down.
*
* [initialOffsetY] is a lambda that takes the full Height of the content and returns an
* offset. This allows the starting offset to be defined proportional to the full height, or as an
* absolute value. It defaults to return half of negative height, which would offset the content
* up by half of its Height, and slide down.
*
* @sample androidx.compose.animation.samples.FullyLoadedTransition
*
* @param animationSpec the animation used for the slide-in, [spring] by default.
* @param initialOffsetY a lambda that takes the full Height of the content and returns the
* initial offset for the slide-in, by default it returns `-fullHeight/2`
*/
@Stable
fun slideInVertically(
animationSpec: FiniteAnimationSpec<IntOffset> =
spring(
stiffness = Spring.StiffnessMediumLow,
visibilityThreshold = IntOffset.VisibilityThreshold
),
initialOffsetY: (fullHeight: Int) -> Int = { -it / 2 },
): EnterTransition =
slideIn(
initialOffset = { IntOffset(0, initialOffsetY(it.height)) },
animationSpec = animationSpec
)
/**
* This slides out the content horizontally, from 0 to a target offset defined in [targetOffsetX]
* in **pixels**. The direction of the slide can be controlled by configuring the
* [targetOffsetX]. A positive value means sliding to the right, whereas a negative
* value would slide the content towards the left.
*
* [targetOffsetX] is a lambda that takes the full width of the content and returns an
* offset. This allows the target offset to be defined proportional to the full size, or as an
* absolute value. It defaults to return half of negative width, which would slide the content to
* the left by half of its width.
*
* @sample androidx.compose.animation.samples.SlideTransition
*
* @param animationSpec the animation used for the slide-out, [spring] by default.
* @param targetOffsetX a lambda that takes the full width of the content and returns the
* initial offset for the slide-in, by default it returns `fullWidth/2`
*/
@Stable
fun slideOutHorizontally(
animationSpec: FiniteAnimationSpec<IntOffset> =
spring(
stiffness = Spring.StiffnessMediumLow,
visibilityThreshold = IntOffset.VisibilityThreshold
),
targetOffsetX: (fullWidth: Int) -> Int = { -it / 2 },
): ExitTransition =
slideOut(
targetOffset = { IntOffset(targetOffsetX(it.width), 0) },
animationSpec = animationSpec
)
/**
* This slides out the content vertically, from 0 to a target offset defined in [targetOffsetY]
* in **pixels**. The direction of the slide-out can be controlled by configuring the
* [targetOffsetY]. A positive target offset means sliding down, whereas a negative value would
* slide the content up.
*
* [targetOffsetY] is a lambda that takes the full Height of the content and returns an
* offset. This allows the target offset to be defined proportional to the full height, or as an
* absolute value. It defaults to return half of the negative height, which would slide the content
* up by half of its Height.
*
* @param animationSpec the animation used for the slide-out, [spring] by default.
* @param targetOffsetY a lambda that takes the full Height of the content and returns the
* target offset for the slide-out, by default it returns `fullHeight/2`
*/
@Stable
fun slideOutVertically(
animationSpec: FiniteAnimationSpec<IntOffset> =
spring(
stiffness = Spring.StiffnessMediumLow,
visibilityThreshold = IntOffset.VisibilityThreshold
),
targetOffsetY: (fullHeight: Int) -> Int = { -it / 2 },
): ExitTransition =
slideOut(
targetOffset = { IntOffset(0, targetOffsetY(it.height)) },
animationSpec = animationSpec
)
/*********************** Below are internal classes and methods ******************/
@Immutable
internal data class Fade(val alpha: Float, val animationSpec: FiniteAnimationSpec<Float>)
@Immutable
internal data class Slide(
val slideOffset: (fullSize: IntSize) -> IntOffset,
val animationSpec: FiniteAnimationSpec<IntOffset>
)
@Immutable
internal data class ChangeSize(
val alignment: Alignment,
val size: (fullSize: IntSize) -> IntSize = { IntSize(0, 0) },
val animationSpec: FiniteAnimationSpec<IntSize>,
val clip: Boolean = true
)
@Immutable
internal data class Scale(
val scale: Float,
val transformOrigin: TransformOrigin,
val animationSpec: FiniteAnimationSpec<Float>
)
@Immutable
private class EnterTransitionImpl(override val data: TransitionData) : EnterTransition()
@Immutable
private class ExitTransitionImpl(override val data: TransitionData) : ExitTransition()
private fun Alignment.Horizontal.toAlignment() =
when (this) {
Alignment.Start -> Alignment.CenterStart
Alignment.End -> Alignment.CenterEnd
else -> Alignment.Center
}
private fun Alignment.Vertical.toAlignment() =
when (this) {
Alignment.Top -> Alignment.TopCenter
Alignment.Bottom -> Alignment.BottomCenter
else -> Alignment.Center
}
@Immutable
internal data class TransitionData(
val fade: Fade? = null,
val slide: Slide? = null,
val changeSize: ChangeSize? = null,
val scale: Scale? = null
)
@Suppress("ModifierFactoryExtensionFunction", "ComposableModifierFactory")
@Composable
internal fun Transition<EnterExitState>.createModifier(
enter: EnterTransition,
exit: ExitTransition,
label: String
): Modifier {
// Generates up to 3 modifiers, one for each type of enter/exit transition in the order:
// slide then shrink/expand then alpha.
var modifier: Modifier = Modifier
modifier = modifier.slideInOut(
this,
rememberUpdatedState(enter.data.slide),
rememberUpdatedState(exit.data.slide),
label
).shrinkExpand(
this,
rememberUpdatedState(enter.data.changeSize),
rememberUpdatedState(exit.data.changeSize),
label
)
// Fade - it's important to put fade in the end. Otherwise fade will clip slide.
// We'll animate if at any point during the transition fadeIn/fadeOut becomes non-null. This
// would ensure the removal of fadeIn/Out amid a fade animation doesn't result in a jump.
var shouldAnimateAlpha by remember(this) { mutableStateOf(false) }
var shouldAnimateScale by remember(this) { mutableStateOf(false) }
if (currentState == targetState && !isSeeking) {
shouldAnimateAlpha = false
shouldAnimateScale = false
} else {
if (enter.data.fade != null || exit.data.fade != null) {
shouldAnimateAlpha = true
}
if (enter.data.scale != null || exit.data.scale != null) {
shouldAnimateScale = true
}
}
val alpha by if (shouldAnimateAlpha) {
animateFloat(
transitionSpec = {
when {
EnterExitState.PreEnter isTransitioningTo EnterExitState.Visible ->
enter.data.fade?.animationSpec ?: DefaultAlphaAndScaleSpring
EnterExitState.Visible isTransitioningTo EnterExitState.PostExit ->
exit.data.fade?.animationSpec ?: DefaultAlphaAndScaleSpring
else -> DefaultAlphaAndScaleSpring
}
},
label = remember { "$label alpha" }
) {
when (it) {
EnterExitState.Visible -> 1f
EnterExitState.PreEnter -> enter.data.fade?.alpha ?: 1f
EnterExitState.PostExit -> exit.data.fade?.alpha ?: 1f
}
}
} else {
DefaultAlpha
}
if (shouldAnimateScale) {
val scale by animateFloat(
transitionSpec = {
when {
EnterExitState.PreEnter isTransitioningTo EnterExitState.Visible ->
enter.data.scale?.animationSpec ?: DefaultAlphaAndScaleSpring
EnterExitState.Visible isTransitioningTo EnterExitState.PostExit ->
exit.data.scale?.animationSpec ?: DefaultAlphaAndScaleSpring
else -> DefaultAlphaAndScaleSpring
}
},
label = remember { "$label scale" }
) {
when (it) {
EnterExitState.Visible -> 1f
EnterExitState.PreEnter -> enter.data.scale?.scale ?: 1f
EnterExitState.PostExit -> exit.data.scale?.scale ?: 1f
}
}
val transformOriginWhenVisible =
if (currentState == EnterExitState.PreEnter) {
enter.data.scale?.transformOrigin ?: exit.data.scale?.transformOrigin
} else {
exit.data.scale?.transformOrigin ?: enter.data.scale?.transformOrigin
}
// Animate transform origin if there's any change. If scale is only defined for enter or
// exit, use the same transform origin for both.
val transformOrigin by animateValue(
TransformOriginVectorConverter,
label = "TransformOriginInterruptionHandling"
) {
when (it) {
EnterExitState.Visible -> transformOriginWhenVisible
EnterExitState.PreEnter ->
enter.data.scale?.transformOrigin ?: exit.data.scale?.transformOrigin
EnterExitState.PostExit ->
exit.data.scale?.transformOrigin ?: enter.data.scale?.transformOrigin
} ?: TransformOrigin.Center
}
modifier = modifier.graphicsLayer {
this.alpha = alpha
this.scaleX = scale
this.scaleY = scale
this.transformOrigin = transformOrigin
}
} else if (shouldAnimateAlpha) {
modifier = modifier.graphicsLayer {
this.alpha = alpha
}
}
return modifier
}
private val TransformOriginVectorConverter =
TwoWayConverter<TransformOrigin, AnimationVector2D>(
convertToVector = { AnimationVector2D(it.pivotFractionX, it.pivotFractionY) },
convertFromVector = { TransformOrigin(it.v1, it.v2) }
)
private val DefaultAlpha = mutableStateOf(1f)
private val DefaultAlphaAndScaleSpring = spring<Float>(stiffness = Spring.StiffnessMediumLow)
@Suppress("ModifierInspectorInfo")
private fun Modifier.slideInOut(
transition: Transition<EnterExitState>,
slideIn: State<Slide?>,
slideOut: State<Slide?>,
labelPrefix: String
): Modifier = composed {
// We'll animate if at any point during the transition slideIn/slideOut becomes non-null. This
// would ensure the removal of slideIn/Out amid a slide animation doesn't result in a jump.
var shouldAnimate by remember(transition) { mutableStateOf(false) }
if (transition.currentState == transition.targetState && !transition.isSeeking) {
shouldAnimate = false
} else {
if (slideIn.value != null || slideOut.value != null) {
shouldAnimate = true
}
}
if (shouldAnimate) {
val animation = transition.createDeferredAnimation(
IntOffset.VectorConverter,
remember { "$labelPrefix slide" }
)
val modifier = remember(transition) {
SlideModifier(animation, slideIn, slideOut)
}
this.then(modifier)
} else {
this
}
}
private val DefaultOffsetAnimationSpec = spring(
stiffness = Spring.StiffnessMediumLow, visibilityThreshold = IntOffset.VisibilityThreshold
)
private class SlideModifier(
val lazyAnimation: Transition<EnterExitState>.DeferredAnimation<IntOffset, AnimationVector2D>,
val slideIn: State<Slide?>,
val slideOut: State<Slide?>
) : LayoutModifierWithPassThroughIntrinsics() {
val transitionSpec: Transition.Segment<EnterExitState>.() -> FiniteAnimationSpec<IntOffset> =
{
when {
EnterExitState.PreEnter isTransitioningTo EnterExitState.Visible -> {
slideIn.value?.animationSpec ?: DefaultOffsetAnimationSpec
}
EnterExitState.Visible isTransitioningTo EnterExitState.PostExit -> {
slideOut.value?.animationSpec ?: DefaultOffsetAnimationSpec
}
else -> DefaultOffsetAnimationSpec
}
}
fun targetValueByState(targetState: EnterExitState, fullSize: IntSize): IntOffset {
val preEnter = slideIn.value?.slideOffset?.invoke(fullSize) ?: IntOffset.Zero
val postExit = slideOut.value?.slideOffset?.invoke(fullSize) ?: IntOffset.Zero
return when (targetState) {
EnterExitState.Visible -> IntOffset.Zero
EnterExitState.PreEnter -> preEnter
EnterExitState.PostExit -> postExit
}
}
override fun MeasureScope.measure(
measurable: Measurable,
constraints: Constraints
): MeasureResult {
val placeable = measurable.measure(constraints)
val measuredSize = IntSize(placeable.width, placeable.height)
return layout(placeable.width, placeable.height) {
val slideOffset = lazyAnimation.animate(
transitionSpec
) {
targetValueByState(it, measuredSize)
}
placeable.placeWithLayer(slideOffset.value)
}
}
}
@Suppress("ModifierInspectorInfo")
private fun Modifier.shrinkExpand(
transition: Transition<EnterExitState>,
expand: State<ChangeSize?>,
shrink: State<ChangeSize?>,
labelPrefix: String
): Modifier = composed {
// We'll animate if at any point during the transition shrink/expand becomes non-null. This
// would ensure the removal of shrink/expand amid a size change animation doesn't result in a
// jump.
var shouldAnimate by remember(transition) { mutableStateOf(false) }
if (transition.currentState == transition.targetState && !transition.isSeeking) {
shouldAnimate = false
} else {
if (expand.value != null || shrink.value != null) {
shouldAnimate = true
}
}
if (shouldAnimate) {
val alignment: State<Alignment?> = rememberUpdatedState(
with(transition.segment) {
EnterExitState.PreEnter isTransitioningTo EnterExitState.Visible
}.let {
if (it) {
expand.value?.alignment ?: shrink.value?.alignment
} else {
shrink.value?.alignment ?: expand.value?.alignment
}
}
)
val sizeAnimation = transition.createDeferredAnimation(
IntSize.VectorConverter,
remember { "$labelPrefix shrink/expand" }
)
val offsetAnimation = key(transition.currentState == transition.targetState) {
transition.createDeferredAnimation(
IntOffset.VectorConverter,
remember { "$labelPrefix InterruptionHandlingOffset" }
)
}
val expandShrinkModifier = remember(transition) {
ExpandShrinkModifier(
sizeAnimation,
offsetAnimation,
expand,
shrink,
alignment
)
}
if (transition.currentState == transition.targetState) {
expandShrinkModifier.currentAlignment = null
} else if (expandShrinkModifier.currentAlignment == null) {
expandShrinkModifier.currentAlignment = alignment.value ?: Alignment.TopStart
}
val disableClip = expand.value?.clip == false || shrink.value?.clip == false
this.then(if (disableClip) Modifier else Modifier.clipToBounds())
.then(expandShrinkModifier)
} else {
this
}
}
private val DefaultSizeAnimationSpec = spring(
stiffness = Spring.StiffnessMediumLow, visibilityThreshold = IntSize.VisibilityThreshold
)
private class ExpandShrinkModifier(
val sizeAnimation: Transition<EnterExitState>.DeferredAnimation<IntSize, AnimationVector2D>,
val offsetAnimation: Transition<EnterExitState>.DeferredAnimation<IntOffset,
AnimationVector2D>,
val expand: State<ChangeSize?>,
val shrink: State<ChangeSize?>,
val alignment: State<Alignment?>
) : LayoutModifierWithPassThroughIntrinsics() {
var currentAlignment: Alignment? = null
val sizeTransitionSpec: Transition.Segment<EnterExitState>.() -> FiniteAnimationSpec<IntSize> =
{
when {
EnterExitState.PreEnter isTransitioningTo EnterExitState.Visible ->
expand.value?.animationSpec
EnterExitState.Visible isTransitioningTo EnterExitState.PostExit ->
shrink.value?.animationSpec
else -> DefaultSizeAnimationSpec
} ?: DefaultSizeAnimationSpec
}
fun sizeByState(targetState: EnterExitState, fullSize: IntSize): IntSize {
val preEnterSize = expand.value?.let { it.size(fullSize) } ?: fullSize
val postExitSize = shrink.value?.let { it.size(fullSize) } ?: fullSize
return when (targetState) {
EnterExitState.Visible -> fullSize
EnterExitState.PreEnter -> preEnterSize
EnterExitState.PostExit -> postExitSize
}
}
// This offset is only needed when the alignment value changes during the shrink/expand
// animation. For example, if user specify an enter that expands from the left, and an exit
// that shrinks towards the right, the asymmetric enter/exit will be brittle to interruption.
// Hence the following offset animation to smooth over such interruption.
fun targetOffsetByState(targetState: EnterExitState, fullSize: IntSize): IntOffset =
when {
currentAlignment == null -> IntOffset.Zero
alignment.value == null -> IntOffset.Zero
currentAlignment == alignment.value -> IntOffset.Zero
else -> when (targetState) {
EnterExitState.Visible -> IntOffset.Zero
EnterExitState.PreEnter -> IntOffset.Zero
EnterExitState.PostExit -> shrink.value?.let {
val endSize = it.size(fullSize)
val targetOffset = alignment.value!!.align(
fullSize,
endSize,
LayoutDirection.Ltr
)
val currentOffset = currentAlignment!!.align(
fullSize,
endSize,
LayoutDirection.Ltr
)
targetOffset - currentOffset
} ?: IntOffset.Zero
}
}
override fun MeasureScope.measure(
measurable: Measurable,
constraints: Constraints
): MeasureResult {
val placeable = measurable.measure(constraints)
val measuredSize = IntSize(placeable.width, placeable.height)
val currentSize = sizeAnimation.animate(sizeTransitionSpec) {
sizeByState(it, measuredSize)
}.value
val offsetDelta = offsetAnimation.animate({ DefaultOffsetAnimationSpec }) {
targetOffsetByState(it, measuredSize)
}.value
val offset =
currentAlignment?.align(measuredSize, currentSize, LayoutDirection.Ltr)
?: IntOffset.Zero
return layout(currentSize.width, currentSize.height) {
placeable.place(offset.x + offsetDelta.x, offset.y + offsetDelta.y)
}
}
}
| apache-2.0 | ccfc205963840dd1b61268a56a70d2b7 | 41.521628 | 100 | 0.693675 | 4.671357 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/jobs/RetrieveRemoteAnnouncementsJob.kt | 1 | 17480 | package org.thoughtcrime.securesms.jobs
import androidx.core.os.LocaleListCompat
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.ObjectNode
import org.json.JSONObject
import org.signal.core.util.Hex
import org.signal.core.util.ThreadUtil
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.BuildConfig
import org.thoughtcrime.securesms.conversationlist.model.ConversationFilter
import org.thoughtcrime.securesms.database.MessageDatabase
import org.thoughtcrime.securesms.database.RemoteMegaphoneDatabase
import org.thoughtcrime.securesms.database.SignalDatabase
import org.thoughtcrime.securesms.database.model.RemoteMegaphoneRecord
import org.thoughtcrime.securesms.database.model.addButton
import org.thoughtcrime.securesms.database.model.addLink
import org.thoughtcrime.securesms.database.model.addStyle
import org.thoughtcrime.securesms.database.model.databaseprotos.BodyRangeList
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.jobmanager.Data
import org.thoughtcrime.securesms.jobmanager.Job
import org.thoughtcrime.securesms.jobmanager.impl.NetworkConstraint
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.notifications.v2.ConversationId
import org.thoughtcrime.securesms.providers.BlobProvider
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.releasechannel.ReleaseChannel
import org.thoughtcrime.securesms.s3.S3
import org.thoughtcrime.securesms.transport.RetryLaterException
import org.thoughtcrime.securesms.util.LocaleFeatureFlags
import org.whispersystems.signalservice.internal.ServiceResponse
import java.io.IOException
import java.lang.Integer.max
import java.security.MessageDigest
import java.util.Locale
import java.util.concurrent.TimeUnit
/**
* Retrieves and processes release channel messages.
*/
class RetrieveRemoteAnnouncementsJob private constructor(private val force: Boolean, parameters: Parameters) : BaseJob(parameters) {
companion object {
const val KEY = "RetrieveReleaseChannelJob"
private const val MANIFEST = "${S3.DYNAMIC_PATH}/release-notes/release-notes-v2.json"
private const val BASE_RELEASE_NOTE = "${S3.STATIC_PATH}/release-notes"
private const val KEY_FORCE = "force"
private val TAG = Log.tag(RetrieveRemoteAnnouncementsJob::class.java)
private val RETRIEVE_FREQUENCY = TimeUnit.DAYS.toMillis(3)
@JvmStatic
@JvmOverloads
fun enqueue(force: Boolean = false) {
if (!SignalStore.account().isRegistered) {
Log.i(TAG, "Not registered, skipping.")
return
}
if (!force && System.currentTimeMillis() < SignalStore.releaseChannelValues().nextScheduledCheck) {
Log.i(TAG, "Too soon to check for updated release notes")
return
}
val job = RetrieveRemoteAnnouncementsJob(
force,
Parameters.Builder()
.setQueue("RetrieveReleaseChannelJob")
.setMaxInstancesForFactory(1)
.setMaxAttempts(3)
.addConstraint(NetworkConstraint.KEY)
.build()
)
ApplicationDependencies.getJobManager()
.startChain(CreateReleaseChannelJob.create())
.then(job)
.enqueue()
}
}
override fun serialize(): Data = Data.Builder().putBoolean(KEY_FORCE, force).build()
override fun getFactoryKey(): String = KEY
override fun onFailure() = Unit
override fun onRun() {
if (!SignalStore.account().isRegistered) {
Log.i(TAG, "Not registered, skipping.")
return
}
val values = SignalStore.releaseChannelValues()
if (values.releaseChannelRecipientId == null) {
Log.w(TAG, "Release Channel recipient is null, this shouldn't happen, will try to create on next run")
return
}
if (!force && System.currentTimeMillis() < values.nextScheduledCheck) {
Log.i(TAG, "Too soon to check for updated release notes")
return
}
val manifestMd5: ByteArray? = S3.getObjectMD5(MANIFEST)
if (manifestMd5 == null) {
Log.i(TAG, "Unable to retrieve manifest MD5")
return
}
when {
values.highestVersionNoteReceived == 0 -> {
Log.i(TAG, "First check, saving code and skipping download")
values.highestVersionNoteReceived = BuildConfig.CANONICAL_VERSION_CODE
}
!force && MessageDigest.isEqual(manifestMd5, values.previousManifestMd5) -> {
Log.i(TAG, "Manifest has not changed since last fetch.")
}
else -> fetchManifest(manifestMd5)
}
values.previousManifestMd5 = manifestMd5
values.nextScheduledCheck = System.currentTimeMillis() + RETRIEVE_FREQUENCY
}
private fun fetchManifest(manifestMd5: ByteArray) {
Log.i(TAG, "Updating release notes to ${Hex.toStringCondensed(manifestMd5)}")
val allReleaseNotes: ReleaseNotes? = S3.getAndVerifyObject(MANIFEST, ReleaseNotes::class.java, manifestMd5).result.orElse(null)
if (allReleaseNotes != null) {
updateReleaseNotes(allReleaseNotes.announcements)
updateMegaphones(allReleaseNotes.megaphones ?: emptyList())
} else {
Log.w(TAG, "Unable to retrieve manifest json")
}
}
@Suppress("UsePropertyAccessSyntax")
private fun updateReleaseNotes(announcements: List<ReleaseNote>) {
val values = SignalStore.releaseChannelValues()
if (Recipient.resolved(values.releaseChannelRecipientId!!).isBlocked) {
Log.i(TAG, "Release channel is blocked, do not bother with updates")
values.highestVersionNoteReceived = announcements.mapNotNull { it.androidMinVersion?.toIntOrNull() }.maxOrNull() ?: values.highestVersionNoteReceived
return
}
if (!values.hasMetConversationRequirement) {
if ((SignalDatabase.threads.getArchivedConversationListCount(ConversationFilter.OFF) + SignalDatabase.threads.getUnarchivedConversationListCount(ConversationFilter.OFF)) < 6) {
Log.i(TAG, "User does not have enough conversations to show release channel")
values.nextScheduledCheck = System.currentTimeMillis() + RETRIEVE_FREQUENCY
return
} else {
values.hasMetConversationRequirement = true
}
}
val resolvedNotes: List<FullReleaseNote?> = announcements
.asSequence()
.filter {
val minVersion = it.androidMinVersion?.toIntOrNull()
if (minVersion != null) {
minVersion > values.highestVersionNoteReceived && minVersion <= BuildConfig.CANONICAL_VERSION_CODE
} else {
false
}
}
.filter { it.countries == null || LocaleFeatureFlags.shouldShowReleaseNote(it.uuid, it.countries) }
.sortedBy { it.androidMinVersion!!.toInt() }
.map { resolveReleaseNote(it) }
.toList()
if (resolvedNotes.any { it == null }) {
Log.w(TAG, "Some release notes did not resolve, aborting.")
throw RetryLaterException()
}
val threadId = SignalDatabase.threads.getOrCreateThreadIdFor(Recipient.resolved(values.releaseChannelRecipientId!!))
var highestVersion = values.highestVersionNoteReceived
var addedNewNotes = false
resolvedNotes
.filterNotNull()
.forEach { note ->
val body = "${note.translation.title}\n\n${note.translation.body}"
val bodyRangeList = BodyRangeList.newBuilder()
.addStyle(BodyRangeList.BodyRange.Style.BOLD, 0, note.translation.title.length)
if (note.releaseNote.link?.isNotEmpty() == true && note.translation.linkText?.isNotEmpty() == true) {
val linkIndex = body.indexOf(note.translation.linkText)
if (linkIndex != -1 && linkIndex + note.translation.linkText.length < body.length) {
bodyRangeList.addLink(note.releaseNote.link, linkIndex, note.translation.linkText.length)
}
}
if (note.releaseNote.ctaId?.isNotEmpty() == true && note.translation.callToActionText?.isNotEmpty() == true) {
bodyRangeList.addButton(note.translation.callToActionText, note.releaseNote.ctaId, body.lastIndex, 0)
}
ThreadUtil.sleep(5)
val insertResult: MessageDatabase.InsertResult? = ReleaseChannel.insertReleaseChannelMessage(
recipientId = values.releaseChannelRecipientId!!,
body = body,
threadId = threadId,
messageRanges = bodyRangeList.build(),
image = note.translation.image,
imageWidth = note.translation.imageWidth?.toIntOrNull() ?: 0,
imageHeight = note.translation.imageHeight?.toIntOrNull() ?: 0
)
if (insertResult != null) {
addedNewNotes = addedNewNotes || (note.releaseNote.includeBoostMessage ?: true)
SignalDatabase.attachments.getAttachmentsForMessage(insertResult.messageId)
.forEach { ApplicationDependencies.getJobManager().add(AttachmentDownloadJob(insertResult.messageId, it.attachmentId, false)) }
ApplicationDependencies.getMessageNotifier().updateNotification(context, ConversationId.forConversation(insertResult.threadId))
TrimThreadJob.enqueueAsync(insertResult.threadId)
highestVersion = max(highestVersion, note.releaseNote.androidMinVersion!!.toInt())
}
}
if (addedNewNotes) {
ThreadUtil.sleep(5)
SignalDatabase.sms.insertBoostRequestMessage(values.releaseChannelRecipientId!!, threadId)
}
values.highestVersionNoteReceived = highestVersion
}
private fun updateMegaphones(megaphones: List<RemoteMegaphone>) {
val resolvedMegaphones: List<FullRemoteMegaphone?> = megaphones
.asSequence()
.filter { it.androidMinVersion != null }
.map { resolveMegaphone(it) }
.toList()
if (resolvedMegaphones.any { it == null }) {
Log.w(TAG, "Some megaphones did not resolve, will retry later.")
throw RetryLaterException()
}
val manifestMegaphones: MutableSet<String> = mutableSetOf()
val existingMegaphones: Map<String, RemoteMegaphoneRecord> = SignalDatabase.remoteMegaphones.getAll().associateBy { it.uuid }
resolvedMegaphones
.filterNotNull()
.forEach { megaphone ->
val uuid = megaphone.remoteMegaphone.uuid
manifestMegaphones += uuid
if (existingMegaphones.contains(uuid)) {
SignalDatabase.remoteMegaphones.update(
uuid = uuid,
priority = megaphone.remoteMegaphone.priority,
countries = megaphone.remoteMegaphone.countries,
title = megaphone.translation.title,
body = megaphone.translation.body,
primaryActionText = megaphone.translation.primaryCtaText,
secondaryActionText = megaphone.translation.secondaryCtaText
)
} else {
val record = RemoteMegaphoneRecord(
uuid = uuid,
priority = megaphone.remoteMegaphone.priority,
countries = megaphone.remoteMegaphone.countries,
minimumVersion = megaphone.remoteMegaphone.androidMinVersion!!.toInt(),
doNotShowBefore = megaphone.remoteMegaphone.dontShowBeforeEpochSeconds?.let { TimeUnit.SECONDS.toMillis(it) } ?: 0,
doNotShowAfter = megaphone.remoteMegaphone.dontShowAfterEpochSeconds?.let { TimeUnit.SECONDS.toMillis(it) } ?: Long.MAX_VALUE,
showForNumberOfDays = megaphone.remoteMegaphone.showForNumberOfDays ?: 0,
conditionalId = megaphone.remoteMegaphone.conditionalId,
primaryActionId = RemoteMegaphoneRecord.ActionId.from(megaphone.remoteMegaphone.primaryCtaId),
secondaryActionId = RemoteMegaphoneRecord.ActionId.from(megaphone.remoteMegaphone.secondaryCtaId),
imageUrl = megaphone.translation.image,
title = megaphone.translation.title,
body = megaphone.translation.body,
primaryActionText = megaphone.translation.primaryCtaText,
secondaryActionText = megaphone.translation.secondaryCtaText,
primaryActionData = megaphone.remoteMegaphone.primaryCtaData?.takeIf { it is ObjectNode }?.let { JSONObject(it.toString()) },
secondaryActionData = megaphone.remoteMegaphone.secondaryCtaData?.takeIf { it is ObjectNode }?.let { JSONObject(it.toString()) }
)
SignalDatabase.remoteMegaphones.insert(record)
if (record.imageUrl != null) {
ApplicationDependencies.getJobManager().add(FetchRemoteMegaphoneImageJob(record.uuid, record.imageUrl))
}
}
}
val megaphonesToDelete = existingMegaphones
.filterKeys { !manifestMegaphones.contains(it) }
.filterValues { it.minimumVersion != RemoteMegaphoneDatabase.VERSION_FINISHED }
if (megaphonesToDelete.isNotEmpty()) {
Log.i(TAG, "Clearing ${megaphonesToDelete.size} stale megaphones ${megaphonesToDelete.keys}")
for ((uuid, megaphone) in megaphonesToDelete) {
if (megaphone.imageUri != null) {
BlobProvider.getInstance().delete(context, megaphone.imageUri)
}
SignalDatabase.remoteMegaphones.clear(uuid)
}
}
}
private fun resolveReleaseNote(releaseNote: ReleaseNote): FullReleaseNote? {
val potentialNoteUrls = "$BASE_RELEASE_NOTE/${releaseNote.uuid}".getLocaleUrls()
for (potentialUrl: String in potentialNoteUrls) {
val translationJson: ServiceResponse<TranslatedReleaseNote> = S3.getAndVerifyObject(potentialUrl, TranslatedReleaseNote::class.java)
if (translationJson.result.isPresent) {
return FullReleaseNote(releaseNote, translationJson.result.get())
} else if (translationJson.status != 404 && translationJson.executionError.orElse(null) !is S3.Md5FailureException) {
throw RetryLaterException()
}
}
return null
}
private fun resolveMegaphone(remoteMegaphone: RemoteMegaphone): FullRemoteMegaphone? {
val potentialNoteUrls = "$BASE_RELEASE_NOTE/${remoteMegaphone.uuid}".getLocaleUrls()
for (potentialUrl: String in potentialNoteUrls) {
val translationJson: ServiceResponse<TranslatedRemoteMegaphone> = S3.getAndVerifyObject(potentialUrl, TranslatedRemoteMegaphone::class.java)
if (translationJson.result.isPresent) {
return FullRemoteMegaphone(remoteMegaphone, translationJson.result.get())
} else if (translationJson.status != 404 && translationJson.executionError.orElse(null) !is S3.Md5FailureException) {
throw RetryLaterException()
}
}
return null
}
override fun onShouldRetry(e: Exception): Boolean {
return e is RetryLaterException || e is IOException
}
private fun String.getLocaleUrls(): List<String> {
val localeList: LocaleListCompat = LocaleListCompat.getDefault()
val potentialNoteUrls = mutableListOf<String>()
if (SignalStore.settings().language != "zz") {
potentialNoteUrls += "$this/${SignalStore.settings().language}.json"
}
for (index in 0 until localeList.size()) {
val locale: Locale = localeList.get(index) ?: continue
if (locale.language.isNotEmpty()) {
if (locale.country.isNotEmpty()) {
potentialNoteUrls += "$this/${locale.language}_${locale.country}.json"
}
potentialNoteUrls += "$this/${locale.language}.json"
}
}
potentialNoteUrls += "$this/en.json"
return potentialNoteUrls
}
data class FullReleaseNote(val releaseNote: ReleaseNote, val translation: TranslatedReleaseNote)
data class FullRemoteMegaphone(val remoteMegaphone: RemoteMegaphone, val translation: TranslatedRemoteMegaphone)
data class ReleaseNotes(@JsonProperty val announcements: List<ReleaseNote>, @JsonProperty val megaphones: List<RemoteMegaphone>?)
data class ReleaseNote(
@JsonProperty val uuid: String,
@JsonProperty val countries: String?,
@JsonProperty val androidMinVersion: String?,
@JsonProperty val link: String?,
@JsonProperty val ctaId: String?,
@JsonProperty val includeBoostMessage: Boolean?
)
data class RemoteMegaphone(
@JsonProperty val uuid: String,
@JsonProperty val priority: Long,
@JsonProperty val countries: String?,
@JsonProperty val androidMinVersion: String?,
@JsonProperty val dontShowBeforeEpochSeconds: Long?,
@JsonProperty val dontShowAfterEpochSeconds: Long?,
@JsonProperty val showForNumberOfDays: Long?,
@JsonProperty val conditionalId: String?,
@JsonProperty val primaryCtaId: String?,
@JsonProperty val secondaryCtaId: String?,
@JsonProperty val primaryCtaData: JsonNode?,
@JsonProperty val secondaryCtaData: JsonNode?
)
data class TranslatedReleaseNote(
@JsonProperty val uuid: String,
@JsonProperty val image: String?,
@JsonProperty val imageWidth: String?,
@JsonProperty val imageHeight: String?,
@JsonProperty val linkText: String?,
@JsonProperty val title: String,
@JsonProperty val body: String,
@JsonProperty val callToActionText: String?,
)
data class TranslatedRemoteMegaphone(
@JsonProperty val uuid: String,
@JsonProperty val image: String?,
@JsonProperty val title: String,
@JsonProperty val body: String,
@JsonProperty val primaryCtaText: String?,
@JsonProperty val secondaryCtaText: String?,
)
class Factory : Job.Factory<RetrieveRemoteAnnouncementsJob> {
override fun create(parameters: Parameters, data: Data): RetrieveRemoteAnnouncementsJob {
return RetrieveRemoteAnnouncementsJob(data.getBoolean(KEY_FORCE), parameters)
}
}
}
| gpl-3.0 | bba5e0120edaaa7a248ae3e9c4df5d2e | 40.323877 | 182 | 0.718535 | 4.383149 | false | false | false | false |
androidx/androidx | compose/ui/ui-text/src/androidMain/kotlin/androidx/compose/ui/text/platform/ActualParagraph.android.kt.kt | 3 | 3221 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("AndroidParagraph_androidKt")
package androidx.compose.ui.text.platform
import androidx.compose.ui.text.AndroidParagraph
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.Paragraph
import androidx.compose.ui.text.ParagraphIntrinsics
import androidx.compose.ui.text.Placeholder
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.ceilToInt
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.createFontFamilyResolver
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
@Suppress("DEPRECATION")
@Deprecated(
"Font.ResourceLoader is deprecated, instead pass FontFamily.Resolver",
replaceWith = ReplaceWith(
"ActualParagraph(text, style, spanStyles, placeholders, " +
"maxLines, ellipsis, width, density, fontFamilyResolver)"
),
)
internal actual fun ActualParagraph(
text: String,
style: TextStyle,
spanStyles: List<AnnotatedString.Range<SpanStyle>>,
placeholders: List<AnnotatedString.Range<Placeholder>>,
maxLines: Int,
ellipsis: Boolean,
width: Float,
density: Density,
@Suppress("DEPRECATION") resourceLoader: Font.ResourceLoader
): Paragraph = AndroidParagraph(
AndroidParagraphIntrinsics(
text = text,
style = style,
placeholders = placeholders,
spanStyles = spanStyles,
fontFamilyResolver = createFontFamilyResolver(resourceLoader),
density = density
),
maxLines,
ellipsis,
Constraints(maxWidth = width.ceilToInt())
)
internal actual fun ActualParagraph(
text: String,
style: TextStyle,
spanStyles: List<AnnotatedString.Range<SpanStyle>>,
placeholders: List<AnnotatedString.Range<Placeholder>>,
maxLines: Int,
ellipsis: Boolean,
constraints: Constraints,
density: Density,
fontFamilyResolver: FontFamily.Resolver
): Paragraph = AndroidParagraph(
AndroidParagraphIntrinsics(
text = text,
style = style,
placeholders = placeholders,
spanStyles = spanStyles,
fontFamilyResolver = fontFamilyResolver,
density = density
),
maxLines,
ellipsis,
constraints
)
internal actual fun ActualParagraph(
paragraphIntrinsics: ParagraphIntrinsics,
maxLines: Int,
ellipsis: Boolean,
constraints: Constraints
): Paragraph = AndroidParagraph(
paragraphIntrinsics as AndroidParagraphIntrinsics,
maxLines,
ellipsis,
constraints
)
| apache-2.0 | 1a25d71225edcdc0fab9c938bf060408 | 30.891089 | 75 | 0.737659 | 4.654624 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/new/tests/testData/newJ2k/issues/kt-19340.kt | 13 | 465 | package test.nullabilityOnClassBoundaries
class Item {
private var s1: String? = null
private var s2: String? = null
operator fun set(s1: String?, s2: String?) {
this.s1 = s1
this.s2 = s2
}
}
class Reader {
fun readItem(n: Int): Item {
val item = Item()
item[readString(n)] = null
return item
}
fun readString(n: Int): String? {
return if (n <= 0) null else Integer.toString(n)
}
}
| apache-2.0 | c56558a7f1de0c923fde09c5d835de73 | 20.136364 | 56 | 0.569892 | 3.419118 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/internal/ui/gridLayoutTestAction/SizeGroupPanel.kt | 8 | 1107 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal.ui.gridLayoutTestAction
import com.intellij.ui.dsl.gridLayout.GridLayout
import com.intellij.ui.dsl.gridLayout.builders.RowsGridBuilder
import javax.swing.JLabel
import javax.swing.JPanel
class SizeGroupPanel {
val panel = createTabPanel("Cells in same size groups should have the same sizes", createContent())
private fun createContent(): JPanel {
val result = JPanel(GridLayout())
val builder = RowsGridBuilder(result)
builder.label("Label")
.label("Label", widthGroup = "horiz1")
.row()
.label("Label a very very very very long label", widthGroup = "horiz1")
return result
}
private fun RowsGridBuilder.label(text: String, widthGroup: String? = null): RowsGridBuilder {
val lines = mutableListOf(text)
if (widthGroup != null) {
lines += "widthGroup = $widthGroup"
}
cell(JLabel(lines.joinToString("<br>", prefix = "<html>")),
widthGroup = widthGroup)
return this
}
}
| apache-2.0 | 487aeb3049411bebe5a94160918c4d7d | 31.558824 | 120 | 0.70822 | 4.241379 | false | false | false | false |
GunoH/intellij-community | java/idea-ui/testSrc/com/intellij/jarRepository/MavenRepoFixture.kt | 2 | 2168 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.jarRepository
import java.io.File
class MavenRepoFixture(private val myMavenRepo: File) {
fun addLibraryArtifact(group: String = "myGroup",
artifact: String = "myArtifact",
version: String = "1.0",
text: String = "Fake library artifact")
: String = File(myMavenRepo, "$group/$artifact/$version/$artifact-$version.jar")
.apply {
parentFile.mkdirs()
writeText(text)
}.name
fun addAnnotationsArtifact(group: String = "myGroup",
artifact: String = "myArtifact",
version: String)
: String = File(myMavenRepo, "$group/$artifact/$version/$artifact-$version-annotations.zip")
.apply {
parentFile.mkdirs()
writeText("Fake annotations artifact")
}.name
fun generateMavenMetadata(group: String, artifact: String) {
val files = listOf(File(myMavenRepo, "$group/$artifact/maven-metadata.xml"),
File(myMavenRepo, "$group/$artifact-annotations/maven-metadata.xml"))
for (metadata in files) {
metadata.parentFile.mkdirs()
val versionsList = metadata.parentFile
.listFiles()
.asSequence()
.filter { it.isDirectory }
.map { it.name }
.toList()
if (versionsList.isEmpty()) {
continue
}
val releaseVersion = versionsList.last()
metadata.writeText("""
|<?xml version="1.0" encoding="UTF-8"?>
|<metadata>
| <groupId>$group</groupId>
| <artifactId>$artifact</artifactId>
| <version>$releaseVersion</version>
| <versioning>
| <latest>$releaseVersion</latest>
| <release>$releaseVersion</release>
| <versions>
| ${versionsList.joinToString(separator = "\n") { "<version>$it</version>" }}
| </versions>
| <lastUpdated>20180809190315</lastUpdated>
| </versioning>
|</metadata>
""".trimMargin())
}
}
} | apache-2.0 | 344eeb2722c1f99ed02135badd6ac8bb | 32.890625 | 140 | 0.591328 | 4.310139 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/data/coroutineInfoDatas.kt | 2 | 3272 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.coroutine.data
import com.intellij.debugger.engine.JavaValue
import com.sun.jdi.ThreadReference
import org.jetbrains.kotlin.idea.debugger.coroutine.data.CoroutineInfoData.Companion.DEFAULT_COROUTINE_NAME
import org.jetbrains.kotlin.idea.debugger.coroutine.data.CoroutineInfoData.Companion.DEFAULT_COROUTINE_STATE
import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.mirror.MirrorOfCoroutineInfo
abstract class CoroutineInfoData(val descriptor: CoroutineDescriptor) {
abstract val stackTrace: List<CoroutineStackFrameItem>
abstract val creationStackTrace: List<CreationCoroutineStackFrameItem>
abstract val activeThread: ThreadReference?
val topFrameVariables: List<JavaValue> by lazy {
stackTrace.firstOrNull()?.spilledVariables ?: emptyList()
}
fun isSuspended() = descriptor.state == State.SUSPENDED
fun isCreated() = descriptor.state == State.CREATED
fun isRunning() = descriptor.state == State.RUNNING
companion object {
const val DEFAULT_COROUTINE_NAME = "coroutine"
const val DEFAULT_COROUTINE_STATE = "UNKNOWN"
}
}
class LazyCoroutineInfoData(
private val mirror: MirrorOfCoroutineInfo,
private val stackTraceProvider: CoroutineStackTraceProvider
) : CoroutineInfoData(CoroutineDescriptor.instance(mirror)) {
private val stackFrames: CoroutineStackTraceProvider.CoroutineStackFrames? by lazy {
stackTraceProvider.findStackFrames(mirror)
}
override val stackTrace by lazy {
stackFrames?.restoredStackFrames ?: emptyList()
}
override val creationStackTrace by lazy {
stackFrames?.creationStackFrames ?: emptyList()
}
override val activeThread = mirror.lastObservedThread
}
class CompleteCoroutineInfoData(
descriptor: CoroutineDescriptor,
override val stackTrace: List<CoroutineStackFrameItem>,
override val creationStackTrace: List<CreationCoroutineStackFrameItem>,
override val activeThread: ThreadReference? = null, // for suspended coroutines should be null
) : CoroutineInfoData(descriptor)
fun CoroutineInfoData.toCompleteCoroutineInfoData() =
when (this) {
is CompleteCoroutineInfoData -> this
else ->
CompleteCoroutineInfoData(
descriptor,
stackTrace,
creationStackTrace,
activeThread
)
}
data class CoroutineDescriptor(val name: String, val id: String, val state: State, val dispatcher: String?) {
fun formatName() =
"$name:$id"
companion object {
fun instance(mirror: MirrorOfCoroutineInfo): CoroutineDescriptor =
CoroutineDescriptor(
mirror.context?.name ?: DEFAULT_COROUTINE_NAME,
"${mirror.sequenceNumber}",
State.valueOf(mirror.state ?: DEFAULT_COROUTINE_STATE),
mirror.context?.dispatcher
)
}
}
enum class State {
RUNNING,
SUSPENDED,
CREATED,
UNKNOWN,
SUSPENDED_COMPLETING,
SUSPENDED_CANCELLING,
CANCELLED,
COMPLETED,
NEW
}
| apache-2.0 | ae4bdf74a708b832f246a070accbe03f | 33.442105 | 158 | 0.716687 | 5.152756 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/conventionNameCalls/ReplaceGetOrSetInspection.kt | 3 | 4324 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.conventionNameCalls
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.ReplaceGetOrSetInspectionUtils
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.intentions.calleeName
import org.jetbrains.kotlin.idea.intentions.isReceiverExpressionWithValue
import org.jetbrains.kotlin.idea.intentions.toResolvedCall
import org.jetbrains.kotlin.idea.util.calleeTextRangeInThis
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.util.isValidOperator
class ReplaceGetOrSetInspection : AbstractApplicabilityBasedInspection<KtDotQualifiedExpression>(
KtDotQualifiedExpression::class.java
) {
private fun FunctionDescriptor.isExplicitOperator(): Boolean {
return if (overriddenDescriptors.isEmpty())
containingDeclaration !is JavaClassDescriptor && isOperator
else
overriddenDescriptors.any { it.isExplicitOperator() }
}
override fun isApplicable(element: KtDotQualifiedExpression): Boolean {
if (!ReplaceGetOrSetInspectionUtils.looksLikeGetOrSetOperatorCall(element)) return false
val callExpression = element.callExpression ?: return false
val bindingContext = callExpression.analyze(BodyResolveMode.PARTIAL_WITH_CFA)
val resolvedCall = callExpression.getResolvedCall(bindingContext) ?: return false
if (!resolvedCall.isReallySuccess()) return false
val target = resolvedCall.resultingDescriptor as? FunctionDescriptor ?: return false
if (!target.isValidOperator() || target.name !in setOf(OperatorNameConventions.GET, OperatorNameConventions.SET)) return false
if (!element.isReceiverExpressionWithValue()) return false
return target.name != OperatorNameConventions.SET || !element.isUsedAsExpression(bindingContext)
}
override fun inspectionText(element: KtDotQualifiedExpression) = KotlinBundle.message("should.be.replaced.with.indexing")
override fun inspectionHighlightType(element: KtDotQualifiedExpression): ProblemHighlightType =
if ((element.toResolvedCall(BodyResolveMode.PARTIAL)?.resultingDescriptor as? FunctionDescriptor)?.isExplicitOperator() == true) {
ProblemHighlightType.GENERIC_ERROR_OR_WARNING
} else {
ProblemHighlightType.INFORMATION
}
override val defaultFixText: String get() = KotlinBundle.message("replace.get.or.set.call.with.indexing.operator")
override fun fixText(element: KtDotQualifiedExpression): String {
val callExpression = element.callExpression ?: return defaultFixText
val resolvedCall = callExpression.resolveToCall() ?: return defaultFixText
return KotlinBundle.message("replace.0.call.with.indexing.operator", resolvedCall.resultingDescriptor.name.asString())
}
override fun inspectionHighlightRangeInElement(element: KtDotQualifiedExpression) = element.calleeTextRangeInThis()
override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) {
ReplaceGetOrSetInspectionUtils.replaceGetOrSetWithPropertyAccessor(
element,
element.calleeName == OperatorNameConventions.SET.identifier,
editor
)
}
}
| apache-2.0 | 2aac2acea85298bcaadd4a1a7fd10437 | 53.05 | 158 | 0.794172 | 5.501272 | false | false | false | false |
busybusy/AnalyticsKit-Android | graylog-provider/src/main/kotlin/graylog_provider/GraylogProvider.kt | 2 | 6183 | /*
* Copyright 2017 - 2022 busybusy, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.busybusy.graylog_provider
import com.busybusy.analyticskit_android.AnalyticsEvent
import com.busybusy.analyticskit_android.AnalyticsKitProvider
import com.busybusy.analyticskit_android.AnalyticsKitProvider.PriorityFilter
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import java.io.IOException
import java.text.DecimalFormat
/**
* Initializes a new {@code GraylogProvider} object.
*
* @param client an initialized {@link OkHttpClient} instance
* @param graylogInputUrl the URL of the Graylog HTTP input to use. Example: {@code http://graylog.example.org:12202/gelf}
* @param graylogHostName the name of the host application that is sending events
* @property priorityFilter the {@code PriorityFilter} to use when evaluating events
*
* @author John Hunt on 6/28/17.
*/
class GraylogProvider constructor(
private val client: OkHttpClient,
private val graylogInputUrl: String,
graylogHostName: String,
private val priorityFilter: PriorityFilter = PriorityFilter { true },
) : AnalyticsKitProvider {
private val GELF_SPEC_VERSION = "1.1"
private val jsonizer: EventJsonizer = EventJsonizer(GELF_SPEC_VERSION, graylogHostName)
private val timedEvents: MutableMap<String, AnalyticsEvent> by lazy { mutableMapOf() }
private val eventTimes: MutableMap<String, Long> by lazy { mutableMapOf() }
var callbackListener: GraylogResponseListener? = null
/**
* Specifies the [GraylogResponseListener] that should listen for callbacks.
*
* @param callbackListener the instance that should be notified on each Graylog response
* @return the `GraylogProvider` instance (for builder-style convenience)
*/
fun setCallbackHandler(callbackListener: GraylogResponseListener): GraylogProvider {
this.callbackListener = callbackListener
return this
}
/**
* Returns the filter used to restrict events by priority.
*
* @return the [PriorityFilter] instance the provider is using to determine if an
* event of a given priority should be logged
*/
override fun getPriorityFilter(): PriorityFilter = priorityFilter
/**
* Sends the event using provider-specific code.
*
* @param event an instantiated event
*/
@Throws(IllegalStateException::class)
override fun sendEvent(event: AnalyticsEvent) {
if (event.isTimed()) { // Hang onto it until it is done
eventTimes[event.name()] = System.currentTimeMillis()
timedEvents[event.name()] = event
} else { // Send the event to the Graylog input
logFromJson(event.name(), event.hashCode(), jsonizer.getJsonBody(event))
}
}
/**
* End the timed event.
*
* @param timedEvent the event which has finished
*/
@Throws(IllegalStateException::class)
override fun endTimedEvent(timedEvent: AnalyticsEvent) {
val endTime = System.currentTimeMillis()
val startTime = eventTimes.remove(timedEvent.name())
val finishedEvent = timedEvents.remove(timedEvent.name())
if (startTime != null && finishedEvent != null) {
val durationSeconds = ((endTime - startTime) / 1_000).toDouble()
val df = DecimalFormat("#.###")
finishedEvent.putAttribute("event_duration", df.format(durationSeconds))
logFromJson(
finishedEvent.name(),
finishedEvent.hashCode(),
jsonizer.getJsonBody(finishedEvent)
)
} else {
error("Attempted ending an event that was never started (or was previously ended): ${timedEvent.name()}")
}
}
/**
* Logs a JSON payload to your Graylog instance.
*
* @param eventName the result of calling [AnalyticsEvent.name]
* @param eventHashCode the result of calling [AnalyticsEvent.hashCode]
* @param json the payload to send to the Graylog input
*/
private fun logFromJson(eventName: String, eventHashCode: Int, json: String) {
val jsonMediaType: MediaType = "application/json; charset=utf-8".toMediaType()
val body: RequestBody = json.toRequestBody(jsonMediaType)
val request: Request = Request.Builder()
.url(graylogInputUrl)
.post(body)
.build()
// Prevent the old NetworkOnMainThreadException by using async calls
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
providerCallback(GraylogResponse(420,
"An error occurred communicating with the Graylog server",
eventName,
eventHashCode,
json))
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
providerCallback(
GraylogResponse(
response.code,
response.message,
eventName,
eventHashCode,
json
)
)
}
fun providerCallback(graylogResponse: GraylogResponse) =
callbackListener?.onGraylogResponse(graylogResponse)
})
}
}
| apache-2.0 | caa2f4a8624d8f5d634a1e374694e98a | 38.890323 | 122 | 0.660036 | 4.789311 | false | false | false | false |
getsentry/raven-java | sentry-spring/src/test/kotlin/io/sentry/spring/SentryUserProviderEventProcessorTest.kt | 1 | 6550 | package io.sentry.spring
import com.nhaarman.mockitokotlin2.mock
import io.sentry.SentryEvent
import io.sentry.SentryOptions
import io.sentry.SentryTracer
import io.sentry.TransactionContext
import io.sentry.protocol.SentryTransaction
import io.sentry.protocol.User
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
class SentryUserProviderEventProcessorTest {
class Fixture {
val sentryTracer = SentryTracer(TransactionContext("", ""), mock())
fun getSut(isSendDefaultPii: Boolean = false, userProvider: () -> User?): SentryUserProviderEventProcessor {
val options = SentryOptions().apply {
setSendDefaultPii(isSendDefaultPii)
}
return SentryUserProviderEventProcessor(options, userProvider)
}
}
private val fixture = Fixture()
@Test
fun `when event user is null, provider user data is set`() {
val processor = fixture.getSut {
val user = User()
user.username = "john.doe"
user.id = "user-id"
user.ipAddress = "192.168.0.1"
user.email = "[email protected]"
user.others = mapOf("key" to "value")
user
}
val event = SentryEvent()
val result = processor.process(event, null)
assertNotNull(result)
assertNotNull(result.user) {
assertEquals("john.doe", it.username)
assertEquals("user-id", it.id)
assertEquals("192.168.0.1", it.ipAddress)
assertEquals("[email protected]", it.email)
assertEquals(mapOf("key" to "value"), it.others)
}
}
@Test
fun `when event user is empty, provider user data is set`() {
val processor = fixture.getSut {
val user = User()
user.username = "john.doe"
user.id = "user-id"
user.ipAddress = "192.168.0.1"
user.email = "[email protected]"
user.others = mapOf("key" to "value")
user
}
val event = SentryEvent()
event.user = User()
val result = processor.process(event, null)
assertNotNull(result)
assertNotNull(result.user) {
assertEquals("john.doe", it.username)
assertEquals("user-id", it.id)
assertEquals("192.168.0.1", it.ipAddress)
assertEquals("[email protected]", it.email)
assertEquals(mapOf("key" to "value"), it.others)
}
}
@Test
fun `when processor returns empty User, user data is not changed`() {
val processor = fixture.getSut {
val user = User()
user
}
val event = SentryEvent()
event.user = User().apply {
username = "jane.smith"
id = "jane-smith"
ipAddress = "192.168.0.3"
email = "[email protected]"
others = mapOf("key" to "value")
}
val result = processor.process(event, null)
assertNotNull(result)
assertNotNull(result.user) {
assertEquals("jane.smith", it.username)
assertEquals("jane-smith", it.id)
assertEquals("192.168.0.3", it.ipAddress)
assertEquals("[email protected]", it.email)
assertEquals(mapOf("key" to "value"), it.others)
}
}
@Test
fun `when processor returns null, user data is not changed`() {
val processor = fixture.getSut {
null
}
val event = SentryEvent()
event.user = User().apply {
username = "jane.smith"
id = "jane-smith"
ipAddress = "192.168.0.3"
email = "[email protected]"
others = mapOf("key" to "value")
}
val result = processor.process(event, null)
assertNotNull(result)
assertNotNull(result.user) {
assertEquals("jane.smith", it.username)
assertEquals("jane-smith", it.id)
assertEquals("192.168.0.3", it.ipAddress)
assertEquals("[email protected]", it.email)
assertEquals(mapOf("key" to "value"), it.others)
}
}
@Test
fun `merges user#others with existing user#others set on SentryEvent`() {
val processor = fixture.getSut {
val user = User()
user.others = mapOf("key" to "value")
user
}
val event = SentryEvent()
event.user = User().apply {
others = mapOf("new-key" to "new-value")
}
val result = processor.process(event, null)
assertNotNull(result)
assertNotNull(result.user) {
assertEquals(mapOf("key" to "value", "new-key" to "new-value"), it.others)
}
}
@Test
fun `when isSendDefaultPii is true and user is not set, user remains null`() {
val processor = fixture.getSut(isSendDefaultPii = true) {
null
}
val event = SentryEvent()
event.user = null
val result = processor.process(event, null)
assertNotNull(result)
assertNull(result.user)
}
@Test
fun `when isSendDefaultPii is true and user is set with custom ip address, user ip is unchanged`() {
val processor = fixture.getSut(isSendDefaultPii = true) {
null
}
val event = SentryEvent()
val user = User()
user.ipAddress = "192.168.0.1"
event.user = user
val result = processor.process(event, null)
assertNotNull(result)
assertNotNull(result.user) {
assertEquals(user.ipAddress, it.ipAddress)
}
}
@Test
fun `when isSendDefaultPii is true and user is set with {{auto}} ip address, user ip is set to null`() {
val processor = fixture.getSut(isSendDefaultPii = true) {
null
}
val event = SentryEvent()
val user = User()
user.ipAddress = "{{auto}}"
event.user = user
val result = processor.process(event, null)
assertNotNull(result)
assertNotNull(result.user) {
assertNull(it.ipAddress)
}
}
@Test
fun `User is set on transaction`() {
val processor = fixture.getSut(isSendDefaultPii = true) {
User()
}
val result = processor.process(SentryTransaction(fixture.sentryTracer), null)
assertNotNull(result.user)
}
}
| bsd-3-clause | 61d5d80d700e4fcd385ad0f0d3e0ae1c | 28.772727 | 116 | 0.571908 | 4.272668 | false | true | false | false |
liujoshua/BridgeAndroidSDK | sageresearch-app-sdk/src/main/java/org/sagebionetworks/research/sageresearch/dao/room/ResearchDatabase.kt | 1 | 13548 | package org.sagebionetworks.research.sageresearch.dao.room
import android.arch.persistence.room.Database
import android.arch.persistence.room.Room
import android.arch.persistence.room.RoomDatabase
import android.arch.persistence.room.TypeConverters
import android.content.Context
import org.sagebionetworks.research.sageresearch.util.SingletonWithParam
import javax.inject.Singleton
import android.arch.persistence.db.SupportSQLiteDatabase
import android.arch.persistence.room.migration.Migration
//
// Copyright © 2018 Sage Bionetworks. 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. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// 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.
//
@Database(entities = arrayOf(
ScheduledActivityEntity::class,
ReportEntity::class),
version = 2)
/**
* version 1 - ScheduleActivityEntity table created and added
* version 2 - ReportEntity table created and added
*/
@TypeConverters(EntityTypeConverters::class)
abstract class ResearchDatabase : RoomDatabase() {
companion object {
val migrations: Array<Migration> get() = arrayOf(
object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
val reportTable = "ReportEntity"
// Create the ReportEntity table
// This can be copy/pasted from "2.json" or whatever version database was created
database.execSQL("CREATE TABLE `$reportTable` " +
"(`primaryKey` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
"`identifier` TEXT, " +
"`data` TEXT, " +
"`dateTime` INTEGER, " +
"`localDate` TEXT, " +
"`needsSyncedToBridge` INTEGER)")
// If indexes are specified for a field name, they need to be added separately
database.execSQL(migrationAddIndex(reportTable, "identifier"))
database.execSQL(migrationAddIndex(reportTable, "dateTime"))
database.execSQL(migrationAddIndex(reportTable, "localDate"))
database.execSQL(migrationAddIndex(reportTable, "needsSyncedToBridge"))
}
})
/**
* @param tableName to add the index to
* @param fieldName to add the index to
* @return the SQL command to add an index to a field name in a table
*/
private fun migrationAddIndex(tableName: String, fieldName: String): String {
return "CREATE INDEX index_${tableName}_$fieldName ON $tableName ($fieldName)"
}
}
abstract fun scheduleDao(): ScheduledActivityEntityDao
abstract fun reportDao(): ReportEntityDao
}
internal class RoomSql {
/**
* Because all Room queries need to be verified at compile time, we cannot build dynamic queries based on state.
* This is where these constant string values come into play, as building blocks to form reliable Room queries.
* These originally came about to model re-usable query components like iOS' NSPredicates and CoreData.
*/
companion object RoomSqlConstants {
/**
* OP constants combing CONDITION constants
*/
private const val OP_AND = " AND "
private const val OP_OR = " OR "
/**
* DELETE constants delete tables
*/
const val SCHEDULE_DELETE = "DELETE FROM scheduledactivityentity"
const val REPORT_DELETE = "DELETE FROM reportentity"
const val REPORT_DELETE_WHERE = "DELETE FROM reportentity WHERE "
/**
* SELECT constants start off queries
*/
private const val SCHEDULE_SELECT = "SELECT * FROM scheduledactivityentity WHERE "
private const val REPORT_SELECT = "SELECT * FROM reportentity WHERE "
/**
* ORDER BY constants do sorting on queries
*/
private const val ORDER_BY_SCHEDULED_ON_OLDEST = " ORDER BY scheduledOn ASC"
private const val ORDER_BY_FINISHED = " ORDER BY finishedOn DESC"
// Multiple order bys will first sort by date, and then if any date is equal, then by primary key (most recently saved)
private const val ORDER_BY_REPORT_DATE = " ORDER BY localDate DESC, dateTime DESC, primaryKey DESC"
/**
* LIMIT constants restrict the number of db rows
*/
private const val LIMIT_1 = " LIMIT 1"
/**
* CONDITION constants need to be joined by AND or OR in the select statement
*/
private const val SCHEDULE_CONDITION_GUID = "guid = :guid"
private const val SCHEDULE_CONDITION_ACTIVITY_GROUP_ID =
"(activity_task_identifier IN (:activityGroup) OR " +
"activity_survey_identifier IN (:activityGroup) OR " +
"activity_compound_taskIdentifier IN (:activityGroup))"
private const val SCHEDULE_CONDITION_EXCLUDE_ACTIVITY_GROUP_ID =
"((activity_task_identifier IS NULL OR activity_task_identifier NOT IN (:activityGroup)) AND " +
"(activity_survey_identifier IS NULL OR activity_survey_identifier NOT IN (:activityGroup)) AND " +
"(activity_compound_taskIdentifier IS NULL OR activity_compound_taskIdentifier NOT IN (:activityGroup)))"
private const val SCHEDULE_CONDITION_EXCLUDE_SURVEY_GROUP_ID =
"(activity_survey_identifier IS NOT NULL AND activity_survey_identifier NOT IN (:surveyGroup))"
private const val SCHEDULE_CONDITION_NOT_FINISHED = "(finishedOn IS NULL)"
private const val SCHEDULE_CONDITION_FINISHED = "(finishedOn IS NOT NULL)"
private const val SCHEDULE_CONDITION_FINISHED_BETWEEN = "(finishedOn BETWEEN :finishedStart AND :finishedEnd)"
private const val SCHEDULE_CONDITION_FINISHED_BETWEEN_OR_NULL =
"($SCHEDULE_CONDITION_NOT_FINISHED$OP_OR$SCHEDULE_CONDITION_FINISHED_BETWEEN)"
// Room doesn't have boolean type and maps true = 1 and false = 0
private const val SCHEDULE_CONDITION_NEEDS_SYNCED_TO_BRIDGE =
"(needsSyncedToBridge IS NOT NULL AND needsSyncedToBridge = 1)"
private const val SCHEDULE_CONDITION_NO_EXPIRES_DATE = "(expiresOn IS NULL)"
private const val SCHEDULE_CONDITION_HAS_EXPIRES_DATE = "(expiresOn IS NOT NULL)"
private const val SCHEDULE_CONDITION_EXPIRES_BETWEEN = "(expiresOn BETWEEN :start AND :end)"
private const val SCHEDULE_CONDITION_EXPIRES_BETWEEN_OR_NULL =
"($SCHEDULE_CONDITION_NO_EXPIRES_DATE$OP_OR$SCHEDULE_CONDITION_EXPIRES_BETWEEN)"
private const val SCHEDULE_CONDITION_AVAILABLE_DATE =
"((:date BETWEEN scheduledOn AND expiresOn) OR " +
"(expiresOn IS NULL AND :date >= scheduledOn))"
private const val SCHEDULE_CONDITION_BETWEEN_DATES =
"(" + SCHEDULE_CONDITION_FINISHED_BETWEEN_OR_NULL + OP_AND +
SCHEDULE_CONDITION_EXPIRES_BETWEEN_OR_NULL + OP_AND +
"(scheduledOn <= :end)" + ")"
private const val REPORT_CONDITION_REPORT_IDENTIFIER = "(identifier = :reportIdentifier)"
private const val REPORT_CONDITION_LOCAL_DATE_NOT_NULL = "(localDate IS NOT NULL)"
private const val REPORT_CONDITION_LOCAL_DATE_BETWEEN = "(localDate BETWEEN :start AND :end)"
private const val REPORT_CONDITION_DATE_TIME_NOT_NULL = "(dateTime IS NOT NULL)"
private const val REPORT_CONDITION_DATE_TIME_BETWEEN = "(dateTime BETWEEN :start AND :end)"
const val REPORTS_CONDITION_BETWEEN_DATE_TIME_WITH_IDENTIFIER =
REPORT_CONDITION_REPORT_IDENTIFIER + OP_AND +
REPORT_CONDITION_DATE_TIME_NOT_NULL + OP_AND + REPORT_CONDITION_DATE_TIME_BETWEEN
const val REPORTS_CONDITION_BETWEEN_LOCAL_DATE_WITH_IDENTIFIER =
REPORT_CONDITION_REPORT_IDENTIFIER + OP_AND +
REPORT_CONDITION_LOCAL_DATE_NOT_NULL + OP_AND + REPORT_CONDITION_LOCAL_DATE_BETWEEN
// Room doesn't have boolean type and maps true = 1 and false = 0
private const val REPORT_CONDITION_NEEDS_SYNCED_TO_BRIDGE =
"(needsSyncedToBridge IS NOT NULL AND needsSyncedToBridge = 1)"
/**
* QUERY constants are full Room queries
*/
const val SCHEDULE_QUERY_ALL = "SELECT * FROM scheduledactivityentity"
const val REPORT_QUERY_ALL = "SELECT * FROM reportentity"
const val SCHEDULE_QUERY_SELECT_GUID =
SCHEDULE_SELECT + SCHEDULE_CONDITION_GUID
const val SCHEDULE_QUERY_SELECT_ACTIVITY_GROUP =
SCHEDULE_SELECT + SCHEDULE_CONDITION_ACTIVITY_GROUP_ID
const val SCHEDULE_QUERY_SELECT_AVAILABLE_DATE =
SCHEDULE_SELECT + SCHEDULE_CONDITION_AVAILABLE_DATE
const val SCHEDULE_QUERY_SELECT_NOT_FINISHED_AVAILABLE_DATE =
SCHEDULE_SELECT + SCHEDULE_CONDITION_AVAILABLE_DATE + OP_AND + SCHEDULE_CONDITION_NOT_FINISHED
const val SCHEDULE_QUERY_SELECT_ACTIVITY_GROUP_AVAILABLE_DATE =
SCHEDULE_SELECT + SCHEDULE_CONDITION_AVAILABLE_DATE + OP_AND + SCHEDULE_CONDITION_ACTIVITY_GROUP_ID
const val SCHEDULE_QUERY_SELECT_ACTIVITY_GROUP_BETWEEN_DATE_UNFINISHED_OR_FINISHED_BETWEEN =
SCHEDULE_SELECT + SCHEDULE_CONDITION_ACTIVITY_GROUP_ID + OP_AND + SCHEDULE_CONDITION_BETWEEN_DATES
const val SCHEDULE_QUERY_ACTIVITY_GROUP_FINISHED_BETWEEN =
SCHEDULE_SELECT + SCHEDULE_CONDITION_ACTIVITY_GROUP_ID +
OP_AND + SCHEDULE_CONDITION_FINISHED + OP_AND + SCHEDULE_CONDITION_FINISHED_BETWEEN
const val SCHEDULE_QUERY_EXCLUDE_ACTIVITY_GROUP_FINISHED_BETWEEN =
SCHEDULE_SELECT + SCHEDULE_CONDITION_EXCLUDE_ACTIVITY_GROUP_ID +
OP_AND + SCHEDULE_CONDITION_FINISHED + OP_AND + SCHEDULE_CONDITION_FINISHED_BETWEEN
const val SCHEDULE_QUERY_EXCLUDE_SURVEY_GROUP_UNFINISHED_AVAILABLE_DATE =
SCHEDULE_SELECT + SCHEDULE_CONDITION_EXCLUDE_SURVEY_GROUP_ID +
OP_AND + SCHEDULE_CONDITION_NOT_FINISHED + OP_AND + SCHEDULE_CONDITION_AVAILABLE_DATE
const val SCHEDULE_MOST_RECENT_FINISHED_ACTIVITY =
SCHEDULE_SELECT + SCHEDULE_CONDITION_ACTIVITY_GROUP_ID + OP_AND +
SCHEDULE_CONDITION_FINISHED + ORDER_BY_FINISHED + LIMIT_1
const val SCHEDULE_OLDEST_ACTIVITY =
SCHEDULE_SELECT + SCHEDULE_CONDITION_ACTIVITY_GROUP_ID +
ORDER_BY_SCHEDULED_ON_OLDEST + LIMIT_1
const val SCHEDULE_ACTIVITIES_THAT_NEED_SYNCED =
SCHEDULE_SELECT + SCHEDULE_CONDITION_NEEDS_SYNCED_TO_BRIDGE
const val SELECT_REPORTS_BETWEEN_DATE_TIME_WITH_IDENTIFIER =
REPORT_SELECT + REPORTS_CONDITION_BETWEEN_DATE_TIME_WITH_IDENTIFIER
const val SELECT_REPORTS_BETWEEN_LOCAL_DATE_WITH_IDENTIFIER =
REPORT_SELECT + REPORTS_CONDITION_BETWEEN_LOCAL_DATE_WITH_IDENTIFIER
const val SELECT_REPORTS_BETWEEN_LOCAL_DATE_WITH_IDENTIFIER_REMOVE =
REPORT_SELECT + REPORTS_CONDITION_BETWEEN_LOCAL_DATE_WITH_IDENTIFIER + ORDER_BY_REPORT_DATE
const val DELETE_REPORTS_BETWEEN_DATE_TIME_WITH_IDENTIFIER =
REPORT_DELETE_WHERE + REPORTS_CONDITION_BETWEEN_DATE_TIME_WITH_IDENTIFIER
const val DELETE_REPORTS_BETWEEN_LOCAL_DATE_WITH_IDENTIFIER =
REPORT_DELETE_WHERE + REPORTS_CONDITION_BETWEEN_LOCAL_DATE_WITH_IDENTIFIER
const val REPORTS_THAT_NEED_SYNCED =
REPORT_SELECT + REPORT_CONDITION_NEEDS_SYNCED_TO_BRIDGE
const val SELECT_MOST_RECENT_REPORT_WITH_DATE_IDENTIFIER =
REPORT_SELECT + REPORT_CONDITION_REPORT_IDENTIFIER + ORDER_BY_REPORT_DATE + LIMIT_1
}
} | apache-2.0 | 853d166686b4249075673cc370353dde | 50.124528 | 127 | 0.666052 | 4.730098 | false | false | false | false |
dodyg/Kotlin101 | src/Functions/Infix/Infix.kt | 1 | 546 | package Functions.Infix
public fun main(args : Array<String>) {
//using a function
val say = "Hello " add "world" //infix function call
println(say)
val say2 = "Hello ".add("world 2")
println(say2)
//using a method
val hello = HelloWorld()
var say3 = hello say "world 3"
println(say3)
var say4 = hello.say("world 4")
println(say4)
}
infix fun String.add(more : String) : String = this + more
class HelloWorld() {
infix fun say(more : String) : String {
return "Hello " + more
}
}
| bsd-3-clause | 06d157781a9351b67f3d636b49f10679 | 20 | 58 | 0.60989 | 3.477707 | false | false | false | false |
breadwallet/breadwallet-android | app/src/main/java/com/breadwallet/tools/animation/SlideDetector.kt | 1 | 3185 | /**
* BreadWallet
*
* Created by Drew Carlson <[email protected]> on 9/25/19.
* Copyright (c) 2019 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.tools.animation
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.view.MotionEvent
import android.view.View
import android.view.animation.OvershootInterpolator
import com.bluelinelabs.conductor.Router
@Suppress("MagicNumber")
class SlideDetector(private val root: View) : View.OnTouchListener {
constructor(router: Router, root: View) : this(root) {
this.router = router
}
private var router: Router? = null
private var origY: Float = 0f
private var dY: Float = 0f
override fun onTouch(v: View, event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
origY = root.y
dY = root.y - event.rawY
}
MotionEvent.ACTION_MOVE -> if (event.rawY + dY > origY)
root.animate()
.y(event.rawY + dY)
.setDuration(0)
.start()
MotionEvent.ACTION_UP -> if (root.y > origY + root.height / 5) {
root.animate()
.y((root.height * 2).toFloat())
.setDuration(200)
.setInterpolator(OvershootInterpolator(0.5f))
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
super.onAnimationEnd(animation)
removeCurrentView()
}
})
.start()
} else {
root.animate()
.y(origY)
.setDuration(100)
.setInterpolator(OvershootInterpolator(0.5f))
.start()
}
else -> return false
}
return true
}
private fun removeCurrentView() {
router?.popCurrentController()
}
}
| mit | 25212c0399bf88c89a15c07c6590c4b1 | 36.916667 | 80 | 0.614129 | 4.840426 | false | false | false | false |
fossasia/rp15 | app/src/main/java/org/fossasia/openevent/general/notification/NotificationViewModel.kt | 1 | 3216 | package org.fossasia.openevent.general.notification
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.auth.AuthHolder
import org.fossasia.openevent.general.common.SingleLiveEvent
import org.fossasia.openevent.general.data.Network
import org.fossasia.openevent.general.data.Resource
import org.fossasia.openevent.general.utils.extensions.withDefaultSchedulers
import timber.log.Timber
class NotificationViewModel(
private val notificationService: NotificationService,
private val authHolder: AuthHolder,
private val network: Network,
private val resource: Resource
) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
private val mutableNotifications = MutableLiveData<List<Notification>>()
val notifications: LiveData<List<Notification>> = mutableNotifications
private val mutableProgress = MutableLiveData<Boolean>()
val progress: LiveData<Boolean> = mutableProgress
private val mutableNoInternet = SingleLiveEvent<Boolean>()
val noInternet: LiveData<Boolean> = mutableNoInternet
private val mutableError = SingleLiveEvent<String>()
val error: LiveData<String> = mutableError
fun getId() = authHolder.getId()
fun isLoggedIn() = authHolder.isLoggedIn()
fun getNotifications(showAll: Boolean) {
if (!isConnected()) {
return
}
compositeDisposable += notificationService.getNotifications(getId())
.withDefaultSchedulers()
.doOnSubscribe {
mutableProgress.value = true
}.doFinally {
mutableProgress.value = false
}.subscribe({ list ->
if (!showAll) {
mutableNotifications.value = list.filter {
!it.isRead
}
} else
mutableNotifications.value = list
Timber.d("Notification retrieve successful")
}, {
mutableError.value = resource.getString(R.string.msg_failed_to_load_notification)
Timber.d(it, resource.getString(R.string.msg_failed_to_load_notification))
})
}
fun updateReadStatus(notifications: List<Notification>) {
if (!isConnected() || notifications.isEmpty())
return
notifications.forEach { notification ->
if (notification.isRead)
return@forEach
notification.isRead = true
compositeDisposable += notificationService.updateNotification(notification)
.withDefaultSchedulers()
.subscribe({
Timber.d("Updated notification ${it.id}")
}, {
Timber.d(it, "Failed to update notification ${notification.id}")
})
}
}
fun isConnected(): Boolean {
val isConnected = network.isNetworkConnected()
mutableNoInternet.value = !isConnected
return isConnected
}
}
| apache-2.0 | de9794a7e32d867320206c64c86deb3c | 35.965517 | 97 | 0.658271 | 5.573657 | false | false | false | false |
InflationX/ViewPump | viewpump/src/main/java/io/github/inflationx/viewpump/InflateRequest.kt | 1 | 1966 | package io.github.inflationx.viewpump
import android.content.Context
import android.util.AttributeSet
import android.view.View
data class InflateRequest(
@get:JvmName("name")
val name: String,
@get:JvmName("context")
val context: Context,
@get:JvmName("attrs")
val attrs: AttributeSet? = null,
@get:JvmName("parent")
val parent: View? = null,
@get:JvmName("fallbackViewCreator")
val fallbackViewCreator: FallbackViewCreator
) {
fun toBuilder(): Builder {
return Builder(this)
}
class Builder {
private var name: String? = null
private var context: Context? = null
private var attrs: AttributeSet? = null
private var parent: View? = null
private var fallbackViewCreator: FallbackViewCreator? = null
internal constructor()
internal constructor(request: InflateRequest) {
this.name = request.name
this.context = request.context
this.attrs = request.attrs
this.parent = request.parent
this.fallbackViewCreator = request.fallbackViewCreator
}
fun name(name: String) = apply {
this.name = name
}
fun context(context: Context) = apply {
this.context = context
}
fun attrs(attrs: AttributeSet?) = apply {
this.attrs = attrs
}
fun parent(parent: View?) = apply {
this.parent = parent
}
fun fallbackViewCreator(fallbackViewCreator: FallbackViewCreator) = apply {
this.fallbackViewCreator = fallbackViewCreator
}
fun build() =
InflateRequest(name = name ?: throw IllegalStateException("name == null"),
context = context ?: throw IllegalStateException("context == null"),
attrs = attrs,
parent = parent,
fallbackViewCreator = fallbackViewCreator ?: throw IllegalStateException("fallbackViewCreator == null")
)
}
companion object {
@JvmStatic
fun builder(): Builder {
return Builder()
}
}
}
| apache-2.0 | 5de6205e90e718481d0a40d95c0bb67f | 24.532468 | 115 | 0.655646 | 4.437923 | false | false | false | false |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/view/SoftButtonActionArrayFragment.kt | 1 | 8655 | /*
* Copyright (C) 2017-2019 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.legacy.action.view
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.commit
import androidx.fragment.app.setFragmentResultListener
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.snackbar.Snackbar
import jp.hazuki.yuzubrowser.legacy.R
import jp.hazuki.yuzubrowser.legacy.action.ActionIconMap
import jp.hazuki.yuzubrowser.legacy.action.ActionManager
import jp.hazuki.yuzubrowser.legacy.action.ActionNameMap
import jp.hazuki.yuzubrowser.legacy.action.SoftButtonActionArrayManagerBase
import jp.hazuki.yuzubrowser.legacy.action.manager.SoftButtonActionArrayFile
import jp.hazuki.yuzubrowser.legacy.action.manager.SoftButtonActionFile
import jp.hazuki.yuzubrowser.legacy.utils.view.recycler.RecyclerFabFragment
import jp.hazuki.yuzubrowser.ui.dialog.DeleteDialogCompat
import jp.hazuki.yuzubrowser.ui.extensions.applyIconColor
import jp.hazuki.yuzubrowser.ui.widget.recycler.ArrayRecyclerAdapter
import jp.hazuki.yuzubrowser.ui.widget.recycler.OnRecyclerListener
class SoftButtonActionArrayFragment : RecyclerFabFragment(), OnRecyclerListener, DeleteDialogCompat.OnDelete {
private val activityViewModel by activityViewModels<SoftButtonActionViewModel> {
SoftButtonActionViewModel.Factory(
ActionNameMap(resources),
ActionIconMap(resources)
)
}
private var mActionType: Int = 0
private var mActionId: Int = 0
private lateinit var actionArray: SoftButtonActionArrayFile
private lateinit var actionManager: SoftButtonActionArrayManagerBase
private lateinit var adapter: ActionListAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setFragmentResultListener(SoftButtonActionDetailFragment.RESTART) { _, _ ->
adapter.notifyDataSetChanged()
checkMax()
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val activity = activity ?: return
setHasOptionsMenu(true)
initData()
val actionNames = activityViewModel.actionNames
val actionIcons = activityViewModel.actionIcons
val list = actionArray.list
adapter = ActionListAdapter(activity, list, actionNames, actionIcons, this)
setRecyclerViewAdapter(adapter)
checkMax()
}
override fun onMove(recyclerView: RecyclerView, fromIndex: Int, toIndex: Int): Boolean {
adapter.move(fromIndex, toIndex)
return true
}
override fun onMoved(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, fromPos: Int, target: RecyclerView.ViewHolder, toPos: Int, x: Int, y: Int) {
actionArray.write(requireContext().applicationContext)
}
override fun onRecyclerItemClicked(v: View, position: Int) {
onListItemClick(position)
}
override fun onRecyclerItemLongClicked(v: View, position: Int): Boolean {
DeleteDialogCompat.newInstance(activity, R.string.confirm, R.string.confirm_delete_button, position)
.show(childFragmentManager, "delete")
return true
}
override fun onDelete(position: Int) {
actionArray.list.removeAt(position)
actionArray.write(requireContext())
adapter.notifyDataSetChanged()
}
override fun onAddButtonClick() {
actionArray.list.add(SoftButtonActionFile())
actionArray.write(requireContext())
onListItemClick(actionArray.list.size - 1)
}
private fun onListItemClick(position: Int) {
parentFragmentManager.commit {
replace(R.id.container, SoftButtonActionDetailFragment(mActionType, mActionId, position))
addToBackStack(null)
}
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, index: Int) {
val file = actionArray.list.removeAt(index)
val context = requireActivity().applicationContext
adapter.notifyDataSetChanged()
checkMax()
Snackbar.make(rootView, R.string.deleted, Snackbar.LENGTH_SHORT)
.setAction(R.string.undo) {
actionArray.list.add(index, file)
adapter.notifyDataSetChanged()
checkMax()
}
.addCallback(object : Snackbar.Callback() {
override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
if (event != DISMISS_EVENT_ACTION) {
actionArray.write(context)
}
}
})
.show()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
RESULT_REQUEST_ADD -> {
adapter.notifyDataSetChanged()
checkMax()
}
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.sort, menu)
applyIconColor(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.sort -> {
val next = !adapter.isSortMode
adapter.isSortMode = next
Toast.makeText(activity, if (next) R.string.start_sort else R.string.end_sort, Toast.LENGTH_SHORT).show()
return true
}
}
return false
}
override val isLongPressDragEnabled
get() = adapter.isSortMode
private fun checkMax() {
setAddButtonEnabled(actionManager.max >= adapter.itemCount)
}
private fun initData() {
val arguments = arguments ?: throw IllegalArgumentException()
val context = requireContext().applicationContext
mActionType = arguments.getInt(ACTION_TYPE)
mActionId = arguments.getInt(ACTION_ID)
actionManager = ActionManager.getActionManager(context, mActionType) as SoftButtonActionArrayManagerBase
actionArray = actionManager.getActionArrayFile(mActionId)
}
private class ActionListAdapter(
context: Context,
list: MutableList<SoftButtonActionFile>,
private val actionNames: ActionNameMap,
private val actionIcons: ActionIconMap,
listener: OnRecyclerListener
) : ArrayRecyclerAdapter<SoftButtonActionFile, ActionListAdapter.ViewHolder>(context, list, listener) {
override fun onBindViewHolder(holder: ViewHolder, item: SoftButtonActionFile, position: Int) {
holder.apply {
textView.text = actionNames[item.press]
imageView.setImageDrawable(actionIcons[item.press])
}
}
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup?, viewType: Int): ViewHolder {
return ViewHolder(
inflater.inflate(R.layout.action_list_item, parent, false), this)
}
private class ViewHolder(
view: View, adapter: ActionListAdapter
) : ArrayViewHolder<SoftButtonActionFile>(view, adapter) {
val textView: TextView = view.findViewById(R.id.textView)
val imageView: ImageView = view.findViewById(R.id.imageView)
}
}
override val isNeedDivider: Boolean
get() = false
companion object {
private const val ACTION_TYPE = "type"
private const val ACTION_ID = "id"
private const val RESULT_REQUEST_ADD = 1
operator fun invoke(actionType: Int, actionId: Int): androidx.fragment.app.Fragment {
return SoftButtonActionArrayFragment().apply {
arguments = Bundle().apply {
putInt(ACTION_TYPE, actionType)
putInt(ACTION_ID, actionId)
}
}
}
}
}
| apache-2.0 | abc89cba3ffb31f0361062418082c782 | 36.306034 | 166 | 0.681225 | 4.962729 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/command/account/AccountLinkCommand.kt | 1 | 2355 | /*
* Copyright 2020 Ren Binden
*
* 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.rpkit.players.bukkit.command.account
import com.rpkit.players.bukkit.RPKPlayersBukkit
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
/**
* Account link command.
* Links another account to the current player.
*/
class AccountLinkCommand(private val plugin: RPKPlayersBukkit): CommandExecutor {
private val accountLinkIRCCommand = AccountLinkIRCCommand(plugin)
private val accountLinkMinecraftCommand = AccountLinkMinecraftCommand(plugin)
private val accountLinkDiscordCommand = AccountLinkDiscordCommand(plugin)
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (!sender.hasPermission("rpkit.players.command.account.link")) {
sender.sendMessage(plugin.messages["no-permission-account-link"])
return true
}
if (args.isNotEmpty()) {
val newArgs = args.drop(1).toTypedArray()
if (args[0].equals("irc", ignoreCase = true)) {
return accountLinkIRCCommand.onCommand(sender, command, label, newArgs)
} else if (args[0].equals("minecraft", ignoreCase = true) || args[0].equals("mc", ignoreCase = true)) {
return accountLinkMinecraftCommand.onCommand(sender, command, label, newArgs)
} else if (args[0].equals("discord", ignoreCase = true)) {
return accountLinkDiscordCommand.onCommand(sender, command, label, newArgs)
} else {
sender.sendMessage(plugin.messages["account-link-usage"])
}
} else {
sender.sendMessage(plugin.messages["account-link-usage"])
}
return true
}
}
| apache-2.0 | 1b0f3c9053427274f05fd21d92bbd1a0 | 41.053571 | 118 | 0.693843 | 4.502868 | false | false | false | false |
JetBrains/teamcity-azure-plugin | plugin-azure-server/src/main/kotlin/jetbrains/buildServer/clouds/azure/arm/throttler/AzureThrottlerTaskQueueCallHistoryImpl.kt | 1 | 2379 | /*
* Copyright 2000-2021 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 jetbrains.buildServer.clouds.azure.arm.throttler
import java.time.Clock
import java.time.LocalDateTime
import java.util.concurrent.ConcurrentLinkedQueue
class AzureThrottlerTaskQueueCallHistoryImpl : AzureThrottlerTaskQueueCallHistory {
private val historyTable = ConcurrentLinkedQueue<HistoryItem>()
override fun addRequestCall() {
historyTable.add(HistoryItem(LocalDateTime.now(Clock.systemUTC()), true, null))
cleanup()
}
override fun addExecutionCall(readsCount: Long?) {
historyTable.add(HistoryItem(LocalDateTime.now(Clock.systemUTC()), false, readsCount))
cleanup()
}
override fun getStatistics(startDateTime: LocalDateTime): AzureThrottlerTaskQueueCallHistoryStatistics {
var requestCallCount : Long? = null
var executionCallCount : Long? = null
var requestsCount : Long? = null
historyTable
.filter { it.dateTime >= startDateTime }
.forEach {
requestCallCount = (requestCallCount ?: 0) + if (it.isRequestCall) 1 else 0
executionCallCount = (executionCallCount ?: 0) + if (it.isRequestCall) 0 else 1
requestsCount = if (it.readsCount != null) (requestsCount ?: 0) + it.readsCount else requestsCount
}
return AzureThrottlerTaskQueueCallHistoryStatistics(requestCallCount, executionCallCount, requestsCount)
}
private fun cleanup() {
val currentDate = LocalDateTime.now(Clock.systemUTC()).minusHours(1)
historyTable.removeAll(historyTable.filter { it.dateTime < currentDate })
}
data class HistoryItem(
val dateTime: LocalDateTime,
val isRequestCall: Boolean,
val readsCount: Long?)
}
| apache-2.0 | da791b2dfb5020c94bca0fcb6f09a4a2 | 39.322034 | 118 | 0.696511 | 4.692308 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/search/gene/numeric/NumberGene.kt | 1 | 5053 | package org.evomaster.core.search.gene.numeric
import org.evomaster.core.search.gene.interfaces.ComparableGene
import org.evomaster.core.search.gene.interfaces.HistoryBasedMutationGene
import org.evomaster.core.search.gene.root.SimpleGene
import java.math.BigDecimal
import java.math.BigInteger
/**
* Common superclass for all number genes (i.e. Float,Double,Integer,Long)
*/
abstract class NumberGene<T : Number>(name: String,
value: T?,
/**
* lower bound of the number
*/
val min : T?,
/**
* upper bound of the number
*/
val max : T?,
/**
* indicate whether to include the lower bound
*/
val minInclusive : Boolean,
/**
* indicate whether to include the upper bound
*/
val maxInclusive : Boolean,
/**
* maximum number of digits
*
* Note that this presents the max range,
* eg, DEC(4,2) on mysql, @Digits(integer=2, fraction=2)
* the precision is 4 and the scale is 2
* its range would be from -99.99 to 99.99.
* 5.2 and 0.1 are considered as `valid`
*/
val precision: Int?,
/**
* maximum number of digits to the right of the decimal point
*
* Note that this presents the max range,
* eg, DEC(4,2) on mysql, @Digits(integer=2, fraction=2)
* the precision is 4 and the scale is 2
* its range would be from -99.99 to 99.99.
* 5.2 and 0.1 are considered as `valid`
*/
val scale: Int?
) : ComparableGene, HistoryBasedMutationGene, SimpleGene(name) {
var value : T
init {
if (value == null)
this.value = getDefaultValue()
else
this.value = value
if (precision != null && precision <= 0)
throw IllegalArgumentException("precision must be positive number")
if (scale != null && scale < 0)
throw IllegalArgumentException("scale must be zero or positive number")
if (getMaximum().toDouble() < getMinimum().toDouble())
throwMinMaxException()
}
fun throwMinMaxException(){
val x = if(minInclusive) "inclusive" else "exclusive"
val y = if(maxInclusive) "inclusive" else "exclusive"
throw IllegalArgumentException("max must be greater than min but $y max is $max and $x min is $min")
}
open fun isRangeSpecified() = min != null || max != null
fun toInt(): Int =
value.toInt()
fun toLong(): Long =
value.toLong()
fun toDouble(): Double =
value.toDouble()
fun toFloat(): Float =
value.toFloat()
/**
* @return whether the [value] is between [min] and [max] if they are specified
*/
override fun isLocallyValid() : Boolean{
if (max != null && max !is BigDecimal && max !is BigInteger && value.toDouble() > max.toDouble())
return false
if (min != null && max !is BigDecimal && max !is BigInteger && value.toDouble() < min.toDouble())
return false
return true
}
override fun isMutable(): Boolean {
// it is not mutable if max equals to min
return min == null || max == null || max != min
}
/**
* @return inclusive Minimum value of the gene
*/
abstract fun getMinimum() : T
/**
* @return inclusive Maximum value of the gene
*/
abstract fun getMaximum() : T
/**
* @return a default value if the value is not specified
*/
open fun getDefaultValue() : T = getZero()
/**
* @return zero with the number format
*/
abstract fun getZero() : T
override fun toString(): String {
return "${this.javaClass.simpleName}: $value [$minInclusive $min, $maxInclusive $max] [s=$scale,p=$precision]"
}
} | lgpl-3.0 | f178bd17c51b9ed317f08b25a6303a91 | 36.716418 | 118 | 0.447259 | 5.671156 | false | false | false | false |
Litote/kmongo | kmongo-core/src/main/kotlin/kotlin/collections/KMongoIterable.kt | 1 | 52741 | /*
* Copyright (C) 2016/2022 Litote
*
* 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 kotlin.collections
import com.mongodb.Function
import com.mongodb.ServerAddress
import com.mongodb.ServerCursor
import com.mongodb.client.MongoCursor
import com.mongodb.client.MongoIterable
import java.util.function.Consumer
import kotlin.internal.HidesMembers
import kotlin.internal.InlineOnly
import kotlin.internal.NoInfer
import kotlin.internal.OnlyInputTypes
//utility class & methods ->
/**
* Utility class - this is not part of the KMongo public API.
*/
private class MongoCursorIterable<T>(private val cursor: MongoCursor<T>) : MongoCursor<T> by cursor, Iterable<T> {
override fun iterator(): Iterator<T> = cursor
}
/**
* Utility method - this is not part of the KMongo public API.
*/
private fun <T> MongoIterable<T>.kCursor(): MongoCursorIterable<T> = MongoCursorIterable(iterator())
/**
* Utility method - this is not part of the KMongo public API.
*/
fun <T, R> MongoIterable<T>.useCursor(block: (Iterable<T>) -> R): R {
return kCursor().use(block)
}
//specific overrides
/**
* Overrides [Iterable.forEach] to ensure [MongoIterable.forEach] is called.
*
* @param
*/
@HidesMembers
inline fun <T> MongoIterable<T>.forEach(crossinline action: (T) -> Unit): Unit =
forEach(Consumer { action.invoke(it) })
/**
* Returns the first element, or `null` if the collection is empty.
*/
fun <T> MongoIterable<T>.firstOrNull(): T? {
return first()
}
/**
* Iterator transforming original `iterator` into iterator of [IndexedValue], counting index from zero.
*/
private class MongoIndexingIterator<T>(val iterator: MongoCursor<T>) : MongoCursor<IndexedValue<T>> {
private var index = 0
override fun hasNext(): Boolean = iterator.hasNext()
override fun next(): IndexedValue<T> = IndexedValue(index++, iterator.next())
override fun tryNext(): IndexedValue<T>? = iterator.tryNext()?.let { IndexedValue(index++, it) }
override fun remove() = iterator.remove()
override fun close() = iterator.close()
override fun getServerCursor(): ServerCursor? = iterator.serverCursor
override fun getServerAddress(): ServerAddress = iterator.serverAddress
override fun available(): Int = iterator.available()
}
/**
* A wrapper over another [Iterable] (or any other object that can produce an [Iterator]) that returns
* an indexing iterator.
*/
private class MongoIndexingIterable<T>(
private val iterable: MongoIterable<T>
) : MongoIterable<IndexedValue<T>> {
override fun batchSize(batchSize: Int): MongoIterable<IndexedValue<T>> =
MongoIndexingIterable(iterable.batchSize(batchSize))
override fun <U : Any?> map(mapper: Function<IndexedValue<T>, U>): MongoIterable<U> {
var index = 0
return iterable.map { mapper.apply(IndexedValue(index++, it)) }
}
override fun forEach(action: Consumer<in IndexedValue<T>>) {
var index = 0
iterable.forEach {
action.accept(IndexedValue(index++, it))
}
}
override fun first(): IndexedValue<T>? = iterable.first()?.let { IndexedValue(0, it) }
override fun <A : MutableCollection<in IndexedValue<T>>> into(target: A): A {
val l = mutableListOf<T>()
return target.apply { addAll(iterable.into(l).mapIndexed { i, v -> IndexedValue(i, v) }) }
}
override fun cursor(): MongoCursor<IndexedValue<T>> = iterator()
override fun iterator(): MongoCursor<IndexedValue<T>> = MongoIndexingIterator(iterable.iterator())
}
/**
* Returns a lazy [Iterable] of [IndexedValue] for each element of the original collection.
*/
fun <T> MongoIterable<T>.withIndex(): MongoIterable<IndexedValue<T>> {
return MongoIndexingIterable(this)
}
/**
* Returns an [Iterator] wrapping each value produced by this [Iterator] with the [IndexedValue],
* containing value and it's index.
* @sample samples.collections.Iterators.withIndexIterator
*/
fun <T> MongoCursor<T>.withIndex(): MongoCursor<IndexedValue<T>> =
MongoIndexingIterator(this)
/**
* Returns an original collection containing all the non-`null` elements, throwing an [IllegalArgumentException] if there are any `null` elements.
*/
fun <T : Any> MongoIterable<T?>.requireNoNulls(): Iterable<T> =
toList().requireNoNulls()
/**
* Creates a [Sequence] instance that wraps the original collection returning its elements when being iterated.
*
* @sample samples.collections.Sequences.Building.sequenceFromCollection
*/
fun <T> MongoIterable<T>.asSequence(): Sequence<T> {
//lazy sequence
return object : Sequence<T> {
override fun iterator(): Iterator<T> = [email protected]().asSequence().iterator()
}
}
//common overrides ->
/**
* Returns `true` if [element] is found in the collection.
*/
operator fun <@OnlyInputTypes T> MongoIterable<T>.contains(element: T): Boolean {
return useCursor { it.contains(element) }
}
/**
* Returns an element at the given [index] or throws an [IndexOutOfBoundsException] if the [index] is out of bounds of this collection.
*/
fun <T> MongoIterable<T>.elementAt(index: Int): T {
return useCursor { it.elementAt(index) }
}
/**
* Returns an element at the given [index] or the result of calling the [defaultValue] function if the [index] is out of bounds of this collection.
*/
fun <T> MongoIterable<T>.elementAtOrElse(index: Int, defaultValue: (Int) -> T): T {
return useCursor { it.elementAtOrElse(index, defaultValue) }
}
/**
* Returns an element at the given [index] or `null` if the [index] is out of bounds of this collection.
*/
fun <T> MongoIterable<T>.elementAtOrNull(index: Int): T? {
return useCursor { it.elementAtOrNull(index) }
}
/**
* Returns the first element matching the given [predicate], or `null` if no such element was found.
*/
@InlineOnly
inline fun <T> MongoIterable<T>.find(crossinline predicate: (T) -> Boolean): T? {
return useCursor { it.find(predicate) }
}
/**
* Returns the last element matching the given [predicate], or `null` if no such element was found.
*/
@InlineOnly
inline fun <T> MongoIterable<T>.findLast(crossinline predicate: (T) -> Boolean): T? {
return useCursor { it.findLast(predicate) }
}
/**
* Returns the first element matching the given [predicate].
* @throws [NoSuchElementException] if no such element is found.
*/
inline fun <T> MongoIterable<T>.first(crossinline predicate: (T) -> Boolean): T {
return useCursor { it.first(predicate) }
}
/**
* Returns the first element matching the given [predicate], or `null` if element was not found.
*/
inline fun <T> MongoIterable<T>.firstOrNull(crossinline predicate: (T) -> Boolean): T? {
return useCursor { it.firstOrNull(predicate) }
}
/**
* Returns first index of [element], or -1 if the collection does not contain element.
*/
fun <@OnlyInputTypes T> MongoIterable<T>.indexOf(element: T): Int {
return useCursor { it.indexOf(element) }
}
/**
* Returns index of the first element matching the given [predicate], or -1 if the collection does not contain such element.
*/
inline fun <T> MongoIterable<T>.indexOfFirst(crossinline predicate: (T) -> Boolean): Int {
return useCursor { it.indexOfFirst(predicate) }
}
/**
* Returns index of the last element matching the given [predicate], or -1 if the collection does not contain such element.
*/
inline fun <T> MongoIterable<T>.indexOfLast(crossinline predicate: (T) -> Boolean): Int {
return useCursor { it.indexOfLast(predicate) }
}
/**
* Returns the last element.
* @throws [NoSuchElementException] if the collection is empty.
*/
fun <T> MongoIterable<T>.last(): T {
return useCursor { it.last() }
}
/**
* Returns the last element matching the given [predicate].
* @throws [NoSuchElementException] if no such element is found.
*/
inline fun <T> MongoIterable<T>.last(crossinline predicate: (T) -> Boolean): T {
return useCursor { it.last(predicate) }
}
/**
* Returns last index of [element], or -1 if the collection does not contain element.
*/
fun <@OnlyInputTypes T> MongoIterable<T>.lastIndexOf(element: T): Int {
return useCursor { it.lastIndexOf(element) }
}
/**
* Returns the last element, or `null` if the collection is empty.
*/
fun <T> MongoIterable<T>.lastOrNull(): T? {
return useCursor { it.lastOrNull() }
}
/**
* Returns the last element matching the given [predicate], or `null` if no such element was found.
*/
inline fun <T> MongoIterable<T>.lastOrNull(crossinline predicate: (T) -> Boolean): T? {
return useCursor { it.lastOrNull(predicate) }
}
/**
* Returns the single element, or throws an exception if the collection is empty or has more than one element.
*/
fun <T> MongoIterable<T>.single(): T {
return useCursor { it.single() }
}
/**
* Returns the single element matching the given [predicate], or throws exception if there is no or more than one matching element.
*/
inline fun <T> MongoIterable<T>.single(crossinline predicate: (T) -> Boolean): T {
return useCursor { it.single(predicate) }
}
/**
* Returns single element, or `null` if the collection is empty or has more than one element.
*/
fun <T> MongoIterable<T>.singleOrNull(): T? {
return useCursor { it.singleOrNull() }
}
/**
* Returns the single element matching the given [predicate], or `null` if element was not found or more than one element was found.
*/
inline fun <T> MongoIterable<T>.singleOrNull(crossinline predicate: (T) -> Boolean): T? {
return useCursor { it.singleOrNull(predicate) }
}
/**
* Returns a list containing all elements except first [n] elements.
*
* @sample samples.collections.Collections.Transformations.drop
*/
fun <T> MongoIterable<T>.drop(n: Int): List<T> {
return useCursor { it.drop(n) }
}
/**
* Returns a list containing all elements except first elements that satisfy the given [predicate].
*
* @sample samples.collections.Collections.Transformations.drop
*/
inline fun <T> MongoIterable<T>.dropWhile(crossinline predicate: (T) -> Boolean): List<T> {
return useCursor { it.dropWhile(predicate) }
}
/**
* Returns a list containing only elements matching the given [predicate].
*/
inline fun <T> MongoIterable<T>.filter(crossinline predicate: (T) -> Boolean): List<T> {
return useCursor { it.filter(predicate) }
}
/**
* Returns a list containing only elements matching the given [predicate].
* @param [predicate] function that takes the index of an element and the element itself
* and returns the result of predicate evaluation on the element.
*/
inline fun <T> MongoIterable<T>.filterIndexed(crossinline predicate: (index: Int, T) -> Boolean): List<T> {
return useCursor { it.filterIndexed(predicate) }
}
/**
* Appends all elements matching the given [predicate] to the given [destination].
* @param [predicate] function that takes the index of an element and the element itself
* and returns the result of predicate evaluation on the element.
*/
inline fun <T, C : MutableCollection<in T>> MongoIterable<T>.filterIndexedTo(
destination: C,
crossinline predicate: (index: Int, T) -> Boolean
): C {
return useCursor { it.filterIndexedTo(destination, predicate) }
}
/**
* Returns a list containing all elements that are instances of specified type parameter R.
*/
inline fun <reified R> MongoIterable<*>.filterIsInstance(): List<@NoInfer R> {
return useCursor { it.filterIsInstance<R>() }
}
/**
* Appends all elements that are instances of specified type parameter R to the given [destination].
*/
inline fun <reified R, C : MutableCollection<in R>> MongoIterable<*>.filterIsInstanceTo(destination: C): C {
return useCursor { it.filterIsInstanceTo(destination) }
}
/**
* Returns a list containing all elements not matching the given [predicate].
*/
inline fun <T> MongoIterable<T>.filterNot(crossinline predicate: (T) -> Boolean): List<T> {
return useCursor { it.filterNot(predicate) }
}
/**
* Returns a list containing all elements that are not `null`.
*/
fun <T : Any> MongoIterable<T?>.filterNotNull(): List<T> {
return useCursor { it.filterNotNull() }
}
/**
* Appends all elements that are not `null` to the given [destination].
*/
fun <C : MutableCollection<in T>, T : Any> MongoIterable<T?>.filterNotNullTo(destination: C): C {
return useCursor { it.filterNotNullTo(destination) }
}
/**
* Appends all elements not matching the given [predicate] to the given [destination].
*/
inline fun <T, C : MutableCollection<in T>> MongoIterable<T>.filterNotTo(
destination: C,
crossinline predicate: (T) -> Boolean
): C {
return useCursor { it.filterNotTo(destination, predicate) }
}
/**
* Appends all elements matching the given [predicate] to the given [destination].
*/
inline fun <T, C : MutableCollection<in T>> MongoIterable<T>.filterTo(
destination: C,
crossinline predicate: (T) -> Boolean
): C {
return useCursor { it.filterTo(destination, predicate) }
}
/**
* Returns a list containing first [n] elements.
*
* @sample samples.collections.Collections.Transformations.take
*/
fun <T> MongoIterable<T>.take(n: Int): List<T> {
return useCursor { it.take(n) }
}
/**
* Returns a list containing first elements satisfying the given [predicate].
*
* @sample samples.collections.Collections.Transformations.take
*/
inline fun <T> MongoIterable<T>.takeWhile(crossinline predicate: (T) -> Boolean): List<T> {
return useCursor { it.takeWhile(predicate) }
}
/**
* Returns a list with elements in reversed order.
*/
fun <T> MongoIterable<T>.reversed(): List<T> {
return useCursor { it.reversed() }
}
/**
* Returns a list of all elements sorted according to their natural sort order.
*/
fun <T : Comparable<T>> MongoIterable<T>.sorted(): List<T> {
return useCursor { it.sorted() }
}
/**
* Returns a list of all elements sorted according to natural sort order of the value returned by specified [selector] function.
*/
inline fun <T, R : Comparable<R>> MongoIterable<T>.sortedBy(crossinline selector: (T) -> R?): List<T> {
return useCursor { it.sortedBy(selector) }
}
/**
* Returns a list of all elements sorted descending according to natural sort order of the value returned by specified [selector] function.
*/
inline fun <T, R : Comparable<R>> MongoIterable<T>.sortedByDescending(crossinline selector: (T) -> R?): List<T> {
return useCursor { it.sortedByDescending(selector) }
}
/**
* Returns a list of all elements sorted descending according to their natural sort order.
*/
fun <T : Comparable<T>> MongoIterable<T>.sortedDescending(): List<T> {
return useCursor { it.sortedDescending() }
}
/**
* Returns a list of all elements sorted according to the specified [comparator].
*/
fun <T> MongoIterable<T>.sortedWith(comparator: Comparator<in T>): List<T> {
return useCursor { it.sortedWith(comparator) }
}
/**
* Returns a [Map] containing key-value pairs provided by [transform] function
* applied to elements of the given collection.
*
* If any of two pairs would have the same key the last one gets added to the map.
*
* The returned map preserves the entry iteration order of the original collection.
*/
inline fun <T, K, V> MongoIterable<T>.associate(crossinline transform: (T) -> Pair<K, V>): Map<K, V> {
return useCursor { it.associate(transform) }
}
/**
* Returns a [Map] containing the elements from the given collection indexed by the key
* returned from [keySelector] function applied to each element.
*
* If any two elements would have the same key returned by [keySelector] the last one gets added to the map.
*
* The returned map preserves the entry iteration order of the original collection.
*/
inline fun <T, K> MongoIterable<T>.associateBy(crossinline keySelector: (T) -> K): Map<K, T> {
return useCursor { it.associateBy(keySelector) }
}
/**
* Returns a [Map] containing the values provided by [valueTransform] and indexed by [keySelector] functions applied to elements of the given collection.
*
* If any two elements would have the same key returned by [keySelector] the last one gets added to the map.
*
* The returned map preserves the entry iteration order of the original collection.
*/
inline fun <T, K, V> MongoIterable<T>.associateBy(
crossinline keySelector: (T) -> K,
crossinline valueTransform: (T) -> V
): Map<K, V> {
return useCursor { it.associateBy(keySelector, valueTransform) }
}
/**
* Populates and returns the [destination] mutable map with key-value pairs,
* where key is provided by the [keySelector] function applied to each element of the given collection
* and value is the element itself.
*
* If any two elements would have the same key returned by [keySelector] the last one gets added to the map.
*/
inline fun <T, K, M : MutableMap<in K, in T>> MongoIterable<T>.associateByTo(
destination: M,
crossinline keySelector: (T) -> K
): M {
return useCursor { it.associateByTo(destination, keySelector) }
}
/**
* Populates and returns the [destination] mutable map with key-value pairs,
* where key is provided by the [keySelector] function and
* and value is provided by the [valueTransform] function applied to elements of the given collection.
*
* If any two elements would have the same key returned by [keySelector] the last one gets added to the map.
*/
inline fun <T, K, V, M : MutableMap<in K, in V>> MongoIterable<T>.associateByTo(
destination: M,
crossinline keySelector: (T) -> K,
crossinline valueTransform: (T) -> V
): M {
return useCursor { it.associateByTo(destination, keySelector, valueTransform) }
}
/**
* Populates and returns the [destination] mutable map with key-value pairs
* provided by [transform] function applied to each element of the given collection.
*
* If any of two pairs would have the same key the last one gets added to the map.
*/
inline fun <T, K, V, M : MutableMap<in K, in V>> MongoIterable<T>.associateTo(
destination: M,
crossinline transform: (T) -> Pair<K, V>
): M {
return useCursor { it.associateTo(destination, transform) }
}
/**
* Appends all elements to the given [destination] collection.
*/
fun <T, C : MutableCollection<in T>> MongoIterable<T>.toCollection(destination: C): C {
return useCursor { it.toCollection(destination) }
}
/**
* Returns a [HashSet] of all elements.
*/
fun <T> MongoIterable<T>.toHashSet(): HashSet<T> {
return useCursor { it.toHashSet() }
}
/**
* Returns a [List] containing all elements.
*/
fun <T> MongoIterable<T>.toList(): List<T> {
return useCursor { it.toList() }
}
/**
* Returns a [MutableList] filled with all elements of this collection.
*/
fun <T> MongoIterable<T>.toMutableList(): MutableList<T> {
return useCursor { it.toMutableList() }
}
/**
* Returns a [Set] of all elements.
*
* The returned set preserves the element iteration order of the original collection.
*/
fun <T> MongoIterable<T>.toSet(): Set<T> {
return useCursor { it.toSet() }
}
/**
* Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original collection.
*/
inline fun <T, R> MongoIterable<T>.flatMap(crossinline transform: (T) -> MongoIterable<R>): List<R> {
return useCursor { it.flatMap(transform) }
}
/**
* Appends all elements yielded from results of [transform] function being invoked on each element of original collection, to the given [destination].
*/
inline fun <T, R, C : MutableCollection<in R>> MongoIterable<T>.flatMapTo(
destination: C,
crossinline transform: (T) -> MongoIterable<R>
): C {
return useCursor { it.flatMapTo(destination, transform) }
}
/**
* Groups elements of the original collection by the key returned by the given [keySelector] function
* applied to each element and returns a map where each group key is associated with a list of corresponding elements.
*
* The returned map preserves the entry iteration order of the keys produced from the original collection.
*
* @sample samples.collections.Collections.Transformations.groupBy
*/
inline fun <T, K> MongoIterable<T>.groupBy(crossinline keySelector: (T) -> K): Map<K, List<T>> {
return useCursor { it.groupBy(keySelector) }
}
/**
* Groups values returned by the [valueTransform] function applied to each element of the original collection
* by the key returned by the given [keySelector] function applied to the element
* and returns a map where each group key is associated with a list of corresponding values.
*
* The returned map preserves the entry iteration order of the keys produced from the original collection.
*
* @sample samples.collections.Collections.Transformations.groupByKeysAndValues
*/
inline fun <T, K, V> MongoIterable<T>.groupBy(
crossinline keySelector: (T) -> K,
crossinline valueTransform: (T) -> V
): Map<K, List<V>> {
return useCursor { it.groupBy(keySelector, valueTransform) }
}
/**
* Groups elements of the original collection by the key returned by the given [keySelector] function
* applied to each element and puts to the [destination] map each group key associated with a list of corresponding elements.
*
* @return The [destination] map.
*
* @sample samples.collections.Collections.Transformations.groupBy
*/
inline fun <T, K, M : MutableMap<in K, MutableList<T>>> MongoIterable<T>.groupByTo(
destination: M,
crossinline keySelector: (T) -> K
): M {
return useCursor { it.groupByTo(destination, keySelector) }
}
/**
* Groups values returned by the [valueTransform] function applied to each element of the original collection
* by the key returned by the given [keySelector] function applied to the element
* and puts to the [destination] map each group key associated with a list of corresponding values.
*
* @return The [destination] map.
*
* @sample samples.collections.Collections.Transformations.groupByKeysAndValues
*/
inline fun <T, K, V, M : MutableMap<in K, MutableList<V>>> MongoIterable<T>.groupByTo(
destination: M,
crossinline keySelector: (T) -> K,
crossinline valueTransform: (T) -> V
): M {
return useCursor { it.groupByTo(destination, keySelector, valueTransform) }
}
/**
* Creates a [Grouping] source from a collection to be used later with one of group-and-fold operations
* using the specified [keySelector] function to extract a key from each element.
*
* @sample samples.collections.Collections.Transformations.groupingByEachCount
*/
@SinceKotlin("1.1")
inline fun <T, K> MongoIterable<T>.groupingBy(crossinline keySelector: (T) -> K): Grouping<T, K> {
return useCursor { it.groupingBy(keySelector) }
}
/**
* Returns a list containing the results of applying the given [transform] function
* to each element in the original collection.
*/
inline fun <T, R> MongoIterable<T>.map(crossinline transform: (T) -> R): List<R> {
return useCursor { it.map(transform) }
}
/**
* Returns a list containing the results of applying the given [transform] function
* to each element and its index in the original collection.
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
inline fun <T, R> MongoIterable<T>.mapIndexed(crossinline transform: (index: Int, T) -> R): List<R> {
return useCursor { it.mapIndexed(transform) }
}
/**
* Returns a list containing only the non-null results of applying the given [transform] function
* to each element and its index in the original collection.
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
inline fun <T, R : Any> MongoIterable<T>.mapIndexedNotNull(crossinline transform: (index: Int, T) -> R?): List<R> {
return useCursor { it.mapIndexedNotNull(transform) }
}
/**
* Applies the given [transform] function to each element and its index in the original collection
* and appends only the non-null results to the given [destination].
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
inline fun <T, R : Any, C : MutableCollection<in R>> MongoIterable<T>.mapIndexedNotNullTo(
destination: C,
crossinline transform: (index: Int, T) -> R?
): C {
return useCursor { it.mapIndexedNotNullTo(destination, transform) }
}
/**
* Applies the given [transform] function to each element and its index in the original collection
* and appends the results to the given [destination].
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
inline fun <T, R, C : MutableCollection<in R>> MongoIterable<T>.mapIndexedTo(
destination: C,
crossinline transform: (index: Int, T) -> R
): C {
return useCursor { it.mapIndexedTo(destination, transform) }
}
/**
* Returns a list containing only the non-null results of applying the given [transform] function
* to each element in the original collection.
*/
inline fun <T, R : Any> MongoIterable<T>.mapNotNull(crossinline transform: (T) -> R?): List<R> {
return useCursor { it.mapNotNull(transform) }
}
/**
* Applies the given [transform] function to each element in the original collection
* and appends only the non-null results to the given [destination].
*/
inline fun <T, R : Any, C : MutableCollection<in R>> MongoIterable<T>.mapNotNullTo(
destination: C,
crossinline transform: (T) -> R?
): C {
return useCursor { it.mapNotNullTo(destination, transform) }
}
/**
* Applies the given [transform] function to each element of the original collection
* and appends the results to the given [destination].
*/
inline fun <T, R, C : MutableCollection<in R>> MongoIterable<T>.mapTo(
destination: C,
crossinline transform: (T) -> R
): C {
return useCursor { it.mapTo(destination, transform) }
}
/**
* Returns a list containing only distinct elements from the given collection.
*
* The elements in the resulting list are in the same order as they were in the source collection.
*/
fun <T> MongoIterable<T>.distinct(): List<T> {
return useCursor { it.distinct() }
}
/**
* Returns a list containing only elements from the given collection
* having distinct keys returned by the given [selector] function.
*
* The elements in the resulting list are in the same order as they were in the source collection.
*/
inline fun <T, K> MongoIterable<T>.distinctBy(crossinline selector: (T) -> K): List<T> {
return useCursor { it.distinctBy(selector) }
}
/**
* Returns a set containing all elements that are contained by both this set and the specified collection.
*
* The returned set preserves the element iteration order of the original collection.
*/
infix fun <T> MongoIterable<T>.intersect(other: Iterable<T>): Set<T> {
return useCursor { it.intersect(other) }
}
/**
* Returns a set containing all elements that are contained by this collection and not contained by the specified collection.
*
* The returned set preserves the element iteration order of the original collection.
*/
infix fun <T> MongoIterable<T>.subtract(other: Iterable<T>): Set<T> {
return useCursor { it.subtract(other) }
}
/**
* Returns a mutable set containing all distinct elements from the given collection.
*
* The returned set preserves the element iteration order of the original collection.
*/
fun <T> MongoIterable<T>.toMutableSet(): MutableSet<T> {
return useCursor { it.toMutableSet() }
}
/**
* Returns a set containing all distinct elements from both collections.
*
* The returned set preserves the element iteration order of the original collection.
* Those elements of the [other] collection that are unique are iterated in the end
* in the order of the [other] collection.
*/
infix fun <T> MongoIterable<T>.union(other: Iterable<T>): Set<T> {
return useCursor { it.union(other) }
}
/**
* Returns `true` if all elements match the given [predicate].
*
* @sample samples.collections.Collections.Aggregates.all
*/
inline fun <T> MongoIterable<T>.all(crossinline predicate: (T) -> Boolean): Boolean {
return useCursor { it.all(predicate) }
}
/**
* Returns `true` if collection has at least one element.
*
* @sample samples.collections.Collections.Aggregates.any
*/
fun <T> MongoIterable<T>.any(): Boolean {
return useCursor { it.any() }
}
/**
* Returns `true` if at least one element matches the given [predicate].
*
* @sample samples.collections.Collections.Aggregates.anyWithPredicate
*/
inline fun <T> MongoIterable<T>.any(crossinline predicate: (T) -> Boolean): Boolean {
return useCursor { it.any(predicate) }
}
/**
* Returns the number of elements in this collection.
*/
fun <T> MongoIterable<T>.count(): Int {
return useCursor { it.count() }
}
/**
* Returns the number of elements matching the given [predicate].
*/
inline fun <T> MongoIterable<T>.count(crossinline predicate: (T) -> Boolean): Int {
return useCursor { it.count(predicate) }
}
/**
* Accumulates value starting with [initial] value and applying [operation] from left to right to current accumulator value and each element.
*/
inline fun <T, R> MongoIterable<T>.fold(initial: R, crossinline operation: (acc: R, T) -> R): R {
return useCursor { it.fold(initial, operation) }
}
/**
* Accumulates value starting with [initial] value and applying [operation] from left to right
* to current accumulator value and each element with its index in the original collection.
* @param [operation] function that takes the index of an element, current accumulator value
* and the element itself, and calculates the next accumulator value.
*/
inline fun <T, R> MongoIterable<T>.foldIndexed(initial: R, crossinline operation: (index: Int, acc: R, T) -> R): R {
return useCursor { it.foldIndexed(initial, operation) }
}
/**
* Performs the given [action] on each element, providing sequential index with the element.
* @param [action] function that takes the index of an element and the element itself
* and performs the desired action on the element.
*/
inline fun <T> MongoIterable<T>.forEachIndexed(crossinline action: (index: Int, T) -> Unit): Unit {
return useCursor { it.forEachIndexed(action) }
}
/**
* Returns the largest element or `null` if there are no elements.
*
* If any of elements is `NaN` returns `NaN`.
*/
@SinceKotlin("1.1")
fun MongoIterable<Double>.max(): Double? {
return useCursor { it.maxOrNull() }
}
/**
* Returns the largest element or `null` if there are no elements.
*
* If any of elements is `NaN` returns `NaN`.
*/
@SinceKotlin("1.1")
fun MongoIterable<Float>.max(): Float? {
return useCursor { it.maxOrNull() }
}
/**
* Returns the largest element or `null` if there are no elements.
*/
fun <T : Comparable<T>> MongoIterable<T>.max(): T? {
return useCursor { it.maxOrNull() }
}
/**
* Returns the first element yielding the largest value of the given function or `null` if there are no elements.
*/
inline fun <T, R : Comparable<R>> MongoIterable<T>.maxBy(crossinline selector: (T) -> R): T? {
return useCursor { it.maxByOrNull(selector) }
}
/**
* Returns the first element having the largest value according to the provided [comparator] or `null` if there are no elements.
*/
fun <T> MongoIterable<T>.maxWith(comparator: Comparator<in T>): T? {
return useCursor { it.maxWithOrNull(comparator) }
}
/**
* Returns the smallest element or `null` if there are no elements.
*
* If any of elements is `NaN` returns `NaN`.
*/
@SinceKotlin("1.1")
fun MongoIterable<Double>.min(): Double? {
return useCursor { it.minOrNull() }
}
/**
* Returns the smallest element or `null` if there are no elements.
*
* If any of elements is `NaN` returns `NaN`.
*/
@SinceKotlin("1.1")
fun MongoIterable<Float>.min(): Float? {
return useCursor { it.minOrNull() }
}
/**
* Returns the smallest element or `null` if there are no elements.
*/
fun <T : Comparable<T>> MongoIterable<T>.min(): T? {
return useCursor { it.minOrNull() }
}
/**
* Returns the first element yielding the smallest value of the given function or `null` if there are no elements.
*/
inline fun <T, R : Comparable<R>> MongoIterable<T>.minBy(crossinline selector: (T) -> R): T? {
return useCursor { it.minByOrNull(selector) }
}
/**
* Returns the first element having the smallest value according to the provided [comparator] or `null` if there are no elements.
*/
fun <T> MongoIterable<T>.minWith(comparator: Comparator<in T>): T? {
return useCursor { it.minWithOrNull(comparator) }
}
/**
* Returns the largest element or `null` if there are no elements.
*
* If any of elements is `NaN` returns `NaN`.
*/
@SinceKotlin("1.4")
fun MongoIterable<Double>.maxOrNull(): Double? {
return useCursor { it.maxOrNull() }
}
/**
* Returns the largest element or `null` if there are no elements.
*
* If any of elements is `NaN` returns `NaN`.
*/
@SinceKotlin("1.4")
fun MongoIterable<Float>.maxOrNull(): Float? {
return useCursor { it.maxOrNull() }
}
/**
* Returns the largest element or `null` if there are no elements.
*/
fun <T : Comparable<T>> MongoIterable<T>.maxOrNull(): T? {
return useCursor { it.maxOrNull() }
}
/**
* Returns the first element yielding the largest value of the given function or `null` if there are no elements.
*/
inline fun <T, R : Comparable<R>> MongoIterable<T>.maxByOrNull(crossinline selector: (T) -> R): T? {
return useCursor { it.maxByOrNull(selector) }
}
/**
* Returns the first element having the largest value according to the provided [comparator] or `null` if there are no elements.
*/
fun <T> MongoIterable<T>.maxWithOrNull(comparator: Comparator<in T>): T? {
return useCursor { it.maxWithOrNull(comparator) }
}
/**
* Returns the smallest element or `null` if there are no elements.
*
* If any of elements is `NaN` returns `NaN`.
*/
@SinceKotlin("1.4")
fun MongoIterable<Double>.minOrNull(): Double? {
return useCursor { it.minOrNull() }
}
/**
* Returns the smallest element or `null` if there are no elements.
*
* If any of elements is `NaN` returns `NaN`.
*/
@SinceKotlin("1.4")
fun MongoIterable<Float>.minOrNull(): Float? {
return useCursor { it.minOrNull() }
}
/**
* Returns the smallest element or `null` if there are no elements.
*/
fun <T : Comparable<T>> MongoIterable<T>.minOrNull(): T? {
return useCursor { it.minOrNull() }
}
/**
* Returns the first element yielding the smallest value of the given function or `null` if there are no elements.
*/
inline fun <T, R : Comparable<R>> MongoIterable<T>.minByOrNull(crossinline selector: (T) -> R): T? {
return useCursor { it.minByOrNull(selector) }
}
/**
* Returns the first element having the smallest value according to the provided [comparator] or `null` if there are no elements.
*/
fun <T> MongoIterable<T>.minWithOrNull(comparator: Comparator<in T>): T? {
return useCursor { it.minWithOrNull(comparator) }
}
/**
* Returns `true` if the collection has no elements.
*
* @sample samples.collections.Collections.Aggregates.none
*/
fun <T> MongoIterable<T>.none(): Boolean {
return useCursor { it.none() }
}
/**
* Returns `true` if no elements match the given [predicate].
*
* @sample samples.collections.Collections.Aggregates.noneWithPredicate
*/
inline fun <T> MongoIterable<T>.none(crossinline predicate: (T) -> Boolean): Boolean {
return useCursor { it.none(predicate) }
}
/**
* Accumulates value starting with the first element and applying [operation] from left to right to current accumulator value and each element.
*/
inline fun <S, T : S> MongoIterable<T>.reduce(crossinline operation: (acc: S, T) -> S): S {
return useCursor { it.reduce(operation) }
}
/**
* Accumulates value starting with the first element and applying [operation] from left to right
* to current accumulator value and each element with its index in the original collection.
* @param [operation] function that takes the index of an element, current accumulator value
* and the element itself and calculates the next accumulator value.
*/
inline fun <S, T : S> MongoIterable<T>.reduceIndexed(crossinline operation: (index: Int, acc: S, T) -> S): S {
return useCursor { it.reduceIndexed(operation) }
}
/**
* Returns the sum of all values produced by [selector] function applied to each element in the collection.
*/
inline fun <T> MongoIterable<T>.sumBy(crossinline selector: (T) -> Int): Int {
return useCursor { it.sumOf(selector) }
}
/**
* Returns the sum of all values produced by [selector] function applied to each element in the collection.
*/
inline fun <T> MongoIterable<T>.sumByDouble(crossinline selector: (T) -> Double): Double {
return useCursor { it.sumOf(selector) }
}
/**
* Splits this collection into a list of lists each not exceeding the given [size].
*
* The last list in the resulting list may have less elements than the given [size].
*
* @param size the number of elements to take in each list, must be positive and can be greater than the number of elements in this collection.
*
* @sample samples.collections.Collections.Transformations.chunked
*/
@SinceKotlin("1.2")
fun <T> MongoIterable<T>.chunked(size: Int): List<List<T>> {
return useCursor { it.chunked(size) }
}
/**
* Splits this collection into several lists each not exceeding the given [size]
* and applies the given [transform] function to an each.
*
* @return list of results of the [transform] applied to an each list.
*
* Note that the list passed to the [transform] function is ephemeral and is valid only inside that function.
* You should not store it or allow it to escape in some way, unless you made a snapshot of it.
* The last list may have less elements than the given [size].
*
* @param size the number of elements to take in each list, must be positive and can be greater than the number of elements in this collection.
*
* @sample samples.text.Strings.chunkedTransform
*/
@SinceKotlin("1.2")
fun <T, R> MongoIterable<T>.chunked(size: Int, transform: (List<T>) -> R): List<R> {
return useCursor { it.chunked(size, transform) }
}
/**
* Returns a list containing all elements of the original collection without the first occurrence of the given [element].
*/
operator fun <T> MongoIterable<T>.minus(element: T): List<T> {
return useCursor { it.minus(element) }
}
/**
* Returns a list containing all elements of the original collection except the elements contained in the given [elements] array.
*/
operator fun <T> MongoIterable<T>.minus(elements: Array<out T>): List<T> {
return useCursor { it.minus(elements) }
}
/**
* Returns a list containing all elements of the original collection except the elements contained in the given [elements] collection.
*/
operator fun <T> MongoIterable<T>.minus(elements: Iterable<T>): List<T> {
return useCursor { it.minus(elements) }
}
/**
* Returns a list containing all elements of the original collection except the elements contained in the given [elements] sequence.
*/
operator fun <T> MongoIterable<T>.minus(elements: Sequence<T>): List<T> {
return useCursor { it.minus(elements) }
}
/**
* Returns a list containing all elements of the original collection without the first occurrence of the given [element].
*/
@InlineOnly
inline fun <T> MongoIterable<T>.minusElement(element: T): List<T> {
return useCursor { it.minusElement(element) }
}
/**
* Splits the original collection into pair of lists,
* where *first* list contains elements for which [predicate] yielded `true`,
* while *second* list contains elements for which [predicate] yielded `false`.
*/
inline fun <T> MongoIterable<T>.partition(crossinline predicate: (T) -> Boolean): Pair<List<T>, List<T>> {
return useCursor { it.partition(predicate) }
}
/**
* Returns a list containing all elements of the original collection and then the given [element].
*/
operator fun <T> MongoIterable<T>.plus(element: T): List<T> {
return useCursor { it.plus(element) }
}
/**
* Returns a list containing all elements of the original collection and then all elements of the given [elements] array.
*/
operator fun <T> MongoIterable<T>.plus(elements: Array<out T>): List<T> {
return useCursor { it.plus(elements) }
}
/**
* Returns a list containing all elements of the original collection and then all elements of the given [elements] collection.
*/
operator fun <T> MongoIterable<T>.plus(elements: Iterable<T>): List<T> {
return useCursor { it.plus(elements) }
}
/**
* Returns a list containing all elements of the original collection and then all elements of the given [elements] sequence.
*/
operator fun <T> MongoIterable<T>.plus(elements: Sequence<T>): List<T> {
return useCursor { it.plus(elements) }
}
/**
* Returns a list containing all elements of the original collection and then the given [element].
*/
@InlineOnly
inline fun <T> MongoIterable<T>.plusElement(element: T): List<T> {
return useCursor { it.plusElement(element) }
}
/**
* Returns a list of snapshots of the window of the given [size]
* sliding along this collection with the given [step], where each
* snapshot is a list.
*
* Several last lists may have less elements than the given [size].
*
* Both [size] and [step] must be positive and can be greater than the number of elements in this collection.
* @param size the number of elements to take in each window
* @param step the number of elements to move the window forward by on an each step, by default 1
* @param partialWindows controls whether or not to keep partial windows in the end if any,
* by default `false` which means partial windows won't be preserved
*
* @sample samples.collections.Sequences.Transformations.takeWindows
*/
@SinceKotlin("1.2")
fun <T> MongoIterable<T>.windowed(size: Int, step: Int = 1, partialWindows: Boolean = false): List<List<T>> {
return useCursor { it.windowed(size, step, partialWindows) }
}
/**
* Returns a list of results of applying the given [transform] function to
* an each list representing a view over the window of the given [size]
* sliding along this collection with the given [step].
*
* Note that the list passed to the [transform] function is ephemeral and is valid only inside that function.
* You should not store it or allow it to escape in some way, unless you made a snapshot of it.
* Several last lists may have less elements than the given [size].
*
* Both [size] and [step] must be positive and can be greater than the number of elements in this collection.
* @param size the number of elements to take in each window
* @param step the number of elements to move the window forward by on an each step, by default 1
* @param partialWindows controls whether or not to keep partial windows in the end if any,
* by default `false` which means partial windows won't be preserved
*
* @sample samples.collections.Sequences.Transformations.averageWindows
*/
@SinceKotlin("1.2")
fun <T, R> MongoIterable<T>.windowed(
size: Int,
step: Int = 1,
partialWindows: Boolean = false,
transform: (List<T>) -> R
): List<R> {
return useCursor { it.windowed(size, step, partialWindows, transform) }
}
/**
* Returns a list of pairs built from the elements of `this` collection and the [other] array with the same index.
* The returned list has length of the shortest collection.
*
* @sample samples.collections.Iterables.Operations.zipIterable
*/
infix fun <T, R> MongoIterable<T>.zip(other: Array<out R>): List<Pair<T, R>> {
return useCursor { it.zip(other) }
}
/**
* Returns a list of values built from the elements of `this` collection and the [other] array with the same index
* using the provided [transform] function applied to each pair of elements.
* The returned list has length of the shortest collection.
*
* @sample samples.collections.Iterables.Operations.zipIterableWithTransform
*/
inline fun <T, R, V> MongoIterable<T>.zip(other: Array<out R>, crossinline transform: (a: T, b: R) -> V): List<V> {
return useCursor { it.zip(other, transform) }
}
/**
* Returns a list of pairs built from the elements of `this` collection and [other] collection with the same index.
* The returned list has length of the shortest collection.
*
* @sample samples.collections.Iterables.Operations.zipIterable
*/
infix fun <T, R> MongoIterable<T>.zip(other: Iterable<R>): List<Pair<T, R>> {
return useCursor { it.zip(other) }
}
/**
* Returns a list of values built from the elements of `this` collection and the [other] collection with the same index
* using the provided [transform] function applied to each pair of elements.
* The returned list has length of the shortest collection.
*
* @sample samples.collections.Iterables.Operations.zipIterableWithTransform
*/
inline fun <T, R, V> MongoIterable<T>.zip(other: Iterable<R>, crossinline transform: (a: T, b: R) -> V): List<V> {
return useCursor { it.zip(other, transform) }
}
/**
* Returns a list of pairs of each two adjacent elements in this collection.
*
* The returned list is empty if this collection contains less than two elements.
*
* @sample samples.collections.Collections.Transformations.zipWithNext
*/
@SinceKotlin("1.2")
fun <T> MongoIterable<T>.zipWithNext(): List<Pair<T, T>> {
return useCursor { it.zipWithNext() }
}
/**
* Returns a list containing the results of applying the given [transform] function
* to an each pair of two adjacent elements in this collection.
*
* The returned list is empty if this collection contains less than two elements.
*
* @sample samples.collections.Collections.Transformations.zipWithNextToFindDeltas
*/
@SinceKotlin("1.2")
inline fun <T, R> MongoIterable<T>.zipWithNext(crossinline transform: (a: T, b: T) -> R): List<R> {
return useCursor { it.zipWithNext(transform) }
}
/**
* Appends the string from all the elements separated using [separator] and using the given [prefix] and [postfix] if supplied.
*
* If the collection could be huge, you can specify a non-negative value of [limit], in which case only the first [limit]
* elements will be appended, followed by the [truncated] string (which defaults to "...").
*
* @sample samples.collections.Collections.Transformations.joinTo
*/
fun <T, A : Appendable> MongoIterable<T>.joinTo(
buffer: A,
separator: CharSequence = ", ",
prefix: CharSequence = "",
postfix: CharSequence = "",
limit: Int = -1,
truncated: CharSequence = "...",
transform: ((T) -> CharSequence)? = null
): A {
return useCursor { it.joinTo(buffer, separator, prefix, postfix, limit, truncated, transform) }
}
/**
* Creates a string from all the elements separated using [separator] and using the given [prefix] and [postfix] if supplied.
*
* If the collection could be huge, you can specify a non-negative value of [limit], in which case only the first [limit]
* elements will be appended, followed by the [truncated] string (which defaults to "...").
*
* @sample samples.collections.Collections.Transformations.joinToString
*/
fun <T> MongoIterable<T>.joinToString(
separator: CharSequence = ", ",
prefix: CharSequence = "",
postfix: CharSequence = "",
limit: Int = -1,
truncated: CharSequence = "...",
transform: ((T) -> CharSequence)? = null
): String {
return useCursor { it.joinToString(separator, prefix, postfix, limit, truncated, transform) }
}
/**
* Returns an average value of elements in the collection.
*/
@kotlin.jvm.JvmName("averageOfByte")
fun MongoIterable<Byte>.average(): Double {
return useCursor { it.average() }
}
/**
* Returns an average value of elements in the collection.
*/
@kotlin.jvm.JvmName("averageOfShort")
fun MongoIterable<Short>.average(): Double {
return useCursor { it.average() }
}
/**
* Returns an average value of elements in the collection.
*/
@kotlin.jvm.JvmName("averageOfInt")
fun MongoIterable<Int>.average(): Double {
return useCursor { it.average() }
}
/**
* Returns an average value of elements in the collection.
*/
@kotlin.jvm.JvmName("averageOfLong")
fun MongoIterable<Long>.average(): Double {
return useCursor { it.average() }
}
/**
* Returns an average value of elements in the collection.
*/
@kotlin.jvm.JvmName("averageOfFloat")
fun MongoIterable<Float>.average(): Double {
return useCursor { it.average() }
}
/**
* Returns an average value of elements in the collection.
*/
@kotlin.jvm.JvmName("averageOfDouble")
fun MongoIterable<Double>.average(): Double {
return useCursor { it.average() }
}
/**
* Returns the sum of all elements in the collection.
*/
@kotlin.jvm.JvmName("sumOfByte")
fun MongoIterable<Byte>.sum(): Int {
return useCursor { it.sum() }
}
/**
* Returns the sum of all elements in the collection.
*/
@kotlin.jvm.JvmName("sumOfShort")
fun MongoIterable<Short>.sum(): Int {
return useCursor { it.sum() }
}
/**
* Returns the sum of all elements in the collection.
*/
@kotlin.jvm.JvmName("sumOfInt")
fun MongoIterable<Int>.sum(): Int {
return useCursor { it.sum() }
}
/**
* Returns the sum of all elements in the collection.
*/
@kotlin.jvm.JvmName("sumOfLong")
fun MongoIterable<Long>.sum(): Long {
return useCursor { it.sum() }
}
/**
* Returns the sum of all elements in the collection.
*/
@kotlin.jvm.JvmName("sumOfFloat")
fun MongoIterable<Float>.sum(): Float {
return useCursor { it.sum() }
}
/**
* Returns the sum of all elements in the collection.
*/
@kotlin.jvm.JvmName("sumOfDouble")
fun MongoIterable<Double>.sum(): Double {
return useCursor { it.sum() }
}
/**
* Returns a single list of all elements from all collections in the given collection.
* @sample samples.collections.Iterables.Operations.flattenIterable
*/
fun <T> MongoIterable<Iterable<T>>.flatten(): List<T> {
return useCursor { it.flatten() }
}
/**
* Returns a pair of lists, where
* *first* list is built from the first values of each pair from this collection,
* *second* list is built from the second values of each pair from this collection.
* @sample samples.collections.Iterables.Operations.unzipIterable
*/
fun <T, R> MongoIterable<Pair<T, R>>.unzip(): Pair<List<T>, List<R>> {
return useCursor { it.unzip() }
}
/**
* Returns a new map containing all key-value pairs from the given collection of pairs.
*
* The returned map preserves the entry iteration order of the original collection.
*/
fun <K, V> MongoIterable<Pair<K, V>>.toMap(): Map<K, V> {
return useCursor { it.toMap() }
}
/**
* Populates and returns the [destination] mutable map with key-value pairs from the given collection of pairs.
*/
fun <K, V, M : MutableMap<in K, in V>> MongoIterable<Pair<K, V>>.toMap(destination: M): M =
useCursor { it.toMap(destination) }
/**
* Returns a list containing all elements that are instances of specified class.
*/
fun <R> MongoIterable<*>.filterIsInstance(klass: Class<R>): List<R> {
return useCursor { it.filterIsInstance(klass) }
}
/**
* Appends all elements that are instances of specified class to the given [destination].
*/
fun <C : MutableCollection<in R>, R> MongoIterable<*>.filterIsInstanceTo(destination: C, klass: Class<R>): C {
return useCursor { it.filterIsInstanceTo(destination, klass) }
}
/**
* Returns a [SortedSet][java.util.SortedSet] of all elements.
*/
fun <T : Comparable<T>> MongoIterable<T>.toSortedSet(): java.util.SortedSet<T> {
return useCursor { it.toSortedSet() }
}
/**
* Returns a [SortedSet][java.util.SortedSet] of all elements.
*
* Elements in the set returned are sorted according to the given [comparator].
*/
fun <T> MongoIterable<T>.toSortedSet(comparator: Comparator<in T>): java.util.SortedSet<T> {
return useCursor { it.toSortedSet(comparator) }
}
/**
* Returns a new list with the elements of this list randomly shuffled.
*/
@SinceKotlin("1.2")
fun <T> MongoIterable<T>.shuffled(): List<T> = useCursor { it.shuffled() }
/**
* Returns a new list with the elements of this list randomly shuffled
* using the specified [random] instance as the source of randomness.
*/
@SinceKotlin("1.2")
fun <T> MongoIterable<T>.shuffled(random: java.util.Random): List<T> = useCursor { it.shuffled(random) }
| apache-2.0 | 9e05d17fff03dc3ccdf0db7b2529c012 | 33.538965 | 153 | 0.710339 | 3.8332 | false | false | false | false |
Szewek/Minecraft-Flux | src/main/java/szewek/mcflux/util/MCFluxReport.kt | 1 | 2326 | package szewek.mcflux.util
import com.rollbar.notifier.Rollbar
import com.rollbar.notifier.config.ConfigBuilder
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap
import net.minecraftforge.common.ForgeVersion
import net.minecraftforge.fml.common.Loader
import szewek.mcflux.MCFlux.Companion.L
import szewek.mcflux.R
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.PrintStream
import java.text.SimpleDateFormat
import java.util.*
import java.util.zip.GZIPOutputStream
object MCFluxReport {
private val rollbar = Rollbar(ConfigBuilder.withAccessToken(R.MF_ACCESS_TOKEN)
.environment(R.MF_ENVIRONMENT)
.codeVersion(R.MF_VERSION)
.custom(::addCustomInfo)
.platform(System.getProperty("os.name"))
.build())
private val errMsgs = Int2ObjectOpenHashMap<ErrMsg>()
private val fileDate = SimpleDateFormat("yyyy-MM-dd_HH.mm.ss")
private fun addCustomInfo(): Map<String, Any> {
val cm = HashMap<String, Any>()
cm["Forge"] = ForgeVersion.getVersion()
cm["Mods"] = Loader.instance().indexedModList.keys.toTypedArray()
return cm
}
fun handleErrors() {
rollbar.handleUncaughtErrors()
}
fun sendException(th: Throwable, n: String) {
rollbar.warning(th, n + ": " + th.message)
}
fun addErrMsg(em: ErrMsg) {
val hc = em.hashCode()
em.sendInfo(rollbar)
if (errMsgs.containsKey(hc)) {
val xem = errMsgs.get(hc)
xem.addThrowable(em.msgThrown)
xem.addUp()
} else {
errMsgs[hc] = em
em.addUp()
}
}
@Throws(IOException::class)
fun reportAll(dirf: File) {
if (!errMsgs.isEmpty()) {
val f = File(dirf, "mcflux-" + fileDate.format(Date()) + ".log.gz")
val ps = PrintStream(GZIPOutputStream(FileOutputStream(f)))
ps.println("== START OF ERROR MESSAGES")
for (em in errMsgs.values) {
ps.println("+-- ErrMsg: $em")
ps.println(em.makeInfo())
val lt = em.throwables
if (lt.isEmpty())
ps.println("| No throwables found.")
else {
ps.println("| Throwables: " + lt.size)
for (th in lt) {
if (th == null) {
ps.println("A null throwable found.")
continue
}
th.printStackTrace(ps)
ps.println()
}
}
ps.println("+--")
}
ps.println("== END OF ERROR MESSAGES")
errMsgs.clear()
ps.close()
} else
L!!.info("No errors found!")
}
}
| mit | a8a24cf65d0b41263e7f928798afe088 | 25.735632 | 79 | 0.683147 | 3.130552 | false | false | false | false |
TheContext/podcast-ci | src/test/kotlin/io/thecontext/podcaster/input/InputFilesLocatorSpec.kt | 1 | 4351 | package io.thecontext.podcaster.input
import com.greghaskins.spectrum.Spectrum
import com.greghaskins.spectrum.dsl.specification.Specification.*
import io.reactivex.schedulers.Schedulers
import io.thecontext.podcaster.input.InputFilesLocator.FileNames
import io.thecontext.podcaster.input.InputFilesLocator.Result
import io.thecontext.podcaster.memoized
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import java.io.File
@RunWith(Spectrum::class)
class InputFilesLocatorSpec {
init {
val workingDir = TemporaryFolder()
val locator by memoized { InputFilesLocator.Impl(Schedulers.trampoline()) }
beforeEach {
workingDir.create()
}
describe("files available") {
beforeEach {
listOf(FileNames.PEOPLE, FileNames.PODCAST).forEach {
workingDir.newFile(it)
}
val episodeDir = workingDir.newFolder("episode-42")
listOf(FileNames.EPISODE, FileNames.EPISODE_NOTES).forEach {
File(episodeDir, it).createNewFile()
}
}
it("emits result as success") {
locator.locate(workingDir.root)
.test()
.assertValue { it is Result.Success }
}
}
describe("directory does not exist") {
it("emits result as failure") {
val dir = File("does-not-actually-exist")
locator.locate(dir)
.test()
.assertValue { it is Result.Failure }
}
}
describe("directory is not a directory") {
it("emits result as failure") {
val file = workingDir.newFile("podcast")
locator.locate(file)
.test()
.assertValue { it is Result.Failure }
}
}
describe("people file is not available") {
beforeEach {
workingDir.newFile(FileNames.PODCAST)
val episodeDir = workingDir.newFolder("episode-42")
listOf(FileNames.EPISODE, FileNames.EPISODE_NOTES).forEach {
File(episodeDir, it).createNewFile()
}
}
it("emits result as failure") {
locator.locate(workingDir.root)
.test()
.assertValue { it is Result.Failure }
}
}
describe("podcast file is not available") {
beforeEach {
workingDir.newFile(FileNames.PEOPLE)
val episodeDir = workingDir.newFolder("episode-42")
listOf(FileNames.EPISODE, FileNames.EPISODE_NOTES).forEach {
File(episodeDir, it).createNewFile()
}
}
it("emits result as failure") {
locator.locate(workingDir.root)
.test()
.assertValue { it is Result.Failure }
}
}
describe("episode file is not available") {
beforeEach {
listOf(FileNames.PEOPLE, FileNames.PODCAST).forEach {
workingDir.newFile(it)
}
val episodeDir = workingDir.newFolder("episode-42")
File(episodeDir, FileNames.EPISODE_NOTES).createNewFile()
}
it("emits result as failure") {
locator.locate(workingDir.root)
.test()
.assertValue { it is Result.Failure }
}
}
describe("episode notes file is not available") {
beforeEach {
listOf(FileNames.PEOPLE, FileNames.PODCAST).forEach {
workingDir.newFile(it)
}
val episodeDir = workingDir.newFolder("episode-42")
File(episodeDir, FileNames.EPISODE).createNewFile()
}
it("emits result as failure") {
locator.locate(workingDir.root)
.test()
.assertValue { it is Result.Failure }
}
}
afterEach {
workingDir.delete()
}
}
}
| apache-2.0 | 9c39d015bb8b85f848e1602fd71904cf | 28.80137 | 83 | 0.515054 | 5.364982 | false | false | false | false |
Nice3point/ScheduleMVP | app/src/main/java/nice3point/by/schedule/StartActivity/PStartActivity.kt | 1 | 1200 | package nice3point.by.schedule.StartActivity
import android.content.Context
import android.content.Intent
import android.preference.PreferenceManager
import android.widget.ArrayAdapter
import nice3point.by.schedule.Core.VCore
import nice3point.by.schedule.R
import nice3point.by.schedule.TechnicalModule
class PStartActivity(private val view: iVStartActivity) : iPStartActivity {
override fun buttonPressed(spinnerGroup: String) {
TechnicalModule.currentGroup = spinnerGroup
savePreferences(spinnerGroup)
val intent = Intent(view as Context, VCore::class.java)
view.startNextActivity(intent)
}
override fun getSpinnerAdapter(): ArrayAdapter<CharSequence> {
val adapter = ArrayAdapter.createFromResource(view as Context, R.array.Groups_list, R.layout.spinner_layout)
adapter.setDropDownViewResource(R.layout.background_spinner)
return adapter
}
override fun savePreferences(group: String) {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(view as Context)
val ed = sharedPreferences.edit()
ed.putString(TechnicalModule.getGroupAccessKey(), group)
ed.apply()
}
}
| apache-2.0 | 2c130930ec8a8d1b37744e099d9e35ec | 36.5 | 116 | 0.758333 | 4.580153 | false | false | false | false |
luks91/Team-Bucket | app/src/main/java/com/github/luks91/teambucket/main/MainPresenter.kt | 2 | 8733 | /**
* Copyright (c) 2017-present, Team Bucket Contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package com.github.luks91.teambucket.main
import android.support.annotation.StringRes
import com.github.luks91.teambucket.connection.ConnectionProvider
import com.github.luks91.teambucket.R
import com.github.luks91.teambucket.model.*
import com.github.luks91.teambucket.connection.BitbucketApi
import com.github.luks91.teambucket.ReactiveBus
import com.github.luks91.teambucket.persistence.RepositoriesStorage
import com.github.luks91.teambucket.util.MatchedResources
import com.github.luks91.teambucket.util.matchSortedWith
import com.hannesdorfmann.mosby3.mvp.MvpPresenter
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposables
import io.reactivex.functions.BiFunction
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class MainPresenter @Inject constructor(val connectionProvider: ConnectionProvider,
val repositoriesStorage: RepositoriesStorage,
val eventsBus: ReactiveBus) : MvpPresenter<MainView> {
private var disposable = Disposables.empty()
override fun attachView(view: MainView) {
val connection = connectionProvider.connections().publish()
val projectsSelection = Observable.combineLatest(
connection, eventsBus.receive(ReactiveBus.EventRepositoriesMissing::class.java)
.debounce(100, TimeUnit.MILLISECONDS)
.cast(Any::class.java)
.mergeWith(view.intentRepositorySettings()),
BiFunction<BitbucketConnection, Any, Observable<List<Project>>> {
(_, _, api, token), _ -> projectSelection(api, token, view)
}
).switchMap { obs -> obs }.publish()
val repositoriesSelection =
Observable.combineLatest(
connection, projectsSelection,
BiFunction<BitbucketConnection, List<Project>, Observable<List<Repository>>> {
(_, _, api, token), projects -> repositoriesSelection(projects, api, token, view)
}
).switchMap { obs -> obs }.publish()
disposable = CompositeDisposable(
eventsBus.receive(ReactiveBus.EventCredentialsInvalid::class.java)
.debounce(500, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.filter { it.message > 0 }
.observeOn(AndroidSchedulers.mainThread())
.subscribe { view.showErrorNotification(it.message) },
eventsBus.receive(ReactiveBus.EventCredentialsInvalid::class.java)
.debounce(500, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.zipWith(eventsBus.receive(BitbucketCredentials::class.java)
.mergeWith(connectionProvider.cachedCredentials().toObservable())
.subscribeOn(Schedulers.io()),
BiFunction<Any, BitbucketCredentials, Observable<BitbucketCredentials>> {
_, previousCredentials -> view.requestUserCredentials(previousCredentials)
})
.observeOn(AndroidSchedulers.mainThread())
.switchMap { obs -> obs }
.observeOn(Schedulers.io())
.subscribe { credentials -> eventsBus.post(credentials) },
repositoriesStorage.subscribeRepositoriesPersisting(projectsSelection, repositoriesSelection),
repositoriesSelection.connect(),
projectsSelection.connect(),
connectionProvider.connections()
.observeOn(Schedulers.io())
.switchMap { (userName, _, api, token) -> api.getUser(token, userName)
.onErrorResumeNext { _: Throwable -> Observable.empty<User>() } }
.map { user -> user.displayName }
.observeOn(AndroidSchedulers.mainThread())
.subscribe { view.displayUserName(it) },
connection.connect()
)
}
private fun projectSelection(api: BitbucketApi, token: String, view: MainView): Observable<List<Project>> {
return BitbucketApi.queryPaged { start -> api.getProjects(token, start) }
.subscribeOn(Schedulers.io())
.onErrorResumeNext(connectionProvider.handleNetworkError(MainPresenter::class.java.simpleName))
.reduce { t1, t2 -> t1 + t2 }.toObservable()
.withLatestFrom(
repositoriesStorage.selectedProjects(sortColumn = "key"),
BiFunction<List<Project>, List<Project>, Observable<List<Project>>> {
remoteProjects, localProjects ->
requestUserToSelectFrom(
remoteProjects.sortedBy { it.key }
.matchSortedWith(localProjects, compareBy<Project> { it.key }),
view, R.string.projects_choose_header, { data -> data.name })
}
)
.observeOn(AndroidSchedulers.mainThread())
.concatMap { obs -> obs }
}
private inline fun <T> requestUserToSelectFrom(resources: MatchedResources<T>, view: MainView, @StringRes headerText: Int,
crossinline labelFunction: (T) -> String): Observable<List<T>> {
return Observable.just(resources.resources).zipWith(
Observable.just(resources)
.observeOn(AndroidSchedulers.mainThread())
.concatMap { resources -> view.requestToSelectFrom(headerText, resources.resources.map(labelFunction),
resources.matchedIndices.toIntArray())},
BiFunction<List<T>, List<Int>, List<T>> {
projects, selection ->
projects.filterIndexed { index, _ -> selection.contains(index) }
})
}
private fun repositoriesSelection(projects: List<Project>, api: BitbucketApi, token: String, view: MainView)
: Observable<List<Repository>> {
return Observable.fromIterable(projects).flatMap { (key) -> Observable.empty<List<Repository>>()
BitbucketApi.queryPaged { start -> api.getProjectRepositories(token, key, start) }
.subscribeOn(Schedulers.io())
}
.onErrorResumeNext(connectionProvider.handleNetworkError(MainPresenter::class.java.simpleName))
.reduce { t1, t2 -> t1 + t2 }.toObservable()
.withLatestFrom(
repositoriesStorage.selectedRepositories(sortColumn = "slug", notifyIfMissing = false),
BiFunction<List<Repository>, List<Repository>, Observable<List<Repository>>> {
remoteRepositories, remoteProjects ->
requestUserToSelectFrom(
remoteRepositories.sortedBy { it.slug }
.matchSortedWith(remoteProjects, compareBy<Repository> { it.slug }),
view, R.string.repositories_choose_header, { data -> data.name })
}
)
.observeOn(AndroidSchedulers.mainThread())
.concatMap { obs -> obs }
.first(listOf<Repository>())
.toObservable()
}
override fun detachView(retainInstance: Boolean) {
disposable.dispose()
}
} | apache-2.0 | 8382f8e939f3294e486de94960e36bef | 54.987179 | 126 | 0.58445 | 5.659754 | false | false | false | false |
FutureioLab/FastPeak | app/src/main/java/com/binlly/fastpeak/base/glide/progress/ProgressManager.kt | 1 | 2169 | package com.binlly.fastpeak.base.glide.progress
import android.widget.ImageView
import com.bumptech.glide.load.engine.GlideException
import okhttp3.OkHttpClient
import java.lang.ref.WeakReference
import java.util.concurrent.ConcurrentHashMap
object ProgressManager {
private val listeners = ConcurrentHashMap<WeakReference<ImageView>, WeakReference<OnProgressListener>>()
val okHttpClient: OkHttpClient by lazy {
OkHttpClient.Builder().addNetworkInterceptor { chain ->
val request = chain.request()
val response = chain.proceed(request)
response.newBuilder().body(
ProgressResponseBody(request.url().toString(), response.body(),
listener)).build()
}.build()
}
private val listener = object: OnProgressListener {
override fun onProgress(imageUrl: String, bytesRead: Long, totalBytes: Long,
isDone: Boolean, exception: GlideException?) {
listeners.forEach { (imageview, listener) ->
listener.get()?.onProgress(imageUrl, bytesRead, totalBytes, isDone,
exception) ?: listeners.remove(imageview)
}
}
}
fun addProgressListener(imageView: ImageView, progressListener: OnProgressListener?) {
progressListener ?: return
removeProgressListener(imageView)
listeners.put(WeakReference(imageView), WeakReference(progressListener))
}
fun removeProgressListener(imageView: ImageView) {
listeners.forEach { (view, _) ->
if (view.get() === imageView) {
listeners.remove(view)
return
}
}
}
fun clearInvalidValues() {
listeners.forEach { (view, _) ->
if (view.get() === null) {
listeners.remove(view)
}
}
}
private fun findProgressListener(imageView: ImageView): OnProgressListener? {
listeners.forEach { (view, listener) ->
if (view.get() === imageView) {
return listener.get()
}
}
return null
}
}
| mit | a455ba312adc19ae130723365b5ee391 | 32.890625 | 108 | 0.603504 | 5.342365 | false | false | false | false |
googlecodelabs/android-compose-codelabs | AccessibilityCodelab/app/src/main/java/com/example/jetnews/ui/components/InsetAwareTopAppBar.kt | 1 | 2226 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetnews.ui.components
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.TopAppBar
import androidx.compose.material.contentColorFor
import androidx.compose.material.primarySurface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
/**
* A wrapper around [TopAppBar] which uses [Modifier.statusBarsPadding] to shift the app bar's
* contents down, but still draws the background behind the status bar too.
*/
@Composable
fun InsetAwareTopAppBar(
title: @Composable () -> Unit,
modifier: Modifier = Modifier,
navigationIcon: @Composable (() -> Unit)? = null,
actions: @Composable RowScope.() -> Unit = {},
backgroundColor: Color = MaterialTheme.colors.primarySurface,
contentColor: Color = contentColorFor(backgroundColor),
elevation: Dp = 4.dp
) {
Surface(
color = backgroundColor,
elevation = elevation,
modifier = modifier
) {
TopAppBar(
title = title,
navigationIcon = navigationIcon,
actions = actions,
backgroundColor = Color.Transparent,
contentColor = contentColor,
elevation = 0.dp,
modifier = Modifier.statusBarsPadding()
)
}
}
| apache-2.0 | 708ded46ec6ef13460f00ade07d35ff5 | 34.903226 | 94 | 0.728212 | 4.618257 | false | false | false | false |
QReport/q-report | src/main/kotlin/ru/redenergy/report/client/ui/admin/StatisticsShow.kt | 2 | 4164 | package ru.redenergy.report.client.ui.admin
import com.rabbit.gui.background.DefaultBackground
import com.rabbit.gui.component.control.Button
import com.rabbit.gui.component.control.MultiTextbox
import com.rabbit.gui.component.display.Shape
import com.rabbit.gui.component.display.ShapeType
import com.rabbit.gui.component.display.TextLabel
import com.rabbit.gui.component.display.graph.PieChart
import com.rabbit.gui.render.TextAlignment
import com.rabbit.gui.show.Show
import net.minecraft.client.resources.I18n
import org.apache.commons.lang3.time.DurationFormatUtils
import ru.redenergy.report.client.QReportClient
import java.awt.Color
class StatisticsShow: Show() {
init {
background = DefaultBackground()
}
override fun setup() {
super.setup()
registerComponent(TextLabel(this.width / 3, this.height / 5, this.width / 3, 20, I18n.format("show.stats.title"), TextAlignment.CENTER))
val avgTime = if(QReportClient.syncedStats.averageTime == -1L) I18n.format("show.stats.unknown")
else formatAverageResponseTime()
registerComponent(TextLabel(this.width / 3 + this.width / 20, this.height / 3, this.width / 3, 20, I18n.format("show.stats.avgtime", avgTime)))
registerComponent(MultiTextbox(this.width / 3 + this.width / 20 - 5, this.height / 3 + 30, this.width / 3, this.height / 7)
.setId("active_users")
.setBackgroundVisibility(false)
.setIsEnabled(false))
updateActiveUsersLabel()
val data = if(QReportClient.syncedStats.tickets.values.sum() == 0) doubleArrayOf(1.0, 1.0, 1.0, 1.0)
else QReportClient.syncedStats.tickets.values.map { it.toDouble() } .toDoubleArray()
registerComponent(PieChart(this.width / 3 + this.width / 20, this.height / 2 + this.height / 10, (this.width / 7 + this.height / 5) / 2,
data,
QReportClient.syncedStats.tickets.values.toList().map { it.toString() }.toTypedArray()))
val colorLabelsX = this.width / 2 + 25
val colorLabelsY = this.width / 18 + this.height / 2;
val colorShapeWidth = this.width / 60
val colorShapeHeight = this.height / 50
val colorTitles = QReportClient.syncedStats.tickets.keys.toList().map { I18n.format(it.translateKey) }
for((i, color) in arrayOf(Color.BLUE, Color.RED, Color.ORANGE, Color.MAGENTA).withIndex()){
registerComponent(TextLabel(colorLabelsX + colorShapeWidth, colorLabelsY + this.height / 6 - this.height / 20 * i, 200, 20, " - ${colorTitles[i]}"))
registerComponent(Shape(colorLabelsX, colorLabelsY + this.height / 6 - this.height / 20 * i, colorShapeWidth, colorShapeHeight, ShapeType.RECT, color))
}
registerComponent(Button(this.width / 3, this.height / 10 * 9, this.width / 3, 20, I18n.format("show.stats.back"))
.setClickListener { this.getStage().displayPrevious() })
}
fun formatAverageResponseTime(): String = DurationFormatUtils.formatDuration(QReportClient.syncedStats.averageTime, "HH:mm")
fun updateActiveUsersLabel(){
val output = StringBuilder()
with(output){
if(QReportClient.syncedStats.activeUsers.size > 0) {
append("${I18n.format("show.stats.activeusers")} \n")
QReportClient.syncedStats.activeUsers.forEach {
append("${it.key} - ${it.value} ${declensionTicketsLocales(it.value)}\n")
}
}
}
findComponentById<MultiTextbox>("active_users").setText(output.toString())
}
fun declensionTicketsLocales(amount: Int): String{
val remainder = amount % 10
val secondRemainder = (remainder / 10) % 10
if((remainder == 1) && (secondRemainder != 1))
return I18n.format("ticket.one")
else if ((remainder >= 2) && (remainder <= 4) && (secondRemainder != 1))
return I18n.format("ticket.few")
else
return I18n.format("ticket.many")
}
} | mit | 1836016cc0f9600585f164faae7efe92 | 46.44186 | 163 | 0.64073 | 3.887955 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/action/movement/polar/AcceleratePolarInput.kt | 1 | 1739 | /*
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.action.movement.polar
import uk.co.nickthecoder.tickle.action.Action
import uk.co.nickthecoder.tickle.events.Input
import uk.co.nickthecoder.tickle.resources.Resources
import uk.co.nickthecoder.tickle.util.Polar2d
open class AcceleratePolarInput(
val velocity: Polar2d,
var acceleration: Double,
var deceleration: Double = -acceleration,
var autoSlow: Double = 0.0,
accelerate: String = "up",
decelerate: String = "down")
: Action {
val accelerate = Resources.instance.inputs.find(accelerate) ?: Input.dummyInput
val decelerate = Resources.instance.inputs.find(decelerate) ?: Input.dummyInput
override fun act(): Boolean {
if (accelerate.isPressed()) {
velocity.magnitude += acceleration
} else if (decelerate.isPressed()) {
velocity.magnitude += deceleration
} else {
// Automatically slow down (gradually), when no keys are pressed
velocity.magnitude -= autoSlow
}
return false
}
}
| gpl-3.0 | b20596ccfaa62c8144920914beddfdda | 33.78 | 83 | 0.712478 | 4.241463 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/events/MouseInput.kt | 1 | 1158 | /*
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.events
import org.lwjgl.glfw.GLFW
import uk.co.nickthecoder.tickle.graphics.Window
class MouseInput(val mouseButton: Int, val state: ButtonState) : Input {
override fun isPressed(): Boolean {
return GLFW.glfwGetMouseButton(Window.instance?.handle ?: 0, mouseButton) == GLFW.GLFW_PRESS
}
override fun matches(event: KeyEvent): Boolean {
return false
}
override fun toString() = "MouseInput key=$mouseButton state=$state"
}
| gpl-3.0 | de8336e3a4030c8b21ae8fa86bb0506c | 31.166667 | 100 | 0.755613 | 4.257353 | false | false | false | false |
FWDekker/intellij-randomness | src/main/kotlin/com/fwdekker/randomness/decimal/DecimalSchemeEditor.kt | 1 | 5936 | package com.fwdekker.randomness.decimal
import com.fwdekker.randomness.Bundle
import com.fwdekker.randomness.StateEditor
import com.fwdekker.randomness.array.ArrayDecoratorEditor
import com.fwdekker.randomness.decimal.DecimalScheme.Companion.DEFAULT_DECIMAL_SEPARATOR
import com.fwdekker.randomness.decimal.DecimalScheme.Companion.DEFAULT_GROUPING_SEPARATOR
import com.fwdekker.randomness.decimal.DecimalScheme.Companion.MAX_VALUE_DIFFERENCE
import com.fwdekker.randomness.decimal.DecimalScheme.Companion.MIN_DECIMAL_COUNT
import com.fwdekker.randomness.ui.JDoubleSpinner
import com.fwdekker.randomness.ui.JIntSpinner
import com.fwdekker.randomness.ui.MaxLengthDocumentFilter
import com.fwdekker.randomness.ui.MinMaxLengthDocumentFilter
import com.fwdekker.randomness.ui.UIConstants
import com.fwdekker.randomness.ui.VariableLabelRadioButton
import com.fwdekker.randomness.ui.addChangeListenerTo
import com.fwdekker.randomness.ui.bindSpinners
import com.fwdekker.randomness.ui.getValue
import com.fwdekker.randomness.ui.setLabel
import com.fwdekker.randomness.ui.setValue
import com.intellij.ui.SeparatorFactory
import com.intellij.ui.TitledSeparator
import javax.swing.ButtonGroup
import javax.swing.JCheckBox
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.JTextField
import javax.swing.event.ChangeEvent
/**
* Component for editing random decimal settings.
*
* @param scheme the scheme to edit in the component
*/
@Suppress("LateinitUsage") // Initialized by scene builder
class DecimalSchemeEditor(scheme: DecimalScheme = DecimalScheme()) : StateEditor<DecimalScheme>(scheme) {
override lateinit var rootComponent: JPanel private set
override val preferredFocusedComponent
get() = minValue.editorComponent
private lateinit var valueSeparator: TitledSeparator
private lateinit var minValue: JDoubleSpinner
private lateinit var maxValue: JDoubleSpinner
private lateinit var decimalCount: JIntSpinner
private lateinit var showTrailingZeroesCheckBox: JCheckBox
private lateinit var groupingSeparatorLabel: JLabel
private lateinit var groupingSeparatorGroup: ButtonGroup
private lateinit var customGroupingSeparator: VariableLabelRadioButton
private lateinit var decimalSeparatorLabel: JLabel
private lateinit var decimalSeparatorGroup: ButtonGroup
private lateinit var customDecimalSeparator: VariableLabelRadioButton
private lateinit var prefixInput: JTextField
private lateinit var suffixInput: JTextField
private lateinit var arrayDecoratorPanel: JPanel
private lateinit var arrayDecoratorEditor: ArrayDecoratorEditor
init {
decimalCount.addChangeListener(
{ _: ChangeEvent? ->
showTrailingZeroesCheckBox.isEnabled = decimalCount.value > 0
}.also { it(null) }
)
customGroupingSeparator.addToButtonGroup(groupingSeparatorGroup)
groupingSeparatorGroup.setLabel(groupingSeparatorLabel)
customDecimalSeparator.addToButtonGroup(decimalSeparatorGroup)
decimalSeparatorGroup.setLabel(decimalSeparatorLabel)
loadState()
}
/**
* Initializes custom UI components.
*
* This method is called by the scene builder at the start of the constructor.
*/
@Suppress("UnusedPrivateMember") // Used by scene builder
private fun createUIComponents() {
valueSeparator = SeparatorFactory.createSeparator(Bundle("decimal.ui.value_separator"), null)
minValue = JDoubleSpinner()
maxValue = JDoubleSpinner()
bindSpinners(minValue, maxValue, MAX_VALUE_DIFFERENCE)
decimalCount = JIntSpinner(value = MIN_DECIMAL_COUNT, minValue = MIN_DECIMAL_COUNT)
customGroupingSeparator = VariableLabelRadioButton(UIConstants.WIDTH_TINY, MaxLengthDocumentFilter(1))
customDecimalSeparator = VariableLabelRadioButton(UIConstants.WIDTH_TINY, MinMaxLengthDocumentFilter(1, 1))
arrayDecoratorEditor = ArrayDecoratorEditor(originalState.arrayDecorator)
arrayDecoratorPanel = arrayDecoratorEditor.rootComponent
}
override fun loadState(state: DecimalScheme) {
super.loadState(state)
minValue.value = state.minValue
maxValue.value = state.maxValue
decimalCount.value = state.decimalCount
showTrailingZeroesCheckBox.isSelected = state.showTrailingZeroes
customGroupingSeparator.label = state.customGroupingSeparator
groupingSeparatorGroup.setValue(state.groupingSeparator)
customDecimalSeparator.label = state.customDecimalSeparator
decimalSeparatorGroup.setValue(state.decimalSeparator)
prefixInput.text = state.prefix
suffixInput.text = state.suffix
arrayDecoratorEditor.loadState(state.arrayDecorator)
}
override fun readState() =
DecimalScheme(
minValue = minValue.value,
maxValue = maxValue.value,
decimalCount = decimalCount.value,
showTrailingZeroes = showTrailingZeroesCheckBox.isSelected,
groupingSeparator = groupingSeparatorGroup.getValue() ?: DEFAULT_GROUPING_SEPARATOR,
customGroupingSeparator = customGroupingSeparator.label,
decimalSeparator = decimalSeparatorGroup.getValue() ?: DEFAULT_DECIMAL_SEPARATOR,
customDecimalSeparator = customDecimalSeparator.label,
prefix = prefixInput.text,
suffix = suffixInput.text,
arrayDecorator = arrayDecoratorEditor.readState()
).also { it.uuid = originalState.uuid }
override fun addChangeListener(listener: () -> Unit) =
addChangeListenerTo(
minValue, maxValue, decimalCount, showTrailingZeroesCheckBox, groupingSeparatorGroup,
customGroupingSeparator, decimalSeparatorGroup, customDecimalSeparator, prefixInput, suffixInput,
arrayDecoratorEditor,
listener = listener
)
}
| mit | 421afb347c1114216794c7588f676d6e | 42.647059 | 115 | 0.763477 | 5.202454 | false | false | false | false |
android/user-interface-samples | WindowManager/app/src/main/java/com/example/windowmanagersample/embedding/SplitActivityTrampoline.kt | 1 | 2425 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.windowmanagersample.embedding
import android.content.Intent
import android.os.Bundle
import android.util.LayoutDirection
import androidx.window.core.ExperimentalWindowApi
import androidx.window.embedding.ActivityFilter
import androidx.window.embedding.SplitController
import androidx.window.embedding.SplitPlaceholderRule
import androidx.window.embedding.SplitRule
/**
* Example trampoline activity that launches a split and finishes itself.
*/
@ExperimentalWindowApi
class SplitActivityTrampoline : SplitActivityBase() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val activityFilters = setOf(
ActivityFilter(
componentName(
"com.example.windowmanagersample.embedding.SplitActivityTrampolineTarget"
),
null
)
)
val placeholderIntent = Intent()
placeholderIntent.component =
componentName("com.example.windowmanagersample.embedding.SplitActivityPlaceholder")
val placeholderRule = SplitPlaceholderRule(
filters = activityFilters,
placeholderIntent = placeholderIntent,
isSticky = false,
finishPrimaryWithSecondary = SplitRule.FINISH_ADJACENT,
minWidth = minSplitWidth(),
minSmallestWidth = 0,
splitRatio = SPLIT_RATIO,
layoutDirection = LayoutDirection.LOCALE
)
SplitController.getInstance().registerRule(placeholderRule)
val activityIntent = Intent()
activityIntent.component = componentName(
"com.example.windowmanagersample.embedding.SplitActivityTrampolineTarget"
)
startActivity(activityIntent)
finish()
}
}
| apache-2.0 | 79af853c0d2c1262977ae2f5a06cc2ea | 35.742424 | 95 | 0.705155 | 5.116034 | false | false | false | false |
LorittaBot/Loritta | web/showtime/web-common/src/commonMain/kotlin/com/mrpowergamerbr/loritta/utils/locale/BaseLocale.kt | 1 | 2210 | package com.mrpowergamerbr.loritta.utils.locale
import kotlinx.serialization.Serializable
import mu.KotlinLogging
import net.perfectdreams.loritta.api.utils.format
@Serializable
class BaseLocale(val id: String) {
companion object {
private val logger = KotlinLogging.logger {}
}
val localeStringEntries = mutableMapOf<String, String?>()
val localeListEntries = mutableMapOf<String, List<String>?>()
val path: String
get() = this["website.localePath"]
fun get(localeKeyData: LocaleKeyData): String {
// The spread operator is used in a .get(...) because it doesn't work inside of a [...], I don't know why
val arguments = localeKeyData.arguments?.map {
when (it) {
is LocaleStringData -> it.text
is LocaleKeyData -> get(it)
else -> it.toString()
}
}?.toTypedArray() ?: arrayOf()
return get(
localeKeyData.key,
*arguments
)
}
fun getList(localeKeyData: LocaleKeyData): List<String> {
val arguments = localeKeyData.arguments?.map {
when (it) {
is LocaleStringData -> it.text
is LocaleKeyData -> get(it)
else -> it.toString()
}
}?.toTypedArray() ?: arrayOf()
return getList(
localeKeyData.key,
arguments
)
}
operator fun get(key: String, vararg arguments: Any?): String {
try {
return localeStringEntries[key]?.format(*arguments) ?: throw RuntimeException("Key $key doesn't exist in locale $id!")
} catch (e: RuntimeException) {
logger.error(e) { "Error when trying to retrieve $key for locale $id" }
}
return "!!{$key}!!"
}
fun getList(key: String, vararg arguments: Any?): List<String> {
try {
return localeListEntries[key]?.map { it.format(*arguments) } ?: throw RuntimeException("Key $key doesn't exist in locale $id!")
} catch (e: RuntimeException) {
logger.error(e) { "Error when trying to retrieve $key for locale $id" }
}
return listOf("!!{$key}!!")
}
} | agpl-3.0 | 1d3d4d9e76fdf5d67e1d3fd21b3915a0 | 32.5 | 139 | 0.580543 | 4.613779 | false | false | false | false |
MaibornWolff/codecharta | analysis/model/src/main/kotlin/de/maibornwolff/codecharta/model/NodeInserter.kt | 1 | 2054 | package de.maibornwolff.codecharta.model
import mu.KotlinLogging
object NodeInserter {
private val logger = KotlinLogging.logger {}
/**
* Inserts the node as child of the element at the specified position
* in the sub-tree spanned by the children of the root node.
*
* @param root where another node should be inserted
* @param path relative path to parent of new node in root node
* @param node that has to be inserted
*/
fun insertByPath(root: MutableNode, path: Path, node: MutableNode): MutableNode {
if (path.isTrivial) {
if (rootContainsNodeAlready(root, node)) {
val original = getNode(root, node.name)!!
root.children.remove(original)
val mergedNode = original.merge(listOf(node))
root.children.add(mergedNode)
logger.debug {
"Node with name ${node.name} already exists, merging $original and $node to $mergedNode."
}
} else {
root.children.add(node)
}
} else {
val name = path.head
val folderNode = getNode(root, name)
?: root.insertNewFolderNode(name).getNodeBy(Path(name)) as MutableNode
insertByPath(folderNode, path.tail, node)
}
return root
}
private fun getNode(root: MutableNode, name: String): MutableNode? {
return root.children.firstOrNull { it.name == name }
}
private fun rootContainsNodeAlready(root: MutableNode, node: MutableNode): Boolean {
return root.children.filter { it.name == node.name }.count() > 0
}
private fun createFolderNode(name: String): MutableNode {
return MutableNode(name, NodeType.Folder, nodeMergingStrategy = NodeMaxAttributeMerger(true))
}
private fun MutableNode.insertNewFolderNode(name: String): MutableNode {
val folderNode = createFolderNode(name)
insertByPath(this, Path.TRIVIAL, folderNode)
return this
}
}
| bsd-3-clause | 4ff913f391eafa13e715da1b11e2ff81 | 34.413793 | 109 | 0.622687 | 4.61573 | false | false | false | false |
eugeis/ee | ee-asm/src/main/kotlin/ee/asm/gradleUtils.kt | 1 | 1480 | package ee.asm
import java.io.File
private val mvnManifest: String
get() = File("anko/props/mvn/AndroidManifest.xml").readText()
fun generateMavenArtifact(outputDirectory: File, artifactName: String, sdkVersion: String) {
fun copy(original: String) {
val originalFile = File("anko/props/mvn/$original")
val toCreateFile = File(outputDirectory, original)
originalFile.copyTo(toCreateFile)
}
fun copy(original: String, process: (String) -> String) {
val contents = process(File("anko/props/mvn/$original").readText())
File(outputDirectory, original).writeText(contents)
}
// Create res directory
val resDirectory = File(outputDirectory, "src/main/res/")
if (!resDirectory.exists()) {
resDirectory.mkdirs()
}
// Write manifest
val manifest = mvnManifest.replace("%SDK_VERSION", sdkVersion)
File(outputDirectory, "src/main/AndroidManifest.xml").writeText(manifest)
// Copy gradle wrapper
copy("gradlew")
copy("gradlew.bat")
copy("gradle/wrapper/gradle-wrapper.jar")
copy("gradle/wrapper/gradle-wrapper.properties")
// Copy gradle build files
fun String.substVersions(): String {
return replace("%SDK_VERSION", sdkVersion).replace("%ARTIFACT_VERSION", File("version.txt").readText())
.replace("%ARTIFACT_NAME", artifactName)
}
copy("gradle.properties") { it.substVersions() }
copy("build.gradle") { it.substVersions() }
} | apache-2.0 | f032a517d1a5dfe2c222c770a7f33145 | 33.44186 | 111 | 0.677027 | 4.228571 | false | false | false | false |
google/xplat | j2kt/jre/java/native/java/util/regex/Matcher.kt | 1 | 12756 | /*
* Copyright (C) 2007 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 java.util.regex
import kotlin.math.max
/** The result of applying a `Pattern` to a given input. */
class Matcher(var pattern: Pattern, var input: CharSequence) {
/**
* Holds the start of the region, or 0 if the matching should start at the beginning of the text.
*/
private var regionStart = 0
/** Holds the active region of the input. */
private var region: String = input.toString()
/** Holds the position where the next find operation will take place. */
private var findPos = 0
private var matchResult: kotlin.text.MatchResult? = null
private var appendPosition = 0
/**
* Implements a non-terminal append-and-replace step.
*
* This method performs the following actions:
*
* It reads characters from the input sequence, starting at the append position, and appends them
* to the given string buffer. It stops after reading the last character preceding the previous
* match, that is, the character at index start() - 1.
*
* It appends the given replacement string to the string buffer.
*
* It sets the append position of this matcher to the index of the last character matched, plus
* one, that is, to end().
*/
fun appendReplacement(sb: StringBuilder, replacement: String): Matcher {
sb.append(region.subSequence(appendPosition, start()))
sb.append(replacement)
appendPosition = end()
return this
}
/**
* Implements a terminal append-and-replace step.
*
* This method reads characters from the input sequence, starting at the append position, and
* appends them to the given string buffer. It is intended to be invoked after one or more
* invocations of the appendReplacement method in order to copy the remainder of the input
* sequence.
*/
fun appendTail(sb: StringBuilder): StringBuilder {
sb.append(region.subSequence(appendPosition, region.length))
appendPosition = region.length
return sb
}
/**
* Resets the `Matcher`. This results in the region being set to the whole input. Results of a
* previous find get lost. The next attempt to find an occurrence of the [Pattern] in the string
* will start at the beginning of the input.
*
* @return the `Matcher` itself.
*/
fun reset(): Matcher {
return reset(input, 0, input.length)
}
/**
* Provides a new input and resets the `Matcher`. This results in the region being set to the
* whole input. Results of a previous find get lost. The next attempt to find an occurrence of the
* [Pattern] in the string will start at the beginning of the input.
*
* @param input the new input sequence.
*
* @return the `Matcher` itself.
*/
fun reset(input: CharSequence): Matcher {
return reset(input, 0, input.length)
}
/**
* Resets the Matcher. A new input sequence and a new region can be specified. Results of a
* previous find get lost. The next attempt to find an occurrence of the Pattern in the string
* will start at the beginning of the region. This is the internal version of reset() to which the
* several public versions delegate.
*
* @param input the input sequence.
* @param start the start of the region.
* @param end the end of the region.
*
* @return the matcher itself.
*/
private fun reset(input: CharSequence, start: Int, end: Int): Matcher {
if (start < 0 || end < 0 || start > input.length || end > input.length || start > end) {
throw IndexOutOfBoundsException()
}
this.input = input!!.toString()
regionStart = start
region = input.substring(start, end)
matchResult = null
findPos = 0
return this
}
/**
* Sets a new pattern for the `Matcher`. Results of a previous find get lost. The next attempt to
* find an occurrence of the [Pattern] in the string will start at the beginning of the input.
*
* @param pattern the new `Pattern`.
*
* @return the `Matcher` itself.
*/
fun usePattern(pattern: Pattern): Matcher {
this.pattern = pattern
matchResult = null
return this
}
/**
* Resets this matcher and sets a region. Only characters inside the region are considered for a
* match.
*
* @param start the first character of the region.
* @param end the first character after the end of the region.
* @return the `Matcher` itself.
*/
fun region(start: Int, end: Int): Matcher {
return reset(input, start, end)
}
/**
* Returns the [Pattern] instance used inside this matcher.
*
* @return the `Pattern` instance.
*/
fun pattern(): Pattern {
return pattern
}
/**
* Returns the text that matched a given group of the regular expression. Explicit capturing
* groups in the pattern are numbered left to right in order of their *opening* parenthesis,
* starting at 1. The special group 0 represents the entire match (as if the entire pattern is
* surrounded by an implicit capturing group). For example, "a((b)c)" matching "abc" would give
* the following groups: <pre> 0 "abc" 1 "bc" 2 "b" </pre> *
*
* An optional capturing group that failed to match as part of an overall successful match (for
* example, "a(b)?c" matching "ac") returns null. A capturing group that matched the empty string
* (for example, "a(b?)c" matching "ac") returns the empty string.
*
* @throws IllegalStateException if no successful match has been made.
*/
fun group(group: Int): String? = ensureMatch().groupValues[group]
/**
* Returns the text that matched the whole regular expression.
*
* @return the text.
* @throws IllegalStateException if no successful match has been made.
*/
fun group(): String {
return group(0)!! // group(0) can only throw or return non-null
}
/**
* Returns the next occurrence of the [Pattern] in the input. The method starts the search from
* the given character in the input.
*
* @param start The index in the input at which the find operation is to begin. If this is less
* than the start of the region, it is automatically adjusted to that value. If it is beyond the
* end of the region, the method will fail.
* @return true if (and only if) a match has been found.
*/
fun find(start: Int): Boolean {
findPos = max(start - regionStart, 0)
return find()
}
/** Performs a kotlin regex operation and maps the result to the corresponding state here. */
private fun op(op: (Regex) -> kotlin.text.MatchResult?): Boolean {
val result = op(pattern.regex)
matchResult = result
return if (result != null) {
findPos = result.range.endInclusive + 1
true
} else {
false
}
}
/**
* Returns the next occurrence of the [Pattern] in the input. If a previous match was successful,
* the method continues the search from the first character following that match in the input.
* Otherwise it searches either from the region start (if one has been set), or from position 0.
*
* @return true if (and only if) a match has been found.
*/
fun find(): Boolean {
if (findPos < 0) {
findPos = 0
} else if (findPos >= region.length) {
matchResult = null
return false
}
return op { it.find(region, findPos) }
}
/**
* Tries to match the [Pattern], starting from the beginning of the region (or the beginning of
* the input, if no region has been set). Doesn't require the `Pattern` to match against the whole
* region.
*
* @return true if (and only if) the `Pattern` matches.
*/
// TODO(b/239727859): Investigate: Kotlin matchAt() doesn't seem to have the documented signature.
// fun lookingAt() = op { it.matchAt(region, 0) }
/**
* Tries to match the [Pattern] against the entire region (or the entire input, if no region has
* been set).
*
* @return true if (and only if) the `Pattern` matches the entire region.
*/
fun matches() = op { it.matchEntire(region) }
/**
* Returns the index of the first character of the text that matched a given group.
*
* @param group the group, ranging from 0 to groupCount() - 1, with 0 representing the whole
* pattern.
* @return the character index.
* @throws IllegalStateException if no successful match has been made.
*/
fun start(group: Int): Int {
val group = ensureMatch().groups[group]
return if (group == null) -1 else (group.range.start + regionStart)
}
/** Returns the number of capturing groups in this matcher's pattern. */
fun groupCount() = ensureMatch().groups.size - 1
/**
* Returns the index of the first character following the text that matched a given group.
*
* @param group the group, ranging from 0 to groupCount() - 1, with 0 representing the whole
* pattern.
* @return the character index.
* @throws IllegalStateException if no successful match has been made.
*/
fun end(group: Int): Int {
val group = ensureMatch().groups[group]
return if (group == null) -1 else (group.range.endInclusive + 1 + regionStart)
}
/**
* Returns the index of the first character of the text that matched the whole regular expression.
*
* @return the character index.
* @throws IllegalStateException if no successful match has been made.
*/
fun start(): Int {
return start(0)
}
/**
* Returns the index of the first character following the text that matched the whole regular
* expression.
*
* @return the character index.
* @throws IllegalStateException if no successful match has been made.
*/
fun end(): Int {
return end(0)
}
/**
* Indicates whether this matcher has anchoring bounds enabled. When anchoring bounds are enabled,
* the start and end of the input match the '^' and '$' meta-characters, otherwise not. Anchoring
* bounds are enabled by default.
*
* @return true if (and only if) the `Matcher` uses anchoring bounds.
*/
fun hasAnchoringBounds() = true
/**
* Makes sure that a successful match has been made. Is invoked internally from various places in
* the class.
*
* @throws IllegalStateException if no successful match has been made.
*/
private fun ensureMatch(): kotlin.text.MatchResult {
val matchResult = matchResult
if (matchResult == null) {
throw IllegalStateException("No successful match so far")
}
return matchResult
}
/**
* Indicates whether this matcher has transparent bounds enabled. When transparent bounds are
* enabled, the parts of the input outside the region are subject to lookahead and lookbehind,
* otherwise they are not. Transparent bounds are disabled by default.
*
* @return true if (and only if) the `Matcher` uses anchoring bounds.
*/
fun hasTransparentBounds() = false
/**
* Returns this matcher's region start, that is, the first character that is considered for a
* match.
*
* @return the start of the region.
*/
fun regionStart() = regionStart
/**
* Returns this matcher's region end, that is, the first character that is not considered for a
* match.
*
* @return the end of the region.
*/
fun regionEnd() = regionStart + region.length
/**
* Replaces the first subsequence of the input sequence that matches the pattern with the given
* replacement string.
*
* Note that we don't try to emulate undocumented side effects of the original methods here.
*/
fun replaceFirst(replacement: String) = pattern.regex.replaceFirst(region, replacement)
/**
* Replaces all subsequence of the input sequence matching the pattern with the given replacement
* string.
*
* Note that we don't try to emulate undocumented side effects of the original methods here.
*/
fun replaceAll(replacement: String) = pattern.regex.replace(region, replacement)
companion object {
/**
* Returns a replacement string for the given one that has all backslashes and dollar signs
* escaped.
*
* @param s the input string.
* @return the input string, with all backslashes and dollar signs having been escaped.
*/
fun quoteReplacement(s: String) = Regex.escapeReplacement(s)
}
}
| apache-2.0 | 7879958513c07f5c4ebc626683f4e8b2 | 33.852459 | 100 | 0.683051 | 4.239282 | false | false | false | false |
ansman/kotshi | compiler/src/main/kotlin/se/ansman/kotshi/CodeBlockExt.kt | 1 | 2179 | @file:Suppress("unused")
package se.ansman.kotshi
import com.squareup.kotlinpoet.CodeBlock
inline fun CodeBlock.Builder.addControlFlow(
controlFlow: String,
vararg args: Any,
close: Boolean = true,
block: CodeBlock.Builder.() -> Unit
): CodeBlock.Builder {
beginControlFlow(controlFlow, *args)
block()
if (close) endControlFlow()
return this
}
inline fun CodeBlock.Builder.addNextControlFlow(
controlFlow: String,
vararg args: Any,
close: Boolean = true,
block: CodeBlock.Builder.() -> Unit
): CodeBlock.Builder {
nextControlFlow(controlFlow, *args)
block()
if (close) endControlFlow()
return this
}
/**
* Adds a switch branch.
*
* A trailing : and a break is automatically inserted
*/
inline fun CodeBlock.Builder.addWhenBranch(
branch: String,
vararg args: Any,
block: CodeBlock.Builder.() -> Unit
): CodeBlock.Builder {
beginControlFlow("$branch:", *args)
block()
return endControlFlow()
}
inline fun CodeBlock.Builder.addIf(
predicate: String,
vararg args: Any,
block: CodeBlock.Builder.() -> Unit
): CodeBlock.Builder = addControlFlow("if ($predicate)", *args) { block() }
inline fun CodeBlock.Builder.addIfElse(
predicate: String,
vararg args: Any,
block: CodeBlock.Builder.() -> Unit
): CodeBlock.Builder = addControlFlow("if ($predicate)", *args, close = false) { block() }
inline fun CodeBlock.Builder.addElseIf(
predicate: String,
vararg args: Any,
block: CodeBlock.Builder.() -> Unit
): CodeBlock.Builder = addNextControlFlow("else if ($predicate)", *args, close = false) { block() }
inline fun CodeBlock.Builder.addElse(block: CodeBlock.Builder.() -> Unit): CodeBlock.Builder =
addNextControlFlow("else") { block() }
inline fun CodeBlock.Builder.addWhile(
predicate: String,
vararg args: Any,
block: CodeBlock.Builder.() -> Unit
): CodeBlock.Builder = addControlFlow("while ($predicate)", *args) { block() }
inline fun CodeBlock.Builder.addWhen(
predicate: String,
vararg args: Any,
block: CodeBlock.Builder.() -> Unit
): CodeBlock.Builder = addControlFlow("switch ($predicate)", *args) { block() }
| apache-2.0 | 2f4c968198ea90295f78d99b4019edda | 26.935897 | 99 | 0.6838 | 4.050186 | false | false | false | false |
Shynixn/PetBlocks | petblocks-bukkit-plugin/petblocks-bukkit-nms-118R1/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/nms/v1_18_R1/NMSPetBat.kt | 1 | 5064 | package com.github.shynixn.petblocks.bukkit.logic.business.nms.v1_18_R1
import com.github.shynixn.petblocks.api.PetBlocksApi
import com.github.shynixn.petblocks.api.business.proxy.PathfinderProxy
import com.github.shynixn.petblocks.api.business.service.ConcurrencyService
import com.github.shynixn.petblocks.api.persistence.entity.AIFlying
import net.minecraft.core.BlockPosition
import net.minecraft.world.entity.Entity
import net.minecraft.world.entity.EntityTypes
import net.minecraft.world.entity.ai.attributes.GenericAttributes
import net.minecraft.world.entity.ai.goal.PathfinderGoal
import net.minecraft.world.entity.ai.goal.PathfinderGoalSelector
import net.minecraft.world.entity.animal.EntityParrot
import net.minecraft.world.level.block.state.IBlockData
import org.bukkit.Bukkit
import org.bukkit.Location
import org.bukkit.craftbukkit.v1_18_R1.CraftServer
import org.bukkit.craftbukkit.v1_18_R1.CraftWorld
import org.bukkit.event.entity.CreatureSpawnEvent
/**
* NMS implementation of the Parrot pet backend.
*/
class NMSPetBat(petDesign: NMSPetArmorstand, location: Location) : EntityParrot(EntityTypes.al, (location.world as CraftWorld).handle) {
// NMSPetBee might be instantiated from another source.
private var petDesign: NMSPetArmorstand? = null
// Pathfinders need to be self cached for Paper.
private var initialClear = true
private var pathfinderCounter = 0
private var cachedPathfinders = HashSet<PathfinderGoal>()
// BukkitEntity has to be self cached since 1.14.
private var entityBukkit: Any? = null
init {
this.petDesign = petDesign
this.d(true) // Set Silent.
clearAIGoals()
// NMS can sometimes instantiate this object without petDesign.
if (this.petDesign != null) {
val flyingAI = this.petDesign!!.proxy.meta.aiGoals.firstOrNull { a -> a is AIFlying } as AIFlying?
if (flyingAI != null) {
this.a(GenericAttributes.d)!!.a(0.30000001192092896 * 0.75) // Set Value.
this.a(GenericAttributes.e)!!.a( 0.30000001192092896 * flyingAI.movementSpeed) // Set Value.
this.P = flyingAI.climbingHeight.toFloat()
}
}
val mcWorld = (location.world as CraftWorld).handle
this.e(location.x, location.y - 200, location.z)
mcWorld.addFreshEntity(this, CreatureSpawnEvent.SpawnReason.CUSTOM)
val targetLocation = location.clone()
PetBlocksApi.resolve(ConcurrencyService::class.java).runTaskSync(20L) {
// Only fix location if it is not already fixed.
if (this.bukkitEntity.location.distance(targetLocation) > 20) {
this.e(targetLocation.x, targetLocation.y + 1.0, targetLocation.z)
}
}
}
/**
* Applies pathfinders to the entity.
*/
fun applyPathfinders(pathfinders: List<Any>) {
clearAIGoals()
pathfinderCounter = 0
val proxies = HashMap<PathfinderProxy, CombinedPathfinder.Cache>()
val hyperPathfinder = CombinedPathfinder(proxies)
for (pathfinder in pathfinders) {
if (pathfinder is PathfinderProxy) {
val wrappedPathfinder = Pathfinder(pathfinder)
this.cachedPathfinders.add(wrappedPathfinder)
proxies[pathfinder] = CombinedPathfinder.Cache()
} else {
this.bR.a(pathfinderCounter++, pathfinder as PathfinderGoal)
this.cachedPathfinders.add(pathfinder)
}
}
this.bR.a(pathfinderCounter++, hyperPathfinder)
this.cachedPathfinders.add(hyperPathfinder)
}
/**
* Gets called on move to play sounds.
*/
override fun b(blockposition: BlockPosition, iblockdata: IBlockData) {
if (petDesign == null) {
return
}
if (!this.aQ()) { // IsInWater.
petDesign!!.proxy.playMovementEffects()
}
}
/**
* Disable health.
*/
override fun c(f: Float) {
}
/**
* Gets the bukkit entity.
*/
override fun getBukkitEntity(): CraftPet {
if (this.entityBukkit == null) {
entityBukkit = CraftPet(Bukkit.getServer() as CraftServer, this)
val field = Entity::class.java.getDeclaredField("bukkitEntity")
field.isAccessible = true
field.set(this, entityBukkit)
}
return this.entityBukkit as CraftPet
}
override fun e(): Entity? {
return null
}
/**
* Clears all entity aiGoals.
*/
private fun clearAIGoals() {
if (initialClear) {
val dField = PathfinderGoalSelector::class.java.getDeclaredField("d")
dField.isAccessible = true
(dField.get(this.bR) as MutableSet<*>).clear()
(dField.get(this.bS) as MutableSet<*>).clear()
initialClear = false
}
for (pathfinder in cachedPathfinders) {
this.bR.a(pathfinder)
}
this.cachedPathfinders.clear()
}
}
| apache-2.0 | 61cbe30a10886f32df13386f8493a334 | 33.924138 | 136 | 0.653633 | 4.324509 | false | false | false | false |
tom-kita/kktAPK | app/src/main/kotlin/com/bl_lia/kirakiratter/domain/entity/realm/RealmStatus.kt | 1 | 1201 | package com.bl_lia.kirakiratter.domain.entity.realm
import com.bl_lia.kirakiratter.domain.entity.Status
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import java.util.*
open class RealmStatus(
@PrimaryKey
open var id: Int = -1,
open var content: RealmContent? = null,
open var account: RealmAccount? = null,
open var reblog: RealmStatus? = null,
open var reblogged: Boolean = false,
open var favourited: Boolean = false,
open var mediaAttachments: RealmList<RealmMedia> = RealmList(),
open var sensitive: Boolean = false,
open var createdAt: Date? = null
): RealmObject() {
fun toStatus(): Status =
Status(
id = id,
content = content?.toContent(),
account = account?.toAccount(),
reblog = reblog?.toStatus(),
reblogged = reblogged,
favourited = favourited,
mediaAttachments = mediaAttachments.map { it.toMedia() },
sensitive = sensitive,
createdAt = createdAt
)
} | mit | cd5b544ba86542888ed92028947f1727 | 34.352941 | 77 | 0.578684 | 4.842742 | false | false | false | false |
toastkidjp/Jitte | planning/src/main/java/jp/toastkid/planning/Adapter.kt | 1 | 1338 | package jp.toastkid.planning
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
/**
* RecyclerView's adapter.
*
* @author toastkidjp
*/
internal class Adapter : RecyclerView.Adapter<ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
ViewHolder(
DataBindingUtil.inflate(
LayoutInflater.from(parent.context),
LAYOUT_ID,
parent,
false
)
)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val text = Suite.values()[position % Suite.values().size].text()
holder.setText(text)
}
override fun getItemCount(): Int = MAXIMUM_SIZE
companion object {
@LayoutRes
private val LAYOUT_ID = R.layout.item_planning_poker
/**
* Maximum size.
*/
private val MAXIMUM_SIZE = Suite.values().size * 20
/**
* Medium.
*/
private val MEDIUM = MAXIMUM_SIZE / 2
/**
* Return medium number.
*/
fun medium(): Int = MEDIUM
}
} | epl-1.0 | a43a2c121d03d5f4ccbe867a051bc8f2 | 24.264151 | 72 | 0.567265 | 5.247059 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/RsTokenType.kt | 1 | 2830 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi
import com.intellij.psi.tree.IElementType
import com.intellij.psi.tree.TokenSet
import org.rust.lang.RsLanguage
import org.rust.lang.core.parser.RustParserDefinition.Companion.BLOCK_COMMENT
import org.rust.lang.core.parser.RustParserDefinition.Companion.EOL_COMMENT
import org.rust.lang.core.parser.RustParserDefinition.Companion.INNER_BLOCK_DOC_COMMENT
import org.rust.lang.core.parser.RustParserDefinition.Companion.INNER_EOL_DOC_COMMENT
import org.rust.lang.core.parser.RustParserDefinition.Companion.OUTER_BLOCK_DOC_COMMENT
import org.rust.lang.core.parser.RustParserDefinition.Companion.OUTER_EOL_DOC_COMMENT
import org.rust.lang.core.psi.RsElementTypes.*
open class RsTokenType(debugName: String) : IElementType(debugName, RsLanguage)
fun tokenSetOf(vararg tokens: IElementType) = TokenSet.create(*tokens)
val RS_KEYWORDS = tokenSetOf(
AS,
BOX, BREAK,
CONST, CONTINUE, CRATE, CSELF,
DEFAULT,
ELSE, ENUM, EXTERN,
FN, FOR,
IF, IMPL, IN,
MACRO_KW,
LET, LOOP,
MATCH, MOD, MOVE, MUT,
PUB,
REF, RETURN,
SELF, STATIC, STRUCT, SUPER,
TRAIT, TYPE_KW,
UNION, UNSAFE, USE,
WHERE, WHILE
)
val RS_OPERATORS = tokenSetOf(
AND, ANDEQ, ARROW, FAT_ARROW, SHA, COLON, COLONCOLON, COMMA, DIV, DIVEQ, DOT, DOTDOT, DOTDOTDOT, EQ, EQEQ, EXCL,
EXCLEQ, GT, LT, MINUS, MINUSEQ, MUL, MULEQ, OR, OREQ, PLUS, PLUSEQ, REM, REMEQ, SEMICOLON, XOR, XOREQ, Q, AT,
DOLLAR, GTGTEQ, GTGT, GTEQ, LTLTEQ, LTLT, LTEQ, OROR, ANDAND
)
val RS_BINARY_OPS = tokenSetOf(
AND, ANDEQ, ANDAND,
DIV, DIVEQ,
EQ, EQEQ, EXCLEQ,
GT, GTGT, GTEQ, GTGTEQ,
LT, LTLT, LTEQ, LTLTEQ,
MINUS, MINUSEQ, MUL, MULEQ,
OR, OREQ, OROR,
PLUS, PLUSEQ,
REM, REMEQ,
XOR, XOREQ
)
val RS_DOC_COMMENTS = tokenSetOf(
INNER_BLOCK_DOC_COMMENT, OUTER_BLOCK_DOC_COMMENT,
INNER_EOL_DOC_COMMENT, OUTER_EOL_DOC_COMMENT
)
val RS_COMMENTS = TokenSet.orSet(
tokenSetOf(BLOCK_COMMENT, EOL_COMMENT),
RS_DOC_COMMENTS)
val RS_EOL_COMMENTS = tokenSetOf(EOL_COMMENT, INNER_EOL_DOC_COMMENT, OUTER_EOL_DOC_COMMENT)
val RS_STRING_LITERALS = tokenSetOf(STRING_LITERAL, BYTE_STRING_LITERAL)
val RS_RAW_LITERALS = tokenSetOf(RAW_STRING_LITERAL, RAW_BYTE_STRING_LITERAL)
val RS_LITERALS = tokenSetOf(STRING_LITERAL, BYTE_STRING_LITERAL, RAW_STRING_LITERAL, RAW_BYTE_STRING_LITERAL,
CHAR_LITERAL, BYTE_LITERAL, INTEGER_LITERAL, FLOAT_LITERAL, BOOL_LITERAL)
val RS_CONTEXTUAL_KEYWORDS = tokenSetOf(DEFAULT, UNION, AUTO, DYN)
val RS_LIST_OPEN_SYMBOLS = tokenSetOf(LPAREN, LT)
val RS_LIST_CLOSE_SYMBOLS = tokenSetOf(RPAREN, GT)
val RS_BLOCK_LIKE_EXPRESSIONS = tokenSetOf(WHILE_EXPR, IF_EXPR, FOR_EXPR, LOOP_EXPR, MATCH_EXPR, BLOCK_EXPR)
| mit | caa33fabecc9b0aae35edb3dd16461f6 | 32.690476 | 116 | 0.731449 | 3.241695 | false | false | false | false |
camsteffen/polite | src/main/java/me/camsteffen/polite/rule/master/RuleMasterRecyclerView.kt | 1 | 1533 | package me.camsteffen.polite.rule.master
import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.ContextMenu
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import me.camsteffen.polite.model.Rule
class RuleMasterRecyclerView(context: Context, attrs: AttributeSet? = null) :
RecyclerView(context, attrs) {
init {
setHasFixedSize(true)
layoutManager = LinearLayoutManager(context)
addItemDecoration(Divider())
}
var adapter: RuleMasterAdapter?
get() = super.getAdapter() as RuleMasterAdapter?
set(value) = super.setAdapter(value)
private var ruleContextMenuInfo: RuleContextMenuInfo? = null
override fun getContextMenuInfo(): RuleContextMenuInfo? = ruleContextMenuInfo
override fun showContextMenuForChild(originalView: View): Boolean {
val position = getChildAdapterPosition(originalView)
if (position >= 0) {
val rule = adapter!!.getRuleAt(position)
ruleContextMenuInfo = RuleContextMenuInfo(rule)
return super.showContextMenuForChild(originalView)
}
return false
}
class RuleContextMenuInfo(val rule: Rule) : ContextMenu.ContextMenuInfo
class Divider : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: State) {
outRect.bottom = 1
}
}
}
| mpl-2.0 | 96614d9e61bae59fff2a5693cf2955a5 | 31.617021 | 100 | 0.720809 | 4.961165 | false | false | false | false |
Kiskae/Twitch-Archiver | twitch/src/main/kotlin/net/serverpeon/twitcharchiver/twitch/OAuthInterceptor.kt | 1 | 1596 | package net.serverpeon.twitcharchiver.twitch
import com.google.common.net.HttpHeaders
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.Response
/**
* Injects the OAuth token into any secure requests to the twitch api.
*
* It will not inject the token into insecure HTTP requests for safety.
*/
internal class OAuthInterceptor private constructor(
private val token: () -> String?,
private val clientId: String
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
return chain.proceed(chain.request().let { req ->
val currentToken = token()
if (currentToken != null && isSecureTwitchApi(req.url())) {
req.newBuilder().addHeader(HttpHeaders.AUTHORIZATION, "OAuth $currentToken")
} else {
req.newBuilder()
}.apply {
addHeader(HttpHeaders.ACCEPT, TWITCH_API_V3_JSON_MEDIATYPE.toString())
addHeader(TWITCH_CLIENT_ID_HEADER, clientId)
}.build()
})
}
private fun isSecureTwitchApi(url: HttpUrl): Boolean {
return url.isHttps && "api.twitch.tv" == url.host()
}
companion object {
private val TWITCH_API_V3_JSON_MEDIATYPE = MediaType.parse("application/vnd.twitchtv.v3+json")
private val TWITCH_CLIENT_ID_HEADER = "Client-ID"
fun static(token: String, clientId: String) = OAuthInterceptor({ token }, clientId)
fun dynamic(token: OAuthToken, clientId: String) = OAuthInterceptor({ token.value }, clientId)
}
} | mit | 81f29eb5dcf6af22c04ff9591991f96a | 35.295455 | 102 | 0.657895 | 4.372603 | false | false | false | false |
Kotlin/dokka | runners/gradle-plugin/src/test/kotlin/org/jetbrains/dokka/gradle/DokkaMultiModuleTaskTest.kt | 1 | 8177 | @file:Suppress("UnstableApiUsage")
package org.jetbrains.dokka.gradle
import org.gradle.kotlin.dsl.*
import org.gradle.testfixtures.ProjectBuilder
import org.jetbrains.dokka.*
import java.io.File
import kotlin.test.*
class DokkaMultiModuleTaskTest {
private val rootProject = ProjectBuilder.builder()
.withName("root")
.build()
private val childProject = ProjectBuilder.builder()
.withName("child")
.withProjectDir(rootProject.projectDir.resolve("child"))
.withParent(rootProject).build()
private val childDokkaTask = childProject.tasks.create<DokkaTaskPartial>("childDokkaTask")
private val multiModuleTask = rootProject.tasks.create<DokkaMultiModuleTask>("multiModuleTask").apply {
addChildTask(childDokkaTask)
}
init {
rootProject.allprojects { project ->
project.tasks.withType<AbstractDokkaTask>().configureEach { task ->
task.plugins.withDependencies { dependencies -> dependencies.clear() }
}
}
}
@Test
fun `child project is withing root project`() {
assertEquals(
rootProject.projectDir, childProject.projectDir.parentFile,
"Expected child project being inside the root project"
)
assertEquals(
childProject.projectDir.name, "child",
"Expected folder of child project to be called 'child'"
)
}
@Test
fun buildDokkaConfiguration() {
val include1 = childDokkaTask.project.file("include1.md")
val include2 = childDokkaTask.project.file("include2.md")
val topLevelInclude = multiModuleTask.project.file("README.md")
childDokkaTask.apply {
dokkaSourceSets.create("main")
dokkaSourceSets.create("test")
dokkaSourceSets.configureEach {
it.includes.from(include1, include2)
}
}
multiModuleTask.apply {
moduleVersion by "1.5.0"
moduleName by "custom Module Name"
outputDirectory by project.buildDir.resolve("customOutputDirectory")
cacheRoot by File("customCacheRoot")
pluginsConfiguration.add(PluginConfigurationImpl("pluginA", DokkaConfiguration.SerializationFormat.JSON, """ { "key" : "value2" } """))
failOnWarning by true
offlineMode by true
includes.from(listOf(topLevelInclude))
}
val dokkaConfiguration = multiModuleTask.buildDokkaConfiguration()
assertEquals(
DokkaConfigurationImpl(
moduleName = "custom Module Name",
moduleVersion = "1.5.0",
outputDir = multiModuleTask.project.buildDir.resolve("customOutputDirectory"),
cacheRoot = File("customCacheRoot"),
pluginsConfiguration = mutableListOf(PluginConfigurationImpl("pluginA", DokkaConfiguration.SerializationFormat.JSON, """ { "key" : "value2" } """)),
pluginsClasspath = emptyList(),
failOnWarning = true,
offlineMode = true,
includes = setOf(topLevelInclude),
modules = listOf(
DokkaModuleDescriptionImpl(
name = "child",
relativePathToOutputDirectory = File("child"),
includes = setOf(include1, include2),
sourceOutputDirectory = childDokkaTask.outputDirectory.getSafe()
)
)
),
dokkaConfiguration
)
}
@Test
fun `multimodule task should not include unspecified version`(){
childDokkaTask.apply {
dokkaSourceSets.create("main")
dokkaSourceSets.create("test")
}
multiModuleTask.apply {
moduleVersion by "unspecified"
}
val dokkaConfiguration = multiModuleTask.buildDokkaConfiguration()
assertNull(dokkaConfiguration.moduleVersion)
}
@Test
fun `setting dokkaTaskNames declares proper task dependencies`() {
val dependenciesInitial = multiModuleTask.taskDependencies.getDependencies(multiModuleTask).toSet()
assertEquals(1, dependenciesInitial.size, "Expected one dependency")
val dependency = dependenciesInitial.single()
assertTrue(dependency is DokkaTaskPartial, "Expected dependency to be of Type ${DokkaTaskPartial::class.simpleName}")
assertEquals(childProject, dependency.project, "Expected dependency from child project")
val customDokkaTask = childProject.tasks.create<DokkaTask>("customDokkaTask")
multiModuleTask.addSubprojectChildTasks("customDokkaTask")
val dependenciesAfter = multiModuleTask.taskDependencies.getDependencies(multiModuleTask).toSet()
assertEquals(2, dependenciesAfter.size, "Expected two dependencies")
assertTrue(customDokkaTask in dependenciesAfter, "Expected 'customDokkaTask' in dependencies")
}
@Test
fun `multimodule task with no child tasks throws DokkaException`() {
val project = ProjectBuilder.builder().build()
val multimodule = project.tasks.create<DokkaMultiModuleTask>("multimodule")
project.configurations.configureEach { it.withDependencies { it.clear() } }
assertFailsWith<DokkaException> { multimodule.generateDocumentation() }
}
@Test
fun childDokkaTaskIncludes() {
val childDokkaTaskInclude1 = childProject.file("include1")
val childDokkaTaskInclude2 = childProject.file("include2")
val childDokkaTaskInclude3 = childProject.file("include3")
childDokkaTask.apply {
dokkaSourceSets.create("main") {
it.includes.from(childDokkaTaskInclude1, childDokkaTaskInclude2)
}
dokkaSourceSets.create("main2") {
it.includes.from(childDokkaTaskInclude3)
}
}
val secondChildDokkaTaskInclude = childProject.file("include4")
val secondChildDokkaTask = childProject.tasks.create<DokkaTaskPartial>("secondChildDokkaTask") {
dokkaSourceSets.create("main") {
it.includes.from(secondChildDokkaTaskInclude)
}
}
multiModuleTask.addChildTask(secondChildDokkaTask)
assertEquals(
mapOf(
":child:childDokkaTask" to setOf(
childDokkaTaskInclude1,
childDokkaTaskInclude2,
childDokkaTaskInclude3
),
":child:secondChildDokkaTask" to setOf(secondChildDokkaTaskInclude)
),
multiModuleTask.childDokkaTaskIncludes
)
}
@Test
fun sourceChildOutputDirectories() {
val parent = ProjectBuilder.builder().build()
val child = ProjectBuilder.builder().withName("child").withParent(parent).build()
val parentTask = parent.tasks.create<DokkaMultiModuleTask>("parent")
val childTask = child.tasks.create<DokkaTask>("child")
parentTask.addChildTask(childTask)
childTask.outputDirectory by child.file("custom/output")
assertEquals(
listOf(parent.file("child/custom/output")), parentTask.sourceChildOutputDirectories,
"Expected child output directory being present"
)
}
@Test
fun targetChildOutputDirectories() {
val parent = ProjectBuilder.builder().build()
val child = ProjectBuilder.builder().withName("child").withParent(parent).build()
val parentTask = parent.tasks.create<DokkaMultiModuleTask>("parent")
val childTask = child.tasks.create<DokkaTask>("child")
parentTask.addChildTask(childTask)
@Suppress("NAME_SHADOWING") // ¯\_(ツ)_/¯
parentTask.fileLayout by DokkaMultiModuleFileLayout { parent, child ->
parent.project.buildDir.resolve(child.name)
}
assertEquals(
listOf(parent.project.buildDir.resolve("child")), parentTask.targetChildOutputDirectories,
"Expected child target output directory being present"
)
}
}
| apache-2.0 | dc46133e978a6d53a1fb733f9f3f66b4 | 37.013953 | 164 | 0.642848 | 5.098565 | false | true | false | false |
googleapis/gax-kotlin | examples/src/main/kotlin/example/grpc/Logging.kt | 1 | 4466 | /*
* Copyright 2018 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 example.grpc
import com.google.api.MonitoredResource
import com.google.api.kgax.Page
import com.google.api.kgax.grpc.StubFactory
import com.google.api.kgax.grpc.pager
import com.google.logging.v2.ListLogEntriesRequest
import com.google.logging.v2.ListLogEntriesResponse
import com.google.logging.v2.LogEntry
import com.google.logging.v2.LoggingServiceV2Grpc
import com.google.logging.v2.WriteLogEntriesRequest
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import java.io.File
import java.util.Date
/**
* Simple example of calling the Logging API with a generated Kotlin gRPC client.
*
* Run this example using your service account as follows:
*
* ```
* $ CREDENTIALS=<path_to_your_service_account.json> PROJECT=<your_gcp_project_id> ./gradlew examples:run --args logging
* ```
*/
@ExperimentalCoroutinesApi
fun loggingExample(credentials: String) = runBlocking {
// create a stub factory
val factory = StubFactory(
LoggingServiceV2Grpc.LoggingServiceV2FutureStub::class,
"logging.googleapis.com", 443
)
// create a stub
val stub = File(credentials).inputStream().use {
factory.fromServiceAccount(
it,
listOf(
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
"https://www.googleapis.com/auth/logging.admin",
"https://www.googleapis.com/auth/logging.read",
"https://www.googleapis.com/auth/logging.write"
)
)
}
// get the project id
val projectId = System.getenv("PROJECT")
?: throw RuntimeException("You must set the PROJECT environment variable to run this example")
// resources to use
val project = "projects/$projectId"
val log = "$project/logs/testLog-${Date().time}"
val globalResource = MonitoredResource.newBuilder().apply { type = "global" }.build()
// ensure we have some logs to read
val newEntries = List(40) {
LogEntry.newBuilder().apply {
logName = log
resource = globalResource
textPayload = "log number: ${it + 1}"
}.build()
}
// write the entries
println("Writing ${newEntries.size} log entries...")
stub.execute {
it.writeLogEntries(WriteLogEntriesRequest.newBuilder().apply {
logName = log
resource = globalResource
addAllEntries(newEntries)
}.build())
}
// wait a few seconds (if read back immediately the API may not have saved the entries)
delay(10_000)
// now, read those entries back
val pages = pager(
method = { request ->
stub.execute { it.listLogEntries(request) }
},
initialRequest = { ->
ListLogEntriesRequest.newBuilder().apply {
addResourceNames(project)
filter = "logName=$log"
orderBy = "timestamp asc"
pageSize = 10
}.build()
},
nextRequest = { request, token ->
request.toBuilder().apply { pageToken = token }.build()
},
nextPage = { r: ListLogEntriesResponse ->
Page(r.entriesList, r.nextPageToken)
}
)
// go through all the logs, one page at a time
var numRead = 0
println("Reading log entries...")
for (page in pages) {
for (entry in page.elements) {
numRead++
println("log : ${entry.textPayload}")
}
}
println("Read a total of $numRead log entries!")
// sanity check
if (newEntries.size != numRead) {
throw RuntimeException("Oh no! The number of logs read does not match the number of writes!")
}
// shutdown
factory.shutdown()
}
| apache-2.0 | 9de0f90e77bcea69307a6b8ffba9a0cd | 32.081481 | 120 | 0.644201 | 4.319149 | false | false | false | false |
beyama/winter | winter-java/src/main/kotlin/io/jentz/winter/java/JWinter.kt | 1 | 1499 | package io.jentz.winter.java
import io.jentz.winter.ClassTypeKey
import io.jentz.winter.Graph
import io.jentz.winter.Provider
import io.jentz.winter.TypeKey
object JWinter {
/**
* Creates a [TypeKey] with argument type Unit and return type [R] from a Java class.
*
* @param type The return type.
* @param qualifier The optional qualifier.
* @return The type key.
*/
@JvmStatic
@JvmOverloads
fun <R : Any> key(
type: Class<R>,
qualifier: Any? = null
): TypeKey<R> = ClassTypeKey(type, qualifier)
/**
* @see Graph.instance
*/
@JvmStatic
@JvmOverloads
fun <R : Any> instance(graph: Graph, type: Class<R>, qualifier: Any? = null): R =
graph.instanceByKey(key(type, qualifier))
/**
* @see Graph.instanceOrNull
*/
@JvmStatic
@JvmOverloads
fun <R : Any> instanceOrNull(graph: Graph, type: Class<R>, qualifier: Any? = null): R? =
graph.instanceOrNullByKey(key(type, qualifier))
/**
* @see Graph.provider
*/
@JvmStatic
@JvmOverloads
fun <R : Any> provider(graph: Graph, type: Class<R>, qualifier: Any? = null): Provider<R> =
graph.providerByKey(key(type, qualifier))
/**
* @see Graph.providerOrNull
*/
@JvmStatic
@JvmOverloads
fun <R : Any> providerOrNull(
graph: Graph,
type: Class<R>,
qualifier: Any? = null
): Provider<R>? = graph.providerOrNullByKey(key(type, qualifier))
}
| apache-2.0 | 6daa25ad819a563e0a0c4508613a2eae | 24.40678 | 95 | 0.60974 | 3.804569 | false | false | false | false |
Shynixn/BlockBall | blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/business/service/GameExecutionServiceImpl.kt | 1 | 2809 | package com.github.shynixn.blockball.core.logic.business.service
import com.github.shynixn.blockball.api.business.enumeration.Team
import com.github.shynixn.blockball.api.business.service.GameExecutionService
import com.github.shynixn.blockball.api.business.service.ProxyService
import com.github.shynixn.blockball.api.persistence.entity.Game
import com.google.inject.Inject
/**
* Created by Shynixn 2019.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2019 by Shynixn
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
class GameExecutionServiceImpl @Inject constructor(private val proxyService: ProxyService) : GameExecutionService {
/**
* Applies points to the belonging teams when the given [player] dies in the given [game].
*/
override fun <P, G : Game> applyDeathPoints(game: G, player: P) {
val team = game.ingamePlayersStorage[player as Any]!!.team!!
if (team == Team.RED) {
game.blueScore += game.arena.meta.blueTeamMeta.pointsPerEnemyDeath
} else {
game.redScore += game.arena.meta.redTeamMeta.pointsPerEnemyDeath
}
}
/**
* Lets the given [player] in the given [game] respawn at the specified spawnpoint.
*/
override fun <P, G : Game> respawn(game: G, player: P) {
val team = game.ingamePlayersStorage[player as Any]!!.goalTeam!!
val teamMeta = if (team == Team.RED) {
game.arena.meta.redTeamMeta
} else {
game.arena.meta.blueTeamMeta
}
if (teamMeta.spawnpoint == null) {
proxyService.setPlayerLocation(player, game.arena.meta.ballMeta.spawnpoint!!)
} else {
proxyService.setPlayerLocation(player, teamMeta.spawnpoint!!)
}
}
} | apache-2.0 | ad88a163d5900efa8b7abcfb3e7c5dc3 | 40.323529 | 115 | 0.704877 | 4.106725 | false | false | false | false |
BaReinhard/Hacktoberfest-Data-Structure-and-Algorithms | data_structures/linked_list/kotlin/LinkedList.kt | 1 | 5500 | import java.util.*
/*
* Kotlin Program to Implement Singly Linked List
*/
/* Class Node */
internal class Node {
/* Function to get data from current Node */
/* Function to set data to current Node */
var data: Int = 0
/* Function to get link to next node */
/* Function to set link to next Node */
var link: Node? = null
/* Constructor */
constructor() {
link = null
data = 0
}
/* Constructor */
constructor(d: Int, n: Node?) {
data = d
link = n
}
}
/* Class linkedList */
internal class linkedList {
private var start: Node? = null
private var end: Node? = null
/* Function to get size of list */
var size: Int = 0
/* Function to check if list is empty */
val isEmpty: Boolean
get() = start == null
/* Constructor */
init {
start = null
end = null
size = 0
}
/* Function to insert an element at begining */
fun insertAtStart(value: Int) {
val nptr = Node(value, null)
size++
if (start == null) {
start = nptr
end = start
} else {
nptr.link = start
start = nptr
}
}
/* Function to insert an element at end */
fun insertAtEnd(value: Int) {
val nptr = Node(value, null)
size++
if (start == null) {
start = nptr
end = start
} else {
end!!.link = nptr
end = nptr
}
}
/* Function to insert an element at position */
fun insertAtPos(value: Int, pos: Int) {
var pos = pos
val nptr = Node(value, null)
var ptr = start
pos =- 1
for (i in 1 until size) {
if (i == pos) {
val tmp = ptr!!.link
ptr.link = nptr
nptr.link = tmp
break
}
ptr = ptr!!.link
}
size++
}
/* Function to delete an element at position */
fun deleteAtPos(pos: Int) {
var pos = pos
if (pos == 1) {
start = start!!.link
size--
return
}
if (pos == size) {
var s = start
var t = start
while (s !== end) {
t = s
s = s!!.link
}
end = t
end!!.link = null
size--
return
}
var ptr = start
pos =- 1
for (i in 1 until size - 1) {
if (i == pos) {
var tmp = ptr!!.link
tmp = tmp!!.link
ptr.link = tmp
break
}
ptr = ptr!!.link
}
size--
}
/* Function to display elements */
fun display() {
print("\nSingly Linked List = ")
if (size == 0) {
print("empty\n")
return
}
if (start!!.link == null) {
println(start!!.data)
return
}
var ptr = start
print(start!!.data.toString() + "->")
ptr = start!!.link
while (ptr!!.link != null) {
print(ptr.data.toString() + "->")
ptr = ptr.link
}
print(ptr.data.toString() + "\n")
}
}
/* Class SinglyLinkedList */
object SinglyLinkedList {
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
/* Creating object of class linkedList */
val list = linkedList()
println("Singly Linked List Test\n")
var ch: Char
/* Perform list operations */
do {
println("\nSingly Linked List Operations\n")
println("1. insert at begining")
println("2. insert at end")
println("3. insert at position")
println("4. delete at position")
println("5. check empty")
println("6. get size")
val choice = scan.nextInt()
when (choice) {
1 -> {
println("Enter integer element to insert")
list.insertAtStart(scan.nextInt())
}
2 -> {
println("Enter integer element to insert")
list.insertAtEnd(scan.nextInt())
}
3 -> {
println("Enter integer element to insert")
val num = scan.nextInt()
println("Enter position")
val pos = scan.nextInt()
if (pos <= 1 || pos > list.size)
println("Invalid position\n")
else
list.insertAtPos(num, pos)
}
4 -> {
println("Enter position")
val p = scan.nextInt()
if (p < 1 || p > list.size)
println("Invalid position\n")
else
list.deleteAtPos(p)
}
5 -> println("Empty status = " + list.isEmpty)
6 -> println("Size = " + list.size + " \n")
else -> println("Wrong Entry \n ")
}
/* Display List */
list.display()
println("\nDo you want to continue (Type y or n) \n")
ch = scan.next()[0]
} while (ch == 'Y' || ch == 'y')
}
}
| gpl-3.0 | 203505bf40e726190828f33737d54155 | 25.315789 | 65 | 0.426 | 4.453441 | false | false | false | false |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/main/java/com/garpr/android/features/common/views/RefreshLayout.kt | 1 | 1875 | package com.garpr.android.features.common.views
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.annotation.IdRes
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.garpr.android.R
import com.garpr.android.misc.Heartbeat
import com.garpr.android.misc.ListLayout
/**
* A child class of the official Android [SwipeRefreshLayout] that helps us work around some of
* its shortcomings. We should use this view instead of SwipeRefreshLayout in every case.
*/
class RefreshLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : SwipeRefreshLayout(context, attrs), Heartbeat, ListLayout {
override val isAlive: Boolean
get() = ViewCompat.isAttachedToWindow(this)
@IdRes
private val scrollingChildId: Int
private var scrollingChild: View? = null
init {
val ta = context.obtainStyledAttributes(attrs, R.styleable.RefreshLayout)
scrollingChildId = ta.getResourceId(R.styleable.RefreshLayout_scrollingChildId, View.NO_ID)
ta.recycle()
}
/*
* http://stackoverflow.com/q/25270171/823952
*/
override fun canChildScrollUp(): Boolean {
return scrollingChild?.canScrollVertically(-1) ?: super.canChildScrollUp()
}
override fun getRecyclerView(): RecyclerView? {
return scrollingChild as? RecyclerView?
}
override fun onFinishInflate() {
super.onFinishInflate()
if (scrollingChildId != View.NO_ID) {
scrollingChild = ViewCompat.requireViewById(this, scrollingChildId)
}
setColorSchemeColors(*resources.getIntArray(R.array.spinner_colors))
setProgressBackgroundColorSchemeResource(R.color.card_background)
}
}
| unlicense | 541c05d45b263edc6f3786358bb1277a | 30.779661 | 99 | 0.7328 | 4.62963 | false | false | false | false |
ysahnpark/claroforma | server/claroforma-backend/src/main/kotlin/com/claroaprende/util/MapHelper.kt | 1 | 796 | package com.claroaprende.util
object MapHelper {
fun dotAccess(map: Map<*, *>, path: String) : Any? {
val pathItems = path.split(".")
return dotAccess(map, pathItems)
}
fun dotAccess(map: Map<*, *>, pathItems: List<String>) : Any? {
if (pathItems.size == 0) {
throw IllegalArgumentException("pathItem cannot be empty")
}
else if (!map.containsKey(pathItems[0])) {
return null
}
var entry = map[pathItems[0]]
if (pathItems.size == 1) {
return entry
}
else if (entry is Map<*, *>) {
val trimmedPathItems = pathItems.subList(1, pathItems.size)
return dotAccess(entry, trimmedPathItems)
} else {
return null
}
}
} | mit | 54f2f5328b1a914cc36042749f1bd306 | 28.518519 | 71 | 0.538945 | 4.061224 | false | false | false | false |
kotlin-es/kotlin-JFrame-standalone | 10-start-async-checkbutton-application/src/main/kotlin/components/progressBar/ProgressBarImpl.kt | 7 | 1002 | package components.progressBar
import utils.ThreadMain
import java.awt.Component
import java.util.concurrent.CompletableFuture
import javax.swing.JProgressBar
/**
* Created by vicboma on 05/12/16.
*/
class ProgressBarImpl internal constructor(val min: Int, val max: Int) : JProgressBar(min,max) , ProgressBar {
companion object {
fun create(min: Int, max: Int): ProgressBar {
return ProgressBarImpl(min,max)
}
}
init{
value = 0
isStringPainted = true
setAlignmentX(Component.CENTER_ALIGNMENT)
}
override fun asyncUI() {
ThreadMain.asyncUI {
CompletableFuture.runAsync {
for (i in min..max) {
Thread.sleep(30)
value = i * 1
}
}.thenAcceptAsync {
Thread.sleep(500)
value = 0
asyncUI()
}
}
}
override fun component() : JProgressBar = this
}
| mit | 4fcd382db2cedf18f9e6b1693e3836bf | 22.857143 | 110 | 0.558882 | 4.554545 | false | false | false | false |
mehulsbhatt/emv-bertlv | src/main/java/io/github/binaryfoo/tlv/BerTlv.kt | 1 | 7467 | package io.github.binaryfoo.tlv
import java.nio.ByteBuffer
import java.util.ArrayList
import java.util.Arrays
import kotlin.platform.platformStatic
/**
* Model data elements encoded using the Basic Encoding Rules: http://en.wikipedia.org/wiki/X.690#BER_encoding.
*/
public abstract class BerTlv(public val tag: Tag) {
public fun toBinary(): ByteArray {
val value = getValue()
val encodedTag = tag.bytes
val encodedLength = getLength(value)
val b = ByteBuffer.allocate(encodedTag.size + encodedLength.size + value.size)
b.put(encodedTag)
b.put(encodedLength)
b.put(value)
b.flip()
return b.array()
}
/**
* The whole object (the T, L and V components) as a hex string.
*/
public fun toHexString(): String = ISOUtil.hexString(toBinary())
/**
* The value of V in TLV as a hex string.
*/
public val valueAsHexString: String
get() = ISOUtil.hexString(getValue())
/**
* The number of bytes used to encode the L (length) in TLV.
* Eg 1 byte might be used to encode a length of 12, whilst at least 2 bytes would be used for a length of 300.
*/
public val lengthInBytesOfEncodedLength: Int
get() = getLength(getValue()).size
/**
* The value of L (length) in TLV. Length in bytes of the value.
*/
public val length: Int
get() = getValue().size
/**
* Skip the tag and length bytes.
*/
public val startIndexOfValue: Int
get() = tag.bytes.size + lengthInBytesOfEncodedLength
public abstract fun findTlv(tag: Tag): BerTlv?
public abstract fun findTlvs(tag: Tag): List<BerTlv>
/**
* The value of V in TLV as a byte array.
*/
public abstract fun getValue(): ByteArray
/**
* For a constructed TLV the child elements that make up the V. For a primitive, an empty list.
*/
public abstract fun getChildren(): List<BerTlv>
private fun getLength(value: ByteArray?): ByteArray {
val length: ByteArray
if (value == null) {
return byteArray(0.toByte())
}
if (value.size <= 0x7F) {
length = byteArray(value.size.toByte())
} else {
val wanted = value.size
var expected = 256
var needed = 1
while (wanted >= expected) {
needed++
expected = expected shl 8
if (expected == 0) {
// just to be sure
throw IllegalArgumentException()
}
}
length = ByteArray(needed + 1)
length[0] = (0x80 or needed).toByte()
for (i in 1..length.size - 1) {
length[length.size - i] = ((wanted shr (8 * (i - 1))) and 255).toByte()
}
}
return length
}
class object {
platformStatic public fun newInstance(tag: Tag, value: ByteArray): BerTlv {
return PrimitiveBerTlv(tag, value)
}
platformStatic public fun newInstance(tag: Tag, hexString: String): BerTlv {
return PrimitiveBerTlv(tag, ISOUtil.hex2byte(hexString))
}
platformStatic public fun newInstance(tag: Tag, value: Int): BerTlv {
if (value > 255) {
throw IllegalArgumentException("Value greater than 255 must be encoded in a byte array")
}
return PrimitiveBerTlv(tag, byteArray(value.toByte()))
}
platformStatic public fun newInstance(tag: Tag, value: List<BerTlv>): BerTlv {
return ConstructedBerTlv(tag, value)
}
platformStatic public fun newInstance(tag: Tag, tlv1: BerTlv, tlv2: BerTlv): BerTlv {
return ConstructedBerTlv(tag, Arrays.asList<BerTlv>(tlv1, tlv2))
}
platformStatic public fun parse(data: ByteArray): BerTlv {
return parseList(ByteBuffer.wrap(data), true).get(0)
}
platformStatic public fun parseAsPrimitiveTag(data: ByteArray): BerTlv {
return parseList(ByteBuffer.wrap(data), false).get(0)
}
platformStatic public fun parseList(data: ByteArray, parseConstructedTags: Boolean): List<BerTlv> {
return parseList(ByteBuffer.wrap(data), parseConstructedTags)
}
platformStatic public fun parseList(data: ByteArray, parseConstructedTags: Boolean, recognitionMode: TagRecognitionMode): List<BerTlv> {
return parseList(ByteBuffer.wrap(data), parseConstructedTags, recognitionMode)
}
private fun parseList(data: ByteBuffer, parseConstructedTags: Boolean, recognitionMode: TagRecognitionMode = CompliantTagMode): List<BerTlv> {
val tlvs = ArrayList<BerTlv>()
while (data.hasRemaining()) {
val tag = Tag.parse(data, recognitionMode)
if (isPaddingByte(tag)) {
continue
}
try {
val length = parseLength(data)
val value = readUpToLength(data, length)
if (tag.constructed && parseConstructedTags) {
try {
tlvs.add(newInstance(tag, parseList(value, true, recognitionMode)))
} catch (e: Exception) {
tlvs.add(newInstance(tag, value))
}
} else {
tlvs.add(newInstance(tag, value))
}
} catch (e: Exception) {
throw TlvParseException(tlvs, "Failed parsing TLV with tag $tag: " + e.getMessage(), e)
}
}
return tlvs
}
private fun readUpToLength(data: ByteBuffer, length: Int): ByteArray {
val value = ByteArray(if (length > data.remaining()) data.remaining() else length)
data.get(value)
return value
}
// Specification Update No. 69, 2009, Padding of BER-TLV Encoded Constructed Data Objects
private fun isPaddingByte(tag: Tag): Boolean {
return tag.bytes.size == 1 && tag.bytes[0] == 0.toByte()
}
private fun parseLength(data: ByteBuffer): Int {
val firstByte = data.get().toInt()
var length = 0
if ((firstByte and 0x80) == 0x80) {
var numberOfBytesToEncodeLength = (firstByte and 0x7F)
for (i in 1..numberOfBytesToEncodeLength) {
if (!data.hasRemaining()) {
throw IllegalArgumentException("Bad length: expected to read $numberOfBytesToEncodeLength (0x${firstByte.toByte().toHexString()}) bytes. Only have ${i-1}.")
}
length += (data.get().toInt() and 0xFF)
if (i != numberOfBytesToEncodeLength) {
length *= 256
}
if (length < 0) {
throw IllegalArgumentException("Bad length: $length < 0. Read $i of $numberOfBytesToEncodeLength (0x${firstByte.toByte().toHexString()}) bytes used to encode length of TLV.")
}
}
} else {
length = firstByte
}
return length
}
platformStatic public fun findTlv(tlvs: List<BerTlv>, tag: Tag): BerTlv? = tlvs.firstOrNull { it.tag == tag }
}
}
| mit | f6b88b0b2abdf34e6ff684307ea6de32 | 35.247573 | 198 | 0.56435 | 4.597906 | false | false | false | false |
tschuchortdev/kotlin-compile-testing | core/src/main/kotlin/com/tschuchort/compiletesting/DefaultPropertyDelegate.kt | 1 | 954 | package com.tschuchort.compiletesting
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
@Suppress("MemberVisibilityCanBePrivate")
internal class DefaultPropertyDelegate<R,T>(private val createDefault: () -> T) : ReadWriteProperty<R, T> {
val hasDefaultValue
@Synchronized get() = (value == DEFAULT)
private var value: Any? = DEFAULT
val defaultValue by lazy { createDefault() }
@Synchronized
override operator fun getValue(thisRef: R, property: KProperty<*>): T {
@Suppress("UNCHECKED_CAST")
return if(hasDefaultValue)
defaultValue
else
value as T
}
@Synchronized
override operator fun setValue(thisRef: R, property: KProperty<*>, value: T) {
this.value = value
}
companion object {
private object DEFAULT
}
}
internal fun <R,T> default(createDefault: () -> T) = DefaultPropertyDelegate<R,T>(createDefault) | mpl-2.0 | 2a028331cf2a0db48b71018e7918e39e | 27.939394 | 107 | 0.677149 | 4.79397 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.