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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jwren/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeInsight/hints/KotlinCallChainHintsProviderTest.kt | 2 | 5273 | // 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.codeInsight.hints
import com.intellij.testFramework.utils.inlays.InlayHintsProviderTestCase
/**
* [org.jetbrains.kotlin.idea.codeInsight.hints.KotlinCallChainHintsProvider]
*/
class KotlinCallChainHintsProviderTest : InlayHintsProviderTestCase() {
val chainLib = """
class Foo {
var foo = Foo()
var bar = Bar()
fun foo(block: () -> Unit = {}) = Foo()
fun nullFoo(): Foo? = null
fun bar(block: () -> Unit = {}) = Bar()
fun nullBar(): Bar? = null
operator fun inc() = Foo()
operator fun get(index: Int) = Bar()
operator fun invoke() = Bar()
}
class Bar {
var foo = Foo()
var bar = Bar()
fun foo(block: () -> Unit = {}) = Foo()
fun nullFoo(): Foo? = null
fun bar(block: () -> Unit = {}) = Bar()
fun nullBar(): Bar? = null
operator fun inc() = Bar()
operator fun get(index: Int) = Foo()
operator fun invoke() = Foo()
}
""".trimIndent()
fun `test error type`() = doTest("""
// NO_HINTS
interface Baz {
fun foo(): Foo = Foo()
}
class Outer : Baz {
class Nested {
val x = [email protected]()
.bar()
.foo()
.bar()
}
}
""".trimIndent())
fun `test simple`() = doTest("""
fun main() {
Foo().bar()<# [temp:///src/foo.kt:311]Bar #>
.foo()<# [temp:///src/foo.kt:0]Foo #>
.bar()<# [temp:///src/foo.kt:311]Bar #>
.foo()
}
""".trimIndent())
fun `test multiline calls`() = doTest("""
fun main() {
Foo()
.bar {
}<# [temp:///src/foo.kt:311]Bar #>
.foo()<# [temp:///src/foo.kt:0]Foo #>
.bar {}<# [temp:///src/foo.kt:311]Bar #>
.foo()
}
""".trimIndent())
fun `test duplicated builder`() = doTest("""
fun main() {
Foo().foo()<# [temp:///src/foo.kt:0]Foo #>
.bar().foo()
.bar()<# [temp:///src/foo.kt:311]Bar #>
.foo()
}
""".trimIndent())
fun `test comments`() = doTest("""
fun main() {
Foo().bar() // comment
.foo()<# [temp:///src/foo.kt:0]Foo #>
.bar()<# [temp:///src/foo.kt:311]Bar #>
.foo()// comment
.bar()
.bar()
}
""".trimIndent())
fun `test properties`() = doTest("""
fun main() {
Foo().bar<# [temp:///src/foo.kt:311]Bar #>
.foo<# [temp:///src/foo.kt:0]Foo #>
.bar.bar<# [temp:///src/foo.kt:311]Bar #>
.foo()<# [temp:///src/foo.kt:0]Foo #>
.bar<# [temp:///src/foo.kt:311]Bar #>
.bar()
}
""".trimIndent())
fun `test postfix operators`() = doTest("""
fun main() {
Foo().bar()!!<# [temp:///src/foo.kt:311]Bar #>
.foo++<# [temp:///src/foo.kt:0]Foo #>
.foo[1]<# [temp:///src/foo.kt:311]Bar #>
.nullFoo()!!<# [temp:///src/foo.kt:0]Foo #>
.foo()()<# [temp:///src/foo.kt:311]Bar #>
.bar
}
""".trimIndent())
fun `test safe dereference`() = doTest("""
fun main() {
Foo()
.nullBar()<# [[temp:///src/foo.kt:311]Bar ?] #>
?.foo!!<# [temp:///src/foo.kt:0]Foo #>
.bar()
}
""".trimIndent())
fun `test several call chains`() = doTest("""
fun main() {
Foo()
.nullBar()<# [[temp:///src/foo.kt:311]Bar ?] #>
?.foo!!<# [temp:///src/foo.kt:0]Foo #>
.bar()
Bar().foo()<# [temp:///src/foo.kt:0]Foo #>
.bar().foo()
.bar()<# [temp:///src/foo.kt:311]Bar #>
.foo()
}
""".trimIndent())
fun `test nested call chains`() = doTest("""
fun main() {
Foo().foo {
Bar().foo()<# [temp:///src/foo.kt:0]Foo #>
.bar()<# [temp:///src/foo.kt:311]Bar #>
.foo()
}<# [temp:///src/foo.kt:0]Foo #>
.bar()<# [temp:///src/foo.kt:311]Bar #>
.foo()<# [temp:///src/foo.kt:0]Foo #>
.bar()
}
""".trimIndent())
fun `test nullable and notnullable types rotation of the same type`() = doTest("""
fun main() {
Foo().nullBar()<# [[temp:///src/foo.kt:311]Bar ?] #>
?.bar!!<# [temp:///src/foo.kt:311]Bar #>
.nullBar()<# [[temp:///src/foo.kt:311]Bar ?] #>
?.foo()
}
""".trimIndent())
private fun doTest(text: String) {
testProvider("foo.kt", "$chainLib\n$text", KotlinCallChainHintsProvider())
}
} | apache-2.0 | cf5d26291cb59741398921f32e9ffad4 | 31.355828 | 158 | 0.413617 | 3.952774 | false | true | false | false |
JetBrains/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/Linker.kt | 1 | 11178 | package org.jetbrains.kotlin.backend.konan
import org.jetbrains.kotlin.konan.KonanExternalToolFailure
import org.jetbrains.kotlin.konan.exec.Command
import org.jetbrains.kotlin.konan.file.File
import org.jetbrains.kotlin.konan.library.KonanLibrary
import org.jetbrains.kotlin.konan.target.*
import org.jetbrains.kotlin.library.resolver.TopologicalLibraryOrder
import org.jetbrains.kotlin.library.uniqueName
import org.jetbrains.kotlin.utils.addToStdlib.cast
internal fun determineLinkerOutput(context: Context): LinkerOutputKind =
when (context.config.produce) {
CompilerOutputKind.FRAMEWORK -> {
val staticFramework = context.config.produceStaticFramework
if (staticFramework) LinkerOutputKind.STATIC_LIBRARY else LinkerOutputKind.DYNAMIC_LIBRARY
}
CompilerOutputKind.DYNAMIC_CACHE,
CompilerOutputKind.DYNAMIC -> LinkerOutputKind.DYNAMIC_LIBRARY
CompilerOutputKind.STATIC_CACHE,
CompilerOutputKind.STATIC -> LinkerOutputKind.STATIC_LIBRARY
CompilerOutputKind.PROGRAM -> LinkerOutputKind.EXECUTABLE
else -> TODO("${context.config.produce} should not reach native linker stage")
}
// TODO: We have a Linker.kt file in the shared module.
internal class Linker(val context: Context) {
private val platform = context.config.platform
private val config = context.config.configuration
private val linkerOutput = determineLinkerOutput(context)
private val linker = platform.linker
private val target = context.config.target
private val optimize = context.shouldOptimize()
private val debug = context.config.debug || context.config.lightDebug
fun link(objectFiles: List<ObjectFile>) {
val nativeDependencies = context.llvm.nativeDependenciesToLink
val includedBinariesLibraries = if (context.config.produce.isCache) {
context.config.librariesToCache
} else {
nativeDependencies.filterNot { context.config.cachedLibraries.isLibraryCached(it) }
}
val includedBinaries = includedBinariesLibraries.map { (it as? KonanLibrary)?.includedPaths.orEmpty() }.flatten()
val libraryProvidedLinkerFlags = context.llvm.allNativeDependencies.map { it.linkerOpts }.flatten()
if (context.config.produce.isCache) {
context.config.outputFiles.tempCacheDirectory!!.mkdirs()
saveAdditionalInfoForCache()
}
runLinker(objectFiles, includedBinaries, libraryProvidedLinkerFlags)
renameOutput()
}
private fun saveAdditionalInfoForCache() {
saveCacheBitcodeDependencies()
}
private fun saveCacheBitcodeDependencies() {
val outputFiles = context.config.outputFiles
val bitcodeDependenciesFile = File(outputFiles.bitcodeDependenciesFile!!)
val bitcodeDependencies = context.config.resolvedLibraries
.getFullList(TopologicalLibraryOrder)
.filter {
require(it is KonanLibrary)
context.llvmImports.bitcodeIsUsed(it)
&& it !in context.config.cacheSupport.librariesToCache // Skip loops.
}.cast<List<KonanLibrary>>()
bitcodeDependenciesFile.writeLines(bitcodeDependencies.map { it.uniqueName })
}
private fun renameOutput() {
if (context.config.produce.isCache) {
val outputFiles = context.config.outputFiles
// For caches the output file is a directory. It might be created by someone else,
// We have to delete it in order to the next renaming operation to succeed.
java.io.File(outputFiles.mainFile).delete()
if (!java.io.File(outputFiles.tempCacheDirectory!!.absolutePath).renameTo(java.io.File(outputFiles.mainFile)))
outputFiles.tempCacheDirectory.deleteRecursively()
}
}
private fun asLinkerArgs(args: List<String>): List<String> {
if (linker.useCompilerDriverAsLinker) {
return args
}
val result = mutableListOf<String>()
for (arg in args) {
// If user passes compiler arguments to us - transform them to linker ones.
if (arg.startsWith("-Wl,")) {
result.addAll(arg.substring(4).split(','))
} else {
result.add(arg)
}
}
return result
}
private fun runLinker(objectFiles: List<ObjectFile>,
includedBinaries: List<String>,
libraryProvidedLinkerFlags: List<String>): ExecutableFile? {
val additionalLinkerArgs: List<String>
val executable: String
if (context.config.produce != CompilerOutputKind.FRAMEWORK) {
additionalLinkerArgs = if (target.family.isAppleFamily) {
when (context.config.produce) {
CompilerOutputKind.DYNAMIC_CACHE ->
listOf("-install_name", context.config.outputFiles.dynamicCacheInstallName)
else -> listOf("-dead_strip")
}
} else {
emptyList()
}
executable = context.config.outputFiles.nativeBinaryFile
} else {
val framework = File(context.config.outputFile)
val dylibName = framework.name.removeSuffix(".framework")
val dylibRelativePath = when (target.family) {
Family.IOS,
Family.TVOS,
Family.WATCHOS -> dylibName
Family.OSX -> "Versions/A/$dylibName"
else -> error(target)
}
additionalLinkerArgs = listOf("-dead_strip", "-install_name", "@rpath/${framework.name}/$dylibRelativePath")
val dylibPath = framework.child(dylibRelativePath)
dylibPath.parentFile.mkdirs()
executable = dylibPath.absolutePath
}
val needsProfileLibrary = context.coverage.enabled
val mimallocEnabled = config.get(KonanConfigKeys.ALLOCATION_MODE) == "mimalloc" &&
target.supportsMimallocAllocator()
val linkerInput = determineLinkerInput(objectFiles, linkerOutput)
try {
File(executable).delete()
val linkerArgs = asLinkerArgs(config.getNotNull(KonanConfigKeys.LINKER_ARGS)) +
BitcodeEmbedding.getLinkerOptions(context.config) +
linkerInput.caches.dynamic +
libraryProvidedLinkerFlags + additionalLinkerArgs
val finalOutputCommands = linker.finalLinkCommands(
objectFiles = linkerInput.objectFiles,
executable = executable,
libraries = linker.linkStaticLibraries(includedBinaries) + linkerInput.caches.static,
linkerArgs = linkerArgs,
optimize = optimize,
debug = debug,
kind = linkerOutput,
outputDsymBundle = context.config.outputFiles.symbolicInfoFile,
needsProfileLibrary = needsProfileLibrary,
mimallocEnabled = mimallocEnabled)
(linkerInput.preLinkCommands + finalOutputCommands).forEach {
it.logWith(context::log)
it.execute()
}
} catch (e: KonanExternalToolFailure) {
val extraUserInfo =
if (linkerInput.cachingInvolved)
"""
Please try to disable compiler caches and rerun the build. To disable compiler caches, add the following line to the gradle.properties file in the project's root directory:
kotlin.native.cacheKind.${target.presetName}=none
Also, consider filing an issue with full Gradle log here: https://kotl.in/issue
""".trimIndent()
else ""
context.reportCompilationError("${e.toolName} invocation reported errors\n$extraUserInfo\n${e.message}")
}
return executable
}
private fun shouldPerformPreLink(caches: CachesToLink, linkerOutputKind: LinkerOutputKind): Boolean {
// Pre-link is only useful when producing static library. Otherwise its just a waste of time.
val isStaticLibrary = linkerOutputKind == LinkerOutputKind.STATIC_LIBRARY &&
context.config.produce.isFinalBinary
val enabled = context.config.cacheSupport.preLinkCaches
val nonEmptyCaches = caches.static.isNotEmpty()
return isStaticLibrary && enabled && nonEmptyCaches
}
private fun determineLinkerInput(objectFiles: List<ObjectFile>, linkerOutputKind: LinkerOutputKind): LinkerInput {
val caches = determineCachesToLink(context)
// Since we have several linker stages that involve caching,
// we should detect cache usage early to report errors correctly.
val cachingInvolved = caches.static.isNotEmpty() || caches.dynamic.isNotEmpty()
return when {
context.config.produce == CompilerOutputKind.STATIC_CACHE -> {
// Do not link static cache dependencies.
LinkerInput(objectFiles, CachesToLink(emptyList(), caches.dynamic), emptyList(), cachingInvolved)
}
shouldPerformPreLink(caches, linkerOutputKind) -> {
val preLinkResult = context.config.tempFiles.create("withStaticCaches", ".o").absolutePath
val preLinkCommands = linker.preLinkCommands(objectFiles + caches.static, preLinkResult)
LinkerInput(listOf(preLinkResult), CachesToLink(emptyList(), caches.dynamic), preLinkCommands, cachingInvolved)
}
else -> LinkerInput(objectFiles, caches, emptyList(), cachingInvolved)
}
}
}
private class LinkerInput(
val objectFiles: List<ObjectFile>,
val caches: CachesToLink,
val preLinkCommands: List<Command>,
val cachingInvolved: Boolean
)
private class CachesToLink(val static: List<String>, val dynamic: List<String>)
private fun determineCachesToLink(context: Context): CachesToLink {
val staticCaches = mutableListOf<String>()
val dynamicCaches = mutableListOf<String>()
context.llvm.allCachedBitcodeDependencies.forEach { library ->
val currentBinaryContainsLibrary = context.llvmModuleSpecification.containsLibrary(library)
val cache = context.config.cachedLibraries.getLibraryCache(library)
?: error("Library $library is expected to be cached")
// Consistency check. Generally guaranteed by implementation.
if (currentBinaryContainsLibrary)
error("Library ${library.libraryName} is found in both cache and current binary")
val list = when (cache.kind) {
CachedLibraries.Cache.Kind.DYNAMIC -> dynamicCaches
CachedLibraries.Cache.Kind.STATIC -> staticCaches
}
list += cache.path
}
return CachesToLink(static = staticCaches, dynamic = dynamicCaches)
}
| apache-2.0 | b692d5e149db524403748c3538846acc | 45.966387 | 196 | 0.645106 | 5.060208 | false | true | false | false |
jwren/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/KotlinClassRenderer.kt | 5 | 7338 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger
import com.intellij.debugger.JavaDebuggerBundle
import com.intellij.debugger.engine.DebuggerManagerThreadImpl
import com.intellij.debugger.engine.DebuggerUtils
import com.intellij.debugger.engine.JVMNameUtil
import com.intellij.debugger.engine.evaluation.EvaluationContext
import com.intellij.debugger.impl.DebuggerUtilsAsync
import com.intellij.debugger.settings.NodeRendererSettings
import com.intellij.debugger.ui.impl.watch.ValueDescriptorImpl
import com.intellij.debugger.ui.tree.DebuggerTreeNode
import com.intellij.debugger.ui.tree.NodeManager
import com.intellij.debugger.ui.tree.ValueDescriptor
import com.intellij.debugger.ui.tree.render.ChildrenBuilder
import com.intellij.debugger.ui.tree.render.ClassRenderer
import com.intellij.debugger.ui.tree.render.DescriptorLabelListener
import com.intellij.openapi.project.Project
import com.sun.jdi.*
import java.util.concurrent.CompletableFuture
import java.util.function.Function
class KotlinClassRenderer : ClassRenderer() {
init {
setIsApplicableChecker(Function { type: Type? ->
if (type is ReferenceType && type !is ArrayType && !type.canBeRenderedBetterByPlatformRenderers()) {
return@Function type.isInKotlinSourcesAsync()
}
CompletableFuture.completedFuture(false)
})
}
override fun buildChildren(value: Value?, builder: ChildrenBuilder, evaluationContext: EvaluationContext) {
DebuggerManagerThreadImpl.assertIsManagerThread()
if (value !is ObjectReference) {
builder.setChildren(emptyList())
return
}
val parentDescriptor = builder.parentDescriptor as ValueDescriptorImpl
val nodeManager = builder.nodeManager
val nodeDescriptorFactory = builder.descriptorManager
val refType = value.referenceType()
val gettersFuture = DebuggerUtilsAsync.allMethods(refType)
.thenApply { methods -> methods.getters().createNodes(value, parentDescriptor.project, evaluationContext, nodeManager) }
DebuggerUtilsAsync.allFields(refType).thenCombine(gettersFuture) { fields, getterNodes ->
if (fields.isEmpty() && getterNodes.isEmpty()) {
builder.setChildren(listOf(nodeManager.createMessageNode(KotlinDebuggerCoreBundle.message("message.class.has.no.properties"))))
return@thenCombine
}
createNodesToShow(fields, evaluationContext, parentDescriptor, nodeManager, nodeDescriptorFactory, value)
.thenAccept { nodesToShow ->
if (nodesToShow.isEmpty()) {
val classHasNoFieldsToDisplayMessage =
nodeManager.createMessageNode(
JavaDebuggerBundle.message("message.node.class.no.fields.to.display")
)
builder.setChildren(
listOf(classHasNoFieldsToDisplayMessage) +
getterNodes
)
return@thenAccept
}
builder.setChildren(mergeNodesLists(nodesToShow, getterNodes))
}
}
}
override fun calcLabel(
descriptor: ValueDescriptor,
evaluationContext: EvaluationContext?,
labelListener: DescriptorLabelListener
): String {
val renderer = NodeRendererSettings.getInstance().toStringRenderer
return renderer.calcLabel(descriptor, evaluationContext, labelListener)
}
override fun isApplicable(type: Type?) = throw IllegalStateException("Should not be called")
override fun shouldDisplay(context: EvaluationContext?, objInstance: ObjectReference, field: Field): Boolean {
val referenceType = objInstance.referenceType()
if (field.isStatic && referenceType.isKotlinObjectType()) {
if (field.isInstanceFieldOfType(referenceType)) {
return false
}
return true
}
return super.shouldDisplay(context, objInstance, field)
}
private fun mergeNodesLists(fieldNodes: List<DebuggerTreeNode>, getterNodes: List<DebuggerTreeNode>): List<DebuggerTreeNode> {
val namesToIndex = getterNodes.withIndex().associate { it.value.descriptor.name to it.index }
val result = ArrayList<DebuggerTreeNode>(fieldNodes.size + getterNodes.size)
val added = BooleanArray(getterNodes.size)
for (fieldNode in fieldNodes) {
result.add(fieldNode)
val name = fieldNode.descriptor.name.removeSuffix("\$delegate")
val index = namesToIndex[name] ?: continue
if (!added[index]) {
result.add(getterNodes[index])
added[index] = true
}
}
result.addAll(getterNodes.filterIndexed { i, _ -> !added[i] })
return result
}
private fun List<Method>.getters() =
filter { method ->
!method.isAbstract &&
GetterDescriptor.GETTER_PREFIXES.any { method.name().startsWith(it) } &&
method.argumentTypeNames().isEmpty() &&
method.name() != "getClass" &&
!method.name().endsWith("\$annotations") &&
method.declaringType().isInKotlinSources() &&
!method.isSimpleGetter() &&
!method.isLateinitVariableGetter()
}
.distinctBy { it.name() }
.toList()
private fun List<Method>.createNodes(
parentObject: ObjectReference,
project: Project,
evaluationContext: EvaluationContext,
nodeManager: NodeManager
) = map { nodeManager.createNode(GetterDescriptor(parentObject, it, project), evaluationContext) }
private fun ReferenceType.isKotlinObjectType() =
containsInstanceField() && hasPrivateConstructor()
private fun ReferenceType.containsInstanceField() =
safeFields().any { it.isInstanceFieldOfType(this) }
private fun ReferenceType.hasPrivateConstructor(): Boolean {
val constructor = methodsByName(JVMNameUtil.CONSTRUCTOR_NAME).singleOrNull() ?: return false
return constructor.isPrivate && constructor.argumentTypeNames().isEmpty()
}
/**
* IntelliJ Platform has good collections' debugger renderers.
*
* We want to use them even when the collection is implemented completely in Kotlin
* (e.g. lists, sets and maps empty singletons; subclasses of `Abstract(List|Set|Map)`;
* collections, built by `build(List|Set|Map) { ... }` methods).
*
* Also we want to use platform renderer for Map entries.
*/
private fun ReferenceType.canBeRenderedBetterByPlatformRenderers(): Boolean {
val typesWithGoodDefaultRenderers = listOf(
"java.util.Collection",
"java.util.Map",
"java.util.Map.Entry",
)
return typesWithGoodDefaultRenderers.any { superType -> DebuggerUtils.instanceOf(this, superType) }
}
private fun Field.isInstanceFieldOfType(type: Type) =
isStatic && isFinal && name() == "INSTANCE" && safeType() == type
}
| apache-2.0 | 79fed5f5cccc7c2d431de154cb68207c | 43.472727 | 158 | 0.667893 | 5.057202 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/Weighers.kt | 1 | 17568 | // 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
import com.intellij.codeInsight.completion.CompletionLocation
import com.intellij.codeInsight.completion.CompletionWeigher
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementWeigher
import com.intellij.codeInsight.lookup.WeighingContext
import com.intellij.openapi.util.Key
import com.intellij.psi.util.proximity.PsiProximityComparator
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.completion.smart.*
import org.jetbrains.kotlin.idea.core.ExpectedInfo
import org.jetbrains.kotlin.idea.core.completion.DeclarationLookupObject
import org.jetbrains.kotlin.idea.core.completion.PackageLookupObject
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.CallType
import org.jetbrains.kotlin.idea.util.CallTypeAndReceiver
import org.jetbrains.kotlin.idea.util.toFuzzyType
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.descriptorUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.findOriginalTopMostOverriddenDescriptors
import org.jetbrains.kotlin.types.typeUtil.isNothing
object PriorityWeigher : LookupElementWeigher("kotlin.priority") {
override fun weigh(element: LookupElement, context: WeighingContext) = element.priority ?: ItemPriority.DEFAULT
}
object PreferDslMembers : LookupElementWeigher("kotlin.preferDsl") {
override fun weigh(element: LookupElement, context: WeighingContext): Boolean {
if (element.isDslMember == true) return false // high priority
return true // lower priority
}
}
class NotImportedWeigher(private val classifier: ImportableFqNameClassifier) : LookupElementWeigher("kotlin.notImported") {
private enum class Weight {
default,
siblingImported,
notImported,
notToBeUsedInKotlin
}
override fun weigh(element: LookupElement): Comparable<*> {
if (element.getUserData(NOT_IMPORTED_KEY) == null) return Weight.default
val o = element.`object` as? DeclarationLookupObject
val fqName = o?.importableFqName ?: return Weight.default
return when (classifier.classify(fqName, o is PackageLookupObject)) {
ImportableFqNameClassifier.Classification.siblingImported -> Weight.siblingImported
ImportableFqNameClassifier.Classification.notImported -> Weight.notImported
ImportableFqNameClassifier.Classification.notToBeUsedInKotlin -> Weight.notToBeUsedInKotlin
else -> Weight.default
}
}
}
class NotImportedStaticMemberWeigher(private val classifier: ImportableFqNameClassifier) :
LookupElementWeigher("kotlin.notImportedMember") {
override fun weigh(element: LookupElement): Comparable<*>? {
if (element.priority != ItemPriority.STATIC_MEMBER) return null
val fqName = (element.`object` as DeclarationLookupObject).importableFqName ?: return null
return classifier.classify(fqName.parent(), false)
}
}
class ImportedWeigher(private val classifier: ImportableFqNameClassifier) : LookupElementWeigher("kotlin.imported") {
private enum class Weight {
currentPackage,
preciseImport,
defaultImport,
allUnderImport
}
override fun weigh(element: LookupElement): Comparable<*>? {
val o = element.`object` as? DeclarationLookupObject
val fqName = o?.importableFqName ?: return null
return when (classifier.classify(fqName, o is PackageLookupObject)) {
ImportableFqNameClassifier.Classification.fromCurrentPackage -> Weight.currentPackage
ImportableFqNameClassifier.Classification.defaultImport -> Weight.defaultImport
ImportableFqNameClassifier.Classification.preciseImport -> Weight.preciseImport
ImportableFqNameClassifier.Classification.allUnderImport -> Weight.allUnderImport
else -> null
}
}
}
// analog of LookupElementProximityWeigher which does not work for us
object KotlinLookupElementProximityWeigher : CompletionWeigher() {
override fun weigh(element: LookupElement, location: CompletionLocation): Comparable<Nothing>? {
val psiElement = (element.`object` as? DeclarationLookupObject)?.psiElement ?: return null
return PsiProximityComparator.getProximity({ psiElement }, location.completionParameters.position, location.processingContext)
}
}
object SmartCompletionPriorityWeigher : LookupElementWeigher("kotlin.smartCompletionPriority") {
override fun weigh(element: LookupElement, context: WeighingContext) =
element.getUserData(SMART_COMPLETION_ITEM_PRIORITY_KEY) ?: SmartCompletionItemPriority.DEFAULT
}
object KindWeigher : LookupElementWeigher("kotlin.kind") {
private enum class Weight {
probableKeyword,
enumMember,
callable,
keyword,
default,
/**
* This does not mean that the keyword cannot be used at all; it just means that
* it is highly unlikely that it will be used.
*/
notProbableKeyword,
packages
}
override fun weigh(element: LookupElement): Comparable<*> {
val o = element.`object`
return when (o) {
is PackageLookupObject -> Weight.packages
is DeclarationLookupObject -> {
val descriptor = o.descriptor
when (descriptor) {
is VariableDescriptor, is FunctionDescriptor -> Weight.callable
is ClassDescriptor -> if (descriptor.kind == ClassKind.ENUM_ENTRY) Weight.enumMember else Weight.default
else -> Weight.default
}
}
is KeywordLookupObject -> when (element.keywordProbability) {
KeywordProbability.HIGH -> Weight.probableKeyword
KeywordProbability.DEFAULT -> Weight.keyword
KeywordProbability.LOW -> Weight.notProbableKeyword
}
else -> Weight.default
}
}
}
object CallableWeigher : LookupElementWeigher("kotlin.callableWeight") {
private enum class Weight1 {
local,
memberOrExtension,
globalOrStatic,
typeParameterExtension,
receiverCastRequired
}
private enum class Weight2 {
thisClassMember,
baseClassMember,
thisTypeExtension,
baseTypeExtension,
other
}
private data class CompoundWeight(val weight1: Weight1, val receiverIndex: Int, val weight2: Weight2) : Comparable<CompoundWeight> {
override fun compareTo(other: CompoundWeight): Int {
if (weight1 != other.weight1) return weight1.compareTo(other.weight1)
if (receiverIndex != other.receiverIndex) return receiverIndex.compareTo(other.receiverIndex)
return weight2.compareTo(other.weight2)
}
}
override fun weigh(element: LookupElement): Comparable<*>? {
val weight = element.getUserData(CALLABLE_WEIGHT_KEY) ?: return null
val w1 = when (weight.enum) {
CallableWeightEnum.local -> Weight1.local
CallableWeightEnum.thisClassMember,
CallableWeightEnum.baseClassMember,
CallableWeightEnum.thisTypeExtension,
CallableWeightEnum.baseTypeExtension -> Weight1.memberOrExtension
CallableWeightEnum.globalOrStatic -> Weight1.globalOrStatic
CallableWeightEnum.typeParameterExtension -> Weight1.typeParameterExtension
CallableWeightEnum.receiverCastRequired -> Weight1.receiverCastRequired
}
val w2 = when (weight.enum) {
CallableWeightEnum.thisClassMember -> Weight2.thisClassMember
CallableWeightEnum.baseClassMember -> Weight2.baseClassMember
CallableWeightEnum.thisTypeExtension -> Weight2.thisTypeExtension
CallableWeightEnum.baseTypeExtension -> Weight2.baseTypeExtension
else -> Weight2.other
}
return CompoundWeight(w1, weight.receiverIndex ?: Int.MAX_VALUE, w2)
}
}
object VariableOrFunctionWeigher : LookupElementWeigher("kotlin.variableOrFunction") {
private enum class Weight {
variable,
function
}
override fun weigh(element: LookupElement): Comparable<*>? {
val descriptor = (element.`object` as? DeclarationLookupObject)?.descriptor ?: return null
return when (descriptor) {
is VariableDescriptor -> Weight.variable
is FunctionDescriptor -> Weight.function
else -> null
}
}
}
/**
* Decreases priority of properties when prefix starts with "get" or "set" (and the property name does not)
*/
object PreferGetSetMethodsToPropertyWeigher : LookupElementWeigher("kotlin.preferGetSetMethodsToProperty", false, true) {
override fun weigh(element: LookupElement, context: WeighingContext): Int {
val property = (element.`object` as? DeclarationLookupObject)?.descriptor as? PropertyDescriptor ?: return 0
val prefixMatcher = context.itemMatcher(element)
if (prefixMatcher.prefixMatches(property.name.asString())) return 0
val matchedLookupStrings = element.allLookupStrings.filter { prefixMatcher.prefixMatches(it) }
return if (matchedLookupStrings.all { it.startsWith("get") || it.startsWith("set") }) 1 else 0
}
}
object DeprecatedWeigher : LookupElementWeigher("kotlin.deprecated") {
override fun weigh(element: LookupElement): Int {
val o = element.`object` as? DeclarationLookupObject ?: return 0
return if (o.isDeprecated) 1 else 0
}
}
/**
* This weigher is designed to "sink down" specific elements in completion.
*
* For now it only works on "Flow.collect" member method (see [https://youtrack.jetbrains.com/issue/KT-36808] for details).
*/
object KotlinUnwantedLookupElementWeigher : LookupElementWeigher("kotlin.unwantedElement") {
private val flowCollectFqName = FqName("kotlinx.coroutines.flow.Flow.collect")
override fun weigh(element: LookupElement): Int {
val descriptor = (element.`object` as? DeclarationLookupObject)?.descriptor ?: return 0
return if (descriptor.fqNameSafe == flowCollectFqName) 1 else 0
}
}
object PreferMatchingItemWeigher : LookupElementWeigher("kotlin.preferMatching", false, true) {
private enum class Weight {
keywordExactMatch,
defaultExactMatch,
functionExactMatch,
notImportedExactMatch,
specialExactMatch,
notExactMatch
}
override fun weigh(element: LookupElement, context: WeighingContext): Comparable<*> {
val prefix = context.itemPattern(element)
if (element.lookupString != prefix) {
return Weight.notExactMatch
} else {
val o = element.`object`
return when (o) {
is KeywordLookupObject -> Weight.keywordExactMatch
is DeclarationLookupObject -> {
val smartCompletionPriority = element.getUserData(SMART_COMPLETION_ITEM_PRIORITY_KEY)
when {
smartCompletionPriority != null && smartCompletionPriority != SmartCompletionItemPriority.DEFAULT -> Weight.specialExactMatch
element.getUserData(NOT_IMPORTED_KEY) != null -> Weight.notImportedExactMatch
o.descriptor is FunctionDescriptor -> Weight.functionExactMatch
else -> Weight.defaultExactMatch
}
}
else -> Weight.defaultExactMatch
}
}
}
}
class SmartCompletionInBasicWeigher(
private val smartCompletion: SmartCompletion,
private val callTypeAndReceiver: CallTypeAndReceiver<*, *>,
private val resolutionFacade: ResolutionFacade,
private val bindingContext: BindingContext
) : LookupElementWeigher("kotlin.smartInBasic", true, false) {
companion object {
val KEYWORD_VALUE_MATCHED_KEY = Key<Unit>("SmartCompletionInBasicWeigher.KEYWORD_VALUE_MATCHED_KEY")
val NAMED_ARGUMENT_KEY = Key<Unit>("SmartCompletionInBasicWeigher.NAMED_ARGUMENT_KEY")
}
private val descriptorsToSkip = smartCompletion.descriptorsToSkip
private val expectedInfos = smartCompletion.expectedInfos
private val PRIORITY_COUNT = SmartCompletionItemPriority.values().size
private fun itemWeight(priority: SmartCompletionItemPriority, nameSimilarity: Int) =
(nameSimilarity.toLong() shl 32) + PRIORITY_COUNT - priority.ordinal
private val NAMED_ARGUMENT_WEIGHT = 1L
private val NO_MATCH_WEIGHT = 0L
private val DESCRIPTOR_TO_SKIP_WEIGHT = -1L // if descriptor is skipped from smart completion then it's probably irrelevant
override fun weigh(element: LookupElement): Long {
if (element.getUserData(NAMED_ARGUMENT_KEY) != null) {
return NAMED_ARGUMENT_WEIGHT
}
val priority = element.getUserData(SMART_COMPLETION_ITEM_PRIORITY_KEY)
if (priority != null) { // it's an "additional item" came from smart completion, don't match it against expected type
return itemWeight(priority, element.getUserData(NAME_SIMILARITY_KEY) ?: 0)
}
val o = element.`object`
if ((o as? DeclarationLookupObject)?.descriptor in descriptorsToSkip) return DESCRIPTOR_TO_SKIP_WEIGHT
if (expectedInfos.isEmpty()) return NO_MATCH_WEIGHT
val smartCastCalculator = smartCompletion.smartCastCalculator
val (fuzzyTypes, name) = when (o) {
is DeclarationLookupObject -> {
val descriptor = o.descriptor ?: return NO_MATCH_WEIGHT
descriptor.fuzzyTypesForSmartCompletion(
smartCastCalculator,
callTypeAndReceiver,
resolutionFacade,
bindingContext
) to descriptor.name
}
is ThisItemLookupObject -> smartCastCalculator.types(o.receiverParameter).map { it.toFuzzyType(emptyList()) } to null
else -> return NO_MATCH_WEIGHT
}
if (fuzzyTypes.isEmpty()) return NO_MATCH_WEIGHT
val matched: Collection<Pair<ExpectedInfo, ExpectedInfoMatch>> = expectedInfos.map { it to fuzzyTypes.matchExpectedInfo(it) }
if (matched.all { it.second == ExpectedInfoMatch.noMatch }) return NO_MATCH_WEIGHT
val nameSimilarity = if (name != null) {
val matchingInfos = matched.filter { it.second != ExpectedInfoMatch.noMatch }.map { it.first }
calcNameSimilarity(name.asString(), matchingInfos)
} else {
0
}
return if (matched.any { it.second.isMatch() })
itemWeight(SmartCompletionItemPriority.DEFAULT, nameSimilarity)
else
itemWeight(SmartCompletionItemPriority.NULLABLE, nameSimilarity)
}
}
class PreferContextElementsWeigher(context: DeclarationDescriptor) : LookupElementWeigher("kotlin.preferContextElements", true, false) {
private val contextElements = context.parentsWithSelf
.takeWhile { it !is PackageFragmentDescriptor }
.toList()
.flatMap { if (it is CallableDescriptor) it.findOriginalTopMostOverriddenDescriptors() else listOf(it) }
.toSet()
private val contextElementNames = contextElements.map { it.name }.toSet()
override fun weigh(element: LookupElement): Boolean {
val lookupObject = element.`object` as? DeclarationLookupObject ?: return false
val descriptor = lookupObject.descriptor ?: return false
return descriptor.isContextElement()
}
private fun DeclarationDescriptor.isContextElement(): Boolean {
if (name !in contextElementNames) return false // optimization
if (this is CallableMemberDescriptor) {
val overridden = this.overriddenDescriptors
if (overridden.isNotEmpty()) {
return overridden.any { it.isContextElement() }
}
}
return original in contextElements
}
}
object ByNameAlphabeticalWeigher : LookupElementWeigher("kotlin.byNameAlphabetical") {
override fun weigh(element: LookupElement): String? {
val lookupObject = element.`object` as? DeclarationLookupObject ?: return null
return lookupObject.name?.asString()
}
}
object PreferLessParametersWeigher : LookupElementWeigher("kotlin.preferLessParameters") {
override fun weigh(element: LookupElement): Int? {
val lookupObject = element.`object` as? DeclarationLookupObject ?: return null
val function = lookupObject.descriptor as? FunctionDescriptor ?: return null
return function.valueParameters.size
}
}
class CallableReferenceWeigher(private val callType: CallType<*>) : LookupElementWeigher("kotlin.callableReference") {
override fun weigh(element: LookupElement): Int? {
if (callType == CallType.CALLABLE_REFERENCE || element.getUserData(SMART_COMPLETION_ITEM_PRIORITY_KEY) == SmartCompletionItemPriority.CALLABLE_REFERENCE) {
val descriptor = (element.`object` as? DeclarationLookupObject)?.descriptor as? CallableDescriptor
return if (descriptor?.returnType?.isNothing() == true) 1 else 0
}
return null
}
}
| apache-2.0 | 6899f453f9261517ef7f0d124e718b9b | 41.640777 | 163 | 0.69786 | 5.129343 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/perf/util/ESUploader.kt | 1 | 2194 | // 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.perf.util
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import org.jetbrains.kotlin.idea.performance.tests.utils.logMessage
object ESUploader {
var host: String? = null
var username: String? = null
var password: String? = null
var indexName = "kotlin_ide_benchmarks"
private val JSON: MediaType = "application/json; charset=utf-8".toMediaType()
private val client = OkHttpClient()
init {
host = System.getenv("ES_HOSTNAME") ?: System.getenv("es.hostname")
username = System.getenv("ES_USERNAME") ?: System.getenv("es.username")
password = System.getenv("ES_PASSWORD") ?: System.getenv("es.password")
logMessage { "initialized es details $username @ $host" }
}
fun upload(benchmark: Benchmark) {
if (host == null) {
logMessage { "ES host is not specified, ${benchmark.id()} would not be uploaded" }
return
}
val url = "$host/$indexName/_doc/${benchmark.id()}"
val auth = if (username != null && password != null) {
Credentials.basic(username!!, password!!);
} else {
null
}
val json = kotlinJsonMapper.writeValueAsString(benchmark)
val body: RequestBody = json.toRequestBody(JSON)
val request: Request = Request.Builder()
.url(url)
.post(body)
.header("Content-Type", "application/json")
.also { builder ->
auth?.let {
builder.header("Authorization", it)
}
}
.build()
client.newCall(request).execute().use { response ->
val code = response.code
val string = response.body?.string()
logMessage { "$code -> $string" }
if (code != 200 && code != 201) {
throw IllegalStateException("Error code $code -> $string")
}
}
}
} | apache-2.0 | 4e0d53e89c80ea79857dcfa5ad0b6b37 | 34.983607 | 158 | 0.593437 | 4.477551 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/grid/LazyGridState.kt | 3 | 18079 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.lazy.grid
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.MutatePriority
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.ScrollScope
import androidx.compose.foundation.gestures.ScrollableState
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.lazy.AwaitFirstLayoutModifier
import androidx.compose.foundation.lazy.layout.LazyLayoutPrefetchState
import androidx.compose.foundation.lazy.layout.animateScrollToItem
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.collection.mutableVectorOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.layout.Remeasurement
import androidx.compose.ui.layout.RemeasurementModifier
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.util.fastForEach
import kotlin.math.abs
/**
* Creates a [LazyGridState] that is remembered across compositions.
*
* Changes to the provided initial values will **not** result in the state being recreated or
* changed in any way if it has already been created.
*
* @param initialFirstVisibleItemIndex the initial value for [LazyGridState.firstVisibleItemIndex]
* @param initialFirstVisibleItemScrollOffset the initial value for
* [LazyGridState.firstVisibleItemScrollOffset]
*/
@Composable
fun rememberLazyGridState(
initialFirstVisibleItemIndex: Int = 0,
initialFirstVisibleItemScrollOffset: Int = 0
): LazyGridState {
return rememberSaveable(saver = LazyGridState.Saver) {
LazyGridState(
initialFirstVisibleItemIndex,
initialFirstVisibleItemScrollOffset
)
}
}
/**
* A state object that can be hoisted to control and observe scrolling.
*
* In most cases, this will be created via [rememberLazyGridState].
*
* @param firstVisibleItemIndex the initial value for [LazyGridState.firstVisibleItemIndex]
* @param firstVisibleItemScrollOffset the initial value for
* [LazyGridState.firstVisibleItemScrollOffset]
*/
@OptIn(ExperimentalFoundationApi::class)
@Stable
class LazyGridState constructor(
firstVisibleItemIndex: Int = 0,
firstVisibleItemScrollOffset: Int = 0
) : ScrollableState {
/**
* The holder class for the current scroll position.
*/
private val scrollPosition =
LazyGridScrollPosition(firstVisibleItemIndex, firstVisibleItemScrollOffset)
/**
* The index of the first item that is visible.
*
* Note that this property is observable and if you use it in the composable function it will
* be recomposed on every change causing potential performance issues.
*
* If you want to run some side effects like sending an analytics event or updating a state
* based on this value consider using "snapshotFlow":
* @sample androidx.compose.foundation.samples.UsingGridScrollPositionForSideEffectSample
*
* If you need to use it in the composition then consider wrapping the calculation into a
* derived state in order to only have recompositions when the derived value changes:
* @sample androidx.compose.foundation.samples.UsingGridScrollPositionInCompositionSample
*/
val firstVisibleItemIndex: Int get() = scrollPosition.index.value
/**
* The scroll offset of the first visible item. Scrolling forward is positive - i.e., the
* amount that the item is offset backwards
*/
val firstVisibleItemScrollOffset: Int get() = scrollPosition.scrollOffset
/** Backing state for [layoutInfo] */
private val layoutInfoState = mutableStateOf<LazyGridLayoutInfo>(EmptyLazyGridLayoutInfo)
/**
* The object of [LazyGridLayoutInfo] calculated during the last layout pass. For example,
* you can use it to calculate what items are currently visible.
*
* Note that this property is observable and is updated after every scroll or remeasure.
* If you use it in the composable function it will be recomposed on every change causing
* potential performance issues including infinity recomposition loop.
* Therefore, avoid using it in the composition.
*
* If you want to run some side effects like sending an analytics event or updating a state
* based on this value consider using "snapshotFlow":
* @sample androidx.compose.foundation.samples.UsingGridLayoutInfoForSideEffectSample
*/
val layoutInfo: LazyGridLayoutInfo get() = layoutInfoState.value
/**
* [InteractionSource] that will be used to dispatch drag events when this
* grid is being dragged. If you want to know whether the fling (or animated scroll) is in
* progress, use [isScrollInProgress].
*/
val interactionSource: InteractionSource get() = internalInteractionSource
internal val internalInteractionSource: MutableInteractionSource = MutableInteractionSource()
/**
* The amount of scroll to be consumed in the next layout pass. Scrolling forward is negative
* - that is, it is the amount that the items are offset in y
*/
internal var scrollToBeConsumed = 0f
private set
/**
* Needed for [animateScrollToItem]. Updated on every measure.
*/
internal var slotsPerLine: Int by mutableStateOf(0)
/**
* Needed for [animateScrollToItem]. Updated on every measure.
*/
internal var density: Density by mutableStateOf(Density(1f, 1f))
/**
* Needed for [notifyPrefetch].
*/
internal var isVertical: Boolean by mutableStateOf(true)
/**
* The ScrollableController instance. We keep it as we need to call stopAnimation on it once
* we reached the end of the grid.
*/
private val scrollableState = ScrollableState { -onScroll(-it) }
/**
* Only used for testing to confirm that we're not making too many measure passes
*/
/*@VisibleForTesting*/
internal var numMeasurePasses: Int = 0
private set
/**
* Only used for testing to disable prefetching when needed to test the main logic.
*/
/*@VisibleForTesting*/
internal var prefetchingEnabled: Boolean = true
/**
* The index scheduled to be prefetched (or the last prefetched index if the prefetch is done).
*/
private var lineToPrefetch = -1
/**
* The list of handles associated with the items from the [lineToPrefetch] line.
*/
private val currentLinePrefetchHandles =
mutableVectorOf<LazyLayoutPrefetchState.PrefetchHandle>()
/**
* Keeps the scrolling direction during the previous calculation in order to be able to
* detect the scrolling direction change.
*/
private var wasScrollingForward = false
/**
* The [Remeasurement] object associated with our layout. It allows us to remeasure
* synchronously during scroll.
*/
private var remeasurement: Remeasurement? by mutableStateOf(null)
/**
* The modifier which provides [remeasurement].
*/
internal val remeasurementModifier = object : RemeasurementModifier {
override fun onRemeasurementAvailable(remeasurement: Remeasurement) {
[email protected] = remeasurement
}
}
/**
* Provides a modifier which allows to delay some interactions (e.g. scroll)
* until layout is ready.
*/
internal val awaitLayoutModifier = AwaitFirstLayoutModifier()
/**
* Finds items on a line and their measurement constraints. Used for prefetching.
*/
internal var prefetchInfoRetriever: (line: LineIndex) -> List<Pair<Int, Constraints>> by
mutableStateOf({ emptyList() })
internal var placementAnimator by mutableStateOf<LazyGridItemPlacementAnimator?>(null)
private val animateScrollScope = LazyGridAnimateScrollScope(this)
/**
* Instantly brings the item at [index] to the top of the viewport, offset by [scrollOffset]
* pixels.
*
* @param index the index to which to scroll. Must be non-negative.
* @param scrollOffset the offset that the item should end up after the scroll. Note that
* positive offset refers to forward scroll, so in a top-to-bottom list, positive offset will
* scroll the item further upward (taking it partly offscreen).
*/
suspend fun scrollToItem(
/*@IntRange(from = 0)*/
index: Int,
scrollOffset: Int = 0
) {
scroll {
snapToItemIndexInternal(index, scrollOffset)
}
}
internal fun snapToItemIndexInternal(index: Int, scrollOffset: Int) {
scrollPosition.requestPosition(ItemIndex(index), scrollOffset)
// placement animation is not needed because we snap into a new position.
placementAnimator?.reset()
remeasurement?.forceRemeasure()
}
/**
* Call this function to take control of scrolling and gain the ability to send scroll events
* via [ScrollScope.scrollBy]. All actions that change the logical scroll position must be
* performed within a [scroll] block (even if they don't call any other methods on this
* object) in order to guarantee that mutual exclusion is enforced.
*
* If [scroll] is called from elsewhere, this will be canceled.
*/
override suspend fun scroll(
scrollPriority: MutatePriority,
block: suspend ScrollScope.() -> Unit
) {
awaitLayoutModifier.waitForFirstLayout()
scrollableState.scroll(scrollPriority, block)
}
override fun dispatchRawDelta(delta: Float): Float =
scrollableState.dispatchRawDelta(delta)
override val isScrollInProgress: Boolean
get() = scrollableState.isScrollInProgress
override var canScrollForward: Boolean by mutableStateOf(false)
private set
override var canScrollBackward: Boolean by mutableStateOf(false)
private set
// TODO: Coroutine scrolling APIs will allow this to be private again once we have more
// fine-grained control over scrolling
/*@VisibleForTesting*/
internal fun onScroll(distance: Float): Float {
if (distance < 0 && !canScrollForward || distance > 0 && !canScrollBackward) {
return 0f
}
check(abs(scrollToBeConsumed) <= 0.5f) {
"entered drag with non-zero pending scroll: $scrollToBeConsumed"
}
scrollToBeConsumed += distance
// scrollToBeConsumed will be consumed synchronously during the forceRemeasure invocation
// inside measuring we do scrollToBeConsumed.roundToInt() so there will be no scroll if
// we have less than 0.5 pixels
if (abs(scrollToBeConsumed) > 0.5f) {
val preScrollToBeConsumed = scrollToBeConsumed
remeasurement?.forceRemeasure()
if (prefetchingEnabled) {
notifyPrefetch(preScrollToBeConsumed - scrollToBeConsumed)
}
}
// here scrollToBeConsumed is already consumed during the forceRemeasure invocation
if (abs(scrollToBeConsumed) <= 0.5f) {
// We consumed all of it - we'll hold onto the fractional scroll for later, so report
// that we consumed the whole thing
return distance
} else {
val scrollConsumed = distance - scrollToBeConsumed
// We did not consume all of it - return the rest to be consumed elsewhere (e.g.,
// nested scrolling)
scrollToBeConsumed = 0f // We're not consuming the rest, give it back
return scrollConsumed
}
}
private fun notifyPrefetch(delta: Float) {
val prefetchState = prefetchState
if (!prefetchingEnabled) {
return
}
val info = layoutInfo
if (info.visibleItemsInfo.isNotEmpty()) {
val scrollingForward = delta < 0
val lineToPrefetch: Int
val closestNextItemToPrefetch: Int
if (scrollingForward) {
lineToPrefetch = 1 + info.visibleItemsInfo.last().let {
if (isVertical) it.row else it.column
}
closestNextItemToPrefetch = info.visibleItemsInfo.last().index + 1
} else {
lineToPrefetch = -1 + info.visibleItemsInfo.first().let {
if (isVertical) it.row else it.column
}
closestNextItemToPrefetch = info.visibleItemsInfo.first().index - 1
}
if (lineToPrefetch != this.lineToPrefetch &&
closestNextItemToPrefetch in 0 until info.totalItemsCount
) {
if (wasScrollingForward != scrollingForward) {
// the scrolling direction has been changed which means the last prefetched
// is not going to be reached anytime soon so it is safer to dispose it.
// if this line is already visible it is safe to call the method anyway
// as it will be no-op
currentLinePrefetchHandles.forEach { it.cancel() }
}
this.wasScrollingForward = scrollingForward
this.lineToPrefetch = lineToPrefetch
currentLinePrefetchHandles.clear()
prefetchInfoRetriever(LineIndex(lineToPrefetch)).fastForEach {
currentLinePrefetchHandles.add(
prefetchState.schedulePrefetch(it.first, it.second)
)
}
}
}
}
private fun cancelPrefetchIfVisibleItemsChanged(info: LazyGridLayoutInfo) {
if (lineToPrefetch != -1 && info.visibleItemsInfo.isNotEmpty()) {
val expectedLineToPrefetch = if (wasScrollingForward) {
info.visibleItemsInfo.last().let {
if (isVertical) it.row else it.column
} + 1
} else {
info.visibleItemsInfo.first().let {
if (isVertical) it.row else it.column
} - 1
}
if (lineToPrefetch != expectedLineToPrefetch) {
lineToPrefetch = -1
currentLinePrefetchHandles.forEach { it.cancel() }
currentLinePrefetchHandles.clear()
}
}
}
internal val prefetchState = LazyLayoutPrefetchState()
/**
* Animate (smooth scroll) to the given item.
*
* @param index the index to which to scroll. Must be non-negative.
* @param scrollOffset the offset that the item should end up after the scroll. Note that
* positive offset refers to forward scroll, so in a top-to-bottom list, positive offset will
* scroll the item further upward (taking it partly offscreen).
*/
suspend fun animateScrollToItem(
/*@IntRange(from = 0)*/
index: Int,
scrollOffset: Int = 0
) {
animateScrollScope.animateScrollToItem(index, scrollOffset)
}
/**
* Updates the state with the new calculated scroll position and consumed scroll.
*/
internal fun applyMeasureResult(result: LazyGridMeasureResult) {
scrollPosition.updateFromMeasureResult(result)
scrollToBeConsumed -= result.consumedScroll
layoutInfoState.value = result
canScrollForward = result.canScrollForward
canScrollBackward = (result.firstVisibleLine?.index?.value ?: 0) != 0 ||
result.firstVisibleLineScrollOffset != 0
numMeasurePasses++
cancelPrefetchIfVisibleItemsChanged(result)
}
/**
* When the user provided custom keys for the items we can try to detect when there were
* items added or removed before our current first visible item and keep this item
* as the first visible one even given that its index has been changed.
*/
internal fun updateScrollPositionIfTheFirstItemWasMoved(itemProvider: LazyGridItemProvider) {
scrollPosition.updateScrollPositionIfTheFirstItemWasMoved(itemProvider)
}
companion object {
/**
* The default [Saver] implementation for [LazyGridState].
*/
val Saver: Saver<LazyGridState, *> = listSaver(
save = { listOf(it.firstVisibleItemIndex, it.firstVisibleItemScrollOffset) },
restore = {
LazyGridState(
firstVisibleItemIndex = it[0],
firstVisibleItemScrollOffset = it[1]
)
}
)
}
}
@OptIn(ExperimentalFoundationApi::class)
private object EmptyLazyGridLayoutInfo : LazyGridLayoutInfo {
override val visibleItemsInfo = emptyList<LazyGridItemInfo>()
override val viewportStartOffset = 0
override val viewportEndOffset = 0
override val totalItemsCount = 0
override val viewportSize = IntSize.Zero
override val orientation = Orientation.Vertical
override val reverseLayout = false
override val beforeContentPadding: Int = 0
override val afterContentPadding: Int = 0
}
| apache-2.0 | a158812f9cb2289ced1c97a4c0516497 | 39.086475 | 99 | 0.684385 | 5.143385 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/mediapreview/VideoControlsDelegate.kt | 1 | 2085 | package org.thoughtcrime.securesms.mediapreview
import android.net.Uri
import org.thoughtcrime.securesms.video.VideoPlayer
/**
* Class to manage video playback in preview screen.
*/
class VideoControlsDelegate {
private val playWhenReady: MutableMap<Uri, Boolean> = mutableMapOf()
private var player: Player? = null
private var isMuted: Boolean = true
fun getPlayerState(uri: Uri): PlayerState? {
val player: Player? = this.player
return if (player?.uri == uri && player.videoPlayer != null) {
PlayerState(uri, player.videoPlayer.playbackPosition, player.videoPlayer.duration, player.isGif, player.loopCount)
} else {
null
}
}
fun pause() = player?.videoPlayer?.pause()
fun resume(uri: Uri) {
if (player?.uri == uri) {
player?.videoPlayer?.play()
} else {
playWhenReady[uri] = true
}
}
fun restart() {
player?.videoPlayer?.playbackPosition = 0L
}
fun onPlayerPositionDiscontinuity(reason: Int) {
val player = this.player
if (player != null && player.isGif) {
this.player = player.copy(loopCount = if (reason == 0) player.loopCount + 1 else 0)
}
}
fun mute() {
isMuted = true
player?.videoPlayer?.mute()
}
fun unmute() {
isMuted = false
player?.videoPlayer?.unmute()
}
fun hasAudioStream(): Boolean {
return player?.videoPlayer?.hasAudioTrack() ?: false
}
fun attachPlayer(uri: Uri, videoPlayer: VideoPlayer?, isGif: Boolean) {
player = Player(uri, videoPlayer, isGif)
if (isMuted) {
videoPlayer?.mute()
} else {
videoPlayer?.unmute()
}
if (playWhenReady[uri] == true) {
playWhenReady[uri] = false
videoPlayer?.play()
}
}
fun detachPlayer() {
player = Player()
}
private data class Player(
val uri: Uri = Uri.EMPTY,
val videoPlayer: VideoPlayer? = null,
val isGif: Boolean = false,
val loopCount: Int = 0
)
data class PlayerState(
val mediaUri: Uri,
val position: Long,
val duration: Long,
val isGif: Boolean,
val loopCount: Int
)
}
| gpl-3.0 | f445b4db242e8d47c8a15e21eaaa87ea | 21.663043 | 120 | 0.644125 | 3.91182 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureConflictSearcher.kt | 2 | 20934 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.changeSignature
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.changeSignature.*
import com.intellij.refactoring.util.CommonRefactoringUtil
import com.intellij.refactoring.util.RefactoringUIUtil
import com.intellij.usageView.UsageInfo
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeInContext
import org.jetbrains.kotlin.idea.caches.resolve.*
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.*
import org.jetbrains.kotlin.idea.refactoring.createTempCopy
import org.jetbrains.kotlin.idea.refactoring.getBodyScope
import org.jetbrains.kotlin.idea.refactoring.getContainingScope
import org.jetbrains.kotlin.idea.refactoring.rename.noReceivers
import org.jetbrains.kotlin.idea.util.*
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.kdoc.psi.impl.KDocName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.calls.util.getImplicitReceivers
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.classId
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.source.getPsi
class KotlinChangeSignatureConflictSearcher(
private val originalInfo: ChangeInfo,
private val refUsages: Ref<Array<UsageInfo>>
) {
private lateinit var changeInfo: KotlinChangeInfo
private val result = MultiMap<PsiElement, String>()
fun findConflicts(): MultiMap<PsiElement, String> {
// Delete OverriderUsageInfo and CallerUsageInfo for Kotlin declarations since they can't be processed correctly
// TODO (OverriderUsageInfo only): Drop when OverriderUsageInfo.getElement() gets deleted
val usageInfos = refUsages.get()
val adjustedUsages = usageInfos.filterNot { getOverriderOrCaller(it.unwrapped) is KtLightMethod }
if (adjustedUsages.size < usageInfos.size) {
refUsages.set(adjustedUsages.toTypedArray())
}
changeInfo = originalInfo.asKotlinChangeInfo ?: return result
doFindConflicts()
return result
}
private fun doFindConflicts() {
val parameterNames = hashSetOf<String>()
val function = changeInfo.method
val bindingContext = (function as KtElement).analyze(BodyResolveMode.FULL)
// to avoid KT-35903
val descriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, function] ?: changeInfo.originalBaseFunctionDescriptor
val containingDeclaration = descriptor.containingDeclaration
val parametersScope = when {
descriptor is ConstructorDescriptor && containingDeclaration is ClassDescriptorWithResolutionScopes -> {
val classDescriptor = containingDeclaration.classId?.let {
function.findModuleDescriptor().findClassAcrossModuleDependencies(it) as? ClassDescriptorWithResolutionScopes
} ?: containingDeclaration
classDescriptor.scopeForInitializerResolution
}
function is KtFunction -> function.getBodyScope(bindingContext)
else -> null
}
val callableScope = descriptor.getContainingScope()
val kind = changeInfo.kind
if (!kind.isConstructor && callableScope != null && changeInfo.newName.isNotEmpty()) {
val newName = Name.identifier(changeInfo.newName)
val conflicts = if (descriptor is FunctionDescriptor)
callableScope.getAllAccessibleFunctions(newName)
else
callableScope.getAllAccessibleVariables(newName)
val newTypes = changeInfo.newParameters.map { it.currentTypeInfo.type }
for (conflict in conflicts) {
if (conflict === descriptor) continue
val conflictElement = DescriptorToSourceUtils.descriptorToDeclaration(conflict)
if (conflictElement === changeInfo.method) continue
val candidateTypes = listOfNotNull(conflict.extensionReceiverParameter?.type) + conflict.valueParameters.map { it.type }
if (candidateTypes == newTypes) {
result.putValue(
conflictElement,
KotlinBundle.message(
"text.function.already.exists",
DescriptorRenderer.SHORT_NAMES_IN_TYPES.render(conflict)
)
)
break
}
}
}
val parametersToRemove = changeInfo.parametersToRemove
if (changeInfo.checkUsedParameters && function is KtCallableDeclaration) {
checkParametersToDelete(function, parametersToRemove)
}
for (parameter in changeInfo.getNonReceiverParameters()) {
val valOrVar = parameter.valOrVar
val parameterName = parameter.name
if (!parameterNames.add(parameterName)) {
result.putValue(function, KotlinBundle.message("text.duplicating.parameter", parameterName))
}
if (parametersScope != null) {
if (kind === KotlinMethodDescriptor.Kind.PRIMARY_CONSTRUCTOR && valOrVar !== KotlinValVar.None) {
for (property in parametersScope.getVariablesFromImplicitReceivers(Name.identifier(parameterName))) {
val propertyDeclaration = DescriptorToSourceUtils.descriptorToDeclaration(property) ?: continue
if (propertyDeclaration.parent !is KtParameterList) {
result.putValue(
propertyDeclaration,
KotlinBundle.message("text.duplicating.property", parameterName)
)
break
}
}
} else if (function is KtFunction) {
for (variable in parametersScope.getContributedVariables(Name.identifier(parameterName), NoLookupLocation.FROM_IDE)) {
if (variable is ValueParameterDescriptor) continue
val conflictElement = DescriptorToSourceUtils.descriptorToDeclaration(variable)
result.putValue(conflictElement, KotlinBundle.message("text.duplicating.local.variable", parameterName))
}
}
}
}
val newReceiverInfo = changeInfo.receiverParameterInfo
val originalReceiverInfo = changeInfo.methodDescriptor.receiver
if (function is KtCallableDeclaration && newReceiverInfo != originalReceiverInfo) {
findReceiverIntroducingConflicts(function, newReceiverInfo)
findInternalExplicitReceiverConflicts(function, refUsages.get(), originalReceiverInfo)
findReceiverToParameterInSafeCallsConflicts(refUsages.get())
findThisLabelConflicts(refUsages, function)
}
fun processUsageInfo(usageInfo: UsageInfo) {
if (usageInfo is KotlinCallerUsage) {
val namedDeclaration = usageInfo.element
val callerDescriptor = namedDeclaration?.resolveToDescriptorIfAny() ?: return
findParameterDuplicationInCaller(namedDeclaration, callerDescriptor)
}
}
val usageInfos = refUsages.get()
for (usageInfo in usageInfos) {
when (usageInfo) {
is KotlinWrapperForPropertyInheritorsUsage -> processUsageInfo(usageInfo.originalUsageInfo)
is KotlinWrapperForJavaUsageInfos -> findConflictsInJavaUsages(usageInfo)
is KotlinCallableDefinitionUsage<*> -> {
val declaration = usageInfo.declaration as? KtCallableDeclaration ?: continue
if (changeInfo.checkUsedParameters) {
checkParametersToDelete(declaration, parametersToRemove)
}
}
else -> processUsageInfo(usageInfo)
}
}
}
private fun getOverriderOrCaller(usage: UsageInfo): PsiMethod? {
if (usage is OverriderUsageInfo) return usage.overridingMethod
if (usage is CallerUsageInfo) {
val element = usage.element
return if (element is PsiMethod) element else null
}
return null
}
private fun checkParametersToDelete(
callableDeclaration: KtCallableDeclaration,
toRemove: BooleanArray,
) {
val scope = LocalSearchScope(callableDeclaration)
val valueParameters = callableDeclaration.valueParameters
val hasReceiver = valueParameters.size != toRemove.size
if (hasReceiver && toRemove[0]) {
findReceiverUsages(callableDeclaration)
}
for ((i, parameter) in valueParameters.withIndex()) {
val index = (if (hasReceiver) 1 else 0) + i
if (toRemove[index]) {
registerConflictIfUsed(parameter, scope)
}
}
}
private fun findReceiverIntroducingConflicts(
callable: PsiElement,
newReceiverInfo: KotlinParameterInfo?
) {
if (newReceiverInfo != null && (callable is KtNamedFunction) && callable.bodyExpression != null) {
val originalContext = callable.analyzeWithContent()
val noReceiverRefs = ArrayList<KtSimpleNameExpression>()
callable.forEachDescendantOfType<KtSimpleNameExpression> {
val resolvedCall = it.getResolvedCall(originalContext) ?: return@forEachDescendantOfType
if (resolvedCall.noReceivers()) {
noReceiverRefs += it
}
}
val psiFactory = KtPsiFactory(callable.project)
val tempFile = (callable.containingFile as KtFile).createTempCopy()
val functionWithReceiver = tempFile.findElementAt(callable.textOffset)?.getNonStrictParentOfType<KtNamedFunction>() ?: return
val receiverTypeRef = psiFactory.createType(newReceiverInfo.currentTypeInfo.getReceiverTypeText())
functionWithReceiver.setReceiverTypeReference(receiverTypeRef)
val newContext = functionWithReceiver.bodyExpression!!.analyze(BodyResolveMode.FULL)
val originalOffset = callable.bodyExpression!!.textOffset
val newBody = functionWithReceiver.bodyExpression ?: return
for (originalRef in noReceiverRefs) {
val newRef = newBody.findElementAt(originalRef.textOffset - originalOffset)
?.getNonStrictParentOfType<KtReferenceExpression>()
val newResolvedCall = newRef.getResolvedCall(newContext)
if (newResolvedCall == null || newResolvedCall.extensionReceiver != null || newResolvedCall.dispatchReceiver != null) {
val descriptor = originalRef.getResolvedCall(originalContext)!!.candidateDescriptor
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(callable.project, descriptor)
val prefix = if (declaration != null) RefactoringUIUtil.getDescription(declaration, true) else originalRef.text
result.putValue(
originalRef,
KotlinBundle.message("text.0.will.no.longer.be.accessible.after.signature.change", prefix.capitalize())
)
}
}
}
}
private fun findInternalExplicitReceiverConflicts(
function: KtCallableDeclaration,
usages: Array<UsageInfo>,
originalReceiverInfo: KotlinParameterInfo?
) {
if (originalReceiverInfo != null) return
val isObjectFunction = function.containingClassOrObject is KtObjectDeclaration
loop@ for (usageInfo in usages) {
if (!(usageInfo is KotlinFunctionCallUsage || usageInfo is KotlinPropertyCallUsage || usageInfo is KotlinByConventionCallUsage)) continue
val callElement = usageInfo.element as? KtElement ?: continue
val parent = callElement.parent
val elementToReport = when {
usageInfo is KotlinByConventionCallUsage -> callElement
parent is KtQualifiedExpression && parent.selectorExpression === callElement && !isObjectFunction -> parent
else -> continue@loop
}
val message = KotlinBundle.message(
"text.explicit.receiver.is.already.present.in.call.element.0",
CommonRefactoringUtil.htmlEmphasize(elementToReport.text)
)
result.putValue(callElement, message)
}
}
private fun findReceiverToParameterInSafeCallsConflicts(
usages: Array<UsageInfo>
) {
val originalReceiverInfo = changeInfo.methodDescriptor.receiver
if (originalReceiverInfo == null || originalReceiverInfo !in changeInfo.getNonReceiverParameters()) return
for (usageInfo in usages) {
if (!(usageInfo is KotlinFunctionCallUsage || usageInfo is KotlinPropertyCallUsage)) continue
val callElement = usageInfo.element as? KtElement ?: continue
val qualifiedExpression = callElement.getQualifiedExpressionForSelector()
if (qualifiedExpression is KtSafeQualifiedExpression) {
result.putValue(
callElement,
KotlinBundle.message(
"text.receiver.can.t.be.safely.transformed.to.value.argument",
CommonRefactoringUtil.htmlEmphasize(qualifiedExpression.text)
)
)
}
}
}
private fun findThisLabelConflicts(
refUsages: Ref<Array<UsageInfo>>,
callable: KtCallableDeclaration
) {
val psiFactory = KtPsiFactory(callable.project)
for (usageInfo in refUsages.get()) {
if (usageInfo !is KotlinParameterUsage) continue
val newExprText = usageInfo.getReplacementText(changeInfo)
if (!newExprText.startsWith("this")) continue
if (usageInfo.element is KDocName) continue // TODO support converting parameter to receiver in KDoc
val originalExpr = usageInfo.element as? KtExpression ?: continue
val bindingContext = originalExpr.analyze(BodyResolveMode.FULL)
val scope = originalExpr.getResolutionScope(bindingContext, originalExpr.getResolutionFacade())
val newExpr = psiFactory.createExpression(newExprText) as KtThisExpression
val newContext = newExpr.analyzeInContext(scope, originalExpr)
val labelExpr = newExpr.getTargetLabel()
if (labelExpr != null && newContext.get(BindingContext.AMBIGUOUS_LABEL_TARGET, labelExpr) != null) {
result.putValue(
originalExpr,
KotlinBundle.message(
"text.parameter.reference.can.t.be.safely.replaced.with.0.since.1.is.ambiguous.in.this.context",
newExprText,
labelExpr.text
)
)
continue
}
val thisTarget = newContext.get(BindingContext.REFERENCE_TARGET, newExpr.instanceReference)
val thisTargetPsi = (thisTarget as? DeclarationDescriptorWithSource)?.source?.getPsi()
if (thisTargetPsi != null && callable.isAncestor(thisTargetPsi, true)) {
result.putValue(
originalExpr,
KotlinBundle.message(
"text.parameter.reference.can.t.be.safely.replaced.with.0.since.target.function.can.t.be.referenced.in.this.context",
newExprText
)
)
}
}
}
private fun findParameterDuplicationInCaller(
caller: KtNamedDeclaration,
callerDescriptor: DeclarationDescriptor
) {
val valueParameters = caller.getValueParameters()
val existingParameters = valueParameters.associateBy { it.name }
val signature = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.render(callerDescriptor)
for (parameterInfo in changeInfo.getNonReceiverParameters()) {
if (!(parameterInfo.isNewParameter)) continue
val name = parameterInfo.name
val parameter = existingParameters[name] ?: continue
result.putValue(parameter, KotlinBundle.message("text.there.is.already.a.parameter", name, signature))
}
}
private fun findConflictsInJavaUsages(
wrapper: KotlinWrapperForJavaUsageInfos,
) {
val kotlinChangeInfo = wrapper.kotlinChangeInfo
val javaChangeInfo = wrapper.javaChangeInfo
val javaUsageInfos = wrapper.javaUsageInfos
val parametersToRemove = javaChangeInfo.toRemoveParm()
val hasDefaultValue = javaChangeInfo.newParameters.any { !it.defaultValue.isNullOrBlank() }
val hasDefaultParameter = kotlinChangeInfo.newParameters.any { it.defaultValueAsDefaultParameter }
for (javaUsage in javaUsageInfos) when (javaUsage) {
is OverriderUsageInfo -> {
if (!kotlinChangeInfo.checkUsedParameters) continue
val javaMethod = javaUsage.overridingMethod
val baseMethod = javaUsage.baseMethod
if (baseMethod != javaChangeInfo.method) continue
JavaChangeSignatureUsageProcessor.ConflictSearcher.checkParametersToDelete(javaMethod, parametersToRemove, result)
}
is MethodCallUsageInfo -> {
val conflictMessage = when {
hasDefaultValue -> KotlinBundle.message("change.signature.conflict.text.kotlin.default.value.in.non.kotlin.files")
hasDefaultParameter -> KotlinBundle.message("change.signature.conflict.text.kotlin.default.parameter.in.non.kotlin.files")
else -> continue
}
result.putValue(javaUsage.element, conflictMessage)
}
}
}
private fun findReceiverUsages(
callableDeclaration: KtCallableDeclaration,
) {
var hasUsage = false
callableDeclaration.accept(referenceExpressionRecursiveVisitor(fun(referenceExpression: KtReferenceExpression) {
if (hasUsage) return
val context = referenceExpression.analyze(BodyResolveMode.PARTIAL)
val target = referenceExpression.getResolvedCall(context) ?: return
val descriptorsToCheck = if (referenceExpression.parent is KtThisExpression)
listOfNotNull(target.resultingDescriptor as? ReceiverParameterDescriptor)
else
target.getImplicitReceivers().mapNotNull { it.getReceiverTargetDescriptor(context) }
for (descriptor in descriptorsToCheck) {
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(callableDeclaration.project, descriptor) ?: continue
if (declaration == callableDeclaration || declaration == callableDeclaration.receiverTypeReference) {
hasUsage = true
return
}
}
}))
if (hasUsage) {
result.putValue(
callableDeclaration.receiverTypeReference,
KotlinBundle.message("parameter.used.in.declaration.body.warning", KotlinBundle.message("text.receiver")),
)
}
}
private fun registerConflictIfUsed(
element: PsiNamedElement,
scope: LocalSearchScope
) {
if (ReferencesSearch.search(element, scope).findFirst() != null) {
result.putValue(element, KotlinBundle.message("parameter.used.in.declaration.body.warning", element.name.toString()))
}
}
} | apache-2.0 | 626178343eb595c5d3b2c605d0777b3f | 45.419069 | 158 | 0.65888 | 5.886952 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/search/ideaExtensions/KotlinDefinitionsSearcher.kt | 1 | 7564 | // 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.search.ideaExtensions
import com.intellij.openapi.application.ReadAction
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.SearchScope
import com.intellij.psi.search.searches.ClassInheritorsSearch
import com.intellij.psi.search.searches.DefinitionsScopedSearch
import com.intellij.util.Processor
import com.intellij.util.QueryExecutor
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.asJava.toFakeLightClass
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.actualsForExpected
import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.isExpectDeclaration
import org.jetbrains.kotlin.idea.search.declarationsSearch.forEachImplementation
import org.jetbrains.kotlin.idea.search.declarationsSearch.forEachOverridingMethod
import org.jetbrains.kotlin.idea.search.declarationsSearch.toPossiblyFakeLightMethods
import com.intellij.openapi.application.runReadAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.contains
import java.util.concurrent.Callable
class KotlinDefinitionsSearcher : QueryExecutor<PsiElement, DefinitionsScopedSearch.SearchParameters> {
override fun execute(queryParameters: DefinitionsScopedSearch.SearchParameters, consumer: Processor<in PsiElement>): Boolean {
val processor = skipDelegatedMethodsConsumer(consumer)
val element = queryParameters.element
val scope = queryParameters.scope
return when (element) {
is KtClass -> {
val isExpectEnum = runReadAction { element.isEnum() && element.isExpectDeclaration() }
if (isExpectEnum) {
processActualDeclarations(element, processor)
} else {
processClassImplementations(element, processor) && processActualDeclarations(element, processor)
}
}
is KtObjectDeclaration -> {
processActualDeclarations(element, processor)
}
is KtLightClass -> {
val useScope = runReadAction { element.useScope }
if (useScope is LocalSearchScope)
processLightClassLocalImplementations(element, useScope, processor)
else
true
}
is KtNamedFunction, is KtSecondaryConstructor -> {
processFunctionImplementations(element as KtFunction, scope, processor) && processActualDeclarations(element, processor)
}
is KtProperty -> {
processPropertyImplementations(element, scope, processor) && processActualDeclarations(element, processor)
}
is KtParameter -> {
if (isFieldParameter(element)) {
processPropertyImplementations(element, scope, processor) && processActualDeclarations(element, processor)
} else {
true
}
}
else -> true
}
}
companion object {
private fun skipDelegatedMethodsConsumer(baseConsumer: Processor<in PsiElement>): Processor<PsiElement> = Processor { element ->
if (isDelegated(element)) {
return@Processor true
}
baseConsumer.process(element)
}
private fun isDelegated(element: PsiElement): Boolean = element is KtLightMethod && element.isDelegated
private fun isFieldParameter(parameter: KtParameter): Boolean = runReadAction {
KtPsiUtil.getClassIfParameterIsProperty(parameter) != null
}
private fun processClassImplementations(klass: KtClass, consumer: Processor<PsiElement>): Boolean {
val psiClass = runReadAction { klass.toLightClass() ?: klass.toFakeLightClass() }
val searchScope = runReadAction { psiClass.useScope }
if (searchScope is LocalSearchScope) {
return processLightClassLocalImplementations(psiClass, searchScope, consumer)
}
return runReadAction { ContainerUtil.process(ClassInheritorsSearch.search(psiClass, true), consumer) }
}
private fun processLightClassLocalImplementations(
psiClass: KtLightClass,
searchScope: LocalSearchScope,
consumer: Processor<PsiElement>
): Boolean {
// workaround for IDEA optimization that uses Java PSI traversal to locate inheritors in local search scope
val virtualFiles = runReadAction {
searchScope.scope.mapTo(HashSet()) { it.containingFile.virtualFile }
}
val globalScope = GlobalSearchScope.filesScope(psiClass.project, virtualFiles)
return ContainerUtil.process(ClassInheritorsSearch.search(psiClass, globalScope, true)) { candidate ->
val candidateOrigin = candidate.unwrapped ?: candidate
val inScope = runReadAction { candidateOrigin in searchScope }
if (inScope) {
consumer.process(candidate)
} else {
true
}
}
}
private fun processFunctionImplementations(
function: KtFunction,
scope: SearchScope,
consumer: Processor<PsiElement>,
): Boolean =
ReadAction.nonBlocking(Callable {
function.toPossiblyFakeLightMethods().firstOrNull()?.forEachImplementation(scope, consumer::process) ?: true
}).executeSynchronously()
private fun processPropertyImplementations(
declaration: KtNamedDeclaration,
scope: SearchScope,
consumer: Processor<PsiElement>
): Boolean = runReadAction {
processPropertyImplementationsMethods(declaration.toPossiblyFakeLightMethods(), scope, consumer)
}
private fun processActualDeclarations(declaration: KtDeclaration, consumer: Processor<PsiElement>): Boolean = runReadAction {
if (!declaration.isExpectDeclaration()) true
else declaration.actualsForExpected().all(consumer::process)
}
fun processPropertyImplementationsMethods(
accessors: Iterable<PsiMethod>,
scope: SearchScope,
consumer: Processor<PsiElement>
): Boolean = accessors.all { method ->
method.forEachOverridingMethod(scope) { implementation ->
if (isDelegated(implementation)) return@forEachOverridingMethod true
val elementToProcess = runReadAction {
when (val mirrorElement = (implementation as? KtLightMethod)?.kotlinOrigin) {
is KtProperty, is KtParameter -> mirrorElement
is KtPropertyAccessor -> if (mirrorElement.parent is KtProperty) mirrorElement.parent else implementation
else -> implementation
}
}
consumer.process(elementToProcess)
}
}
}
}
| apache-2.0 | dd74119b2f2203ac4221e94aa0a16672 | 43.494118 | 136 | 0.66605 | 5.960599 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/MoveTypeAliasToTopLevelFix.kt | 3 | 1575 | // 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.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtTypeAlias
import org.jetbrains.kotlin.psi.psiUtil.parents
class MoveTypeAliasToTopLevelFix(element: KtTypeAlias) : KotlinQuickFixAction<KtTypeAlias>(element) {
override fun getText() = KotlinBundle.message("fix.move.typealias.to.top.level")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val typeAlias = element ?: return
val parents = typeAlias.parents.toList().reversed()
val containingFile = parents.firstOrNull() as? KtFile ?: return
val target = parents.getOrNull(1) ?: return
containingFile.addAfter(typeAlias, target)
containingFile.addAfter(KtPsiFactory(typeAlias).createNewLine(2), target)
typeAlias.delete()
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic) = (diagnostic.psiElement as? KtTypeAlias)?.let { MoveTypeAliasToTopLevelFix(it) }
}
}
| apache-2.0 | 6ae708e1974e044e3a31f2b1f91f0d5b | 46.727273 | 158 | 0.768254 | 4.525862 | false | false | false | false |
vovagrechka/fucking-everything | phizdets/phizdetsc/src/org/jetbrains/kotlin/js/resolve/diagnostics/sourceLocationUtils.kt | 6 | 1295 | /*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.js.resolve.diagnostics
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithSource
import org.jetbrains.kotlin.resolve.source.getPsi
fun DeclarationDescriptor.findPsi(): PsiElement? {
val psi = (this as? DeclarationDescriptorWithSource)?.source?.getPsi()
return if (psi == null && this is CallableMemberDescriptor && kind == CallableMemberDescriptor.Kind.FAKE_OVERRIDE) {
overriddenDescriptors.mapNotNull { it.findPsi() }.firstOrNull()
}
else {
psi
}
} | apache-2.0 | 976578457bb3048a938e4831dcc9b4d0 | 38.272727 | 120 | 0.762162 | 4.512195 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/reporter/KotlinReportSubmitter.kt | 3 | 11066 | // 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.reporter
import com.intellij.diagnostic.ReportMessages
import com.intellij.ide.DataManager
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.IdeaLoggingEvent
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.SubmittedReportInfo
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.util.Consumer
import com.intellij.util.ThreeState
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinPluginUpdater
import org.jetbrains.kotlin.idea.PluginUpdateStatus
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinIdePlugin
import org.jetbrains.kotlin.idea.util.application.isApplicationInternalMode
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import java.awt.Component
import java.io.IOException
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeParseException
import java.time.temporal.ChronoUnit
import javax.swing.Icon
/**
* We need to wrap ITNReporter for force showing or errors from kotlin plugin even from released version of IDEA.
*/
class KotlinReportSubmitter : ITNReporterCompat() {
companion object {
private const val KOTLIN_FATAL_ERROR_NOTIFICATION_PROPERTY = "kotlin.fatal.error.notification"
private const val IDEA_FATAL_ERROR_NOTIFICATION_PROPERTY = "idea.fatal.error.notification"
private const val DISABLED_VALUE = "disabled"
private const val ENABLED_VALUE = "enabled"
private const val KOTLIN_PLUGIN_RELEASE_DATE = "kotlin.plugin.releaseDate"
private val LOG = Logger.getInstance(KotlinReportSubmitter::class.java)
@Volatile
private var isFatalErrorReportingDisabledInRelease = ThreeState.UNSURE
private val isIdeaAndKotlinRelease by lazy {
// Disabled in released version of IDEA and Android Studio
// Enabled in EAPs, Canary and Beta
val isReleaseLikeIdea = DISABLED_VALUE == System.getProperty(IDEA_FATAL_ERROR_NOTIFICATION_PROPERTY, ENABLED_VALUE)
isReleaseLikeIdea && KotlinIdePlugin.isRelease
}
private const val NUMBER_OF_REPORTING_DAYS_FROM_RELEASE = 7
fun setupReportingFromRelease() {
if (isUnitTestMode()) {
return
}
if (!isIdeaAndKotlinRelease) {
return
}
val currentPluginReleaseDate = readStoredPluginReleaseDate()
if (currentPluginReleaseDate != null) {
isFatalErrorReportingDisabledInRelease =
if (isFatalErrorReportingDisabled(currentPluginReleaseDate)) ThreeState.YES else ThreeState.NO
return
}
ApplicationManager.getApplication().executeOnPooledThread {
val releaseDate =
try {
KotlinPluginUpdater.fetchPluginReleaseDate(KotlinIdePlugin.id, KotlinIdePlugin.version, null)
} catch (e: IOException) {
LOG.warn(e)
null
} catch (e: KotlinPluginUpdater.Companion.ResponseParseException) {
// Exception won't be shown, but will be logged
LOG.error(e)
return@executeOnPooledThread
}
if (releaseDate != null) {
writePluginReleaseValue(releaseDate)
} else {
// Will try to fetch the same release date on IDE restart
}
isFatalErrorReportingDisabledInRelease = isFatalErrorReportingWithDefault(releaseDate)
}
}
private fun isFatalErrorReportingWithDefault(releaseDate: LocalDate?): ThreeState {
return if (releaseDate != null) {
if (isFatalErrorReportingDisabled(releaseDate)) ThreeState.YES else ThreeState.NO
} else {
// Disable reporting by default until we obtain a valid release date.
// We might fail reporting exceptions that happened before initialization but after successful release date fetching
// such exceptions maybe be reported after restart.
ThreeState.YES
}
}
private fun isFatalErrorReportingDisabledWithUpdate(): Boolean {
val currentPluginReleaseDate = readStoredPluginReleaseDate()
isFatalErrorReportingDisabledInRelease = isFatalErrorReportingWithDefault(currentPluginReleaseDate)
return isFatalErrorReportingDisabledInRelease == ThreeState.YES
}
private fun isFatalErrorReportingDisabled(releaseDate: LocalDate): Boolean {
return ChronoUnit.DAYS.between(releaseDate, LocalDate.now()) > NUMBER_OF_REPORTING_DAYS_FROM_RELEASE
}
private val RELEASE_DATE_FORMATTER: DateTimeFormatter by lazy {
DateTimeFormatter.ofPattern("yyyy-MM-dd")
}
private fun readStoredPluginReleaseDate(): LocalDate? {
val pluginVersionToReleaseDate = PropertiesComponent.getInstance().getValue(KOTLIN_PLUGIN_RELEASE_DATE) ?: return null
val parsedDate = fun(): LocalDate? {
val parts = pluginVersionToReleaseDate.split(":")
if (parts.size != 2) {
return null
}
val pluginVersion = parts[0]
if (pluginVersion != KotlinIdePlugin.version) {
// Stored for some other plugin version
return null
}
return try {
val dateString = parts[1]
LocalDate.parse(dateString, RELEASE_DATE_FORMATTER)
} catch (e: DateTimeParseException) {
null
}
}.invoke()
if (parsedDate == null) {
PropertiesComponent.getInstance().setValue(KOTLIN_PLUGIN_RELEASE_DATE, null)
}
return parsedDate
}
private fun writePluginReleaseValue(date: LocalDate) {
val currentKotlinVersion = KotlinIdePlugin.version
val dateStr = RELEASE_DATE_FORMATTER.format(date)
PropertiesComponent.getInstance().setValue(KOTLIN_PLUGIN_RELEASE_DATE, "$currentKotlinVersion:$dateStr")
}
}
private var hasUpdate = false
private var hasLatestVersion = false
override fun showErrorInRelease(event: IdeaLoggingEvent): Boolean {
if (isApplicationInternalMode()) {
// Reporting is always enabled for internal mode in the platform
return true
}
if (isUnitTestMode()) {
return true
}
if (hasUpdate) {
return false
}
val kotlinNotificationEnabled = DISABLED_VALUE != System.getProperty(KOTLIN_FATAL_ERROR_NOTIFICATION_PROPERTY, ENABLED_VALUE)
if (!kotlinNotificationEnabled) {
// Kotlin notifications are explicitly disabled
return false
}
if (!isIdeaAndKotlinRelease) {
return true
}
return when (isFatalErrorReportingDisabledInRelease) {
ThreeState.YES ->
false
ThreeState.NO -> {
// Reiterate the check for the case when there was no restart for long and reporting decision might expire
!isFatalErrorReportingDisabledWithUpdate()
}
ThreeState.UNSURE -> {
// There might be an exception while initialization isn't complete.
// Decide urgently based on previously stored release version if already fetched.
!isFatalErrorReportingDisabledWithUpdate()
}
}
}
override fun submitCompat(
events: Array<IdeaLoggingEvent>,
additionalInfo: String?,
parentComponent: Component?,
consumer: Consumer<in SubmittedReportInfo>
): Boolean {
if (hasUpdate) {
if (isApplicationInternalMode()) {
return super.submitCompat(events, additionalInfo, parentComponent, consumer)
}
// TODO: What happens here? User clicks report but no report is send?
return true
}
if (hasLatestVersion) {
return super.submitCompat(events, additionalInfo, parentComponent, consumer)
}
val project: Project? = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(parentComponent))
if (KotlinIdePlugin.hasPatchedVersion) {
ReportMessages.GROUP
.createNotification(KotlinBundle.message("reporter.text.can.t.report.exception.from.patched.plugin"), NotificationType.INFORMATION)
.setImportant(false)
.notify(project)
return true
}
KotlinPluginUpdater.getInstance().runUpdateCheck { status ->
if (status is PluginUpdateStatus.Update) {
hasUpdate = true
if (isApplicationInternalMode()) {
super.submitCompat(events, additionalInfo, parentComponent, consumer)
}
val rc = showDialog(
parentComponent,
KotlinBundle.message(
"reporter.message.text.you.re.running.kotlin.plugin.version",
KotlinIdePlugin.version,
status.pluginDescriptor.version
),
KotlinBundle.message("reporter.title.update.kotlin.plugin"),
arrayOf(KotlinBundle.message("reporter.button.text.update"), KotlinBundle.message("reporter.button.text.ignore")),
0, Messages.getInformationIcon()
)
if (rc == 0) {
KotlinPluginUpdater.getInstance().installPluginUpdate(status)
}
} else {
hasLatestVersion = true
super.submitCompat(events, additionalInfo, parentComponent, consumer)
}
false
}
return true
}
fun showDialog(parent: Component?, @Nls message: String, @Nls title: String, options: Array<String>, defaultOptionIndex: Int, icon: Icon?): Int {
return if (parent != null) {
Messages.showDialog(parent, message, title, options, defaultOptionIndex, icon)
} else {
Messages.showDialog(message, title, options, defaultOptionIndex, icon)
}
}
}
| apache-2.0 | f0f43fe82123d0b254e1a4a90f8a5516 | 39.534799 | 158 | 0.630671 | 5.533 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinUFunctionCallExpression.kt | 2 | 8139 | // 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.uast.kotlin
import com.intellij.psi.*
import com.intellij.psi.util.PropertyUtilBase
import com.intellij.psi.util.PsiTypesUtil
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.psi.*
import org.jetbrains.uast.*
import org.jetbrains.uast.internal.acceptList
import org.jetbrains.uast.kotlin.internal.TypedResolveResult
import org.jetbrains.uast.visitor.UastVisitor
@ApiStatus.Internal
class KotlinUFunctionCallExpression(
override val sourcePsi: KtCallElement,
givenParent: UElement?,
) : KotlinAbstractUExpression(givenParent), UCallExpression, KotlinUElementWithType, UMultiResolvable {
override val receiverType by lz {
baseResolveProviderService.getReceiverType(sourcePsi, this)
}
override val methodName by lz {
baseResolveProviderService.resolvedFunctionName(sourcePsi)
}
override val classReference: UReferenceExpression by lz {
KotlinClassViaConstructorUSimpleReferenceExpression(sourcePsi, methodName.orAnonymous("class"), this)
}
override val methodIdentifier: UIdentifier? by lz {
if (sourcePsi is KtSuperTypeCallEntry) {
((sourcePsi.parent as? KtInitializerList)?.parent as? KtEnumEntry)?.let { ktEnumEntry ->
return@lz KotlinUIdentifier(ktEnumEntry.nameIdentifier, this)
}
}
when (val calleeExpression = sourcePsi.calleeExpression) {
null -> null
is KtNameReferenceExpression ->
KotlinUIdentifier(calleeExpression.getReferencedNameElement(), this)
is KtConstructorDelegationReferenceExpression ->
KotlinUIdentifier(calleeExpression.firstChild ?: calleeExpression, this)
is KtConstructorCalleeExpression -> {
val referencedNameElement = calleeExpression.constructorReferenceExpression?.getReferencedNameElement()
if (referencedNameElement != null) KotlinUIdentifier(referencedNameElement, this)
else generateSequence<PsiElement>(calleeExpression) { it.firstChild?.takeIf { it.nextSibling == null } }
.lastOrNull()
?.takeIf { it.firstChild == null }
?.let { KotlinUIdentifier(it, this) }
}
is KtLambdaExpression ->
KotlinUIdentifier(calleeExpression.functionLiteral.lBrace, this)
else -> KotlinUIdentifier(
sourcePsi.valueArgumentList?.leftParenthesis
?: sourcePsi.lambdaArguments.singleOrNull()?.getLambdaExpression()?.functionLiteral?.lBrace
?: sourcePsi.typeArgumentList?.firstChild
?: calleeExpression, this)
}
}
override val valueArgumentCount: Int
get() = sourcePsi.valueArguments.size
override val valueArguments by lz {
sourcePsi.valueArguments.map {
baseResolveProviderService.baseKotlinConverter.convertOrEmpty(it.getArgumentExpression(), this)
}
}
override fun getArgumentForParameter(i: Int): UExpression? {
val resolvedCall = baseResolveProviderService.resolveCall(sourcePsi)
if (resolvedCall != null) {
val actualParamIndex = if (baseResolveProviderService.isResolvedToExtension(sourcePsi)) i - 1 else i
if (actualParamIndex == -1) return receiver
return baseResolveProviderService.getArgumentForParameter(sourcePsi, actualParamIndex, this)
}
val argument = valueArguments.getOrNull(i) ?: return null
val argumentType = argument.getExpressionType()
for (resolveResult in multiResolve()) {
val psiMethod = resolveResult.element as? PsiMethod ?: continue
val psiParameter = psiMethod.parameterList.parameters.getOrNull(i) ?: continue
if (argumentType == null || psiParameter.type.isAssignableFrom(argumentType))
return argument
}
return null
}
override fun getExpressionType(): PsiType? {
super<KotlinUElementWithType>.getExpressionType()?.let { return it }
for (resolveResult in multiResolve()) {
val psiMethod = resolveResult.element
when {
psiMethod.isConstructor ->
psiMethod.containingClass?.let { return PsiTypesUtil.getClassType(it) }
else ->
psiMethod.returnType?.let { return it }
}
}
return null
}
override val typeArgumentCount: Int
get() = sourcePsi.typeArguments.size
override val typeArguments by lz {
sourcePsi.typeArguments.map { ktTypeProjection ->
ktTypeProjection.typeReference?.let { baseResolveProviderService.resolveToType(it, this, boxed = true) } ?: UastErrorType
}
}
override val returnType: PsiType? by lz {
getExpressionType()
}
override val kind: UastCallKind by lz {
baseResolveProviderService.callKind(sourcePsi)
}
override val receiver: UExpression? by lz {
(uastParent as? UQualifiedReferenceExpression)?.let {
if (it.selector == this) return@lz it.receiver
}
val ktNameReferenceExpression = sourcePsi.calleeExpression as? KtNameReferenceExpression ?: return@lz null
val callableDeclaration = baseResolveProviderService.resolveToDeclaration(ktNameReferenceExpression) ?: return@lz null
val variable = when (callableDeclaration) {
is PsiVariable -> callableDeclaration
is PsiMethod -> {
callableDeclaration.containingClass?.let { containingClass ->
PropertyUtilBase.getPropertyName(callableDeclaration.name)?.let { propertyName ->
PropertyUtilBase.findPropertyField(containingClass, propertyName, true)
}
}
}
else -> null
} ?: return@lz null
// an implicit receiver for variables calls (KT-25524)
object : KotlinAbstractUExpression(this), UReferenceExpression {
override val sourcePsi: KtNameReferenceExpression get() = ktNameReferenceExpression
override val resolvedName: String? get() = variable.name
override fun resolve(): PsiElement = variable
}
}
private val multiResolved: Iterable<TypedResolveResult<PsiMethod>> by lz {
val contextElement = sourcePsi
val calleeExpression = contextElement.calleeExpression as? KtReferenceExpression ?: return@lz emptyList()
val methodName = methodName ?: calleeExpression.text ?: return@lz emptyList()
val variants = baseResolveProviderService.getReferenceVariants(calleeExpression, methodName)
variants.flatMap {
when (it) {
is PsiClass -> it.constructors.asSequence()
is PsiMethod -> sequenceOf(it)
else -> emptySequence()
}
}.map { TypedResolveResult(it) }.asIterable()
}
override fun multiResolve(): Iterable<TypedResolveResult<PsiMethod>> =
multiResolved
override fun resolve(): PsiMethod? =
baseResolveProviderService.resolveCall(sourcePsi)
override fun accept(visitor: UastVisitor) {
if (visitor.visitCallExpression(this)) return
uAnnotations.acceptList(visitor)
methodIdentifier?.accept(visitor)
classReference.accept(visitor)
valueArguments.acceptList(visitor)
visitor.afterVisitCallExpression(this)
}
override fun convertParent(): UElement? = super.convertParent().let { result ->
when (result) {
is UMethod -> result.uastBody ?: result
is UClass ->
result.methods
.filterIsInstance<KotlinConstructorUMethod>()
.firstOrNull { it.isPrimary }
?.uastBody
?: result
else -> result
}
}
}
| apache-2.0 | ad7a59a52d5052ca1ca6e617e04abcc6 | 40.314721 | 158 | 0.657943 | 6.046805 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/EntityStorageExtensions.kt | 4 | 15650 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.impl
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.EntityStorage
// ------------------------- Updating references ------------------------
@Suppress("unused")
fun EntityStorage.updateOneToManyChildrenOfParent(connectionId: ConnectionId,
parent: WorkspaceEntity,
children: List<WorkspaceEntity>) {
this as MutableEntityStorageImpl
val parentId = (parent as WorkspaceEntityBase).id
val childrenIds = children.map { (it as WorkspaceEntityBase).id.asChild() }
if (!connectionId.isParentNullable) {
val existingChildren = extractOneToManyChildrenIds(connectionId, parentId).toHashSet()
childrenIds.forEach {
existingChildren.remove(it.id)
}
existingChildren.forEach { removeEntityByEntityId(it) }
}
refs.updateOneToManyChildrenOfParent(connectionId, parentId.arrayId, childrenIds)
}
@Suppress("unused")
fun EntityStorage.updateOneToAbstractManyChildrenOfParent(connectionId: ConnectionId,
parentEntity: WorkspaceEntity,
childrenEntity: Sequence<WorkspaceEntity>) {
this as MutableEntityStorageImpl
val parentId = (parentEntity as WorkspaceEntityBase).id.asParent()
val childrenIds = childrenEntity.map { (it as WorkspaceEntityBase).id.asChild() }
refs.updateOneToAbstractManyChildrenOfParent(connectionId, parentId, childrenIds)
}
@Suppress("unused")
fun EntityStorage.updateOneToAbstractOneChildOfParent(connectionId: ConnectionId,
parentEntity: WorkspaceEntity,
childEntity: WorkspaceEntity?) {
this as MutableEntityStorageImpl
val parentId = (parentEntity as WorkspaceEntityBase).id.asParent()
val childId = (childEntity as? WorkspaceEntityBase)?.id?.asChild()
if (childId != null) {
refs.updateOneToAbstractOneChildOfParent(connectionId, parentId, childId)
} else {
refs.removeOneToAbstractOneRefByParent(connectionId, parentId)
}
}
@Suppress("unused")
fun EntityStorage.updateOneToOneChildOfParent(connectionId: ConnectionId, parentEntity: WorkspaceEntity,
childEntity: WorkspaceEntity?) {
this as MutableEntityStorageImpl
val parentId = (parentEntity as WorkspaceEntityBase).id
val childId = (childEntity as? WorkspaceEntityBase)?.id?.asChild()
val existingChildId = extractOneToOneChildIds(connectionId, parentId)
if (!connectionId.isParentNullable && existingChildId != null && (childId == null || childId.id != existingChildId)) {
removeEntityByEntityId(existingChildId)
}
if (childId != null) {
refs.updateOneToOneChildOfParent(connectionId, parentId.arrayId, childId)
}
else {
refs.removeOneToOneRefByParent(connectionId, parentId.arrayId)
}
}
@Suppress("unused")
fun <Parent : WorkspaceEntity> EntityStorage.updateOneToManyParentOfChild(connectionId: ConnectionId,
childEntity: WorkspaceEntity,
parentEntity: Parent?) {
this as MutableEntityStorageImpl
val childId = (childEntity as WorkspaceEntityBase).id.asChild()
val parentId = (parentEntity as? WorkspaceEntityBase)?.id?.asParent()
if (parentId != null) {
refs.updateOneToManyParentOfChild(connectionId, childId.id.arrayId, parentId)
}
else {
refs.removeOneToManyRefsByChild(connectionId, childId.id.arrayId)
}
}
fun <Parent : WorkspaceEntity> EntityStorage.updateOneToAbstractManyParentOfChild(connectionId: ConnectionId,
child: WorkspaceEntity,
parent: Parent?) {
this as MutableEntityStorageImpl
val childId = (child as WorkspaceEntityBase).id.asChild()
val parentId = (parent as? WorkspaceEntityBase)?.id?.asParent()
if (parentId != null) {
refs.updateOneToAbstractManyParentOfChild(connectionId, childId, parentId)
} else {
refs.removeOneToAbstractManyRefsByChild(connectionId, childId)
}
}
@Suppress("unused")
fun <Parent : WorkspaceEntity> EntityStorage.updateOneToOneParentOfChild(connectionId: ConnectionId,
childEntity: WorkspaceEntity,
parentEntity: Parent?) {
this as MutableEntityStorageImpl
val parentId = (parentEntity as? WorkspaceEntityBase)?.id?.asParent()
val childId = (childEntity as WorkspaceEntityBase).id
if (!connectionId.isParentNullable && parentId != null) {
// A very important thing. If we replace a field in one-to-one connection, the previous entity is automatically removed.
val existingChild = extractOneToOneChild<WorkspaceEntityBase>(connectionId, parentEntity)
if (existingChild != null && existingChild != childEntity) {
removeEntity(existingChild)
}
}
if (parentId != null) {
refs.updateOneToOneParentOfChild(connectionId, childId.arrayId, parentId.id)
}
else {
refs.removeOneToOneRefByChild(connectionId, childId.arrayId)
}
}
fun <Parent : WorkspaceEntity> EntityStorage.updateOneToAbstractOneParentOfChild(connectionId: ConnectionId,
childEntity: WorkspaceEntity, parentEntity: Parent?
) {
this as MutableEntityStorageImpl
val parentId = (parentEntity as? WorkspaceEntityBase)?.id?.asParent()
val childId = (childEntity as WorkspaceEntityBase).id.asChild()
if (!connectionId.isParentNullable && parentId != null) {
// A very important thing. If we replace a field in one-to-one connection, the previous entity is automatically removed.
val existingChild = extractOneToAbstractOneChild<WorkspaceEntityBase>(connectionId, parentEntity)
if (existingChild != null && existingChild != childEntity) {
removeEntity(existingChild)
}
}
if (parentId != null) {
refs.updateOneToAbstractOneParentOfChild(connectionId, childId, parentId)
}
else {
refs.removeOneToAbstractOneRefByChild(connectionId, childId)
}
}
// ------------------------- Extracting references references ------------------------
@Suppress("unused")
fun <Child : WorkspaceEntity> EntityStorage.extractOneToManyChildren(connectionId: ConnectionId,
parent: WorkspaceEntity): Sequence<Child> {
return (this as AbstractEntityStorage).extractOneToManyChildren(connectionId, (parent as WorkspaceEntityBase).id)
}
@Suppress("UNCHECKED_CAST")
internal fun <Child : WorkspaceEntity> AbstractEntityStorage.extractOneToManyChildren(connectionId: ConnectionId,
parentId: EntityId): Sequence<Child> {
val entitiesList = entitiesByType[connectionId.childClass] ?: return emptySequence()
return refs.getOneToManyChildren(connectionId, parentId.arrayId)?.map {
val entityData = entitiesList[it]
if (entityData == null) {
if (!brokenConsistency) {
error(
"""Cannot resolve entity.
|Connection id: $connectionId
|Unresolved array id: $it
|All child array ids: ${refs.getOneToManyChildren(connectionId, parentId.arrayId)?.toArray()}
""".trimMargin()
)
}
null
}
else entityData.createEntity(this)
}?.filterNotNull() as? Sequence<Child> ?: emptySequence()
}
internal fun AbstractEntityStorage.extractOneToManyChildrenIds(connectionId: ConnectionId, parentId: EntityId): Sequence<EntityId> {
return refs.getOneToManyChildren(connectionId, parentId.arrayId)?.map { createEntityId(it, connectionId.childClass) } ?: emptySequence()
}
internal fun AbstractEntityStorage.extractOneToOneChildIds(connectionId: ConnectionId, parentId: EntityId): EntityId? {
return refs.getOneToOneChild(connectionId, parentId.arrayId)?.let { createEntityId(it, connectionId.childClass) } ?: return null
}
@Suppress("unused")
fun <Child : WorkspaceEntity> EntityStorage.extractOneToAbstractManyChildren(connectionId: ConnectionId,
parent: WorkspaceEntity): Sequence<Child> {
return (this as AbstractEntityStorage).extractOneToAbstractManyChildren(connectionId, (parent as WorkspaceEntityBase).id.asParent())
}
@Suppress("UNCHECKED_CAST")
internal fun <Child : WorkspaceEntity> AbstractEntityStorage.extractOneToAbstractManyChildren(connectionId: ConnectionId,
parentId: ParentEntityId): Sequence<Child> {
return refs.getOneToAbstractManyChildren(connectionId, parentId)?.asSequence()?.map { pid ->
entityDataByIdOrDie(pid.id).createEntity(this)
} as? Sequence<Child> ?: emptySequence()
}
fun <Parent : WorkspaceEntity> EntityStorage.extractOneToAbstractManyParent(
connectionId: ConnectionId,
child: WorkspaceEntity
): Parent? {
return (this as AbstractEntityStorage).extractOneToAbstractManyParent(
connectionId,
(child as WorkspaceEntityBase).id.asChild()
)
}
@Suppress("UNCHECKED_CAST")
internal fun <Parent : WorkspaceEntity> AbstractEntityStorage.extractOneToAbstractManyParent(
connectionId: ConnectionId,
child: ChildEntityId
): Parent? {
return refs.getOneToAbstractManyParent(connectionId, child)?.let { entityDataByIdOrDie(it.id).createEntity(this) as Parent }
}
@Suppress("unused")
fun <Child : WorkspaceEntity> EntityStorage.extractOneToAbstractOneChild(connectionId: ConnectionId,
parent: WorkspaceEntity): Child? {
return (this as AbstractEntityStorage).extractOneToAbstractOneChild(connectionId, (parent as WorkspaceEntityBase).id.asParent())
}
@Suppress("UNCHECKED_CAST")
internal fun <Child : WorkspaceEntity> AbstractEntityStorage.extractOneToAbstractOneChild(connectionId: ConnectionId,
parentId: ParentEntityId): Child? {
return refs.getAbstractOneToOneChildren(connectionId, parentId)?.let { entityDataByIdOrDie(it.id).createEntity(this) as Child }
}
@Suppress("unused")
fun <Child : WorkspaceEntity> EntityStorage.extractAbstractOneToOneChild(connectionId: ConnectionId,
parent: WorkspaceEntity): Child? {
return (this as AbstractEntityStorage).extractAbstractOneToOneChild(connectionId, (parent as WorkspaceEntityBase).id.asParent())
}
@Suppress("UNCHECKED_CAST")
internal fun <Child : WorkspaceEntity> AbstractEntityStorage.extractAbstractOneToOneChild(connectionId: ConnectionId,
parentId: ParentEntityId): Child? {
return refs.getAbstractOneToOneChildren(connectionId, parentId)?.let { entityDataByIdOrDie(it.id).createEntity(this) as Child }
}
@Suppress("unused")
fun <Child : WorkspaceEntity> EntityStorage.extractOneToOneChild(connectionId: ConnectionId, parent: WorkspaceEntity): Child? {
return (this as AbstractEntityStorage).extractOneToOneChild(connectionId, (parent as WorkspaceEntityBase).id)
}
@Suppress("UNCHECKED_CAST")
internal fun <Child : WorkspaceEntity> AbstractEntityStorage.extractOneToOneChild(connectionId: ConnectionId, parentId: EntityId): Child? {
val entitiesList = entitiesByType[connectionId.childClass] ?: return null
return refs.getOneToOneChild(connectionId, parentId.arrayId) {
val childEntityData = entitiesList[it]
if (childEntityData == null) {
if (!brokenConsistency) {
error("""
Consistency issue. Cannot get a child in one to one connection.
Connection id: $connectionId
Parent id: $parentId
Child array id: $it
""".trimIndent())
}
null
}
else childEntityData.createEntity(this) as Child
}
}
@Suppress("unused")
fun <Parent : WorkspaceEntity> EntityStorage.extractOneToOneParent(connectionId: ConnectionId,
child: WorkspaceEntity): Parent? {
return (this as AbstractEntityStorage).extractOneToOneParent(connectionId, (child as WorkspaceEntityBase).id)
}
@Suppress("UNCHECKED_CAST")
internal fun <Parent : WorkspaceEntity> AbstractEntityStorage.extractOneToOneParent(connectionId: ConnectionId,
childId: EntityId): Parent? {
val entitiesList = entitiesByType[connectionId.parentClass] ?: return null
return refs.getOneToOneParent(connectionId, childId.arrayId) {
val parentEntityData = entitiesList[it]
if (parentEntityData == null) {
if (!brokenConsistency) {
error("""
Consistency issue. Cannot get a parent in one to one connection.
Connection id: $connectionId
Child id: $childId
Parent array id: $it
""".trimIndent())
}
null
}
else parentEntityData.createEntity(this) as Parent
}
}
fun <Parent : WorkspaceEntity> EntityStorage.extractOneToAbstractOneParent(
connectionId: ConnectionId,
child: WorkspaceEntity,
): Parent? {
return (this as AbstractEntityStorage).extractOneToAbstractOneParent(
connectionId,
(child as WorkspaceEntityBase).id.asChild()
)
}
@Suppress("UNCHECKED_CAST")
internal fun <Parent : WorkspaceEntity> AbstractEntityStorage.extractOneToAbstractOneParent(
connectionId: ConnectionId,
childId: ChildEntityId
): Parent? {
return refs.getOneToAbstractOneParent(connectionId, childId)
?.let { entityDataByIdOrDie(it.id).createEntity(this) as Parent }
}
@Suppress("unused")
fun <Parent : WorkspaceEntity> EntityStorage.extractOneToManyParent(connectionId: ConnectionId,
child: WorkspaceEntity): Parent? {
return (this as AbstractEntityStorage).extractOneToManyParent(connectionId, (child as WorkspaceEntityBase).id)
}
@Suppress("UNCHECKED_CAST")
internal fun <Parent : WorkspaceEntity> AbstractEntityStorage.extractOneToManyParent(connectionId: ConnectionId,
childId: EntityId): Parent? {
val entitiesList = entitiesByType[connectionId.parentClass] ?: return null
return refs.getOneToManyParent(connectionId, childId.arrayId) {
val parentEntityData = entitiesList[it]
if (parentEntityData == null) {
if (!brokenConsistency) {
error("""
Consistency issue. Cannot get a parent in one to many connection.
Connection id: $connectionId
Child id: $childId
Parent array id: $it
""".trimIndent())
}
null
}
else parentEntityData.createEntity(this) as Parent
}
}
| apache-2.0 | e2196e762518b627a2bf8321333bac82 | 46.280967 | 139 | 0.658019 | 5.854845 | false | false | false | false |
smmribeiro/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/util/MigLayoutExtensions.kt | 3 | 883 | @file:Suppress("MagicNumber") // Swing dimension constants...
package com.jetbrains.packagesearch.intellij.plugin.ui.util
import net.miginfocom.layout.LC
internal fun LC.noInsets() = insets("0")
internal fun LC.scaledInsets(
@ScalableUnits top: Int = 0,
@ScalableUnits left: Int = 0,
@ScalableUnits bottom: Int = 0,
@ScalableUnits right: Int = 0
) = insets(top.scaled(), left.scaled(), bottom.scaled(), right.scaled())
internal fun LC.insets(
@ScaledPixels top: Int = 0,
@ScaledPixels left: Int = 0,
@ScaledPixels bottom: Int = 0,
@ScaledPixels right: Int = 0
) = insets(top.toString(), left.toString(), bottom.toString(), right.toString())
internal fun LC.skipInvisibleComponents() = hideMode(3)
internal fun LC.gridGap(@ScalableUnits hSize: Int = 0, @ScalableUnits vSize: Int = 0) =
gridGap(hSize.scaledAsString(), vSize.scaledAsString())
| apache-2.0 | b5902108ddc1ab6aeed3ff026d9ec671 | 34.32 | 87 | 0.705549 | 3.633745 | false | false | false | false |
smmribeiro/intellij-community | python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyTypedDictStubImpl.kt | 5 | 4913 | // 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.jetbrains.python.psi.impl.stubs
import com.intellij.psi.stubs.StubInputStream
import com.intellij.psi.stubs.StubOutputStream
import com.intellij.psi.util.QualifiedName
import com.jetbrains.python.codeInsight.typing.PyTypedDictTypeProvider
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.PyEvaluator
import com.jetbrains.python.psi.impl.PyPsiUtils
import com.jetbrains.python.psi.resolve.PyResolveUtil
import com.jetbrains.python.psi.stubs.PyTypedDictStub
import com.jetbrains.python.psi.types.PyTypedDictType.Companion.TYPED_DICT_FIELDS_PARAMETER
import com.jetbrains.python.psi.types.PyTypedDictType.Companion.TYPED_DICT_NAME_PARAMETER
import com.jetbrains.python.psi.types.PyTypedDictType.Companion.TYPED_DICT_TOTAL_PARAMETER
import java.io.IOException
import java.util.*
class PyTypedDictStubImpl private constructor(private val myCalleeName: QualifiedName,
override val name: String,
override val fields: LinkedHashMap<String, Optional<String>>,
override val isRequired: Boolean = true) : PyTypedDictStub {
override fun getTypeClass(): Class<out CustomTargetExpressionStubType<*>> {
return PyTypedDictStubType::class.java
}
@Throws(IOException::class)
override fun serialize(stream: StubOutputStream) {
stream.writeName(myCalleeName.toString())
stream.writeName(name)
stream.writeBoolean(isRequired)
stream.writeVarInt(fields.size)
for ((key, value) in fields) {
stream.writeName(key)
stream.writeName(value.orElse(null))
}
}
override fun getCalleeName(): QualifiedName {
return myCalleeName
}
companion object {
fun create(expression: PyTargetExpression): PyTypedDictStub? {
val assignedValue = expression.findAssignedValue()
return if (assignedValue is PyCallExpression) create(assignedValue) else null
}
fun create(expression: PyCallExpression): PyTypedDictStub? {
val calleeReference = expression.callee as? PyReferenceExpression ?: return null
val calleeName = getCalleeName(calleeReference)
if (calleeName != null) {
val name = PyResolveUtil.resolveStrArgument(expression, 0, TYPED_DICT_NAME_PARAMETER) ?: return null
val fieldsArgument = expression.getArgument(1, TYPED_DICT_FIELDS_PARAMETER, PyDictLiteralExpression::class.java) ?: return null
val fields = getTypingTDFieldsFromIterable(fieldsArgument)
if (fields != null) {
return PyTypedDictStubImpl(calleeName,
name,
fields,
PyEvaluator.evaluateAsBoolean(expression.getKeywordArgument(TYPED_DICT_TOTAL_PARAMETER), true))
}
}
return null
}
@Throws(IOException::class)
fun deserialize(stream: StubInputStream): PyTypedDictStub? {
val calleeName = stream.readNameString()
val name = stream.readNameString()
val isRequired = stream.readBoolean()
val fields = deserializeFields(stream, stream.readVarInt())
return if (calleeName == null || name == null) {
null
}
else PyTypedDictStubImpl(QualifiedName.fromDottedString(calleeName), name, fields, isRequired)
}
private fun getCalleeName(referenceExpression: PyReferenceExpression): QualifiedName? {
val calleeName = PyPsiUtils.asQualifiedName(referenceExpression) ?: return null
for (name in PyResolveUtil.resolveImportedElementQNameLocally(referenceExpression).map { it.toString() }) {
if (PyTypedDictTypeProvider.nameIsTypedDict(name)) {
return calleeName
}
}
return null
}
@Throws(IOException::class)
private fun deserializeFields(stream: StubInputStream, fieldsSize: Int): LinkedHashMap<String, Optional<String>> {
val fields = LinkedHashMap<String, Optional<String>>(fieldsSize)
for (i in 0 until fieldsSize) {
val name = stream.readNameString()
val type = stream.readNameString()
if (name != null) {
fields[name] = Optional.ofNullable(type)
}
}
return fields
}
private fun getTypingTDFieldsFromIterable(fields: PySequenceExpression): LinkedHashMap<String, Optional<String>>? {
val result = LinkedHashMap<String, Optional<String>>()
fields.elements.forEach {
if (it !is PyKeyValueExpression) return null
val name: PyExpression = it.key
val type: PyExpression? = it.value
if (name !is PyStringLiteralExpression) return null
result[name.stringValue] = Optional.ofNullable(type?.text)
}
return result
}
}
}
| apache-2.0 | 7b36cfe0a8c302c5cfa5f4494a27a528 | 35.93985 | 140 | 0.692449 | 4.82613 | false | false | false | false |
douzifly/clear-todolist | app/src/main/java/douzifly/list/alarm/Alarm.kt | 1 | 1292 | package douzifly.list.alarm
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import com.activeandroid.query.Select
import douzifly.list.ListApplication
import douzifly.list.model.Thing
import douzifly.list.utils.logd
/**
* Created by air on 15/10/20.
*/
object Alarm {
fun setAlarmForAllThing() {
val things = Select()
.from(Thing::class.java)
.where("isComplete=0 and reminderTime>0").execute<Thing>()
things.forEach {
thing->
if (thing.reminderTime > System.currentTimeMillis()) {
setAlarm(thing.id, thing.reminderTime, thing.title, thing.color)
}
}
}
fun setAlarm(thingId: Long, reminderTime: Long, title: String, color: Int) {
"setAlarm id: ${thingId} time:${reminderTime} title:${title}".logd("oooo")
val am = ListApplication.appContext!!.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val i = Intent("ClearAlarmPro")
i.putExtra("title", title)
i.putExtra("color", color)
i.putExtra("id", thingId.toInt())
val pi = PendingIntent.getBroadcast(ListApplication.appContext, thingId.toInt(), i, PendingIntent.FLAG_CANCEL_CURRENT)
am.set(AlarmManager.RTC_WAKEUP, reminderTime, pi)
}
} | gpl-3.0 | 129b105d0ce3ae105fe1c4c2d9ea8760 | 30.536585 | 122 | 0.701238 | 3.939024 | false | false | false | false |
glorantq/KalanyosiRamszesz | src/glorantq/ramszesz/utils/DictionaryResult.kt | 1 | 1167 | package glorantq.ramszesz.utils
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
/**
* Created by glora on 2017. 07. 28..
*/
class DictionaryResult {
@SerializedName("textProns")
@Expose
var textProns: List<Any>? = null
@SerializedName("sourceDictionary")
@Expose
var sourceDictionary: String = ""
@SerializedName("exampleUses")
@Expose
var exampleUses: List<Any>? = null
@SerializedName("relatedWords")
@Expose
var relatedWords: List<Any>? = null
@SerializedName("labels")
@Expose
var labels: List<Any>? = null
@SerializedName("citations")
@Expose
var citations: List<Any>? = null
@SerializedName("word")
@Expose
var word: String = ""
@SerializedName("partOfSpeech")
@Expose
var partOfSpeech: String = ""
@SerializedName("attributionText")
@Expose
var attributionText: String = ""
@SerializedName("sequence")
@Expose
var sequence: String = ""
@SerializedName("text")
@Expose
var text: String = ""
@SerializedName("score")
@Expose
var score: Double = 0.toDouble()
} | gpl-3.0 | bcec64e8a617d6d033ab847b2bf3976a | 19.491228 | 49 | 0.648672 | 4.167857 | false | false | false | false |
nobumin/mstdn_light_android | app/src/main/java/view/mstdn/meas/jp/multimstdn/util/PrograssDialogFragment.kt | 1 | 1061 | package view.mstdn.meas.jp.multimstdn.util
import android.app.Dialog
import android.app.ProgressDialog
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v4.app.FragmentManager
/**
* Created by nobu on 2017/04/28.
*/
class PrograssDialogFragment : DialogFragment() {
var isShowing = false
private set
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
isCancelable = false
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = ProgressDialog(activity, theme)
dialog.setMessage("インスタンス接続中...")
dialog.isIndeterminate = true
dialog.setCancelable(true)
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER)
return dialog
}
override fun show(manager: FragmentManager, tag: String) {
super.show(manager, tag)
isShowing = true
}
override fun dismiss() {
super.dismiss()
isShowing = false
}
}
| mit | 87da83879e03f104e567efe3bfaa7803 | 24.439024 | 70 | 0.686481 | 4.554585 | false | false | false | false |
BenoitDuffez/AndroidCupsPrint | app/src/main/java/org/cups4j/operations/ipp/IppCancelJobOperation.kt | 1 | 2740 | package org.cups4j.operations.ipp
/**
* Copyright (C) 2011 Harald Weyhing
*
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
*
* 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 Lesser General Public License for more details. You should have received a copy of
* the GNU Lesser General Public License along with this program; if not, see
* <http:></http:>//www.gnu.org/licenses/>.
*/
/*Notice
* This file has been modified. It is not the original.
* Jon Freeman - 2013
*/
import android.content.Context
import org.cups4j.CupsClient
import org.cups4j.PrintRequestResult
import org.cups4j.operations.IppOperation
import java.io.UnsupportedEncodingException
import java.net.URL
import java.nio.ByteBuffer
import java.util.HashMap
import ch.ethz.vppserver.ippclient.IppTag
class IppCancelJobOperation(context: Context) : IppOperation(context) {
init {
operationID = 0x0008
bufferSize = 8192
}
@Throws(UnsupportedEncodingException::class)
override fun getIppHeader(url: URL, map: Map<String, String>?): ByteBuffer {
var ippBuf = ByteBuffer.allocateDirect(bufferSize.toInt())
ippBuf = IppTag.getOperation(ippBuf, operationID)
if (map == null) {
ippBuf = IppTag.getEnd(ippBuf)
ippBuf.flip()
return ippBuf
}
map["job-id"]?.let {
ippBuf = IppTag.getUri(ippBuf, "printer-uri", stripPortNumber(url))
ippBuf = IppTag.getInteger(ippBuf, "job-id", it.toInt())
} ?: run {
ippBuf = IppTag.getUri(ippBuf, "job-uri", stripPortNumber(url))
}
ippBuf = IppTag.getNameWithoutLanguage(ippBuf, "requesting-user-name", map["requesting-user-name"])
if (map["message"] != null) {
ippBuf = IppTag.getTextWithoutLanguage(ippBuf, "message", map["message"])
}
ippBuf = IppTag.getEnd(ippBuf)
ippBuf?.flip()
return ippBuf
}
@Throws(Exception::class)
fun cancelJob(url: URL, userName: String?, jobID: Int): Boolean {
val requestUrl = URL(url.toString() + "/jobs/" + Integer.toString(jobID))
val map = HashMap<String, String>()
map["requesting-user-name"] = userName?:CupsClient.DEFAULT_USER
map["job-uri"] = requestUrl.toString()
return PrintRequestResult(request(requestUrl, map)).isSuccessfulResult
}
}
| lgpl-3.0 | b9463fd7d5c4950d1ce0b28ba9bf4b43 | 32.012048 | 107 | 0.675547 | 3.864598 | false | false | false | false |
arcao/Geocaching4Locus | geocaching-api/src/main/java/com/arcao/geocaching4locus/data/api/model/request/GeocacheTrackableExpand.kt | 1 | 1149 | package com.arcao.geocaching4locus.data.api.model.request
import com.arcao.geocaching4locus.data.api.model.request.Expand.Companion.EXPAND_FIELD_IMAGES
import com.arcao.geocaching4locus.data.api.model.request.Expand.Companion.EXPAND_FIELD_TRACKABLE_LOGS
import com.arcao.geocaching4locus.data.api.model.request.Expand.Companion.EXPAND_FIELD_TRACKABLE_LOG_IMAGES
class GeocacheTrackableExpand : Expand<GeocacheTrackableExpand> {
var images: Int? = null
var trackableLogs: Int? = null
var trackableLogsImages: Int? = null
override fun all(): GeocacheTrackableExpand {
images = 0
trackableLogs = 0
trackableLogsImages = 0
return this
}
override fun toString(): String {
val items = ArrayList<String>(3)
images?.run {
items.add(EXPAND_FIELD_IMAGES.expand(this))
}
trackableLogs?.run {
items.add(EXPAND_FIELD_TRACKABLE_LOGS.expand(this))
}
trackableLogsImages?.run {
items.add(EXPAND_FIELD_TRACKABLE_LOG_IMAGES.expand(this))
}
return items.joinToString(Expand.EXPAND_FIELD_SEPARATOR)
}
}
| gpl-3.0 | ac6c564066a7b5218091eb8f52c50375 | 32.794118 | 107 | 0.691036 | 3.894915 | false | false | false | false |
lice-lang/lice | src/main/kotlin/org/lice/parse/ASTNode.kt | 1 | 2245 | package org.lice.parse
import org.lice.core.SymbolList
import org.lice.model.*
import org.lice.util.ParseException
import java.util.*
abstract class ASTNode internal constructor(val metaData: MetaData) {
abstract fun accept(symbolList: SymbolList): Node
}
class ASTAtomicNode internal constructor(metaData: MetaData, private val token: Token) : ASTNode(metaData) {
override fun accept(symbolList: SymbolList) = when (token.type) {
Token.TokenType.BinNumber -> ValueNode(token.strValue.toBinInt(), metaData)
Token.TokenType.OctNumber -> ValueNode(token.strValue.toOctInt(), metaData)
Token.TokenType.HexNumber -> ValueNode(token.strValue.toHexInt(), metaData)
Token.TokenType.DecNumber -> ValueNode(token.strValue.toInt(), metaData)
Token.TokenType.LongInteger -> ValueNode(token.strValue.toLong(), metaData)
Token.TokenType.ShortInteger -> ValueNode(token.strValue.toInt(), metaData)
Token.TokenType.Byte -> ValueNode(token.strValue.toInt(), metaData)
Token.TokenType.BigInt -> ValueNode(token.strValue.toBigInt(), metaData)
Token.TokenType.BigDec -> ValueNode(token.strValue.toBigDec(), metaData)
Token.TokenType.FloatNumber -> ValueNode(token.strValue.toFloat(), metaData)
Token.TokenType.DoubleNumber -> ValueNode(token.strValue.toDouble(), metaData)
Token.TokenType.StringLiteral -> ValueNode(token.strValue, metaData)
Token.TokenType.Identifier -> SymbolNode(symbolList, token.strValue, metaData)
Token.TokenType.LispKwd, Token.TokenType.EOI ->
throw ParseException("Unexpected token '${token.strValue}'", metaData)
}
}
class ASTRootNode(private val subNodes: ArrayList<ASTNode>) : ASTNode(MetaData()) {
override fun accept(symbolList: SymbolList) = ExpressionNode(
SymbolNode(symbolList, "", metaData), metaData, subNodes.map { it.accept(symbolList) })
}
class ASTListNode(lParthMetaData: MetaData, private val subNodes: ArrayList<ASTNode>) : ASTNode(lParthMetaData) {
override fun accept(symbolList: SymbolList) = if (subNodes.size > 0) {
val first = subNodes[0]
val mapFirstResult = first.accept(symbolList)
mapFirstResult as? ValueNode ?: ExpressionNode(mapFirstResult, metaData,
(1 until subNodes.size).map { subNodes[it].accept(symbolList) })
} else ValueNode(null, metaData)
}
| gpl-3.0 | 31db7caf421768101d06d10b36ebf843 | 48.888889 | 113 | 0.771938 | 3.729236 | false | false | false | false |
cketti/k-9 | app/core/src/main/java/com/fsck/k9/K9.kt | 1 | 18672 | package com.fsck.k9
import android.content.Context
import android.content.SharedPreferences
import com.fsck.k9.Account.SortType
import com.fsck.k9.core.BuildConfig
import com.fsck.k9.mail.K9MailLib
import com.fsck.k9.mailstore.LocalStore
import com.fsck.k9.preferences.RealGeneralSettingsManager
import com.fsck.k9.preferences.Storage
import com.fsck.k9.preferences.StorageEditor
import timber.log.Timber
import timber.log.Timber.DebugTree
@Deprecated("Use GeneralSettingsManager and GeneralSettings instead")
object K9 : EarlyInit {
private val generalSettingsManager: RealGeneralSettingsManager by inject()
/**
* If this is `true`, various development settings will be enabled.
*/
@JvmField
val DEVELOPER_MODE = BuildConfig.DEBUG
/**
* Name of the [SharedPreferences] file used to store the last known version of the
* accounts' databases.
*
* See `UpgradeDatabases` for a detailed explanation of the database upgrade process.
*/
private const val DATABASE_VERSION_CACHE = "database_version_cache"
/**
* Key used to store the last known database version of the accounts' databases.
*
* @see DATABASE_VERSION_CACHE
*/
private const val KEY_LAST_ACCOUNT_DATABASE_VERSION = "last_account_database_version"
/**
* A reference to the [SharedPreferences] used for caching the last known database version.
*
* @see checkCachedDatabaseVersion
* @see setDatabasesUpToDate
*/
private var databaseVersionCache: SharedPreferences? = null
/**
* @see areDatabasesUpToDate
*/
private var databasesUpToDate = false
/**
* Check if we already know whether all databases are using the current database schema.
*
* This method is only used for optimizations. If it returns `true` we can be certain that getting a [LocalStore]
* instance won't trigger a schema upgrade.
*
* @return `true`, if we know that all databases are using the current database schema. `false`, otherwise.
*/
@Synchronized
@JvmStatic
fun areDatabasesUpToDate(): Boolean {
return databasesUpToDate
}
/**
* Remember that all account databases are using the most recent database schema.
*
* @param save
* Whether or not to write the current database version to the
* `SharedPreferences` [.DATABASE_VERSION_CACHE].
*
* @see .areDatabasesUpToDate
*/
@Synchronized
@JvmStatic
fun setDatabasesUpToDate(save: Boolean) {
databasesUpToDate = true
if (save) {
val editor = databaseVersionCache!!.edit()
editor.putInt(KEY_LAST_ACCOUNT_DATABASE_VERSION, LocalStore.getDbVersion())
editor.apply()
}
}
/**
* Loads the last known database version of the accounts' databases from a `SharedPreference`.
*
* If the stored version matches [LocalStore.getDbVersion] we know that the databases are up to date.
* Using `SharedPreferences` should be a lot faster than opening all SQLite databases to get the current database
* version.
*
* See the class `UpgradeDatabases` for a detailed explanation of the database upgrade process.
*
* @see areDatabasesUpToDate
*/
private fun checkCachedDatabaseVersion(context: Context) {
databaseVersionCache = context.getSharedPreferences(DATABASE_VERSION_CACHE, Context.MODE_PRIVATE)
val cachedVersion = databaseVersionCache!!.getInt(KEY_LAST_ACCOUNT_DATABASE_VERSION, 0)
if (cachedVersion >= LocalStore.getDbVersion()) {
setDatabasesUpToDate(false)
}
}
@JvmStatic
var isDebugLoggingEnabled: Boolean = DEVELOPER_MODE
set(debug) {
field = debug
updateLoggingStatus()
}
@JvmStatic
var isSensitiveDebugLoggingEnabled: Boolean = false
@JvmStatic
var k9Language = ""
@JvmStatic
val fontSizes = FontSizes()
@JvmStatic
var backgroundOps = BACKGROUND_OPS.ALWAYS
@JvmStatic
var isShowAnimations = true
@JvmStatic
var isConfirmDelete = false
@JvmStatic
var isConfirmDiscardMessage = true
@JvmStatic
var isConfirmDeleteStarred = false
@JvmStatic
var isConfirmSpam = false
@JvmStatic
var isConfirmDeleteFromNotification = true
@JvmStatic
var isConfirmMarkAllRead = true
@JvmStatic
var notificationQuickDeleteBehaviour = NotificationQuickDelete.ALWAYS
@JvmStatic
var lockScreenNotificationVisibility = LockScreenNotificationVisibility.MESSAGE_COUNT
@JvmStatic
var isShowMessageListStars = true
@JvmStatic
var messageListPreviewLines = 2
@JvmStatic
var isShowCorrespondentNames = true
@JvmStatic
var isMessageListSenderAboveSubject = false
@JvmStatic
var isShowContactName = false
@JvmStatic
var isChangeContactNameColor = false
@JvmStatic
var contactNameColor = 0xFF1093F5.toInt()
@JvmStatic
var isShowContactPicture = true
@JvmStatic
var isUseMessageViewFixedWidthFont = false
@JvmStatic
var isMessageViewReturnToList = false
@JvmStatic
var isMessageViewShowNext = false
@JvmStatic
var isUseVolumeKeysForNavigation = false
@JvmStatic
var isShowUnifiedInbox = true
@JvmStatic
var isShowStarredCount = false
@JvmStatic
var isAutoFitWidth: Boolean = false
var isQuietTimeEnabled = false
var isNotificationDuringQuietTimeEnabled = true
var quietTimeStarts: String? = null
var quietTimeEnds: String? = null
@JvmStatic
var isHideUserAgent = false
@JvmStatic
var isHideTimeZone = false
@get:Synchronized
@set:Synchronized
@JvmStatic
var sortType: SortType = Account.DEFAULT_SORT_TYPE
private val sortAscending = mutableMapOf<SortType, Boolean>()
@JvmStatic
var isUseBackgroundAsUnreadIndicator = false
@get:Synchronized
@set:Synchronized
@JvmStatic
var isThreadedViewEnabled = true
@get:Synchronized
@set:Synchronized
@JvmStatic
var splitViewMode = SplitViewMode.NEVER
var isColorizeMissingContactPictures = true
@JvmStatic
var isMessageViewArchiveActionVisible = false
@JvmStatic
var isMessageViewDeleteActionVisible = true
@JvmStatic
var isMessageViewMoveActionVisible = false
@JvmStatic
var isMessageViewCopyActionVisible = false
@JvmStatic
var isMessageViewSpamActionVisible = false
@JvmStatic
var pgpInlineDialogCounter: Int = 0
@JvmStatic
var pgpSignOnlyDialogCounter: Int = 0
@JvmStatic
var swipeRightAction: SwipeAction = SwipeAction.ToggleSelection
@JvmStatic
var swipeLeftAction: SwipeAction = SwipeAction.ToggleRead
val isQuietTime: Boolean
get() {
if (!isQuietTimeEnabled) {
return false
}
val clock = DI.get<Clock>()
val quietTimeChecker = QuietTimeChecker(clock, quietTimeStarts, quietTimeEnds)
return quietTimeChecker.isQuietTime
}
@Synchronized
@JvmStatic
fun isSortAscending(sortType: SortType): Boolean {
if (sortAscending[sortType] == null) {
sortAscending[sortType] = sortType.isDefaultAscending
}
return sortAscending[sortType]!!
}
@Synchronized
@JvmStatic
fun setSortAscending(sortType: SortType, sortAscending: Boolean) {
K9.sortAscending[sortType] = sortAscending
}
fun init(context: Context) {
K9MailLib.setDebugStatus(object : K9MailLib.DebugStatus {
override fun enabled(): Boolean = isDebugLoggingEnabled
override fun debugSensitive(): Boolean = isSensitiveDebugLoggingEnabled
})
com.fsck.k9.logging.Timber.logger = TimberLogger()
checkCachedDatabaseVersion(context)
loadPrefs(generalSettingsManager.storage)
}
@JvmStatic
fun loadPrefs(storage: Storage) {
isDebugLoggingEnabled = storage.getBoolean("enableDebugLogging", DEVELOPER_MODE)
isSensitiveDebugLoggingEnabled = storage.getBoolean("enableSensitiveLogging", false)
isShowAnimations = storage.getBoolean("animations", true)
isUseVolumeKeysForNavigation = storage.getBoolean("useVolumeKeysForNavigation", false)
isShowUnifiedInbox = storage.getBoolean("showUnifiedInbox", true)
isShowStarredCount = storage.getBoolean("showStarredCount", false)
isMessageListSenderAboveSubject = storage.getBoolean("messageListSenderAboveSubject", false)
isShowMessageListStars = storage.getBoolean("messageListStars", true)
messageListPreviewLines = storage.getInt("messageListPreviewLines", 2)
isAutoFitWidth = storage.getBoolean("autofitWidth", true)
isQuietTimeEnabled = storage.getBoolean("quietTimeEnabled", false)
isNotificationDuringQuietTimeEnabled = storage.getBoolean("notificationDuringQuietTimeEnabled", true)
quietTimeStarts = storage.getString("quietTimeStarts", "21:00")
quietTimeEnds = storage.getString("quietTimeEnds", "7:00")
isShowCorrespondentNames = storage.getBoolean("showCorrespondentNames", true)
isShowContactName = storage.getBoolean("showContactName", false)
isShowContactPicture = storage.getBoolean("showContactPicture", true)
isChangeContactNameColor = storage.getBoolean("changeRegisteredNameColor", false)
contactNameColor = storage.getInt("registeredNameColor", 0xFF1093F5.toInt())
isUseMessageViewFixedWidthFont = storage.getBoolean("messageViewFixedWidthFont", false)
isMessageViewReturnToList = storage.getBoolean("messageViewReturnToList", false)
isMessageViewShowNext = storage.getBoolean("messageViewShowNext", false)
isHideUserAgent = storage.getBoolean("hideUserAgent", false)
isHideTimeZone = storage.getBoolean("hideTimeZone", false)
isConfirmDelete = storage.getBoolean("confirmDelete", false)
isConfirmDiscardMessage = storage.getBoolean("confirmDiscardMessage", true)
isConfirmDeleteStarred = storage.getBoolean("confirmDeleteStarred", false)
isConfirmSpam = storage.getBoolean("confirmSpam", false)
isConfirmDeleteFromNotification = storage.getBoolean("confirmDeleteFromNotification", true)
isConfirmMarkAllRead = storage.getBoolean("confirmMarkAllRead", true)
sortType = storage.getEnum("sortTypeEnum", Account.DEFAULT_SORT_TYPE)
val sortAscendingSetting = storage.getBoolean("sortAscending", Account.DEFAULT_SORT_ASCENDING)
sortAscending[sortType] = sortAscendingSetting
notificationQuickDeleteBehaviour = storage.getEnum("notificationQuickDelete", NotificationQuickDelete.ALWAYS)
lockScreenNotificationVisibility = storage.getEnum(
"lockScreenNotificationVisibility",
LockScreenNotificationVisibility.MESSAGE_COUNT
)
splitViewMode = storage.getEnum("splitViewMode", SplitViewMode.NEVER)
isUseBackgroundAsUnreadIndicator = storage.getBoolean("useBackgroundAsUnreadIndicator", false)
isThreadedViewEnabled = storage.getBoolean("threadedView", true)
fontSizes.load(storage)
backgroundOps = storage.getEnum("backgroundOperations", BACKGROUND_OPS.ALWAYS)
isColorizeMissingContactPictures = storage.getBoolean("colorizeMissingContactPictures", true)
isMessageViewArchiveActionVisible = storage.getBoolean("messageViewArchiveActionVisible", false)
isMessageViewDeleteActionVisible = storage.getBoolean("messageViewDeleteActionVisible", true)
isMessageViewMoveActionVisible = storage.getBoolean("messageViewMoveActionVisible", false)
isMessageViewCopyActionVisible = storage.getBoolean("messageViewCopyActionVisible", false)
isMessageViewSpamActionVisible = storage.getBoolean("messageViewSpamActionVisible", false)
pgpInlineDialogCounter = storage.getInt("pgpInlineDialogCounter", 0)
pgpSignOnlyDialogCounter = storage.getInt("pgpSignOnlyDialogCounter", 0)
k9Language = storage.getString("language", "")
swipeRightAction = storage.getEnum("swipeRightAction", SwipeAction.ToggleSelection)
swipeLeftAction = storage.getEnum("swipeLeftAction", SwipeAction.ToggleRead)
}
internal fun save(editor: StorageEditor) {
editor.putBoolean("enableDebugLogging", isDebugLoggingEnabled)
editor.putBoolean("enableSensitiveLogging", isSensitiveDebugLoggingEnabled)
editor.putEnum("backgroundOperations", backgroundOps)
editor.putBoolean("animations", isShowAnimations)
editor.putBoolean("useVolumeKeysForNavigation", isUseVolumeKeysForNavigation)
editor.putBoolean("autofitWidth", isAutoFitWidth)
editor.putBoolean("quietTimeEnabled", isQuietTimeEnabled)
editor.putBoolean("notificationDuringQuietTimeEnabled", isNotificationDuringQuietTimeEnabled)
editor.putString("quietTimeStarts", quietTimeStarts)
editor.putString("quietTimeEnds", quietTimeEnds)
editor.putBoolean("messageListSenderAboveSubject", isMessageListSenderAboveSubject)
editor.putBoolean("showUnifiedInbox", isShowUnifiedInbox)
editor.putBoolean("showStarredCount", isShowStarredCount)
editor.putBoolean("messageListStars", isShowMessageListStars)
editor.putInt("messageListPreviewLines", messageListPreviewLines)
editor.putBoolean("showCorrespondentNames", isShowCorrespondentNames)
editor.putBoolean("showContactName", isShowContactName)
editor.putBoolean("showContactPicture", isShowContactPicture)
editor.putBoolean("changeRegisteredNameColor", isChangeContactNameColor)
editor.putInt("registeredNameColor", contactNameColor)
editor.putBoolean("messageViewFixedWidthFont", isUseMessageViewFixedWidthFont)
editor.putBoolean("messageViewReturnToList", isMessageViewReturnToList)
editor.putBoolean("messageViewShowNext", isMessageViewShowNext)
editor.putBoolean("hideUserAgent", isHideUserAgent)
editor.putBoolean("hideTimeZone", isHideTimeZone)
editor.putString("language", k9Language)
editor.putBoolean("confirmDelete", isConfirmDelete)
editor.putBoolean("confirmDiscardMessage", isConfirmDiscardMessage)
editor.putBoolean("confirmDeleteStarred", isConfirmDeleteStarred)
editor.putBoolean("confirmSpam", isConfirmSpam)
editor.putBoolean("confirmDeleteFromNotification", isConfirmDeleteFromNotification)
editor.putBoolean("confirmMarkAllRead", isConfirmMarkAllRead)
editor.putEnum("sortTypeEnum", sortType)
editor.putBoolean("sortAscending", sortAscending[sortType] ?: false)
editor.putString("notificationQuickDelete", notificationQuickDeleteBehaviour.toString())
editor.putString("lockScreenNotificationVisibility", lockScreenNotificationVisibility.toString())
editor.putBoolean("useBackgroundAsUnreadIndicator", isUseBackgroundAsUnreadIndicator)
editor.putBoolean("threadedView", isThreadedViewEnabled)
editor.putEnum("splitViewMode", splitViewMode)
editor.putBoolean("colorizeMissingContactPictures", isColorizeMissingContactPictures)
editor.putBoolean("messageViewArchiveActionVisible", isMessageViewArchiveActionVisible)
editor.putBoolean("messageViewDeleteActionVisible", isMessageViewDeleteActionVisible)
editor.putBoolean("messageViewMoveActionVisible", isMessageViewMoveActionVisible)
editor.putBoolean("messageViewCopyActionVisible", isMessageViewCopyActionVisible)
editor.putBoolean("messageViewSpamActionVisible", isMessageViewSpamActionVisible)
editor.putInt("pgpInlineDialogCounter", pgpInlineDialogCounter)
editor.putInt("pgpSignOnlyDialogCounter", pgpSignOnlyDialogCounter)
editor.putEnum("swipeRightAction", swipeRightAction)
editor.putEnum("swipeLeftAction", swipeLeftAction)
fontSizes.save(editor)
}
private fun updateLoggingStatus() {
Timber.uprootAll()
if (isDebugLoggingEnabled) {
Timber.plant(DebugTree())
}
}
@JvmStatic
fun saveSettingsAsync() {
generalSettingsManager.saveSettingsAsync()
}
private inline fun <reified T : Enum<T>> Storage.getEnum(key: String, defaultValue: T): T {
return try {
val value = getString(key, null)
if (value != null) {
enumValueOf(value)
} else {
defaultValue
}
} catch (e: Exception) {
Timber.e("Couldn't read setting '%s'. Using default value instead.", key)
defaultValue
}
}
private fun <T : Enum<T>> StorageEditor.putEnum(key: String, value: T) {
putString(key, value.name)
}
const val LOCAL_UID_PREFIX = "K9LOCAL:"
const val IDENTITY_HEADER = K9MailLib.IDENTITY_HEADER
/**
* Specifies how many messages will be shown in a folder by default. This number is set
* on each new folder and can be incremented with "Load more messages..." by the
* VISIBLE_LIMIT_INCREMENT
*/
const val DEFAULT_VISIBLE_LIMIT = 25
/**
* The maximum size of an attachment we're willing to download (either View or Save)
* Attachments that are base64 encoded (most) will be about 1.375x their actual size
* so we should probably factor that in. A 5MB attachment will generally be around
* 6.8MB downloaded but only 5MB saved.
*/
const val MAX_ATTACHMENT_DOWNLOAD_SIZE = 128 * 1024 * 1024
/**
* How many times should K-9 try to deliver a message before giving up until the app is killed and restarted
*/
const val MAX_SEND_ATTEMPTS = 5
const val MANUAL_WAKE_LOCK_TIMEOUT = 120000
const val PUSH_WAKE_LOCK_TIMEOUT = K9MailLib.PUSH_WAKE_LOCK_TIMEOUT
const val MAIL_SERVICE_WAKE_LOCK_TIMEOUT = 60000
const val BOOT_RECEIVER_WAKE_LOCK_TIMEOUT = 60000
enum class BACKGROUND_OPS {
ALWAYS, NEVER, WHEN_CHECKED_AUTO_SYNC
}
/**
* Controls behaviour of delete button in notifications.
*/
enum class NotificationQuickDelete {
ALWAYS,
FOR_SINGLE_MSG,
NEVER
}
enum class LockScreenNotificationVisibility {
EVERYTHING,
SENDERS,
MESSAGE_COUNT,
APP_NAME,
NOTHING
}
/**
* Controls when to use the message list split view.
*/
enum class SplitViewMode {
ALWAYS,
NEVER,
WHEN_IN_LANDSCAPE
}
}
| apache-2.0 | 2f1fdb7b6702c654e93e23a06136a91d | 34.701721 | 117 | 0.713689 | 5.009928 | false | false | false | false |
nickthecoder/tickle | tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/scene/SnapToGuides.kt | 1 | 3646 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.editor.scene
import uk.co.nickthecoder.paratask.AbstractTask
import uk.co.nickthecoder.paratask.TaskDescription
import uk.co.nickthecoder.paratask.parameters.BooleanParameter
import uk.co.nickthecoder.paratask.parameters.DoubleParameter
import uk.co.nickthecoder.paratask.parameters.InformationParameter
import uk.co.nickthecoder.paratask.parameters.MultipleParameter
import uk.co.nickthecoder.tickle.editor.EditorActions
import uk.co.nickthecoder.tickle.editor.resources.DesignActorResource
class SnapToGuides : SnapTo {
var enabled: Boolean = true
val xGuides = mutableListOf<Double>()
val yGuides = mutableListOf<Double>()
var closeness = 5.0
private val adjustment = Adjustment()
override fun snapActor(actorResource: DesignActorResource, adjustments: MutableList<Adjustment>) {
if (enabled == false) return
adjustment.reset()
xGuides.forEach { xGuide ->
val dx = xGuide - actorResource.x
if (dx > -closeness && dx < closeness) {
adjustment.x = dx
adjustment.score = Math.abs(dx) + closeness
}
}
yGuides.forEach { yGuide ->
val dy = yGuide - actorResource.y
if (dy > -closeness && dy < closeness) {
adjustment.y = dy
adjustment.score = if (adjustment.score == Double.MAX_VALUE) Math.abs(dy) + closeness else adjustment.score + Math.abs(dy)
}
}
if (adjustment.score != Double.MAX_VALUE) {
adjustments.add(adjustment)
}
}
override fun task() = GuidesTask()
override fun toString(): String {
return "Guides enabled=$enabled closeness=$closeness x=$xGuides y=$yGuides"
}
inner class GuidesTask : AbstractTask() {
val enabledP = BooleanParameter("enabled", value = enabled)
val toggleInfoP = InformationParameter("toggleInfo",
information = "Note. You can toggle guide snapping using the keyboard shortcut : ${EditorActions.SNAP_TO_GUIDES_TOGGLE.shortcutLabel() ?: "<NONE>"}\n${snapInfo()}")
val xGuidesP = MultipleParameter("xGuides", value = xGuides, isBoxed = true) {
DoubleParameter("x")
}
val yGuidesP = MultipleParameter("yGuides", value = yGuides, isBoxed = true) {
DoubleParameter("x")
}
val closenessP = DoubleParameter("closeness", value = closeness)
override val taskD = TaskDescription("editGuides")
.addParameters(enabledP, toggleInfoP, xGuidesP, yGuidesP, closenessP)
init {
xGuidesP.value = xGuides
}
override fun run() {
xGuides.clear()
yGuides.clear()
xGuidesP.value.forEach { xGuides.add(it!!) }
yGuidesP.value.forEach { yGuides.add(it!!) }
closeness = closenessP.value!!
enabled = enabledP.value!!
}
}
}
| gpl-3.0 | 65ede8af3dd7c768f6408320102ba9d3 | 32.145455 | 180 | 0.661547 | 4.392771 | false | false | false | false |
cketti/k-9 | app/ui/base/src/main/java/com/fsck/k9/ui/base/extensions/TextInputLayoutExtensions.kt | 1 | 5292 | @file:JvmName("TextInputLayoutHelper")
package com.fsck.k9.ui.base.extensions
import android.annotation.SuppressLint
import android.text.method.PasswordTransformationMethod
import android.view.WindowManager.LayoutParams.FLAG_SECURE
import android.widget.EditText
import android.widget.Toast
import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG
import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_WEAK
import androidx.biometric.BiometricManager.Authenticators.DEVICE_CREDENTIAL
import androidx.biometric.BiometricPrompt
import androidx.core.content.ContextCompat
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.get
import com.google.android.material.textfield.TextInputLayout
/**
* Configures a [TextInputLayout] so the password can only be revealed after authentication.
*
* **IMPORTANT**: Only call this after the instance state has been restored! Otherwise, restoring the previous state
* after the initial state has been set will be detected as replacing the whole text. In that case showing the password
* will be allowed without authentication.
*/
fun TextInputLayout.configureAuthenticatedPasswordToggle(
activity: FragmentActivity,
title: String,
subtitle: String,
needScreenLockMessage: String,
) {
val viewModel = ViewModelProvider(activity).get<AuthenticatedPasswordToggleViewModel>()
viewModel.textInputLayout = this
viewModel.activity = activity
fun authenticateUserAndShowPassword(activity: FragmentActivity) {
val mainExecutor = ContextCompat.getMainExecutor(activity)
val context = activity.applicationContext
val authenticationCallback = object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
// The Activity might have been recreated since this callback object was created (e.g. due to an
// orientation change). So we fetch the (new) references from the ViewModel.
viewModel.isAuthenticated = true
viewModel.activity?.setSecure(true)
viewModel.textInputLayout?.editText?.showPassword()
}
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
if (errorCode == BiometricPrompt.ERROR_HW_NOT_PRESENT ||
errorCode == BiometricPrompt.ERROR_NO_DEVICE_CREDENTIAL ||
errorCode == BiometricPrompt.ERROR_NO_BIOMETRICS
) {
Toast.makeText(context, needScreenLockMessage, Toast.LENGTH_SHORT).show()
} else if (errString.isNotEmpty()) {
Toast.makeText(context, errString, Toast.LENGTH_SHORT).show()
}
}
}
BiometricPrompt(activity, mainExecutor, authenticationCallback).authenticate(
BiometricPrompt.PromptInfo.Builder()
.setAllowedAuthenticators(BIOMETRIC_STRONG or BIOMETRIC_WEAK or DEVICE_CREDENTIAL)
.setTitle(title)
.setSubtitle(subtitle)
.build()
)
}
val editText = this.editText ?: error("TextInputLayout.editText == null")
editText.doOnTextChanged { text, _, before, count ->
// Check if the password field is empty or if all of the previous text was replaced
if (text != null && before > 0 && (text.isEmpty() || text.length - count == 0)) {
viewModel.isNewPassword = true
}
}
setEndIconOnClickListener {
if (editText.isPasswordHidden) {
if (viewModel.isShowPasswordAllowed) {
activity.setSecure(true)
editText.showPassword()
} else {
authenticateUserAndShowPassword(activity)
}
} else {
viewModel.isAuthenticated = false
editText.hidePassword()
activity.setSecure(false)
}
}
}
private val EditText.isPasswordHidden: Boolean
get() = transformationMethod is PasswordTransformationMethod
private fun EditText.showPassword() {
transformationMethod = null
}
private fun EditText.hidePassword() {
transformationMethod = PasswordTransformationMethod.getInstance()
}
private fun FragmentActivity.setSecure(secure: Boolean) {
window.setFlags(if (secure) FLAG_SECURE else 0, FLAG_SECURE)
}
@SuppressLint("StaticFieldLeak")
class AuthenticatedPasswordToggleViewModel : ViewModel() {
val isShowPasswordAllowed: Boolean
get() = isAuthenticated || isNewPassword
var isNewPassword = false
var isAuthenticated = false
var textInputLayout: TextInputLayout? = null
var activity: FragmentActivity? = null
set(value) {
field = value
value?.lifecycle?.addObserver(object : DefaultLifecycleObserver {
override fun onDestroy(owner: LifecycleOwner) {
textInputLayout = null
field = null
}
})
}
}
| apache-2.0 | a5e51b30c98514a2067888f741459918 | 38.492537 | 119 | 0.691799 | 5.313253 | false | false | false | false |
kittinunf/ReactiveAndroid | reactiveandroid-support-v4/src/main/kotlin/com/github/kittinunf/reactiveandroid/support/v4/widget/FragmentPagerExtension.kt | 1 | 1947 | package com.github.kittinunf.reactiveandroid.support.v4.widget
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import com.github.kittinunf.reactiveandroid.scheduler.AndroidThreadScheduler
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
abstract class FragmentPagerProxyAdapter<ARG>(fragmentManager: FragmentManager) : FragmentPagerAdapter(fragmentManager) {
internal var items: List<ARG> = listOf()
abstract var pageTitle: ((Int, ARG) -> String)
abstract var item: ((Int, ARG) -> Fragment)
override fun getItem(position: Int): Fragment? = item.invoke(position, items[position])
override fun getPageTitle(position: Int): CharSequence? = pageTitle.invoke(position, items[position])
override fun getCount(): Int = items.size
override fun getItemId(position: Int): Long = position.toLong()
}
fun <ARG, L : List<ARG>> ViewPager.rx_fragmentsWith(observable: Observable<L>, fragmentManager: FragmentManager,
getItem: (Int, ARG) -> Fragment,
getPageTitle: ((Int, ARG) -> String)): Disposable {
val proxyAdapter = object : FragmentPagerProxyAdapter<ARG>(fragmentManager) {
override var item: (Int, ARG) -> Fragment = getItem
override var pageTitle: ((Int, ARG) -> String) = getPageTitle
}
return rx_fragmentsWith(observable, proxyAdapter)
}
fun <ARG, ADT : FragmentPagerProxyAdapter<ARG>, L : List<ARG>> ViewPager.rx_fragmentsWith(observable: Observable<L>, fragmentPagerProxyAdapter: ADT): Disposable {
adapter = fragmentPagerProxyAdapter
return observable.observeOn(AndroidThreadScheduler.main).subscribe {
fragmentPagerProxyAdapter.items = it
fragmentPagerProxyAdapter.notifyDataSetChanged()
}
}
| mit | aa1436506042081cc717268611bde3bf | 40.425532 | 162 | 0.717514 | 4.635714 | false | false | false | false |
klose911/klose911.github.io | src/kotlin/src/tutorial/introduction/InnerClass.kt | 1 | 445 | package tutorial.introduction
private class OuterNested {
private val bar: Int = 1
class Nested {
fun foo() = 2
}
}
private val demo1 = OuterNested.Nested().foo() // == 2
private class OuterInner {
private val bar: Int = 1
inner class Inner {
fun foo() = bar
}
}
private val demo2 = OuterInner().Inner().foo() // == 1
fun main() {
println("out nested: $demo1")
println("out nested: $demo2")
} | bsd-2-clause | a37c1cb0f95816a3129330ccd5a679b0 | 17.583333 | 54 | 0.6 | 3.56 | false | false | false | false |
MaibornWolff/codecharta | analysis/import/CodeMaatImporter/src/test/kotlin/de/maibornwolff/codecharta/importer/codemaat/CodeMaatImporterTest.kt | 1 | 1956 | package de.maibornwolff.codecharta.importer.codemaat
import de.maibornwolff.codecharta.importer.codemaat.CodeMaatImporter.Companion.main
import de.maibornwolff.codecharta.serialization.ProjectDeserializer
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.io.File
class CodeMaatImporterTest {
@Test
fun `should create json uncompressed file`() {
main(
arrayOf(
"src/test/resources/coupling-codemaat.csv",
"-nc",
"-o=src/test/resources/coupling-codemaat.cc.json"
)
)
val file = File("src/test/resources/coupling-codemaat.cc.json")
file.deleteOnExit()
assertTrue(file.exists())
}
@Test
fun `should create json gzip file`() {
main(
arrayOf(
"src/test/resources/coupling-codemaat.csv",
"-o=src/test/resources/coupling-codemaat.cc.json"
)
)
val file = File("src/test/resources/coupling-codemaat.cc.json.gz")
file.deleteOnExit()
assertTrue(file.exists())
}
@Test
fun `should contain expected content`() {
main(
arrayOf(
"src/test/resources/coupling-codemaat.csv",
"-nc",
"-o=src/test/resources/coupling-codemaat-content.cc.json"
)
)
val file = File("src/test/resources/coupling-codemaat-content.cc.json")
file.deleteOnExit()
assertThat(file.readText()).contains("\"avgCommits\":5")
assertThat(file.readText()).contains(listOf("attributeDescriptors", "\"description\":\"Average"))
assertEquals(ProjectDeserializer.deserializeProject(file.reader()).attributeDescriptors, getAttributeDescriptors())
}
}
| bsd-3-clause | 4e8ff211014d56713b29ce0113317016 | 32.724138 | 123 | 0.622699 | 4.206452 | false | true | false | false |
eugeis/ee | ee-lang/src/main/kotlin/ee/lang/gen/proto/ProtoContextUtils.kt | 1 | 6150 | package ee.lang.gen.proto
import ee.common.ext.*
import ee.lang.*
import ee.lang.gen.common.LangCommonContextFactory
import java.nio.file.Path
open class ProtoContextBuilder<M>(name: String, macroController: MacroController, builder: M.() -> ProtoContext)
: ContextBuilder<M>(name, macroController, builder)
open class LangProtoContextFactory(targetAsSingleModule: Boolean = true) : LangCommonContextFactory(targetAsSingleModule) {
open fun buildForImplOnly(scope: String = "main"): ContextBuilder<StructureUnitI<*>> {
val derivedController = DerivedController()
registerForImplOnly(derivedController)
return contextBuilder(derivedController, scope)
}
protected open fun contextBuilder(derived: DerivedController, scope: String): ProtoContextBuilder<StructureUnitI<*>> {
return ProtoContextBuilder(CONTEXT_PROTO, macroController) {
val structureUnit = this
ProtoContext(namespace = structureUnit.namespace().toLowerCase(), moduleFolder = computeModuleFolder(),
derivedController = derived, macroController = macroController)
}
}
override fun buildName(item: ItemI<*>, kind: String): String {
return if (item is ConstructorI) {
buildNameForConstructor(item, kind)
} else if (item is OperationI) {
buildNameForOperation(item, kind)
} else {
super.buildName(item, kind)
}
}
override fun buildNameForOperation(item: OperationI<*>, kind: String): String {
return buildNameCommon(item, kind).capitalize()
}
companion object {
const val CONTEXT_PROTO = "proto"
}
}
open class ProtoContext(
namespace: String = "", moduleFolder: String = "", genFolder: String = "",
genFolderDeletable: Boolean = false, genFolderPatternDeletable: Regex? = ".*_base.proto".toRegex(),
derivedController: DerivedController, macroController: MacroController)
: GenerationContext(namespace, moduleFolder, genFolder, genFolderDeletable,
genFolderPatternDeletable, derivedController, macroController) {
private val namespaceLastPart: String = namespace.substringAfterLast(".")
override fun resolveFolder(base: Path): Path {
return base.resolve(genFolder)
}
override fun complete(content: String, indent: String): String {
return "${toHeader(indent)}${indent}syntax = \"proto3\";${nL}${toImports(indent)}${
toPackage(indent)}$content${toFooter(indent)}"
}
private fun toPackage(indent: String): String {
return namespace.isNotEmpty().then {
"""${indent}package ${namespace.toProtoPackage()};$nL${
indent}option java_package = "$namespace.proto";$nL${
indent}option go_package = "$namespaceLastPart";$nL$nL"""
}
}
private fun toImports(indent: String): String {
return types.isNotEmpty().then {
val outsideTypes = types.filter {
it.namespace().isNotEmpty() && !it.namespace().equals(namespace, true)
}
outsideTypes.isNotEmpty().then {
outsideTypes.sortedBy {
it.namespace()
}.map { "$indent${it.namespace().substringAfterLast(".")}" }.toSortedSet()
.joinSurroundIfNotEmptyToString("") {
"""import "${it.toLowerCase()}_base.proto";$nL"""
}
}
}
}
override fun n(item: ItemI<*>, derivedKind: String): String {
val derived = types.addReturn(derivedController.derive(item, derivedKind))
return if (derived.namespace().isEmpty() || derived.namespace().equals(namespace, true)) {
derived.name()
} else {
"${derived.namespace().toProtoPackage()}.${derived.name()}"
}
}
}
fun AttributeI<*>.nameForProtoMember(): String = storage.getOrPut(this, "nameForProtoMember", {
name().decapitalize()
})
val itemAndTemplateNameAsProtoFileName: TemplateI<*>.(CompositeI<*>) -> Names = {
Names("${it.name().toUnderscoredLowerCase()}_${name.toUnderscoredLowerCase()}.proto")
}
val templateNameAsProtoFileName: TemplateI<*>.(CompositeI<*>) -> Names = {
Names("${name.toUnderscoredLowerCase()}.proto")
}
val itemNameAsProtoFileName: TemplateI<*>.(CompositeI<*>) -> Names = {
Names("${it.name().toUnderscoredLowerCase()}.proto")
}
object proto : StructureUnit({ namespace("").name("Proto") }) {
val error = ExternalType { ifc(true) }
object errors : StructureUnit({ namespace("errors") }) {
val New = Operation { ret(error) }
}
object io : StructureUnit({ namespace("io") }) {
}
object time : StructureUnit({ namespace("time") }) {
val Time = ExternalType()
val Now = Operation()
}
object context : StructureUnit({ namespace("context") }) {
val Context = ExternalType { ifc(true) }
}
object net : StructureUnit({ namespace("net") }) {
object http : StructureUnit() {
val Client = ExternalType {}
}
}
object encoding : StructureUnit({ namespace("encoding") }) {
object json : StructureUnit() {
} val NewDecoder = Operation()
val Decoder = ExternalType()
val Marshal = Operation()
val Unmarshal = Operation()
}
//common libs
object gee : StructureUnit({ namespace("github.com.go-ee.utils") }) {
val PtrTime = Operation()
object enum : StructureUnit() {
val Literal = ExternalType()
}
object net : StructureUnit() {
val Command = ExternalType()
}
}
object google : StructureUnit({ namespace("github.com.google").name("google") }) {
object uuid : StructureUnit() {
object UUID : ExternalType()
object New : Operation()
}
}
object eh : StructureUnit({ namespace("github.com.looplab.eventhorizon").name("eh") }) {
object Command : ExternalType({ ifc(true) }) {}
object Entity : ExternalType({ ifc(true) }) {}
}
} | apache-2.0 | 795056cd42e0774322763c68f9e4b89f | 34.554913 | 123 | 0.620813 | 4.606742 | false | false | false | false |
jitsi/jitsi-videobridge | rtp/src/main/kotlin/org/jitsi/rtp/rtcp/RtcpRrPacket.kt | 1 | 4286 | /*
* Copyright @ 2018 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.rtp.rtcp
import org.jitsi.rtp.util.BufferPool
import org.jitsi.rtp.util.RtpUtils
/**
* https://tools.ietf.org/html/rfc3550#section-6.4.2
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* header |V=2|P| RC | PT=RR=201 | length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | SSRC of packet sender |
* +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
* report | SSRC_1 (SSRC of first source) |
* block +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* 1 | fraction lost | cumulative number of packets lost |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | extended highest sequence number received |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | interarrival jitter |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | last SR (LSR) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | delay since last SR (DLSR) |
* +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
* report | SSRC_2 (SSRC of second source) |
* block +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* 2 : ... :
* +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
* | profile-specific extensions |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
class RtcpRrPacket(
buffer: ByteArray,
offset: Int,
length: Int
) : RtcpPacket(buffer, offset, length) {
val reportBlocks: List<RtcpReportBlock> by lazy {
(0 until reportCount).map {
RtcpReportBlock.fromBuffer(buffer, offset + REPORT_BLOCKS_OFFSET + it * RtcpReportBlock.SIZE_BYTES)
}.toList()
}
override fun clone(): RtcpRrPacket = RtcpRrPacket(cloneBuffer(0), 0, length)
companion object {
const val PT = 201
const val REPORT_BLOCKS_OFFSET = 8
}
}
data class RtcpRrPacketBuilder(
var rtcpHeader: RtcpHeaderBuilder = RtcpHeaderBuilder(),
val reportBlocks: List<RtcpReportBlock> = listOf()
) {
init {
require(reportBlocks.size <= 31) { "Too many report blocks ${reportBlocks.size}: RR can contain at most 31" }
}
private fun getLengthValue(): Int =
RtpUtils.calculateRtcpLengthFieldValue(sizeBytes)
private val sizeBytes: Int
get() = RtcpHeader.SIZE_BYTES + reportBlocks.size * RtcpReportBlock.SIZE_BYTES
fun build(): RtcpRrPacket {
val buf = BufferPool.getArray(sizeBytes)
writeTo(buf, 0)
return RtcpRrPacket(buf, 0, sizeBytes)
}
fun writeTo(buf: ByteArray, offset: Int) {
rtcpHeader.apply {
packetType = RtcpRrPacket.PT
reportCount = reportBlocks.size
length = getLengthValue()
}.writeTo(buf, offset)
reportBlocks.forEachIndexed { index, reportBlock ->
reportBlock.writeTo(buf, offset + RtcpRrPacket.REPORT_BLOCKS_OFFSET + index * RtcpReportBlock.SIZE_BYTES)
}
}
}
| apache-2.0 | ac4f09090069c1e657ca53301c568377 | 41.435644 | 117 | 0.445637 | 4.364562 | false | false | false | false |
lanhuaguizha/Christian | app/src/main/java/com/christian/nav/disciple/ChatItemView.kt | 1 | 13841 | package com.christian.nav.disciple
import android.app.Activity
import android.content.Intent
import android.view.View
import android.view.animation.AnimationUtils
import androidx.appcompat.widget.AppCompatImageButton
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.christian.HistoryAndMyArticlesActivity
import com.christian.R
import com.christian.common.*
import com.christian.common.data.Gospel
import com.christian.data.Setting
import com.christian.databinding.ItemChatBinding
import com.christian.nav.gospel.GospelDetailActivity
import com.christian.nav.me.AboutActivity
import com.christian.nav.toolbarTitle
import com.christian.swipe.SwipeBackActivity
import com.christian.util.*
import com.christian.view.showPopupMenu
import org.jetbrains.anko.dip
/**
* NavItemView/NavItemHolder is view logic of nav items.
*/
open class ChatItemView(private val binding: ItemChatBinding,
swipeBackActivity: SwipeBackActivity,
navId: Int,
) : RecyclerView.ViewHolder(binding.root) {
init {
// containerView.login_nav_item.setOnClickListener {
// }
// when (adapterPosition) {
// 1 -> {
// itemView.setOnClickListener {
// if (isOn) {
// itemView.findViewById<Switch>(R.id.switch_nav_item_small).isChecked = false
// isOn = false
// } else {
// itemView.findViewById<Switch>(R.id.switch_nav_item_small).isChecked = true
// isOn = true
// }
// }
// }
// else -> {
// itemView.setOnClickListener {
// val i = Intent(itemView.context, NavDetailActivity::class.java)
// i.putExtra(toolbarTitle, presenter.getTitle(adapterPosition))
// itemView.context.startActivity(i)
// }
// }
// }
val displayWidth = getDisplayWidth(swipeBackActivity)
val displayHeight = getDisplayHeight(swipeBackActivity)
if (itemView.findViewById<AppCompatImageButton>(R.id.ib_nav_item) != null) itemView.findViewById<AppCompatImageButton>(
R.id.ib_nav_item
).setOnClickListener { v: View ->
// val list: ArrayList<CharSequence> = ArrayList()
// list.add(Html.fromHtml(containerView.context.getString(R.string.share)))
// list.add(Html.fromHtml(containerView.context.getString(R.string.favorite)))
// list.add(Html.fromHtml(containerView.context.getString(R.string.translate)))
// ChristianUtil.showListDialog(v.context as NavActivity, list)
// showPopupMenu(v)
val array = getPopupMenuArray(gospel)
showPopupMenu(
v, swipeBackActivity, array
) { _, text ->
when (text) {
array[0] -> {
actionShareText(swipeBackActivity, gospel.content)
}
array[1] -> {
actionFavorite(gospel, navId, swipeBackActivity)
}
array[2] -> {
toEditorActivity(swipeBackActivity, navId, gospel.gospelId)
}
array[3] -> {
actionHide(gospel, navId)
}
array[4] -> {
DeleteDialogFragment(
swipeBackActivity,
navId,
gospel.gospelId
).show(swipeBackActivity.supportFragmentManager, "ExitDialogFragment")
}
array[5] -> {
}
}
}
}
// activity = navActivity
}
/*private fun showPopupMenu(v: View) {
val popupMenu = PopupMenu(v.context, v)
popupMenu.gravity = Gravity.END or Gravity.BOTTOM
popupMenu.menuInflater.inflate(R.menu.menu_nav_item, popupMenu.menu)
popupMenu.setOnMenuItemClickListener { false }
popupMenu.show()
}*/
fun initView() {
// cv_nav_item.radius = 0f
// cv_nav_item.foreground = null
// tv_subtitle_nav_item.visibility = View.GONE
// tv_title_nav_item.visibility = View.GONE
// tv_detail_nav_item.textColor = ResourcesCompat.getColor(itemView.resources, R.color.text_color_primary, itemView.context.theme)
// tv_detail_nav_item.textSize = 18f
// tv_detail_nav_item.maxLines = Integer.MAX_VALUE
}
fun animateItemView(itemView: View) {
val animation = AnimationUtils.loadAnimation(itemView.context, R.anim.up_from_bottom)
itemView.startAnimation(animation)
}
fun clearItemAnimation(itemView: View) {
itemView.clearAnimation()
}
fun bind(navId: Int, gospel: Gospel) {
this.gospel = gospel
val gospelImg = filterImageUrlThroughDetailPageContent(gospel.content)
if (gospel.author == ADMIN) {
Glide.with(binding.root.context).load(R.drawable.me).into(binding.messengerImageView)
} else {
}
/*if (gospelImg.isNotBlank()) {
binding.messengerImageView.visibility = View.VISIBLE
Glide.with(binding.root.context).load(gospelImg).into(binding.messengerImageView)
} else {
binding.messengerImageView.visibility = View.GONE
}*/
if (gospel.content.contains(Regex("https://"))) {
binding.messageTextView.visibility = View.GONE
binding.messageImageView.visibility = View.VISIBLE
Glide.with(binding.root.context).load(gospelImg)
.apply(RequestOptions().transform(CenterCrop(), RoundedCorners(context.dip(2))))
.into(binding.messageImageView)
} else {
binding.messageTextView.visibility = View.VISIBLE
binding.messageImageView.visibility = View.GONE
setMarkdownToTextView(binding.root.context, binding.messageTextView, gospel.content)
// .replace(Regex("!\\[.+\\)"), "")
// .replace(Regex("\\s+"), "")
}
binding.lanTextView.text = gospel.classify
// binding.tvSubtitleNavItem.text = gospel.title
// makeViewBlur(tv_title_nav_item, cl_nav_item, activity.window, true)
binding.messengerTextView.text = gospel.author + "·" + gospel.createTime
// textView2.text = gospel.church
// textView3.text = gospel.time
binding.root.setOnClickListener {
startGospelDetailActivity(navId, gospel)
}
/*binding.tvTitleNavItem.setOnClickListener {
// gospelId = gospel.id
startGospelDetailActivity(gospel)
}*/
// binding.tvSubtitleNavItem.setOnClickListener { startGospelDetailActivity(gospel) }
// binding.tvDetailNavItem.setOnClickListener { startGospelDetailActivity(gospel) }
// binding.textView.setOnClickListener { startGospelDetailActivity(gospel) }
}
/* private fun startGospelDetailActivity(gospel: Gospel) {
val intent = Intent(binding.root.context, GospelDetailActivity::class.java)
intent.putExtra(binding.root.context.getString(R.string.category), gospel.classify)
intent.putExtra(binding.root.context.getString(R.string.name), gospel.title)
intent.putExtra(binding.root.context.getString(R.string.content_lower_case), gospel.content)
intent.putExtra(binding.root.context.getString(R.string.author), gospel.author)
// intent.putExtra(binding.root.context.getString(R.string.church_lower_case), gospel.church)
intent.putExtra(binding.root.context.getString(R.string.time), gospel.createTime)
intent.putExtra("gospelId", gospel.gospelId)
intent.putExtra(USER_ID, gospel.userId)
intent.putExtra(toolbarTitle, gospel.title)
binding.root.context.startActivity(intent)
}*/
private lateinit var gospel: Gospel
private var isOn = false
fun bind(setting: Setting) {
when (adapterPosition) {
/* 0 -> {
containerView.setOnClickListener {
if (isOn) {
containerView.findViewById<Switch>(R.id.switch_nav_item_small).isChecked = false
// 恢复应用默认皮肤
// Aesthetic.config {
// activityTheme(R.style.Christian)
// isDark(false)
// textColorPrimary(res = R.color.text_color_primary)
// textColorSecondary(res = R.color.text_color_secondary)
// attribute(R.attr.my_custom_attr, res = R.color.default_background_nav)
// attribute(R.attr.my_custom_attr2, res = R.color.white)
// }
isOn = false
} else {
containerView.findViewById<Switch>(R.id.switch_nav_item_small).isChecked = true
// 夜间模式
// Aesthetic.config {
// activityTheme(R.style.ChristianDark)
// isDark(true)
// textColorPrimary(res = android.R.color.primary_text_dark)
// textColorSecondary(res = android.R.color.secondary_text_dark)
// attribute(R.attr.my_custom_attr, res = R.color.text_color_primary)
// attribute(R.attr.my_custom_attr2, res = R.color.background_material_dark)
// }
isOn = true
}
}
}*/
4 -> {
binding.root.setOnClickListener {
// 老的跳转设置移到了NavActivity页的options menu
val i = Intent(binding.root.context, AboutActivity::class.java)
i.putExtra(toolbarTitle, getTitle(setting, adapterPosition))
binding.root.context.startActivity(i)
}
}
else -> {
binding.root.setOnClickListener {
val i = Intent(binding.root.context, HistoryAndMyArticlesActivity::class.java)
i.putExtra(toolbarTitle, getTitle(setting, adapterPosition))
binding.root.context.startActivity(i)
}
}
}
if (adapterPosition == 0) {
val sharedPreferences =
binding.root.context.getSharedPreferences("christian", Activity.MODE_PRIVATE)
val string = sharedPreferences.getString("sunrise", "") ?: ""
val string1 = sharedPreferences.getString("sunset", "") ?: ""
// switch_nav_item_small.visibility = View.VISIBLE
if (string.isNotEmpty() && string.isNotEmpty()) {
val sunriseString = string.substring(11, 19)
val sunsetString = string1.substring(11, 19)
// switch_nav_item_small.text = String.format(binding.root.context.getString(R.string.sunrise_sunset), sunriseString, sunsetString)
// switch_nav_item_small.visibility = View.VISIBLE
} else {
// switch_nav_item_small.text = binding.root.context.getString(R.string.no_location_service)
// switch_nav_item_small.visibility = View.GONE
}
}
// tv_nav_item_small.text = setting.name
// tv2_nav_item_small.text = setting.desc
val url = setting.url
// Glide.with(binding.root.context).load(if (CommonApp.getNightModeSP(binding.root.context)) generateUrlIdNightMode(url) else generateUrlId(url)).into(iv_nav_item_small)
}
private fun getTitle(setting: Setting, pos: Int): String {
// return when (navId) {
// VIEW_HOME, VIEW_GOSPEL, VIEW_DISCIPLE -> {
// snapshots[pos].data?.get("subtitle").toString()
// }
// VIEW_ME -> {
return when (pos) {
// 0 -> {
// containerView.context.getString(R.string.me)
// }
in 0..1 -> {
setting.name
}
else -> ""
}
// }
// else -> {
// return ""
// }
}
private fun startGospelDetailActivity(navId: Int, gospel: Gospel) {
val intent = Intent(binding.root.context, GospelDetailActivity::class.java)
intent.putExtra(binding.root.context.getString(R.string.category), gospel.classify)
intent.putExtra(binding.root.context.getString(R.string.name), gospel.title)
intent.putExtra(binding.root.context.getString(R.string.content_lower_case), gospel.content)
intent.putExtra(binding.root.context.getString(R.string.author), gospel.author)
// intent.putExtra(binding.root.context.getString(R.string.church_lower_case), gospel.church)
intent.putExtra(binding.root.context.getString(R.string.time), gospel.createTime)
intent.putExtra(GOSPEL_ID, gospel.gospelId)
intent.putExtra(TAB_ID, navId)
intent.putExtra(USER_ID, gospel.userId)
intent.putExtra(toolbarTitle, gospel.title)
binding.root.context.startActivity(intent)
}
} | gpl-3.0 | 4054e94ffa371765bb7144bb66171d8e | 43.214744 | 176 | 0.579455 | 4.521141 | false | false | false | false |
wireapp/wire-android | storage/src/main/kotlin/com/waz/zclient/storage/db/phone/PhoneNumbersEntity.kt | 1 | 578 | package com.waz.zclient.storage.db.phone
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
@Entity(
tableName = "PhoneNumbers",
primaryKeys = ["contact", "phone_number"],
indices = [
Index(name = "PhoneNumbers_contact", value = ["contact"]),
Index(name = "PhoneNumbers_phone", value = ["phone_number"])
]
)
data class PhoneNumbersEntity(
@ColumnInfo(name = "contact", defaultValue = "")
val contactId: String,
@ColumnInfo(name = "phone_number", defaultValue = "")
val phoneNumber: String
)
| gpl-3.0 | 347948f0eaddc449dd689f46b3c80771 | 26.52381 | 68 | 0.67301 | 3.931973 | false | false | false | false |
spark/photon-tinker-android | meshui/src/main/java/io/particle/mesh/ui/setup/NewMeshNetworkPasswordFragment.kt | 1 | 2080 | package io.particle.mesh.ui.setup
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentActivity
import com.afollestad.materialdialogs.MaterialDialog
import io.particle.mesh.setup.flow.FlowRunnerUiListener
import io.particle.mesh.ui.BaseFlowFragment
import io.particle.mesh.ui.R
import kotlinx.android.synthetic.main.fragment_new_mesh_network_password.*
class NewMeshNetworkPasswordFragment : BaseFlowFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_new_mesh_network_password, container, false)
}
override fun onFragmentReady(activity: FragmentActivity, flowUiListener: FlowRunnerUiListener) {
super.onFragmentReady(activity, flowUiListener)
action_next.setOnClickListener { onNetworkPasswordEntered() }
}
private fun onNetworkPasswordEntered() {
val password = networkPasswordInputLayout.editText!!.text.toString()
val isValid = validateNetworkPassword(password)
if (!isValid) {
MaterialDialog.Builder(requireActivity())
.content(R.string.p_newmeshnetworkname_invalid_password_dialog_text)
.positiveText(android.R.string.ok)
.show()
return
}
val confirmation = networkPasswordConfirmInputLayout.editText!!.text.toString()
if (password != confirmation) {
MaterialDialog.Builder(requireActivity())
.content(R.string.p_newmeshnetworkpassword_passwords_do_not_match_dialog_content)
.positiveText(android.R.string.ok)
.show()
return
}
flowUiListener?.mesh?.updateNewNetworkPassword(password)
}
// FIXME: move this to the backend
private fun validateNetworkPassword(password: String): Boolean {
return password.length >= 6
}
}
| apache-2.0 | e7f319d69741d776c6423ab1fcc7d960 | 36.142857 | 101 | 0.690865 | 4.871194 | false | false | false | false |
facebook/litho | litho-core-kotlin/src/main/kotlin/com/facebook/litho/ComponentScope.kt | 1 | 2147 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho
import android.view.View
/**
* The implicit receiver for [KComponent.render] call. This class exposes the ability to use hooks,
* like [useState], and convenience functions, like [dp].
*/
open class ComponentScope(
override val context: ComponentContext,
internal var renderStateContext: RenderStateContext? = null
) : ResourcesScope {
// TODO: Extract into more generic container to track hooks when needed
internal var useStateIndex = 0
internal var useCachedIndex = 0
internal var transitions: MutableList<Transition>? = null
internal var useEffectEntries: MutableList<Attachable>? = null
/**
* A utility function to find the View with a given tag under the current Component's LithoView.
* To set a view tag, use Style.viewTag. An appropriate time to call this is in your Component's
* onVisible callback.
*
* <p>As with View.findViewWithTag in general, this must be called on the main thread.
*
* <p>Note that null may be returned if the associated View doesn't exist or isn't mounted: with
* incremental mount turned on (which is the default), if the component is off-screen, it won't be
* mounted.
*
* <p>Finally, note that you should never hold a reference to the view returned by this function
* as Litho may unmount your Component and mount it to a different View.
*/
fun <T : View> findViewWithTag(tag: Any): T? {
return context.findViewWithTag(tag)
}
internal fun cleanUp() {
renderStateContext = null
}
}
| apache-2.0 | f7bb6f715396c1d30a3c7da4ffe93d32 | 37.339286 | 100 | 0.728924 | 4.234714 | false | false | false | false |
google/horologist | media-ui/src/test/java/com/google/android/horologist/media/ui/controls/SeekForwardButtonTest.kt | 1 | 3395 | /*
* 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
*
* 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.
*/
@file:OptIn(
ExperimentalHorologistPaparazziApi::class,
ExperimentalHorologistMediaUiApi::class
)
package com.google.android.horologist.media.ui.controls
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi
import com.google.android.horologist.media.ui.components.controls.SeekButtonIncrement
import com.google.android.horologist.media.ui.components.controls.SeekForwardButton
import com.google.android.horologist.paparazzi.ExperimentalHorologistPaparazziApi
import com.google.android.horologist.paparazzi.WearPaparazzi
import org.junit.Rule
import org.junit.Test
class SeekForwardButtonTest {
@get:Rule
val paparazzi = WearPaparazzi()
@Test
fun givenIncrementIsFive_thenIconIsFive() {
paparazzi.snapshot {
Box(modifier = Modifier.background(Color.Black), contentAlignment = Alignment.Center) {
SeekForwardButton(
onClick = {},
seekButtonIncrement = SeekButtonIncrement.Five
)
}
}
}
@Test
fun givenIncrementIsTen_thenIconIsTen() {
paparazzi.snapshot {
Box(modifier = Modifier.background(Color.Black), contentAlignment = Alignment.Center) {
SeekForwardButton(
onClick = {},
seekButtonIncrement = SeekButtonIncrement.Ten
)
}
}
}
@Test
fun givenIncrementIsThirty_thenIconIsThirty() {
paparazzi.snapshot {
Box(modifier = Modifier.background(Color.Black), contentAlignment = Alignment.Center) {
SeekForwardButton(
onClick = {},
seekButtonIncrement = SeekButtonIncrement.Thirty
)
}
}
}
@Test
fun givenIncrementIsOtherValue_thenIconIsDefault() {
paparazzi.snapshot {
Box(modifier = Modifier.background(Color.Black), contentAlignment = Alignment.Center) {
SeekForwardButton(
onClick = {},
seekButtonIncrement = SeekButtonIncrement.Known(15)
)
}
}
}
@Test
fun givenIncrementIsUnknown_thenIconIsDefault() {
paparazzi.snapshot {
Box(modifier = Modifier.background(Color.Black), contentAlignment = Alignment.Center) {
SeekForwardButton(
onClick = {},
seekButtonIncrement = SeekButtonIncrement.Unknown
)
}
}
}
}
| apache-2.0 | c70720ea90896abd0d9ce9ba3a965367 | 32.613861 | 99 | 0.650368 | 4.96345 | false | true | false | false |
google/horologist | composables/src/debug/java/com/google/android/horologist/composables/SegmentedProgressIndicatorPreview.kt | 1 | 2293 | /*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.composables
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@OptIn(ExperimentalHorologistComposablesApi::class)
@Preview(device = Devices.WEAR_OS_LARGE_ROUND, showSystemUi = true)
@Composable
private fun SegmentedProgressIndicatorRoundPreview() {
val segments = listOf(
ProgressIndicatorSegment(1f, Color.Green),
ProgressIndicatorSegment(1f, Color.Cyan),
ProgressIndicatorSegment(1f, Color.Magenta),
ProgressIndicatorSegment(1f, Color.Yellow),
ProgressIndicatorSegment(2f, Color.Red)
)
SegmentedProgressIndicator(
trackSegments = segments,
progress = 0.5833f,
modifier = Modifier.fillMaxSize(),
strokeWidth = 10.dp,
paddingAngle = 2f,
trackColor = Color.Gray
)
}
@OptIn(ExperimentalHorologistComposablesApi::class)
@Preview(device = Devices.WEAR_OS_SQUARE, showSystemUi = true)
@Composable
private fun SegmentedProgressIndicatorSquarePreview() {
val segments = listOf(
ProgressIndicatorSegment(1f, Color.Cyan),
ProgressIndicatorSegment(1f, Color.Magenta),
ProgressIndicatorSegment(1f, Color.Yellow)
)
SegmentedProgressIndicator(
trackSegments = segments,
progress = 0.75f,
modifier = Modifier.fillMaxSize(),
strokeWidth = 15.dp,
paddingAngle = 2f,
trackColor = Color.Gray
)
}
| apache-2.0 | 9edbc7d6407d7bc30f6683fa340a224b | 33.223881 | 75 | 0.730048 | 4.351044 | false | false | false | false |
jabbink/PokemonGoAPI | src/main/kotlin/ink/abb/pogo/api/network/ActionQueue.kt | 1 | 11091 | package ink.abb.pogo.api.network
import POGOProtos.Networking.Envelopes.AuthTicketOuterClass
import POGOProtos.Networking.Envelopes.RequestEnvelopeOuterClass
import POGOProtos.Networking.Envelopes.ResponseEnvelopeOuterClass
import POGOProtos.Networking.Envelopes.SignatureOuterClass
import POGOProtos.Networking.Requests.RequestOuterClass
import POGOProtos.Networking.Requests.RequestTypeOuterClass
import ink.abb.pogo.api.PoGoApi
import ink.abb.pogo.api.auth.CredentialProvider
import ink.abb.pogo.api.exceptions.LoginFailedException
import ink.abb.pogo.api.exceptions.RemoteServerException
import ink.abb.pogo.api.request.CheckChallenge
import ink.abb.pogo.api.util.Signature
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import rx.Observable
import rx.subjects.PublishSubject
import rx.subjects.ReplaySubject
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.*
import java.util.concurrent.ConcurrentLinkedDeque
import java.util.concurrent.TimeUnit
class ActionQueue(val poGoApi: PoGoApi, val okHttpClient: OkHttpClient, val credentialProvider: CredentialProvider) {
val signature = Signature(poGoApi)
val maxItems = 10
val queueInterval = 300L
var lastRequest = poGoApi.currentTimeMillis()
val requestQueue = ConcurrentLinkedDeque<Pair<ServerRequest, ReplaySubject<ServerRequest>>>()
val didAction = PublishSubject.create<Nothing>()
val lastUseds = mutableMapOf<RequestTypeOuterClass.RequestType, Long>()
val rateLimits = mutableMapOf<RequestTypeOuterClass.RequestType, Int>()
init {
didAction.subscribe({
val timer = Observable.timer(queueInterval, TimeUnit.MILLISECONDS)
timer.subscribe timerSubscribe@ {
//println("Time start")
if (requestQueue.isEmpty()) {
//println("Time end")
didAction.onNext(null)
return@timerSubscribe
}
var taken = 0
val queue = mutableListOf<Pair<ServerRequest, ReplaySubject<ServerRequest>>>()
val curTime = poGoApi.currentTimeMillis()
val newQueue = ConcurrentLinkedDeque<Pair<ServerRequest, ReplaySubject<ServerRequest>>>()
while (requestQueue.isNotEmpty() && taken < maxItems) {
val next = requestQueue.pop()
val type = next.first.getRequestType()
val lastUsed = lastUseds.getOrElse(type, { 0 })
val rateLimit = rateLimits.getOrElse(type, { 0 })
if (curTime > lastUsed + rateLimit) {
lastUseds.put(type, curTime)
queue.add(next)
taken++
} else {
//println("Skipping $type, because $curTime > $lastUsed + $rateLimit")
newQueue.offer(next)
}
}
while (newQueue.isNotEmpty()) {
requestQueue.offer(newQueue.pop())
}
if (queue.isNotEmpty()) {
sendRequests(queue.map { it })
}
//println("Time end")
didAction.onNext(null)
}
})
}
var apiEndpoint = "https://pgorelease.nianticlabs.com/plfe/rpc"
var authTicket: AuthTicketOuterClass.AuthTicket? = null
private var requestId: Long = 0
private val random = Random()
private fun sendRequests(requests: List<Pair<ServerRequest, ReplaySubject<ServerRequest>>>) {
val envelope = RequestEnvelopeOuterClass.RequestEnvelope.newBuilder()
envelope.setAccuracy(Math.random() * 6.0 + 4.0).setLatitude(poGoApi.latitude).setLongitude(poGoApi.longitude)
// TODO Set ticket when we have a valid one
val authTicketExpiry: Long = authTicket?.expireTimestampMs ?: 0
val now = poGoApi.currentTimeMillis()
if (authTicketExpiry > now + CredentialProvider.REFRESH_TOKEN_BUFFER_TIME) {
envelope.authTicket = authTicket
//println("Using authTicket: ${authTicket?.expireTimestampMs} > ${poGoApi.currentTimeMillis() + CredentialProvider.REFRESH_TOKEN_BUFFER_TIME}")
} else {
envelope.authInfo = credentialProvider.authInfo
//println("Using authInfo because ${authTicket?.expireTimestampMs} < ${poGoApi.currentTimeMillis() + CredentialProvider.REFRESH_TOKEN_BUFFER_TIME}")
}
envelope.addAllRequests(requests.map {
RequestOuterClass.Request.newBuilder()
.setRequestMessage(it.first.build(poGoApi).toByteString())
.setRequestType(it.first.getRequestType())
.build()
})
val challenge = CheckChallenge().withDebugRequest(false)
envelope.addRequests(RequestOuterClass.Request.newBuilder()
.setRequestMessage(challenge.build(poGoApi).toByteString())
.setRequestType(challenge.getRequestType())
.build())
envelope.statusCode = 2
requestId++
val rand = random.nextLong() or requestId.ushr(31)
envelope.requestId = rand shl 32 or requestId;
signature.setSignature(envelope, lastRequest)
//println("verification: ${signature.verifySignature(envelope, lastRequest)}")
val stream = ByteArrayOutputStream()
val request = envelope.build()
try {
request.writeTo(stream)
} catch (e: IOException) {
System.err.println("Failed to write request to bytearray ouput stream. This should never happen")
}
lastRequest = poGoApi.currentTimeMillis()
val body = RequestBody.create(null, stream.toByteArray())
val httpRequest = okhttp3.Request.Builder().url(apiEndpoint).post(body).build()
try {
okHttpClient.newCall(httpRequest).execute().use({ response ->
if (response.code() != 200) {
throw RemoteServerException("Got a unexpected http code : " + response.code())
}
val responseEnvelope: ResponseEnvelopeOuterClass.ResponseEnvelope =
try {
response.body().byteStream().use({ content -> ResponseEnvelopeOuterClass.ResponseEnvelope.parseFrom(content) })
} catch (e: Exception) {
// retrieved garbage from the server
throw RemoteServerException("Received malformed response : " + e)
}
if (responseEnvelope.apiUrl != null && responseEnvelope.apiUrl.length > 0) {
apiEndpoint = "https://" + responseEnvelope.apiUrl + "/rpc"
}
if (responseEnvelope.hasAuthTicket()) {
authTicket = responseEnvelope.authTicket
}
if (responseEnvelope.statusCode == ResponseEnvelopeOuterClass.ResponseEnvelope.StatusCode.INVALID_AUTH_TOKEN) {
throw LoginFailedException(String.format("Invalid Auth status code received, token not refreshed?",
responseEnvelope.apiUrl, responseEnvelope.error))
} else if (responseEnvelope.statusCode == ResponseEnvelopeOuterClass.ResponseEnvelope.StatusCode.REDIRECT) {
// 53 means that the api_endpoint was not correctly set, should be at this point, though, so redo the request
Thread.sleep(queueInterval)
return sendRequests(requests)
} else if (responseEnvelope.statusCode != ResponseEnvelopeOuterClass.ResponseEnvelope.StatusCode.OK && responseEnvelope.statusCode != ResponseEnvelopeOuterClass.ResponseEnvelope.StatusCode.OK_RPC_URL_IN_RESPONSE) {
System.err.println("Unexpected response envelope status received: ${responseEnvelope.statusCode}; Responses are probably malformed or unreliable")
}
/**
* map each reply to the numeric response,
* ie first response = first request and send back to the requests to toBlocking.
*/
var count = 0
if (responseEnvelope.returnsCount != requests.size + 1) {
if (responseEnvelope.returnsCount == requests.size) {
//System.err.println("Captcha request - ignoring")
} else {
System.err.println("Inconsistent replies received; expected " + (requests.size + 1) + " payloads; received " + responseEnvelope.returnsCount);
System.err.println("Probable culprit:")
System.err.println(requests[responseEnvelope.returnsCount].first.getRequestType())
System.err.println(requests[responseEnvelope.returnsCount].first.build(poGoApi).toString())
System.err.println("Envelope location: "+ envelope.latitude +" "+ envelope.longitude)
requests.drop(responseEnvelope.returnsCount).forEach {
val original = it.second
// no idea if .subscribe(original) would work here automatically as well
System.err.println("Re-queueing ${it.first.getRequestType()}, ${it.first.build(poGoApi).toString()}")
poGoApi.queueRequest(it.first).subscribe(
{ original.onNext(it) }, { original.onError(it) }, { original.onCompleted() })
}
}
}
for (payload in responseEnvelope.returnsList) {
if (count < requests.size) {
val serverReq = requests[count]
/**
* TODO: Probably all other payloads are garbage as well in this case,
* so might as well throw an exception and leave this loop */
if (payload != null) {
serverReq.first.setResponse(payload)
poGoApi.handleResponse(serverReq.first)
try {
serverReq.second.onNext(serverReq.first)
serverReq.second.onCompleted()
} catch (e: Exception) {
System.err.println("Error in handler")
e.printStackTrace()
}
}
count++
}
}
})
} catch (e: IOException) {
throw RemoteServerException(e)
} catch (e: RemoteServerException) {
// catch it, so the auto-close of resources triggers, but don't wrap it in yet another RemoteServer Exception
throw e
}
}
fun start() {
didAction.onNext(null)
}
} | gpl-3.0 | d6cc0e543e3a868142e83c6c7b407c07 | 47.863436 | 230 | 0.592192 | 5.334776 | false | false | false | false |
fnberta/PopularMovies | app/src/main/java/ch/berta/fabio/popularmovies/features/details/component/Intention.kt | 1 | 1373 | /*
* Copyright (c) 2017 Fabio Berta
*
* 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 ch.berta.fabio.popularmovies.features.details.component
import ch.berta.fabio.popularmovies.data.dtos.YOU_TUBE
import io.reactivex.Observable
fun intention(sources: DetailsSources): Observable<DetailsAction> {
val snackbarShown = sources.uiEvents.snackbarShown
.map { DetailsAction.SnackbarShown }
val favClicks = sources.uiEvents.favClicks
.map { DetailsAction.FavClick }
val updateSwipes = sources.uiEvents.updateSwipes
.map { DetailsAction.UpdateSwipe }
val videoClicks = sources.uiEvents.videoClicks
.filter { it.site == YOU_TUBE }
.map { DetailsAction.VideoClick(it) }
val actions = listOf(snackbarShown, favClicks, updateSwipes, videoClicks)
return Observable.merge(actions)
} | apache-2.0 | a533e33096c45d36d5aaf97e71b05ae2 | 38.257143 | 77 | 0.730517 | 4.098507 | false | false | false | false |
toastkidjp/Yobidashi_kt | app/src/main/java/jp/toastkid/yobidashi/main/ui/finder/FindInPage.kt | 1 | 5703 | /*
* Copyright (c) 2022 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.main.ui.finder
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.viewmodel.compose.viewModel
import jp.toastkid.lib.viewmodel.PageSearcherViewModel
import jp.toastkid.yobidashi.R
@Composable
internal fun FindInPage(
openFindInPageState: MutableState<Boolean>,
tint: Color,
pageSearcherInput: MutableState<String>
) {
val activity = LocalContext.current as? ViewModelStoreOwner ?: return
val pageSearcherViewModel = viewModel(PageSearcherViewModel::class.java, activity)
val closeAction = {
pageSearcherViewModel.clearInput()
pageSearcherViewModel.hide()
openFindInPageState.value = false
}
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
painterResource(id = R.drawable.ic_close),
contentDescription = stringResource(id = R.string.content_description_close_find_area),
tint = tint,
modifier = Modifier
.clickable(onClick = closeAction)
.padding(start = 16.dp)
)
val focusRequester = remember { FocusRequester() }
TextField(
value = pageSearcherInput.value,
onValueChange = { text ->
pageSearcherInput.value = text
pageSearcherViewModel.find(text)
},
label = {
Text(
stringResource(id = R.string.hint_find_in_page),
color = MaterialTheme.colors.onPrimary
)
},
singleLine = true,
textStyle = TextStyle(
color = MaterialTheme.colors.onPrimary,
textAlign = TextAlign.Start,
),
colors = TextFieldDefaults.textFieldColors(
backgroundColor = Color.Transparent,
cursorColor = MaterialTheme.colors.onPrimary,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent
),
trailingIcon = {
Icon(
painterResource(R.drawable.ic_clear_form),
contentDescription = "clear text",
tint = MaterialTheme.colors.onPrimary,
modifier = Modifier
.clickable {
pageSearcherInput.value = ""
pageSearcherViewModel.clearInput()
}
)
},
maxLines = 1,
keyboardActions = KeyboardActions {
pageSearcherViewModel.findDown(pageSearcherInput.value)
},
keyboardOptions = KeyboardOptions(
autoCorrect = true,
imeAction = ImeAction.Search
),
modifier = Modifier
.weight(1f)
.padding(end = 4.dp)
.background(Color.Transparent)
.focusRequester(focusRequester)
)
Icon(
painterResource(id = R.drawable.ic_up),
contentDescription = stringResource(id = R.string.content_description_find_upward),
tint = tint,
modifier = Modifier
.clickable {
pageSearcherViewModel.findUp(
pageSearcherInput.value
)
}
.padding(8.dp)
)
Icon(
painterResource(id = R.drawable.ic_down),
contentDescription = stringResource(id = R.string.content_description_find_downward),
tint = tint,
modifier = Modifier
.clickable {
pageSearcherViewModel.findDown(pageSearcherInput.value)
}
.padding(8.dp)
)
BackHandler(openFindInPageState.value) {
closeAction()
}
LaunchedEffect(key1 = "find_in_page_first_launch", block = {
if (openFindInPageState.value) {
focusRequester.requestFocus()
}
})
}
} | epl-1.0 | d1fd3c16cd285e9e2209c8942b1fa792 | 36.526316 | 99 | 0.627564 | 5.193989 | false | false | false | false |
msebire/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/ScreenshotOnFailure.kt | 1 | 2875 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.impl
import com.intellij.testGuiFramework.framework.GuiTestPaths
import com.intellij.testGuiFramework.util.ScreenshotTaker
import com.intellij.testGuiFramework.util.logError
import com.intellij.testGuiFramework.util.logInfo
import com.intellij.testGuiFramework.util.logWarning
import org.fest.swing.core.BasicComponentPrinter
import org.fest.swing.exception.ComponentLookupException
import org.junit.rules.TestWatcher
import org.junit.runner.Description
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.PrintStream
import java.text.SimpleDateFormat
import java.util.*
class ScreenshotOnFailure: TestWatcher() {
override fun failed(throwable: Throwable?, description: Description?) {
val screenshotName = "${description!!.testClass.simpleName}.${description.methodName}"
takeScreenshot(screenshotName, throwable)
}
companion object {
private val myScreenshotTaker = ScreenshotTaker()
fun takeScreenshot(screenshotName: String, t: Throwable? = null) {
try {
val file = getOrCreateScreenshotFile(screenshotName)
if (t is ComponentLookupException) logWarning("${getHierarchy()} \n caused by:", t)
myScreenshotTaker.safeTakeScreenshotAndSave(file)
logInfo("Screenshot saved to '$file'")
}
catch (e: Exception) {
logError("Screenshot failed. ${e.message}")
}
}
private fun getOrCreateScreenshotFile(screenshotName: String): File {
var file = File(GuiTestPaths.failedTestScreenshotDir, "$screenshotName.jpg")
if (file.exists())
file = File(GuiTestPaths.failedTestScreenshotDir, "$screenshotName.${getDateAndTime()}.jpg")
file.delete()
return file
}
fun getHierarchy(): String {
val out = ByteArrayOutputStream()
val printStream = PrintStream(out, true)
val componentPrinter = BasicComponentPrinter.printerWithCurrentAwtHierarchy()
componentPrinter.printComponents(printStream)
printStream.flush()
return String(out.toByteArray())
}
private fun getDateAndTime(): String {
val dateFormat = SimpleDateFormat("yyyy_MM_dd.HH_mm_ss_SSS")
val date = Date()
return dateFormat.format(date) //2016/11/16 12:08:43
}
}
} | apache-2.0 | b4433597b13f80f3d04c8e195f922de6 | 34.95 | 100 | 0.737739 | 4.443586 | false | true | false | false |
rustamgaifullin/TranslateIt | api/src/main/kotlin/com/rm/translateit/api/translation/source/wiki/WikiDetailsUrl.kt | 1 | 491 | package com.rm.translateit.api.translation.source.wiki
import com.rm.translateit.api.models.LanguageModel
import com.rm.translateit.api.translation.source.Url
class WikiDetailsUrl : Url {
private val detailsUrl =
"https://%s.wikipedia.org/w/api.php?action=query&format=json&prop=extracts|info&exintro=&explaintext=&inprop=url&titles=%s"
override fun construct(
word: String,
from: LanguageModel,
to: LanguageModel
) = detailsUrl.format(to.code.toLowerCase(), word)
} | mit | 96d4d1989a0bef24afbfeea3db7aa091 | 31.8 | 127 | 0.759674 | 3.457746 | false | false | false | false |
openhab/openhab.android | mobile/src/main/java/org/openhab/habdroid/ui/ImageWidgetActivity.kt | 1 | 5599 | /*
* Copyright (c) 2010-2022 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.habdroid.ui
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.os.Bundle
import android.util.Base64
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import com.github.chrisbanes.photoview.PhotoView
import kotlin.math.max
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject
import org.openhab.habdroid.R
import org.openhab.habdroid.core.connection.ConnectionFactory
import org.openhab.habdroid.util.HttpClient
import org.openhab.habdroid.util.ImageConversionPolicy
import org.openhab.habdroid.util.ScreenLockMode
import org.openhab.habdroid.util.determineDataUsagePolicy
import org.openhab.habdroid.util.orDefaultIfEmpty
class ImageWidgetActivity : AbstractBaseActivity() {
private lateinit var imageView: PhotoView
private var refreshJob: Job? = null
private var delay: Long = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_image)
setSupportActionBar(findViewById(R.id.openhab_toolbar))
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.title =
intent.getStringExtra(WIDGET_LABEL).orDefaultIfEmpty(getString(R.string.widget_type_image))
imageView = findViewById(R.id.activity_content)
delay = intent.getIntExtra(WIDGET_REFRESH, 0).toLong()
}
override fun onResume() {
super.onResume()
launch(Dispatchers.Main) {
if (determineDataUsagePolicy().canDoRefreshes && delay != 0L) {
scheduleRefresh()
} else {
loadImage()
}
}
}
override fun onPause() {
super.onPause()
refreshJob?.cancel()
refreshJob = null
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
Log.d(TAG, "onCreateOptionsMenu()")
menuInflater.inflate(R.menu.fullscreen_image_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
Log.d(TAG, "onOptionsItemSelected()")
return when (item.itemId) {
android.R.id.home -> {
finish()
super.onOptionsItemSelected(item)
}
R.id.refresh -> {
CoroutineScope(Dispatchers.IO + Job()).launch {
loadImage()
}
true
}
else -> super.onOptionsItemSelected(item)
}
}
private suspend fun loadImage() {
val connection = ConnectionFactory.activeUsableConnection?.connection
if (connection == null) {
Log.d(TAG, "Got no connection")
return finish()
}
val widgetUrl = intent.getStringExtra(WIDGET_URL)
val bitmap = if (widgetUrl != null) {
Log.d(TAG, "Load image from url")
val displayMetrics = resources.displayMetrics
val size = max(displayMetrics.widthPixels, displayMetrics.heightPixels)
try {
connection
.httpClient
.get(widgetUrl)
.asBitmap(size, ImageConversionPolicy.PreferTargetSize)
.response
} catch (e: HttpClient.HttpException) {
Log.d(TAG, "Failed to load image", e)
return finish()
}
} else {
val link = intent.getStringExtra(WIDGET_LINK)!!
val widgetState = JSONObject(
connection
.httpClient
.get(link)
.asText()
.response
).getString("state") ?: return finish()
if (widgetState.matches("data:image/.*;base64,.*".toRegex())) {
Log.d(TAG, "Load image from value")
val dataString = widgetState.substring(widgetState.indexOf(",") + 1)
val data = Base64.decode(dataString, Base64.DEFAULT)
BitmapFactory.decodeByteArray(data, 0, data.size)
} else {
null
}
}
bitmap ?: return finish()
// Restore zoom after image refresh
val matrix = Matrix()
imageView.getSuppMatrix(matrix)
imageView.setImageBitmap(bitmap)
imageView.setSuppMatrix(matrix)
}
private fun scheduleRefresh() {
Log.d(TAG, "scheduleRefresh()")
refreshJob = launch {
loadImage()
delay(delay)
Log.d(TAG, "refreshJob after delay")
scheduleRefresh()
}
}
override fun doesLockModeRequirePrompt(mode: ScreenLockMode): Boolean {
return mode == ScreenLockMode.Enabled
}
companion object {
private val TAG = ImageWidgetActivity::class.java.simpleName
const val WIDGET_LABEL = "widget_label"
const val WIDGET_REFRESH = "widget_refresh"
const val WIDGET_URL = "widget_url"
const val WIDGET_LINK = "widget_link"
}
}
| epl-1.0 | 0323f4c73de3e7a3ec77d1bca1001aa2 | 31.364162 | 103 | 0.617789 | 4.839239 | false | false | false | false |
tipsy/javalin | javalin/src/test/java/io/javalin/TestConfigureServletContextHandler.kt | 1 | 2641 | /*
* Javalin - https://javalin.io
* Copyright 2017 David Åse
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*
*/
package io.javalin
import io.javalin.testing.HttpUtil
import io.javalin.testing.TestUtil
import org.assertj.core.api.Assertions.assertThat
import org.eclipse.jetty.servlet.FilterHolder
import org.junit.jupiter.api.Test
import java.util.*
import javax.servlet.DispatcherType
import javax.servlet.Filter
import javax.servlet.FilterChain
import javax.servlet.FilterConfig
import javax.servlet.ServletContextEvent
import javax.servlet.ServletContextListener
import javax.servlet.ServletRequest
import javax.servlet.ServletResponse
class TestConfigureServletContextHandler {
@Test
fun `adding an event listener to the ServletContextHandler works`() = TestUtil.runLogLess {
val listener = object : ServletContextListener {
var called = false
override fun contextInitialized(ev: ServletContextEvent?) {
called = true
}
override fun contextDestroyed(ev: ServletContextEvent?) {
called = true
}
}
val app = Javalin.create {
it.configureServletContextHandler { handler ->
handler.addEventListener(listener)
}
}.start(0)
val http = HttpUtil(app.port())
http.htmlGet("/")
assertThat(listener.called).isTrue()
}
@Test
fun `adding a filter to the ServletContextHandler works`() {
val filter = object : Filter {
var initialized = false
var called = false
var destroyed = false
override fun init(config: FilterConfig?) {
initialized = true
}
override fun doFilter(request: ServletRequest?, response: ServletResponse?, chain: FilterChain?) {
called = true
chain?.doFilter(request, response)
}
override fun destroy() {
destroyed = true
}
}
val filterJavalin = Javalin.create {
it.configureServletContextHandler { handler ->
handler.addFilter(FilterHolder(filter), "/*", EnumSet.allOf(DispatcherType::class.java))
}
}
TestUtil.test(filterJavalin) { app, http ->
app.get("/test") { it.result("Test") }
val response = http.get("/test")
assertThat(response.body).isEqualTo("Test")
assertThat(filter.initialized).isTrue()
assertThat(filter.called).isTrue()
}
}
}
| apache-2.0 | 5c85d40a3312ece41e2155d28ee5343e | 29 | 110 | 0.619697 | 4.870849 | false | true | false | false |
tipsy/javalin | javalin/src/main/java/io/javalin/jetty/JettyResourceHandler.kt | 1 | 4794 | /*
* Javalin - https://javalin.io
* Copyright 2017 David Åse
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*/
package io.javalin.jetty
import io.javalin.core.util.JavalinException
import io.javalin.core.util.JavalinLogger
import io.javalin.http.staticfiles.Location
import io.javalin.http.staticfiles.StaticFileConfig
import org.eclipse.jetty.server.Request
import org.eclipse.jetty.server.handler.ResourceHandler
import org.eclipse.jetty.util.URIUtil
import org.eclipse.jetty.util.resource.EmptyResource
import org.eclipse.jetty.util.resource.Resource
import java.io.File
import java.nio.file.AccessDeniedException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import io.javalin.http.staticfiles.ResourceHandler as JavalinResourceHandler
class JettyResourceHandler : JavalinResourceHandler {
init {
JettyUtil.disableJettyLogger()
}
val handlers = mutableListOf<ConfigurableHandler>()
override fun addStaticFileConfig(config: StaticFileConfig) {
handlers.add(ConfigurableHandler(config).apply { start() })
}
override fun handle(httpRequest: HttpServletRequest, httpResponse: HttpServletResponse): Boolean {
val target = httpRequest.getAttribute("jetty-target") as String
val baseRequest = httpRequest.getAttribute("jetty-request") as Request
handlers.filter { !it.config.skipFileFunction(httpRequest) }.forEach { handler ->
try {
val resource = handler.getResource(target)
if (resource.isFile() || resource.isDirectoryWithWelcomeFile(handler, target)) {
handler.config.headers.forEach { httpResponse.setHeader(it.key, it.value) }
if (handler.config.precompress && JettyPrecompressingResourceHandler.handle(resource, httpRequest, httpResponse)) {
return true
}
httpResponse.contentType = null // Jetty will only set the content-type if it's null
httpResponse.outputStream.use { handler.handle(target, baseRequest, httpRequest, httpResponse) }
httpRequest.setAttribute("handled-as-static-file", true)
return true
}
} catch (e: Exception) { // it's fine, we'll just 404
if (!JettyUtil.isClientAbortException(e)) {
JavalinLogger.info("Exception occurred while handling static resource", e)
}
}
}
return false
}
private fun Resource?.isFile() = this != null && this.exists() && !this.isDirectory
private fun Resource?.isDirectoryWithWelcomeFile(handler: ResourceHandler, target: String) =
this != null && this.isDirectory && handler.getResource("${target.removeSuffix("/")}/index.html")?.exists() == true
}
open class ConfigurableHandler(val config: StaticFileConfig) : ResourceHandler() {
init {
resourceBase = getResourceBase(config)
isDirAllowed = false
isEtags = true
JavalinLogger.addDelayed {
JavalinLogger.info("Static file handler added: ${config.refinedToString()}. File system location: '${getResourceBase(config)}'")
}
}
override fun getResource(path: String): Resource {
val aliasResource by lazy { baseResource!!.addPath(URIUtil.canonicalPath(path)) }
return when {
config.directory == "META-INF/resources/webjars" ->
Resource.newClassPathResource("META-INF/resources$path") ?: EmptyResource.INSTANCE
config.aliasCheck != null && aliasResource.isAlias ->
if (config.aliasCheck?.check(path, aliasResource) == true) aliasResource else throw AccessDeniedException("Failed alias check")
config.hostedPath == "/" -> super.getResource(path) // same as regular ResourceHandler
path.startsWith(config.hostedPath) -> super.getResource(path.removePrefix(config.hostedPath))
else -> EmptyResource.INSTANCE // files that don't start with hostedPath should not be accessible
}
}
private fun getResourceBase(config: StaticFileConfig): String {
val noSuchDirMessage = "Static resource directory with path: '${config.directory}' does not exist."
val classpathHint = "Depending on your setup, empty folders might not get copied to classpath."
if (config.location == Location.CLASSPATH) {
return Resource.newClassPathResource(config.directory)?.toString() ?: throw JavalinException("$noSuchDirMessage $classpathHint")
}
if (!File(config.directory).exists()) {
throw JavalinException(noSuchDirMessage)
}
return config.directory
}
}
| apache-2.0 | ae2dc8596c2d2d88ff2a68bc74a95a55 | 45.086538 | 143 | 0.680367 | 4.764414 | false | true | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/stats/ChartView.kt | 1 | 3649 | /****************************************************************************************
* Copyright (c) 2014 Michael Goldbach <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki.stats
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.view.View
import com.ichi2.anki.Statistics.ChartFragment
import com.ichi2.utils.KotlinCleanup
import com.wildplot.android.rendering.PlotSheet
import com.wildplot.android.rendering.graphics.wrapper.GraphicsWrap
import timber.log.Timber
class ChartView : View {
private var mFragment: ChartFragment? = null
private var mPlotSheet: PlotSheet? = null
private var mDataIsSet = false
@KotlinCleanup("is this really needed?")
private val drawingBoundsRect = Rect()
private val paint = Paint(Paint.LINEAR_TEXT_FLAG)
private val graphicsWrap = GraphicsWrap()
// The following constructors are needed for the layout inflater
constructor(context: Context?) : super(context) {
setWillNotDraw(false)
}
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
setWillNotDraw(false)
}
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
setWillNotDraw(false)
}
public override fun onDraw(canvas: Canvas) {
// Timber.d("drawing chart");
if (mDataIsSet) {
// Paint paint = new Paint(Paint.LINEAR_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
paint.apply {
reset()
isAntiAlias = true
style = Paint.Style.STROKE
}
graphicsWrap.paint = paint
graphicsWrap.canvas = canvas
drawingBoundsRect.setEmpty()
getDrawingRect(drawingBoundsRect)
mPlotSheet?.paint(graphicsWrap) ?: super.onDraw(canvas)
} else {
super.onDraw(canvas)
}
}
fun addFragment(fragment: ChartFragment?) {
mFragment = fragment
}
fun setData(plotSheet: PlotSheet?) {
mPlotSheet = plotSheet
mDataIsSet = true
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
Timber.d("ChartView sizeChange!")
if (mFragment != null) {
mFragment!!.checkAndUpdate()
}
}
}
| gpl-3.0 | 9f99e7de64e480df719d90f0f30e7c80 | 40.465909 | 115 | 0.558235 | 5.139437 | false | false | false | false |
yuyashuai/SurfaceViewFrameAnimation | frameanimation/src/main/java/com/yuyashuai/frameanimation/Util.kt | 1 | 1863 | package com.yuyashuai.frameanimation
import android.content.Context
import android.util.Log
import java.io.File
import java.io.IOException
import java.util.*
/**
* @author yuyashuai 2019-04-25.
*/
object Util {
private val TAG = javaClass.simpleName
/**
* get the path list from assets
*
* @param assetsPath assets resource path, must be a directory
* @return if assets does not exist return a empty list
*/
fun getPathList(context: Context, assetsPath: String): List<String> {
val assetManager = context.assets
try {
val assetFiles = assetManager.list(assetsPath)
if (assetFiles.isNullOrEmpty()) {
Log.e(TAG, "no file in this asset directory")
return emptyList()
}
//转换真实路径
for (i in assetFiles.indices) {
assetFiles[i] = assetsPath + File.separator + assetFiles[i]
}
return assetFiles.toList()
} catch (e: IOException) {
Log.e(TAG, e.message)
e.printStackTrace()
}
return emptyList()
}
/**
* get the path list from file
*
* @param file the resources directory
* @return if file does not exist return a empty list
*/
fun getPathList(file: File?): List<String> {
val list = ArrayList<String>()
if (file != null) {
if (file.exists() && file.isDirectory) {
val files = file.listFiles() ?: return list
list.addAll(files.map { it.absolutePath })
} else if (!file.exists()) {
Log.e(TAG, "file doesn't exists")
} else {
Log.e(TAG, "file isn't a directory")
}
} else {
Log.e(TAG, "file is null")
}
return list
}
} | apache-2.0 | e1445718779c85220ce16ea8e4a4b28e | 28.870968 | 75 | 0.547812 | 4.274827 | false | false | false | false |
tfcbandgeek/SmartReminders-android | app/src/main/java/jgappsandgames/smartreminderslite/utility/IntentBuilderUtility.kt | 1 | 8970 | package jgappsandgames.smartreminderslite.utility
// Android OS
import android.app.Activity
import android.content.Intent
// Application
import jgappsandgames.smartreminderslite.home.*
import jgappsandgames.smartreminderslite.sort.*
import jgappsandgames.smartreminderslite.tasks.*
// Save
import jgappsandgames.smartreminderssave.tasks.Task
fun buildHomeIntent(activity: Activity, options: IntentOptions): Intent {
val intent = Intent(activity, HomeActivity::class.java).setAction(Intent.ACTION_DEFAULT).putExtra("home", true)
if (options.shortcut) intent.putExtra("shortcut", true)
if (options.option) intent.putExtra("option", true)
if (options.automated) intent.putExtra("automated", true)
if (options.notification) intent.putExtra("notification", true)
if (options.settings) intent.putExtra("settings", true)
if (options.fromExternal) intent.putExtra("external", true)
if (options.clearStack) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
if (options.fillStack) intent.putExtra("fillStack", true)
return intent
}
fun buildTagsIntent(activity: Activity, options: IntentOptions): Intent {
val intent = Intent(activity, TagActivity::class.java)
if (options.shortcut) intent.putExtra("shortcut", true)
if (options.option) intent.putExtra("option", true)
if (options.automated) intent.putExtra("automated", true)
if (options.notification) intent.putExtra("notification", true)
if (options.settings) intent.putExtra("settings", true)
if (options.fromExternal) intent.putExtra("external", true)
if (options.clearStack) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
if (options.fillStack) intent.putExtra("fillStack", true)
return intent
}
fun buildStatusIntent(activity: Activity, options: IntentOptions): Intent {
val intent = Intent(activity, StatusActivity::class.java)
if (options.shortcut) intent.putExtra("shortcut", true)
if (options.option) intent.putExtra("option", true)
if (options.automated) intent.putExtra("automated", true)
if (options.notification) intent.putExtra("notification", true)
if (options.settings) intent.putExtra("settings", true)
if (options.fromExternal) intent.putExtra("external", true)
if (options.clearStack) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
if (options.fillStack) intent.putExtra("fillStack", true)
return intent
}
fun buildPriorityIntent(activity: Activity, options: IntentOptions): Intent {
val intent = Intent(activity, PriorityActivity::class.java)
if (options.shortcut) intent.putExtra("shortcut", true)
if (options.option) intent.putExtra("option", true)
if (options.automated) intent.putExtra("automated", true)
if (options.notification) intent.putExtra("notification", true)
if (options.settings) intent.putExtra("settings", true)
if (options.fromExternal) intent.putExtra("external", true)
if (options.clearStack) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
if (options.fillStack) intent.putExtra("fillStack", true)
return intent
}
fun buildDayIntent(activity: Activity, options: IntentOptions): Intent {
val intent = Intent(activity, DayActivity::class.java)
if (options.shortcut) intent.putExtra("shortcut", true)
if (options.option) intent.putExtra("option", true)
if (options.automated) intent.putExtra("automated", true)
if (options.notification) intent.putExtra("notification", true)
if (options.settings) intent.putExtra("settings", true)
if (options.fromExternal) intent.putExtra("external", true)
if (options.clearStack) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
return intent
}
fun buildWeekIntent(activity: Activity, options: IntentOptions): Intent {
val intent = Intent(activity, WeekActivity::class.java)
if (options.shortcut) intent.putExtra("shortcut", true)
if (options.option) intent.putExtra("option", true)
if (options.automated) intent.putExtra("automated", true)
if (options.notification) intent.putExtra("notification", true)
if (options.settings) intent.putExtra("settings", true)
if (options.fromExternal) intent.putExtra("exteranal", true)
if (options.clearStack) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
return intent
}
fun buildMonthIntent(activity: Activity, options: IntentOptions): Intent {
val intent = Intent(activity, MonthActivity::class.java)
if (options.shortcut) intent.putExtra("shortcut", true)
if (options.option) intent.putExtra("option", true)
if (options.automated) intent.putExtra("automated", true)
if (options.notification) intent.putExtra("notification", true)
if (options.settings) intent.putExtra("settings", true)
if (options.fromExternal) intent.putExtra("external", true)
if (options.clearStack) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
return intent
}
fun buildTaskIntent(activity: Activity, options: IntentOptions, task: TaskOptions): Intent {
val intent = Intent(activity, TaskActivity::class.java)
if (task.task != null) {
intent.putExtra(TASK_TYPE, task.task.getType())
intent.putExtra(TASK_NAME, task.task.getFilename())
} else {
intent.putExtra(TASK_TYPE, task.type)
intent.putExtra(TASK_NAME, task.filename)
}
if (options.shortcut) intent.putExtra("shortcut", true)
if (options.option) intent.putExtra("option", true)
if (options.automated) intent.putExtra("automated", true)
if (options.notification) intent.putExtra("notification", true)
if (options.settings) intent.putExtra("settings", true)
if (options.fromExternal) intent.putExtra("external", true)
if (options.create) intent.putExtra(CREATE, true)
if (options.deleteOnExit) intent.putExtra("deleteOnExit", true)
if (options.toHomeOnExit) intent.putExtra("toHomeOnExit", true)
if (options.clearStack) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
return intent
}
fun buildTaskTagsIntent(activity: Activity, options: IntentOptions, task: TaskOptions): Intent {
val intent = Intent(activity, TagEditorActivity::class.java)
intent.putExtra(TASK_NAME, task.getTaskFilename())
if (options.shortcut) intent.putExtra("shortcut", true)
if (options.option) intent.putExtra("option", true)
if (options.automated) intent.putExtra("automated", true)
if (options.notification) intent.putExtra("notification", true)
if (options.settings) intent.putExtra("settings", true)
if (options.fromExternal) intent.putExtra("external", true)
if (options.clearStack) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
return intent
}
fun buildSettingsIntent(activity: Activity, options: IntentOptions): Intent {
val intent = Intent(activity, Settings2Activity::class.java)
if (options.shortcut) intent.putExtra("shortcut", true)
if (options.option) intent.putExtra("option", true)
if (options.automated) intent.putExtra("automated", true)
if (options.notification) intent.putExtra("notification", true)
if (options.settings) intent.putExtra("settings", true)
if (options.fromExternal) intent.putExtra("external", true)
if (options.clearStack) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
return intent
}
fun buildAboutIntent(activity: Activity, options: IntentOptions): Intent {
val intent = Intent(activity, AboutActivity::class.java)
if (options.shortcut) intent.putExtra("shortcut", true)
if (options.option) intent.putExtra("option", true)
if (options.automated) intent.putExtra("automated", true)
if (options.notification) intent.putExtra("notification", true)
if (options.settings) intent.putExtra("settings", true)
if (options.fromExternal) intent.putExtra("external", true)
if (options.clearStack) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
return intent
}
class IntentOptions(val shortcut: Boolean = false, val option: Boolean = false, val settings: Boolean = false,
val fromExternal: Boolean = false, val notification: Boolean = false, val automated: Boolean = false,
val clearStack: Boolean = false, val fillStack: Boolean = false,
val create: Boolean = false, val deleteOnExit: Boolean = false, val toHomeOnExit: Boolean = false)
class TaskOptions(val filename: String? = null, val task: Task? = null, val type: Int? = null) {
fun getTaskFilename(): String {
if (filename == null) return task!!.getFilename()
return filename
}
} | apache-2.0 | 2b844aef8d6bccb8e38865f35153c1a7 | 45.005128 | 121 | 0.735229 | 4.000892 | false | false | false | false |
openMF/self-service-app | app/src/main/java/org/mifos/mobile/models/accounts/savings/Summary.kt | 1 | 1109 | package org.mifos.mobile.models.accounts.savings
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
/**
* Created by Rajan Maurya on 05/03/17.
*/
@Parcelize
data class Summary(
@SerializedName("currency")
var currency: Currency,
@SerializedName("totalDeposits")
var totalDeposits: Double? = null,
@SerializedName("totalWithdrawals")
var totalWithdrawals: Double? = null,
@SerializedName("totalInterestEarned")
var totalInterestEarned: Double? = null,
@SerializedName("totalInterestPosted")
var totalInterestPosted: Double? = null,
@SerializedName("accountBalance")
var accountBalance: Double? = null,
@SerializedName("totalOverdraftInterestDerived")
var totalOverdraftInterestDerived: Double? = null,
@SerializedName("interestNotPosted")
var interestNotPosted: Double? = null,
@SerializedName("lastInterestCalculationDate")
var lastInterestCalculationDate: List<Int>
) : Parcelable | mpl-2.0 | 5ee0ba26cdc28a1f41a81048a2ff061d | 25.428571 | 58 | 0.695221 | 4.545082 | false | false | false | false |
dafi/commonutils | app/src/main/java/com/ternaryop/utils/intent/ShareUtils.kt | 1 | 2110 | package com.ternaryop.utils.intent
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
data class ShareChooserParams(
val destFileUri: Uri,
val title: String,
val subject: String,
val mimeType: String = "image/jpeg")
object ShareUtils {
fun showShareChooser(context: Context, shareChooserParams: ShareChooserParams) {
val intent = Intent(Intent.ACTION_SEND)
.setDataAndType(shareChooserParams.destFileUri, shareChooserParams.mimeType)
.putExtra(Intent.EXTRA_SUBJECT, shareChooserParams.subject)
.putExtra(Intent.EXTRA_STREAM, shareChooserParams.destFileUri)
.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
context.startActivity(Intent.createChooser(intent, shareChooserParams.title))
}
@Deprecated(
message = "Do not properly work with Api level 29, use showShareChooser",
replaceWith = ReplaceWith(
expression = "showShareChooser",
imports = ["com.ternaryop.utils.intent.ShareUtils.showShareChooser"]
),
level = DeprecationLevel.WARNING)
fun shareImage(context: Context, fullPath: String, mimeType: String, subject: String, chooserTitle: String) {
val values = ContentValues(4)
values.put(MediaStore.Images.Media.MIME_TYPE, mimeType)
values.put(MediaStore.Images.Media.DATA, fullPath)
// sharing on google plus works only using MediaStore
val uri = context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
val sharingIntent = Intent(android.content.Intent.ACTION_SEND)
sharingIntent.type = mimeType
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject)
sharingIntent.putExtra(android.content.Intent.EXTRA_STREAM, uri)
sharingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT)
context.startActivity(Intent.createChooser(sharingIntent, chooserTitle))
}
}
| mit | d5be8617f0c600616b9b0624c02d138a | 42.958333 | 113 | 0.722749 | 4.432773 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/entity/weather/LanternLightningBolt.kt | 1 | 5092 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.entity.weather
import org.lanternpowered.api.cause.CauseStack
import org.lanternpowered.api.cause.entity.damage.DamageTypes
import org.lanternpowered.api.cause.withFrame
import org.lanternpowered.api.effect.sound.SoundCategory
import org.lanternpowered.api.entity.Entity
import org.lanternpowered.api.event.EventManager
import org.lanternpowered.server.event.LanternEventFactory
import org.lanternpowered.api.util.collections.asNonNullList
import org.lanternpowered.api.world.getIntersectingEntities
import org.lanternpowered.server.effect.entity.EntityEffectCollection
import org.lanternpowered.server.effect.entity.EntityEffectTypes
import org.lanternpowered.server.effect.entity.sound.weather.LightningSoundEffect
import org.lanternpowered.server.entity.EntityCreationData
import org.lanternpowered.server.entity.LanternEntity
import org.lanternpowered.server.network.entity.EntityProtocolTypes
import org.spongepowered.api.block.BlockSnapshot
import org.lanternpowered.api.data.Keys
import org.spongepowered.api.data.Transaction
import org.spongepowered.api.entity.weather.LightningBolt
import org.spongepowered.api.event.cause.entity.damage.source.EntityDamageSource
import org.spongepowered.api.util.AABB
import org.spongepowered.api.world.BlockChangeFlags
import kotlin.time.Duration
import kotlin.time.seconds
class LanternLightningBolt(creationData: EntityCreationData) : LanternEntity(creationData), LightningBolt {
companion object {
val DEFAULT_SOUND_COLLECTION = EntityEffectCollection.builder()
.add(EntityEffectTypes.LIGHTNING, LightningSoundEffect)
.build()
/**
* The region that the [LightningBolt] will damage [Entity]s.
*/
private val ENTITY_STRIKE_REGION = AABB(-3.0, -3.0, -3.0, 3.0, 9.0, 3.0)
}
/**
* The time that the lightning bolt will be alive.
*/
private var timeToLive = 0.5.seconds
private var remove = false
init {
this.protocolType = EntityProtocolTypes.LIGHTNING
this.effectCollection = DEFAULT_SOUND_COLLECTION.copy()
this.soundCategory = SoundCategory.WEATHER
keyRegistry {
register(Keys.IS_EFFECT_ONLY, false)
}
}
override fun update(deltaTime: Duration) {
super.update(deltaTime)
this.timeToLive -= deltaTime
if (this.timeToLive > Duration.ZERO)
return
if (this.remove) {
CauseStack.withFrame { frame ->
// Add this entity to the cause of removal
frame.pushCause(this)
// Throw the expire and post event
val cause = frame.currentCause
EventManager.post(LanternEventFactory.createExpireEntityEvent(cause, this))
EventManager.post(LanternEventFactory.createLightningEventPost(cause))
this.remove()
}
} else {
this.remove = true
// Play the sound effect
this.effectCollection.getCombinedOrEmpty(EntityEffectTypes.LIGHTNING).play(this)
CauseStack.withFrame { frame ->
frame.pushCause(this)
val entities: MutableList<Entity> = if (this.require(Keys.IS_EFFECT_ONLY)) {
mutableListOf()
} else {
// Move the entity strike region to the lightning position
val strikeRegion = ENTITY_STRIKE_REGION.offset(this.position)
// Get all intersecting entities
this.world.getIntersectingEntities(strikeRegion) { entity -> entity != this }.toMutableList()
}
val blockChanges = mutableListOf<Transaction<BlockSnapshot>>()
val event = LanternEventFactory.createLightningEventStrike(
frame.currentCause, entities, blockChanges.asNonNullList())
// TODO: Create fire, once fire is implemented
EventManager.post(event)
if (event.isCancelled)
return
// Construct the damage source
val damageSource = EntityDamageSource.builder()
.entity(this).type(DamageTypes.LIGHTNING).build()
// Apply all the block changes
for (transaction in blockChanges) {
if (transaction.isValid)
transaction.final.restore(false, BlockChangeFlags.ALL)
}
// Damage all the entities within the region, or trigger other effects, like zombie pigman etc.
for (entity in entities)
entity.damage(5.0, damageSource)
}
}
}
}
| mit | 6b0190dbf602b8f0f2480ac40e41a892 | 38.78125 | 113 | 0.66143 | 4.785714 | false | false | false | false |
ageery/kwicket | kwicket-wicket-core/src/main/kotlin/org/kwicket/wicket/core/markup/html/form/KForm.kt | 1 | 3460 | package org.kwicket.wicket.core.markup.html.form
import org.apache.wicket.behavior.Behavior
import org.apache.wicket.markup.html.form.Form
import org.apache.wicket.markup.html.form.validation.IFormValidator
import org.apache.wicket.model.IModel
import org.kwicket.component.init
/**
* [Form] with named and default constructor arguments.
*
* @param T type of the model backing the component
* @param id Wicket markup id
* @param model model for the component
* @param outputMarkupId whether to include an HTML id for the component in the markup
* @param outputMarkupPlaceholderTag whether to include a placeholder tag for the component in the markup when the
* component is not visible
* @param visible whether the component is visible
* @param enabled whether the component is enabled
* @param escapeModelStrings whether model strings should be escaped
* @param renderBodyOnly whether the tag associated with the component should be included in the markup
* @param behaviors list of [Behavior] to add to the component
* @param validators list of form validators to add to the form
*/
open class KForm<T>(
id: String,
model: IModel<T>? = null,
outputMarkupPlaceholderTag: Boolean? = null,
outputMarkupId: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
escapeModelStrings: Boolean? = null,
renderBodyOnly: Boolean? = null,
validators: List<IFormValidator>? = null,
behaviors: List<Behavior>? = null
) : Form<T>(id, model) {
/**
* Creates a new [KForm].
*
* @param id Wicket markup id
* @param model model for the component
* @param outputMarkupId whether to include an HTML id for the component in the markup
* @param outputMarkupPlaceholderTag whether to include a placeholder tag for the component in the markup when the
* component is not visible
* @param visible whether the component is visible
* @param enabled whether the component is enabled
* @param escapeModelStrings whether model strings should be escaped
* @param renderBodyOnly whether the tag associated with the component should be included in the markup
* @param behavior [Behavior] to add to the component
* @param validators list of form validators to add to the form
*/
constructor(
id: String,
model: IModel<T>? = null,
outputMarkupPlaceholderTag: Boolean? = null,
outputMarkupId: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
escapeModelStrings: Boolean? = null,
renderBodyOnly: Boolean? = null,
validators: List<IFormValidator>? = null,
behavior: Behavior
) : this(
id = id,
model = model,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
outputMarkupId = outputMarkupId,
visible = visible,
enabled = enabled,
escapeModelStrings = escapeModelStrings,
renderBodyOnly = renderBodyOnly,
behaviors = listOf(behavior),
validators = validators
)
init {
init(
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
outputMarkupId = outputMarkupId,
visible = visible,
enabled = enabled,
escapeModelStrings = escapeModelStrings,
renderBodyOnly = renderBodyOnly,
behaviors = behaviors
)
validators?.forEach { add(it) }
}
} | apache-2.0 | 2665f648178645d66b7075bcae869e98 | 37.88764 | 118 | 0.689017 | 4.978417 | false | false | false | false |
RoverPlatform/rover-android | experiences/src/main/kotlin/io/rover/sdk/experiences/RoverExperiences.kt | 1 | 23048 | package io.rover.sdk.experiences
import android.app.Application
import androidx.lifecycle.Lifecycle
import android.content.Context
import android.graphics.Color
import android.os.Parcelable
import androidx.annotation.ColorInt
import android.util.DisplayMetrics
import io.rover.sdk.core.data.http.AndroidHttpsUrlConnectionNetworkClient
import io.rover.sdk.core.streams.Scheduler
import io.rover.sdk.experiences.assets.AndroidAssetService
import io.rover.sdk.experiences.assets.ImageDownloader
import io.rover.sdk.experiences.assets.ImageOptimizationService
import io.rover.sdk.core.data.domain.Background
import io.rover.sdk.core.data.domain.Barcode
import io.rover.sdk.core.data.domain.BarcodeBlock
import io.rover.sdk.core.data.domain.Block
import io.rover.sdk.core.data.domain.Border
import io.rover.sdk.core.data.domain.ButtonBlock
import io.rover.sdk.core.data.domain.Experience
import io.rover.sdk.core.data.domain.Image
import io.rover.sdk.core.data.domain.ImageBlock
import io.rover.sdk.core.data.domain.ImagePoll
import io.rover.sdk.core.data.domain.ImagePollBlock
import io.rover.sdk.core.data.domain.RectangleBlock
import io.rover.sdk.core.data.domain.Row
import io.rover.sdk.core.data.domain.Screen
import io.rover.sdk.core.data.domain.Text
import io.rover.sdk.core.data.domain.TextBlock
import io.rover.sdk.core.data.domain.TextPoll
import io.rover.sdk.core.data.domain.TextPollBlock
import io.rover.sdk.core.data.domain.WebView
import io.rover.sdk.core.data.domain.WebViewBlock
import io.rover.sdk.core.data.graphql.GraphQlApiServiceInterface
import io.rover.sdk.experiences.data.events.AnalyticsService
import io.rover.sdk.experiences.data.events.AppOpenedTracker
import io.rover.sdk.experiences.logging.log
import io.rover.sdk.experiences.platform.IoMultiplexingExecutor
import io.rover.sdk.experiences.platform.LocalStorage
import io.rover.sdk.experiences.services.BarcodeRenderingService
import io.rover.sdk.experiences.services.EmbeddedWebBrowserDisplay
import io.rover.sdk.experiences.services.EventEmitter
import io.rover.sdk.experiences.services.MeasurementService
import io.rover.sdk.experiences.services.SessionStore
import io.rover.sdk.experiences.services.SessionTracker
import io.rover.sdk.core.streams.forAndroidMainThread
import io.rover.sdk.core.streams.forExecutor
import io.rover.experiences.BuildConfig
import io.rover.sdk.experiences.ui.RoverViewModel
import io.rover.sdk.experiences.ui.blocks.barcode.BarcodeBlockView
import io.rover.sdk.experiences.ui.blocks.barcode.BarcodeBlockViewModel
import io.rover.sdk.experiences.ui.blocks.barcode.BarcodeViewModel
import io.rover.sdk.experiences.ui.blocks.button.ButtonBlockView
import io.rover.sdk.experiences.ui.blocks.button.ButtonBlockViewModel
import io.rover.sdk.experiences.ui.blocks.concerns.background.BackgroundViewModel
import io.rover.sdk.experiences.ui.blocks.concerns.border.BorderViewModel
import io.rover.sdk.experiences.ui.blocks.concerns.layout.BlockViewModel
import io.rover.sdk.experiences.ui.blocks.concerns.layout.CompositeBlockViewModelInterface
import io.rover.sdk.experiences.ui.blocks.concerns.layout.LayoutPaddingDeflection
import io.rover.sdk.experiences.ui.blocks.concerns.layout.LayoutableView
import io.rover.sdk.experiences.ui.blocks.concerns.layout.LayoutableViewModel
import io.rover.sdk.experiences.ui.blocks.concerns.layout.Measurable
import io.rover.sdk.experiences.ui.blocks.concerns.text.AndroidRichTextToSpannedTransformer
import io.rover.sdk.experiences.ui.blocks.concerns.text.TextViewModel
import io.rover.sdk.experiences.ui.blocks.image.ImageBlockView
import io.rover.sdk.experiences.ui.blocks.image.ImageBlockViewModel
import io.rover.sdk.experiences.ui.blocks.image.ImageViewModel
import io.rover.sdk.experiences.ui.blocks.poll.VotingInteractor
import io.rover.sdk.experiences.ui.blocks.poll.VotingService
import io.rover.sdk.experiences.ui.blocks.poll.VotingStorage
import io.rover.sdk.experiences.ui.blocks.poll.image.ImagePollBlockView
import io.rover.sdk.experiences.ui.blocks.poll.image.ImagePollBlockViewModel
import io.rover.sdk.experiences.ui.blocks.poll.image.ImagePollViewModel
import io.rover.sdk.experiences.ui.blocks.poll.text.TextPollBlockView
import io.rover.sdk.experiences.ui.blocks.poll.text.TextPollBlockViewModel
import io.rover.sdk.experiences.ui.blocks.poll.text.TextPollViewModel
import io.rover.sdk.experiences.ui.blocks.rectangle.RectangleBlockView
import io.rover.sdk.experiences.ui.blocks.rectangle.RectangleBlockViewModel
import io.rover.sdk.experiences.ui.blocks.text.TextBlockView
import io.rover.sdk.experiences.ui.blocks.text.TextBlockViewModel
import io.rover.sdk.experiences.ui.blocks.web.WebBlockView
import io.rover.sdk.experiences.ui.blocks.web.WebViewBlockViewModel
import io.rover.sdk.experiences.ui.blocks.web.WebViewModel
import io.rover.sdk.experiences.ui.layout.BlockAndRowLayoutManager
import io.rover.sdk.experiences.ui.layout.BlockAndRowRecyclerAdapter
import io.rover.sdk.experiences.ui.layout.Layout
import io.rover.sdk.experiences.ui.layout.ViewType
import io.rover.sdk.experiences.ui.layout.row.RowView
import io.rover.sdk.experiences.ui.layout.row.RowViewModel
import io.rover.sdk.experiences.ui.layout.screen.ScreenViewModel
import io.rover.sdk.experiences.ui.navigation.NavigationViewModel
import io.rover.sdk.experiences.ui.toolbar.ExperienceToolbarViewModel
import io.rover.sdk.experiences.ui.toolbar.ToolbarConfiguration
import java.net.HttpURLConnection
import java.util.concurrent.Executor
/**
* Entry point for the Rover SDK.
*/
open class RoverExperiences(
/**
* When initializing Rover you must give it a reference
*/
private val application: Application,
/**
* Set your Rover Account Token (API Key) here.
*/
private var accountToken: String,
/**
* Set the background colour for the Custom Chrome tabs that are used for presenting web content
* in a web browser.
*/
private val chromeTabBackgroundColor: Int,
/**
* Network service for making Rover API requests via GraphQL.
*/
private val apiService: GraphQlApiServiceInterface
) {
var experienceTransformer: ((Experience) -> Experience)? = null
private set
/**
* Sets an experience transformer on the [RoverExperiences] object enabling retrieved experiences to be altered
* in the desired way. The transformer is called on the UI thread so the transformer shouldn't block
* the thread.
*/
fun setExperienceTransformer(experienceTransformer: (Experience) -> Experience) {
this.experienceTransformer = experienceTransformer
}
fun removeExperienceTransformer() {
experienceTransformer = null
}
/**
* Public in order to be accessible for capturing events for analytics and automation.
*/
val eventEmitter: EventEmitter = EventEmitter()
private val endpoint: String = "https://api.rover.io/graphql"
private val mainScheduler: Scheduler = Scheduler.forAndroidMainThread()
private val ioExecutor: Executor = IoMultiplexingExecutor.build("io")
private val ioScheduler: Scheduler = Scheduler.forExecutor(
ioExecutor
)
private val imageDownloader: ImageDownloader = ImageDownloader(ioExecutor)
private val assetService: AndroidAssetService =
AndroidAssetService(imageDownloader, ioScheduler, mainScheduler)
private val imageOptimizationService: ImageOptimizationService = ImageOptimizationService()
private val packageInfo = application.packageManager.getPackageInfo(application.packageName, 0)
private val httpClient: AndroidHttpsUrlConnectionNetworkClient = AndroidHttpsUrlConnectionNetworkClient(ioScheduler, packageInfo)
internal val webBrowserDisplay: EmbeddedWebBrowserDisplay =
EmbeddedWebBrowserDisplay(chromeTabBackgroundColor)
private val localStorage: LocalStorage = LocalStorage(application)
private val sessionStore: SessionStore = SessionStore(localStorage)
private val analyticsService: AnalyticsService = AnalyticsService(
application,
packageInfo,
accountToken,
eventEmitter
)
private val appOpenedTracker: AppOpenedTracker = AppOpenedTracker(eventEmitter)
private val pollsEndpoint = "https://polls.rover.io/v1/polls"
private val pollVotingService: VotingService = VotingService(pollsEndpoint, httpClient)
private val pollVotingStorage: VotingStorage = VotingStorage(localStorage.getKeyValueStorageFor("voting"))
private val sessionTracker: SessionTracker = SessionTracker(eventEmitter, sessionStore, 10)
private val textFormatter: AndroidRichTextToSpannedTransformer =
AndroidRichTextToSpannedTransformer()
internal val barcodeRenderingService: BarcodeRenderingService = BarcodeRenderingService()
private val measurementService: MeasurementService = MeasurementService(
displayMetrics = application.resources.displayMetrics,
richTextToSpannedTransformer = textFormatter,
barcodeRenderingService = barcodeRenderingService
)
internal val views: Views = Views()
internal val viewModels: ViewModels by lazy {
ViewModels(
apiService,
mainScheduler,
eventEmitter,
sessionTracker,
imageOptimizationService,
assetService,
measurementService,
pollVotingService,
pollVotingStorage
)
}
companion object {
/**
* Be sure to always call this before [RoverExperiences.initialize] in your Application's onCreate()!
*
* Rover internally uses the standard HTTP client included with Android, but to work
* effectively it needs HTTP caching enabled. Unfortunately, this can only be done at the
* global level, so we ask that you call this method -- [installSaneGlobalHttpCache] -- at
* application start time (unless you have already added your own cache to Android's
* [HttpURLConnection].
*/
@JvmStatic
fun installSaneGlobalHttpCache(applicationContext: Context) {
AndroidHttpsUrlConnectionNetworkClient.installSaneGlobalHttpCache(applicationContext)
}
@JvmStatic
@JvmOverloads
fun initialize(
application: Application,
accountToken: String,
@ColorInt chromeTabColor: Int = Color.BLACK,
apiService: GraphQlApiServiceInterface
) {
shared = RoverExperiences(
application = application,
accountToken = accountToken,
chromeTabBackgroundColor = chromeTabColor,
apiService = apiService
)
}
/**
* The global Rover context. A Rover instance must be set here in order to use any of Rover.
* You can use one of the [initialize] methods to do so.
*/
@JvmStatic
var shared: RoverExperiences? = null
}
init {
log.i("Started Rover Android SDK v${BuildConfig.VERSION_NAME}.")
}
}
// TODO: consider moving entire class into appropriate sub-package
internal class ViewModels(
private val apiService: GraphQlApiServiceInterface,
private val mainScheduler: Scheduler,
private val eventEmitter: EventEmitter,
private val sessionTracker: SessionTracker,
private val imageOptimizationService: ImageOptimizationService,
private val assetService: AndroidAssetService,
private val measurementService: MeasurementService,
private val pollVotingService: VotingService,
private val pollVotingStorage: VotingStorage
) {
fun experienceViewModel(
experienceRequest: RoverViewModel.ExperienceRequest,
campaignId: String?,
initialScreenId: String?,
activityLifecycle: Lifecycle,
experienceTransformer: ((Experience) -> Experience)? = RoverExperiences.shared?.experienceTransformer
): RoverViewModel {
return RoverViewModel(
experienceRequest = experienceRequest,
graphQlApiService = apiService,
mainThreadScheduler = mainScheduler,
resolveNavigationViewModel = { experience, icicle ->
experienceNavigationViewModel(experience, campaignId, initialScreenId, activityLifecycle, icicle)
},
experienceTransformer = experienceTransformer
)
}
private fun experienceToolbarViewModel(toolbarConfiguration: ToolbarConfiguration): ExperienceToolbarViewModel {
return ExperienceToolbarViewModel(toolbarConfiguration)
}
private fun experienceNavigationViewModel(
experience: Experience,
campaignId: String?,
initialScreenId: String?,
activityLifecycle: Lifecycle,
icicle: Parcelable? = null
): NavigationViewModel {
return NavigationViewModel(
experience,
eventEmitter = eventEmitter,
campaignId = campaignId,
sessionTracker = sessionTracker,
resolveScreenViewModel = { screen -> screenViewModel(screen, experience, campaignId) },
resolveToolbarViewModel = { configuration -> experienceToolbarViewModel(configuration) },
initialScreenId = initialScreenId,
activityLifecycle = activityLifecycle,
icicle = icicle
)
}
fun screenViewModel(
screen: Screen,
experience: Experience,
campaignId: String?
): ScreenViewModel {
return ScreenViewModel(
screen,
backgroundViewModel(screen.background),
resolveRowViewModel = { row -> rowViewModel(row, screen, experience, campaignId) }
)
}
private fun backgroundViewModel(
background: Background
): BackgroundViewModel {
return BackgroundViewModel(
background = background,
assetService = assetService,
imageOptimizationService = imageOptimizationService,
mainScheduler = mainScheduler
)
}
fun rowViewModel(
row: Row,
screen: Screen,
experience: Experience,
campaignId: String?
): RowViewModel {
return RowViewModel(
row = row,
blockViewModelResolver = { block ->
blockContentsViewModel(block, screen, experience, campaignId)
},
backgroundViewModel = this.backgroundViewModel(row.background)
)
}
private fun blockContentsViewModel(
block: Block,
screen: Screen,
experience: Experience,
campaignId: String?
): CompositeBlockViewModelInterface {
when (block) {
is RectangleBlock -> {
return RectangleBlockViewModel(
blockViewModel = blockViewModel(block, emptySet(), null),
backgroundViewModel = backgroundViewModel(block.background),
borderViewModel = borderViewModel(block.border)
)
}
is TextBlock -> {
val textViewModel = textViewModel(block.text, singleLine = false)
return TextBlockViewModel(
blockViewModel = blockViewModel(block, emptySet(), textViewModel),
textViewModel = textViewModel,
backgroundViewModel = backgroundViewModel(block.background),
borderViewModel = borderViewModel(block.border)
)
}
is ImageBlock -> {
val imageViewModel = imageViewModel(block.image, block)
return ImageBlockViewModel(
blockViewModel = blockViewModel(block, emptySet(), imageViewModel),
backgroundViewModel = backgroundViewModel(block.background),
imageViewModel = imageViewModel,
borderViewModel = borderViewModel(block.border)
)
}
is ButtonBlock -> {
return ButtonBlockViewModel(
blockViewModel = blockViewModel(block, emptySet(), null),
borderViewModel = borderViewModel(block.border),
backgroundViewModel = backgroundViewModel(block.background),
textViewModel = textViewModel(
block.text,
singleLine = true,
centerVertically = true
)
)
}
is WebViewBlock -> {
return WebViewBlockViewModel(
blockViewModel = blockViewModel(block, setOf(), null),
backgroundViewModel = backgroundViewModel(block.background),
borderViewModel = borderViewModel(block.border),
webViewModel = webViewModel(block.webView)
)
}
is BarcodeBlock -> {
val barcodeViewModel = barcodeViewModel(block.barcode)
return BarcodeBlockViewModel(
blockViewModel = blockViewModel(block, emptySet(), barcodeViewModel),
barcodeViewModel = barcodeViewModel
)
}
is TextPollBlock -> {
val textPollViewModel = textPollViewModel(block.textPoll, block, screen, experience, "${experience.id}:${block.id}", campaignId)
return TextPollBlockViewModel(
textPollViewModel = textPollViewModel,
blockViewModel = blockViewModel(block, setOf(), textPollViewModel),
backgroundViewModel = backgroundViewModel(block.background),
borderViewModel = borderViewModel(block.border)
)
}
is ImagePollBlock -> {
val imagePollViewModel = imagePollViewModel(block.imagePoll, block, screen, experience, "${experience.id}:${block.id}", campaignId)
return ImagePollBlockViewModel(
imagePollViewModel = imagePollViewModel,
blockViewModel = blockViewModel(block, setOf(), imagePollViewModel),
backgroundViewModel = backgroundViewModel(block.background),
borderViewModel = borderViewModel(block.border)
)
}
else -> throw Exception(
"This Rover UI block type is not supported by this version of the SDK: ${block.javaClass.simpleName}."
)
}
}
private fun imagePollViewModel(imagePoll: ImagePoll, block: Block, screen: Screen, experience: Experience, id: String, campaignId: String?): ImagePollViewModel {
return ImagePollViewModel(
id = id,
imagePoll = imagePoll,
measurementService = measurementService,
imageOptimizationService = imageOptimizationService,
assetService = assetService,
mainScheduler = mainScheduler,
pollVotingInteractor = VotingInteractor(pollVotingService, pollVotingStorage, mainScheduler),
eventEmitter = eventEmitter,
block = block,
screen = screen,
experience = experience,
campaignId = campaignId
)
}
private fun textPollViewModel(
textPoll: TextPoll,
block: Block,
screen: Screen,
experience: Experience,
id: String,
campaignId: String?
): TextPollViewModel {
return TextPollViewModel(
id,
textPoll,
measurementService,
backgroundViewModel(textPoll.options.first().background),
VotingInteractor(pollVotingService, pollVotingStorage, mainScheduler),
eventEmitter,
block,
screen,
experience,
campaignId
)
}
private fun blockViewModel(
block: Block,
paddingDeflections: Set<LayoutPaddingDeflection>,
measurable: Measurable?
): BlockViewModel {
return BlockViewModel(
block = block,
paddingDeflections = paddingDeflections,
measurable = measurable
)
}
private fun borderViewModel(
border: Border
): BorderViewModel {
return BorderViewModel(border)
}
private fun textViewModel(
text: Text,
singleLine: Boolean,
centerVertically: Boolean = false
): TextViewModel {
return TextViewModel(
styledText = text,
measurementService = measurementService,
singleLine = singleLine,
centerVertically = centerVertically
)
}
private fun imageViewModel(
image: Image,
containingBlock: Block
): ImageViewModel {
return ImageViewModel(
image = image,
block = containingBlock,
imageOptimizationService = imageOptimizationService,
assetService = assetService,
mainScheduler = mainScheduler
)
}
private fun webViewModel(
webView: WebView
): WebViewModel {
return WebViewModel(webView)
}
private fun barcodeViewModel(
barcode: Barcode
): BarcodeViewModel {
return BarcodeViewModel(
barcode,
measurementService
)
}
}
internal class Views {
// TODO: consider moving into RoverView
fun blockAndRowLayoutManager(
layout: Layout,
displayMetrics: DisplayMetrics
): BlockAndRowLayoutManager {
return BlockAndRowLayoutManager(
layout,
displayMetrics
)
}
private fun blockView(
viewType: ViewType,
context: Context
): LayoutableView<out LayoutableViewModel> {
return when (viewType) {
ViewType.Row -> RowView(context)
ViewType.Rectangle -> RectangleBlockView(context)
ViewType.Text -> TextBlockView(context)
ViewType.Button -> ButtonBlockView(context)
ViewType.Image -> ImageBlockView(context)
ViewType.WebView -> WebBlockView(context)
ViewType.Barcode -> BarcodeBlockView(context)
ViewType.TextPoll -> TextPollBlockView(context)
ViewType.ImagePoll -> ImagePollBlockView(context)
}
}
// TODO: consider moving into RoverView
fun blockAndRowRecyclerAdapter(
layout: Layout,
displayMetrics: DisplayMetrics
): BlockAndRowRecyclerAdapter {
return BlockAndRowRecyclerAdapter(
layout = layout,
displayMetrics = displayMetrics,
blockViewFactory = { viewType, context ->
blockView(viewType, context)
}
)
}
} | apache-2.0 | 71995e7742b9c876e0c34fa8a7a8e294 | 38.946274 | 165 | 0.678454 | 5.082249 | false | false | false | false |
lightem90/Sismic | app/src/main/java/com/polito/sismic/Interactors/Helpers/SismicBuildingCalculatorHelper.kt | 1 | 9351 | package com.polito.sismic.Interactors.Helpers
import android.content.Context
import com.polito.sismic.Domain.*
import com.polito.sismic.Extensions.distanceFrom
import com.polito.sismic.Extensions.verticalMiddlePoint
import com.polito.sismic.R
/**
* Created by it0003971 on 15/09/2017.
*/
enum class LivelloConoscenza(val multiplier: Double) {
I(1.35),
II(1.20),
III(1.00)
}
enum class C1(val multiplier: Double) {
Acciaio(0.085),
Calcestruzzo(0.075),
Altro(0.050)
}
class SismicBuildingCalculatorHelper(val mContext: Context) {
//Stati functions to help mapping from ui to domain
companion object {
val SENSIBILITY = 20
val TO_FROM_KN = 1000.0
val TO_FROM_KN_M = 1000000.0
fun calculateECM(fcm: Double, lcCalc: Double): Double {
val newFcm = fcm / lcCalc
return 22000 * (Math.pow((newFcm / 10), 0.3))
}
fun calculateFCD(fck: Double, lcCalc: Double): Double {
return 0.85 * (fck / lcCalc) / 1.5
}
fun calculateFYD(fyk: Double, lcAcc: Double): Double {
return (fyk / lcAcc) / 1.15
}
fun calculateAs(numFerri: Int, diamFerri: Double): Double {
val r = diamFerri / 2
return numFerri * (Math.PI * r * r) //mm * mm
}
fun calculateT1(hTot: Double): Double {
val exp = (3.0 / 4.0)
return C1.Calcestruzzo.multiplier * Math.pow(hTot, exp)
}
//returns a value in kN, the weigths are for kN/mq
fun calculateBuildWeigth(numPiani : Int, areaTot : Double, pesoSolaio: Double, pesoCopertura: Double): Double {
return if (numPiani > 1) {
(((numPiani - 1) * (pesoSolaio)) + pesoCopertura) * areaTot
} else {
pesoCopertura * areaTot
}
}
fun calculateGravityCenter(pointList: List<PlantPoint>): PlantPoint {
val triangleList = createTriangleList(pointList)
val tripleList = triangleList.map {
val xi = (it.first.x + it.second.x + it.third.x) / 3
val yi = (it.first.y + it.second.y + it.third.y) / 3
val s = deterimantOf(it)
Triple(xi, yi, s)
}
//sum of (xi * si) / sum of (s)
val sumOfS = tripleList.sumByDouble { it.third }
val xg = (tripleList.sumByDouble { it.first * it.third }) / sumOfS
val yg = (tripleList.sumByDouble { it.second * it.third }) / sumOfS
return PlantPoint(xg, yg)
}
private fun deterimantOf(triple: Triple<PlantPoint, PlantPoint, PlantPoint>): Double = with(triple) {
val firstQuadrant = first.x * (second.y - third.y)
val secondQuadrant = first.y * (second.x - third.x)
val thirdQuadrant = ((second.x * third.y) - (second.y * third.x))
firstQuadrant - secondQuadrant + thirdQuadrant
}
private fun createTriangleList(pointList: List<PlantPoint>): List<Triple<PlantPoint, PlantPoint, PlantPoint>> {
return (1 until pointList.size - 1).map { Triple(pointList[0], pointList[it], pointList[it + 1]) }
}
fun calculatePerimeter(pointList: List<PlantPoint>): Double {
var sum = 0.0
for (i in 0 until pointList.size) {
if (i == pointList.size - 1) {
sum += pointList[i].distanceFrom(pointList[0])
continue
}
sum += pointList[i].distanceFrom(pointList[i + 1])
}
return sum
}
fun calculateArea(pointList: List<PlantPoint>): Double {
val leftSum = (0 until pointList.size - 1).sumByDouble { (pointList[it].x * pointList[it + 1].y) }
val rightSum = (0 until pointList.size - 1).sumByDouble { (pointList[it].y * pointList[it + 1].x) }
return (leftSum + rightSum) / 2
}
}
// AND Denis data
fun getPillarDomainForGraph(data: PillarState): List<PillarDomainGraphPoint> = with(data) {
val entries = mutableListOf<PillarDomainGraphPoint>()
//first and last point consider a linear interval, parabolic in between
entries.add(calculatePointOne(fyd, area_ferri))
entries.addAll(calculateFromThreeToFour(fcd, bx, area_ferri, fyd, c, hy))
entries.add(calculatePointTwo(fyd, area_ferri, bx, hy, fcd))
entries.forEach {
//from n to kn
it.n = (it.n / TO_FROM_KN)
//from nmm to kNm
it.m = (it.m / TO_FROM_KN_M)
}
return entries
}
//Based on http://www.federica.unina.it/architettura/laboratorio-di-tecnica-delle-costruzioni/slu-pressoflessione/
//Point 1 is on the left (x is negative) and we got a line until point 3. Point 2 is on the other side with M = 0
//Point 3 to 4 form a curve.
private fun calculateFromThreeToFour(fcd: Double, b: Double, As: Double, fyd: Double, dFirst: Double, H: Double): List<PillarDomainGraphPoint> {
val points = mutableListOf<PillarDomainGraphPoint>()
var h = 0.0
val step = H / SENSIBILITY
val notHeigthDependingValue = (As * fyd) * (H - (2 * dFirst))
while (h <= H) {
points.add(innerCalculatePointFromThreeToFour(notHeigthDependingValue, h, H, fcd, b))
h += step
}
return points.toList()
}
private fun innerCalculatePointFromThreeToFour(notHeigthDependingValue: Double, h: Double, H: Double, fcd: Double, b: Double): PillarDomainGraphPoint {
val n = fcd * b * h
val m = fastCalculateM(notHeigthDependingValue, h, n, H)
return PillarDomainGraphPoint(n, m)
}
private fun fastCalculateM(notHeigthDependingValue: Double, h: Double, n: Double, H: Double): Double {
return notHeigthDependingValue + (n * ((H / 2) - (h / 2)))
}
private fun calculateMFromN(As: Double, fyd: Double, H: Double, dFirst: Double, n: Double, h: Double): Double {
return (As * fyd) * (H - (2 * dFirst)) + (n * ((H / 2) - (h / 2)))
}
private fun calculatePointOne(fyd: Double, As: Double): PillarDomainGraphPoint {
val nTrd = -(2 * fyd * As)
return PillarDomainGraphPoint(nTrd, 0.0)
}
private fun calculatePointTwo(fyd: Double, As: Double, b: Double, H: Double, fcd: Double): PillarDomainGraphPoint {
val nCrd = (2 * fyd * As) + (fcd * b * H)
return PillarDomainGraphPoint(nCrd, 0.0)
}
//If this point is inside domain... all good
fun getLimitStatePointsInDomainForPillar(state: ReportState): List<PillarDomainPoint> {
//N is the component on X axis
val nPiani = state.buildingState.takeoverState.numero_piani
val pesoSpecVerticale = if (nPiani == 1) //in kn/mq
{
state.buildingState.structuralState.q_copertura
} else {
state.buildingState.structuralState.q_copertura +
(state.buildingState.structuralState.q_solaio * nPiani - 1)
}
//in kn, weigth on a single pillar (by influence area)
val nPoint = state.buildingState.pillarLayoutState.area * pesoSpecVerticale * 1.3 //+30% for pillar
//To calculate m i find the closest t on the graph foreach spectrum, find the relative fh and divide it foreach pillar
//Finally by multiplying by H/2 i find the fh horizontal component (M)
val t1 = state.buildingState.takeoverState.t1
val lambda = state.buildingState.takeoverState.lambda
val limitStatePoints = mutableListOf<PillarDomainPoint>()
//get the first point on x that is greater than wanted point
state.sismicState.projectSpectrumState.spectrums.mapTo(limitStatePoints) { spectrum ->
var forcePointIndex = spectrum.pointList.indexOfFirst { it.x >= t1 }
if (forcePointIndex == 0) forcePointIndex++
//simple interpolation on y to get acceleration value
val acceleration = spectrum.pointList[forcePointIndex].verticalMiddlePoint(spectrum.pointList[forcePointIndex - 1])
val force = acceleration * (state.buildingState.structuralState.peso_totale * lambda) // / 9.80665)
val ty = force / state.buildingState.pillarLayoutState.pillarCount
val mPoint = ty * (state.buildingState.takeoverState.altezza_piano_terra / 2)
PillarDomainPoint(nPoint, mPoint, acceleration, force, ty, spectrum.name, spectrum.color)
}
//Add mrd point (the same n, it should be on domain line)
calculateMrd(nPoint, state.buildingState.pillarState)?.let {
limitStatePoints.add(it)
}
return limitStatePoints.toList()
}
private fun calculateMrd(n: Double, pillarState: PillarState): PillarDomainPoint? {
if (pillarState.fcd == 0.0 || pillarState.bx == 0.0) return null
//I dont have h, so i calculate by inverting the formula above (its not ok if the value is not between h and H
val h = (n * TO_FROM_KN) / (pillarState.fcd * pillarState.bx)
val m = calculateMFromN(pillarState.area_ferri, pillarState.fyd, pillarState.hy, pillarState.c, (n * TO_FROM_KN), h) / TO_FROM_KN_M
return PillarDomainPoint(n, m, 0.0, 0.0, 0.0, "MRD", R.color.mrd)
}
} | mit | 969ca4d7c4f96cd6ad75d2b6cd739a5d | 40.017544 | 155 | 0.615549 | 3.575908 | false | false | false | false |
KrenVpravo/SafeFacebook | app/src/main/java/com/krenvpravo/safefacebook/Constants.kt | 1 | 500 | package com.krenvpravo.safefacebook
/**
* @author Dmitry Borodin on 2017-01-22.
*/
object Constants {
val MAIN_URL = "https://m.facebook.com/"
val GROUPS_URL = "https://m.facebook.com/groups/?seemore"
val FRIENDS_URL = "https://m.facebook.com/buddylist.php"
val MESSAGES_RUL = "https://m.facebook.com/messages/"
val USERAGENT_CHROME = "Mozilla/5.0 (Linux; Android 4.4.4; One Build/KTU84L.H4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.135 Mobile Safari/537.36"
}
| apache-2.0 | 776bb2333163d9cf9930d4efc54a3924 | 37.461538 | 165 | 0.694 | 2.840909 | false | false | false | false |
FHannes/intellij-community | uast/uast-common/src/org/jetbrains/uast/declarations/UClass.kt | 8 | 3281 | /*
* 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 org.jetbrains.uast
import com.intellij.psi.PsiAnonymousClass
import com.intellij.psi.PsiClass
import org.jetbrains.uast.internal.acceptList
import org.jetbrains.uast.internal.log
import org.jetbrains.uast.visitor.UastTypedVisitor
import org.jetbrains.uast.visitor.UastVisitor
/**
* A class wrapper to be used in [UastVisitor].
*/
interface UClass : UDeclaration, PsiClass {
override val psi: PsiClass
/**
* Returns a [UClass] wrapper of the superclass of this class, or null if this class is [java.lang.Object].
*/
override fun getSuperClass(): UClass? {
val superClass = psi.superClass ?: return null
return getUastContext().convertWithParent(superClass)
}
val uastSuperTypes: List<UTypeReferenceExpression>
/**
* Returns [UDeclaration] wrappers for the class declarations.
*/
val uastDeclarations: List<UDeclaration>
override fun getFields(): Array<UField> =
psi.fields.map { getLanguagePlugin().convert<UField>(it, this) }.toTypedArray()
override fun getInitializers(): Array<UClassInitializer> =
psi.initializers.map { getLanguagePlugin().convert<UClassInitializer>(it, this) }.toTypedArray()
override fun getMethods(): Array<UMethod> =
psi.methods.map { getLanguagePlugin().convert<UMethod>(it, this) }.toTypedArray()
override fun getInnerClasses(): Array<UClass> =
psi.innerClasses.map { getLanguagePlugin().convert<UClass>(it, this) }.toTypedArray()
override fun asLogString() = log("name = $name")
override fun accept(visitor: UastVisitor) {
if (visitor.visitClass(this)) return
annotations.acceptList(visitor)
uastDeclarations.acceptList(visitor)
visitor.afterVisitClass(this)
}
override fun asRenderString() = buildString {
append(psi.renderModifiers())
val kind = when {
psi.isAnnotationType -> "annotation"
psi.isInterface -> "interface"
psi.isEnum -> "enum"
else -> "class"
}
append(kind).append(' ').append(psi.name)
val superTypes = uastSuperTypes
if (superTypes.isNotEmpty()) {
append(" : ")
append(superTypes.joinToString { it.asRenderString() })
}
appendln(" {")
uastDeclarations.forEachIndexed { index, declaration ->
appendln(declaration.asRenderString().withMargin)
}
append("}")
}
override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D) =
visitor.visitClass(this, data)
}
interface UAnonymousClass : UClass, PsiAnonymousClass {
override val psi: PsiAnonymousClass
} | apache-2.0 | 3af9b7bed52273842a80711ddd061528 | 33.914894 | 111 | 0.679976 | 4.634181 | false | false | false | false |
KawaiiTech/slack-bot | src/main/kotlin/Bot.kt | 1 | 1345 | import kotlin.js.json
object Bot {
var controller: dynamic = null
init {
initBotController()
}
private fun initBotController() {
val config = json("json_file_store" to "./db_slack_bot_ci/")
val customIntegration = require("../lib/custom_integrations")
val token = process.env.TOKEN ?: process.env.SLACK_TOKEN
controller = customIntegration.configure(token, config, Bot::onInstallation)
controller.on("rtm_open", {
println("** The RTM api just connected!")
})
controller.on("rtm_close", {
println("** The RTM api just closed")
})
controller.on("bot_channel_join", { bot, message ->
bot.reply(message, "I'm here!")
})
controller.hears("hello", "direct_message", { bot, message ->
bot.reply(message, "Hello!")
})
}
fun onInstallation(bot: dynamic, installer: dynamic) {
installer?.let {
bot.startPrivateConversation(json("user" to installer), {
err, convo ->
if (err != null) println(err) else {
convo.say("I am a bot that has just joined your team")
convo.say("You must now /invite me to a channel so that I can be of use!")
}
})
}
}
} | mit | 6f80a9a06acab1734840cc84e6097494 | 32.65 | 94 | 0.544981 | 4.269841 | false | true | false | false |
QuickBlox/quickblox-android-sdk | sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/presentation/screens/createchat/ViewState.kt | 1 | 1292 | package com.quickblox.sample.conference.kotlin.presentation.screens.createchat
import androidx.annotation.IntDef
import com.quickblox.sample.conference.kotlin.presentation.screens.createchat.ViewState.Companion.CREATE_CHAT
import com.quickblox.sample.conference.kotlin.presentation.screens.createchat.ViewState.Companion.ERROR
import com.quickblox.sample.conference.kotlin.presentation.screens.createchat.ViewState.Companion.SHOW_CHAT_SCREEN
import com.quickblox.sample.conference.kotlin.presentation.screens.createchat.ViewState.Companion.SHOW_LOGIN_SCREEN
import com.quickblox.sample.conference.kotlin.presentation.screens.createchat.ViewState.Companion.SHOW_NAME_CHAT_SCREEN
import com.quickblox.sample.conference.kotlin.presentation.screens.createchat.ViewState.Companion.SHOW_NEW_CHAT_SCREEN
/*
* Created by Injoit in 2021-09-30.
* Copyright © 2021 Quickblox. All rights reserved.
*/
@IntDef(SHOW_NEW_CHAT_SCREEN, SHOW_NAME_CHAT_SCREEN, SHOW_CHAT_SCREEN, CREATE_CHAT, ERROR, SHOW_LOGIN_SCREEN)
annotation class ViewState {
companion object {
const val SHOW_NEW_CHAT_SCREEN = 0
const val SHOW_NAME_CHAT_SCREEN = 1
const val SHOW_CHAT_SCREEN = 2
const val CREATE_CHAT = 3
const val ERROR = 4
const val SHOW_LOGIN_SCREEN = 5
}
} | bsd-3-clause | d88cb7b9513fca553d0b645ff6538877 | 50.68 | 119 | 0.791634 | 3.935976 | false | false | false | false |
QuickBlox/quickblox-android-sdk | sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/presentation/LiveData.kt | 1 | 1826 | package com.quickblox.sample.conference.kotlin.presentation
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
/*
* Created by Injoit in 2021-09-30.
* Copyright © 2021 Quickblox. All rights reserved.
*/
class LiveData<T> {
private var value: T? = null
private val observers: HashMap<(T?) -> Unit, LiveDataLifecycleObserver> = HashMap()
fun setValue(value: T?) {
this.value = value
for (lifecycleObserver in observers.values) {
val owner = lifecycleObserver.owner
if (owner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED))
notifyChange(lifecycleObserver)
}
}
fun getValue(): T? {
return value
}
fun observe(owner: LifecycleOwner, observer: (T?) -> Unit) {
val lifecycleObserver = LiveDataLifecycleObserver(owner, observer)
observers[observer] = lifecycleObserver
owner.lifecycle.addObserver(lifecycleObserver)
}
fun removeObserver(observer: (T?) -> Unit) {
val lifecycleObserver = observers.remove(observer)
lifecycleObserver?.owner?.lifecycle?.removeObserver(lifecycleObserver)
}
private fun notifyChange(lifecycleObserver: LiveDataLifecycleObserver) {
lifecycleObserver.observer.invoke(value)
this.value = null
}
private inner class LiveDataLifecycleObserver(val owner: LifecycleOwner, val observer: (T?) -> Unit) : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
private fun onResumed() {
notifyChange(this)
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
private fun onDestroyed() {
removeObserver(observer)
}
}
} | bsd-3-clause | 829bb03c4b8c82a0e354ee92c825314c | 31.035088 | 126 | 0.68274 | 4.853723 | false | false | false | false |
light-and-salt/kotloid | src/main/kotlin/kr/or/lightsalt/kotloid/app/TabsFragment.kt | 1 | 1624 | package kr.or.lightsalt.kotloid.app
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
import kr.or.lightsalt.kotloid.R
import kr.or.lightsalt.kotloid.lazyViewById
import kotlin.reflect.KClass
@Suppress("HasPlatformType", "MemberVisibilityCanBePrivate", "unused")
open class TabsFragment<T>(contentLayoutId: Int = R.layout.fragment_tabs) : Fragment(contentLayoutId)
where T : PagerAdapter, T : IFragmentPagerAdapter<TabsFragment.Tab> {
var tabLayout by lazyViewById<TabLayout>(R.id.tabLayout)
var viewPager by lazyViewById<ViewPager>(R.id.viewPager)
var adapter: T? = null
set(value) {
field = value
viewPager.adapter = value
val tabLayout = tabLayout
tabLayout.setupWithViewPager(viewPager)
for (i in 0 until tabLayout.tabCount) {
value!!.getPage(i).data?.icon?.let(tabLayout.getTabAt(i)!!::setIcon)
}
}
override fun onDestroyView() {
super.onDestroyView()
adapter = null
tabLayout = null
viewPager = null
}
open class Tab constructor(
var icon: Int? = null
)
companion object {
fun tabPage(
fragment: KClass<out Fragment>,
title: CharSequence? = null,
icon: Int? = null,
args: Bundle? = null
) = Page.FragmentPage<Tab>(fragment, args).apply {
data = Tab(icon)
this.title = title
}
}
}
| apache-2.0 | 23d34d905df6a8777c0a0eb9db2f7255 | 30.843137 | 101 | 0.644089 | 4.437158 | false | false | false | false |
SpineEventEngine/core-java | buildSrc/src/main/kotlin/io/spine/internal/gradle/publish/CloudRepo.kt | 2 | 2613 | /*
* Copyright 2022, TeamDev. 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
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* 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 io.spine.internal.gradle.publish
import io.spine.internal.gradle.Repository
/**
* CloudRepo Maven repository.
*
* There is a special treatment for this repository. Usually, fetching and publishing of artifacts
* is performed via the same URL. But it is not true for CloudRepo. Fetching is performed via
* public repository, and publishing via private one. Their URLs differ in `/public` infix.
*/
internal object CloudRepo {
private const val name = "CloudRepo"
private const val credentialsFile = "cloudrepo.properties"
private const val publicUrl = "https://spine.mycloudrepo.io/public/repositories"
private val privateUrl = publicUrl.replace("/public", "")
/**
* CloudRepo repository for fetching of artifacts.
*
* Use this instance to depend on artifacts from this repository.
*/
val published = Repository(
name = name,
releases = "$publicUrl/releases",
snapshots = "$publicUrl/snapshots",
credentialsFile = credentialsFile
)
/**
* CloudRepo repository for publishing of artifacts.
*
* Use this instance to push new artifacts to this repository.
*/
val destination = Repository(
name = name,
releases = "$privateUrl/releases",
snapshots = "$privateUrl/snapshots",
credentialsFile = credentialsFile
)
}
| apache-2.0 | 34ee9d176572b4acf670f745857015c6 | 37.426471 | 98 | 0.719097 | 4.536458 | false | false | false | false |
nickthecoder/paratask | paratask-examples/src/main/kotlin/uk/co/nickthecoder/paratask/examples/GroupExample.kt | 1 | 1483 | package uk.co.nickthecoder.paratask.examples
import uk.co.nickthecoder.paratask.AbstractTask
import uk.co.nickthecoder.paratask.TaskDescription
import uk.co.nickthecoder.paratask.TaskParser
import uk.co.nickthecoder.paratask.parameters.*
class GroupExample : AbstractTask(), ParameterListener {
val normalIntP = IntParameter("normalInt", label = "Int")
val normalStringP = StringParameter("normalString", label = "String", columns = 10)
val normalGroupP = SimpleGroupParameter("normalGroup")
.addParameters(normalIntP, normalStringP)
val plainIntP = IntParameter("plainInt", label = "Int")
val plainStringP = StringParameter("plainString", label = "String", columns = 10)
val plainGroupP = SimpleGroupParameter("plainGroup")
.addParameters(plainIntP, plainStringP).asPlain()
override val taskD = TaskDescription("groupExample",
description = """Demonstrates how to group parameters.
There are other ways to lay out groups. See HorizontalGroupExample, and GridGroupExample.""")
.addParameters(normalGroupP, plainGroupP)
init {
plainGroupP.parameterListeners.add(this)
}
override fun parameterChanged(event: ParameterEvent) {
println("parameter=${event.parameter} inner=${event.innerParameter} type=${event.type} oldValue=${event.oldValue}")
}
override fun run() {
}
}
fun main(args: Array<String>) {
TaskParser(GroupExample()).go(args, prompt = true)
}
| gpl-3.0 | 97f0da2f543197744345ac7c080731ca | 35.170732 | 123 | 0.72151 | 4.249284 | false | false | false | false |
ashdavies/data-binding | mobile/src/main/kotlin/io/ashdavies/playground/conferences/ConferencesBoundaryCallback.kt | 1 | 1217 | package io.ashdavies.playground.conferences
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.paging.PagedList
import io.ashdavies.playground.github.ConferenceDao
import io.ashdavies.playground.network.Conference
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
internal class ConferencesBoundaryCallback(
private val dao: ConferenceDao,
private val scope: CoroutineScope,
private val service: ConferencesService
) : PagedList.BoundaryCallback<Conference>() {
private val _error: MutableLiveData<Throwable> = MutableLiveData()
val error: LiveData<Throwable> = _error
private var page: Int = 0
override fun onZeroItemsLoaded() {
requestItems()
}
override fun onItemAtEndLoaded(itemAtEnd: Conference) {
requestItems()
}
private fun requestItems() {
scope.launch {
val result: Result<List<Conference>> = runCatching {
service.conferences(page, NETWORK_PAGE_SIZE)
}
result.onSuccess {
dao.insert(it)
page++
}
result.onFailure {
_error.postValue(it)
}
}
}
companion object {
private const val NETWORK_PAGE_SIZE = 50L
}
}
| apache-2.0 | 4158031e4cce1847a4ff823b569ac281 | 22.862745 | 68 | 0.721446 | 4.393502 | false | false | false | false |
nemerosa/ontrack | ontrack-kdsl-acceptance/src/test/java/net/nemerosa/ontrack/kdsl/acceptance/tests/metrics/MetricsSupportTest.kt | 1 | 5084 | package net.nemerosa.ontrack.kdsl.acceptance.tests.metrics
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class MetricsSupportTest {
@Test
fun `Parsing Prometheus data`() {
val data = """
# HELP tomcat_sessions_active_max_sessions Maximum number of sessions in Tomcat
# TYPE tomcat_sessions_active_max_sessions gauge
tomcat_sessions_active_max_sessions 0.0
# HELP ontrack_entity_event_total
# TYPE ontrack_entity_event_total gauge
ontrack_entity_event_total 16.0
# HELP ontrack_connector_count Number of connectors
# TYPE ontrack_connector_count gauge
ontrack_connector_count{type="git",} 0.0
ontrack_connector_count{type="github",} 1.0
ontrack_connector_count{type="sonarqube",} 2.0
ontrack_connector_count{type="artifactory",} 0.0
# HELP rabbitmq_unrouted_published_total
# TYPE rabbitmq_unrouted_published_total counter
rabbitmq_unrouted_published_total{name="rabbit",} 20.0
# HELP ontrack_job_duration_ms_seconds
# TYPE ontrack_job_duration_ms_seconds summary
ontrack_job_duration_ms_seconds_count{job_category="core",job_id="git",job_type="connector-status",} 29.0
ontrack_job_duration_ms_seconds_sum{job_category="core",job_id="git",job_type="connector-status",} 0.229
ontrack_job_duration_ms_seconds_count{job_category="core",job_id="nop",job_type="connector-status",} 30.0
ontrack_job_duration_ms_seconds_sum{job_category="core",job_id="nop",job_type="connector-status",} 0.002
""".trimIndent()
val metrics = MetricsSupport.parseMetrics(data)
assertEquals(
MetricCollection(
listOf(
Metric(
"tomcat_sessions_active_max_sessions",
"gauge",
"Maximum number of sessions in Tomcat",
listOf(
MetricValue(value = 0.0),
),
),
Metric(
"ontrack_entity_event_total",
"gauge",
"",
listOf(
MetricValue(value = 16.0),
),
),
Metric(
"ontrack_connector_count",
"gauge",
"Number of connectors",
listOf(
MetricValue(value = 0.0, "type" to "git"),
MetricValue(value = 1.0, "type" to "github"),
MetricValue(value = 2.0, "type" to "sonarqube"),
MetricValue(value = 0.0, "type" to "artifactory"),
),
),
Metric(
"rabbitmq_unrouted_published_total",
"counter",
"",
listOf(
MetricValue(value = 20.0, "name" to "rabbit"),
),
),
Metric(
"ontrack_job_duration_ms_seconds",
"summary",
"",
listOf(
MetricValue(
value = 29.0,
name = "ontrack_job_duration_ms_seconds_count",
"job_category" to "core",
"job_id" to "git",
"job_type" to "connector-status"
),
MetricValue(
value = 0.229,
name = "ontrack_job_duration_ms_seconds_sum",
"job_category" to "core",
"job_id" to "git",
"job_type" to "connector-status"
),
MetricValue(
value = 30.0,
name = "ontrack_job_duration_ms_seconds_count",
"job_category" to "core",
"job_id" to "nop",
"job_type" to "connector-status"
),
MetricValue(
value = 0.002,
name = "ontrack_job_duration_ms_seconds_sum",
"job_category" to "core",
"job_id" to "nop",
"job_type" to "connector-status"
),
),
),
)
),
metrics
)
}
} | mit | 4a693e07c7fd79656f279f2f6ad51448 | 44 | 117 | 0.409127 | 5.214359 | false | false | false | false |
programingjd/server | src/main/kotlin/info/jdavid/asynk/server/http/handler/FileHandler.kt | 1 | 6245 | package info.jdavid.asynk.server.http.handler
import info.jdavid.asynk.core.asyncWrite
import info.jdavid.asynk.http.Headers
import info.jdavid.asynk.http.MediaType
import info.jdavid.asynk.http.Method
import info.jdavid.asynk.http.Status
import info.jdavid.asynk.http.Uri
import info.jdavid.asynk.server.Server
import info.jdavid.asynk.server.http.CacheControl
import info.jdavid.asynk.server.http.base.AbstractHttpHandler
import info.jdavid.asynk.server.http.route.FileRoute
import java.io.File
import java.net.InetAddress
import java.net.InetSocketAddress
import java.nio.ByteBuffer
import java.nio.channels.AsynchronousSocketChannel
import java.util.Base64
/**
* File-based HTTP Handler.<br>
* By default, it uses the default [CacheControl] policies.<br>
* ETags are generated based on the last modification date and time.<br>
* No cache is used by default. All new requests (unless Unmodified is returned because of the ETag) are
* reading the file content directly from disk. It is possible (and recommended) to extend this handler
* to implement a caching mechanism.
*/
open class FileHandler(route: FileRoute): HttpHandler<HttpHandler.Acceptance<File>,
File,
AbstractHttpHandler.Context,
File>(route) {
companion object {
internal fun serveDirectory(directory: File, port: Int) {
Server(
FileHandler(FileRoute(directory)),
InetSocketAddress(InetAddress.getLoopbackAddress(), port)
).use {
Thread.sleep(Long.MAX_VALUE)
}
}
/**
* Starts a server that serves the current directory on localhost:8080.
* @param args are not used.
*/
@JvmStatic fun main(args: Array<String>) {
serveDirectory(File("."), 8080)
}
}
final override suspend fun handle(acceptance: Acceptance<File>, headers: Headers, body: ByteBuffer,
context: Context): Response<*> {
val uriParams = acceptance.routeParams
val file = if (uriParams.isDirectory) {
val path = Uri.path(acceptance.uri)
if (path.last() != '/') return redirect("${path}/${acceptance.uri.substring(path.length)}")
indexFilenames().map { File(uriParams, it) }.firstOrNull { it.exists() } ?: return forbidden(context)
} else uriParams
val mediaType = mediaType(file) ?: return forbidden(context)
val cacheControl = mediaTypes()[mediaType] ?: return forbidden(context)
val responseHeaders = Headers()
responseHeaders.set(Headers.CACHE_CONTROL, cacheControl.value())
if (cacheControl.maxAge > -1) {
val etag = etag(file) ?: return FileResponse(file, mediaType, responseHeaders)
responseHeaders.set(Headers.ETAG, etag)
if (etag == headers.value(Headers.IF_NONE_MATCH)) return notModified(responseHeaders)
return FileResponse(file, mediaType, responseHeaders)
}
else {
return FileResponse(file, mediaType, responseHeaders)
}
}
/**
* Returns the ETag value for the specified file.<br>
* By default, the ETag is generated based on the file last modification date and time.
* @param file the file to serve.
* @return the ETag value (can be null, in which case no ETag will be sent).
*/
protected open fun etag(file: File): String? {
return Base64.getUrlEncoder().encodeToString(
String.format("%012x", file.lastModified()).toByteArray(Charsets.US_ASCII)
)
}
/**
* Returns the media type of the file or null if it is not known.
* @param file the file.
* @return the file media type or null if it is not known.
*/
protected open fun mediaType(file: File): String? {
return MediaType.fromFile(file)
}
/**
* Returns the media types that are allowed with their cache control policies.
* @return the map of key/value entries with the key being the allowed media type and the value being the
* associated cache control policy.
*/
protected open fun mediaTypes() = CacheControl.defaultCacheControls
/**
* Returns an (ordered) sequence of file names that can be used as directory "index" pages. The first match
* is used. By defaults, this only includes "index.html".
* @return the sequence of file names for index pages.
*/
protected open fun indexFilenames(): Sequence<String> = sequenceOf("index.html")
private fun notModified(h: Headers) = object: Response<Nothing>(
Status.NOT_MODIFIED, null, h) {
override fun bodyMediaType(body: Nothing) = throw UnsupportedOperationException()
override suspend fun bodyByteLength(body: Nothing) = throw UnsupportedOperationException()
override suspend fun writeBody(socket: AsynchronousSocketChannel, buffer: ByteBuffer) {}
}
private fun redirect(uri: String) = object: Response<Nothing>(
Status.MOVED_PERMANENTLY) {
override fun bodyMediaType(body: Nothing) = throw UnsupportedOperationException()
override suspend fun bodyByteLength(body: Nothing) = throw UnsupportedOperationException()
override suspend fun writeBody(socket: AsynchronousSocketChannel, buffer: ByteBuffer) {}
}.header(Headers.LOCATION, uri)
/**
* Creates a 403 Forbidden response. By default, this sends a response with no body.
*/
private fun forbidden(context: Context) = object: Response<Nothing>(
Status.FORBIDDEN) {
override fun bodyMediaType(body: Nothing) = throw UnsupportedOperationException()
override suspend fun bodyByteLength(body: Nothing) = throw UnsupportedOperationException()
override suspend fun writeBody(socket: AsynchronousSocketChannel, buffer: ByteBuffer) {}
override suspend fun write(socket: AsynchronousSocketChannel, buffer: ByteBuffer, method: Method) {
context.FORBIDDEN.flip()
socket.asyncWrite(context.FORBIDDEN, true)
}
}.header(Headers.CONNECTION, "close")
override suspend fun context(others: Collection<*>?) = Context(others, route.maxRequestSize)
override suspend fun acceptUri(remoteAddress: InetSocketAddress,
method: Method, uri: String, params: File): Acceptance<File>? {
return Acceptance(remoteAddress, false, false, method, uri, params)
}
}
| apache-2.0 | e02505a905b2d1eeb06a38980cb9a5c5 | 41.773973 | 109 | 0.702802 | 4.545124 | false | false | false | false |
drakeet/MultiType | sample/src/main/kotlin/com/drakeet/multitype/sample/selectable/MultiSelectableActivity.kt | 1 | 2813 | /*
* Copyright (c) 2016-present. Drakeet Xu
*
* 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.drakeet.multitype.sample.selectable
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.drakeet.multitype.MultiTypeAdapter
import com.drakeet.multitype.sample.MenuBaseActivity
import com.drakeet.multitype.sample.R
import com.drakeet.multitype.sample.common.Category
import com.drakeet.multitype.sample.common.CategoryHolderInflater
import java.util.*
class MultiSelectableActivity : MenuBaseActivity() {
var items: MutableList<Any> = ArrayList()
var adapter = MultiTypeAdapter()
private lateinit var fab: Button
private lateinit var selectedSet: TreeSet<Int>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_multi_selectable)
val recyclerView = findViewById<RecyclerView>(R.id.list)
val layoutManager = GridLayoutManager(this, SPAN_COUNT)
layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
return if (items[position] is Category) SPAN_COUNT else 1
}
}
selectedSet = TreeSet()
recyclerView.layoutManager = layoutManager
adapter.register(CategoryHolderInflater())
adapter.register(SquareViewBinder(selectedSet))
loadData()
recyclerView.adapter = adapter
setupFAB()
}
private fun loadData() {
val spacialCategory = Category("特别篇")
items.add(spacialCategory)
for (i in 0..6) {
items.add(Square(i + 1))
}
val currentCategory = Category("本篇")
items.add(currentCategory)
for (i in 0..999) {
items.add(Square(i + 1))
}
adapter.items = items
adapter.notifyDataSetChanged()
}
private fun setupFAB() {
fab = findViewById(R.id.fab)
fab.setOnClickListener { v ->
val content = StringBuilder()
for (number in selectedSet) {
content.append(number).append(" ")
}
Toast.makeText(v.context, "Selected items: $content", Toast.LENGTH_SHORT).show()
}
}
companion object {
private const val SPAN_COUNT = 5
}
}
| apache-2.0 | ce7635708d9b8b4ebf7b1ebe7a8b359f | 30.144444 | 86 | 0.726008 | 4.234139 | false | false | false | false |
REBOOTERS/AndroidAnimationExercise | imitate/src/main/java/com/engineer/imitate/interfaces/SimpleActivityCallback.kt | 1 | 1555 | package com.engineer.imitate.interfaces
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.util.Log
/**
* @author Rookie
* @since 07-01-2020
*/
@SuppressLint("LogNotTimber")
open class SimpleActivityCallback : Application.ActivityLifecycleCallbacks {
val TAG = "activity-life"
override fun onActivityPaused(activity: Activity) {
Log.d(TAG, "onActivityPaused() called with: activity = $activity")
}
override fun onActivityStarted(activity: Activity) {
Log.d(TAG, "onActivityStarted() called with: activity = $activity")
}
override fun onActivityDestroyed(activity: Activity) {
Log.d(TAG, "onActivityDestroyed() called with: activity = $activity")
}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
Log.d(
TAG,
"onActivitySaveInstanceState() called with: activity = $activity, outState = $outState"
)
}
override fun onActivityStopped(activity: Activity) {
Log.d(TAG, "onActivityStopped() called with: activity = $activity")
}
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
Log.d(
TAG,
"onActivityCreated() called with: activity = $activity, savedInstanceState = $savedInstanceState"
)
}
override fun onActivityResumed(activity: Activity) {
Log.d(TAG, "onActivityResumed() called with: activity = $activity")
}
} | apache-2.0 | 5a4703f9d8445eacfcb03ca2aa0ae28e | 30.12 | 109 | 0.686174 | 4.726444 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/facet/MinecraftFacetEditorTab.kt | 1 | 10254 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.facet
import com.demonwav.mcdev.asset.PlatformAssets
import com.demonwav.mcdev.platform.PlatformType
import com.intellij.facet.ui.FacetEditorTab
import com.intellij.util.ui.UIUtil
import javax.swing.JCheckBox
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
class MinecraftFacetEditorTab(private val configuration: MinecraftFacetConfiguration) : FacetEditorTab() {
private lateinit var panel: JPanel
private lateinit var bukkitEnabledCheckBox: JCheckBox
private lateinit var bukkitAutoCheckBox: JCheckBox
private lateinit var spigotEnabledCheckBox: JCheckBox
private lateinit var spigotAutoCheckBox: JCheckBox
private lateinit var paperEnabledCheckBox: JCheckBox
private lateinit var paperAutoCheckBox: JCheckBox
private lateinit var spongeEnabledCheckBox: JCheckBox
private lateinit var spongeAutoCheckBox: JCheckBox
private lateinit var forgeEnabledCheckBox: JCheckBox
private lateinit var forgeAutoCheckBox: JCheckBox
private lateinit var fabricEnabledCheckBox: JCheckBox
private lateinit var fabricAutoCheckBox: JCheckBox
private lateinit var liteloaderEnabledCheckBox: JCheckBox
private lateinit var liteloaderAutoCheckBox: JCheckBox
private lateinit var mcpEnabledCheckBox: JCheckBox
private lateinit var mcpAutoCheckBox: JCheckBox
private lateinit var mixinEnabledCheckBox: JCheckBox
private lateinit var mixinAutoCheckBox: JCheckBox
private lateinit var bungeecordEnabledCheckBox: JCheckBox
private lateinit var bungeecordAutoCheckBox: JCheckBox
private lateinit var waterfallEnabledCheckBox: JCheckBox
private lateinit var waterfallAutoCheckBox: JCheckBox
private lateinit var velocityEnabledCheckBox: JCheckBox
private lateinit var velocityAutoCheckBox: JCheckBox
private lateinit var adventureEnabledCheckBox: JCheckBox
private lateinit var adventureAutoCheckBox: JCheckBox
private lateinit var spongeIcon: JLabel
private lateinit var mcpIcon: JLabel
private lateinit var mixinIcon: JLabel
private val enableCheckBoxArray: Array<JCheckBox> by lazy {
arrayOf(
bukkitEnabledCheckBox,
spigotEnabledCheckBox,
paperEnabledCheckBox,
spongeEnabledCheckBox,
forgeEnabledCheckBox,
fabricEnabledCheckBox,
liteloaderEnabledCheckBox,
mcpEnabledCheckBox,
mixinEnabledCheckBox,
bungeecordEnabledCheckBox,
waterfallEnabledCheckBox,
velocityEnabledCheckBox,
adventureEnabledCheckBox
)
}
private val autoCheckBoxArray: Array<JCheckBox> by lazy {
arrayOf(
bukkitAutoCheckBox,
spigotAutoCheckBox,
paperAutoCheckBox,
spongeAutoCheckBox,
forgeAutoCheckBox,
fabricAutoCheckBox,
liteloaderAutoCheckBox,
mcpAutoCheckBox,
mixinAutoCheckBox,
bungeecordAutoCheckBox,
waterfallAutoCheckBox,
velocityAutoCheckBox,
adventureAutoCheckBox
)
}
override fun createComponent(): JComponent {
if (UIUtil.isUnderDarcula()) {
spongeIcon.icon = PlatformAssets.SPONGE_ICON_2X_DARK
mcpIcon.icon = PlatformAssets.MCP_ICON_2X_DARK
mixinIcon.icon = PlatformAssets.MIXIN_ICON_2X_DARK
}
runOnAll { enabled, auto, platformType, _, _ ->
auto.addActionListener { checkAuto(auto, enabled, platformType) }
}
bukkitEnabledCheckBox.addActionListener {
unique(
bukkitEnabledCheckBox,
spigotEnabledCheckBox,
paperEnabledCheckBox
)
}
spigotEnabledCheckBox.addActionListener {
unique(
spigotEnabledCheckBox,
bukkitEnabledCheckBox,
paperEnabledCheckBox
)
}
paperEnabledCheckBox.addActionListener {
unique(
paperEnabledCheckBox,
bukkitEnabledCheckBox,
spigotEnabledCheckBox
)
}
bukkitAutoCheckBox.addActionListener {
all(bukkitAutoCheckBox, spigotAutoCheckBox, paperAutoCheckBox)(
SPIGOT,
PAPER
)
}
spigotAutoCheckBox.addActionListener {
all(spigotAutoCheckBox, bukkitAutoCheckBox, paperAutoCheckBox)(
BUKKIT,
PAPER
)
}
paperAutoCheckBox.addActionListener {
all(paperAutoCheckBox, bukkitAutoCheckBox, spigotAutoCheckBox)(
BUKKIT,
SPIGOT
)
}
forgeEnabledCheckBox.addActionListener { also(forgeEnabledCheckBox, mcpEnabledCheckBox) }
fabricEnabledCheckBox.addActionListener {
also(fabricEnabledCheckBox, mixinEnabledCheckBox, mcpEnabledCheckBox)
}
liteloaderEnabledCheckBox.addActionListener { also(liteloaderEnabledCheckBox, mcpEnabledCheckBox) }
mixinEnabledCheckBox.addActionListener { also(mixinEnabledCheckBox, mcpEnabledCheckBox) }
bungeecordEnabledCheckBox.addActionListener { unique(bungeecordEnabledCheckBox, waterfallEnabledCheckBox) }
waterfallEnabledCheckBox.addActionListener { unique(waterfallEnabledCheckBox, bungeecordEnabledCheckBox) }
return panel
}
override fun getDisplayName() = "Minecraft Module Settings"
override fun isModified(): Boolean {
var modified = false
runOnAll { enabled, auto, platformType, userTypes, _ ->
modified += auto.isSelected == platformType in userTypes
modified += !auto.isSelected && enabled.isSelected != userTypes[platformType]
}
return modified
}
override fun reset() {
runOnAll { enabled, auto, platformType, userTypes, autoTypes ->
auto.isSelected = platformType !in userTypes
enabled.isSelected = userTypes[platformType] ?: (platformType in autoTypes)
if (auto.isSelected) {
enabled.isEnabled = false
}
}
}
override fun apply() {
configuration.state.userChosenTypes.clear()
runOnAll { enabled, auto, platformType, userTypes, _ ->
if (!auto.isSelected) {
userTypes[platformType] = enabled.isSelected
}
}
}
private inline fun runOnAll(
run: (JCheckBox, JCheckBox, PlatformType, MutableMap<PlatformType, Boolean>, Set<PlatformType>) -> Unit
) {
val state = configuration.state
for (i in indexes) {
run(
enableCheckBoxArray[i],
autoCheckBoxArray[i],
platformTypes[i],
state.userChosenTypes,
state.autoDetectTypes
)
}
}
private fun unique(vararg checkBoxes: JCheckBox) {
if (checkBoxes.size <= 1) {
return
}
if (checkBoxes[0].isSelected) {
for (i in 1 until checkBoxes.size) {
checkBoxes[i].isSelected = false
}
}
}
private fun also(vararg checkBoxes: JCheckBox) {
if (checkBoxes.size <= 1) {
return
}
if (checkBoxes[0].isSelected) {
for (i in 1 until checkBoxes.size) {
checkBoxes[i].isSelected = true
}
}
}
private fun all(vararg checkBoxes: JCheckBox): Invoker {
if (checkBoxes.size <= 1) {
return Invoker()
}
for (i in 1 until checkBoxes.size) {
checkBoxes[i].isSelected = checkBoxes[0].isSelected
}
return object : Invoker() {
override fun invoke(vararg indexes: Int) {
for (i in indexes) {
checkAuto(autoCheckBoxArray[i], enableCheckBoxArray[i], platformTypes[i])
}
}
}
}
private fun checkAuto(auto: JCheckBox, enabled: JCheckBox, type: PlatformType) {
if (auto.isSelected) {
enabled.isEnabled = false
enabled.isSelected = type in configuration.state.autoDetectTypes
} else {
enabled.isEnabled = true
}
}
private operator fun Boolean.plus(n: Boolean) = this || n
// This is here so we can use vararg. Can't use parameter modifiers in function type definitions for some reason
open class Invoker {
open operator fun invoke(vararg indexes: Int) {}
}
companion object {
private const val BUKKIT = 0
private const val SPIGOT = BUKKIT + 1
private const val PAPER = SPIGOT + 1
private const val SPONGE = PAPER + 1
private const val FORGE = SPONGE + 1
private const val FABRIC = FORGE + 1
private const val LITELOADER = FABRIC + 1
private const val MCP = LITELOADER + 1
private const val MIXIN = MCP + 1
private const val BUNGEECORD = MIXIN + 1
private const val WATERFALL = BUNGEECORD + 1
private const val VELOCITY = WATERFALL + 1
private const val ADVENTURE = VELOCITY + 1
private val platformTypes = arrayOf(
PlatformType.BUKKIT,
PlatformType.SPIGOT,
PlatformType.PAPER,
PlatformType.SPONGE,
PlatformType.FORGE,
PlatformType.FABRIC,
PlatformType.LITELOADER,
PlatformType.MCP,
PlatformType.MIXIN,
PlatformType.BUNGEECORD,
PlatformType.WATERFALL,
PlatformType.VELOCITY,
PlatformType.ADVENTURE
)
private val indexes = intArrayOf(
BUKKIT,
SPIGOT,
PAPER,
SPONGE,
FORGE,
FABRIC,
LITELOADER,
MCP,
MIXIN,
BUNGEECORD,
WATERFALL,
VELOCITY,
ADVENTURE
)
}
}
| mit | 3179c95661f5786a202ecd08247be684 | 31.971061 | 116 | 0.624537 | 5.245013 | false | false | false | false |
kiruto/kotlin-android-mahjong | app/src/main/java/dev/yuriel/mahjan/model/TileWrapper.kt | 1 | 2549 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 yuriel<[email protected]>
*
* 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 dev.yuriel.mahjan.model
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.TextureRegion
import dev.yuriel.kotmahjan.models.Hai
import dev.yuriel.mahjan.enums.TileStatus
import dev.yuriel.mahjan.texture.TileMgr
/**
* Created by yuriel on 8/5/16.
*/
class TileWrapper() {
constructor(hai: Hai): this() {
this.hai = hai
}
var texture: TextureRegion? = null
private set
var back: TextureRegion? = null
private set
var obverse: TextureRegion? = null
private set
var display: Int = 0
set(value) {
field = field and value
}
var hai: Hai? = null
set(value) {
field = value
texture = initTexture(hai = value)
}
var status: TileStatus = TileStatus.NORMAL
set(value) {
field = value
texture = initTexture(status = value)
}
var selected: Boolean = false
fun destroy() {
hai = null
}
private fun initTexture(hai: Hai? = this.hai, status: TileStatus = this.status): TextureRegion? {
if (null == hai) {
back = null
obverse = null
return null
} else {
TileMgr.load()
back = TileMgr.getBack()
obverse = TileMgr.getObverse()
return TileMgr[hai]
}
}
} | mit | 17bc14d585ed5ce503b60df9a0207c42 | 29.722892 | 101 | 0.654767 | 4.241265 | false | false | false | false |
samtstern/quickstart-android | mlkit-smartreply/app/src/main/java/com/google/firebase/samples/apps/mlkit/smartreply/kotlin/chat/ReplyChipAdapter.kt | 1 | 1713 | package com.google.firebase.samples.apps.mlkit.smartreply.kotlin.chat
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.google.firebase.ml.naturallanguage.smartreply.SmartReplySuggestion
import com.google.firebase.samples.apps.mlkit.smartreply.R
import java.util.ArrayList
class ReplyChipAdapter(private val listener: ClickListener) : RecyclerView.Adapter<ReplyChipAdapter.ViewHolder>() {
private val suggestions = ArrayList<SmartReplySuggestion>()
interface ClickListener {
fun onChipClick(chipText: String)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.smart_reply_chip, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val suggestion = suggestions[position]
holder.bind(suggestion)
}
override fun getItemCount(): Int {
return suggestions.size
}
fun setSuggestions(suggestions: List<SmartReplySuggestion>) {
this.suggestions.clear()
this.suggestions.addAll(suggestions)
notifyDataSetChanged()
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val text: TextView
init {
this.text = itemView.findViewById(R.id.smartReplyText)
}
fun bind(suggestion: SmartReplySuggestion) {
text.text = suggestion.text
itemView.setOnClickListener { listener.onChipClick(suggestion.text) }
}
}
}
| apache-2.0 | 74813bd808e43dda1ac22c83972ca854 | 29.589286 | 115 | 0.71979 | 4.568 | false | false | false | false |
stoman/competitive-programming | problems/2021adventofcode11a/submissions/accepted/Stefan.kt | 2 | 887 | import java.util.*
@ExperimentalStdlibApi
fun main() {
var flashes = 0
val s = Scanner(System.`in`)
val energy = mutableMapOf<Pair<Int, Int>, Int>()
var i = 0
while (s.hasNext()) {
s.next().map { it.toString().toInt() }.forEachIndexed { j, level -> energy[Pair(i, j)] = level }
i++
}
repeat(100) {
val increases = ArrayDeque<Pair<Int, Int>>()
increases.addAll(energy.keys)
while (increases.isNotEmpty()) {
val p = increases.removeFirst()
if(p !in energy.keys) {
continue
}
energy[p] = energy[p]!! + 1
if (energy[p] == 10) {
flashes++
for (x in -1..1) {
for (y in -1..1) {
increases.addLast(Pair(p.first + x, p.second + y))
}
}
}
}
for ((p, level) in energy) {
if (level > 9) {
energy[p] = 0
}
}
}
println(flashes)
}
| mit | 2966a6e6fce3dc52d43eafd2a66f38a9 | 22.342105 | 100 | 0.51071 | 3.297398 | false | false | false | false |
oboehm/jfachwert | src/main/kotlin/de/jfachwert/bank/GeldbetragFactory.kt | 1 | 6046 | /*
* Copyright (c) 2018-2020 by Oliver Boehm
*
* 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.
*
* (c)reated 30.07.2018 by oboehm ([email protected])
*/
package de.jfachwert.bank
import de.jfachwert.bank.Geldbetrag
import de.jfachwert.bank.Geldbetrag.Companion.valueOf
import de.jfachwert.pruefung.exception.LocalizedMonetaryException
import java.math.BigDecimal
import java.math.RoundingMode
import javax.money.*
/**
* Analog zu den anderen [Monetary]-Datentype kann mit dieser Factory
* ein [Geldbetrag] erzeugt und vorblegt werden.
*
* @author oboehm
* @since 1.0 (30.07.2018)
*/
class GeldbetragFactory : MonetaryAmountFactory<Geldbetrag> {
private var number: Number = BigDecimal.ZERO
private var currency: CurrencyUnit? = null
private var context = MonetaryContextBuilder.of(Geldbetrag::class.java).setAmountType(Geldbetrag::class.java).setPrecision(41).setMaxScale(4)
.set(RoundingMode.HALF_UP).build()
/**
* Liefert den [MonetaryAmount] Implementierungstyp.
*
* @return die Klasse [Geldbetrag]
*/
override fun getAmountType(): Class<out MonetaryAmount?> {
return Geldbetrag::class.java
}
/**
* Setzt die [CurrencyUnit].
*
* @param currency [CurrencyUnit], nicht `null`
* @return die Factory selber
*/
override fun setCurrency(currency: CurrencyUnit): GeldbetragFactory {
this.currency = currency
return this
}
/**
* Setzt die Nummer fuer den Geldbetrag.
*
* @param number Betrag, darf nicht `null` sein.
* @return die Factory selber
*/
override fun setNumber(number: Double): GeldbetragFactory {
return this.setNumber(BigDecimal.valueOf(number))
}
/**
* Setzt die Nummer fuer den Geldbetrag.
*
* @param number Betrag, darf nicht `null` sein.
* @return die Factory selber
*/
override fun setNumber(number: Long): GeldbetragFactory {
return setNumber(BigDecimal.valueOf(number))
}
/**
* Setzt die Nummer fuer den Geldbetrag.
*
* @param number Betrag, darf nicht `null` sein.
* @return die Factory selber
*/
override fun setNumber(number: Number): GeldbetragFactory {
this.number = number
context = getMonetaryContextOf(number)
return this
}
/**
* Ermittelt den [MonetaryContext] der uebergebenen Nummer. Laesst er
* sich nicht ermitteln, wird der voreigestellte [MonetaryContext]
* zurueckgeliefert.
*
* @param number eine Zahl, z.B. 8.15
* @return den Kontext, der mit dieser Zahl verbunden ist (wie z.B.
* 2 Nachkommastellen, ...)
*/
fun getMonetaryContextOf(number: Number?): MonetaryContext {
if (number is BigDecimal) {
val value = number
if (value.scale() > context.maxScale) {
return MonetaryContextBuilder.of(Geldbetrag::class.java)
.setAmountType(Geldbetrag::class.java)
.setPrecision(context.precision)
.setMaxScale(value.scale())
.set(RoundingMode.HALF_UP).build()
}
}
return context
}
/**
* Liefert die Maximal-Nummer, die der [Geldbetrag] darstellen kann.
*
* @return Maximal-Betrag
*/
override fun getMaxNumber(): NumberValue {
return Geldbetrag.MAX_VALUE.number
}
/**
* Liefert die Minimal-Nummer, die der [Geldbetrag] darstellen kann.
*
* @return Minimal-Betrag
*/
override fun getMinNumber(): NumberValue {
return Geldbetrag.MIN_VALUE.number
}
/**
* Sets the [MonetaryContext] to be used.
*
* @param monetaryContext the [MonetaryContext] to be used, not `null`.
* @return This factory instance, for chaining.
* @throws MonetaryException when the [MonetaryContext] given exceeds the capabilities supported by this
* factory type.
* @see MonetaryAmountFactory.getMaximalMonetaryContext
*/
override fun setContext(monetaryContext: MonetaryContext): GeldbetragFactory {
context = monetaryContext
return this
}
/**
* Erzeugt einen neuen [Geldbetrag] anhand der eingestellten Daten.
*
* @return den entsprechenden [Geldbetrag].
* @see MonetaryAmountFactory.getAmountType
*/
override fun create(): Geldbetrag {
if (currency == null) {
throw LocalizedMonetaryException("currency missing", number)
}
return valueOf(number, currency!!, context)
}
/**
* In der Standardeinstellung liefert der [MonetaryContext] einen
* Wertbereich fuer den Geldbetrag von [Geldbetrag.MIN_VALUE] bis
* [Geldbetrag.MAX_VALUE].
*
* @return den Default-[MonetaryContext].
* @see MonetaryAmountFactory.getMaximalMonetaryContext
*/
override fun getDefaultMonetaryContext(): MonetaryContext {
return context
}
/**
* Der maximale [MonetaryContext] schraenkt den Wertebereich eines
* Geldbetrags nicth ein. D.h. es gibt keine obere und untere Grenze.
*
* @return maximaler [MonetaryContext].
*/
override fun getMaximalMonetaryContext(): MonetaryContext {
return MAX_CONTEXT
}
companion object {
@JvmField
val MAX_CONTEXT = MonetaryContextBuilder.of(Geldbetrag::class.java).setAmountType(Geldbetrag::class.java).setPrecision(0).setMaxScale(-1)
.set(RoundingMode.HALF_UP).build()
}
} | apache-2.0 | e0153fd0e174e658954e468d489608a3 | 30.994709 | 145 | 0.654648 | 3.804909 | false | false | false | false |
cashapp/sqldelight | extensions/rxjava3-extensions/src/main/kotlin/app/cash/sqldelight/rx3/RxJavaExtensions.kt | 1 | 2556 | @file:JvmName("RxQuery")
package app.cash.sqldelight.rx3
import app.cash.sqldelight.Query
import io.reactivex.rxjava3.annotations.CheckReturnValue
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.ObservableEmitter
import io.reactivex.rxjava3.core.ObservableOnSubscribe
import io.reactivex.rxjava3.core.Scheduler
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import java.util.Optional
import java.util.concurrent.atomic.AtomicBoolean
/**
* Turns this [Query] into an [Observable] which emits whenever the underlying result set changes.
*
* @param scheduler By default, emissions occur on the [Schedulers.io] scheduler but can be
* optionally overridden.
*/
@CheckReturnValue
@JvmOverloads
@JvmName("toObservable")
fun <T : Any> Query<T>.asObservable(scheduler: Scheduler = Schedulers.io()): Observable<Query<T>> {
return Observable.create(QueryOnSubscribe(this)).observeOn(scheduler)
}
private class QueryOnSubscribe<T : Any>(
private val query: Query<T>,
) : ObservableOnSubscribe<Query<T>> {
override fun subscribe(emitter: ObservableEmitter<Query<T>>) {
val listenerAndDisposable = QueryListenerAndDisposable(emitter, query)
query.addListener(listenerAndDisposable)
emitter.setDisposable(listenerAndDisposable)
emitter.onNext(query)
}
}
private class QueryListenerAndDisposable<T : Any>(
private val emitter: ObservableEmitter<Query<T>>,
private val query: Query<T>,
) : AtomicBoolean(), Query.Listener, Disposable {
override fun queryResultsChanged() {
emitter.onNext(query)
}
override fun isDisposed() = get()
override fun dispose() {
if (compareAndSet(false, true)) {
query.removeListener(this)
}
}
}
@CheckReturnValue
fun <T : Any> Observable<Query<T>>.mapToOne(): Observable<T> {
return map { it.executeAsOne() }
}
@CheckReturnValue
fun <T : Any> Observable<Query<T>>.mapToOneOrDefault(defaultValue: T): Observable<T> {
return map { it.executeAsOneOrNull() ?: defaultValue }
}
@CheckReturnValue
fun <T : Any> Observable<Query<T>>.mapToOptional(): Observable<Optional<T>> {
return map { Optional.ofNullable(it.executeAsOneOrNull()) }
}
@CheckReturnValue
fun <T : Any> Observable<Query<T>>.mapToList(): Observable<List<T>> {
return map { it.executeAsList() }
}
@CheckReturnValue
fun <T : Any> Observable<Query<T>>.mapToOneNonNull(): Observable<T> {
return flatMap {
val result = it.executeAsOneOrNull()
if (result == null) Observable.empty() else Observable.just(result)
}
}
| apache-2.0 | b4b1f4b9c5ebfff79fb567ab70ed67ff | 29.795181 | 99 | 0.751956 | 4.012559 | false | false | false | false |
panpf/sketch | sketch/src/main/java/com/github/panpf/sketch/datasource/DiskCacheDataSource.kt | 1 | 1778 | /*
* Copyright (C) 2022 panpf <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.datasource
import androidx.annotation.WorkerThread
import com.github.panpf.sketch.Sketch
import com.github.panpf.sketch.cache.DiskCache
import com.github.panpf.sketch.request.ImageRequest
import java.io.File
import java.io.IOException
import java.io.InputStream
/**
* Provides access to image data in disk cache
*/
class DiskCacheDataSource constructor(
override val sketch: Sketch,
override val request: ImageRequest,
override val dataFrom: DataFrom,
val snapshot: DiskCache.Snapshot,
) : DataSource {
private var _length = -1L
@WorkerThread
@Throws(IOException::class)
override fun length(): Long =
_length.takeIf { it != -1L }
?: snapshot.file.length().apply {
this@DiskCacheDataSource._length = this
}
@WorkerThread
@Throws(IOException::class)
override fun newInputStream(): InputStream = snapshot.newInputStream()
@WorkerThread
@Throws(IOException::class)
override fun file(): File = snapshot.file
override fun toString(): String =
"DiskCacheDataSource(from=$dataFrom,file='${snapshot.file.path}')"
} | apache-2.0 | 02e1ae38db81ef9724a4fa187e668add | 30.767857 | 75 | 0.716535 | 4.305085 | false | false | false | false |
vondear/RxTools | RxUI/src/main/java/com/tamsiree/rxui/view/dialog/wheel/WheelScroller.kt | 1 | 6486 | package com.tamsiree.rxui.view.dialog.wheel
import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Message
import android.view.GestureDetector
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.MotionEvent
import android.view.animation.Interpolator
import android.widget.Scroller
/**
* @author tamsiree
* Scroller class handles scrolling events and updates the
*/
class WheelScroller(context: Context, listener: ScrollingListener) {
/**
* Scrolling listener interface
*/
interface ScrollingListener {
/**
* Scrolling callback called when scrolling is performed.
* @param distance the distance to scroll
*/
fun onScroll(distance: Int)
/**
* Starting callback called when scrolling is started
*/
fun onStarted()
/**
* Finishing callback called after justifying
*/
fun onFinished()
/**
* Justifying callback called to justify a view when scrolling is ended
*/
fun onJustify()
}
// Listener
private val listener: ScrollingListener
// Context
private val context: Context
// Scrolling
private val gestureDetector: GestureDetector
private var scroller: Scroller? = null
private var lastScrollY = 0
private var lastTouchedY = 0f
private var isScrollingPerformed = false
/**
* Set the the specified scrolling interpolator
* @param interpolator the interpolator
*/
fun setInterpolator(interpolator: Interpolator?) {
scroller?.forceFinished(true)
scroller = Scroller(context, interpolator)
}
/**
* Scroll the wheel
* @param distance the scrolling distance
* @param time the scrolling duration
*/
fun scroll(distance: Int, time: Int) {
scroller?.forceFinished(true)
lastScrollY = 0
scroller?.startScroll(0, 0, 0, distance, if (time != 0) time else SCROLLING_DURATION)
setNextMessage(MESSAGE_SCROLL)
startScrolling()
}
/**
* Stops scrolling
*/
fun stopScrolling() {
scroller?.forceFinished(true)
}
/**
* Handles Touch event
* @param event the motion event
* @return
*/
fun onTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
lastTouchedY = event.y
scroller?.forceFinished(true)
clearMessages()
}
MotionEvent.ACTION_MOVE -> {
// perform scrolling
val distanceY = (event.y - lastTouchedY).toInt()
if (distanceY != 0) {
startScrolling()
listener.onScroll(distanceY)
lastTouchedY = event.y
}
}
}
if (!gestureDetector.onTouchEvent(event) && event.action == MotionEvent.ACTION_UP) {
justify()
}
return true
}
// gesture listener
private val gestureListener: SimpleOnGestureListener = object : SimpleOnGestureListener() {
override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean {
// Do scrolling in onTouchEvent() since onScroll() are not call immediately
// when user touch and move the wheel
return true
}
override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
lastScrollY = 0
val maxY = 0x7FFFFFFF
val minY = -maxY
scroller?.fling(0, lastScrollY, 0, (-velocityY).toInt(), 0, 0, minY, maxY)
setNextMessage(MESSAGE_SCROLL)
return true
}
}
// Messages
private val MESSAGE_SCROLL = 0
private val MESSAGE_JUSTIFY = 1
/**
* Set next message to queue. Clears queue before.
*
* @param message the message to set
*/
private fun setNextMessage(message: Int) {
clearMessages()
animationHandler.sendEmptyMessage(message)
}
/**
* Clears messages from queue
*/
private fun clearMessages() {
animationHandler.removeMessages(MESSAGE_SCROLL)
animationHandler.removeMessages(MESSAGE_JUSTIFY)
}
// animation handler
private val animationHandler: Handler = @SuppressLint("HandlerLeak")
object : Handler() {
override fun handleMessage(msg: Message) {
scroller?.computeScrollOffset()
var currY = scroller?.currY
val delta = lastScrollY - currY!!
lastScrollY = currY
if (delta != 0) {
listener.onScroll(delta)
}
// scrolling is not finished when it comes to final Y
// so, finish it manually
if (Math.abs(currY - scroller?.finalY!!) < MIN_DELTA_FOR_SCROLLING) {
currY = scroller?.finalY
scroller?.forceFinished(true)
}
if (!(scroller?.isFinished!!)) {
sendEmptyMessage(msg.what)
} else if (msg.what == MESSAGE_SCROLL) {
justify()
} else {
finishScrolling()
}
}
}
/**
* Justifies wheel
*/
private fun justify() {
listener.onJustify()
setNextMessage(MESSAGE_JUSTIFY)
}
/**
* Starts scrolling
*/
private fun startScrolling() {
if (!isScrollingPerformed) {
isScrollingPerformed = true
listener.onStarted()
}
}
/**
* Finishes scrolling
*/
fun finishScrolling() {
if (isScrollingPerformed) {
listener.onFinished()
isScrollingPerformed = false
}
}
companion object {
/** Scrolling duration */
private const val SCROLLING_DURATION = 400
/** Minimum delta for scrolling */
const val MIN_DELTA_FOR_SCROLLING = 1
}
/**
* Constructor
* @param context the current context
* @param listener the scrolling listener
*/
init {
gestureDetector = GestureDetector(context, gestureListener)
gestureDetector.setIsLongpressEnabled(false)
scroller = Scroller(context)
this.listener = listener
this.context = context
}
} | apache-2.0 | 5466b686cac911a4b8bbee2913a9638d | 27.204348 | 110 | 0.58634 | 5.067188 | false | false | false | false |
DarrenAtherton49/android-kotlin-base | app/src/main/kotlin/com/atherton/sample/presentation/util/viewpager/FragmentViewPagerAdapter.kt | 1 | 1349 | package com.atherton.sample.presentation.util.viewpager
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
internal class FragmentViewPagerAdapter(fragmentManager: FragmentManager) : FragmentPagerAdapter(fragmentManager) {
private val fragmentIdList = mutableListOf<Long>()
private val fragmentTitleList = mutableListOf<String>()
private val fragmentList = mutableListOf<Fragment>()
override fun getItem(position: Int): Fragment = fragmentList[position]
override fun getCount(): Int = fragmentList.count()
override fun getPageTitle(position: Int): CharSequence = fragmentTitleList[position]
override fun getItemId(position: Int): Long = fragmentIdList[position]
override fun getItemPosition(item: Any): Int = fragmentList.indexOf(item)
fun addFragment(id: Long, title: String, fragment: Fragment) {
fragmentIdList.add(id)
fragmentTitleList.add(title)
fragmentList.add(fragment)
}
fun addFragmentToStart(id: Long, title: String, fragment: Fragment) {
fragmentIdList.add(0, id)
fragmentTitleList.add(0, title)
fragmentList.add(0, fragment)
}
fun clear() {
fragmentIdList.clear()
fragmentTitleList.clear()
fragmentList.clear()
}
}
| mit | f001a24636d3ec3ddb6485bfe7e01569 | 32.725 | 115 | 0.730912 | 4.75 | false | false | false | false |
paulofernando/localchat | app/src/main/kotlin/site/paulo/localchat/ui/signin/SignInActivity.kt | 1 | 4075 | /*
* Copyright 2017 Paulo Fernando
*
* 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 site.paulo.localchat.ui.signin
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import kotlinx.android.synthetic.main.activity_sign_in.*
import kotlinx.android.synthetic.main.splash_screen.*
import org.jetbrains.anko.*
import site.paulo.localchat.R
import site.paulo.localchat.ui.base.BaseActivity
import site.paulo.localchat.ui.dashboard.DashboardActivity
import site.paulo.localchat.ui.signup.SignUpActivity
import javax.inject.Inject
class SignInActivity : BaseActivity(), SignInContract.View {
@Inject
lateinit var presenter: SignInPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupActivity()
loginSignInBtn.setOnClickListener {
if(validate()) presenter.signIn(emailSignInTxt.text.toString(), passwordSignInTxt.text.toString())
}
passwordSignInTxt.setOnKeyListener(View.OnKeyListener { _, keyCode, event ->
// If the event is a key-down event on the "enter" button
if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
// Perform action on key press
if(validate())
presenter.signIn(emailSignInTxt.text.toString(), passwordSignInTxt.text.toString())
return@OnKeyListener true
}
false
})
signupSignInLink.setOnClickListener {
startActivity<SignUpActivity>()
}
presenter.isAuthenticated { hideSplashScreen() } //if authenticated, sign in
askForLocationPermission()
}
private fun askForLocationPermission() {
when (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
PackageManager.PERMISSION_DENIED -> ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 1)
}
}
private fun hideSplashScreen() {
splashScreen.visibility = View.GONE
}
private fun setupActivity() {
activityComponent.inject(this)
presenter.attachView(this)
val decorView = window.decorView
decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
setContentView(R.layout.activity_sign_in)
}
private fun validate(): Boolean {
if(emailSignInTxt.text.toString().equals("")) {
emailSignInTxt.error = "enter an email address"
return false
} else if(passwordSignInTxt.text.toString().equals("")) {
passwordSignInTxt.error = "enter a password"
return false
} else {
if(spinnerDialog == null) {
spinnerDialog = indeterminateProgressDialog(R.string.authenticating)
} else {
spinnerDialog?.show()
}
return true
}
}
override fun showSuccessFullSignIn() {
spinnerDialog?.cancel()
startActivity(intentFor<DashboardActivity>().newTask().clearTask())
}
override fun showFailSignIn() {
spinnerDialog?.cancel()
alert(R.string.auth_failed) {
title = R.string.auth_failed_title.toString()
}.show()
}
override fun onDestroy() {
super.onDestroy()
presenter.detachView()
}
} | apache-2.0 | a61a41be1034e271232073fa1d4a60df | 31.870968 | 141 | 0.672393 | 4.754959 | false | false | false | false |
wakim/kotlin-mvp-starter | app/src/main/kotlin/br/com/wakim/mvp_starter/ui/SchedulerProviderContract.kt | 1 | 668 | package br.com.wakim.mvp_starter.ui
import io.reactivex.Scheduler
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.internal.schedulers.ImmediateThinScheduler
import io.reactivex.schedulers.Schedulers
interface SchedulerContract {
val io: Scheduler
val ui: Scheduler
}
object DefaultScheduler : SchedulerContract {
override val io: Scheduler = Schedulers.io()
override val ui: Scheduler = AndroidSchedulers.mainThread()
}
object ImmediateScheduler : SchedulerContract {
val scheduler: Scheduler = ImmediateThinScheduler.INSTANCE
override val io: Scheduler = scheduler
override val ui: Scheduler = scheduler
} | apache-2.0 | df0355abeaa003d0c05240eaa6d5ea16 | 28.086957 | 63 | 0.793413 | 4.704225 | false | false | false | false |
androidx/androidx | wear/watchface/watchface-complications/src/androidTest/java/androidx/wear/watchface/complications/ComplicationSlotBoundsTest.kt | 3 | 3840 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.watchface.complications
import android.content.Context
import android.graphics.RectF
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.test.core.app.ApplicationProvider
import androidx.test.filters.MediumTest
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.wear.watchface.complications.data.ComplicationType
import androidx.wear.watchface.complications.test.R
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.xmlpull.v1.XmlPullParser
@RequiresApi(Build.VERSION_CODES.P)
@RunWith(AndroidJUnit4::class)
@MediumTest
class ComplicationSlotBoundsTest {
private val context = ApplicationProvider.getApplicationContext<Context>()
@Test
public fun test_inflate_list_schema() {
val parser = context.resources.getXml(R.xml.complication_slot_bounds)
// Parse next until start tag is found
var nodeType: Int
do {
nodeType = parser.next()
} while (nodeType != XmlPullParser.END_DOCUMENT && nodeType != XmlPullParser.START_TAG)
val bounds = ComplicationSlotBounds.inflate(context.resources, parser, 1.0f, 1.0f)!!
// SHORT_TEXT, LONG_TEXT and RANGED_VALUE should match the input
assertThat(
bounds.perComplicationTypeBounds[ComplicationType.SHORT_TEXT]
).isEqualTo(RectF(0.2f, 0.4f, 0.3f, 0.1f))
assertThat(
bounds.perComplicationTypeMargins[ComplicationType.SHORT_TEXT]
).isEqualTo(RectF(0.1f, 0.2f, 0.3f, 0.4f))
val widthPixels = context.resources.displayMetrics.widthPixels
assertThat(
bounds.perComplicationTypeBounds[ComplicationType.LONG_TEXT]
).isEqualTo(RectF(
96f * context.resources.displayMetrics.density / widthPixels,
96f * context.resources.displayMetrics.density / widthPixels,
192f * context.resources.displayMetrics.density / widthPixels,
192f * context.resources.displayMetrics.density / widthPixels
))
assertThat(bounds.perComplicationTypeMargins[ComplicationType.LONG_TEXT]).isEqualTo(RectF())
assertThat(
bounds.perComplicationTypeBounds[ComplicationType.RANGED_VALUE]
).isEqualTo(RectF(0.3f, 0.3f, 0.5f, 0.7f))
val center = context.resources.getDimension(R.dimen.complication_center) / widthPixels
val halfSize =
context.resources.getDimension(R.dimen.complication_size) / widthPixels / 2.0f
assertThat(
bounds.perComplicationTypeBounds[ComplicationType.SMALL_IMAGE]
).isEqualTo(RectF(
center - halfSize, center - halfSize, center + halfSize, center + halfSize
))
// All other types should have been backfilled with an empty rect.
for (type in ComplicationType.values()) {
if (type != ComplicationType.SHORT_TEXT &&
type != ComplicationType.LONG_TEXT &&
type != ComplicationType.RANGED_VALUE &&
type != ComplicationType.SMALL_IMAGE) {
assertThat(bounds.perComplicationTypeBounds[type]).isEqualTo(RectF())
}
}
}
}
| apache-2.0 | 24673387d88a9a0a9c392f3d55d94751 | 39.851064 | 100 | 0.701042 | 4.539007 | false | true | false | false |
androidx/androidx | camera/camera-extensions/src/test/java/androidx/camera/extensions/internal/ExtensionVersionMaximumCompatibleTest.kt | 3 | 2862 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.extensions.internal
import android.os.Build
import androidx.camera.extensions.internal.util.ExtensionsTestUtil.resetSingleton
import androidx.camera.extensions.internal.util.ExtensionsTestUtil.setTestApiVersion
import com.google.common.truth.Truth.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.ParameterizedRobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.internal.DoNotInstrument
@RunWith(ParameterizedRobolectricTestRunner::class)
@DoNotInstrument
@Config(
minSdk = Build.VERSION_CODES.LOLLIPOP,
instrumentedPackages = arrayOf("androidx.camera.extensions.internal")
)
class ExtensionVersionMaximumCompatibleTest(private val config: TestConfig) {
@Before
@Throws(NoSuchFieldException::class, IllegalAccessException::class)
fun setUp() {
val field = VersionName::class.java.getDeclaredField("CURRENT")
field.isAccessible = true
field[null] = VersionName(config.targetVersion)
}
@After
fun tearDown() {
resetSingleton(ExtensionVersion::class.java, "sExtensionVersion")
}
@Test
fun isMaximumCompatibleVersion() {
setTestApiVersion(config.targetVersion)
val version = Version.parse(config.maximumCompatibleVersion)!!
assertThat(ExtensionVersion.isMaximumCompatibleVersion(version))
.isEqualTo(config.expectedResult)
}
data class TestConfig(
val targetVersion: String,
val maximumCompatibleVersion: String,
val expectedResult: Boolean
)
companion object {
@JvmStatic
@ParameterizedRobolectricTestRunner.Parameters(name = "{0}")
fun createTestSet(): List<TestConfig> {
return listOf(
TestConfig("1.1.0", "1.1.0", true),
TestConfig("1.1.0", "1.2.0", true),
TestConfig("1.1.0", "1.0.0", false),
TestConfig("1.1.0", "0.9.0", false),
// Test to ensure the patch version is ignored
TestConfig("1.2.1", "1.2.0", true),
TestConfig("1.2.0", "1.2.1", true),
)
}
}
} | apache-2.0 | 0dbe2ede94b08eb490aef740ae6fa9d5 | 33.493976 | 84 | 0.696716 | 4.478873 | false | true | false | false |
androidx/androidx | room/integration-tests/kotlintestapp/src/androidTest/java/androidx/room/integration/kotlintestapp/test/ListenableFuturePagingSourceTest.kt | 3 | 11264 | /*
* 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.
*/
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.integration.kotlintestapp.test
import androidx.paging.ListenableFuturePagingSource
import androidx.paging.Pager
import androidx.paging.PagingState
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.androidx.room.integration.kotlintestapp.testutil.ItemStore
import androidx.room.androidx.room.integration.kotlintestapp.testutil.PagingDb
import androidx.room.androidx.room.integration.kotlintestapp.testutil.PagingEntity
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import androidx.testutils.FilteringExecutor
import com.google.common.truth.Truth.assertThat
import com.google.common.util.concurrent.ListenableFuture
import java.util.concurrent.Executors
import kotlin.test.assertFailsWith
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@SmallTest
class ListenableFuturePagingSourceTest {
private lateinit var coroutineScope: CoroutineScope
private lateinit var db: PagingDb
private lateinit var itemStore: ItemStore
// Multiple threads are necessary to prevent deadlock, since Room will acquire a thread to
// dispatch on, when using the query / transaction dispatchers.
private val queryExecutor = FilteringExecutor(Executors.newFixedThreadPool(2))
private val mainThreadQueries = mutableListOf<Pair<String, String>>()
private val pagingSources = mutableListOf<ListenableFuturePagingSourceImpl>()
@Before
fun init() {
coroutineScope = CoroutineScope(Dispatchers.Main)
itemStore = ItemStore(coroutineScope)
val mainThread: Thread = runBlocking(Dispatchers.Main) {
Thread.currentThread()
}
db = Room.inMemoryDatabaseBuilder(
ApplicationProvider.getApplicationContext(),
PagingDb::class.java
).setQueryCallback(
object : RoomDatabase.QueryCallback {
override fun onQuery(sqlQuery: String, bindArgs: List<Any?>) {
if (Thread.currentThread() === mainThread) {
mainThreadQueries.add(
sqlQuery to Throwable().stackTraceToString()
)
}
}
}
) {
// instantly execute the log callback so that we can check the thread.
it.run()
}.setQueryExecutor(queryExecutor)
.build()
}
@After
fun tearDown() {
// Check no mainThread queries happened.
assertThat(mainThreadQueries).isEmpty()
coroutineScope.cancel()
}
@Test
fun refresh_canceledCoroutine_cancelsFuture() {
val items = createItems(startId = 0, count = 90)
db.dao.insert(items)
// filter right away to block initial load
queryExecutor.filterFunction = { runnable ->
// filtering out the transform async function called inside loadFuture
// filtering as String b/c `AbstractTransformFuture` is a package-private class
!runnable.javaClass.enclosingClass.toString()
.contains("AbstractTransformFuture")
}
runTest {
val expectError = assertFailsWith<AssertionError> {
itemStore.awaitInitialLoad(timeOutDuration = 2)
}
assertThat(expectError.message).isEqualTo("didn't complete in expected time")
val futures = pagingSources[0].futures
assertThat(futures.size).isEqualTo(1)
assertThat(futures[0].isDone).isFalse() // initial load future is pending
// now cancel collection which should also cancel the future
coroutineScope.cancel()
// just making sure no new futures are created, and ensuring that the pending future
// is now cancelled
assertThat(futures.size).isEqualTo(1)
assertThat(futures[0].isCancelled).isTrue()
assertThat(futures[0].isDone).isTrue()
}
}
@Test
fun append_canceledCoroutine_cancelsFuture() {
val items = createItems(startId = 0, count = 90)
db.dao.insert(items)
runTest {
itemStore.awaitInitialLoad()
val futures = pagingSources[0].futures
assertThat(futures.size).isEqualTo(1)
assertThat(futures[0].isDone).isTrue() // initial load future is complete
queryExecutor.filterFunction = { runnable ->
// filtering out the transform async function called inside loadFuture
// filtering as String b/c `AbstractTransformFuture` is a package-private class
!runnable.javaClass.enclosingClass.toString()
.contains("AbstractTransformFuture")
}
// now access more items that should trigger loading more
withContext(Dispatchers.Main) {
itemStore.get(10)
}
// await should fail because we have blocked the paging source' async function,
// which calls nonInitialLoad in this case, from executing
val expectError = assertFailsWith<AssertionError> {
assertThat(itemStore.awaitItem(index = 10, timeOutDuration = 2))
.isEqualTo(items[10])
}
assertThat(expectError.message).isEqualTo("didn't complete in expected time")
queryExecutor.awaitDeferredSizeAtLeast(1)
// even though the load runnable was blocked, a new future should have been returned
assertThat(futures.size).isEqualTo(2)
// ensure future is pending
assertThat(futures[1].isDone).isFalse()
// now cancel collection which should also cancel the future
coroutineScope.cancel()
// just making sure no new futures are created, and ensuring that the pending future
// is now cancelled
assertThat(futures.size).isEqualTo(2)
assertThat(futures[1].isCancelled).isTrue()
assertThat(futures[1].isDone).isTrue()
}
}
@Test
fun prepend_canceledCoroutine_cancelsFuture() {
val items = createItems(startId = 0, count = 90)
db.dao.insert(items)
runTest {
itemStore.awaitInitialLoad()
val futures = pagingSources[0].futures
assertThat(futures.size).isEqualTo(1)
assertThat(futures[0].isDone).isTrue() // initial load future is complete
queryExecutor.filterFunction = { runnable ->
// filtering out the transform async function called inside loadFuture
// filtering as String b/c `AbstractTransformFuture` is a package-private class
!runnable.javaClass.enclosingClass.toString()
.contains("AbstractTransformFuture")
}
// now access more items that should trigger loading more
withContext(Dispatchers.Main) {
itemStore.get(40)
}
// await should fail because we have blocked the paging source' async function,
// which calls nonInitialLoad in this case, from executing
val expectError = assertFailsWith<AssertionError> {
assertThat(itemStore.awaitItem(index = 40, timeOutDuration = 2))
.isEqualTo(items[40])
}
assertThat(expectError.message).isEqualTo("didn't complete in expected time")
queryExecutor.awaitDeferredSizeAtLeast(1)
// even though the load runnable was blocked, a new future should have been returned
assertThat(futures.size).isEqualTo(2)
// ensure future is pending
assertThat(futures[1].isDone).isFalse()
// now cancel collection which should also cancel the future
coroutineScope.cancel()
// just making sure no new futures are created, and ensuring that the pending future
// is now cancelled
assertThat(futures.size).isEqualTo(2)
assertThat(futures[1].isCancelled).isTrue()
assertThat(futures[1].isDone).isTrue()
}
}
private fun runTest(
pager: Pager<Int, PagingEntity> =
Pager(config = CONFIG) {
val baseSource = db.dao.loadItemsListenableFuture()
// to get access to the futures returned from loadFuture. Also to
// mimic real use case of wrapping the source returned from Room.
ListenableFuturePagingSourceImpl(baseSource).also { pagingSources.add(it) }
},
block: suspend () -> Unit
) {
val collection = coroutineScope.launch(Dispatchers.Main) {
pager.flow.collectLatest {
itemStore.collectFrom(it)
}
}
runBlocking {
try {
block()
} finally {
collection.cancelAndJoin()
}
}
}
}
private class ListenableFuturePagingSourceImpl(
private val baseSource: ListenableFuturePagingSource<Int, PagingEntity>
) : ListenableFuturePagingSource<Int, PagingEntity>() {
val futures = mutableListOf<ListenableFuture<LoadResult<Int, PagingEntity>>>()
override fun getRefreshKey(state: PagingState<Int, PagingEntity>): Int? {
return baseSource.getRefreshKey(state)
}
override fun loadFuture(params: LoadParams<Int>):
ListenableFuture<LoadResult<Int, PagingEntity>> {
return baseSource.loadFuture(params).also { futures.add(it) }
}
}
| apache-2.0 | 8212d2f98a3105b62b706ae862110c52 | 38.80212 | 96 | 0.657493 | 5.171717 | false | true | false | false |
kirtan403/K4Kotlin | k4kotlin-core/src/main/java/com/livinglifetechway/k4kotlin/core/Views.kt | 1 | 1962 | @file:Suppress("NOTHING_TO_INLINE")
package com.livinglifetechway.k4kotlin.core
import android.view.View
/**
* Sets the view's visibility to GONE
*/
inline fun View.hide() {
visibility = View.GONE
}
/**
* Sets the view's visibility to VISIBLE
*/
inline fun View.show() {
visibility = View.VISIBLE
}
/**
* Sets the view's visibility to INVISIBLE
*/
inline fun View.invisible() {
visibility = View.INVISIBLE
}
/**
* DEPRECATED
* Toggle's view's visibility. If View is visible, then sets to gone. Else sets Visible
*/
@Deprecated("Use toggleVisibility() instead", ReplaceWith("this.toggleVisibility()", "android.view.View"))
inline fun View.toggle() = toggleVisibility()
/**
* Toggle's view's visibility. If View is visible, then sets to gone. Else sets Visible
* Previously knows as toggle()
*/
inline fun View.toggleVisibility() {
visibility = if (visibility == View.VISIBLE) View.GONE else View.VISIBLE
}
/**
* Hides all the views passed in the arguments
*/
fun hideViews(vararg views: View) = views.forEach { it.visibility = View.GONE }
/**
* Shows all the views passed in the arguments
*/
fun showViews(vararg views: View) = views.forEach { it.visibility = View.VISIBLE }
/**
* Sets the onClick listener on the View
*/
inline fun <T : View> T.onClick(crossinline function: T.() -> Unit) {
setOnClickListener { function() }
}
/**
* Sets the onLongClick listener on the View
*/
inline fun <T : View> T.onLongClick(crossinline function: T.() -> Unit) {
setOnLongClickListener { function(); true }
}
/**
* Can update the padding of the specified side without changing other values
*/
fun View.updatePadding(paddingStart: Int = getPaddingStart(),
paddingTop: Int = getPaddingTop(),
paddingEnd: Int = getPaddingEnd(),
paddingBottom: Int = getPaddingBottom()) {
setPaddingRelative(paddingStart, paddingTop, paddingEnd, paddingBottom)
}
| apache-2.0 | 7edc1e0d7e6243eca8698b8b53588486 | 25.16 | 106 | 0.682467 | 4.037037 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/widgets/chartbar/ChartBar.kt | 2 | 1818 | package ru.fantlab.android.ui.widgets.chartbar
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.chartbar.*
import ru.fantlab.android.R
import ru.fantlab.android.helper.BundleConstant
import ru.fantlab.android.helper.Bundler
import ru.fantlab.android.ui.base.BaseBottomSheetDialog
open class ChartBar : BaseBottomSheetDialog() {
override fun layoutRes(): Int = R.layout.chartbar
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val bundle = arguments ?: return
val title = bundle.getString(BundleConstant.EXTRA)
val caption = bundle.getString(BundleConstant.EXTRA_TWO)
val colored = bundle.getBoolean(BundleConstant.YES_NO_EXTRA)
val points = bundle.getSerializable(BundleConstant.ITEM) as ArrayList<Pair<String, Int>>
this.title.text = title
if (caption.isNotEmpty()) {
this.caption.text = caption
this.caption.visibility = View.VISIBLE
}
renderChart(points, colored)
}
private fun renderChart(points: ArrayList<Pair<String, Int>>, colored: Boolean) {
chartBarView.setPoints(points, colored)
}
companion object {
val TAG: String = ChartBar::class.java.simpleName
fun newInstance(title: String, caption: String = "", points: ArrayList<Pair<String, Int>>, colored: Boolean = false): ChartBar {
val chartBarView = ChartBar()
chartBarView.arguments = getBundle(title, caption, points, colored)
return chartBarView
}
private fun getBundle(title: String, caption: String, points: ArrayList<Pair<String, Int>>, colored: Boolean): Bundle {
return Bundler.start()
.put(BundleConstant.EXTRA, title)
.put(BundleConstant.EXTRA_TWO, caption)
.put(BundleConstant.YES_NO_EXTRA, colored)
.put(BundleConstant.ITEM, points)
.end()
}
}
} | gpl-3.0 | 279d0a71fe9fd263768e4c67a60c11a8 | 31.482143 | 130 | 0.751375 | 3.72541 | false | false | false | false |
world-federation-of-advertisers/panel-exchange-client | src/main/kotlin/org/wfanet/panelmatch/common/Protos.kt | 1 | 1933 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.panelmatch.common
import com.google.protobuf.ByteString
import com.google.protobuf.MessageLite
import java.io.InputStream
import java.time.Duration
/** Reads length-delimited [T] messages from a [ByteString]. */
fun <T : MessageLite> ByteString.parseDelimitedMessages(prototype: T): Iterable<T> =
newInput().parseDelimitedMessages(prototype)
/** Reads length-delimited [T] messages from an [InputStream]. */
fun <T : MessageLite> InputStream.parseDelimitedMessages(prototype: T): Iterable<T> = Iterable {
iterator {
[email protected] { inputStream ->
val parser = prototype.parserForType
while (true) {
@Suppress("UNCHECKED_CAST") // MessageLite::getParseForType guarantees this cast is safe.
val message = parser.parseDelimitedFrom(inputStream) as T? ?: break
yield(message)
}
}
}
}
/** Serializes a [MessageLite] with its length. */
fun MessageLite.toDelimitedByteString(): ByteString {
val outputStream = ByteString.newOutput()
writeDelimitedTo(outputStream)
return outputStream.toByteString()
}
/** Converts a java.time.Duration to com.google.protobuf.Duration */
fun Duration.toProto(): com.google.protobuf.Duration {
return com.google.protobuf.Duration.newBuilder().setSeconds(seconds).setNanos(nano).build()
}
| apache-2.0 | 120248705026905551b53e2442d26c81 | 37.66 | 97 | 0.744956 | 4.165948 | false | true | false | false |
lrannn/EasyView | app/src/main/java/com/mass/view/model/data/local/ArticlesDataSource.kt | 1 | 3380 | package com.mass.view.model.data.local
import android.content.ContentValues
import android.content.Context
import com.google.common.collect.Lists
import com.mass.view.model.bean.Article
import com.mass.view.model.data.ArticlesSource
/**
* Created by lrannn on 2017/9/1.
* @email [email protected]
*/
class ArticlesDataSource private constructor(context: Context) : ArticlesSource {
private var mDbHelper: ArticleDbHelper? = null
init {
mDbHelper = ArticleDbHelper(context)
}
companion object {
private var INSTANCE: ArticlesDataSource? = null
fun getInstance(context: Context): ArticlesDataSource? {
if (INSTANCE == null) {
INSTANCE = ArticlesDataSource(context)
}
return INSTANCE
}
}
override fun loadAll(): List<Article> {
val list = Lists.newArrayList<Article>()
val db = mDbHelper?.readableDatabase
val cursor = db?.query(ArticlesPersistenceContract.Companion.ArticleEntry.TABLE_NAME,
null, null, null, null, null, null)
while (cursor!!.moveToNext()) {
}
return list
}
override fun saveArticle(article: Article) {
val db = mDbHelper?.writableDatabase
val values = ContentValues()
values.put(ArticlesPersistenceContract.Companion.ArticleEntry.COLUMN_NAME_ENTRY_ID, article.id)
values.put(ArticlesPersistenceContract.Companion.ArticleEntry.COLUMN_NAME_IMG, article.firstImg)
values.put(ArticlesPersistenceContract.Companion.ArticleEntry.COLUMN_NAME_TITLE, article.title)
values.put(ArticlesPersistenceContract.Companion.ArticleEntry.COLUMN_NAME_SOURCE, article.source)
values.put(ArticlesPersistenceContract.Companion.ArticleEntry.COLUMN_NAME_DESCRIPTION, article.url)
db?.insert(ArticlesPersistenceContract.Companion.ArticleEntry.TABLE_NAME, null, values)
db?.close()
}
// Don't use saveArticle in foreach, beacuse sqlitedabase close function will apply too many memory
override fun saveAll(articles: List<Article>) {
checkNotNull(articles)
val db = mDbHelper?.writableDatabase
val iterator = articles.iterator()
val values = ContentValues()
while (iterator.hasNext()) {
val article = iterator.next()
values.clear()
values.put(ArticlesPersistenceContract.Companion.ArticleEntry.COLUMN_NAME_ENTRY_ID, article.id)
values.put(ArticlesPersistenceContract.Companion.ArticleEntry.COLUMN_NAME_IMG, article.firstImg)
values.put(ArticlesPersistenceContract.Companion.ArticleEntry.COLUMN_NAME_TITLE, article.title)
values.put(ArticlesPersistenceContract.Companion.ArticleEntry.COLUMN_NAME_SOURCE, article.source)
values.put(ArticlesPersistenceContract.Companion.ArticleEntry.COLUMN_NAME_DESCRIPTION, article.url)
db?.insert(ArticlesPersistenceContract.Companion.ArticleEntry.TABLE_NAME, null, values)
}
db?.close()
}
override fun refreshAll() {
}
override fun deleteAll() {
val db = mDbHelper?.writableDatabase
db?.delete(ArticlesPersistenceContract.Companion.ArticleEntry.TABLE_NAME, null, null)
db?.close()
}
override fun delete(article: Article) {
}
override fun delete(id: Int) {
}
} | apache-2.0 | ecb0075a97b2f6f51f880a54035526bd | 36.153846 | 111 | 0.693787 | 4.494681 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/plugin-api/test/uk/co/reecedunn/intellij/plugin/processor/tests/debug/frame/QueryResultsValueTest.kt | 1 | 17896 | /*
* Copyright (C) 2020 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.processor.tests.debug.frame
import com.intellij.xdebugger.frame.XFullValueEvaluator
import com.intellij.xdebugger.frame.XValue
import com.intellij.xdebugger.frame.XValueNode
import com.intellij.xdebugger.frame.XValuePlace
import com.intellij.xdebugger.frame.presentation.XNumericValuePresentation
import com.intellij.xdebugger.frame.presentation.XRegularValuePresentation
import com.intellij.xdebugger.frame.presentation.XValuePresentation
import org.hamcrest.CoreMatchers.*
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import uk.co.reecedunn.intellij.plugin.core.tests.assertion.assertThat
import uk.co.reecedunn.intellij.plugin.processor.debug.frame.QueryResultsValue
import uk.co.reecedunn.intellij.plugin.processor.query.QueryResult
import javax.swing.Icon
@DisplayName("IntelliJ - Base Platform - Run Configuration - Query Debugger - Values")
class QueryResultsValueTest : XValueNode {
// region XValueNode
private var icon: Icon? = null
private var presentation: XValuePresentation? = null
private var hasChildren: Boolean = false
private fun computePresentation(value: XValue, place: XValuePlace) {
icon = null
presentation = null
value.computePresentation(this, place)
}
private fun renderValue(): String? = presentation?.let {
it.renderValue(ValueTextRenderer)
ValueTextRenderer.rendered
}
override fun setFullValueEvaluator(fullValueEvaluator: XFullValueEvaluator): Unit = TODO()
override fun setPresentation(icon: Icon?, type: String?, value: String, hasChildren: Boolean) {
setPresentation(icon, XRegularValuePresentation(value, type), hasChildren)
}
override fun setPresentation(icon: Icon?, presentation: XValuePresentation, hasChildren: Boolean) {
this.icon = icon
this.presentation = presentation
this.hasChildren = hasChildren
}
override fun setPresentation(icon: Icon?, type: String?, separator: String, value: String?, hasChildren: Boolean) {
TODO("Don't call this deprecated API.")
}
// endregion
@Test
@DisplayName("empty sequence")
fun emptySequence() {
val v = QueryResultsValue(listOf())
computePresentation(v, XValuePlace.TREE)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("empty-sequence()"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("()"))
assertThat(hasChildren, `is`(false))
computePresentation(v, XValuePlace.TOOLTIP)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("empty-sequence()"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("()"))
assertThat(hasChildren, `is`(false))
}
@Test
@DisplayName("single item")
fun singleItem() {
val v = QueryResultsValue(listOf(QueryResult.fromItemType(0, "1234", "xs:integer")))
computePresentation(v, XValuePlace.TREE)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XNumericValuePresentation::class.java)))
assertThat(presentation?.type, `is`("xs:integer"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("1234"))
assertThat(hasChildren, `is`(false))
computePresentation(v, XValuePlace.TOOLTIP)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XNumericValuePresentation::class.java)))
assertThat(presentation?.type, `is`("xs:integer"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("1234"))
assertThat(hasChildren, `is`(false))
}
@Test
@DisplayName("multiple items of the same type")
fun multipleItemsOfSameType() {
val v = QueryResultsValue(
listOf(
QueryResult.fromItemType(0, "1", "xs:integer"),
QueryResult.fromItemType(1, "2", "xs:integer"),
QueryResult.fromItemType(2, "3", "xs:integer")
)
)
computePresentation(v, XValuePlace.TREE)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("xs:integer+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
computePresentation(v, XValuePlace.TOOLTIP)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("xs:integer+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
}
@Test
@DisplayName("multiple items of different item() types")
fun multipleItemsOfDifferentItemTypes() {
val v = QueryResultsValue(
listOf(
QueryResult.fromItemType(0, "1", "xs:integer"),
QueryResult.fromItemType(1, "2", "text()"),
QueryResult.fromItemType(2, "3", "xs:integer")
)
)
computePresentation(v, XValuePlace.TREE)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("item()+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
computePresentation(v, XValuePlace.TOOLTIP)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("item()+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
}
@Test
@DisplayName("multiple items with a type subtype-itemType to the other types")
fun multipleItemsSubtypeItemType() {
val v = QueryResultsValue(
listOf(
QueryResult.fromItemType(0, "1", "xs:integer"),
QueryResult.fromItemType(1, "2.0", "xs:decimal"),
QueryResult.fromItemType(2, "3", "xs:integer")
)
)
computePresentation(v, XValuePlace.TREE)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("xs:decimal+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
computePresentation(v, XValuePlace.TOOLTIP)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("xs:decimal+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
}
@Test
@DisplayName("multiple processing instructions with different NCNames")
fun multipleProcessingInstructionsDifferentNCName() {
val v = QueryResultsValue(
listOf(
QueryResult.fromItemType(0, "1", "processing-instruction(a)"),
QueryResult.fromItemType(1, "2", "processing-instruction(b)"),
QueryResult.fromItemType(2, "3", "processing-instruction(c)")
)
)
computePresentation(v, XValuePlace.TREE)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("processing-instruction()+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
computePresentation(v, XValuePlace.TOOLTIP)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("processing-instruction()+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
}
@Test
@DisplayName("named processing instrucuions with other nodes")
fun namedProcessingInstructionsWithOtherNodes() {
val v = QueryResultsValue(
listOf(
QueryResult.fromItemType(0, "1", "processing-instruction(a)"),
QueryResult.fromItemType(1, "2", "comment()"),
QueryResult.fromItemType(2, "3", "text()")
)
)
computePresentation(v, XValuePlace.TREE)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("node()+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
computePresentation(v, XValuePlace.TOOLTIP)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("node()+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
}
@Test
@DisplayName("multiple document nodes with different element types")
fun multipleDocumentNodesDifferentTypes() {
val v = QueryResultsValue(
listOf(
QueryResult.fromItemType(0, "1", "document-node(element(Q{}a))"),
QueryResult.fromItemType(1, "2", "document-node(element(Q{}b))"),
QueryResult.fromItemType(2, "3", "document-node(element(Q{}c))")
)
)
computePresentation(v, XValuePlace.TREE)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("document-node()+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
computePresentation(v, XValuePlace.TOOLTIP)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("document-node()+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
}
@Test
@DisplayName("typed document nodes with other nodes")
fun typedDocumentNodesWithOtherNodes() {
val v = QueryResultsValue(
listOf(
QueryResult.fromItemType(0, "1", "document-node(element(Q{}a))"),
QueryResult.fromItemType(1, "2", "comment()"),
QueryResult.fromItemType(2, "3", "text()")
)
)
computePresentation(v, XValuePlace.TREE)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("node()+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
computePresentation(v, XValuePlace.TOOLTIP)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("node()+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
}
@Test
@DisplayName("multiple elements with different QNames")
fun multipleElementsDifferentQName() {
val v = QueryResultsValue(
listOf(
QueryResult.fromItemType(0, "1", "element(Q{}a)"),
QueryResult.fromItemType(1, "2", "element(Q{}b)"),
QueryResult.fromItemType(2, "3", "element(Q{}c)")
)
)
computePresentation(v, XValuePlace.TREE)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("element()+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
computePresentation(v, XValuePlace.TOOLTIP)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("element()+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
}
@Test
@DisplayName("named element with other nodes")
fun namedElementWithOtherNodes() {
val v = QueryResultsValue(
listOf(
QueryResult.fromItemType(0, "1", "element(Q{}a)"),
QueryResult.fromItemType(1, "2", "comment()"),
QueryResult.fromItemType(2, "3", "text()")
)
)
computePresentation(v, XValuePlace.TREE)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("node()+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
computePresentation(v, XValuePlace.TOOLTIP)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("node()+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
}
@Test
@DisplayName("multiple attributes with different QNames")
fun multipleAttributesDifferentQName() {
val v = QueryResultsValue(
listOf(
QueryResult.fromItemType(0, "1", "attribute(Q{}a)"),
QueryResult.fromItemType(1, "2", "attribute(Q{}b)"),
QueryResult.fromItemType(2, "3", "attribute(Q{}c)")
)
)
computePresentation(v, XValuePlace.TREE)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("attribute()+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
computePresentation(v, XValuePlace.TOOLTIP)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("attribute()+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
}
@Test
@DisplayName("named attribute with other nodes")
fun namedAttributesWithOtherNodes() {
val v = QueryResultsValue(
listOf(
QueryResult.fromItemType(0, "1", "attribute(Q{}a)"),
QueryResult.fromItemType(1, "2", "comment()"),
QueryResult.fromItemType(2, "3", "text()")
)
)
computePresentation(v, XValuePlace.TREE)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("node()+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
computePresentation(v, XValuePlace.TOOLTIP)
assertThat(icon, `is`(nullValue()))
assertThat(presentation, `is`(instanceOf(XRegularValuePresentation::class.java)))
assertThat(presentation?.type, `is`("node()+"))
assertThat(presentation?.separator, `is`(" := "))
assertThat(renderValue(), `is`("size = 3"))
assertThat(hasChildren, `is`(true))
}
}
| apache-2.0 | 552b64efed5c2206816bd25b5942b37e | 41.508314 | 119 | 0.63137 | 4.665276 | false | false | false | false |
westnordost/StreetComplete | app/src/test/java/de/westnordost/streetcomplete/Mockito.kt | 1 | 640 | package de.westnordost.streetcomplete
import org.mockito.ArgumentCaptor
import org.mockito.Mockito
import org.mockito.stubbing.OngoingStubbing
import org.mockito.stubbing.Stubber
fun <T> eq(obj: T): T = Mockito.eq<T>(obj)
fun <T> any(): T = Mockito.any<T>()
fun <T> capture(argumentCaptor: ArgumentCaptor<T>): T = argumentCaptor.capture()
inline fun <reified T : Any> argumentCaptor(): ArgumentCaptor<T> =
ArgumentCaptor.forClass(T::class.java)
fun <T> on(methodCall: T): OngoingStubbing<T> = Mockito.`when`(methodCall)
fun <T> Stubber.on(mock:T): T = this.`when`(mock)
inline fun <reified T> mock():T = Mockito.mock(T::class.java)
| gpl-3.0 | 5ec7f13d1af78689645e7a0dabdefc2e | 36.647059 | 80 | 0.735938 | 3.368421 | false | false | false | false |
fredyw/leetcode | src/main/kotlin/leetcode/Problem1462.kt | 1 | 1562 | package leetcode
/**
* https://leetcode.com/problems/course-schedule-iv/
*/
class Problem1462 {
fun checkIfPrerequisite(numCourses: Int, prerequisites: Array<IntArray>,
queries: Array<IntArray>): List<Boolean> {
val adjList = buildAdjList(prerequisites)
val dependencyMap = mutableMapOf<Int, MutableSet<Int>>()
for (course in 0 until numCourses) {
val dependencies = mutableSetOf<Int>()
dfs(adjList, BooleanArray(numCourses), dependencies, course)
dependencyMap[course] = dependencies
}
val answer = mutableListOf<Boolean>()
for (query in queries) {
answer += query[1] in dependencyMap[query[0]]!!
}
return answer
}
private fun buildAdjList(prerequisites: Array<IntArray>): Map<Int, List<Int>> {
val adjList = mutableMapOf<Int, MutableList<Int>>()
for (prerequisite in prerequisites) {
val from = prerequisite[0]
val to = prerequisite[1]
val list = adjList[from] ?: mutableListOf()
list += to
adjList[from] = list
}
return adjList
}
private fun dfs(adjList: Map<Int, List<Int>>, visited: BooleanArray,
dependencies: MutableSet<Int>, course: Int) {
visited[course] = true
for (adj in (adjList[course] ?: listOf())) {
if (!visited[adj]) {
dfs(adjList, visited, dependencies, adj)
}
}
dependencies += course
}
}
| mit | 3ea90c41670b637dbbc0132161831f20 | 33.711111 | 83 | 0.573624 | 4.527536 | false | false | false | false |
dhleong/ideavim | src/com/maddyhome/idea/vim/ex/handler/ActionListHandler.kt | 1 | 2626 | /*
* IdeaVim - Vim emulator for IDEs based on the IntelliJ platform
* Copyright (C) 2003-2019 The IdeaVim authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.maddyhome.idea.vim.ex.handler
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.KeyboardShortcut
import com.intellij.openapi.editor.Editor
import com.maddyhome.idea.vim.ex.CommandHandler
import com.maddyhome.idea.vim.ex.CommandHandler.Flag.DONT_REOPEN
import com.maddyhome.idea.vim.ex.CommandHandlerFlags
import com.maddyhome.idea.vim.ex.CommandName
import com.maddyhome.idea.vim.ex.ExCommand
import com.maddyhome.idea.vim.ex.ExOutputModel
import com.maddyhome.idea.vim.ex.commands
import com.maddyhome.idea.vim.ex.flags
import com.maddyhome.idea.vim.helper.StringHelper
/**
* @author smartbomb
*/
class ActionListHandler : CommandHandler.SingleExecution() {
override val names: Array<CommandName> = commands("actionlist")
override val argFlags: CommandHandlerFlags = flags(RangeFlag.RANGE_FORBIDDEN, ArgumentFlag.ARGUMENT_OPTIONAL, DONT_REOPEN)
override fun execute(editor: Editor, context: DataContext, cmd: ExCommand): Boolean {
val lineSeparator = "\n"
val searchPattern = cmd.argument.trim().toLowerCase().split("*")
val actionManager = ActionManager.getInstance()
val actions = actionManager.getActionIds("")
.sortedWith(String.CASE_INSENSITIVE_ORDER)
.map { actionName ->
val shortcuts = actionManager.getAction(actionName).shortcutSet.shortcuts.joinToString(" ") {
if (it is KeyboardShortcut) StringHelper.toKeyNotation(it.firstKeyStroke) else it.toString()
}
if (shortcuts.isBlank()) actionName else "${actionName.padEnd(50)} $shortcuts"
}
.filter { line -> searchPattern.all { it in line.toLowerCase() } }
.joinToString(lineSeparator)
ExOutputModel.getInstance(editor).output("--- Actions ---$lineSeparator$actions")
return true
}
}
| gpl-2.0 | 032c5d2f051f9adfef88d7fa0b82a960 | 41.354839 | 124 | 0.756664 | 4.297872 | false | false | false | false |
auth0/Auth0.Android | auth0/src/main/java/com/auth0/android/request/internal/RequestFactory.kt | 1 | 2932 | package com.auth0.android.request.internal
import androidx.annotation.VisibleForTesting
import com.auth0.android.Auth0Exception
import com.auth0.android.request.*
import com.auth0.android.util.Auth0UserAgent
import java.io.Reader
import java.util.*
internal class RequestFactory<U : Auth0Exception> internal constructor(
private val client: NetworkingClient,
private val errorAdapter: ErrorAdapter<U>
) {
private companion object {
private const val DEFAULT_LOCALE_IF_MISSING = "en_US"
private const val ACCEPT_LANGUAGE_HEADER = "Accept-Language"
private const val AUTH0_CLIENT_INFO_HEADER = Auth0UserAgent.HEADER_NAME
val defaultLocale: String
get() {
val language = Locale.getDefault().toString()
return if (language.isNotEmpty()) language else DEFAULT_LOCALE_IF_MISSING
}
}
private val baseHeaders = mutableMapOf(Pair(ACCEPT_LANGUAGE_HEADER, defaultLocale))
fun <T> post(
url: String,
resultAdapter: JsonAdapter<T>
): Request<T, U> = setupRequest(HttpMethod.POST, url, resultAdapter, errorAdapter)
fun post(url: String): Request<Void?, U> =
this.post(url, object : JsonAdapter<Void?> {
override fun fromJson(reader: Reader): Void? {
return null
}
})
fun <T> patch(
url: String,
resultAdapter: JsonAdapter<T>
): Request<T, U> = setupRequest(HttpMethod.PATCH, url, resultAdapter, errorAdapter)
fun <T> delete(
url: String,
resultAdapter: JsonAdapter<T>
): Request<T, U> = setupRequest(HttpMethod.DELETE, url, resultAdapter, errorAdapter)
fun <T> get(
url: String,
resultAdapter: JsonAdapter<T>
): Request<T, U> = setupRequest(HttpMethod.GET, url, resultAdapter, errorAdapter)
fun setHeader(name: String, value: String) {
baseHeaders[name] = value
}
fun setAuth0ClientInfo(clientInfo: String) {
baseHeaders[AUTH0_CLIENT_INFO_HEADER] = clientInfo
}
@VisibleForTesting
fun <T> createRequest(
method: HttpMethod,
url: String,
client: NetworkingClient,
resultAdapter: JsonAdapter<T>,
errorAdapter: ErrorAdapter<U>,
threadSwitcher: ThreadSwitcher
): Request<T, U> = BaseRequest(method, url, client, resultAdapter, errorAdapter, threadSwitcher)
private fun <T> setupRequest(
method: HttpMethod,
url: String,
resultAdapter: JsonAdapter<T>,
errorAdapter: ErrorAdapter<U>
): Request<T, U> {
val request =
createRequest(
method,
url,
client,
resultAdapter,
errorAdapter,
CommonThreadSwitcher.getInstance()
)
baseHeaders.map { request.addHeader(it.key, it.value) }
return request
}
} | mit | 6c9fe9de58f7bdac9bdb309e87eb74c4 | 30.202128 | 100 | 0.631651 | 4.29912 | false | false | false | false |
treelzebub/zinepress | app/src/main/java/net/treelzebub/zinepress/util/dialog/BaseDialogFragment.kt | 1 | 2726 | package net.treelzebub.zinepress.util.dialog
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.app.DialogFragment
import android.content.Intent
import android.os.Bundle
import android.support.annotation.LayoutRes
import android.support.annotation.StringRes
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
/**
* Created by Tre Murillo on 1/30/16
*/
abstract class BaseDialogFragment(@LayoutRes val layout: Int,
@StringRes val title: Int,
@StringRes val message: Int,
@StringRes val positive: Int?,
@StringRes val neutral: Int?,
@StringRes val negative: Int?) : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog? {
val builder = AlertDialog.Builder(context)
.setTitle(title)
.setMessage(message)
if (positive != null) {
builder.setPositiveButton(positive, { dialog, which -> onPositive(null) })
}
if (neutral != null) {
builder.setNeutralButton(neutral, { dialog, which -> onNeutral(null) })
}
if (negative != null) {
builder.setNegativeButton(negative, { dialog, which -> onNegative(null) })
}
return builder.create()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle?): View {
super.onCreateView(inflater, container, savedInstanceState)
return inflater.inflate(layout, container, false).apply {
onCreateDialogView(this)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Override
}
protected open fun onCreateDialogView(v: View?) {
// Override
}
protected open fun onPositive(v: View?) {
onButton(v, Activity.RESULT_OK)
}
protected open fun onNeutral(v: View?) {
onButton(v, 0)
}
protected open fun onNegative(v: View?) {
onButton(v, Activity.RESULT_CANCELED)
}
protected open fun onButton(v: View?, code: Int) {
targetFragment?.onActivityResult(targetRequestCode, code, buildReturnIntent(code))
}
private fun buildReturnIntent(code: Int): Intent {
val retval = Intent()
if (code == Activity.RESULT_OK) {
val args = Bundle()
// onReturnBundle(args)
retval.putExtras(args)
}
return retval
}
}
| gpl-2.0 | 43f82bd92db59f17c42a8e13d9561f0a | 32.243902 | 114 | 0.609685 | 4.938406 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/searchUtil.kt | 1 | 8363 | // 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.search
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
import com.intellij.psi.impl.cache.impl.id.IdIndex
import com.intellij.psi.impl.cache.impl.id.IdIndexEntry
import com.intellij.psi.search.*
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.util.Processor
import com.intellij.util.indexing.FileBasedIndex
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.scriptDefinitionExists
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.kotlin.idea.base.utils.fqname.getKotlinFqName as getKotlinFqNameOriginal
infix fun SearchScope.and(otherScope: SearchScope): SearchScope = intersectWith(otherScope)
infix fun SearchScope.or(otherScope: SearchScope): SearchScope = union(otherScope)
infix fun GlobalSearchScope.or(otherScope: SearchScope): GlobalSearchScope = union(otherScope)
operator fun SearchScope.minus(otherScope: GlobalSearchScope): SearchScope = this and !otherScope
operator fun GlobalSearchScope.not(): GlobalSearchScope = GlobalSearchScope.notScope(this)
fun SearchScope.unionSafe(other: SearchScope): SearchScope {
if (this is LocalSearchScope && this.scope.isEmpty()) {
return other
}
if (other is LocalSearchScope && other.scope.isEmpty()) {
return this
}
return this.union(other)
}
fun Project.allScope(): GlobalSearchScope = GlobalSearchScope.allScope(this)
fun Project.projectScope(): GlobalSearchScope = GlobalSearchScope.projectScope(this)
fun PsiFile.fileScope(): GlobalSearchScope = GlobalSearchScope.fileScope(this)
fun Project.containsKotlinFile(): Boolean = FileTypeIndex.containsFileOfType(KotlinFileType.INSTANCE, projectScope())
fun GlobalSearchScope.restrictByFileType(fileType: FileType) = GlobalSearchScope.getScopeRestrictedByFileTypes(this, fileType)
fun SearchScope.restrictByFileType(fileType: FileType): SearchScope = when (this) {
is GlobalSearchScope -> restrictByFileType(fileType)
is LocalSearchScope -> {
val elements = scope.filter { it.containingFile.fileType == fileType }
when (elements.size) {
0 -> LocalSearchScope.EMPTY
scope.size -> this
else -> LocalSearchScope(elements.toTypedArray())
}
}
else -> this
}
fun GlobalSearchScope.restrictToKotlinSources() = restrictByFileType(KotlinFileType.INSTANCE)
fun SearchScope.restrictToKotlinSources() = restrictByFileType(KotlinFileType.INSTANCE)
fun SearchScope.excludeKotlinSources(project: Project): SearchScope = excludeFileTypes(project, KotlinFileType.INSTANCE)
fun Project.everythingScopeExcludeFileTypes(vararg fileTypes: FileType): GlobalSearchScope {
return GlobalSearchScope.getScopeRestrictedByFileTypes(GlobalSearchScope.everythingScope(this), *fileTypes).not()
}
fun SearchScope.excludeFileTypes(project: Project, vararg fileTypes: FileType): SearchScope {
return if (this is GlobalSearchScope) {
this.intersectWith(project.everythingScopeExcludeFileTypes(*fileTypes))
} else {
this as LocalSearchScope
val filteredElements = scope.filter { it.containingFile.fileType !in fileTypes }
if (filteredElements.isNotEmpty())
LocalSearchScope(filteredElements.toTypedArray())
else
LocalSearchScope.EMPTY
}
}
/**
* `( *\\( *)` and `( *\\) *)` – to find parenthesis
* `( *, *(?![^\\[]*]))` – to find commas outside square brackets
*/
private val parenthesisRegex = Regex("( *\\( *)|( *\\) *)|( *, *(?![^\\[]*]))")
private inline fun CharSequence.ifNotEmpty(action: (CharSequence) -> Unit) {
takeIf(CharSequence::isNotBlank)?.let(action)
}
fun SearchScope.toHumanReadableString(): String = buildString {
val scopeText = [email protected]()
var currentIndent = 0
var lastIndex = 0
for (parenthesis in parenthesisRegex.findAll(scopeText)) {
val subSequence = scopeText.subSequence(lastIndex, parenthesis.range.first)
subSequence.ifNotEmpty {
append(" ".repeat(currentIndent))
appendLine(it)
}
val value = parenthesis.value
when {
"(" in value -> currentIndent += 2
")" in value -> currentIndent -= 2
}
lastIndex = parenthesis.range.last + 1
}
if (isEmpty()) append(scopeText)
}
// Copied from SearchParameters.getEffectiveSearchScope()
fun ReferencesSearch.SearchParameters.effectiveSearchScope(element: PsiElement): SearchScope {
if (element == elementToSearch) return effectiveSearchScope
if (isIgnoreAccessScope) return scopeDeterminedByUser
val accessScope = element.useScope()
return scopeDeterminedByUser.intersectWith(accessScope)
}
fun isOnlyKotlinSearch(searchScope: SearchScope): Boolean {
return searchScope is LocalSearchScope && searchScope.scope.all { it.containingFile is KtFile }
}
fun PsiElement.codeUsageScopeRestrictedToProject(): SearchScope = project.projectScope().intersectWith(codeUsageScope())
fun PsiElement.useScope(): SearchScope = PsiSearchHelper.getInstance(project).getUseScope(this)
fun PsiElement.codeUsageScope(): SearchScope = PsiSearchHelper.getInstance(project).getCodeUsageScope(this)
// TODO: improve scope calculations
fun PsiElement.codeUsageScopeRestrictedToKotlinSources(): SearchScope = codeUsageScope().restrictToKotlinSources()
fun PsiSearchHelper.isCheapEnoughToSearchConsideringOperators(
name: String,
scope: GlobalSearchScope,
fileToIgnoreOccurrencesIn: PsiFile?,
progress: ProgressIndicator?
): PsiSearchHelper.SearchCostResult {
if (OperatorConventions.isConventionName(Name.identifier(name))) {
return PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES
}
return isCheapEnoughToSearch(name, scope, fileToIgnoreOccurrencesIn, progress)
}
fun findScriptsWithUsages(declaration: KtNamedDeclaration, processor: (KtFile) -> Boolean): Boolean {
val project = declaration.project
val scope = declaration.useScope() as? GlobalSearchScope ?: return true
val name = declaration.name.takeIf { it?.isNotBlank() == true } ?: return true
val collector = Processor<VirtualFile> { file ->
val ktFile =
(PsiManager.getInstance(project).findFile(file) as? KtFile)?.takeIf { it.scriptDefinitionExists() } ?: return@Processor true
processor(ktFile)
}
return FileBasedIndex.getInstance().getFilesWithKey(
IdIndex.NAME,
setOf(IdIndexEntry(name, true)),
collector,
scope
)
}
data class ReceiverTypeSearcherInfo(
val psiClass: PsiClass?,
val containsTypeOrDerivedInside: ((KtDeclaration) -> Boolean)
)
fun PsiReference.isImportUsage(): Boolean =
element.getNonStrictParentOfType<KtImportDirective>() != null
// Used in the "mirai" plugin
@Deprecated(
"Use org.jetbrains.kotlin.idea.refactoring.fqName.getKotlinFqName()",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith("getKotlinFqName()", "org.jetbrains.kotlin.idea.refactoring.fqName.getKotlinFqName")
)
fun PsiElement.getKotlinFqName(): FqName? = getKotlinFqNameOriginal()
fun PsiElement?.isPotentiallyOperator(): Boolean {
val namedFunction = safeAs<KtNamedFunction>() ?: return false
if (namedFunction.hasModifier(KtTokens.OPERATOR_KEYWORD)) return true
// operator modifier could be omitted for overriding function
if (!namedFunction.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return false
val name = namedFunction.name ?: return false
if (!OperatorConventions.isConventionName(Name.identifier(name))) return false
// TODO: it's fast PSI-based check, a proper check requires call to resolveDeclarationWithParents() that is not frontend-independent
return true
}
| apache-2.0 | 24f84cf88f1b18c77b79cc5b8e2f7fb7 | 41.217172 | 136 | 0.756191 | 4.92285 | false | false | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/OP/syntax/solver/LastVTSolver.kt | 1 | 1701 | package com.bajdcc.OP.syntax.solver
import com.bajdcc.OP.syntax.ISyntaxComponentVisitor
import com.bajdcc.OP.syntax.exp.BranchExp
import com.bajdcc.OP.syntax.exp.RuleExp
import com.bajdcc.OP.syntax.exp.SequenceExp
import com.bajdcc.OP.syntax.exp.TokenExp
import com.bajdcc.util.VisitBag
/**
* 求解非终结符的LastVT集合
*
* @author bajdcc
*/
class LastVTSolver(private val origin: RuleExp) : ISyntaxComponentVisitor {
/**
* 是否更新,作为算法收敛的依据
*/
/**
* 是否更改
*
* @return 经过此次计算,集合是否更新
*/
var isUpdated = false
private set
/**
* 当前规则中止
*/
private var stop = false
override fun visitBegin(node: TokenExp, bag: VisitBag) {
bag.visitChildren = false
bag.visitEnd = false
if (!stop) {
isUpdated = origin.rule.setLastVT.add(node)// 直接加入终结符,并中止遍历
stop = true
}
}
override fun visitBegin(node: RuleExp, bag: VisitBag) {
bag.visitChildren = false
bag.visitEnd = false
if (!stop) {
isUpdated = origin.rule.setLastVT.addAll(node.rule.setLastVT)// 加入当前非终结符的LastVT
}
}
override fun visitBegin(node: SequenceExp, bag: VisitBag) {
bag.visitEnd = false
stop = false
}
override fun visitBegin(node: BranchExp, bag: VisitBag) {
bag.visitEnd = false
}
override fun visitEnd(node: TokenExp) {
}
override fun visitEnd(node: RuleExp) {
}
override fun visitEnd(node: SequenceExp) {
}
override fun visitEnd(node: BranchExp) {
}
}
| mit | def18724e4761ece742f7a9826a50c41 | 20.148649 | 91 | 0.621725 | 3.58945 | false | false | false | false |
DuncanCasteleyn/DiscordModBot | src/test/kotlin/be/duncanc/discordmodbot/bot/sequences/PlanUnmuteSequenceTest.kt | 1 | 12069 | package be.duncanc.discordmodbot.bot.sequences
import be.duncanc.discordmodbot.bot.services.GuildLogger
import be.duncanc.discordmodbot.data.entities.MuteRole
import be.duncanc.discordmodbot.data.repositories.jpa.MuteRolesRepository
import be.duncanc.discordmodbot.data.services.ScheduledUnmuteService
import net.dv8tion.jda.api.JDA
import net.dv8tion.jda.api.entities.*
import net.dv8tion.jda.api.events.message.MessageReceivedEvent
import net.dv8tion.jda.api.requests.restaction.MessageAction
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.ArgumentMatchers.anyString
import org.mockito.Mock
import org.mockito.junit.jupiter.MockitoExtension
import org.mockito.kotlin.*
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.boot.test.mock.mockito.SpyBean
import org.springframework.test.util.ReflectionTestUtils
import java.util.*
import java.util.function.Consumer
@ExtendWith(MockitoExtension::class)
internal class PlanUnmuteSequenceTest {
@Mock
private lateinit var user: User
@Mock
private lateinit var channel: TextChannel
@Mock
private lateinit var scheduledUnmuteService: ScheduledUnmuteService
@Mock
private lateinit var targetUser: User
@Mock
private lateinit var messageAction: MessageAction
@Mock
private lateinit var jda: JDA
@Mock
private lateinit var messageReceivedEvent: MessageReceivedEvent
@Mock
private lateinit var message: Message
@Mock
private lateinit var guild: Guild
@Mock
private lateinit var guildLogger: GuildLogger
private lateinit var planUnmuteSequence: PlanUnmuteSequence
private lateinit var stubs: Array<Any>
@BeforeEach
fun `Set action for init`() {
whenever(channel.sendMessage(any<String>())).thenReturn(messageAction)
planUnmuteSequence = spy(PlanUnmuteSequence(user, channel, scheduledUnmuteService, targetUser, guildLogger))
stubs = arrayOf(
user,
channel,
scheduledUnmuteService,
targetUser,
messageAction,
jda,
messageReceivedEvent,
message,
guild,
planUnmuteSequence,
guildLogger
)
}
@AfterEach
fun `No more interactions with any spy or mocks`() {
verifyNoMoreInteractions(*stubs)
}
@Test
fun `When providing a valid answer to the first question a mute should be planned`() {
// Arrange
whenever(messageReceivedEvent.message).thenReturn(message)
whenever(message.contentRaw).thenReturn("30")
whenever(channel.guild).thenReturn(guild)
whenever(targetUser.name).thenReturn("A target user")
whenever(user.name).thenReturn("A moderator")
whenever(user.jda).thenReturn(jda)
// Act
val methodInvocationName = "onMessageReceivedDuringSequence"
ReflectionTestUtils.invokeMethod<Void>(
planUnmuteSequence,
methodInvocationName,
messageReceivedEvent
)
// Verify
verify(scheduledUnmuteService).planUnmute(any(), any(), any())
val onMessageReceivedDuringSequence =
mockingDetails(planUnmuteSequence).invocations.filter { it.method.name == methodInvocationName }
onMessageReceivedDuringSequence.first().markVerified()
verify(targetUser).idLong
verify(channel, times(3)).sendMessage(any<String>())
verify(channel).asMention
verify(user).asMention
verify(guild).idLong
verify(messageAction, times(3)).queue(any<Consumer<Message>>())
verify(guild).getMember(user)
verify(guild).getMember(targetUser)
verify(guildLogger).log(
any(),
eq(targetUser),
eq(guild),
eq(null),
eq(GuildLogger.LogTypeAction.MODERATOR),
eq(null)
)
verify(jda).removeEventListener(planUnmuteSequence)
}
@Test
fun `Providing a non-numeric message should fail`() {
// Arrange
whenever(messageReceivedEvent.message).thenReturn(message)
whenever(message.contentRaw).thenReturn("Definitely not a number")
// Act
val methodInvocationName = "onMessageReceivedDuringSequence"
val numberFormatException = assertThrows<NumberFormatException> {
ReflectionTestUtils.invokeMethod<Void>(
planUnmuteSequence, methodInvocationName,
messageReceivedEvent
)
}
// Verify
assertEquals("For input string: \"Definitely not a number\"", numberFormatException.message)
val onMessageReceivedDuringSequence =
mockingDetails(planUnmuteSequence).invocations.filter { it.method.name == methodInvocationName }
onMessageReceivedDuringSequence.first().markVerified()
verify(channel, times(2)).sendMessage(any<String>())
verify(channel).asMention
verify(user).asMention
verify(messageAction, times(2)).queue(any())
}
@Test
fun `Providing a negative number fails`() {
// Arrange
whenever(messageReceivedEvent.message).thenReturn(message)
whenever(message.contentRaw).thenReturn("-123")
// Act
val methodInvocationName = "onMessageReceivedDuringSequence"
val illegalArgumentException = assertThrows<IllegalArgumentException> {
ReflectionTestUtils.invokeMethod<Void>(
planUnmuteSequence, methodInvocationName,
messageReceivedEvent
)
}
// Verify
assertEquals("The numbers of days should not be negative or 0", illegalArgumentException.message)
val onMessageReceivedDuringSequence =
mockingDetails(planUnmuteSequence).invocations.filter { it.method.name == methodInvocationName }
onMessageReceivedDuringSequence.first().markVerified()
verify(channel, times(2)).sendMessage(any<String>())
verify(channel).asMention
verify(user).asMention
verify(messageAction, times(2)).queue(any())
}
}
@SpringBootTest(classes = [PlanUnmuteCommand::class])
@ExtendWith(MockitoExtension::class)
internal class PlanUnmuteCommandTest {
@MockBean
private lateinit var scheduledUnmuteService: ScheduledUnmuteService
@MockBean
private lateinit var guildLogger: GuildLogger
@MockBean
private lateinit var muteRolesRepository: MuteRolesRepository
@SpyBean
private lateinit var planUnmuteCommand: PlanUnmuteCommand
@Mock
private lateinit var messageReceivedEvent: MessageReceivedEvent
@Mock
private lateinit var jda: JDA
@Mock
private lateinit var message: Message
@Mock
private lateinit var guild: Guild
@Mock
private lateinit var member: Member
@Mock
private lateinit var user: User
@Mock
private lateinit var messageAction: MessageAction
@Mock
private lateinit var messageChannel: MessageChannel
@AfterEach
fun `No more interactions with any spy or mocks`() {
verifyNoMoreInteractions(
jda, planUnmuteCommand, scheduledUnmuteService, message, message, guild, member, user,
messageAction, messageChannel, guildLogger, muteRolesRepository
)
}
@Test
fun `Executing a valid command works`() {
// Arrange
val messageContent = "!${planUnmuteCommand.aliases[0]} <@1>"
clearInvocations(planUnmuteCommand)
val optional = Optional.of(MuteRole(1, 1))
whenever(muteRolesRepository.findById(any())).thenReturn(optional)
val roles = mock<List<Role>>()
whenever(member.roles).thenReturn(roles)
whenever(roles.contains(any())).thenReturn(true)
val role = mock<Role>()
whenever(guild.getRoleById(any<Long>())).thenReturn(role)
whenever(member.guild).thenReturn(guild)
whenever(messageReceivedEvent.message).thenReturn(message)
whenever(message.contentRaw).thenReturn(messageContent)
whenever(messageReceivedEvent.guild).thenReturn(guild)
whenever(guild.getMemberById(1)).thenReturn(member)
whenever(member.user).thenReturn(user)
whenever(messageReceivedEvent.author).thenReturn(user)
whenever(messageReceivedEvent.channel).thenReturn(messageChannel)
whenever(messageChannel.sendMessage(anyString())).thenReturn(messageAction)
whenever(messageReceivedEvent.jda).thenReturn(jda)
// Act
ReflectionTestUtils.invokeMethod<Void>(
planUnmuteCommand, "commandExec",
messageReceivedEvent, planUnmuteCommand.aliases[0], null
)
// Assert
verify(planUnmuteCommand).aliases
val commandExecInvocations =
mockingDetails(planUnmuteCommand).invocations.filter { it.method.name == "commandExec" }
assertEquals(1, commandExecInvocations.size, "Expected method commandExec to be executed once.")
commandExecInvocations.first().markVerified()
verify(muteRolesRepository).findById(any<Long>())
verify(messageReceivedEvent).message
verify(messageReceivedEvent).guild
verify(guild).idLong
verify(guild).getMemberById(1)
verify(member).user
verify(jda).addEventListener(any<PlanUnmuteSequence>())
verify(user).asMention
verify(messageAction, times(2)).queue(any())
}
@Test
fun `Executing a command without id does not start sequence`() {
// Arrange
val messageContent = "!${planUnmuteCommand.aliases[0]}"
clearInvocations(planUnmuteCommand)
whenever(messageReceivedEvent.message).thenReturn(message)
whenever(message.contentRaw).thenReturn(messageContent)
// Act
val illegalArgumentException = assertThrows<IllegalArgumentException> {
ReflectionTestUtils.invokeMethod<Void>(
planUnmuteCommand, "commandExec",
messageReceivedEvent, planUnmuteCommand.aliases[0], null
)
}
// Assert
assertEquals("This command requires a user id or mention", illegalArgumentException.message)
verify(planUnmuteCommand).aliases
val commandExecInvocations =
mockingDetails(planUnmuteCommand).invocations.filter { it.method.name == "commandExec" }
assertEquals(1, commandExecInvocations.size, "Expected method commandExec to be executed once.")
commandExecInvocations.first().markVerified()
verify(messageReceivedEvent).message
}
@Test
fun `Executing a command with invalid parameters does not start sequence`() {
// Arrange
val messageContent = "!${planUnmuteCommand.aliases[0]} invalid parameters"
clearInvocations(planUnmuteCommand)
whenever(messageReceivedEvent.message).thenReturn(message)
whenever(message.contentRaw).thenReturn(messageContent)
// Act & Assert throws
val illegalArgumentException = assertThrows<IllegalArgumentException> {
ReflectionTestUtils.invokeMethod<Void>(
planUnmuteCommand, "commandExec",
messageReceivedEvent, planUnmuteCommand.aliases[0], null
)
}
// Assert
assertEquals("This command requires a user id or mention", illegalArgumentException.message)
verify(planUnmuteCommand).aliases
val commandExecInvocations =
mockingDetails(planUnmuteCommand).invocations.filter { it.method.name == "commandExec" }
assertEquals(1, commandExecInvocations.size, "Expected method commandExec to be executed once.")
commandExecInvocations.first().markVerified()
verify(messageReceivedEvent).message
}
}
| apache-2.0 | f7394bce853d11e4c30b782dd50ffad1 | 36.95283 | 116 | 0.693015 | 5.164313 | false | true | false | false |
android/connectivity-samples | BluetoothAdvertisementsKotlin/app/src/main/java/com/example/bluetoothadvertisements/Constants.kt | 1 | 1427 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.bluetoothadvertisements
import android.Manifest
import android.os.ParcelUuid
const val BT_ADVERTISING_FAILED_EXTRA_CODE = "bt_adv_failure_code"
const val INVALID_CODE = -1
const val ADVERTISING_TIMED_OUT = 6
const val BLE_NOTIFICATION_CHANNEL_ID = "bleChl"
const val FOREGROUND_NOTIFICATION_ID = 3
const val ADVERTISING_FAILED = "com.example.android.bluetoothadvertisements.advertising_failed"
const val REQUEST_ENABLE_BT = 11
const val PERMISSION_REQUEST_LOCATION = 101
/**
* Saving the permission type here, under a shorter name, makes calling the permission type
* from multiple sites more efficient
*/
const val LOCATION_FINE_PERM = Manifest.permission.ACCESS_FINE_LOCATION
val ScanFilterService_UUID: ParcelUuid = ParcelUuid.fromString("0000b81d-0000-1000-8000-00805f9b34fb")
| apache-2.0 | 1c621b903c26ee977ba312561d74251d | 39.771429 | 102 | 0.775053 | 3.856757 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/jetpack/common/JetpackListItemState.kt | 1 | 2621 | package org.wordpress.android.ui.jetpack.common
import android.view.View
import androidx.annotation.AttrRes
import androidx.annotation.ColorRes
import androidx.annotation.DimenRes
import androidx.annotation.DrawableRes
import org.wordpress.android.R
import org.wordpress.android.ui.jetpack.common.providers.JetpackAvailableItemsProvider.JetpackAvailableItemType
import org.wordpress.android.ui.utils.UiString
open class JetpackListItemState(open val type: ViewType) {
open fun longId(): Long = hashCode().toLong()
data class IconState(
@DrawableRes val icon: Int,
@ColorRes val colorResId: Int? = null,
@DimenRes val sizeResId: Int = R.dimen.jetpack_icon_size,
@DimenRes val marginResId: Int = R.dimen.jetpack_icon_margin,
val contentDescription: UiString
) : JetpackListItemState(ViewType.ICON)
data class HeaderState(val text: UiString, @AttrRes val textColorRes: Int = R.attr.colorOnSurface) :
JetpackListItemState(ViewType.HEADER)
data class DescriptionState(
val text: UiString?,
val clickableTextsInfo: List<ClickableTextInfo>? = null
) : JetpackListItemState(ViewType.DESCRIPTION) {
data class ClickableTextInfo(
val startIndex: Int,
val endIndex: Int,
val onClick: () -> Unit
)
}
data class ActionButtonState(
val text: UiString,
val contentDescription: UiString,
val isSecondary: Boolean = false,
val isEnabled: Boolean = true,
val isVisible: Boolean = true,
@DrawableRes val iconRes: Int? = null,
val onClick: () -> Unit
) : JetpackListItemState(if (isSecondary) ViewType.SECONDARY_ACTION_BUTTON else ViewType.PRIMARY_ACTION_BUTTON)
data class CheckboxState(
val availableItemType: JetpackAvailableItemType,
val label: UiString,
val labelSpannable: CharSequence? = null,
val checked: Boolean = false,
val isEnabled: Boolean = true,
val onClick: (() -> Unit)
) : JetpackListItemState(ViewType.CHECKBOX)
data class ProgressState(
val progress: Int = 0,
val progressLabel: UiString? = null,
val progressStateLabel: UiString? = null,
val progressInfoLabel: UiString? = null,
val isIndeterminate: Boolean = false,
val isVisible: Boolean = true
) : JetpackListItemState(ViewType.PROGRESS) {
val progressStateLabelTextAlignment = if (progressLabel == null) {
View.TEXT_ALIGNMENT_TEXT_START
} else {
View.TEXT_ALIGNMENT_TEXT_END
}
}
}
| gpl-2.0 | 51bb381b146aaa57dec824ed3901c690 | 36.442857 | 115 | 0.67913 | 4.672014 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/insights/usecases/MostPopularInsightsUseCase.kt | 1 | 6723 | package org.wordpress.android.ui.stats.refresh.lists.sections.insights.usecases
import android.view.View
import kotlinx.coroutines.CoroutineDispatcher
import org.wordpress.android.BuildConfig
import org.wordpress.android.R
import org.wordpress.android.fluxc.model.post.PostStatus
import org.wordpress.android.fluxc.model.stats.InsightsMostPopularModel
import org.wordpress.android.fluxc.store.PostStore
import org.wordpress.android.fluxc.store.StatsStore.InsightType
import org.wordpress.android.fluxc.store.StatsStore.InsightType.MOST_POPULAR_DAY_AND_HOUR
import org.wordpress.android.fluxc.store.stats.insights.MostPopularInsightsStore
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.modules.UI_THREAD
import org.wordpress.android.ui.stats.refresh.lists.sections.BaseStatsUseCase.StatelessUseCase
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Empty
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.QuickScanItem
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.QuickScanItem.Column
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Title
import org.wordpress.android.ui.stats.refresh.utils.ActionCardHandler
import org.wordpress.android.ui.stats.refresh.utils.ItemPopupMenuHandler
import org.wordpress.android.ui.stats.refresh.utils.StatsDateUtils
import org.wordpress.android.ui.stats.refresh.utils.StatsSiteProvider
import org.wordpress.android.util.text.PercentFormatter
import org.wordpress.android.viewmodel.ResourceProvider
import java.math.RoundingMode
import javax.inject.Inject
import javax.inject.Named
import kotlin.math.roundToInt
class MostPopularInsightsUseCase
@Inject constructor(
@Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher,
@Named(BG_THREAD) private val backgroundDispatcher: CoroutineDispatcher,
private val mostPopularStore: MostPopularInsightsStore,
private val postStore: PostStore,
private val statsSiteProvider: StatsSiteProvider,
private val statsDateUtils: StatsDateUtils,
private val resourceProvider: ResourceProvider,
private val popupMenuHandler: ItemPopupMenuHandler,
private val actionCardHandler: ActionCardHandler,
private val percentFormatter: PercentFormatter
) : StatelessUseCase<InsightsMostPopularModel>(MOST_POPULAR_DAY_AND_HOUR, mainDispatcher, backgroundDispatcher) {
override suspend fun loadCachedData(): InsightsMostPopularModel? {
return mostPopularStore.getMostPopularInsights(statsSiteProvider.siteModel)
}
override suspend fun fetchRemoteData(forced: Boolean): State<InsightsMostPopularModel> {
val response = mostPopularStore.fetchMostPopularInsights(statsSiteProvider.siteModel, forced)
val model = response.model
val error = response.error
return when {
error != null -> State.Error(error.message ?: error.type.name)
model != null -> State.Data(model)
else -> State.Empty()
}
}
override fun buildLoadingItem(): List<BlockListItem> = listOf(Title(R.string.stats_insights_popular))
override fun buildEmptyItem(): List<BlockListItem> {
return listOf(buildTitle(), Empty())
}
override fun buildUiModel(domainModel: InsightsMostPopularModel): List<BlockListItem> {
val items = mutableListOf<BlockListItem>()
items.add(buildTitle())
val noActivity = domainModel.highestDayPercent == 0.0 && domainModel.highestHourPercent == 0.0
if (BuildConfig.IS_JETPACK_APP && noActivity) {
items.add(Empty(R.string.stats_most_popular_percent_views_empty))
} else {
val highestDayPercent = resourceProvider.getString(
R.string.stats_most_popular_percent_views,
percentFormatter.format(
value = domainModel.highestDayPercent.roundToInt(),
rounding = RoundingMode.HALF_UP
)
)
val highestHourPercent = resourceProvider.getString(
R.string.stats_most_popular_percent_views,
percentFormatter.format(
value = domainModel.highestHourPercent.roundToInt(),
rounding = RoundingMode.HALF_UP
)
)
items.add(
QuickScanItem(
Column(
R.string.stats_insights_best_day,
statsDateUtils.getWeekDay(domainModel.highestDayOfWeek),
if (BuildConfig.IS_JETPACK_APP) {
highestDayPercent
} else {
null
},
highestDayPercent
),
Column(
R.string.stats_insights_best_hour,
statsDateUtils.getHour(domainModel.highestHour),
if (BuildConfig.IS_JETPACK_APP) {
highestHourPercent
} else {
null
},
highestHourPercent
)
)
)
}
if (BuildConfig.IS_JETPACK_APP) {
addActionCards(domainModel)
}
return items
}
private fun addActionCards(domainModel: InsightsMostPopularModel) {
val popular = domainModel.highestDayOfWeek > 0 || domainModel.highestHour > 0
if (popular) actionCardHandler.display(InsightType.ACTION_REMINDER)
val drafts = postStore.getPostsForSite(statsSiteProvider.siteModel).firstOrNull {
PostStatus.fromPost(it) == PostStatus.DRAFT
}
if (drafts != null) actionCardHandler.display(InsightType.ACTION_SCHEDULE)
}
private fun buildTitle() = Title(
textResource = if (BuildConfig.IS_JETPACK_APP) {
R.string.stats_insights_popular_title
} else {
R.string.stats_insights_popular
},
menuAction = if (BuildConfig.IS_JETPACK_APP) {
null
} else {
this::onMenuClick
})
private fun onMenuClick(view: View) {
popupMenuHandler.onMenuClick(view, type)
}
}
| gpl-2.0 | 65eb9963aceb6ce215aea2a952417770 | 44.425676 | 113 | 0.639149 | 5.032186 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/posts/PostListMainViewState.kt | 1 | 2315 | package org.wordpress.android.ui.posts
import androidx.annotation.DrawableRes
import org.wordpress.android.R
import org.wordpress.android.ui.posts.AuthorFilterSelection.EVERYONE
import org.wordpress.android.ui.posts.AuthorFilterSelection.ME
import org.wordpress.android.ui.utils.UiString
import org.wordpress.android.ui.utils.UiString.UiStringRes
data class PostListMainViewState(
val isFabVisible: Boolean,
val isAuthorFilterVisible: Boolean,
val authorFilterSelection: AuthorFilterSelection,
val authorFilterItems: List<AuthorFilterListItemUIState>
)
sealed class PostListViewLayoutTypeMenuUiState(@DrawableRes val iconRes: Int, val title: UiString) {
object StandardViewLayoutTypeMenuUiState : PostListViewLayoutTypeMenuUiState(
iconRes = R.drawable.ic_view_post_compact_white_24dp,
title = UiStringRes(R.string.post_list_toggle_item_layout_list_view)
)
object CompactViewLayoutTypeMenuUiState : PostListViewLayoutTypeMenuUiState(
iconRes = R.drawable.ic_view_post_full_white_24dp,
title = UiStringRes(R.string.post_list_toggle_item_layout_cards_view)
)
}
sealed class AuthorFilterListItemUIState(
val id: Long,
val text: UiString,
open val isSelected: Boolean
) {
data class Everyone(override val isSelected: Boolean, @DrawableRes val imageRes: Int) :
AuthorFilterListItemUIState(
id = EVERYONE.id,
text = UiStringRes(R.string.everyone),
isSelected = isSelected
)
data class Me(val avatarUrl: String?, override val isSelected: Boolean) :
AuthorFilterListItemUIState(
id = ME.id,
text = UiStringRes(R.string.me),
isSelected = isSelected
)
}
fun getAuthorFilterItems(
selection: AuthorFilterSelection,
avatarUrl: String?
): List<AuthorFilterListItemUIState> {
return AuthorFilterSelection.values().map { value ->
when (value) {
ME -> AuthorFilterListItemUIState.Me(avatarUrl, selection == value)
EVERYONE -> AuthorFilterListItemUIState.Everyone(
selection == value,
R.drawable.bg_oval_neutral_30_multiple_users_white_40dp
)
}
}
}
| gpl-2.0 | 1d42b3ae974e6da12a644fd2d469112f | 36.33871 | 100 | 0.684233 | 4.539216 | false | false | false | false |
ingokegel/intellij-community | plugins/markdown/test/src/org/intellij/plugins/markdown/reference/MissingExtensionFileLinkDestinationReferenceTest.kt | 7 | 2463 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.reference
import org.intellij.plugins.markdown.MarkdownTestingUtil
import java.nio.file.Path
class MissingExtensionFileLinkDestinationReferenceTest : BaseLinkDestinationReferenceTestCase() {
override fun getTestDataPath() = Path.of(MarkdownTestingUtil.TEST_DATA_PATH, "reference", "linkDestination",
"missingExtension").toString()
override fun getLinksFilePath(): String = Path.of("topDir", "links.md").toString()
fun testNear() = testIsReferenceToFile("topDir", "stub_in_top_dir.md")
fun testBelow() = testIsReferenceToFile("topDir", "innerDir", "stub_in_inner_dir.md")
fun testAbove() = testIsReferenceToFile("stub_in_root.md")
fun testRepeatedExtension() = testIsReferenceToFile("topDir", "stub_with_repeated_extension.md.md")
fun testWithHeader() = testIsReferenceToFile("topDir", "stub_in_top_dir.md")
fun testWithNonexistentHeader() = testIsReferenceToFile("topDir", "stub_in_top_dir.md")
fun testIsNotReferenceBecauseOfWrongPathPrefix() = testIsNotReferenceToFile("topDir", "stub_in_top_dir.md")
fun testIsNotReferenceBecauseResolvingIsRelative() = testIsNotReferenceToFile("stub_in_root.md")
fun testIsNotReferenceBecauseOfFullMatchWithOtherFile() = testIsNotReferenceToFile("topDir", "stub_in_top_dir.md.md")
fun testIsNotReferenceToFileBecauseCaretIsAtHeader() = testIsNotReferenceToFile("topDir", "stub_in_top_dir.md")
fun testIsNotReferenceToFileBecauseCaretIsAtNonexistentHeader() = testIsNotReferenceToFile("topDir", "stub_in_top_dir.md")
fun testRenameWithoutExtension() = testRenameFile(Path.of("stub_in_root.md"), "renamed.md")
fun testRenameRepeatedExtension() = testRenameFile(Path.of("topDir", "stub_with_repeated_extension.md.md"), "renamed.md.md")
fun testRenameExtensionRemoval() = testRenameFile(Path.of("stub_in_root.md"), "renamed")
// TODO: move this test to CommonLinkDestinationReferenceTest, since it is a common renaming behavior
fun testRenameExtensionIntroduction() = testRenameFile(Path.of("stub_without_extension"), "renamed.md")
fun testRenameDirectory() = testRenameFile(Path.of("topDir", "innerDir"), "renamed")
fun testRenameNotRenamedBecauseOfFullMatchWithOtherFile() = testRenameFile(Path.of("topDir", "stub_in_top_dir.md.md"), "renamed")
} | apache-2.0 | d787c17ed0a7fa77a3bc2b066a7da8fd | 51.425532 | 140 | 0.764515 | 4.037705 | false | true | false | false |
hermantai/samples | kotlin/kotlin-and-android-development-featuring-jetpack/chapter-7/app/src/main/java/dev/mfazio/pennydrop/types/NewPlayer.kt | 5 | 1179 | package dev.mfazio.pennydrop.types
import androidx.databinding.ObservableBoolean
import dev.mfazio.pennydrop.game.AI
data class NewPlayer(
var playerName: String = "",
val isHuman: ObservableBoolean = ObservableBoolean(true),
val canBeRemoved: Boolean = true,
val canBeToggled: Boolean = true,
var isIncluded: ObservableBoolean = ObservableBoolean(!canBeRemoved),
var selectedAIPosition: Int = -1
) {
fun selectedAI() = if (!isHuman.get()) {
AI.basicAI.getOrNull(selectedAIPosition)
} else {
null
}
fun toPlayer() = Player(
playerName = if (this.isHuman.get()) this.playerName else (this.selectedAI()?.name ?: "AI"),
isHuman = this.isHuman.get(),
selectedAI = this.selectedAI()
)
override fun toString() = listOf(
"name" to this.playerName,
"isIncluded" to this.isIncluded.get(),
"isHuman" to this.isHuman.get(),
"canBeRemoved" to this.canBeRemoved,
"canBeToggled" to this.canBeToggled,
"selectedAI" to (this.selectedAI()?.name ?: "N/A")
).joinToString(", ", "NewPlayer(", ")") { (property, value) ->
"$property=$value"
}
} | apache-2.0 | 847a0aebe66630e477dc62c1e8d508b4 | 31.777778 | 100 | 0.639525 | 4.151408 | false | false | false | false |
android/play-billing-samples | PlayBillingCodelab/finished/src/main/java/com/sample/subscriptionscodelab/ui/composable/Composables.kt | 1 | 10356 | /*
* Copyright 2022 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
*
* 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.sample.subscriptionscodelab.ui.composable
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import com.sample.subscriptionscodelab.Constants
import com.sample.subscriptionscodelab.Constants.BASIC_BASE_PLANS_ROUTE
import com.sample.subscriptionscodelab.Constants.MONTHLY_BASIC_PLANS_TAG
import com.sample.subscriptionscodelab.Constants.MONTHLY_PREMIUM_PLANS_TAG
import com.sample.subscriptionscodelab.Constants.PREMIUM_BASE_PLANS_ROUTE
import com.sample.subscriptionscodelab.Constants.PREPAID_BASIC_PLANS_TAG
import com.sample.subscriptionscodelab.Constants.PREPAID_PREMIUM_PLANS_TAG
import com.sample.subscriptionscodelab.Constants.SUBSCRIPTION_ROUTE
import com.sample.subscriptionscodelab.Constants.YEARLY_BASIC_PLANS_TAG
import com.sample.subscriptionscodelab.Constants.YEARLY_PREMIUM_PLANS_TAG
import com.sample.subscriptionscodelab.R
import com.sample.subscriptionscodelab.ui.ButtonModel
import com.sample.subscriptionscodelab.ui.MainState
import com.sample.subscriptionscodelab.ui.MainViewModel
@Composable
fun SubscriptionNavigationComponent(
productsForSale: MainState,
navController: NavHostController,
viewModel: MainViewModel
) {
NavHost(
navController = navController,
startDestination = stringResource(id = R.string.subscription_composable_name)
) {
composable(route = SUBSCRIPTION_ROUTE) {
Subscription(
navController = navController,
)
}
composable(route = BASIC_BASE_PLANS_ROUTE) {
BasicBasePlans(
productsForSale = productsForSale,
viewModel = viewModel
)
}
composable(route = PREMIUM_BASE_PLANS_ROUTE) {
PremiumBasePlans(
productsForSale = productsForSale,
viewModel = viewModel
)
}
}
}
@Composable
private fun Subscription(
navController: NavHostController,
) {
CenteredSurfaceColumn {
val buttonModels = remember(navController) {
listOf(
ButtonModel(R.string.basic_sub_text) {
navController.navigate(route = BASIC_BASE_PLANS_ROUTE)
},
ButtonModel(R.string.premium_sub_text) {
navController.navigate(route = PREMIUM_BASE_PLANS_ROUTE)
}
)
}
ButtonGroup(buttonModels = buttonModels)
}
}
@Composable
private fun BasicBasePlans(
productsForSale: MainState,
viewModel: MainViewModel,
) {
val context = LocalContext.current
val activity = context.findActivity()
CenteredSurfaceColumn {
val buttonModels = remember(productsForSale, viewModel, activity) {
listOf(
ButtonModel(R.string.monthly_basic_sub_text) {
productsForSale.basicProductDetails?.let {
viewModel.buy(
productDetails = it,
currentPurchases = null,
tag = MONTHLY_BASIC_PLANS_TAG,
activity = activity
)
}
},
ButtonModel(R.string.yearly_sub_text) {
productsForSale.basicProductDetails?.let {
viewModel.buy(
productDetails = it,
currentPurchases = null,
tag = YEARLY_BASIC_PLANS_TAG,
activity = activity
)
}
},
ButtonModel(R.string.prepaid_basic_sub_text) {
productsForSale.basicProductDetails?.let {
viewModel.buy(
productDetails = it,
currentPurchases = null,
tag = Constants.PREPAID_BASIC_PLANS_TAG,
activity = activity
)
}
}
)
}
ButtonGroup(buttonModels = buttonModels)
}
}
@Composable
private fun PremiumBasePlans(
productsForSale: MainState,
viewModel: MainViewModel,
) {
val context = LocalContext.current
val activity = context.findActivity()
CenteredSurfaceColumn {
val buttonModels = remember(productsForSale, viewModel, activity) {
listOf(
ButtonModel(R.string.monthly_premium_sub_text) {
productsForSale.premiumProductDetails?.let {
viewModel.buy(
productDetails = it,
currentPurchases = null,
tag = MONTHLY_PREMIUM_PLANS_TAG,
activity = activity
)
}
},
ButtonModel(R.string.yearly_premium_sub_text) {
productsForSale.premiumProductDetails?.let {
viewModel.buy(
productDetails = it,
currentPurchases = null,
tag = YEARLY_PREMIUM_PLANS_TAG,
activity = activity
)
}
},
ButtonModel(R.string.prepaid_premium_sub_text) {
productsForSale.premiumProductDetails?.let {
viewModel.buy(
productDetails = it,
currentPurchases = null,
tag = PREPAID_PREMIUM_PLANS_TAG,
activity = activity
)
}
}
)
}
ButtonGroup(buttonModels = buttonModels)
}
}
@Composable
fun UserProfile(
buttonModels: List<ButtonModel>,
tag: String?,
profileTextStringResource: Int?
) {
CenteredSurfaceColumn {
if (tag.isNullOrEmpty()) {
CenteredSurfaceColumn {
profileTextStringResource?.let { stringResource(id = it) }
?.let { ProfileText(text = it) }
ButtonGroup(
buttonModels = buttonModels
)
}
} else {
CenteredSurfaceColumn {
when (tag) {
PREPAID_BASIC_PLANS_TAG -> ProfileText(
text = stringResource(id = R.string.basic_prepaid_sub_message)
)
PREPAID_PREMIUM_PLANS_TAG -> ProfileText(
text = stringResource(id = R.string.premium_prepaid_sub_message)
)
}
Spacer(modifier = Modifier.height(dimensionResource(id = R.dimen.spacer_height)))
ButtonGroup(buttonModels = buttonModels)
}
}
}
}
@Composable
private fun ButtonGroup(
buttonModels: List<ButtonModel>,
) {
CenteredSurfaceColumn {
for (buttonModel in buttonModels) {
Button(
modifier = Modifier.size(
width = dimensionResource(id = R.dimen.ui_button_width),
height = dimensionResource(R.dimen.ui_button_height)
),
onClick = buttonModel.onClick
) {
Text(text = stringResource(buttonModel.stringResource))
}
Spacer(modifier = Modifier.height(dimensionResource(id = R.dimen.spacer_height)))
}
}
}
@Composable
fun LoadingScreen() {
CenteredSurfaceColumn {
Text(
text = stringResource(id = R.string.loading_message),
style = MaterialTheme.typography.h1,
textAlign = TextAlign.Center
)
}
}
@Composable
private fun ProfileText(text: String) {
Text(
text = text,
style = MaterialTheme.typography.h3,
textAlign = TextAlign.Center
)
}
@Composable
fun CenteredSurfaceColumn(
content: @Composable ColumnScope.() -> Unit
) {
Surface {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
content()
}
}
}
/**
* Find the closest Activity in a given Context.
*/
internal fun Context.findActivity(): Activity {
var context = this
while (context is ContextWrapper) {
if (context is Activity) return context
context = context.baseContext
}
throw IllegalStateException(getString(R.string.context_finder_error))
}
| apache-2.0 | f9ef30ae92bb11261702bdeaafaac8a7 | 33.751678 | 97 | 0.592507 | 4.966906 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.