repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bozaro/git-lfs-java | gitlfs-common/src/main/kotlin/ru/bozaro/gitlfs/common/data/VerifyLocksRes.kt | 1 | 560 | package ru.bozaro.gitlfs.common.data
import com.fasterxml.jackson.annotation.JsonProperty
class VerifyLocksRes(
@field:JsonProperty(value = "ours", required = true)
@param:JsonProperty(value = "ours", required = true)
val ours: List<Lock>,
@field:JsonProperty(value = "theirs", required = true)
@param:JsonProperty(value = "theirs", required = true)
val theirs: List<Lock>,
@field:JsonProperty(value = "next_cursor")
@param:JsonProperty(value = "next_cursor")
val nextCursor: String?
)
| lgpl-3.0 | 8729b9c2de12f7d618f82421c8ae036a | 36.333333 | 62 | 0.657143 | 3.971631 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/llvm/src/templates/kotlin/llvm/templates/LLVMSupport.kt | 4 | 1702 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package llvm.templates
import llvm.*
import org.lwjgl.generator.*
val LLVMSupport = "LLVMSupport".nativeClass(
Module.LLVM,
prefixConstant = "LLVM",
prefixMethod = "LLVM",
binding = LLVM_BINDING_DELEGATE
) {
documentation = ""
LLVMBool(
"LoadLibraryPermanently",
"This function permanently loads the dynamic library at the given path. It is safe to call this function multiple times for the same library.",
charUTF8.const.p("Filename", "")
)
void(
"ParseCommandLineOptions",
"""
This function parses the given arguments using the LLVM command line parser.
Note that the only stable thing about this function is its signature; you cannot rely on any particular set of command line arguments being interpreted
the same way across LLVM versions.
""",
AutoSize("argv")..int("argc", ""),
charUTF8.const.p.const.p("argv", ""),
charUTF8.const.p("Overview", "")
)
opaque_p(
"SearchForAddressOfSymbol",
"""
This function will search through all previously loaded dynamic libraries for the symbol {@code symbolName}. If it is found, the address of that symbol
is returned. If not, null is returned.
""",
charUTF8.const.p("symbolName", "")
)
void(
"AddSymbol",
"This functions permanently adds the symbol {@code symbolName} with the value {@code symbolValue}. These symbols are searched before any libraries.",
charUTF8.const.p("symbolName", ""),
opaque_p("symbolValue", "")
)
} | bsd-3-clause | b48b41b71ba668d014d67829af11fa43 | 29.410714 | 159 | 0.643948 | 4.650273 | false | false | false | false |
mdanielwork/intellij-community | platform/vcs-log/impl/test/com/intellij/vcs/log/history/FileHistoryTest.kt | 1 | 9329 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.log.history
import com.intellij.openapi.util.Couple
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.LocalFilePath
import com.intellij.util.containers.MultiMap
import com.intellij.vcs.log.data.index.VcsLogPathsIndex
import com.intellij.vcs.log.data.index.VcsLogPathsIndex.ChangeKind.*
import com.intellij.vcs.log.graph.TestGraphBuilder
import com.intellij.vcs.log.graph.TestPermanentGraphInfo
import com.intellij.vcs.log.graph.api.LinearGraph
import com.intellij.vcs.log.graph.asTestGraphString
import com.intellij.vcs.log.graph.graph
import com.intellij.vcs.log.graph.impl.facade.BaseController
import com.intellij.vcs.log.graph.impl.facade.FilteredController
import gnu.trove.THashMap
import gnu.trove.TIntObjectHashMap
import org.junit.Assert
import org.junit.Assume.assumeFalse
import org.junit.Test
class FileHistoryTest {
fun LinearGraph.assert(startCommit: Int, startPath: FilePath, fileNamesData: FileNamesData, result: TestGraphBuilder.() -> Unit) {
val permanentGraphInfo = TestPermanentGraphInfo(this)
val baseController = BaseController(permanentGraphInfo)
val filteredController = object : FilteredController(baseController, permanentGraphInfo, fileNamesData.getCommits()) {}
val historyBuilder = FileHistoryBuilder(startCommit, startPath, fileNamesData)
historyBuilder.accept(filteredController, permanentGraphInfo)
val expectedResultGraph = graph(result)
val actualResultGraph = filteredController.collapsedGraph.compiledGraph
Assert.assertEquals(expectedResultGraph.asTestGraphString(true), actualResultGraph.asTestGraphString(true))
}
@Test
fun linearHistory() {
val path = LocalFilePath("file.txt", false)
val fileNamesData = FileNamesDataBuilder(path)
.addChange(path, 7, listOf(ADDED), listOf(7))
.addChange(path, 6, listOf(MODIFIED), listOf(7))
.addChange(path, 4, listOf(MODIFIED), listOf(5))
.addChange(path, 2, listOf(REMOVED), listOf(3))
.addChange(path, 0, listOf(ADDED), listOf(1))
.build()
graph {
0(1)
1(2)
2(3)
3(4)
4(5)
5(6)
6(7)
7()
}.assert(0, path, fileNamesData) {
0(2.dot)
2(4.dot)
4(6.dot)
6(7)
7()
}
}
@Test
fun historyWithRename() {
val afterPath = LocalFilePath("after.txt", false)
val beforePath = LocalFilePath("before.txt", false)
val fileNamesData = FileNamesDataBuilder(afterPath)
.addChange(beforePath, 6, listOf(ADDED), listOf(7))
.addChange(beforePath, 4, listOf(REMOVED), listOf(5))
.addChange(afterPath, 4, listOf(ADDED), listOf(5))
.addRename(5, 4, beforePath, afterPath)
.addChange(afterPath, 2, listOf(MODIFIED), listOf(3))
.build()
graph {
0(1)
1(2)
2(3)
3(4)
4(5)
5(6)
6(7)
7()
}.assert(0, afterPath, fileNamesData) {
2(4.dot)
4(6.dot)
6()
}
}
@Test
fun historyForDeleted() {
val path = LocalFilePath("file.txt", false)
val fileNamesData = FileNamesDataBuilder(path)
.addChange(path, 7, listOf(ADDED), listOf(7))
.addChange(path, 4, listOf(MODIFIED), listOf(5))
.addChange(path, 2, listOf(REMOVED), listOf(3))
.build()
val graph = graph {
0(1)
1(2)
2(3)
3(4)
4(5)
5(6)
6(7)
7()
}
graph.assert(0, path, fileNamesData) {
2(4.dot)
4(7.dot)
7()
}
graph.assert(4, path, fileNamesData) {
2(4.dot)
4(7.dot)
7()
}
}
@Test
fun historyWithMerges() {
val path = LocalFilePath("file.txt", false)
val fileNamesData = FileNamesDataBuilder(path)
.addChange(path, 7, listOf(ADDED), listOf(7))
.addChange(path, 6, listOf(MODIFIED), listOf(7))
.addChange(path, 4, listOf(NOT_CHANGED, MODIFIED), listOf(6, 5))
.addChange(path, 3, listOf(MODIFIED), listOf(6))
.addChange(path, 2, listOf(MODIFIED), listOf(4))
.addChange(path, 1, listOf(MODIFIED, MODIFIED), listOf(3, 2))
.addChange(path, 0, listOf(MODIFIED), listOf(1))
.build()
graph {
0(1)
1(2, 3)
2(4)
3(6)
4(6, 5)
5(7)
6(7)
7()
}.assert(0, path, fileNamesData) {
0(1)
1(3, 2)
2(6.dot)
3(6)
6(7)
7()
}
}
/**
* Rename happens in one branch, while the other branch only consists of couple of trivial merge commits.
*/
@Test
fun historyWithUndetectedRename() {
val after = LocalFilePath("after.txt", false)
val before = LocalFilePath("before.txt", false)
val fileNamesData = FileNamesDataBuilder(after)
.addChange(before, 7, listOf(ADDED), listOf(7))
.addChange(before, 6, listOf(MODIFIED), listOf(7))
.addChange(before, 5, listOf(MODIFIED), listOf(6))
.addChange(before, 4, listOf(REMOVED), listOf(5))
.addChange(after, 4, listOf(ADDED), listOf(5))
.addRename(5, 4, before, after)
.addChange(after, 3, listOf(MODIFIED), listOf(4))
.addChange(before, 2, listOf(MODIFIED, NOT_CHANGED), listOf(6, 5))
.addChange(before, 1, listOf(REMOVED, NOT_CHANGED), listOf(2, 3))
.addChange(after, 1, listOf(ADDED, NOT_CHANGED), listOf(2, 3))
// rename is not detected at merge commit 1
.addChange(after, 0, listOf(MODIFIED), listOf(1))
.build()
graph {
0(1)
1(2, 3)
2(6, 5)
3(4)
4(5)
5(6)
6(7)
7()
}.assert(0, after, fileNamesData) {
0(3.dot)
3(4)
4(5)
5(6)
6(7)
7()
}
}
@Test
fun historyWithCyclicRenames() {
val aFile = LocalFilePath("a.txt", false)
val bFile = LocalFilePath("b.txt", false)
val fileNamesData = FileNamesDataBuilder(aFile)
.addChange(aFile, 4, listOf(ADDED), listOf(4))
.addChange(aFile, 2, listOf(REMOVED), listOf(3))
.addChange(bFile, 2, listOf(ADDED), listOf(3))
.addRename(3, 2, aFile, bFile)
.addChange(bFile, 0, listOf(REMOVED), listOf(1))
.addChange(aFile, 0, listOf(ADDED), listOf(1))
.addRename(1, 0, bFile, aFile)
.build()
graph {
0(1)
1(2)
2(3)
3(4)
4()
}.assert(0, aFile, fileNamesData) {
0(2.dot)
2(4.dot)
4()
}
}
@Test
fun historyWithCyclicCaseOnlyRenames() {
assumeFalse("Case insensitive fs is required", SystemInfo.isFileSystemCaseSensitive)
val lowercasePath = LocalFilePath("file.txt", false)
val uppercasePath = LocalFilePath("FILE.TXT", false)
val mixedPath = LocalFilePath("FiLe.TxT", false)
val fileNamesData = FileNamesDataBuilder(lowercasePath)
.addChange(lowercasePath, 7, listOf(ADDED), listOf(7))
.addChange(lowercasePath, 6, listOf(MODIFIED), listOf(7))
.addChange(lowercasePath, 5, listOf(REMOVED), listOf(6))
.addChange(mixedPath, 5, listOf(ADDED), listOf(6))
.addRename(6, 5, lowercasePath, mixedPath)
.addChange(mixedPath, 4, listOf(MODIFIED), listOf(5))
.addChange(mixedPath, 3, listOf(REMOVED), listOf(4))
.addChange(uppercasePath, 3, listOf(ADDED), listOf(4))
.addRename(4, 3, mixedPath, uppercasePath)
.addChange(uppercasePath, 2, listOf(MODIFIED), listOf(3))
.addChange(uppercasePath, 1, listOf(REMOVED), listOf(2))
.addChange(lowercasePath, 1, listOf(ADDED), listOf(2))
.addRename(2, 1, uppercasePath, lowercasePath)
.build()
graph {
0(1)
1(2)
2(3)
3(4)
4(5)
5(6)
6(7)
7()
}.assert(0, lowercasePath, fileNamesData) {
1(2)
2(3)
3(4)
4(5)
5(6)
6(7)
7()
}
}
}
private class FileNamesDataBuilder(private val path: FilePath) {
private val commitsMap: MutableMap<FilePath, TIntObjectHashMap<TIntObjectHashMap<VcsLogPathsIndex.ChangeKind>>> =
THashMap(FILE_PATH_HASHING_STRATEGY)
private val renamesMap: MultiMap<Couple<Int>, Couple<FilePath>> = MultiMap.createSmart()
fun addRename(parent: Int, child: Int, beforePath: FilePath, afterPath: FilePath): FileNamesDataBuilder {
renamesMap.putValue(Couple(parent, child), Couple(beforePath, afterPath))
return this
}
fun addChange(path: FilePath, commit: Int, changes: List<VcsLogPathsIndex.ChangeKind>, parents: List<Int>): FileNamesDataBuilder {
commitsMap.getOrPut(path) { TIntObjectHashMap() }.put(commit, parents.zip(changes).toIntObjectMap())
return this
}
fun build(): FileNamesData {
return object : FileNamesData(path) {
override fun findRename(parent: Int, child: Int, accept: (Couple<FilePath>) -> Boolean): Couple<FilePath>? {
return renamesMap[Couple(parent, child)].find { accept(it) }
}
override fun getAffectedCommits(path: FilePath): TIntObjectHashMap<TIntObjectHashMap<VcsLogPathsIndex.ChangeKind>> {
return commitsMap[path] ?: TIntObjectHashMap()
}
}
}
}
private fun <T> List<Pair<Int, T>>.toIntObjectMap(): TIntObjectHashMap<T> {
val result = TIntObjectHashMap<T>()
this.forEach { result.put(it.first, it.second) }
return result
} | apache-2.0 | 712eee23e7770d3694c5dec95d3abfdc | 28.713376 | 140 | 0.644656 | 3.687352 | false | true | false | false |
android/project-replicator | model/src/test/kotlin/com/android/gradle/replicator/model/internal/fixtures/ProjectBuilder.kt | 1 | 1751 | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.gradle.replicator.model.internal.fixtures
import com.android.gradle.replicator.model.ProjectInfo
import com.android.gradle.replicator.model.internal.DefaultProjectInfo
class ProjectBuilder {
var gradleVersion: String = ""
var agpVersion: String = ""
var kotlinVersion: String = ""
var rootModule: ModuleBuilder = ModuleBuilder(path = ":")
val subModules: MutableList<ModuleBuilder> = mutableListOf()
var properties: MutableList<String> = mutableListOf()
fun rootModule(action: ModuleBuilder.() -> Unit) {
action(rootModule)
}
fun subModule(action: ModuleBuilder.() -> Unit) {
val newModule = ModuleBuilder()
action(newModule)
subModules.add(newModule)
}
fun toInfo(): ProjectInfo =
DefaultProjectInfo(
gradleVersion = gradleVersion,
agpVersion = agpVersion,
kotlinVersion = kotlinVersion,
rootModule = rootModule.toInfo(),
subModules = subModules.map(ModuleBuilder::toInfo),
gradleProperties = properties
)
} | apache-2.0 | ea2078e7109e459efc3eaed49bdbbaba | 34.04 | 75 | 0.681325 | 4.918539 | false | false | false | false |
dahlstrom-g/intellij-community | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/ModifiableContentEntryBridge.kt | 3 | 10905 | // 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.ide.impl.legacyBridge.module.roots
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.roots.ContentEntry
import com.intellij.openapi.roots.ExcludeFolder
import com.intellij.openapi.roots.ModuleRootModel
import com.intellij.openapi.roots.SourceFolder
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.util.CachedValueProvider
import com.intellij.util.CachedValueImpl
import com.intellij.workspaceModel.ide.getInstance
import com.intellij.workspaceModel.ide.impl.toVirtualFileUrl
import com.intellij.workspaceModel.ide.isEqualOrParentOf
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.addSourceRootEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.ContentRootEntity
import com.intellij.workspaceModel.storage.bridgeEntities.asJavaResourceRoot
import com.intellij.workspaceModel.storage.bridgeEntities.asJavaSourceRoot
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.jps.model.JpsElement
import org.jetbrains.jps.model.java.JavaResourceRootProperties
import org.jetbrains.jps.model.java.JavaSourceRootProperties
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.jps.model.serialization.module.JpsModuleSourceRootPropertiesSerializer
internal class ModifiableContentEntryBridge(
private val diff: MutableEntityStorage,
private val modifiableRootModel: ModifiableRootModelBridgeImpl,
val contentEntryUrl: VirtualFileUrl
) : ContentEntry {
companion object {
private val LOG = logger<ModifiableContentEntryBridge>()
}
private val virtualFileManager = VirtualFileUrlManager.getInstance(modifiableRootModel.project)
private val currentContentEntry = CachedValueImpl {
val contentEntry = modifiableRootModel.currentModel.contentEntries.firstOrNull { it.url == contentEntryUrl.url } as? ContentEntryBridge
?: error("Unable to find content entry in parent modifiable root model by url: $contentEntryUrl")
CachedValueProvider.Result.createSingleDependency(contentEntry, modifiableRootModel)
}
private fun <P : JpsElement> addSourceFolder(sourceFolderUrl: VirtualFileUrl, type: JpsModuleSourceRootType<P>, properties: P): SourceFolder {
if (!contentEntryUrl.isEqualOrParentOf(sourceFolderUrl)) {
error("Source folder $sourceFolderUrl must be under content entry $contentEntryUrl")
}
val duplicate = findDuplicate(sourceFolderUrl, type, properties)
if (duplicate != null) {
LOG.debug("Source folder for '$sourceFolderUrl' and type '$type' already exist")
return duplicate
}
val serializer: JpsModuleSourceRootPropertiesSerializer<P> = SourceRootPropertiesHelper.findSerializer(type)
?: error("Module source root type $type is not registered as JpsModelSerializerExtension")
val contentRootEntity = currentContentEntry.value.entity
val entitySource = contentRootEntity.entitySource
val sourceRootEntity = diff.addSourceRootEntity(
contentRoot = contentRootEntity,
url = sourceFolderUrl,
rootType = serializer.typeId,
source = entitySource
)
SourceRootPropertiesHelper.addPropertiesEntity(diff, sourceRootEntity, properties, serializer)
return currentContentEntry.value.sourceFolders.firstOrNull {
it.url == sourceFolderUrl.url && it.rootType == type
} ?: error("Source folder for '$sourceFolderUrl' and type '$type' was not found after adding")
}
private fun <P : JpsElement?> findDuplicate(sourceFolderUrl: VirtualFileUrl, type: JpsModuleSourceRootType<P>,
properties: P): SourceFolder? {
val propertiesFilter: (SourceFolder) -> Boolean = when (properties) {
is JavaSourceRootProperties -> label@{ sourceFolder: SourceFolder ->
val javaSourceRoot = (sourceFolder as SourceFolderBridge).sourceRootEntity.asJavaSourceRoot()
return@label javaSourceRoot != null && javaSourceRoot.generated == properties.isForGeneratedSources
&& javaSourceRoot.packagePrefix == properties.packagePrefix
}
is JavaResourceRootProperties -> label@{ sourceFolder: SourceFolder ->
val javaResourceRoot = (sourceFolder as SourceFolderBridge).sourceRootEntity.asJavaResourceRoot()
return@label javaResourceRoot != null && javaResourceRoot.generated == properties.isForGeneratedSources
&& javaResourceRoot.relativeOutputPath == properties.relativeOutputPath
}
else -> { _ -> true }
}
return sourceFolders.filter { it.url == sourceFolderUrl.url && it.rootType == type }.find { propertiesFilter.invoke(it) }
}
override fun removeSourceFolder(sourceFolder: SourceFolder) {
val legacyBridgeSourceFolder = sourceFolder as SourceFolderBridge
val sourceRootEntity = currentContentEntry.value.sourceRootEntities.firstOrNull { it == legacyBridgeSourceFolder.sourceRootEntity }
if (sourceRootEntity == null) {
LOG.error("SourceFolder ${sourceFolder.url} is not present under content entry $contentEntryUrl")
return
}
modifiableRootModel.removeCachedJpsRootProperties(sourceRootEntity.url)
diff.removeEntity(sourceRootEntity)
}
override fun clearSourceFolders() {
currentContentEntry.value.sourceRootEntities.forEach { sourceRoot -> diff.removeEntity(sourceRoot) }
}
private fun addExcludeFolder(excludeUrl: VirtualFileUrl): ExcludeFolder {
if (!contentEntryUrl.isEqualOrParentOf(excludeUrl)) {
error("Exclude folder $excludeUrl must be under content entry $contentEntryUrl")
}
if (excludeUrl !in currentContentEntry.value.entity.excludedUrls) {
updateContentEntry {
excludedUrls = excludedUrls + excludeUrl
}
}
return currentContentEntry.value.excludeFolders.firstOrNull {
it.url == excludeUrl.url
} ?: error("Exclude folder $excludeUrl must be present after adding it to content entry $contentEntryUrl")
}
override fun addExcludeFolder(file: VirtualFile): ExcludeFolder = addExcludeFolder(file.toVirtualFileUrl(virtualFileManager))
override fun addExcludeFolder(url: String): ExcludeFolder = addExcludeFolder(virtualFileManager.fromUrl(url))
override fun removeExcludeFolder(excludeFolder: ExcludeFolder) {
val virtualFileUrl = (excludeFolder as ExcludeFolderBridge).excludeFolderUrl
updateContentEntry {
if (!excludedUrls.contains(virtualFileUrl)) {
error("Exclude folder ${excludeFolder.url} is not under content entry $contentEntryUrl")
}
excludedUrls = excludedUrls.filter { url -> url != virtualFileUrl }
}
}
private fun updateContentEntry(updater: ContentRootEntity.Builder.() -> Unit) {
diff.modifyEntity(ContentRootEntity.Builder::class.java, currentContentEntry.value.entity, updater)
}
override fun removeExcludeFolder(url: String): Boolean {
val virtualFileUrl = virtualFileManager.fromUrl(url)
val excludedUrls = currentContentEntry.value.entity.excludedUrls
if (!excludedUrls.contains(virtualFileUrl)) return false
updateContentEntry {
this.excludedUrls = excludedUrls.filter { excludedUrl -> excludedUrl != virtualFileUrl }
}
return true
}
override fun clearExcludeFolders() {
updateContentEntry {
excludedUrls = emptyList()
}
}
override fun addExcludePattern(pattern: String) {
updateContentEntry {
excludedPatterns = if (excludedPatterns.contains(pattern)) excludedPatterns else (excludedPatterns + pattern)
}
}
override fun removeExcludePattern(pattern: String) {
updateContentEntry {
excludedPatterns = emptyList()
}
}
override fun setExcludePatterns(patterns: MutableList<String>) {
updateContentEntry {
excludedPatterns = patterns.toList()
}
}
override fun equals(other: Any?): Boolean {
return (other as? ContentEntry)?.url == url
}
override fun hashCode(): Int {
return url.hashCode()
}
override fun addSourceFolder(file: VirtualFile, isTestSource: Boolean) = addSourceFolder(file, isTestSource, "")
override fun addSourceFolder(file: VirtualFile, isTestSource: Boolean, packagePrefix: String): SourceFolder =
addSourceFolder(file, if (isTestSource) JavaSourceRootType.TEST_SOURCE else JavaSourceRootType.SOURCE,
JavaSourceRootProperties(packagePrefix, false))
override fun <P : JpsElement> addSourceFolder(file: VirtualFile, type: JpsModuleSourceRootType<P>): SourceFolder =
addSourceFolder(file, type, type.createDefaultProperties())
override fun addSourceFolder(url: String, isTestSource: Boolean): SourceFolder =
addSourceFolder(url, if (isTestSource) JavaSourceRootType.TEST_SOURCE else JavaSourceRootType.SOURCE)
override fun <P : JpsElement> addSourceFolder(url: String, type: JpsModuleSourceRootType<P>): SourceFolder =
addSourceFolder(url, type, type.createDefaultProperties())
override fun <P : JpsElement> addSourceFolder(file: VirtualFile, type: JpsModuleSourceRootType<P>, properties: P): SourceFolder =
addSourceFolder(file.toVirtualFileUrl(virtualFileManager), type, properties)
override fun <P : JpsElement> addSourceFolder(url: String, type: JpsModuleSourceRootType<P>, properties: P): SourceFolder =
addSourceFolder(virtualFileManager.fromUrl(url), type, properties)
override fun getFile(): VirtualFile? = currentContentEntry.value.file
override fun getUrl(): String = contentEntryUrl.url
override fun getSourceFolders(): Array<SourceFolder> = currentContentEntry.value.sourceFolders
override fun getSourceFolders(rootType: JpsModuleSourceRootType<*>): List<SourceFolder> =
currentContentEntry.value.getSourceFolders(rootType)
override fun getSourceFolders(rootTypes: MutableSet<out JpsModuleSourceRootType<*>>): List<SourceFolder> =
currentContentEntry.value.getSourceFolders(rootTypes)
override fun getSourceFolderFiles(): Array<VirtualFile> = currentContentEntry.value.sourceFolderFiles
override fun getExcludeFolders(): Array<ExcludeFolder> = currentContentEntry.value.excludeFolders
override fun getExcludeFolderUrls(): MutableList<String> = currentContentEntry.value.excludeFolderUrls
override fun getExcludeFolderFiles(): Array<VirtualFile> = currentContentEntry.value.excludeFolderFiles
override fun getExcludePatterns(): List<String> = currentContentEntry.value.excludePatterns
override fun getRootModel(): ModuleRootModel = modifiableRootModel
override fun isSynthetic(): Boolean = currentContentEntry.value.isSynthetic
}
| apache-2.0 | 1118e7f96ac9f26a27ba27de9fb0bc79 | 47.039648 | 155 | 0.769372 | 5.552444 | false | false | false | false |
spotify/heroic | heroic-core/src/main/java/com/spotify/heroic/shell/task/parameters/KeyspaceBase.kt | 1 | 1971 | /*
* Copyright (c) 2019 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.spotify.heroic.shell.task.parameters
import com.spotify.heroic.common.OptionalLimit
import org.kohsuke.args4j.Option
abstract class KeyspaceBase : QueryParamsBase() {
@Option(name = "--start", usage = "First key to operate on", metaVar = "<json>")
var start: String? = null
@Option(name = "--end", usage = "Last key to operate on (exclusive)", metaVar = "<json>")
var end: String? = null
@Option(name = "--start-percentage", usage = "First key to operate on in percentage", metaVar = "<int>")
var startPercentage = -1
@Option(name = "--end-percentage", usage = "Last key to operate on (exclusive) in percentage", metaVar = "<int>")
var endPercentage = -1
@Option(name = "--start-token", usage = "First token to operate on", metaVar = "<long>")
var startToken: Long? = null
@Option(name = "--end-token", usage = "Last token to operate on (exclusive)", metaVar = "<int>")
var endToken: Long? = null
@Option(name = "--limit", usage = "Limit the number keys to operate on", metaVar = "<int>")
override var limit: OptionalLimit = OptionalLimit.empty()
}
| apache-2.0 | 8f4c1a1c36f2979c8520f9420567bb04 | 40.0625 | 117 | 0.695079 | 4.022449 | false | false | false | false |
flesire/ontrack | ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/schema/GQLTypeProject.kt | 1 | 5741 | package net.nemerosa.ontrack.graphql.schema
import graphql.Scalars.GraphQLBoolean
import graphql.Scalars.GraphQLString
import graphql.schema.DataFetcher
import graphql.schema.GraphQLArgument.newArgument
import graphql.schema.GraphQLFieldDefinition.newFieldDefinition
import graphql.schema.GraphQLObjectType
import graphql.schema.GraphQLObjectType.newObject
import net.nemerosa.ontrack.common.and
import net.nemerosa.ontrack.graphql.support.GraphqlUtils
import net.nemerosa.ontrack.graphql.support.GraphqlUtils.stdList
import net.nemerosa.ontrack.model.labels.ProjectLabelManagementService
import net.nemerosa.ontrack.model.structure.*
import org.springframework.stereotype.Component
import java.util.*
import java.util.regex.Pattern
const val GRAPHQL_PROJECT_BRANCHES_USE_MODEL_ARG = "useModel"
@Component
class GQLTypeProject(
private val structureService: StructureService,
private val projectLabelManagementService: ProjectLabelManagementService,
creation: GQLTypeCreation,
private val branch: GQLTypeBranch,
projectEntityFieldContributors: List<GQLProjectEntityFieldContributor>,
private val projectEntityInterface: GQLProjectEntityInterface,
private val label: GQLTypeLabel,
private val branchFavouriteService: BranchFavouriteService,
private val branchModelMatcherService: BranchModelMatcherService
) : AbstractGQLProjectEntity<Project>(
Project::class.java,
ProjectEntityType.PROJECT,
projectEntityFieldContributors,
creation
) {
override fun getTypeName(): String {
return PROJECT
}
override fun createType(cache: GQLTypeCache): GraphQLObjectType {
return newObject()
.name(PROJECT)
.withInterface(projectEntityInterface.typeRef)
.fields(projectEntityInterfaceFields())
.field(GraphqlUtils.disabledField())
// Branches
.field(
newFieldDefinition()
.name("branches")
.type(stdList(branch.typeRef))
.argument(
newArgument()
.name("name")
.description("Regular expression to match against the branch name")
.type(GraphQLString)
.build()
)
.argument {
it.name(GRAPHQL_BRANCHES_FAVORITE_ARG)
.description("Gets only favorite branches")
.type(GraphQLBoolean)
}
.argument {
it.name(GRAPHQL_PROJECT_BRANCHES_USE_MODEL_ARG)
.description("If set to true, filter on branch matching the project's branching model")
.type(GraphQLBoolean)
}
.dataFetcher(projectBranchesFetcher())
.build()
)
// Labels for this project
.field {
it.name("labels")
.description("Labels for this project")
.type(stdList(label.typeRef))
.dataFetcher { environment ->
val project: Project = environment.getSource()
projectLabelManagementService.getLabelsForProject(project)
}
}
// OK
.build()
}
private fun projectBranchesFetcher(): DataFetcher<*> {
return DataFetcher<List<Branch>> { environment ->
val source = environment.getSource<Any>()
if (source is Project) {
val name: String? = environment.getArgument<String>("name")
val favorite: Boolean? = environment.getArgument(GRAPHQL_BRANCHES_FAVORITE_ARG)
val useModel: Boolean? = environment.getArgument(GRAPHQL_PROJECT_BRANCHES_USE_MODEL_ARG)
// Combined filter
var filter: (Branch) -> Boolean = { true }
// Name criteria
if (name != null) {
val nameFilter = Pattern.compile(name)
filter = filter.and { branch -> nameFilter.matcher(branch.name).matches() }
}
// Favourite
if (favorite != null && favorite) {
filter = filter and { branchFavouriteService.isBranchFavourite(it) }
}
// Matching the branching model
if (useModel != null && useModel) {
val branchModelMatcher = branchModelMatcherService.getBranchModelMatcher(source)
if (branchModelMatcher != null) {
filter = filter and { branchModelMatcher.matches(it) }
}
}
// Result
structureService
.getBranchesForProject(source.id)
.filter(filter)
} else {
emptyList()
}
}
}
override fun getSignature(entity: Project): Optional<Signature> {
return Optional.ofNullable(entity.signature)
}
companion object {
const val PROJECT = "Project"
}
}
| mit | 776645530c46c8314dad875d6eb44f6b | 42.492424 | 131 | 0.535273 | 6.288061 | false | false | false | false |
georocket/georocket | src/main/kotlin/io/georocket/cli/ServerCommand.kt | 1 | 1696 | package io.georocket.cli
import de.undercouch.underline.InputReader
import io.georocket.GeoRocket
import io.georocket.util.SizeFormat
import io.vertx.core.DeploymentOptions
import io.vertx.core.Promise
import io.vertx.core.buffer.Buffer
import io.vertx.core.streams.WriteStream
import io.vertx.kotlin.coroutines.await
import org.slf4j.LoggerFactory
import java.lang.management.ManagementFactory
/**
* Run GeoRocket in server mode
*/
class ServerCommand : GeoRocketCommand() {
companion object {
private val log = LoggerFactory.getLogger(ServerCommand::class.java)
}
override val usageName = "server"
override val usageDescription = "Run GeoRocket in server mode"
override suspend fun doRun(
remainingArgs: Array<String>, reader: InputReader,
out: WriteStream<Buffer>
): Int {
val banner = GeoRocket::class.java.getResource("georocket_banner.txt")!!.readText()
println(banner)
// log memory info
val memoryMXBean = ManagementFactory.getMemoryMXBean()
val memoryInit = memoryMXBean.heapMemoryUsage.init
val memoryMax = memoryMXBean.heapMemoryUsage.max
log.info(
"Initial heap size: ${SizeFormat.format(memoryInit)}, " +
"max heap size: ${SizeFormat.format(memoryMax)}"
)
// deploy main verticle
val shutdownPromise = Promise.promise<Unit>()
try {
val options = DeploymentOptions().setConfig(config)
vertx.deployVerticle(GeoRocket(shutdownPromise), options).await()
} catch (t: Throwable) {
log.error("Could not deploy GeoRocket")
t.printStackTrace()
return 1
}
// wait until GeoRocket verticle has shut down
shutdownPromise.future().await()
return 0
}
}
| apache-2.0 | bac0ab51c49f96a462a71ea69648dae1 | 28.754386 | 87 | 0.727594 | 4.315522 | false | false | false | false |
jmfayard/skripts | buildSrc/src/main/kotlin/Kotlin.kt | 1 | 358 | object Android {
const val kotlin = "1.2.61"
const val minSdkVersion = 21
const val targetSdkVersion = 25
const val compileSdkVersion = 27
const val Package = "com.github.jmfayard.okandroid"
const val GradleInstallTask = ":ok:installDebug"
const val GradleTestTask = ":ok:testDebugUnitTest"
const val GradleMainModule = "ok"
} | apache-2.0 | 4d61a2af980519bb0e44ee3b6b1d4270 | 34.9 | 55 | 0.709497 | 4.068182 | false | true | false | false |
paplorinc/intellij-community | platform/script-debugger/backend/src/debugger/SuspendContextManager.kt | 7 | 2363 | /*
* 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.debugger
import org.jetbrains.concurrency.Promise
interface SuspendContextManager<CALL_FRAME : CallFrame> {
/**
* Tries to suspend VM. If successful, [DebugEventListener.suspended] will be called.
*/
fun suspend(): Promise<*>
val context: SuspendContext<CALL_FRAME>?
val contextOrFail: SuspendContext<CALL_FRAME>
fun isContextObsolete(context: SuspendContext<*>): Boolean = this.context !== context
fun setOverlayMessage(message: String?)
/**
* Resumes the VM execution. This context becomes invalid until another context is supplied through the
* [DebugEventListener.suspended] event.
* @param stepAction to perform
* *
* @param stepCount steps to perform (not used if `stepAction == CONTINUE`)
*/
fun continueVm(stepAction: StepAction, stepCount: Int = 1): Promise<*>
val isRestartFrameSupported: Boolean
/**
* Restarts a frame (all frames above are dropped from the stack, this frame is started over).
* for success the boolean parameter
* is true if VM has been resumed and is expected to get suspended again in a moment (with
* a standard 'resumed' notification), and is false if call frames list is already updated
* without VM state change (this case presently is never actually happening)
*/
fun restartFrame(callFrame: CALL_FRAME): Promise<Boolean>
/**
* @return whether reset operation is supported for the particular callFrame
*/
fun canRestartFrame(callFrame: CallFrame): Boolean
}
enum class StepAction {
/**
* Resume the JavaScript execution.
*/
CONTINUE,
/**
* Step into the current statement.
*/
IN,
/**
* Step over the current statement.
*/
OVER,
/**
* Step out of the current function.
*/
OUT
} | apache-2.0 | 314f3fa5fe51b77763750a93631175e2 | 28.55 | 105 | 0.716039 | 4.433396 | false | false | false | false |
RuneSuite/client | api/src/main/java/org/runestar/client/api/overlay/SizeCachingOverlay.kt | 1 | 628 | package org.runestar.client.api.overlay
import java.awt.Dimension
import java.awt.Graphics2D
class SizeCachingOverlay(
val overlay: Overlay
) : Overlay {
var modified = true
private var width = -1
private var height = -1
override fun draw(g: Graphics2D, size: Dimension) = overlay.draw(g, size)
override fun getSize(g: Graphics2D, result: Dimension) {
if (!modified) return result.setSize(width, height)
modified = false
overlay.getSize(g, result)
width = result.width
height = result.height
}
}
fun Overlay.cachingSize() = SizeCachingOverlay(this) | mit | 1299176f2acf3723330b72ebc28ea8a3 | 22.296296 | 77 | 0.675159 | 3.900621 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/Instrument.kt | 1 | 3164 | package org.runestar.client.updater.mapper.std.classes
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.OrderMapper
import org.runestar.client.updater.mapper.DependsOn
import org.runestar.client.updater.mapper.MethodParameters
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.type
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Instruction2
import org.runestar.client.updater.mapper.Method2
import org.runestar.client.common.startsWith
import org.objectweb.asm.Opcodes.*
import org.objectweb.asm.Type.*
import org.runestar.client.updater.mapper.Field2
@DependsOn(SoundEnvelope::class)
class Instrument : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == Any::class.type }
.and { it.instanceFields.count { it.type == type<SoundEnvelope>() } >= 6 }
class oscillatorVolume : OrderMapper.InConstructor.Field(Instrument::class, 0, 3) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type }
}
class oscillatorPitch : OrderMapper.InConstructor.Field(Instrument::class, 1, 3) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type }
}
class oscillatorDelays : OrderMapper.InConstructor.Field(Instrument::class, 2, 3) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type }
}
class delayTime : OrderMapper.InConstructor.Field(Instrument::class, 0, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
class delayDecay : OrderMapper.InConstructor.Field(Instrument::class, 1, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
class duration : OrderMapper.InConstructor.Field(Instrument::class, 2, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
class offset : OrderMapper.InConstructor.Field(Instrument::class, 3, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
@MethodParameters("packet")
@DependsOn(Packet::class)
class decode : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.arguments.startsWith(type<Packet>()) }
}
class synthesize : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == IntArray::class.type }
}
class evaluateWave : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE }
}
@DependsOn(AudioFilter::class)
class filter : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<AudioFilter>() }
}
} | mit | ba20083a2f26f6c3520e6cea69a8d089 | 44.214286 | 124 | 0.724399 | 4.264151 | false | false | false | false |
google/intellij-community | platform/collaboration-tools/src/com/intellij/collaboration/async/CoroutineUtil.kt | 1 | 1713 | // 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.collaboration.async
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.Disposer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.*
import org.jetbrains.annotations.ApiStatus
import kotlin.coroutines.CoroutineContext
@ApiStatus.Experimental
@Suppress("FunctionName")
fun DisposingMainScope(parentDisposable: Disposable): CoroutineScope =
MainScope().also {
Disposer.register(parentDisposable) {
it.cancel()
}
}
@ApiStatus.Experimental
@Suppress("FunctionName")
fun DisposingScope(parentDisposable: Disposable, context: CoroutineContext = SupervisorJob()): CoroutineScope =
CoroutineScope(context).also {
Disposer.register(parentDisposable) {
it.cancel()
}
}
@ApiStatus.Experimental
fun Disposable.disposingScope(context: CoroutineContext = SupervisorJob()): CoroutineScope =
DisposingScope(this, context)
@ApiStatus.Experimental
fun <T1, T2, R> combineState(scope: CoroutineScope,
state1: StateFlow<T1>,
state2: StateFlow<T2>,
transform: (T1, T2) -> R): StateFlow<R> =
combine(state1, state2, transform)
.stateIn(scope, SharingStarted.Eagerly, transform(state1.value, state2.value))
@ApiStatus.Experimental
fun <T, M> StateFlow<T>.mapState(
scope: CoroutineScope,
mapper: (value: T) -> M
): StateFlow<M> = map { mapper(it) }.stateIn(scope, SharingStarted.Eagerly, mapper(value)) | apache-2.0 | 77d745159790eaf9c313bc7ef70625bd | 34.708333 | 120 | 0.737887 | 4.358779 | false | false | false | false |
google/iosched | mobile/src/main/java/com/google/samples/apps/iosched/widget/CollapsibleCard.kt | 3 | 5104 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.widget
import android.content.Context
import android.os.Parcel
import android.os.Parcelable
import android.text.method.LinkMovementMethod
import android.transition.Transition
import android.transition.TransitionInflater
import android.transition.TransitionManager
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.core.text.HtmlCompat
import com.google.samples.apps.iosched.R
/**
* Collapsible card, description of which can be HTML.
* In that case, the text specified as "cardDescription" needs to be wrapped with <![CDATA[ ... ]]>
*/
class CollapsibleCard @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
private var expanded = false
private val cardTitleView: TextView
private lateinit var cardDescriptionView: TextView
private val expandIcon: ImageView
private val titleContainer: View
private val toggle: Transition
private val root: View
private val cardTitle: String?
init {
val arr = context.obtainStyledAttributes(attrs, R.styleable.CollapsibleCard, 0, 0)
cardTitle = arr.getString(R.styleable.CollapsibleCard_cardTitle)
val cardDescription = arr.getString(R.styleable.CollapsibleCard_cardDescription)
arr.recycle()
root = LayoutInflater.from(context)
.inflate(R.layout.collapsible_card_content, this, true)
titleContainer = root.findViewById(R.id.title_container)
cardTitleView = root.findViewById<TextView>(R.id.card_title).apply {
text = cardTitle
}
setTitleContentDescription(cardTitle)
cardDescription?.let {
cardDescriptionView = root.findViewById<TextView>(R.id.card_description).apply {
text = HtmlCompat.fromHtml(it, HtmlCompat.FROM_HTML_MODE_COMPACT)
movementMethod = LinkMovementMethod.getInstance()
}
}
expandIcon = root.findViewById(R.id.expand_icon)
toggle = TransitionInflater.from(context)
.inflateTransition(R.transition.info_card_toggle)
titleContainer.setOnClickListener {
toggleExpanded()
}
}
private fun setTitleContentDescription(cardTitle: String?) {
val res = resources
cardTitleView.contentDescription = "$cardTitle, " + if (expanded) {
res.getString(R.string.expanded)
} else {
res.getString(R.string.collapsed)
}
}
private fun toggleExpanded() {
expanded = !expanded
toggle.duration = if (expanded) 300L else 200L
TransitionManager.beginDelayedTransition(root.parent as ViewGroup, toggle)
cardDescriptionView.visibility = if (expanded) View.VISIBLE else View.GONE
expandIcon.rotationX = if (expanded) 180f else 0f
setTitleContentDescription(cardTitle)
}
override fun onSaveInstanceState(): Parcelable {
val savedState = SavedState(super.onSaveInstanceState()!!)
savedState.expanded = expanded
return savedState
}
override fun onRestoreInstanceState(state: Parcelable?) {
if (state is SavedState) {
super.onRestoreInstanceState(state.superState)
if (expanded != state.expanded) {
toggleExpanded()
}
} else {
super.onRestoreInstanceState(state)
}
}
internal class SavedState : BaseSavedState {
var expanded = false
constructor(source: Parcel) : super(source) {
expanded = source.readByte().toInt() != 0
}
constructor(superState: Parcelable) : super(superState)
override fun writeToParcel(out: Parcel, flags: Int) {
super.writeToParcel(out, flags)
out.writeByte((if (expanded) 1 else 0).toByte())
}
companion object {
@JvmField
val CREATOR = object : Parcelable.Creator<SavedState> {
override fun createFromParcel(source: Parcel): SavedState {
return SavedState(source)
}
override fun newArray(size: Int): Array<SavedState?> {
return arrayOfNulls(size)
}
}
}
}
}
| apache-2.0 | 11f0a4bc251b5b96202282f0d51d26d0 | 34.2 | 99 | 0.671042 | 4.870229 | false | false | false | false |
JetBrains/intellij-community | plugins/settings-sync/src/com/intellij/settingsSync/SettingsSyncEventsStatistics.kt | 1 | 1698 | package com.intellij.settingsSync
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
class SettingsSyncEventsStatistics : CounterUsagesCollector() {
companion object {
val GROUP: EventLogGroup = EventLogGroup("settings.sync.events", 1)
val ENABLED_MANUALLY = GROUP.registerEvent("enabled.manually", EventFields.Enum("method", EnabledMethod::class.java))
val DISABLED_MANUALLY = GROUP.registerEvent("disabled.manually", EventFields.Enum("method", ManualDisableMethod::class.java))
val DISABLED_AUTOMATICALLY = GROUP.registerEvent("disabled.automatically", EventFields.Enum("reason", AutomaticDisableReason::class.java))
val MIGRATED_FROM_OLD_PLUGIN = GROUP.registerEvent("migrated.from.old.plugin")
val MIGRATED_FROM_SETTINGS_REPOSITORY = GROUP.registerEvent("migrated.from.settings.repository")
val SETTINGS_REPOSITORY_NOTIFICATION_ACTION = GROUP.registerEvent("invoked.settings.repository.notification.action", EventFields.Enum("action", SettingsRepositoryMigrationNotificationAction::class.java))
}
enum class EnabledMethod {
GET_FROM_SERVER,
PUSH_LOCAL,
PUSH_LOCAL_WAS_ONLY_WAY,
CANCELED
}
enum class ManualDisableMethod {
DISABLED_ONLY,
DISABLED_AND_REMOVED_DATA_FROM_SERVER,
CANCEL
}
enum class AutomaticDisableReason {
REMOVED_FROM_SERVER,
EXCEPTION
}
enum class SettingsRepositoryMigrationNotificationAction {
INSTALL_SETTINGS_REPOSITORY,
USE_NEW_SETTINGS_SYNC
}
override fun getGroup(): EventLogGroup {
return GROUP
}
} | apache-2.0 | 5d875326dd0a5f38cc49f6e5b1d11d7c | 36.755556 | 207 | 0.776796 | 4.552279 | false | false | false | false |
allotria/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/PrefixTreeMap.kt | 2 | 5647 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.util
import com.intellij.util.containers.FList
import java.util.*
import kotlin.NoSuchElementException
import kotlin.collections.LinkedHashMap
import kotlin.collections.component1
import kotlin.collections.component2
/**
* Map for fast finding values by the prefix of their keys
*/
internal class PrefixTreeMap<K, V> : Map<List<K>, V> {
/**
* Gets all descendant entries for [key]
*
* @return descendant entries, [emptyList] if [key] not found
*/
fun getAllDescendants(key: List<K>) = root.getAllDescendants(key.toFList()).toSet()
/**
* Gets all ancestor entries for [key]
*
* @return ancestor entries, [emptyList] if [key] not found
*/
fun getAllAncestors(key: List<K>) = root.getAllAncestors(key.toFList()).toList()
fun getAllDescendantKeys(key: List<K>) = root.getAllDescendants(key.toFList()).map { it.key }.toSet()
fun getAllDescendantValues(key: List<K>) = root.getAllDescendants(key.toFList()).map { it.value }.toSet()
fun getAllAncestorKeys(key: List<K>) = root.getAllAncestors(key.toFList()).map { it.key }.toList()
fun getAllAncestorValues(key: List<K>) = root.getAllAncestors(key.toFList()).map { it.value }.toList()
private val root = Node()
override val size get() = root.size
override val keys get() = root.getEntries().map { it.key }.toSet()
override val values: List<V>
get() = valueSequence.toList()
val valueSequence: Sequence<V>
get() = root.getEntries().map { it.value }
override val entries get() = root.getEntries().toSet()
override fun get(key: List<K>) = root.get(key.toFList())?.value?.getOrNull()
override fun containsKey(key: List<K>) = root.containsKey(key.toFList())
override fun containsValue(value: V) = root.getEntries().any { it.value == value }
override fun isEmpty() = root.isEmpty
operator fun set(path: List<K>, value: V) = root.put(path.toFList(), value).getOrNull()
fun remove(path: List<K>) = root.remove(path.toFList()).getOrNull()
private inner class Node {
private val children = LinkedHashMap<K, Node>()
val isLeaf get() = children.isEmpty()
val isEmpty get() = isLeaf && !value.isPresent
var size: Int = 0
private set
var value = Value.empty<V>()
private set
private fun calculateCurrentSize() =
children.values.sumBy { it.size } + if (value.isPresent) 1 else 0
private fun getAndSet(value: Value<V>) =
this.value.also {
this.value = value
size = calculateCurrentSize()
}
fun put(path: FList<K>, value: V): Value<V> {
val (head, tail) = path
val child = children.getOrPut(head) { Node() }
val previousValue = when {
tail.isEmpty() -> child.getAndSet(Value.of(value))
else -> child.put(tail, value)
}
size = calculateCurrentSize()
return previousValue
}
fun remove(path: FList<K>): Value<V> {
val (head, tail) = path
val child = children[head] ?: return Value.EMPTY
val value = when {
tail.isEmpty() -> child.getAndSet(Value.EMPTY)
else -> child.remove(tail)
}
if (child.isEmpty) children.remove(head)
size = calculateCurrentSize()
return value
}
fun containsKey(path: FList<K>): Boolean {
val (head, tail) = path
val child = children[head] ?: return false
return when {
tail.isEmpty() -> child.value.isPresent
else -> child.containsKey(tail)
}
}
fun get(path: FList<K>): Node? {
val (head, tail) = path
val child = children[head] ?: return null
return when {
tail.isEmpty() -> child
else -> child.get(tail)
}
}
fun getEntries(): Sequence<Map.Entry<FList<K>, V>> {
return sequence {
if (value.isPresent) {
yield(AbstractMap.SimpleImmutableEntry(FList.emptyList(), value.get()))
}
for ((key, child) in children) {
for ((path, value) in child.getEntries()) {
yield(AbstractMap.SimpleImmutableEntry(path.prepend(key), value))
}
}
}
}
fun getAllAncestors(path: FList<K>): Sequence<Map.Entry<FList<K>, V>> {
return sequence {
if (value.isPresent) {
yield(AbstractMap.SimpleImmutableEntry(FList.emptyList(), value.get()))
}
if (path.isEmpty()) return@sequence
val (head, tail) = path
val child = children[head] ?: return@sequence
for ((relative, value) in child.getAllAncestors(tail)) {
yield(AbstractMap.SimpleImmutableEntry(relative.prepend(head), value))
}
}
}
fun getAllDescendants(path: FList<K>) =
root.get(path)?.getEntries()?.map { AbstractMap.SimpleImmutableEntry(path + it.key, it.value) } ?: emptySequence()
}
private class Value<out T> private constructor(val isPresent: Boolean, private val value: Any?) {
fun get(): T {
@Suppress("UNCHECKED_CAST")
if (isPresent) return value as T
throw NoSuchElementException("No value present")
}
fun getOrNull() = if (isPresent) get() else null
companion object {
val EMPTY = Value<Nothing>(false, null)
fun <T> empty() = EMPTY as Value<T>
fun <T> of(value: T) = Value<T>(true, value)
}
}
companion object {
private operator fun <E> FList<E>.component1() = head
private operator fun <E> FList<E>.component2() = tail
private fun <E> List<E>.toFList() = FList.createFromReversed(asReversed())
}
} | apache-2.0 | cf65bc5bf18318952a86b0d25d4715a3 | 32.02924 | 140 | 0.638569 | 3.924253 | false | false | false | false |
Kotlin/kotlinx.coroutines | reactive/kotlinx-coroutines-rx3/test/ObservableMultiTest.kt | 1 | 3231 | /*
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.rx3
import io.reactivex.rxjava3.core.*
import kotlinx.coroutines.*
import kotlinx.coroutines.selects.*
import org.junit.Test
import java.io.*
import kotlin.test.*
/**
* Test emitting multiple values with [rxObservable].
*/
class ObservableMultiTest : TestBase() {
@Test
fun testNumbers() {
val n = 100 * stressTestMultiplier
val observable = rxObservable {
repeat(n) { send(it) }
}
checkSingleValue(observable.toList()) { list ->
assertEquals((0 until n).toList(), list)
}
}
@Test
fun testConcurrentStress() {
val n = 10_000 * stressTestMultiplier
val observable = rxObservable {
newCoroutineContext(coroutineContext)
// concurrent emitters (many coroutines)
val jobs = List(n) {
// launch
launch(Dispatchers.Default) {
val i = it
send(i)
}
}
jobs.forEach { it.join() }
}
checkSingleValue(observable.toList()) { list ->
assertEquals(n, list.size)
assertEquals((0 until n).toList(), list.sorted())
}
}
@Test
fun testConcurrentStressOnSend() {
val n = 10_000 * stressTestMultiplier
val observable = rxObservable<Int> {
newCoroutineContext(coroutineContext)
// concurrent emitters (many coroutines)
val jobs = List(n) {
// launch
launch(Dispatchers.Default) {
val i = it
select<Unit> {
onSend(i) {}
}
}
}
jobs.forEach { it.join() }
}
checkSingleValue(observable.toList()) { list ->
assertEquals(n, list.size)
assertEquals((0 until n).toList(), list.sorted())
}
}
@Test
fun testIteratorResendUnconfined() {
val n = 10_000 * stressTestMultiplier
val observable = rxObservable(Dispatchers.Unconfined) {
Observable.range(0, n).collect { send(it) }
}
checkSingleValue(observable.toList()) { list ->
assertEquals((0 until n).toList(), list)
}
}
@Test
fun testIteratorResendPool() {
val n = 10_000 * stressTestMultiplier
val observable = rxObservable {
Observable.range(0, n).collect { send(it) }
}
checkSingleValue(observable.toList()) { list ->
assertEquals((0 until n).toList(), list)
}
}
@Test
fun testSendAndCrash() {
val observable = rxObservable {
send("O")
throw IOException("K")
}
val single = rxSingle {
var result = ""
try {
observable.collect { result += it }
} catch(e: IOException) {
result += e.message
}
result
}
checkSingleValue(single) {
assertEquals("OK", it)
}
}
}
| apache-2.0 | 563981860c32375375be9560b37fba60 | 27.095652 | 102 | 0.519034 | 4.873303 | false | true | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-telemetry/src/main/kotlin/slatekit/telemetry/Counter.kt | 1 | 441 | package slatekit.telemetry
import java.util.concurrent.atomic.AtomicLong
/**
* Simple counter for a value
*/
data class Counter(override val tags: List<Tag> = listOf(), val customTags:List<String>? = null) : Tagged {
private val value = AtomicLong(0L)
fun inc(): Long = value.incrementAndGet()
fun dec(): Long = value.decrementAndGet()
fun get(): Long = value.get()
fun set(newValue:Long) = value.set(newValue)
}
| apache-2.0 | 2199b1573d50bedb3d9d612b928297d9 | 23.5 | 107 | 0.684807 | 3.834783 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-cli/src/main/kotlin/slatekit/cli/CliSettings.kt | 1 | 581 | /**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.cli
data class CliSettings(
val argPrefix: String = "-",
val argSeparator: String = "=",
val enableLogging: Boolean = false,
val enableOutput: Boolean = false,
val enableStartLog: Boolean = false
)
| apache-2.0 | dc09f1b3b88e5beedf66ac82b446833d | 25.409091 | 56 | 0.695353 | 3.677215 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/reflection/mapping/topLevelProperty.kt | 2 | 868 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
import kotlin.reflect.jvm.*
import kotlin.test.assertEquals
var topLevel = "123"
fun box(): String {
val p = ::topLevel
assert(p.javaField != null) { "Fail p field" }
val field = p.javaField!!
val className = field.getDeclaringClass().getName()
assertEquals("TopLevelPropertyKt", className)
val getter = p.javaGetter!!
val setter = p.javaSetter!!
assertEquals(getter, Class.forName("TopLevelPropertyKt").getMethod("getTopLevel"))
assertEquals(setter, Class.forName("TopLevelPropertyKt").getMethod("setTopLevel", String::class.java))
assert(getter.invoke(null) == "123") { "Fail k getter" }
setter.invoke(null, "456")
assert(getter.invoke(null) == "456") { "Fail k setter" }
return "OK"
}
| apache-2.0 | 6f5bb104f80deb0bd0061dad3f4ef063 | 27.933333 | 106 | 0.684332 | 3.892377 | false | false | false | false |
evanchooly/gridfs-fs-provider | core/src/main/kotlin/com/antwerkz/gridfs/GridFSFileSystemProvider.kt | 1 | 6793 | package com.antwerkz.gridfs
import com.mongodb.MongoClient
import com.mongodb.MongoClientOptions
import com.mongodb.MongoClientURI
import com.mongodb.MongoNamespace
import com.mongodb.client.gridfs.GridFSUploadStream
import com.mongodb.client.model.Filters
import java.io.FileNotFoundException
import java.io.InputStream
import java.net.MalformedURLException
import java.net.URI
import java.nio.channels.SeekableByteChannel
import java.nio.file.AccessMode
import java.nio.file.CopyOption
import java.nio.file.DirectoryStream
import java.nio.file.DirectoryStream.Filter
import java.nio.file.FileStore
import java.nio.file.FileSystem
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.OpenOption
import java.nio.file.Path
import java.nio.file.ProviderMismatchException
import java.nio.file.attribute.BasicFileAttributeView
import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.attribute.FileAttribute
import java.nio.file.attribute.FileAttributeView
import java.nio.file.spi.FileSystemProvider
import java.util.regex.Pattern
class GridFSFileSystemProvider(private val client: MongoClient) : FileSystemProvider() {
companion object {
private val OPTIONS = "gridfs.options"
}
private val fsCache = mutableMapOf<MongoNamespace, GridFSFileSystem>()
override fun getScheme(): String {
return "gridfs"
}
override fun newFileSystem(uri: URI, env: Map<String, *>?): FileSystem {
val gridfsUri = uri.toString().replace("gridfs://", "mongodb://")
val options = env?.get(OPTIONS) as MongoClientOptions?
val builder = if (options == null) MongoClientOptions.builder() else MongoClientOptions.builder(options)
val clientUri = MongoClientURI(gridfsUri, builder)
val bucket = clientUri.collection ?: "gridfs"
return fsCache.getOrPut(MongoNamespace(clientUri.database, bucket), {
GridFSFileSystem(this, client, clientUri.database, bucket)
})
}
override fun getFileSystem(uri: URI) = newFileSystem(uri, mapOf<String, Any>())
fun getFileSystem(database: String, bucket: String): GridFSFileSystem {
return fsCache.getOrPut(MongoNamespace(database, bucket), {
GridFSFileSystem(this, client, database, bucket)
})
}
override fun getPath(uri: URI): Path {
val path = uri.path.dropWhile { it == '/' }
val ns = path.substringBefore("/")
if (!ns.contains('.')) {
throw MalformedURLException("GridFS URIs must be in the form 'gridfs://<host>[:<port>]/<database>.<collection>'")
}
val fileName = path.substringAfter("/")
val mongoUri = uri.toString().replace(path, "") + ns
val fileSystem = getFileSystem(URI(mongoUri))
return fileSystem.getPath("/" + fileName)
}
override fun newInputStream(path: Path, vararg options: OpenOption): InputStream {
return checkPath(path).newInputStream()
}
override fun newOutputStream(path: Path, vararg options: OpenOption): GridFSUploadStream {
return checkPath(path).newOutputStream()
}
override fun newByteChannel(path: Path?, options: Set<OpenOption>, vararg attrs: FileAttribute<*>): SeekableByteChannel {
return GridFSByteChannel(checkPath(path))
}
internal fun checkPath(path: Path?): GridFSPath {
if (path == null) {
throw NullPointerException()
} else if (path !is GridFSPath) {
throw ProviderMismatchException()
} else {
return path
}
}
override fun newDirectoryStream(dir: Path, filter: Filter<in Path>): DirectoryStream<Path> {
throw UnsupportedOperationException("Not implemented")
}
override fun createDirectory(dir: Path, vararg attrs: FileAttribute<*>) {
}
override fun delete(path: Path) {
path as GridFSPath
val file = path.file
val bucket = path.fileSystem.bucket
if (file != null) {
bucket.delete(file.objectId)
} else if (path.path.endsWith("/")) {
val find = bucket.find(Filters.regex("filename", Pattern.compile(path.path).pattern() + ".*")).toList()
find.forEach { bucket.delete(it.objectId) }
}
}
override fun copy(source: Path, target: Path, vararg options: CopyOption) {
if (!Files.isSameFile(source, target)) {
newOutputStream(target).use { outputStream ->
newInputStream(source).use { inputStream ->
inputStream.copyTo(outputStream)
}
}
}
}
override fun move(source: Path, target: Path, vararg options: CopyOption) {
source as GridFSPath
target as GridFSPath
if (!Files.isSameFile(source, target)) {
if (source.fileSystem.equals(target.fileSystem)) {
source.file?.let { file ->
source.fileSystem.bucket.rename(file.objectId, target.path)
}
} else {
copy(source, target, *options)
delete(source)
}
}
}
override fun isSameFile(path: Path, path2: Path): Boolean {
path as GridFSPath
path2 as GridFSPath
return path.fileSystem.equals(path2.fileSystem)
&& path.normalize().equals(path2.normalize())
}
override fun isHidden(path: Path): Boolean {
return false
}
override fun getFileStore(path: Path): FileStore {
throw UnsupportedOperationException("Not implemented")
}
override fun checkAccess(path: Path, vararg modes: AccessMode) {
path as GridFSPath
val fileSystem = path.fileSystem
val find = fileSystem.bucket.find(Filters.eq("filename", path.path))
if (find.firstOrNull() == null) {
throw FileNotFoundException("$path was not found in the '${fileSystem.bucketName}' bucket")
}
}
override fun <V : FileAttributeView> getFileAttributeView(path: Path, type: Class<V>, vararg options: LinkOption): V? {
if (type == BasicFileAttributeView::class.java) {
return GridFSFileAttributeView(path as GridFSPath) as V
}
return null
}
override fun <A : BasicFileAttributes> readAttributes(path: Path, type: Class<A>, vararg options: LinkOption): A {
throw UnsupportedOperationException("Not implemented")
}
override fun readAttributes(path: Path, attributes: String, vararg options: LinkOption): Map<String, Any> {
throw UnsupportedOperationException("Not implemented")
}
override fun setAttribute(path: Path, attribute: String, value: Any, vararg options: LinkOption) {
throw UnsupportedOperationException("Not implemented")
}
}
| apache-2.0 | c4c2941b11c690917fbdb9366d45e76b | 35.718919 | 125 | 0.665244 | 4.710818 | false | false | false | false |
ericfabreu/ktmdb | ktmdb/src/main/kotlin/com/ericfabreu/ktmdb/models/TvSeason.kt | 1 | 6360 | package com.ericfabreu.ktmdb.models
import com.beust.klaxon.JsonArray
import com.beust.klaxon.JsonObject
import com.ericfabreu.ktmdb.Tmdb
import com.ericfabreu.ktmdb.utils.JsonHelper
import com.ericfabreu.ktmdb.utils.ListHelper.ChangeItem
import com.ericfabreu.ktmdb.utils.MediaHelper.ImageFile
import com.ericfabreu.ktmdb.utils.MediaHelper.VideoFile
import com.ericfabreu.ktmdb.utils.PersonHelper.BasicCast
import com.ericfabreu.ktmdb.utils.PersonHelper.BasicCrew
import com.ericfabreu.ktmdb.utils.PersonHelper.BasicTvCast
import com.ericfabreu.ktmdb.utils.PersonHelper.BasicTvCrew
import com.ericfabreu.ktmdb.utils.PersonHelper.CreditList
import org.slf4j.LoggerFactory
/**
* Provides a TV season class with the functionality defined at
* https://developers.themoviedb.org/3/tv-seasons
*/
@Suppress("UNCHECKED_CAST", "UNUSED")
data class TvSeason(private val tmdb: Tmdb, val id: Int, val seasonNumber: Int,
private val language: String = Tmdb.LANGUAGE_EN_US,
private val append: ArrayList<SeasonAppendable> = ArrayList()) {
companion object {
enum class SeasonAppendable(val path: String) {
CHANGES("changes"),
CREDITS("credits"),
EXTERNAL_IDS("external_ids"),
IMAGES("images"),
VIDEOS("videos")
}
data class SeasonAccountState(private val item: JsonObject) {
val id = item["id"] as Int
val episodeNumber = item["episode_number"] as Int
val rating = JsonHelper.getAccountStateRating(item["rated"])
}
data class TvEpisodeItem(private val item: JsonObject) {
val airDate = item["air_date"] as String
val crew = JsonHelper.jsonToList(item["crew"] as JsonArray<JsonObject>, ::BasicTvCrew)
val episodeNumber = item["episode_number"] as Int
val guestStars = JsonHelper.jsonToList(item["guest_stars"] as JsonArray<JsonObject>,
::BasicTvCast)
val name = item["name"] as String
val overview = item["overview"] as String?
val id = item["id"] as Int
val productionCode = item["production_code"] as String?
val seasonNumber = item["season_number"] as Int
val stillPath = item["still_path"] as String?
val voteAverage = item["vote_average"].toString().toDouble()
val voteCount = item["vote_count"] as Int
}
data class TvSeasonExternalIds(private val item: JsonObject) {
val freebaseMid = item["freebase_mid"] as String?
val freebaseId = item["freebase_id"] as String?
val tvdbId = item["tvdb_id"] as Int?
val tvRageId = item["tvRage_id"] as Int?
}
private const val PATH = "tv"
private const val SUB_PATH = "season"
private val LOG = LoggerFactory.getLogger(Tmdb.NAME + TvSeason::class.java.simpleName)
}
private val query = JsonHelper.getImageQuery(language, append.contains(SeasonAppendable.IMAGES))
private val result = tmdb.getJson(tmdb.url(PATH, id.toString(),
subPath = "$SUB_PATH/$seasonNumber", language = language, query = query,
append = JsonHelper.appendToString(append, { it: SeasonAppendable -> it.path })))
val airDate = result["air_date"] as String
val episodes = JsonHelper.jsonToList(result["episodes"] as JsonArray<JsonObject>,
::TvEpisodeItem)
val name = result["name"] as String
val overview = result["overview"] as String?
val posterPath = result["poster_path"] as String?
val seasonId = result["_id"] as String
// Returns changes made in the last 24 hours
val changes: HashMap<String, List<ChangeItem>> by lazy {
JsonHelper.jsonToMap(getAppendable(SeasonAppendable.CHANGES)["changes"]
as JsonArray<JsonObject>, ChangeItem.KEY_ID, ChangeItem.KEY_VALUE, ::ChangeItem)
}
val credits: CreditList<BasicCast, BasicCrew> by lazy {
CreditList(getAppendable(SeasonAppendable.CREDITS), ::BasicCast, ::BasicCrew)
}
val externalIds: TvSeasonExternalIds by lazy {
TvSeasonExternalIds(getAppendable(SeasonAppendable.EXTERNAL_IDS))
}
val images: List<ImageFile> by lazy {
JsonHelper.jsonToList(getAppendable(SeasonAppendable.IMAGES)["posters"]
as JsonArray<JsonObject>, ::ImageFile)
}
val videos: List<VideoFile> by lazy {
val results = getAppendable(SeasonAppendable.VIDEOS)["results"] as JsonArray<JsonObject>
results.map { VideoFile(it) }
}
private fun getSubPath(subPath: String): String {
val idStr = if (subPath == SeasonAppendable.CHANGES.path) seasonId
else seasonNumber.toString()
return "$SUB_PATH/$idStr/$subPath"
}
private fun getAppendable(value: SeasonAppendable): JsonObject {
val idStr = if (value == SeasonAppendable.CHANGES) null else id
return JsonHelper.getAppendable(tmdb, result[value.path], language, idStr,
PATH, getSubPath(value.path), value == SeasonAppendable.IMAGES)
}
fun getChangeWithRange(startDate: String = "",
endDate: String = ""): HashMap<String, List<ChangeItem>> {
return JsonHelper.getChangeWithRange(tmdb, PATH, null, startDate, endDate,
getSubPath(SeasonAppendable.CHANGES.path))
}
// TODO: Deal with guest account state bug once the API is fixed
fun getAccountStates(sessionId: String, isGuest: Boolean = false): List<SeasonAccountState>? {
if (isGuest) {
LOG.warn("Account states not available for guest accounts yet.")
return null
}
return JsonHelper.getAccountStates(tmdb, PATH, id, sessionId, isGuest,
{
JsonHelper.jsonToList(it["results"] as JsonArray<JsonObject>,
::SeasonAccountState)
},
getSubPath(JsonHelper.PATH_ACCOUNT_STATES))
}
fun getImagesByLanguage(languages: String): List<ImageFile> {
return JsonHelper.getImagesByLanguage(tmdb, PATH, id, languages,
{ JsonHelper.jsonToList(it["posters"] as JsonArray<JsonObject>, ::ImageFile) },
getSubPath(JsonHelper.PATH_IMAGES))
}
override fun toString(): String = name
}
| mit | 1db16b4fe29b0e1ecec3dcebe6da85fe | 43.788732 | 100 | 0.656761 | 4.582133 | false | false | false | false |
kohesive/kohesive-iac | model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/cloudformation/processing/CloudFormationFunctionsProcessor.kt | 1 | 2876 | package uy.kohesive.iac.model.aws.cloudformation.processing
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.ObjectNode
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import uy.kohesive.iac.model.aws.IacContext
import uy.kohesive.iac.model.aws.cloudformation.Template
import uy.kohesive.iac.model.aws.cloudformation.functions.CFFindInMapFunction
import uy.kohesive.iac.model.aws.cloudformation.functions.CFGetAttributeFunction
import uy.kohesive.iac.model.aws.cloudformation.functions.CFJoinFunction
import uy.kohesive.iac.model.aws.cloudformation.functions.CFRefFunction
import uy.kohesive.iac.model.aws.proxy.ResourceNode
import uy.kohesive.iac.model.aws.proxy.explodeReference
fun ResourceNode.toCFJsonObject(): Any = if (this is ResourceNode.StringLiteralNode) {
this.value()
} else if (this is ResourceNode.ImplicitNode) {
CFRefFunction((children[0] as ResourceNode.StringLiteralNode).value().replace("-", "::"))
} else if (this is ResourceNode.MapNode) {
CFFindInMapFunction(
mapName = children[0].toCFJsonObject(),
topLevelKey = children[1].toCFJsonObject(),
secondLevelKey = children[2].toCFJsonObject()
)
} else if (this is ResourceNode.RefNode) {
CFRefFunction(children[1].toCFJsonObject())
} else if (this is ResourceNode.RefPropertyNode) {
CFGetAttributeFunction(
logicalNameOfResource = children[1].toCFJsonObject(),
attributeName = children[2].toCFJsonObject()
)
} else if (this is ResourceNode.VariableNode) {
CFRefFunction(children[0].toCFJsonObject())
} else {
throw IllegalArgumentException("Unknown resource node type: ${ this::class.simpleName }")
}
/**
* Converts the kohesive references to CloudFormation-functions-aware sub-trees.
*/
class CloudFormationFunctionsProcessor : TemplateStringProcessor {
companion object {
val JSON = jacksonObjectMapper() // TODO: fancy options?
}
override fun scope(templateNode: ObjectNode) = listOf(
templateNode.get(Template::Resources.name) as? ObjectNode,
templateNode.get(Template::Outputs.name) as? ObjectNode
).filterNotNull()
override fun process(context: IacContext, textNode: TextNodeInParent) {
if (textNode.text().contains("{{kohesive")) {
explodeReference(textNode.text()).let { explodedRefs ->
val valueToReplaceWith = if (explodedRefs.size == 1) {
explodedRefs[0].toCFJsonObject()
} else if (explodedRefs.size > 1) {
CFJoinFunction(explodedRefs.map { it.toCFJsonObject() })
} else {
null
}
valueToReplaceWith?.let {
textNode.replaceWith(JSON.valueToTree<JsonNode>(it))
}
}
}
}
} | mit | 8cff7fe5509699a82aa914ff0b3b2d90 | 40.1 | 93 | 0.696106 | 4.431433 | false | false | false | false |
crispab/codekvast | product/server/intake/src/main/kotlin/io/codekvast/intake/agent/service/impl/AgentStateManagerImpl.kt | 1 | 4876 | /*
* Copyright (c) 2015-2022 Hallin Information Technology AB
*
* 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 io.codekvast.intake.agent.service.impl
import io.codekvast.common.customer.CustomerData
import io.codekvast.common.customer.CustomerService
import io.codekvast.common.logging.LoggerDelegate
import io.codekvast.common.messaging.EventService
import io.codekvast.common.messaging.model.AgentPolledEvent
import io.codekvast.common.thread.NamedThreadTemplate
import io.codekvast.intake.bootstrap.CodekvastIntakeSettings
import io.codekvast.intake.metrics.IntakeMetricsService
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import org.springframework.transaction.annotation.Transactional
import java.time.Instant
/** @author [email protected]
*/
@Component
class AgentStateManagerImpl(
private val settings: CodekvastIntakeSettings,
private val customerService: CustomerService,
private val eventService: EventService,
private val intakeDAO: IntakeDAO,
private val intakeMetricsService: IntakeMetricsService
) : AgentStateManager {
val logger by LoggerDelegate()
@Scheduled(
initialDelayString = "\${codekvast.intake.agent-statistics.delay.seconds:60}000",
fixedRateString = "\${codekvast.intake.agent-statistics.interval.seconds:60}000"
)
@Transactional(readOnly = true)
fun countAgents() {
NamedThreadTemplate().doInNamedThread("metrics") {
val statistics =
intakeDAO.getAgentStatistics(Instant.now().minusSeconds(10))
logger.debug("Collected {}", statistics)
intakeMetricsService.gaugeAgents(statistics)
}
}
@Transactional(rollbackFor = [Exception::class])
override fun updateAgentState(
customerData: CustomerData, jvmUuid: String, appName: String, environment: String
): Boolean {
intakeDAO.writeLockAgentStateForCustomer(customerData.customerId)
return doUpdateAgentState(customerData, jvmUuid, appName, environment)
}
private fun doUpdateAgentState(
customerData: CustomerData, jvmUuid: String, appName: String, environment: String
): Boolean {
val customerId = customerData.customerId
val now = Instant.now()
intakeDAO.markDeadAgentsAsGarbage(
customerId, jvmUuid, now.minusSeconds(settings.fileImportIntervalSeconds * 2L)
)
intakeDAO.setAgentTimestamps(
customerId,
jvmUuid,
now,
now.plusSeconds(customerData.pricePlan.pollIntervalSeconds.toLong())
)
val cd = customerService.registerAgentPoll(customerData, now)
val numOtherEnabledAliveAgents: Int =
intakeDAO.getNumOtherEnabledAliveAgents(customerId, jvmUuid, now.minusSeconds(10))
val event = AgentPolledEvent.builder()
.afterTrialPeriod(cd.isTrialPeriodExpired(now))
.appName(appName)
.customerId(customerId)
.disabledEnvironment(!intakeDAO.isEnvironmentEnabled(customerId, jvmUuid))
.environment(environment)
.jvmUuid(jvmUuid)
.polledAt(now)
.tooManyLiveAgents(
numOtherEnabledAliveAgents >= customerData.pricePlan.maxNumberOfAgents
)
.trialPeriodEndsAt(cd.trialPeriodEndsAt)
.build()
logger.debug(
"Agent {} is {}",
jvmUuid,
if (event.isAgentEnabled) "enabled" else "disabled"
)
eventService.send(event)
intakeDAO.updateAgentEnabledState(customerId, jvmUuid, event.isAgentEnabled)
return event.isAgentEnabled
}
} | mit | 4ee609acd3efd079df401cb5ba8bb911 | 42.544643 | 98 | 0.699959 | 4.895582 | false | false | false | false |
Raizlabs/DBFlow | tests/src/androidTest/java/com/dbflow5/models/IndexModels.kt | 1 | 924 | package com.dbflow5.models
import com.dbflow5.TestDatabase
import com.dbflow5.annotation.Column
import com.dbflow5.annotation.Index
import com.dbflow5.annotation.IndexGroup
import com.dbflow5.annotation.PrimaryKey
import com.dbflow5.annotation.Table
import java.util.*
/**
* Description:
*/
@Table(database = TestDatabase::class,
indexGroups = [
IndexGroup(number = 1, name = "firstIndex"),
IndexGroup(number = 2, name = "secondIndex"),
IndexGroup(number = 3, name = "thirdIndex"),
])
class IndexModel {
@Index(indexGroups = [1, 2, 3])
@PrimaryKey
var id: Int = 0
@Index(indexGroups = [1])
@Column
var first_name: String? = null
@Index(indexGroups = [2])
@Column
var last_name: String? = null
@Index(indexGroups = [3])
@Column
var created_date: Date? = null
@Index(indexGroups = [2, 3])
@Column
var isPro: Boolean = false
} | mit | 47ca022afa5b17315723f4e11cec9a5a | 21.560976 | 53 | 0.658009 | 3.609375 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/decompiler/stubBuilder/AbstractLoadJavaClsStubTest.kt | 1 | 4651 | // 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.decompiler.stubBuilder
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiManager
import com.intellij.psi.stubs.StubElement
import com.intellij.testFramework.BinaryLightVirtualFile
import com.intellij.testFramework.LightVirtualFile
import com.intellij.util.PathUtil
import com.intellij.util.indexing.FileContentImpl
import org.jetbrains.kotlin.analysis.decompiler.psi.KotlinDecompiledFileViewProvider
import org.jetbrains.kotlin.analysis.decompiler.psi.file.KtClsFile
import org.jetbrains.kotlin.analysis.decompiler.stub.file.KotlinClsStubBuilder
import org.jetbrains.kotlin.codegen.ClassBuilderFactories
import org.jetbrains.kotlin.codegen.KotlinCodegenFacade
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.languageVersionSettings
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.stubs.AbstractStubBuilderTest
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.stubs.elements.KtFileStubBuilder
import org.junit.Assert
import java.io.File
abstract class AbstractLoadJavaClsStubTest : KotlinLightCodeInsightFixtureTestCase() {
@Throws(Exception::class)
protected fun doTestCompiledKotlin(absoluteTestDataPath: String) {
myFixture.configureByFile(File(absoluteTestDataPath))
val ktFile = myFixture.file as KtFile
val analysisResult = ktFile.analyzeWithAllCompilerChecks()
val configuration = CompilerConfiguration().apply { languageVersionSettings = file.languageVersionSettings }
val state = GenerationState.Builder(
project, ClassBuilderFactories.BINARIES, analysisResult.moduleDescriptor,
analysisResult.bindingContext, listOf(ktFile), configuration
).build()
try {
KotlinCodegenFacade.compileCorrectFiles(state)
val outputFiles = state.factory
val lightFiles = HashMap<String, VirtualFile>()
fun addDirectory(filePath: String) {
assert(filePath.startsWith('/'))
lightFiles.getOrPut(filePath) {
object : LightVirtualFile(filePath) {
override fun isDirectory() = true
override fun getParent() = lightFiles[PathUtil.getParentPath(filePath)]
override fun findChild(name: String) = lightFiles["$filePath/$name"]
}
}
}
fun addFile(filePath: String, content: ByteArray) {
assert(filePath.startsWith('/'))
val pathSegments = filePath.drop(1).split('/')
repeat(pathSegments.size) { i ->
addDirectory("/" + pathSegments.take(i).joinToString("/"))
}
lightFiles[filePath] = object : BinaryLightVirtualFile(filePath, content) {
override fun getParent() = lightFiles[PathUtil.getParentPath(filePath)]
}
}
addDirectory("/")
for (file in outputFiles.asList()) {
if (!file.relativePath.endsWith(".class")) {
continue
}
addFile("/" + file.relativePath, file.asByteArray())
}
val psiManager = PsiManager.getInstance(project)
for (lightFile in lightFiles.values) {
if (lightFile.isDirectory) {
continue
}
val fileContent = FileContentImpl.createByFile(lightFile)
val stubTreeFromCls = KotlinClsStubBuilder().buildFileStub(fileContent) ?: continue
val decompiledProvider = KotlinDecompiledFileViewProvider(psiManager, lightFile, false, ::KtClsFile)
val stubsFromDeserializedDescriptors = KtFileStubBuilder().buildStubTree(KtClsFile(decompiledProvider))
Assert.assertEquals(
"File: ${lightFile.name}",
stubsFromDeserializedDescriptors.serializeToString(),
stubTreeFromCls.serializeToString()
)
}
} finally {
state.destroy()
}
}
} | apache-2.0 | 2724c5b8e6ad9af5a38690bae2fa61e6 | 41.678899 | 158 | 0.673619 | 5.55675 | false | true | false | false |
spotify/heroic | heroic-core/src/main/java/com/spotify/heroic/shell/task/parameters/SuggestTagParameters.kt | 1 | 1726 | /*
* Copyright (c) 2019 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.spotify.heroic.shell.task.parameters
import com.spotify.heroic.common.OptionalLimit
import org.kohsuke.args4j.Argument
import org.kohsuke.args4j.Option
import java.util.*
internal class SuggestTagParameters : QueryParamsBase() {
@Option(name = "-g", aliases = ["--group"], usage = "Backend group to use", metaVar = "<group>")
val group = Optional.empty<String>()
@Option(name = "-k", aliases = ["--key"], usage = "Provide key context for suggestion")
val key = Optional.empty<String>()
@Option(name = "-v", aliases = ["--value"], usage = "Provide value context for suggestion")
val value = Optional.empty<String>()
@Option(name = "--limit", aliases = ["--limit"], usage = "Limit the number of printed entries")
override val limit: OptionalLimit = OptionalLimit.empty()
@Argument
override val query = ArrayList<String>()
}
| apache-2.0 | 1571e5d1116489706310852d84f2b0be | 38.227273 | 100 | 0.714368 | 4.149038 | false | false | false | false |
androidx/androidx | compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/lookahead/LookaheadWithFlowRowDemo.kt | 3 | 9359 | /*
* 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.animation.demos.lookahead
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.LookaheadLayout
import androidx.compose.ui.layout.Placeable
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import kotlin.math.max
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun LookaheadWithFlowRowDemo() {
Column(
modifier = Modifier.padding(10.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
var isHorizontal by remember { mutableStateOf(true) }
Column(
Modifier
.background(Color(0xfffdedac), RoundedCornerShape(10))
.padding(10.dp)
) {
Text("LookaheadLayout + Modifier.animateBounds")
LookaheadLayout(
measurePolicy = lookaheadMeasurePolicy,
content = {
MyFlowRow(
modifier = Modifier
.height(200.dp)
.fillMaxWidth()
.wrapContentSize(Alignment.CenterStart)
) {
Box(
Modifier
.height(50.dp)
.animateBounds(
Modifier.fillMaxWidth(if (isHorizontal) 0.4f else 1f)
)
.background(colors[0], RoundedCornerShape(10))
)
Box(
Modifier
.height(50.dp)
.animateBounds(
Modifier.fillMaxWidth(if (isHorizontal) 0.2f else 0.4f)
)
.background(colors[1], RoundedCornerShape(10))
)
Box(
Modifier
.height(50.dp)
.animateBounds(
Modifier.fillMaxWidth(if (isHorizontal) 0.2f else 0.4f)
)
.background(colors[2], RoundedCornerShape(10))
)
}
Box(Modifier.size(if (isHorizontal) 200.dp else 100.dp))
})
}
Spacer(Modifier.size(50.dp))
Column(
Modifier
.background(Color(0xfffdedac), RoundedCornerShape(10))
.padding(10.dp)
) {
Text("Animating Width")
MyFlowRow(
modifier = Modifier
.height(200.dp)
.fillMaxWidth()
.wrapContentSize(Alignment.CenterStart)
) {
Box(
Modifier
.height(50.dp)
.fillMaxWidth(animateFloatAsState(if (isHorizontal) 0.4f else 1f).value)
.background(colors[0], RoundedCornerShape(10))
)
Box(
Modifier
.height(50.dp)
.fillMaxWidth(animateFloatAsState(if (isHorizontal) 0.2f else 0.4f).value)
.background(colors[1], RoundedCornerShape(10))
)
Box(
Modifier
.height(50.dp)
.fillMaxWidth(animateFloatAsState(if (isHorizontal) 0.2f else 0.4f).value)
.background(colors[2], RoundedCornerShape(10))
)
}
}
Button(modifier = Modifier.padding(top = 20.dp, bottom = 20.dp),
onClick = { isHorizontal = !isHorizontal }) {
Text("Toggle")
}
}
}
@Composable
internal fun MyFlowRow(
modifier: Modifier = Modifier,
mainAxisSpacing: Dp = 20.dp,
crossAxisSpacing: Dp = 20.dp,
content: @Composable () -> Unit
) {
Layout(modifier = modifier, content = content) { measurables, constraints ->
val sequences = mutableListOf<List<Placeable>>()
val crossAxisSizes = mutableListOf<Int>()
val crossAxisPositions = mutableListOf<Int>()
var mainAxisSpace = 0
var crossAxisSpace = 0
val currentSequence = mutableListOf<Placeable>()
var currentMainAxisSize = 0
var currentCrossAxisSize = 0
// Return whether the placeable can be added to the current sequence.
fun canAddToCurrentSequence(placeable: Placeable) =
currentSequence.isEmpty() || currentMainAxisSize + mainAxisSpacing.roundToPx() +
placeable.width <= constraints.maxWidth
// Store current sequence information and start a new sequence.
fun startNewSequence() {
if (sequences.isNotEmpty()) {
crossAxisSpace += crossAxisSpacing.roundToPx()
}
sequences += currentSequence.toList()
crossAxisSizes += currentCrossAxisSize
crossAxisPositions += crossAxisSpace
crossAxisSpace += currentCrossAxisSize
mainAxisSpace = max(mainAxisSpace, currentMainAxisSize)
currentSequence.clear()
currentMainAxisSize = 0
currentCrossAxisSize = 0
}
for (measurable in measurables) {
// Ask the child for its preferred size.
val placeable = measurable.measure(constraints)
// Start a new sequence if there is not enough space.
if (!canAddToCurrentSequence(placeable)) startNewSequence()
// Add the child to the current sequence.
if (currentSequence.isNotEmpty()) {
currentMainAxisSize += mainAxisSpacing.roundToPx()
}
currentSequence.add(placeable)
currentMainAxisSize += placeable.width
currentCrossAxisSize = max(currentCrossAxisSize, placeable.height)
}
if (currentSequence.isNotEmpty()) startNewSequence()
val mainAxisLayoutSize = max(mainAxisSpace, constraints.minWidth)
val crossAxisLayoutSize = max(crossAxisSpace, constraints.minHeight)
val layoutWidth = mainAxisLayoutSize
val layoutHeight = crossAxisLayoutSize
layout(layoutWidth, layoutHeight) {
sequences.forEachIndexed { i, placeables ->
val childrenMainAxisSizes = IntArray(placeables.size) { j ->
placeables[j].width +
if (j < placeables.lastIndex) mainAxisSpacing.roundToPx() else 0
}
val arrangement = Arrangement.Start
// TODO(soboleva): rtl support
// Handle vertical direction
val mainAxisPositions = IntArray(childrenMainAxisSizes.size) { 0 }
with(arrangement) {
arrange(
mainAxisLayoutSize,
childrenMainAxisSizes,
LayoutDirection.Ltr,
mainAxisPositions
)
}
placeables.forEachIndexed { j, placeable ->
placeable.place(
x = mainAxisPositions[j],
y = crossAxisPositions[i]
)
}
}
}
}
}
private val colors = listOf(
Color(0xffff6f69),
Color(0xffffcc5c),
Color(0xff2a9d84),
Color(0xff264653)
) | apache-2.0 | 6717632b5aca85ec516a10f07b4a87c1 | 37.204082 | 98 | 0.568971 | 5.587463 | false | false | false | false |
gorrotowi/BitsoPriceChecker | app/src/main/java/com/chilangolabs/bitsopricechecker/network/Api.kt | 1 | 5239 | package com.chilangolabs.bitsopricechecker.network
import android.content.Context
import android.util.Log
import com.chilangolabs.bitsopricechecker.models.ChartResponse
import com.chilangolabs.bitsopricechecker.models.LastTradesResponse
import com.chilangolabs.bitsopricechecker.models.OrdersResponse
import com.chilangolabs.bitsopricechecker.models.TickerResponse
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
/**
* Created by Gorro on 05/05/17.
*/
class Api {
companion object factory {
var retrofit: Retrofit? = null
var retrofitChart: Retrofit? = null
lateinit var endpoints: Endpoints
lateinit var endpointsChart: EndpointsChart
}
fun getLogginInterceptor(): OkHttpClient? {
val logginInterceptor = HttpLoggingInterceptor()
logginInterceptor.level = HttpLoggingInterceptor.Level.BODY
val builder = OkHttpClient.Builder()
builder.interceptors().add(logginInterceptor)
return builder.build()
}
fun getClient(): Retrofit? {
when {
Api.retrofit == null -> {
retrofit = Retrofit.Builder()
.baseUrl("https://api.bitso.com/")
.addConverterFactory(GsonConverterFactory.create())
.client(getLogginInterceptor())
.build()
}
}
return retrofit
}
fun getClientChart(): Retrofit? {
when {
Api.retrofitChart == null -> {
retrofitChart = Retrofit.Builder()
.baseUrl("https://apiv2.bitcoinaverage.com/")
.addConverterFactory(GsonConverterFactory.create())
.client(getLogginInterceptor())
.build()
}
}
return retrofitChart
}
fun init() {
endpoints = getClient()?.create(Endpoints::class.java)!!
endpointsChart = getClientChart()?.create(EndpointsChart::class.java)!!
}
fun getTicker(success: (response: TickerResponse) -> Unit, fail: (error: Throwable) -> Unit) {
val call: Call<TickerResponse> = endpoints.getTickers()
call.enqueue(object : Callback<TickerResponse> {
override fun onResponse(call: Call<TickerResponse>?, response: Response<TickerResponse>?) {
if (response?.code() == 200) {
success(response.body())
} else {
fail(Throwable("Intenta nuevamente"))
}
}
override fun onFailure(call: Call<TickerResponse>?, t: Throwable?) {
fail(t ?: Throwable("Error, intenta nuevamente"))
}
})
}
fun getBooksOrder(book: String, success: (response: OrdersResponse) -> Unit, fail: (error: Throwable) -> Unit) {
val call: Call<OrdersResponse> = endpoints.getBookOrder(book)
call.enqueue(object : Callback<OrdersResponse> {
override fun onResponse(call: Call<OrdersResponse>?, response: Response<OrdersResponse>?) {
if (response?.code() == 200) {
success(response.body())
} else {
fail(Throwable("Intenta nuevamente"))
}
}
override fun onFailure(call: Call<OrdersResponse>?, t: Throwable?) {
fail(t ?: Throwable("Error, intenta nuevamente"))
}
})
}
fun getLastOrdersBook(book: String, success: (response: LastTradesResponse) -> Unit, fail: (error: Throwable) -> Unit) {
val call: Call<LastTradesResponse> = endpoints.getLastTrades(book)
call.enqueue(object : Callback<LastTradesResponse> {
override fun onResponse(call: Call<LastTradesResponse>?, response: Response<LastTradesResponse>?) {
if (response?.code() == 200) {
success(response.body())
} else {
fail(Throwable("Intenta nuevamente"))
}
}
override fun onFailure(call: Call<LastTradesResponse>?, t: Throwable?) {
fail(t ?: Throwable("Error, intenta nuevamente"))
}
})
}
fun getChartInfo(symbol: String, success: (response: List<ChartResponse>) -> Unit, fail: (error: Throwable) -> Unit) {
val call: Call<List<ChartResponse>> = endpointsChart.getChart(symbol)
call.enqueue(object : Callback<List<ChartResponse>> {
override fun onResponse(call: Call<List<ChartResponse>>?, response: Response<List<ChartResponse>>?) {
if (response?.code() == 200) {
Log.e("Chart $symbol", "OK!!!!")
success(response.body())
} else {
fail(Throwable("Intenta nuevamente"))
}
}
override fun onFailure(call: Call<List<ChartResponse>>?, t: Throwable?) {
fail(t ?: Throwable("Error, intenta nuevamente"))
}
})
}
}
| apache-2.0 | 0851ec646c427ee4722e4222899342af | 34.639456 | 124 | 0.583508 | 5.176877 | false | false | false | false |
google/playhvz | Android/ghvzApp/app/src/main/java/com/app/playhvz/screens/gamelist/GameListAdapter.kt | 1 | 3053 | /*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.app.playhvz.screens.gamelist
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.app.playhvz.R
import com.app.playhvz.firebase.classmodels.Game
class GameListAdapter(
private var items: List<Any>,
val context: Context,
val navigator: IFragmentNavigator
) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
interface IFragmentNavigator {
fun onGameClicked(gameId: String)
}
enum class ViewType {
HEADER,
GAME,
JOIN_BUTTON
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
if (viewType == ViewType.GAME.ordinal) {
return GameViewHolder(
LayoutInflater.from(context).inflate(
R.layout.list_item_game_list_game,
parent,
false
)
)
} else if (viewType == ViewType.JOIN_BUTTON.ordinal) {
return JoinButtonViewHolder(
LayoutInflater.from(context).inflate(
R.layout.list_item_game_list_join_button,
parent,
false
)
)
}
return HeaderViewHolder(
LayoutInflater.from(context).inflate(
R.layout.list_item_game_list_header,
parent,
false
)
)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is GameViewHolder -> {
holder.onBind(items[position] as Game, navigator)
}
is JoinButtonViewHolder -> {
holder.onBind(R.string.game_list_join_game_button, items[position] as View.OnClickListener)
}
else -> (holder as HeaderViewHolder).onBind(items[position] as String)
}
}
override fun getItemCount(): Int {
return items.size
}
override fun getItemViewType(position: Int): Int {
if (items[position] is Game) {
return ViewType.GAME.ordinal
} else if (items[position] is View.OnClickListener) {
return ViewType.JOIN_BUTTON.ordinal
}
return ViewType.HEADER.ordinal
}
fun setData(data: List<Any>) {
items = data
}
} | apache-2.0 | 19df933a8a370b8bac08c33b2235ba8c | 29.848485 | 107 | 0.614478 | 4.71142 | false | false | false | false |
nebula-plugins/lock-experimental | src/main/kotlin/com/netflix/nebula/lock/groovy/GroovyVariableExtractionVisitor.kt | 1 | 1013 | package com.netflix.nebula.lock.groovy
import org.codehaus.groovy.ast.ClassCodeVisitorSupport
import org.codehaus.groovy.ast.expr.BinaryExpression
import org.codehaus.groovy.ast.expr.PropertyExpression
import org.codehaus.groovy.ast.expr.VariableExpression
class GroovyVariableExtractionVisitor : ClassCodeVisitorSupport() {
override fun getSourceUnit() = null
val variables = mutableMapOf<String, String>()
override fun visitBinaryExpression(expression: BinaryExpression?) {
val left = expression?.leftExpression
val right = expression?.rightExpression
if (left != null && right != null) {
when (left) {
is PropertyExpression -> {
val key = "${left.objectExpression.text}.${left.propertyAsString}"
variables.put(key, right.text)
}
is VariableExpression -> variables.put(left.text, right.text)
}
}
super.visitBinaryExpression(expression)
}
}
| apache-2.0 | 37453e15605dd7a933db35ccee91a1a9 | 37.961538 | 86 | 0.666338 | 4.89372 | false | false | false | false |
GunoH/intellij-community | java/java-tests/testSrc/com/intellij/util/indexing/PerFileElementTypeModificationTrackerBenchmark.kt | 2 | 4038 | // 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.util.indexing
import com.intellij.lang.java.JavaParserDefinition
import com.intellij.openapi.application.runWriteAction
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.stubs.StubIndex
import com.intellij.psi.stubs.StubIndexEx
import com.intellij.psi.stubs.StubIndexImpl
import com.intellij.psi.stubs.StubUpdatingIndex
import com.intellij.psi.tree.StubFileElementType
import com.intellij.testFramework.HeavyPlatformTestCase
import com.intellij.testFramework.writeChild
import com.intellij.util.io.write
import org.junit.Ignore
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.nio.file.Paths
/**
* set "stub.index.per.file.element.type.modification.tracker.precise.check.threshold" system
* property to ~1000 before executing and comment out @Ignore
*/
@RunWith(JUnit4::class)
class PerFileElementTypeModificationTrackerBenchmark : HeavyPlatformTestCase() {
@Test
@Ignore
fun benchmark() {
var lastModCount = getModCount(JavaParserDefinition.JAVA_FILE)
fun assertModCountIncreasedAtLeast(minInc: Int) {
val modCount = getModCount(JavaParserDefinition.JAVA_FILE)
assert(lastModCount + minInc <= modCount ||
StubIndexImpl.PER_FILE_ELEMENT_TYPE_STUB_CHANGE_TRACKING_SOURCE ==
StubIndexImpl.PerFileElementTypeStubChangeTrackingSource.Disabled
) {
"last $lastModCount + minInc $minInc <= current $modCount"
}
lastModCount = modCount
}
fun assertModCountIsSame() {
val modCount = getModCount(JavaParserDefinition.JAVA_FILE)
assert(lastModCount == modCount ||
StubIndexImpl.PER_FILE_ELEMENT_TYPE_STUB_CHANGE_TRACKING_SOURCE ==
StubIndexImpl.PerFileElementTypeStubChangeTrackingSource.Disabled
) {
"last $lastModCount == current $modCount"
}
}
val srcDir = createTestProjectStructure()
val pkg = runWriteAction {
srcDir.createChildDirectory(this, "pkg")
}
val filesRange = 1..500
runWriteAction {
for (i in filesRange) {
pkg.writeChild("C$i.java", """
class C$i {
String s$i;
}
""".trimIndent())
}
}
srcDir.refresh(false, true)
assertModCountIncreasedAtLeast(1)
val durations = mutableListOf<Double>()
repeat(25) {
val startMs = System.currentTimeMillis()
for (i in filesRange) {
Paths.get(pkg.path + "/C$i.java").write("""
class C$i {
int i$i;
}
""".trimIndent())
}
srcDir.refresh(false, true)
assertModCountIncreasedAtLeast(1)
ensureIndexUpToDate()
for (i in filesRange) {
Paths.get(pkg.path + "/C$i.java").write("""
class C$i {
String s$i;
}
""".trimIndent())
}
srcDir.refresh(false, true)
assertModCountIncreasedAtLeast(1)
ensureIndexUpToDate()
runWriteAction { pkg.rename(this, "pkg2") }
srcDir.refresh(false, true)
assertModCountIsSame()
ensureIndexUpToDate()
runWriteAction { pkg.rename(this, "pkg") }
srcDir.refresh(false, true)
assertModCountIsSame()
ensureIndexUpToDate()
val finishMs = System.currentTimeMillis()
durations += (finishMs - startMs).toDouble() / 1e3
}
System.out.println("src = ${StubIndexImpl.PER_FILE_ELEMENT_TYPE_STUB_CHANGE_TRACKING_SOURCE}, mean = ${"%.4f".format(durations.sum() / durations.size)} s, data = ${durations}" )
}
private fun ensureIndexUpToDate() {
FileBasedIndex.getInstance().ensureUpToDate(StubUpdatingIndex.INDEX_ID, project, GlobalSearchScope.allScope(project))
}
private fun getModCount(elementType: StubFileElementType<*>) =
(StubIndex.getInstance() as StubIndexEx)
.getPerFileElementTypeModificationTracker(elementType).modificationCount
} | apache-2.0 | 053810ff77205cdce3862b18738b26d3 | 33.228814 | 181 | 0.685488 | 4.384365 | false | true | false | false |
GunoH/intellij-community | build/launch/src/com/intellij/tools/launch/impl/ClassPathBuilder.kt | 7 | 4331 | package com.intellij.tools.launch.impl
import com.intellij.execution.CommandLineWrapperUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.tools.launch.ModulesProvider
import com.intellij.tools.launch.PathsProvider
import com.intellij.util.SystemProperties
import org.jetbrains.jps.model.JpsElementFactory
import org.jetbrains.jps.model.java.JpsJavaClasspathKind
import org.jetbrains.jps.model.java.JpsJavaExtensionService
import org.jetbrains.jps.model.module.JpsModule
import org.jetbrains.jps.model.module.JpsModuleDependency
import org.jetbrains.jps.model.serialization.JpsModelSerializationDataService
import org.jetbrains.jps.model.serialization.JpsProjectLoader
import java.io.File
import java.util.*
import java.util.logging.Logger
class ClassPathBuilder(private val paths: PathsProvider, private val modules: ModulesProvider) {
private val logger = Logger.getLogger(ClassPathBuilder::class.java.name)
companion object {
fun createClassPathArgFile(paths: PathsProvider, classpath: List<String>): File {
val launcherFolder = paths.logFolder
if (!launcherFolder.exists()) {
launcherFolder.mkdirs()
}
val classPathArgFile = launcherFolder.resolve("Launcher_${UUID.randomUUID().toString().take(4)}.classpath")
CommandLineWrapperUtil.writeArgumentsFile(classPathArgFile, listOf("-classpath", classpath.distinct().joinToString(File.pathSeparator)), Charsets.UTF_8)
return classPathArgFile
}
}
private val model = JpsElementFactory.getInstance().createModel() ?: throw Exception("Couldn't create JpsModel")
fun build(logClasspath: Boolean): File {
val pathVariablesConfiguration = JpsModelSerializationDataService.getOrCreatePathVariablesConfiguration(model.global)
val m2HomePath = File(SystemProperties.getUserHome())
.resolve(".m2")
.resolve("repository")
pathVariablesConfiguration.addPathVariable("MAVEN_REPOSITORY", m2HomePath.canonicalPath)
val pathVariables = JpsModelSerializationDataService.computeAllPathVariables(model.global)
JpsProjectLoader.loadProject(model.project, pathVariables, paths.sourcesRootFolder.toPath())
val productionOutput = paths.outputRootFolder.resolve("production")
if (!productionOutput.isDirectory) {
error("Production classes output directory is missing: $productionOutput")
}
JpsJavaExtensionService.getInstance().getProjectExtension(model.project)!!.outputUrl =
"file://${FileUtil.toSystemIndependentName(paths.outputRootFolder.path)}"
val modulesList = arrayListOf<String>()
modulesList.add("intellij.platform.boot")
modulesList.add(modules.mainModule)
modulesList.addAll(modules.additionalModules)
modulesList.add("intellij.configurationScript")
return createClassPathArgFileForModules(modulesList, logClasspath)
}
private fun createClassPathArgFileForModules(modulesList: List<String>, logClasspath: Boolean): File {
val classpath = mutableListOf<String>()
for (moduleName in modulesList) {
val module = model.project.modules.singleOrNull { it.name == moduleName }
?: throw Exception("Module $moduleName not found")
if (isModuleExcluded(module)) continue
classpath.addAll(getClasspathForModule(module))
}
// Uncomment for big debug output
// seeing as client classpath gets logged anyway, there's no need to comment this out
if (logClasspath) {
logger.info("Created classpath:")
for (path in classpath.distinct().sorted()) {
logger.info(" $path")
}
logger.info("-- END")
} else {
logger.warning("Verbose classpath logging is disabled, set logClasspath to true to see it.")
}
return createClassPathArgFile(paths, classpath)
}
private fun getClasspathForModule(module: JpsModule): List<String> {
return JpsJavaExtensionService
.dependencies(module)
.recursively()
.satisfying { if (it is JpsModuleDependency) !isModuleExcluded(it.module) else true }
.includedIn(JpsJavaClasspathKind.runtime(modules.includeTestDependencies))
.classes().roots.filter { it.exists() }.map { it.path }.toList()
}
private fun isModuleExcluded(module: JpsModule?): Boolean {
if (module == null) return true
return modules.excludedModules.contains(module.name)
}
} | apache-2.0 | 2cb6758332a21a6a12d58193012fc5f3 | 41.058252 | 158 | 0.757331 | 4.882751 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/sealedSubClassToObject/ConvertSealedSubClassToObjectFix.kt | 1 | 5589 | // 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.sealedSubClassToObject
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.lang.Language
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiElement
import com.intellij.psi.SmartPointerManager
import com.intellij.psi.SmartPsiElementPointer
import com.intellij.psi.impl.source.tree.JavaElementType
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgressIfEdt
import org.jetbrains.kotlin.idea.intentions.ConvertSecondaryConstructorToPrimaryIntention
import com.intellij.openapi.application.runWriteAction
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.buildExpression
import org.jetbrains.kotlin.psi.createDeclarationByPattern
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
class ConvertSealedSubClassToObjectFix : LocalQuickFix {
override fun getFamilyName() = KotlinBundle.message("convert.sealed.subclass.to.object.fix.family.name")
override fun startInWriteAction(): Boolean = false
companion object {
val JAVA_LANG = Language.findLanguageByID("JAVA")
val KOTLIN_LANG = Language.findLanguageByID("kotlin")
}
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val klass = descriptor.psiElement.getParentOfType<KtClass>(false) ?: return
val ktClassSmartPointer: SmartPsiElementPointer<KtClass> = SmartPointerManager.createPointer(klass)
changeInstances(ktClassSmartPointer)
changeDeclaration(ktClassSmartPointer)
}
/**
* Changes declaration of class to object.
*/
private fun changeDeclaration(pointer: SmartPsiElementPointer<KtClass>) {
runWriteAction {
val element = pointer.element ?: return@runWriteAction
val factory = KtPsiFactory(element)
element.changeToObject(factory)
element.transformToObject(factory)
}
}
private fun KtClass.changeToObject(factory: KtPsiFactory) {
secondaryConstructors.forEach { ConvertSecondaryConstructorToPrimaryIntention().applyTo(it, null) }
primaryConstructor?.delete()
getClassOrInterfaceKeyword()?.replace(
if (!isData() && languageVersionSettings.supportsFeature(LanguageFeature.DataObjects))
factory.createDeclarationByPattern("${KtTokens.DATA_KEYWORD.value} ${KtTokens.OBJECT_KEYWORD.value}")
else
factory.createExpression(KtTokens.OBJECT_KEYWORD.value)
)
}
private fun KtClass.transformToObject(factory: KtPsiFactory) {
replace(factory.createObject(text))
}
/**
* Replace instantiations of the class with links to the singleton instance of the object.
*/
private fun changeInstances(pointer: SmartPsiElementPointer<KtClass>) {
mapReferencesByLanguage(pointer)
.apply {
runWriteAction {
val ktClass = pointer.element ?: return@runWriteAction
replaceKotlin(ktClass)
replaceJava(ktClass)
}
}
}
/**
* Map references to this class by language
*/
private fun mapReferencesByLanguage(pointer: SmartPsiElementPointer<KtClass>): Map<Language, List<PsiElement>> =
pointer.project.runSynchronouslyWithProgressIfEdt(KotlinBundle.message("progress.looking.up.sealed.subclass.usage"), true) {
pointer.element?.let { ktClass ->
ReferencesSearch.search(ktClass).groupBy({ it.element.language }, { it.element.parent })
} ?: emptyMap()
} ?: emptyMap()
/**
* Replace Kotlin instantiations to a straightforward call to the singleton.
*/
private fun Map<Language, List<PsiElement>>.replaceKotlin(klass: KtClass) {
val list = this[KOTLIN_LANG] ?: return
val singletonCall = KtPsiFactory(klass).buildExpression { appendName(klass.nameAsSafeName) }
list.filter { it.node.elementType == KtNodeTypes.CALL_EXPRESSION }
.forEach { it.replace(singletonCall) }
}
/**
* Replace Java instantiations to an instance of the object, unless it is the only thing
* done in the statement, in which IDEA will consider wrong, so I delete the line.
*/
private fun Map<Language, List<PsiElement>>.replaceJava(klass: KtClass) {
val list = this[JAVA_LANG] ?: return
val first = list.firstOrNull() ?: return
val elementFactory = JavaPsiFacade.getElementFactory(klass.project)
val javaSingletonCall = elementFactory.createExpressionFromText("${klass.name}.INSTANCE", first)
list.filter { it.node.elementType == JavaElementType.NEW_EXPRESSION }
.forEach {
when (it.parent.node.elementType) {
JavaElementType.EXPRESSION_STATEMENT -> it.delete()
else -> it.replace(javaSingletonCall)
}
}
}
} | apache-2.0 | b2e405a3cf58cfb85701ad3d1097eca9 | 42.333333 | 158 | 0.712113 | 5.099453 | false | false | false | false |
dpisarenko/econsim-tr01 | src/main/java/cc/altruix/econsimtr01/ch0202/Sim1a.kt | 1 | 2755 | /*
* Copyright 2012-2016 Dmitri Pisarenko
*
* WWW: http://altruix.cc
* E-Mail: [email protected]
* Skype: dp118m (voice calls must be scheduled in advance)
*
* Physical address:
*
* 4-i Rostovskii pereulok 2/1/20
* 119121 Moscow
* Russian Federation
*
* This file is part of econsim-tr01.
*
* econsim-tr01 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.
*
* econsim-tr01 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 econsim-tr01. If not, see <http://www.gnu.org/licenses/>.
*
*/
package cc.altruix.econsimtr01.ch0202
import cc.altruix.econsimtr01.*
import cc.altruix.econsimtr01.ch0201.OncePerWeek
import org.joda.time.DateTime
import java.util.*
/**
* Created by pisarenko on 04.05.2016.
*/
class Sim1a(logTarget:StringBuilder,
flows:MutableList<ResourceFlow>,
simParametersProvider: Sim1ParametersProvider,
val resultsStorage:MutableMap<DateTime, SimResRow<Sim1aResultRowField>>) :
Sim1(logTarget, flows, simParametersProvider) {
override fun createAgents(): List<IAgent> {
val agents = super.createAgents()
val plFlows = LinkedList<PlFlow>()
agents.forEach { agt ->
if (agt is DefaultAgent) {
agt.actions
.filter { it is PlFlow }
.forEach { plFlows.add(it as PlFlow) }
}
}
plFlows.forEach { flow ->
flow.agents = agents
flow.flows = flows
}
return agents
}
override fun createUnattachedProcesses(): List<IAction> {
val sim1Params = simParametersProvider as Sim1ParametersProvider
return listOf(
IntroductionProcess(
population = population,
triggerFun = OncePerWeek("Monday"),
averageNetworkActivity =
sim1Params.averageNetworkActivity,
averageSuggestibilityOfStrangers =
sim1Params.averageSuggestibilityOfStrangers
)
)
}
override fun createSensors(): List<ISensor> {
return listOf(
Sim1aAccountant(
resultsStorage,
(simParametersProvider as Sim1ParametersProvider).name
)
)
}
}
| gpl-3.0 | 272e3d2b29e034c5f841dfa69cacf404 | 31.797619 | 86 | 0.629038 | 4.538715 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/util/messages.kt | 1 | 1374 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.core.util
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import org.jetbrains.annotations.TestOnly
import java.util.concurrent.ConcurrentHashMap
import javax.swing.Icon
fun showYesNoCancelDialog(key: String, project: Project, message: String, title: String, icon: Icon, default: Int?): Int {
return if (!ApplicationManager.getApplication().isUnitTestMode) {
Messages.showYesNoCancelDialog(project, message, title, icon)
} else {
callInTestMode(key, default)
}
}
private val dialogResults = ConcurrentHashMap<String, Any>()
@TestOnly
fun setDialogsResult(key: String, result: Any) {
dialogResults[key] = result
}
@TestOnly
fun clearDialogsResults() {
dialogResults.clear()
}
private fun <T : Any?> callInTestMode(key: String, default: T?): T {
val result = dialogResults[key]
if (result != null) {
dialogResults.remove(key)
@Suppress("UNCHECKED_CAST")
return result as T
}
if (default != null) {
return default
}
throw IllegalStateException("Can't call '$key' dialog in test mode")
}
| apache-2.0 | 628de628ce1ddbe8f473ec325e9fb542 | 28.869565 | 158 | 0.722707 | 4.101493 | false | true | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/formatter/Utils.kt | 1 | 1424 | // 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.formatter
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.codeStyle.CodeStyleManager
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.util.module
fun PsiFile.commitAndUnblockDocument(): Boolean {
val virtualFile = this.virtualFile ?: return false
val document = FileDocumentManager.getInstance().getDocument(virtualFile) ?: return false
val documentManager = PsiDocumentManager.getInstance(project)
documentManager.doPostponedOperationsAndUnblockDocument(document)
documentManager.commitDocument(document)
return true
}
fun PsiFile.adjustLineIndent(startOffset: Int, endOffset: Int) {
if (!commitAndUnblockDocument()) return
CodeStyleManager.getInstance(project).adjustLineIndent(this, TextRange(startOffset, endOffset))
}
fun trailingCommaAllowedInModule(source: PsiElement): Boolean = source.module
?.languageVersionSettings
?.supportsFeature(LanguageFeature.TrailingCommas) == true
| apache-2.0 | 1a866eacfdfa6db9390a433fcbc30878 | 43.5 | 120 | 0.820225 | 4.979021 | false | false | false | false |
android/compose-samples | Jetchat/app/src/main/java/com/example/compose/jetchat/components/JetchatIcon.kt | 1 | 1911 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.compose.jetchat.components
import androidx.compose.foundation.layout.Box
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import com.example.compose.jetchat.R
@Composable
fun JetchatIcon(
contentDescription: String?,
modifier: Modifier = Modifier
) {
val semantics = if (contentDescription != null) {
Modifier.semantics {
this.contentDescription = contentDescription
this.role = Role.Image
}
} else {
Modifier
}
Box(modifier = modifier.then(semantics)) {
Icon(
painter = painterResource(id = R.drawable.ic_jetchat_back),
contentDescription = null,
tint = MaterialTheme.colorScheme.primaryContainer
)
Icon(
painter = painterResource(id = R.drawable.ic_jetchat_front),
contentDescription = null,
tint = MaterialTheme.colorScheme.primary
)
}
}
| apache-2.0 | b3d20084d1fffcc16f45fd7ec43d18fa | 33.125 | 75 | 0.716379 | 4.47541 | false | false | false | false |
DrOptix/strava-intervall | strava-intervall/src/main/kotlin/com/worldexplorerblog/stravaintervall/fragments/TrainingsListFragment.kt | 1 | 6602 | package com.worldexplorerblog.stravaintervall.fragments
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import android.view.*
import android.widget.ListView
import com.worldexplorerblog.stravaintervall.R
import com.worldexplorerblog.stravaintervall.adapters.TrainingProgramAdapter
import com.worldexplorerblog.stravaintervall.models.TrainingIntensity
import com.worldexplorerblog.stravaintervall.models.TrainingIntervalModel
import com.worldexplorerblog.stravaintervall.models.TrainingPlanModel
class TrainingsListFragment : Fragment() {
public var onTrainingSelected: (TrainingPlanModel) -> Unit = { trainingProgram -> /* Do Nothing */ }
public var onCreateNewTrainingAction: () -> Unit = { /* Do Nothing */ }
var trainingPrograms = arrayListOf<TrainingPlanModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
trainingPrograms.add(
TrainingPlanModel("Test",
arrayListOf(TrainingIntervalModel(TrainingIntensity.WarmUp, 20),
TrainingIntervalModel(TrainingIntensity.Low, 10),
TrainingIntervalModel(TrainingIntensity.Medium, 10),
TrainingIntervalModel(TrainingIntensity.High, 10),
TrainingIntervalModel(TrainingIntensity.CoolDown, 10)
)))
trainingPrograms.add(
TrainingPlanModel(context.getString(R.string.standard_training_program_name),
arrayListOf(TrainingIntervalModel(TrainingIntensity.WarmUp, 5 * 60),
TrainingIntervalModel(TrainingIntensity.Medium, 1 * 60),
TrainingIntervalModel(TrainingIntensity.Low, 1 * 60),
TrainingIntervalModel(TrainingIntensity.Medium, 1 * 60),
TrainingIntervalModel(TrainingIntensity.Low, 1 * 60),
TrainingIntervalModel(TrainingIntensity.Medium, 1 * 60),
TrainingIntervalModel(TrainingIntensity.Low, 1 * 60),
TrainingIntervalModel(TrainingIntensity.Medium, 1 * 60),
TrainingIntervalModel(TrainingIntensity.Low, 1 * 60),
TrainingIntervalModel(TrainingIntensity.Medium, 1 * 60),
TrainingIntervalModel(TrainingIntensity.Low, 1 * 60),
TrainingIntervalModel(TrainingIntensity.Medium, 1 * 60),
TrainingIntervalModel(TrainingIntensity.CoolDown, 5 * 60)
)))
trainingPrograms.add(
TrainingPlanModel(context.getString(R.string.pyramid_training_program_name),
arrayListOf(TrainingIntervalModel(TrainingIntensity.WarmUp, 5 * 60),
TrainingIntervalModel(TrainingIntensity.High, 15),
TrainingIntervalModel(TrainingIntensity.Low, 40),
TrainingIntervalModel(TrainingIntensity.High, 25),
TrainingIntervalModel(TrainingIntensity.Low, 40),
TrainingIntervalModel(TrainingIntensity.High, 35),
TrainingIntervalModel(TrainingIntensity.Low, 40),
TrainingIntervalModel(TrainingIntensity.High, 45),
TrainingIntervalModel(TrainingIntensity.Low, 40),
TrainingIntervalModel(TrainingIntensity.High, 55),
TrainingIntervalModel(TrainingIntensity.Low, 40),
TrainingIntervalModel(TrainingIntensity.High, 45),
TrainingIntervalModel(TrainingIntensity.Low, 40),
TrainingIntervalModel(TrainingIntensity.High, 35),
TrainingIntervalModel(TrainingIntensity.Low, 40),
TrainingIntervalModel(TrainingIntensity.High, 25),
TrainingIntervalModel(TrainingIntensity.Low, 40),
TrainingIntervalModel(TrainingIntensity.High, 15),
TrainingIntervalModel(TrainingIntensity.CoolDown, 5 * 60)
)))
}
override fun onResume() {
super.onResume()
with(activity as AppCompatActivity) {
supportActionBar.title = getString(R.string.app_name)
supportActionBar.setDisplayHomeAsUpEnabled(false)
}
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
val layout = inflater?.inflate(R.layout.training_programs_list_fragment, container, false)
with(layout?.findViewById(R.id.training_programs_list) as ListView) {
adapter = TrainingProgramAdapter(context,
R.layout.training_program_adapter,
trainingPrograms)
setOnItemClickListener { parent, view, position, id -> onTrainingSelected(parent.getItemAtPosition(position) as TrainingPlanModel) }
}
return layout
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
super.onCreateOptionsMenu(menu, inflater)
inflater?.inflate(R.menu.training_programs_list_fragment_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
return when (item?.itemId) {
R.id.create_new_training_program_action -> {
onCreateNewTrainingAction()
true
}
else -> super.onOptionsItemSelected(item)
}
}
} | gpl-3.0 | 7eef4d554ec26b69c6830a979b387669 | 57.955357 | 144 | 0.551954 | 7.191721 | false | false | false | false |
mapzen/eraser-map | app/src/main/kotlin/com/mapzen/erasermap/view/InstructionAdapter.kt | 1 | 3070 | package com.mapzen.erasermap.view
import android.content.Context
import android.support.v4.view.PagerAdapter
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.mapzen.erasermap.R
import com.mapzen.erasermap.util.DisplayHelper
import com.mapzen.valhalla.Instruction
import java.util.ArrayList
class InstructionAdapter(private val context: Context,
private val instructions: ArrayList<Instruction>) : PagerAdapter() {
companion object {
@JvmStatic val TAG = InstructionAdapter::class.java.simpleName
}
override fun instantiateItem(container: ViewGroup?, position: Int): Any? {
val instruction = instructions.get(position)
val view = View.inflate(context, R.layout.pager_item_instruction, null)
val title = view.findViewById(R.id.instruction_text) as TextView
val distance = view.findViewById(R.id.distance) as DistanceView
val icon = view.findViewById(R.id.icon) as ImageView
val turn = instruction.getIntegerInstruction()
val iconId: Int = DisplayHelper.getRouteDrawable(context, turn, true)
distance.realTime = true
distance.distanceInMeters = instruction.distance
title.text = instruction.getName()
icon.setImageResource(iconId)
setDistanceViewVisibility(distance, position)
setTagId(view, position)
container?.addView(view)
return view
}
private fun setDistanceViewVisibility(distanceView: DistanceView, position: Int) {
if (position == count - 1) {
distanceView.visibility = View.GONE
} else {
distanceView.visibility = View.VISIBLE
}
}
override fun getCount(): Int {
return instructions.size
}
private fun setTagId(view: View, position: Int) {
view.tag = RouteModeView.VIEW_TAG + position
}
fun setBackgroundColorActive(view: View?) {
view?.setBackgroundColor(context.resources.getColor(android.R.color.white))
}
fun setBackgroundColorInactive(view: View?) {
view?.setBackgroundColor(context.resources.getColor(R.color.light_gray))
}
fun setBackgroundColorArrived(view: View?) {
view?.setBackgroundColor(context.resources.getColor(R.color.light_gray))
}
override fun isViewFromObject(view: View?, `object`: Any?): Boolean {
return view == `object`
}
override fun destroyItem(container: ViewGroup?, position: Int, `object`: Any?) {
container?.removeView(`object` as View)
}
fun setBeginText(view: View?, instruction: Instruction) {
val title = view?.findViewById(R.id.instruction_text) as TextView
if (instruction.getBeginStreetNames().length > 0) {
title.text = instruction.getBeginStreetNames()
}
}
fun setPostText(view: View?, instruction: Instruction) {
val title = view?.findViewById(R.id.instruction_text) as TextView
title.text = instruction.getName()
}
}
| gpl-3.0 | 4be9e005f27a50cfdd3fb104af457ff9 | 34.287356 | 86 | 0.691857 | 4.442836 | false | false | false | false |
bmaslakov/kotlin-algorithm-club | src/main/io/uuddlrlrba/ktalgs/datastructures/Dequeue.kt | 1 | 3507 | /*
* Copyright (c) 2017 Kotlin Algorithm Club
*
* 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 io.uuddlrlrba.ktalgs.datastructures
import java.util.*
@Suppress("RedundantVisibilityModifier")
public class Dequeue<T> : Collection<T> {
private var head: Node<T>? = null
private var tail: Node<T>? = null
public override var size: Int = 0
private set
private class Node<T>(var value: T) {
var next: Node<T>? = null
}
public fun add(item: T) {
val new = Node(item)
val tail = this.tail
if (tail == null) {
head = new
this.tail = new
} else {
tail.next = new
this.tail = new
}
size++
}
public fun push(item: T) {
val new = Node(item)
new.next = head
head = new
size++
}
public fun peekFirst(): T {
if (size == 0) throw NoSuchElementException()
return head!!.value
}
public fun peekLast(): T {
if (size == 0) throw NoSuchElementException()
return tail!!.value
}
public fun pollFirst(): T {
if (size == 0) throw NoSuchElementException()
val old = head!!
head = old.next
return old.value
}
public fun pollLast(): T {
if (size == 0) throw NoSuchElementException()
var node = head!!
while (node.next != null && node.next != tail) {
node = node.next!!
}
val ret = node.next!!
node.next = null
tail = node
return ret.value
}
public override fun isEmpty(): Boolean {
return size == 0
}
public override fun contains(element: T): Boolean {
for (obj in this) {
if (obj == element) return true
}
return false
}
public override fun containsAll(elements: Collection<T>): Boolean {
for (element in elements) {
if (!contains(element)) return false
}
return true
}
public override fun iterator(): Iterator<T> {
return object : Iterator<T> {
var node = head
override fun hasNext(): Boolean {
return node != null
}
override fun next(): T {
if (!hasNext()) throw NoSuchElementException()
val current = node!!
node = current.next
return current.value
}
}
}
}
| mit | 55eb4dea232f8f7a43e691908b4fc229 | 27.983471 | 81 | 0.591959 | 4.566406 | false | false | false | false |
quran/quran_android | app/src/main/java/com/quran/labs/androidquran/database/DatabaseHandler.kt | 2 | 11195 | package com.quran.labs.androidquran.database
import android.content.Context
import android.database.Cursor
import android.database.DefaultDatabaseErrorHandler
import android.database.SQLException
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteDatabaseCorruptException
import android.provider.BaseColumns
import android.util.SparseArray
import androidx.annotation.IntDef
import androidx.core.content.ContextCompat
import com.quran.common.search.ArabicSearcher
import com.quran.common.search.DefaultSearcher
import com.quran.common.search.Searcher
import com.quran.data.model.QuranText
import com.quran.data.model.VerseRange
import com.quran.labs.androidquran.R
import com.quran.labs.androidquran.data.QuranFileConstants
import com.quran.labs.androidquran.util.QuranFileUtils
import com.quran.labs.androidquran.util.TranslationUtil
import timber.log.Timber
import java.io.File
class DatabaseHandler private constructor(
context: Context,
databaseName: String,
quranFileUtils: QuranFileUtils
) {
private var schemaVersion = 1
private var database: SQLiteDatabase? = null
private val defaultSearcher: Searcher
private val arabicSearcher: Searcher
companion object {
private const val COL_SURA = "sura"
private const val COL_AYAH = "ayah"
private const val COL_TEXT = "text"
private const val VERSE_TABLE = "verses"
const val ARABIC_TEXT_TABLE = "arabic_text"
const val SHARE_TEXT_TABLE = "share_text"
private const val PROPERTIES_TABLE = "properties"
private const val COL_PROPERTY = "property"
private const val COL_VALUE = "value"
private const val MATCH_END = "</font>"
private const val ELLIPSES = "<b>...</b>"
private val databaseMap: MutableMap<String, DatabaseHandler> = HashMap()
@JvmStatic
@Synchronized
fun getDatabaseHandler(
context: Context, databaseName: String, quranFileUtils: QuranFileUtils
): DatabaseHandler {
var handler = databaseMap[databaseName]
if (handler == null) {
handler = DatabaseHandler(context.applicationContext, databaseName, quranFileUtils)
databaseMap[databaseName] = handler
}
return handler
}
@JvmStatic
@Synchronized
fun clearDatabaseHandlerIfExists(databaseName: String) {
try {
val handler = databaseMap.remove(databaseName)
if (handler != null) {
handler.database?.close()
databaseMap.remove(databaseName)
}
} catch (e: Exception) {
Timber.e(e)
}
}
}
init {
// initialize the searchers first
val matchString = "<font color=\"" +
ContextCompat.getColor(context, R.color.translation_highlight) +
"\">"
defaultSearcher = DefaultSearcher(matchString, MATCH_END, ELLIPSES)
arabicSearcher = ArabicSearcher(defaultSearcher, matchString, MATCH_END, QuranFileConstants.SEARCH_EXTRA_REPLACEMENTS)
// if there's no Quran base directory, there are no databases
val base = quranFileUtils.getQuranDatabaseDirectory(context)
base?.let {
val path = base + File.separator + databaseName
Timber.d("opening database file: %s", path)
database = try {
SQLiteDatabase.openDatabase(path, null,
SQLiteDatabase.NO_LOCALIZED_COLLATORS, DefaultDatabaseErrorHandler())
} catch (sce: SQLiteDatabaseCorruptException) {
Timber.d("corrupt database: %s", databaseName)
throw sce
} catch (se: SQLException) {
Timber.d("database at $path ${if (File(path).exists()) "exists " else "doesn 't exist"}")
throw se
}
schemaVersion = getSchemaVersion()
}
}
@Retention(AnnotationRetention.SOURCE)
@IntDef(TextType.ARABIC, TextType.TRANSLATION)
annotation class TextType {
companion object {
const val ARABIC = 0
const val TRANSLATION = 1
}
}
fun validDatabase(): Boolean = database?.isOpen ?: false
private fun getVerses(sura: Int, minAyah: Int, maxAyah: Int): Cursor? {
return getVerses(sura, minAyah, maxAyah, VERSE_TABLE)
}
private fun getProperty(column: String): Int {
var value = 1
if (!validDatabase()) return value
var cursor: Cursor? = null
return try {
cursor = database?.query(PROPERTIES_TABLE, arrayOf(COL_VALUE),
"$COL_PROPERTY= ?", arrayOf(column), null, null, null)
if (cursor != null && cursor.moveToFirst()) {
value = cursor.getInt(0)
}
value
} catch (se: SQLException) {
value
} finally {
DatabaseUtils.closeCursor(cursor)
}
}
fun getSchemaVersion(): Int = getProperty("schema_version")
fun getTextVersion(): Int = getProperty("text_version")
private fun getVerses(sura: Int, minAyah: Int, maxAyah: Int, table: String): Cursor? {
return getVerses(sura, minAyah, sura, maxAyah, table)
}
/**
* @param minSura start sura
* @param minAyah start ayah
* @param maxSura end sura
* @param maxAyah end ayah
* @param table the table
* @return a Cursor with the data
*/
@Deprecated(
"""use {@link #getVerses(VerseRange, int)} instead
"""
)
fun getVerses(
minSura: Int, minAyah: Int, maxSura: Int, maxAyah: Int, table: String
): Cursor? {
// pass -1 for verses since this is used internally only and the field isn't needed.
return getVersesInternal(VerseRange(minSura, minAyah, maxSura, maxAyah, -1), table)
}
fun getVerses(verses: VerseRange, @TextType textType: Int): List<QuranText> {
var cursor: Cursor? = null
val results: MutableList<QuranText> = ArrayList()
val toLookup: MutableSet<Int> = HashSet()
val table = if (textType == TextType.ARABIC) ARABIC_TEXT_TABLE else VERSE_TABLE
try {
cursor = getVersesInternal(verses, table)
while (cursor != null && cursor.moveToNext()) {
val sura = cursor.getInt(1)
val ayah = cursor.getInt(2)
val text = cursor.getString(3)
val quranText = QuranText(sura, ayah, text, null)
results.add(quranText)
val hyperlinkId = TranslationUtil.getHyperlinkAyahId(quranText)
if (hyperlinkId != null) {
toLookup.add(hyperlinkId)
}
}
} finally {
DatabaseUtils.closeCursor(cursor)
}
var didWrite = false
if (toLookup.isNotEmpty()) {
val toExpandBuilder = StringBuilder()
for (id in toLookup) {
if (didWrite) {
toExpandBuilder.append(",")
} else {
didWrite = true
}
toExpandBuilder.append(id)
}
return expandHyperlinks(table, results, toExpandBuilder.toString())
}
return results
}
private fun expandHyperlinks(
table: String, data: List<QuranText>, rowIds: String
): List<QuranText> {
val expansions = SparseArray<String>()
var cursor: Cursor? = null
try {
cursor = database?.query(table, arrayOf("rowid as _id", COL_TEXT),
"rowid in ($rowIds)", null, null, null, "rowid")
while (cursor != null && cursor.moveToNext()) {
val id = cursor.getInt(0)
val text = cursor.getString(1)
expansions.put(id, text)
}
} finally {
DatabaseUtils.closeCursor(cursor)
}
val result: MutableList<QuranText> = ArrayList()
for (ayah in data) {
val linkId = TranslationUtil.getHyperlinkAyahId(ayah)
if (linkId == null) {
result.add(ayah)
} else {
val expandedText = expansions[linkId]
result.add(QuranText(ayah.sura, ayah.ayah, ayah.text, expandedText))
}
}
return result
}
private fun getVersesInternal(verses: VerseRange, table: String): Cursor? {
if (!validDatabase()) return null
val whereQuery = StringBuilder()
whereQuery.append("(")
if (verses.startSura == verses.endingSura) {
whereQuery.append(COL_SURA)
.append("=").append(verses.startSura)
.append(" and ").append(COL_AYAH)
.append(">=").append(verses.startAyah)
.append(" and ").append(COL_AYAH)
.append("<=").append(verses.endingAyah)
} else {
// (sura = minSura and ayah >= minAyah)
whereQuery.append("(").append(COL_SURA).append("=")
.append(verses.startSura).append(" and ")
.append(COL_AYAH).append(">=").append(verses.startAyah).append(")")
whereQuery.append(" or ")
// (sura = maxSura and ayah <= maxAyah)
whereQuery.append("(").append(COL_SURA).append("=")
.append(verses.endingSura).append(" and ")
.append(COL_AYAH).append("<=").append(verses.endingAyah).append(")")
whereQuery.append(" or ")
// (sura > minSura and sura < maxSura)
whereQuery.append("(").append(COL_SURA).append(">")
.append(verses.startSura).append(" and ")
.append(COL_SURA).append("<")
.append(verses.endingSura).append(")")
}
whereQuery.append(")")
return database?.query(
table, arrayOf("rowid as _id", COL_SURA, COL_AYAH, COL_TEXT),
whereQuery.toString(), null, null, null,
"$COL_SURA,$COL_AYAH"
)
}
/**
* @deprecated use {@link #getVerses(VerseRange, int)} instead
* @param sura the sura
* @param ayah the ayah
* @return the result
*/
fun getVerse(sura: Int, ayah: Int): Cursor? {
return getVerses(sura, ayah, ayah)
}
fun getVersesByIds(ids: List<Int>): Cursor? {
val builder = StringBuilder()
for (i in ids.indices) {
if (i > 0) {
builder.append(",")
}
builder.append(ids[i])
}
Timber.d("querying verses by ids for tags...")
val sql = "SELECT rowid as _id, " + COL_SURA + ", " + COL_AYAH + ", " + COL_TEXT +
" FROM " + QuranFileConstants.ARABIC_SHARE_TABLE +
" WHERE rowid in(" + builder.toString() + ")"
return database?.rawQuery(sql, null)
}
fun search(query: String, withSnippets: Boolean, isArabicDatabase: Boolean): Cursor? {
return search(query, VERSE_TABLE, withSnippets, isArabicDatabase)
}
fun search(q: String, table: String, withSnippets: Boolean, isArabicDatabase: Boolean): Cursor? {
if (!validDatabase()) return null
var searchText = q
var pos = 0
var found = 0
var done = false
while (!done) {
val quote = searchText.indexOf("\"", pos)
if (quote > -1) {
found++
pos = quote + 1
} else {
done = true
}
}
if (found % 2 != 0) {
searchText = searchText.replace("\"".toRegex(), "")
}
val searcher: Searcher = if (isArabicDatabase) arabicSearcher else defaultSearcher
val useFullTextIndex = schemaVersion > 1 && !isArabicDatabase
val qtext = searcher.getQuery(withSnippets, useFullTextIndex, table,
"rowid as " + BaseColumns._ID + ", " + COL_SURA + ", " + COL_AYAH, COL_TEXT
) +
" " + searcher.getLimit(withSnippets)
searchText = searcher.processSearchText(searchText, useFullTextIndex)
Timber.d("search query: $qtext, query: $searchText")
val columns = arrayOf(BaseColumns._ID, COL_SURA, COL_AYAH, COL_TEXT)
return try {
searcher.runQuery(database!!, qtext, searchText, q, withSnippets, columns)
} catch (e: Exception) {
Timber.e(e)
null
}
}
}
| gpl-3.0 | 4d0a358c3c96c2fceab8b267d4de5d00 | 30.446629 | 122 | 0.64904 | 4.140163 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/reminders/RemindersNotifications.kt | 1 | 8084 | package com.orgzly.android.reminders
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.media.RingtoneManager
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import com.orgzly.R
import com.orgzly.android.AppIntent
import com.orgzly.android.NotificationBroadcastReceiver
import com.orgzly.android.NotificationChannels
import com.orgzly.android.data.logs.AppLogsRepository
import com.orgzly.android.db.dao.ReminderTimeDao
import com.orgzly.android.prefs.AppPreferences
import com.orgzly.android.ui.notifications.Notifications
import com.orgzly.android.ui.util.ActivityUtils
import com.orgzly.android.ui.util.ActivityUtils.mainActivityPendingIntent
import com.orgzly.android.ui.util.getNotificationManager
import com.orgzly.android.util.LogMajorEvents
import com.orgzly.android.util.OrgFormatter
import com.orgzly.android.util.UserTimeFormatter
object RemindersNotifications {
val VIBRATION_PATTERN = longArrayOf(500, 50, 50, 300)
private val LIGHTS = Triple(Color.BLUE, 1000, 5000)
fun showNotifications(context: Context, notes: List<NoteReminder>, logs: AppLogsRepository) {
val notificationManager = context.getNotificationManager()
for (noteReminder in notes) {
val wearableExtender = NotificationCompat.WearableExtender()
val notificationTag = noteReminder.payload.noteId.toString()
val content = getContent(context, noteReminder)
val builder = NotificationCompat.Builder(context, NotificationChannels.REMINDERS)
.setAutoCancel(true)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setColor(ContextCompat.getColor(context, R.color.notification))
.setSmallIcon(R.drawable.cic_logo_for_notification)
if (canGroupReminders()) {
builder.setGroup(Notifications.REMINDERS_GROUP)
}
// Set vibration
if (AppPreferences.remindersVibrate(context)) {
builder.setVibrate(VIBRATION_PATTERN)
}
// Set notification sound
if (AppPreferences.remindersSound(context)) {
builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
}
// Set LED
if (AppPreferences.remindersLed(context)) {
builder.setLights(LIGHTS.first, LIGHTS.second, LIGHTS.third)
}
builder.setContentTitle(OrgFormatter.parse(
noteReminder.payload.title,
context,
linkify = false,
parseCheckboxes = false
))
builder.setContentText(content)
builder.setStyle(NotificationCompat.InboxStyle()
.setSummaryText(noteReminder.payload.bookName)
.addLine(content)
)
// On click - open note
builder.setContentIntent(mainActivityPendingIntent(
context, noteReminder.payload.bookId, noteReminder.payload.noteId))
// Mark as done action - text depends on repeater
val doneActionText = if (noteReminder.payload.orgDateTime.hasRepeater()) {
context.getString(
R.string.mark_as_done_with_repeater,
noteReminder.payload.orgDateTime.repeater.toString())
} else {
context.getString(R.string.mark_as_done)
}
val markAsDoneAction = NotificationCompat.Action(R.drawable.ic_done,
doneActionText,
markNoteAsDonePendingIntent(
context, noteReminder.payload.noteId, notificationTag))
builder.addAction(markAsDoneAction)
wearableExtender.addAction(markAsDoneAction)
// Snooze action
val snoozeActionText = context.getString(R.string.reminder_snooze)
val snoozeAction = NotificationCompat.Action(R.drawable.ic_snooze,
snoozeActionText,
reminderSnoozePendingIntent(
context,
noteReminder.payload.noteId,
noteReminder.payload.timeType,
noteReminder.runTime.millis,
notificationTag))
builder.addAction(snoozeAction)
wearableExtender.addAction(snoozeAction)
builder.extend(wearableExtender)
notificationManager.notify(notificationTag, Notifications.REMINDER_ID, builder.build())
if (LogMajorEvents.isEnabled()) {
val note = "\"${noteReminder.payload.title}\" (id:${noteReminder.payload.noteId})"
logs.log(
LogMajorEvents.REMINDERS,
"Notified (tag:$notificationTag id:${Notifications.REMINDER_ID}): $note"
)
}
}
// Create a group summary notification, but only if notifications can be grouped
if (canGroupReminders()) {
if (notes.isNotEmpty()) {
val builder = NotificationCompat.Builder(context, NotificationChannels.REMINDERS)
.setAutoCancel(true)
.setSmallIcon(R.drawable.cic_logo_for_notification)
.setGroup(Notifications.REMINDERS_GROUP)
.setGroupSummary(true)
notificationManager.notify(Notifications.REMINDERS_SUMMARY_ID, builder.build())
}
}
}
private fun getContent(context: Context, noteReminder: NoteReminder): String {
val resId = when (noteReminder.payload.timeType) {
ReminderTimeDao.SCHEDULED_TIME ->
R.string.reminder_for_scheduled
ReminderTimeDao.DEADLINE_TIME ->
R.string.reminder_for_deadline
else ->
R.string.reminder_for_event
}
val timeStr = UserTimeFormatter(context).formatAll(noteReminder.payload.orgDateTime)
return context.getString(resId, timeStr)
}
// Create a group summary notification, but only if notifications be grouped and expanded
private fun canGroupReminders(): Boolean {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
}
private fun markNoteAsDonePendingIntent(
context: Context, noteId: Long, tag: String
): PendingIntent {
val intent = Intent(context, NotificationBroadcastReceiver::class.java).apply {
action = AppIntent.ACTION_NOTE_MARK_AS_DONE
putExtra(AppIntent.EXTRA_NOTE_ID, noteId)
putExtra(AppIntent.EXTRA_NOTIFICATION_TAG, tag)
putExtra(AppIntent.EXTRA_NOTIFICATION_ID, Notifications.REMINDER_ID)
}
return PendingIntent.getBroadcast(
context,
noteId.toInt(),
intent,
ActivityUtils.immutable(PendingIntent.FLAG_UPDATE_CURRENT))
}
private fun reminderSnoozePendingIntent(
context: Context, noteId: Long, noteTimeType: Int, timestamp: Long, tag: String
): PendingIntent {
val intent = Intent(context, NotificationBroadcastReceiver::class.java).apply {
action = AppIntent.ACTION_REMINDER_SNOOZE_REQUESTED
putExtra(AppIntent.EXTRA_NOTE_ID, noteId)
putExtra(AppIntent.EXTRA_NOTE_TIME_TYPE, noteTimeType)
putExtra(AppIntent.EXTRA_SNOOZE_TIMESTAMP, timestamp)
putExtra(AppIntent.EXTRA_NOTIFICATION_TAG, tag)
putExtra(AppIntent.EXTRA_NOTIFICATION_ID, Notifications.REMINDER_ID)
}
return PendingIntent.getBroadcast(
context,
noteId.toInt(),
intent,
ActivityUtils.immutable(PendingIntent.FLAG_UPDATE_CURRENT))
}
} | gpl-3.0 | 2d294b741942da531e40051f4a344a29 | 39.223881 | 99 | 0.633597 | 5.26645 | false | false | false | false |
Yorxxx/played-next-kotlin | app/src/main/java/com/piticlistudio/playednext/data/entity/igdb/IGDBModels.kt | 1 | 3154 | package com.piticlistudio.playednext.data.entity.igdb
/**
* Representation of a Remote entities
*/
data class IGDBGame(val id: Int,
val name: String,
val slug: String,
val url: String,
val created_at: Long,
val updated_at: Long,
val summary: String? = null,
val storyline: String? = null,
var collection: IGDBCollection? = null,
val franchise: Int? = null,
val hypes: Int? = 0,
val popularity: Double? = null,
val rating: Double? = null,
val rating_count: Int? = 0,
val aggregated_rating: Double? = null,
val aggregated_rating_count: Int? = 0,
val total_rating: Double? = null,
val total_rating_count: Int? = 0,
val developers: List<IGDBCompany>? = listOf(),
val publishers: List<IGDBCompany>? = listOf(),
val game_engines: List<Int>? = listOf(),
val time_to_beat: IGDBTimeToBeat?,
val genres: List<IGDBGenre>? = listOf(),
val first_release_date: Long? = null,
val release_dates: List<ReleaseDateDTO>? = listOf(),
val screenshots: List<IGDBImage>? = listOf(),
val videos: List<VideoDTO>? = listOf(),
val cover: IGDBImage? = null,
val games: List<Int>? = listOf(),
val platforms: List<IGDBPlatform>? = listOf())
open class BaseEnumeratedEntity(val id: Int, val name: String, val slug: String, val url: String?,
val created_at: Long, val updated_at: Long)
class IGDBCompany(id: Int, name: String, slug: String, url: String, created_at: Long, updated_at: Long) : BaseEnumeratedEntity(id, name, slug, url, created_at, updated_at)
class IGDBGenre(id: Int, name: String, slug: String, url: String, created_at: Long, updated_at: Long) : BaseEnumeratedEntity(id, name, slug, url, created_at, updated_at)
class IGDBCollection(id: Int, name: String, slug: String, url: String, created_at: Long, updated_at: Long) : BaseEnumeratedEntity(id, name, slug, url, created_at, updated_at)
class IGDBPlatform(id: Int, name: String, slug: String, url: String?, created_at: Long, updated_at: Long) : BaseEnumeratedEntity(id, name, slug, url, created_at, updated_at)
data class IGDBTimeToBeat(val hastly: Int?, val normally: Int?, val completely: Int?)
data class ReleaseDateDTO(val game: Int, val category: Int, val platform: Int?, val human: String)
data class IGDBImage(val url: String, val cloudinary_id: String?, val width: Int?, val height: Int?) {
val mediumSizeUrl: String = "https:${clearHTTPPrefix(url)}".replace("t_thumb", "t_screenshot_med")
protected fun clearHTTPPrefix(input: String): String {
return input.removePrefix("http:").removePrefix("https:")
}
}
data class VideoDTO(val name: String, val video_id: String)
| mit | b0be3e6f5b5c129d479285941a565224 | 51.566667 | 174 | 0.580216 | 4.139108 | false | false | false | false |
zitmen/thunderstorm-algorithms | src/main/kotlin/cz/cuni/lf1/thunderstorm/algorithms/filters/DifferenceOfGaussiansFilter.kt | 1 | 1171 | package cz.cuni.lf1.thunderstorm.algorithms.filters
import cz.cuni.lf1.thunderstorm.algorithms.padding.Padding
import cz.cuni.lf1.thunderstorm.datastructures.GrayScaleImage
import cz.cuni.lf1.thunderstorm.datastructures.extensions.minus
public class DifferenceOfGaussiansFilter(size: Int, sigma1: Double, sigma2: Double, paddingTypeFactory: (Int) -> Padding)
: FilterWithVariables {
private val gaussianFilter1 = GaussianFilter(size, sigma1, paddingTypeFactory)
private val gaussianFilter2 = GaussianFilter(size, sigma2, paddingTypeFactory)
public override val variables = mapOf(
"I" to emptyFilterVariable(),
"F" to emptyFilterVariable(),
"G1" to emptyFilterVariable(),
"G2" to emptyFilterVariable())
override fun filter(image: GrayScaleImage): GrayScaleImage {
val g1 = gaussianFilter1.filter(image)
val g2 = gaussianFilter2.filter(image)
val dog = g1 - g2
variables["I"]!!.setRefresher { image }
variables["F"]!!.setRefresher { dog }
variables["G1"]!!.setRefresher { g1 }
variables["G2"]!!.setRefresher { g2 }
return dog
}
}
| gpl-3.0 | 851cc73e64a185e774c479f0b765d0b4 | 36.774194 | 121 | 0.69257 | 4.435606 | false | false | false | false |
UnderMybrella/Visi | src/main/kotlin/org/abimon/visi/collections/Pools.kt | 1 | 5060 | package org.abimon.visi.collections
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
class Pool<T>(val poolSize: Int = -1) {
private val poolables: MutableList<Poolable<T>> = ArrayList()
/**
* Get the first available [Poolable] instance, or null if none are free
*/
fun get(): Poolable<T>? {
synchronized(poolables) {
return poolables.firstOrNull(Poolable<T>::isFree)
}
}
/**
* Waits for a [Poolable] instance to become free, and then returns it. Throws a [TimeOutException]
*/
fun getOrWait(wait: Long, unit: TimeUnit): Poolable<T> {
var passedMilli = 0L
val waitingMilli = unit.toMillis(wait)
while(passedMilli < waitingMilli) {
val res = get()
if(res != null)
return res
Thread.sleep(1000)
passedMilli += 1000
}
throw TimeoutException("No Poolable instances free, waited ${unit.convert(passedMilli, TimeUnit.MILLISECONDS)} ${unit.name.capitalize()}")
}
/**
* Get the first available [Poolable] instance which matches [matches], or null if none of the instances are free that match
*/
fun getWhich(matches: (T) -> Boolean): Poolable<T>? {
synchronized(poolables) {
return poolables.filter { poolable -> matches(poolable()) }.firstOrNull(Poolable<T>::isFree)
}
}
/**
* Waits for a [Poolable] instance to become free, and then returns it. Will hang until one becomes available
*/
fun getOrWaitUntil(wait: Long, unit: TimeUnit, matches: (T) -> Boolean): Poolable<T> {
var passedMilli = 0L
val waitingMilli = unit.toMillis(wait)
while(passedMilli < waitingMilli) {
val res = getWhich(matches)
if(res != null)
return res
Thread.sleep(1000)
passedMilli += 1000
}
throw TimeoutException("No Poolable instances free, waited ${unit.convert(passedMilli, TimeUnit.MILLISECONDS)} ${unit.name.capitalize()}")
}
fun getFirst(sort: (T, T) -> Int): Poolable<T>? {
synchronized(poolables) {
return poolables.filter(Poolable<T>::isFree).sortedWith(Comparator { one, two -> sort(one(), two())}).firstOrNull()
}
}
/**
* Waits for a [Poolable] instance to become free, and then returns it. Will hang until one becomes available
*/
fun getFirstOrWaitUntil(wait: Long, unit: TimeUnit, sort: (T, T) -> Int): Poolable<T> {
var passedMilli = 0L
val waitingMilli = unit.toMillis(wait)
while(passedMilli < waitingMilli) {
val res = getFirst(sort)
if(res != null)
return res
Thread.sleep(1000)
passedMilli += 1000
}
throw TimeoutException("No Poolable instances free, waited ${unit.convert(passedMilli, TimeUnit.MILLISECONDS)} ${unit.name.capitalize()}")
}
/**
* Gets the first available [Poolable] instance, or adds [add] to the pool if there is space. If there is no space and none are free, returns null
*/
fun getOrAdd(add: () -> Poolable<T>): Poolable<T>? {
synchronized(poolables) {
if(poolables.size >= poolSize)
return get()
val poolable = poolables.firstOrNull(Poolable<T>::isFree)
if(poolable == null) {
val newPoolable = add()
poolables.add(newPoolable)
return newPoolable
}
return poolable
}
}
/**
* Gets the first available [Poolable] instance, or adds [add] to the pool if there is space. If there is no space and none are free, wait.
*/
fun getOrAddOrWait(wait: Long, unit: TimeUnit, add: () -> Poolable<T>): Poolable<T> {
synchronized(poolables) {
if(poolables.size >= poolSize)
return getOrWait(wait, unit)
val poolable = poolables.firstOrNull(Poolable<T>::isFree)
if(poolable == null) {
val newPoolable = add()
poolables.add(newPoolable)
return newPoolable
}
return poolable
}
}
fun getFree(): List<Poolable<T>> = poolables.filter(Poolable<T>::isFree)
fun retire(poolable: Poolable<T>): Boolean = poolables.remove(poolable)
fun add(poolable: Poolable<T>): Boolean = if(poolables.size >= poolSize) false else poolables.add(poolable)
}
interface Poolable<out T> {
fun get(): T
fun isFree(): Boolean
operator fun invoke(): T = get()
}
class PoolableObject<out T>(val obj: T) : Poolable<T> {
var inUse = false
override fun get(): T = synchronized(obj as Any) { obj }
override fun isFree(): Boolean = !inUse
fun use(run: (T) -> Unit) {
inUse = true
try {
synchronized(obj as Any) {
run(obj)
}
}
finally {
inUse = false
}
}
} | mit | 724e4272a7357a3593bbb4cb1d55820b | 32.966443 | 150 | 0.585375 | 4.45815 | false | false | false | false |
facebook/fresco | buildSrc/src/main/java/com/facebook/fresco/buildsrc/dependencies.kt | 1 | 2475 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.fresco.buildsrc
object Deps {
const val javaxAnnotation = "javax.annotation:javax.annotation-api:1.2"
const val jsr305 = "com.google.code.findbugs:jsr305:3.0.2"
const val inferAnnotation = "com.facebook.infer.annotation:infer-annotation:0.18.0"
const val okhttp3 = "com.squareup.okhttp3:okhttp:3.12.1"
const val volley = "com.android.volley:volley:1.2.1"
object AndroidX {
const val androidxAnnotation = "androidx.annotation:annotation:1.1.0"
const val core = "androidx.core:core:1.3.1"
const val legacySupportCoreUtils = "androidx.legacy:legacy-support-core-utils:1.0.0"
}
object Bolts {
const val tasks = "com.parse.bolts:bolts-tasks:1.4.0"
}
object Kotlin {
const val version = GradleDeps.Kotlin.version
const val stdlibJdk = "org.jetbrains.kotlin:kotlin-stdlib:$version"
}
object Litho {
private const val version = "0.41.2"
const val core = "com.facebook.litho:litho-core:$version"
const val lithoAnnotations = "com.facebook.litho:litho-annotations:$version"
const val processor = "com.facebook.litho:litho-processor:$version"
const val widget = "com.facebook.litho:litho-widget:$version"
object Sections {
const val core = "com.facebook.litho:litho-sections-core:$version"
const val processor = "com.facebook.litho:litho-sections-processor:$version"
const val sectionsAnnotations = "com.facebook.litho:litho-sections-annotations:$version"
const val widget = "com.facebook.litho:litho-sections-widget:$version"
}
}
object SoLoader {
private const val version = "0.10.4"
const val soloaderAnnotation = "com.facebook.soloader:annotation:$version"
const val nativeloader = "com.facebook.soloader:nativeloader:$version"
const val soloader = "com.facebook.soloader:soloader:$version"
}
object Tools {
object Flipper {
private const val version = "0.121.0"
const val flipper = "com.facebook.flipper:flipper:$version"
const val fresco = "com.facebook.flipper:flipper-fresco-plugin:$version"
}
object Stetho {
private const val version = "1.6.0"
const val stetho = "com.facebook.stetho:stetho:$version"
const val okhttp3 = "com.facebook.stetho:stetho-okhttp3:$version"
}
}
}
| mit | e58f986f438813174753bdbd50b19132 | 33.859155 | 94 | 0.710303 | 3.607872 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-moderation-bukkit/src/main/kotlin/com/rpkit/moderation/bukkit/command/ticket/list/TicketListOpenCommand.kt | 1 | 2639 | /*
* Copyright 2021 Ren Binden
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.moderation.bukkit.command.ticket.list
import com.rpkit.core.service.Services
import com.rpkit.moderation.bukkit.RPKModerationBukkit
import com.rpkit.moderation.bukkit.ticket.RPKTicketService
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import java.time.format.DateTimeFormatter
class TicketListOpenCommand(private val plugin: RPKModerationBukkit) : CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (!sender.hasPermission("rpkit.moderation.command.ticket.list.open")) {
sender.sendMessage(plugin.messages["no-permission-ticket-list-open"])
}
val ticketService = Services[RPKTicketService::class.java]
if (ticketService == null) {
sender.sendMessage(plugin.messages["no-ticket-service"])
return true
}
ticketService.getOpenTickets().thenAccept { openTickets ->
sender.sendMessage(plugin.messages["ticket-list-title"])
val dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
openTickets.forEach { ticket ->
val closeDate = ticket.closeDate
sender.sendMessage(plugin.messages["ticket-list-item", mapOf(
"id" to ticket.id?.value.toString(),
"reason" to ticket.reason,
"location" to "${ticket.location?.world} ${ticket.location?.x}, ${ticket.location?.y}, ${ticket.location?.z}",
"issuer" to ticket.issuer.name.value,
"resolver" to (ticket.resolver?.name?.value ?: "none"),
"open_date" to dateTimeFormatter.format(ticket.openDate),
"close_date" to if (closeDate == null) "none" else dateTimeFormatter.format(ticket.closeDate),
"closed" to ticket.isClosed.toString()
)])
}
}
return true
}
} | apache-2.0 | 5f3139fb5647a1dbdb415c2b7cf8ba09 | 44.517241 | 130 | 0.666919 | 4.542169 | false | false | false | false |
android/user-interface-samples | CanonicalLayouts/supporting-panel-views/app/src/main/java/com/google/supporting/panel/views/SupportingContentView.kt | 1 | 1986 | /*
* 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.supporting.panel.views
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.supporting.panel.views.databinding.SupportingContentBinding
class SupportingContentView @JvmOverloads
constructor(ctx: Context, attributeSet: AttributeSet? = null, defStyleAttr: Int = 0)
: ConstraintLayout(ctx, attributeSet, defStyleAttr) {
private val adapter = SupportAdapter { onItemClicked(it) }
private var itemClickListener: (String) -> Unit = {}
init {
// get the inflater service from the android system
val inflater = ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
with(SupportingContentBinding.inflate(inflater, this, true)){
supportList.adapter = adapter
supportList.layoutManager =
LinearLayoutManager(context, RecyclerView.VERTICAL, false)
}
}
fun updateItems(newItems: List<String>){
adapter.updateItems(newItems)
}
fun setOnItemClickListener(f: (String) -> Unit) {
itemClickListener = f
}
private fun onItemClicked(item: String){
itemClickListener(item)
}
} | apache-2.0 | 20abc5e68965060fa8a7776855230ba6 | 33.258621 | 94 | 0.736153 | 4.774038 | false | false | false | false |
mfklauberg/projetosacademicosfurb | compiladores/core/src/test/kotlin/ui/view/screen/impl/MainScreen.kt | 1 | 6919 | package ui.view.screen.impl
import javafx.geometry.NodeOrientation
import javafx.scene.Scene
import javafx.scene.control.Button
import javafx.scene.control.Label
import javafx.scene.control.TextArea
import javafx.scene.image.ImageView
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyCodeCombination
import javafx.scene.input.KeyCombination
import javafx.scene.layout.BorderPane
import javafx.scene.layout.HBox
import javafx.scene.layout.VBox
import javafx.scene.text.TextAlignment
import javafx.stage.Stage
import ui.utils.ButtonBar
import ui.utils.Resources
import ui.utils.Settings
import ui.view.handler.impl.AppHandler
import ui.view.listener.AppListener
import java.nio.file.Path
/**
* FURB - Bacharelado em Ciências da Computação
* Compiladores - Interface
*
* Fábio Luiz Fischer & Matheus Felipe Klauberg
**/
class MainScreen : AbstractScreen(Settings.MIN_SCREEN_SIZE, Settings.APP_NAME) {
val UPPER_BAR_WIDTH = 910.0
val UPPER_BAR_HEIGHT = 65.0
val CONSOLE_HEIGHT = 100.0
val STATUS_BAR_HEIGHT = 25.0
val STATUS_BAR_WIDTH = 100.0
val LINE_NUMBER_WIDTH = 42.0
private val pane = BorderPane()
private val upperBox = ButtonBar(UPPER_BAR_WIDTH, 2.0)
private val bottomBox = VBox()
private val statusBox = HBox()
private val newFileButton = Button()
private val openFileButton = Button()
private val saveFileButton = Button()
private val copyTextButton = Button()
private val pasteTextButton = Button()
private val cutTextButton = Button()
private val buildProjectButton = Button()
private val appTeam = Button()
private val statusLabel = Label()
private val filePathLabel = Label()
val contentArea = TextArea()
val lineNumberArea = TextArea("1")
val consoleArea = TextArea()
val fileHandler = AppHandler()
var isFileChanged = false
set(isChanged) {
field = isChanged
statusLabel.text = if (isChanged) "Modificado" else "Não Modificado"
}
var actualPath: Path? = null
set(path) {
field = path
filePathLabel.text = if (path != null) "$path" else ""
}
fun writeConsole(content: String, override: Boolean = false) {
write(consoleArea, "\n$content", override)
}
override fun start(primaryStage: Stage) {
stage = primaryStage
initComponents(primaryStage)
primaryStage.scene = initScene()
primaryStage.title = screenName
primaryStage.minHeight = screenSize.x
primaryStage.minWidth = screenSize.y
primaryStage.show()
}
@Suppress("NON_EXHAUSTIVE_WHEN")
override fun initScene(): Scene {
pane.top = upperBox
pane.left = lineNumberArea
pane.center = contentArea
pane.bottom = bottomBox
val scene = Scene(pane, screenSize.x, screenSize.y)
scene.setOnKeyPressed { event ->
when (event.code) {
KeyCodeCombination(KeyCode.N, KeyCombination.CONTROL_ANY).code -> fileHandler.newFileRequest(this)
KeyCodeCombination(KeyCode.O, KeyCombination.CONTROL_ANY).code -> fileHandler.openFileRequest(this)
KeyCodeCombination(KeyCode.S, KeyCombination.CONTROL_ANY).code -> fileHandler.saveFileRequest(this)
KeyCodeCombination(KeyCode.C, KeyCombination.CONTROL_ANY).code -> fileHandler.copyTextRequest(this)
KeyCodeCombination(KeyCode.V, KeyCombination.CONTROL_ANY).code -> fileHandler.pasteTextRequest(this)
KeyCodeCombination(KeyCode.X, KeyCombination.CONTROL_ANY).code -> fileHandler.cutTextRequest(this)
KeyCode.F8 -> fileHandler.buildProjectRequest(this)
KeyCode.F1 -> fileHandler.applicationTeamRequest(this)
}
}
for (styleSheet in Resources.getStyleSheets()) {
scene.stylesheets.add(styleSheet.toString())
}
pane.prefHeightProperty().bind(scene.heightProperty())
pane.prefWidthProperty().bind(scene.widthProperty())
return scene
}
override fun initComponents(primaryStage: Stage) {
primaryStage.setOnCloseRequest { fileHandler.closeAppRequest(this) }
initLabel(statusLabel, "Não modificado", TextAlignment.LEFT, STATUS_BAR_WIDTH, STATUS_BAR_HEIGHT)
initLabel(filePathLabel, "", TextAlignment.RIGHT, STATUS_BAR_WIDTH, STATUS_BAR_HEIGHT)
initTextAreas()
initButtons()
initBoxes()
linkListeners()
linkHandlers()
}
private fun initTextAreas() {
initTextArea(lineNumberArea, LINE_NUMBER_WIDTH, pane.height, false, true)
initTextArea(consoleArea, pane.width, CONSOLE_HEIGHT, false)
initTextArea(contentArea, pane.width, pane.height)
lineNumberArea.nodeOrientation = NodeOrientation.RIGHT_TO_LEFT
}
private fun initBoxes() {
upperBox.addAll(newFileButton, openFileButton, saveFileButton, copyTextButton, pasteTextButton, cutTextButton, buildProjectButton, appTeam)
initHBox(statusBox, 5.0, statusLabel, filePathLabel)
initVBox(bottomBox, 1.0, consoleArea, statusBox)
}
private fun initButtons() {
try {
initButton(newFileButton, "Novo [Ctrl+N)", ImageView(Resources.newFile), UPPER_BAR_HEIGHT)
initButton(openFileButton, "Abrir [Ctrl+O)", ImageView(Resources.openFile), UPPER_BAR_HEIGHT)
initButton(saveFileButton, "Salvar [Ctrl+S)", ImageView(Resources.saveFile), UPPER_BAR_HEIGHT)
initButton(copyTextButton, "Copiar [Ctrl+C)", ImageView(Resources.copyText), UPPER_BAR_HEIGHT)
initButton(pasteTextButton, "Colar [Ctrl+V)", ImageView(Resources.pasteText), UPPER_BAR_HEIGHT)
initButton(cutTextButton, "Cortar [Ctrl+X]", ImageView(Resources.cutText), UPPER_BAR_HEIGHT)
initButton(buildProjectButton, "Compilar [F8]", ImageView(Resources.buildProject), UPPER_BAR_HEIGHT)
initButton(appTeam, "Equipe [F1]", ImageView(Resources.appTeam), UPPER_BAR_HEIGHT)
} catch (e: NoSuchFileException) {
println(e.printStackTrace())
}
}
private fun linkHandlers() {
newFileButton.setOnAction { fileHandler.newFileRequest(this) }
openFileButton.setOnAction { fileHandler.openFileRequest(this) }
saveFileButton.setOnAction { fileHandler.saveFileRequest(this) }
copyTextButton.setOnAction { fileHandler.copyTextRequest(this) }
pasteTextButton.setOnAction { fileHandler.pasteTextRequest(this) }
cutTextButton.setOnAction { fileHandler.cutTextRequest(this) }
buildProjectButton.setOnAction { fileHandler.buildProjectRequest(this) }
appTeam.setOnAction { fileHandler.applicationTeamRequest(this) }
}
private fun linkListeners() {
contentArea.textProperty().addListener(AppListener.listen(this))
}
} | mit | 1c83960181719fd07c1bf2122ebeeb3e | 37.625698 | 147 | 0.691017 | 4.397583 | false | false | false | false |
cliffano/swaggy-jenkins | clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/QueueItemImpl.kt | 1 | 1314 | package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import javax.validation.constraints.DecimalMax
import javax.validation.constraints.DecimalMin
import javax.validation.constraints.Email
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
import javax.validation.Valid
import io.swagger.v3.oas.annotations.media.Schema
/**
*
* @param propertyClass
* @param expectedBuildNumber
* @param id
* @param pipeline
* @param queuedTime
*/
data class QueueItemImpl(
@Schema(example = "null", description = "")
@field:JsonProperty("_class") val propertyClass: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("expectedBuildNumber") val expectedBuildNumber: kotlin.Int? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("id") val id: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("pipeline") val pipeline: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("queuedTime") val queuedTime: kotlin.Int? = null
) {
}
| mit | beea80efdf1658cb53cdd98769daebbc | 29.55814 | 91 | 0.743531 | 4.10625 | false | false | false | false |
oukingtim/king-admin | king-admin-kotlin/src/main/kotlin/com/oukingtim/domain/SysMenu.kt | 1 | 384 | package com.oukingtim.domain
import com.baomidou.mybatisplus.annotations.TableName
/**
* Created by oukingtim
*/
@TableName("sys_menu")
class SysMenu : BaseModel<SysMenu>() {
val parentId: String? = null
val name: String? = null
val type: String? = null
val icon: String? = null
val title: String? = null
val level: Int? = null
val order: Int? = null
} | mit | f3891a9d7c58801d14f47d9eb4e05d54 | 21.647059 | 53 | 0.664063 | 3.588785 | false | false | false | false |
jiangkang/KTools | tools/src/main/java/com/jiangkang/tools/extend/ServiceExt.kt | 1 | 10981 | package com.jiangkang.tools.extend
import android.accounts.AccountManager
import android.app.*
import android.app.admin.DevicePolicyManager
import android.app.usage.NetworkStatsManager
import android.app.usage.StorageStatsManager
import android.app.usage.UsageStatsManager
import android.bluetooth.BluetoothManager
import android.companion.CompanionDeviceManager
import android.content.ClipboardManager
import android.content.Context
import android.content.RestrictionsManager
import android.content.pm.ShortcutManager
import android.hardware.ConsumerIrManager
import android.hardware.SensorManager
import android.hardware.camera2.CameraManager
import android.hardware.display.DisplayManager
import android.hardware.fingerprint.FingerprintManager
import android.hardware.input.InputManager
import android.hardware.usb.UsbManager
import android.location.LocationManager
import android.media.AudioManager
import android.media.midi.MidiManager
import android.media.projection.MediaProjectionManager
import android.media.session.MediaSessionManager
import android.media.tv.TvInputManager
import android.net.ConnectivityManager
import android.net.nsd.NsdManager
import android.net.wifi.WifiManager
import android.net.wifi.aware.WifiAwareManager
import android.net.wifi.p2p.WifiP2pManager
import android.nfc.NfcManager
import android.os.BatteryManager
import android.os.HardwarePropertiesManager
import android.os.PowerManager
import android.os.UserManager
import android.os.health.SystemHealthManager
import android.os.storage.StorageManager
import android.print.PrintManager
import android.telecom.TelecomManager
import android.telephony.CarrierConfigManager
import android.telephony.TelephonyManager
import android.view.WindowManager
import android.view.accessibility.AccessibilityManager
import android.view.accessibility.CaptioningManager
import android.view.inputmethod.InputMethodManager
import android.view.textclassifier.TextClassificationManager
/** Returns the AccessibilityManager instance. **/
val Context.accessibilityManager: AccessibilityManager
get() = getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager
/** Returns the AccountManager instance. **/
val Context.accountManager: AccountManager
get() = getSystemService(Context.ACCOUNT_SERVICE) as AccountManager
/** Returns the ActivityManager instance. **/
val Context.activityManager: ActivityManager
get() = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
/** Returns the AlarmManager instance. **/
val Context.alarmManager: AlarmManager
get() = getSystemService(Context.ALARM_SERVICE) as AlarmManager
/** Returns the AppOpsManager instance. **/
val Context.appOpsManager: AppOpsManager
get() = getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
/** Returns the AudioManager instance. **/
val Context.audioManager: AudioManager
get() = getSystemService(Context.AUDIO_SERVICE) as AudioManager
/** Returns the BatteryManager instance. **/
val Context.batteryManager: BatteryManager
get() = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
/** Returns the BluetoothManager instance. **/
val Context.bluetoothManager: BluetoothManager
get() = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
/** Returns the CameraManager instance. **/
val Context.cameraManager: CameraManager
get() = getSystemService(Context.CAMERA_SERVICE) as CameraManager
/** Returns the CaptioningManager instance. **/
val Context.captioningManager: CaptioningManager
get() = getSystemService(Context.CAPTIONING_SERVICE) as CaptioningManager
/** Returns the CarrierConfigManager instance. **/
val Context.carrierConfigManager: CarrierConfigManager
get() = getSystemService(Context.CARRIER_CONFIG_SERVICE) as CarrierConfigManager
/** Returns the ClipboardManager instance. **/
val Context.clipboardManager: ClipboardManager
get() = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
/** Returns the CompanionDeviceManager instance. **/
val Context.companionDeviceManager: CompanionDeviceManager
get() = getSystemService(Context.COMPANION_DEVICE_SERVICE) as CompanionDeviceManager
/** Returns the ConnectivityManager instance. **/
val Context.connectivityManager: ConnectivityManager
get() = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
/** Returns the ConsumerIrManager instance. **/
val Context.consumerIrManager: ConsumerIrManager
get() = getSystemService(Context.CONSUMER_IR_SERVICE) as ConsumerIrManager
/** Returns the DevicePolicyManager instance. **/
val Context.devicePolicyManager: DevicePolicyManager
get() = getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager
/** Returns the DisplayManager instance. **/
val Context.displayManager: DisplayManager
get() = getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
/** Returns the DownloadManager instance. **/
val Context.downloadManager: DownloadManager
get() = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
/** Returns the FingerprintManager instance. **/
val Context.fingerprintManager: FingerprintManager
get() = getSystemService(Context.FINGERPRINT_SERVICE) as FingerprintManager
/** Returns the HardwarePropertiesManager instance. **/
val Context.hardwarePropertiesManager: HardwarePropertiesManager
get() = getSystemService(Context.HARDWARE_PROPERTIES_SERVICE) as HardwarePropertiesManager
/** Returns the InputManager instance. **/
val Context.inputManager: InputManager
get() = getSystemService(Context.INPUT_SERVICE) as InputManager
/** Returns the InputMethodManager instance. **/
val Context.inputMethodManager: InputMethodManager
get() = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
/** Returns the KeyguardManager instance. **/
val Context.keyguardManager: KeyguardManager
get() = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
/** Returns the LocationManager instance. **/
val Context.locationManager: LocationManager
get() = getSystemService(Context.LOCATION_SERVICE) as LocationManager
/** Returns the MediaProjectionManager instance. **/
val Context.mediaProjectionManager: MediaProjectionManager
get() = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
/** Returns the MediaSessionManager instance. **/
val Context.mediaSessionManager: MediaSessionManager
get() = getSystemService(Context.MEDIA_SESSION_SERVICE) as MediaSessionManager
/** Returns the MidiManager instance. **/
val Context.midiManager: MidiManager
get() = getSystemService(Context.MIDI_SERVICE) as MidiManager
/** Returns the NetworkStatsManager instance. **/
val Context.networkStatsManager: NetworkStatsManager
get() = getSystemService(Context.NETWORK_STATS_SERVICE) as NetworkStatsManager
/** Returns the NfcManager instance. **/
val Context.nfcManager: NfcManager
get() = getSystemService(Context.NFC_SERVICE) as NfcManager
/** Returns the NotificationManager instance. **/
val Context.notificationManager: NotificationManager
get() = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
/** Returns the NsdManager instance. **/
val Context.nsdManager: NsdManager
get() = getSystemService(Context.NSD_SERVICE) as NsdManager
/** Returns the PowerManager instance. **/
val Context.powerManager: PowerManager
get() = getSystemService(Context.POWER_SERVICE) as PowerManager
/** Returns the PrintManager instance. **/
val Context.printManager: PrintManager
get() = getSystemService(Context.PRINT_SERVICE) as PrintManager
/** Returns the RestrictionsManager instance. **/
val Context.restrictionsManager: RestrictionsManager
get() = getSystemService(Context.RESTRICTIONS_SERVICE) as RestrictionsManager
/** Returns the SearchManager instance. **/
val Context.searchManager: SearchManager
get() = getSystemService(Context.SEARCH_SERVICE) as SearchManager
/** Returns the SensorManager instance. **/
val Context.sensorManager: SensorManager
get() = getSystemService(Context.SENSOR_SERVICE) as SensorManager
/** Returns the ShortcutManager instance. **/
val Context.shortcutManager: ShortcutManager
get() = getSystemService(Context.SHORTCUT_SERVICE) as ShortcutManager
/** Returns the StorageManager instance. **/
val Context.storageManager: StorageManager
get() = getSystemService(Context.STORAGE_SERVICE) as StorageManager
/** Returns the StorageStatsManager instance. **/
val Context.storageStatsManager: StorageStatsManager
get() = getSystemService(Context.STORAGE_STATS_SERVICE) as StorageStatsManager
/** Returns the SystemHealthManager instance. **/
val Context.systemHealthManager: SystemHealthManager
get() = getSystemService(Context.SYSTEM_HEALTH_SERVICE) as SystemHealthManager
/** Returns the TelecomManager instance. **/
val Context.telecomManager: TelecomManager
get() = getSystemService(Context.TELECOM_SERVICE) as TelecomManager
/** Returns the TelephonyManager instance. **/
val Context.telephonyManager: TelephonyManager
get() = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
/** Returns the TextClassificationManager instance. **/
val Context.textClassificationManager: TextClassificationManager
get() = getSystemService(Context.TEXT_CLASSIFICATION_SERVICE) as TextClassificationManager
/** Returns the TvInputManager instance. **/
val Context.tvInputManager: TvInputManager
get() = getSystemService(Context.TV_INPUT_SERVICE) as TvInputManager
/** Returns the UiModeManager instance. **/
val Context.uiModeManager: UiModeManager
get() = getSystemService(Context.UI_MODE_SERVICE) as UiModeManager
/** Returns the UsageStatsManager instance. **/
val Context.usageStatsManager: UsageStatsManager
get() = getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
/** Returns the UsbManager instance. **/
val Context.usbManager: UsbManager
get() = getSystemService(Context.USB_SERVICE) as UsbManager
/** Returns the UserManager instance. **/
val Context.userManager: UserManager
get() = getSystemService(Context.USER_SERVICE) as UserManager
/** Returns the WallpaperManager instance. **/
val Context.wallpaperManager: WallpaperManager
get() = getSystemService(Context.WALLPAPER_SERVICE) as WallpaperManager
/** Returns the WifiAwareManager instance. **/
val Context.wifiAwareManager: WifiAwareManager
get() = getSystemService(Context.WIFI_AWARE_SERVICE) as WifiAwareManager
/** Returns the WifiManager instance. **/
val Context.wifiManager: WifiManager
get() = getSystemService(Context.WIFI_SERVICE) as WifiManager
/** Returns the WifiP2pManager instance. **/
val Context.wifiP2pManager: WifiP2pManager
get() = getSystemService(Context.WIFI_P2P_SERVICE) as WifiP2pManager
/** Returns the WindowManager instance. **/
val Context.windowManager: WindowManager
get() = getSystemService(Context.WINDOW_SERVICE) as WindowManager
| mit | 7f243b155cf126ab1f10bde6741c8dcd | 33.971338 | 94 | 0.804754 | 5.330583 | false | false | false | false |
avenwu/jk-address-book | android/app/src/main/kotlin/com/jikexueyuan/mobile/address/ui/LoginActivity.kt | 1 | 9171 | package com.jikexueyuan.mobile.address.ui
import android.accounts.Account
import android.accounts.AccountManager
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.annotation.TargetApi
import android.content.Intent
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.view.View.OnClickListener
import android.view.inputmethod.EditorInfo
import android.widget.AutoCompleteTextView
import android.widget.EditText
import android.widget.TextView
import com.jikexueyuan.mobile.address.*
import com.jikexueyuan.mobile.address.api.AppService
import com.jikexueyuan.mobile.address.extention.startActivitySafely
import kotlinx.android.synthetic.content_login.email_sign_in_button
/**
* A login screen that offers login via email/password.
*/
class LoginActivity : AppCompatActivity() {
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private var mAuthTask: AsyncTask<*, *, *> ? = null
// UI references.
private var mEmailView: AutoCompleteTextView? = null
private var mPasswordView: EditText? = null
private var mProgressView: View? = null
private var mLoginFormView: View? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
mEmailView = findViewById(R.id.email) as AutoCompleteTextView
mPasswordView = findViewById(R.id.password) as EditText
mPasswordView!!.setOnEditorActionListener(object : TextView.OnEditorActionListener {
override fun onEditorAction(textView: TextView, id: Int, keyEvent: KeyEvent): Boolean {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin()
return true
}
return false
}
})
email_sign_in_button.setOnClickListener(object : OnClickListener {
override fun onClick(view: View) {
attemptLogin()
}
})
mLoginFormView = findViewById(R.id.login_form)
mProgressView = findViewById(R.id.login_progress)
if (!intent.hasExtra(Authenticator.PARAM_AUTHTOKEN_TYPE)) {
trySkipLogin()
}
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private fun attemptLogin() {
if (mAuthTask != null) {
return
}
// Reset errors.
mEmailView!!.error = null
mPasswordView!!.error = null
// Store values at the time of the login attempt.
val email = mEmailView!!.text.toString()
val password = mPasswordView!!.text.toString()
var cancel = false
var focusView: View? = null
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView!!.error = getString(R.string.error_invalid_password)
focusView = mPasswordView
cancel = true
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView!!.error = getString(R.string.error_field_required)
focusView = mEmailView
cancel = true
} else if (!isEmailValid(email)) {
mEmailView!!.error = getString(R.string.error_invalid_email)
focusView = mEmailView
cancel = true
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView!!.requestFocus()
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true)
var name = mEmailView!!.text.toString()
var pwd = mPasswordView!!.text.toString()
mAuthTask = AppService.login(name, pwd, { success ->
mAuthTask = null
showProgress(false)
if (success) {
val account = Account(name, Authenticator.PARAM_ACCOUNT_TYPE)
val bundle = Bundle()
AccountManager.get(this).addAccountExplicitly(account, pwd, bundle)
updateLoginTimestamp(this, System.currentTimeMillis())
startActivity(Intent(this, MainActivity::class.java))
finish()
} else {
if (isNetWorkAvailable(this)) {
mPasswordView!!.error = getString(R.string.error_incorrect_password)
mPasswordView!!.requestFocus()
} else {
Snackbar.make(mProgressView, R.string.network_is_unavailable, Snackbar.LENGTH_LONG)
.setAction(R.string.open_setting, {
startActivitySafely(Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS), {
Snackbar.make(mProgressView, R.string.failed_open_setting, Snackbar.LENGTH_SHORT).show()
})
}).show()
}
}
})
}
}
/**
* 1. 3分钟内免登陆; 2.有网自动登录;3.无网络有缓存,跳过登录
*/
fun trySkipLogin() {
var justLogin = (System.currentTimeMillis() - getLoginTimestamp(this)) < 3 * 60 * 1000
if (justLogin) {
startActivity(Intent(this, MainActivity::class.java))
finish()
} else {
val manager = AccountManager.get(this)
val accounts = manager.getAccountsByType(Authenticator.PARAM_ACCOUNT_TYPE)
if (accounts != null && accounts.size > 0) {
val name = accounts[0].name
val pwd = manager.getPassword(accounts[0])
if (!TextUtils.isEmpty(name)) {
mEmailView?.setText(name)
}
if (!TextUtils.isEmpty(pwd)) {
mPasswordView?.setText(pwd)
}
if (isNetWorkAvailable(this)) {
email_sign_in_button.performClick()
} else {
checkUserListCache(this, {
if (it) {
startActivity(Intent(this, MainActivity::class.java))
finish()
}
})
}
}
}
}
private fun isEmailValid(email: String): Boolean {
return true
}
private fun isPasswordValid(password: String): Boolean {
return password.length > 6
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private fun showProgress(show: Boolean) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
val shortAnimTime = resources.getInteger(android.R.integer.config_shortAnimTime)
mLoginFormView!!.visibility = if (show) View.GONE else View.VISIBLE
mLoginFormView!!.animate().setDuration(shortAnimTime.toLong()).alpha(
(if (show) 0 else 1).toFloat()).setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
mLoginFormView!!.visibility = if (show) View.GONE else View.VISIBLE
}
})
mProgressView!!.visibility = if (show) View.VISIBLE else View.GONE
mProgressView!!.animate().setDuration(shortAnimTime.toLong()).alpha(
(if (show) 1 else 0).toFloat()).setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
mProgressView!!.visibility = if (show) View.VISIBLE else View.GONE
}
})
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView!!.visibility = if (show) View.VISIBLE else View.GONE
mLoginFormView!!.visibility = if (show) View.GONE else View.VISIBLE
}
}
override fun onDestroy() {
super.onDestroy()
mAuthTask?.cancel(true)
}
}
| apache-2.0 | b88fa8df1602716a1403b7b022c9e102 | 37.65678 | 128 | 0.589609 | 5.102349 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/api/internal/registries/machines/sieve/SieveRecipe.kt | 2 | 1741 | package com.cout970.magneticraft.api.internal.registries.machines.sieve
import com.cout970.magneticraft.api.internal.ApiUtils
import com.cout970.magneticraft.api.registries.machines.sifter.ISieveRecipe
import com.cout970.magneticraft.misc.inventory.isNotEmpty
import net.minecraft.item.ItemStack
import net.minecraftforge.oredict.OreDictionary
/**
* Created by cout970 on 22/08/2016.
*/
data class SieveRecipe(
private val input: ItemStack,
private val primary: ItemStack,
private val primaryChance: Float,
private val secondary: ItemStack,
private val secondaryChance: Float,
private val tertiary: ItemStack,
private val tertiaryChance: Float,
private val ticks: Float,
private val oreDict: Boolean
) : ISieveRecipe {
init {
require(input.isNotEmpty) { "Input MUST be a non-empty stack" }
}
override fun useOreDictionaryEquivalencies(): Boolean = oreDict
override fun getInput(): ItemStack = input.copy()
override fun getPrimary(): ItemStack = primary.copy()
override fun getSecondary(): ItemStack = secondary.copy()
override fun getTertiary(): ItemStack = tertiary.copy()
override fun getPrimaryChance(): Float = primaryChance
override fun getSecondaryChance(): Float = secondaryChance
override fun getTertiaryChance(): Float = tertiaryChance
override fun getDuration(): Float = ticks
override fun matches(input: ItemStack): Boolean {
if (input.isEmpty) return false
if (ApiUtils.equalsIgnoreSize(input, this.input)) return true
if (oreDict) {
val ids = OreDictionary.getOreIDs(this.input)
return OreDictionary.getOreIDs(input).any { it in ids }
}
return false
}
} | gpl-2.0 | 7a2c9b2859a454fea1c8b0005c4b939f | 30.672727 | 75 | 0.720276 | 4.545692 | false | false | false | false |
spark/photon-tinker-android | app/src/main/java/io/particle/android/sdk/ui/devicelist/DeviceTypeFilterButton.kt | 1 | 3539 | package io.particle.android.sdk.ui.devicelist
import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.core.view.isVisible
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType
import io.particle.android.sdk.ui.devicelist.DeviceTypeFilter.ARGON
import io.particle.android.sdk.ui.devicelist.DeviceTypeFilter.BORON
import io.particle.android.sdk.ui.devicelist.DeviceTypeFilter.ELECTRON
import io.particle.android.sdk.ui.devicelist.DeviceTypeFilter.OTHER
import io.particle.android.sdk.ui.devicelist.DeviceTypeFilter.PHOTON
import io.particle.android.sdk.ui.devicelist.DeviceTypeFilter.XENON
import io.particle.commonui.toDecorationColor
import io.particle.commonui.toDecorationLetter
import io.particle.sdk.app.R
import kotlinx.android.synthetic.main.view_device_type_filter_button.view.*
class DeviceTypeFilterButton : FrameLayout {
var filter: DeviceTypeFilter
get() = _filter
set(value) {
_filter = value
updateFromNewFilter()
}
var isChecked: Boolean
get() {
return _checked
}
set(value) {
_checked = value
onCheckedChanged()
}
private var _filter: DeviceTypeFilter = ARGON
private var _checked = false
constructor(context: Context) : super(context) {
init(null, 0)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init(attrs, 0)
}
constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : super(
context,
attrs,
defStyle
) {
init(attrs, defStyle)
}
private fun init(attrs: AttributeSet?, defStyle: Int) {
inflate(context, R.layout.view_device_type_filter_button, this)
}
private fun onCheckedChanged() {
@DrawableRes val bg = if (_checked) {
R.drawable.device_filter_button_background_selected
} else {
R.drawable.device_filter_button_background_unselected
}
setBackgroundResource(bg)
}
private fun updateFromNewFilter() {
p_common_device_name.text = when (filter) {
BORON -> "Boron / B SoM"
ELECTRON -> "Electron / E SoM"
ARGON -> "Argon"
PHOTON -> "Photon / P1"
XENON -> "Xenon"
OTHER -> "Other"
}
if (filter == OTHER) {
p_common_device_letter_circle.isVisible = false
p_common_device_letter.isVisible = false
return
}
val asDeviceType = when (filter) {
BORON -> ParticleDeviceType.BORON
ELECTRON -> ParticleDeviceType.ELECTRON
ARGON -> ParticleDeviceType.ARGON
PHOTON -> ParticleDeviceType.PHOTON
XENON -> ParticleDeviceType.XENON
OTHER -> ParticleDeviceType.OTHER
}
@ColorInt val colorValue: Int = ContextCompat.getColor(
this.context,
asDeviceType.toDecorationColor()
)
val bg = p_common_device_letter_circle.drawable
bg.mutate()
DrawableCompat.setTint(bg, colorValue)
val letter = asDeviceType.toDecorationLetter()
p_common_device_letter.text = letter
p_common_device_letter.setTextColor(colorValue)
}
}
| apache-2.0 | d09915973098fadb76ce344be292fd56 | 30.882883 | 90 | 0.655552 | 4.440402 | false | false | false | false |
wireapp/wire-android | app/src/main/kotlin/com/waz/zclient/feature/backup/usecase/CreateBackUpUseCase.kt | 1 | 3086 | package com.waz.zclient.feature.backup.usecase
import com.waz.zclient.core.exception.Failure
import com.waz.zclient.core.functional.Either
import com.waz.zclient.core.functional.flatMap
import com.waz.zclient.core.functional.map
import com.waz.zclient.core.usecase.UseCase
import com.waz.zclient.core.utilities.DateAndTimeUtils.instantToString
import com.waz.zclient.core.utilities.DatePattern
import com.waz.zclient.feature.backup.BackUpRepository
import com.waz.zclient.feature.backup.crypto.encryption.EncryptionHandler
import com.waz.zclient.feature.backup.metadata.BackupMetaData
import com.waz.zclient.feature.backup.metadata.MetaDataHandler
import com.waz.zclient.feature.backup.zip.ZipHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import java.io.File
class CreateBackUpUseCase(
private val backUpRepositories: List<BackUpRepository<List<File>>>,
private val zipHandler: ZipHandler,
private val encryptionHandler: EncryptionHandler,
private val metaDataHandler: MetaDataHandler,
private val backUpVersion: Int,
private val coroutineScope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
) : UseCase<File, CreateBackUpUseCaseParams> {
override suspend fun run(params: CreateBackUpUseCaseParams): Either<Failure, File> =
backUpOrFail()
.flatMap { files ->
val metaData = BackupMetaData(
userId = params.userId,
clientId = params.clientId,
userHandle = params.userHandle,
backUpVersion = backUpVersion
)
metaDataHandler.generateMetaDataFile(metaData).map { files + it }
}
.flatMap { files ->
zipHandler.zip(backupFileName(params.userHandle) + ".zip", files)
}
.flatMap { file ->
encryptionHandler.encryptBackup(file, params.userId, params.password, backupFileName(params.userHandle))
}
private suspend fun backUpOrFail(): Either<Failure, List<File>> = extractFiles(
backUpRepositories
.map { coroutineScope.async(Dispatchers.IO) { it.saveBackup() } }
.awaitAll()
)
private fun backupFileName(userHandle: String): String {
val timestamp = instantToString(pattern = DatePattern.DATE_SHORT)
return "Wire-$userHandle-Backup_$timestamp.android_wbu"
}
private fun extractFiles(filesOrFailure: List<Either<Failure, List<File>>>): Either<Failure, List<File>> {
val files = mutableListOf<File>()
filesOrFailure.forEach {
when (it) {
is Either.Right -> files.addAll(it.b)
is Either.Left -> return Either.Left(it.a)
}
}
return Either.Right(files.toList())
}
}
data class CreateBackUpUseCaseParams(val userId: String, val clientId: String, val userHandle: String, val password: String)
| gpl-3.0 | 082a54df633485bef6048927ab0533e2 | 40.702703 | 124 | 0.697991 | 4.518302 | false | false | false | false |
facebook/litho | sample/src/main/java/com/facebook/samples/litho/kotlin/bordereffects/VerticalDashPathEffectBorder.kt | 1 | 1692 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.samples.litho.kotlin.bordereffects
import com.facebook.litho.Border
import com.facebook.litho.Component
import com.facebook.litho.ComponentScope
import com.facebook.litho.KComponent
import com.facebook.litho.Row
import com.facebook.litho.Style
import com.facebook.litho.dp
import com.facebook.litho.flexbox.border
import com.facebook.litho.kotlin.widget.Border
import com.facebook.litho.kotlin.widget.BorderEdge
import com.facebook.litho.kotlin.widget.BorderEffect
import com.facebook.litho.kotlin.widget.Text
class VerticalDashPathEffectBorder : KComponent() {
override fun ComponentScope.render(): Component {
return Row(
style =
Style.border(
Border(
BorderEdge(width = 5f.dp),
edgeVertical = BorderEdge(color = NiceColor.RED),
effect = BorderEffect.dashed(floatArrayOf(20f, 5f), 0f)))) {
child(
Text(
"This component has a dash path effect on its vertical edges", textSize = 20f.dp))
}
}
}
| apache-2.0 | b53f9bafc09f9329f75339ea633381f9 | 35 | 100 | 0.706856 | 4.188119 | false | false | false | false |
maballesteros/vertx3-kotlin-rest-jdbc-tutorial | step04/src/db_utils.kt | 1 | 3230 | import io.vertx.core.Future
import io.vertx.core.json.JsonArray
import io.vertx.ext.jdbc.JDBCClient
import io.vertx.ext.sql.ResultSet
import io.vertx.ext.sql.SQLConnection
/**
* Created by mike on 14/11/15.
*/
fun JDBCClient.withConnection(res: (SQLConnection) -> Future<Unit>): Future<Unit> {
val finished = Future.future<Unit>()
getConnection {
if (it.succeeded()) {
val connection = it.result()
val done = res(connection)
done.setHandler {
// Anyway, close!
connection.close()
if (it.succeeded()) finished.complete()
else finished.fail(it.cause())
}
} else {
finished.fail(it.cause())
}
}
return finished
}
fun JDBCClient.query<T>(query: String, params: List<Any>, rsHandler: (ResultSet) -> List<T>): Future<List<T>> {
val future = Future.future<List<T>>()
withConnection {
val finished = Future.future<Unit>()
it.queryWithParams(query, JsonArray(params), {
if (it.succeeded()) {
try {
val result = rsHandler(it.result());
future.complete(result)
} catch (t: Throwable) {
future.fail(t)
} finally {
finished.complete()
}
} else {
finished.fail(it.cause())
}
})
finished
}
return future
}
fun JDBCClient.queryOne<T>(query: String, params: List<Any>, rsHandler: (ResultSet) -> T): Future<T> {
val future = Future.future<T>()
withConnection {
val finished = Future.future<Unit>()
it.queryWithParams(query, JsonArray(params), {
if (it.succeeded()) {
try {
val result = rsHandler(it.result());
println("queryOne => $result")
future.complete(result)
} catch (t: Throwable) {
future.fail(t)
} finally {
finished.complete()
}
} else {
it.cause().printStackTrace()
finished.fail(it.cause())
}
})
finished
}
return future
}
fun JDBCClient.update(query: String, params: List<Any>): Future<Unit> {
return withConnection {
val finished = Future.future<Unit>()
it.updateWithParams(query, JsonArray(params), {
if (it.succeeded()) {
finished.complete()
} else {
println("ERROR: $query ($params)")
it.cause().printStackTrace()
finished.fail(it.cause())
}
})
finished
}
}
fun JDBCClient.execute(query: String): Future<Unit> {
return withConnection {
val finished = Future.future<Unit>()
it.execute(query, {
if (it.succeeded()) {
finished.complete()
}
else {
println("ERROR: " + query)
it.cause().printStackTrace()
finished.fail(it.cause())
}
})
finished
}
} | apache-2.0 | 86e5efe73bde87baf4e74b9508689571 | 28.642202 | 111 | 0.494737 | 4.549296 | false | false | false | false |
Kiskae/Twitch-Archiver | hls-parser/src/main/kotlin/net/serverpeon/twitcharchiver/hls/TagRepository.kt | 1 | 2606 | package net.serverpeon.twitcharchiver.hls
import com.google.common.collect.ImmutableMap
/**
*
*/
sealed class TagRepository(tags: Collection<HlsTag<*>>) {
protected var internalTags: ImmutableMap<String, HlsTag<*>> = buildInitialMap(tags)
private fun buildInitialMap(tags: Collection<HlsTag<*>>): ImmutableMap<String, HlsTag<*>> {
val builder = ImmutableMap.builder<String, HlsTag<*>>()
tags.forEach { builder.put(it.tag, it) }
return builder.build()
}
operator fun get(index: String): HlsTag<*>? {
return this.internalTags[index]
}
companion object {
val DEFAULT: TagRepository = TagRepository.Mutable(arrayListOf(
OfficialTags.EXT_X_ALLOW_CACHE,
OfficialTags.EXT_X_BYTERANGE,
OfficialTags.EXT_X_DISCONTINUITY,
OfficialTags.EXT_X_ENDLIST,
OfficialTags.EXT_X_I_FRAME_STREAM_INF,
OfficialTags.EXT_X_I_FRAMES_ONLY,
OfficialTags.EXT_X_MEDIA,
OfficialTags.EXT_X_MEDIA_SEQUENCE,
OfficialTags.EXT_X_PLAYLIST_TYPE,
OfficialTags.EXT_X_PROGRAM_DATE_TIME,
OfficialTags.EXT_X_STREAM_INF,
OfficialTags.EXT_X_TARGETDURATION,
OfficialTags.EXT_X_VERSION,
OfficialTags.EXTINF,
OfficialTags.EXTM3U,
OfficialTags.EXT_X_KEY
))
fun newRepository(): TagRepository.Mutable = TagRepository.Mutable(DEFAULT.internalTags.values)
}
class Mutable internal constructor(tags: Collection<HlsTag<*>>) : TagRepository(tags) {
/**
* Register a new tag that will be extracted from the HLS playlist
*
* @param tag the handler that will handle the parsing of the associated tag
* @param override Whether to override an existing tag if it already exists
* @throws IllegalStateException Thrown if a duplicate tag is registered and [override] is false
*/
fun <T> register(tag: HlsTag<T>, override: Boolean = false) {
this.internalTags = ImmutableMap.builder<String, HlsTag<*>>()
.putAll(this.internalTags.let {
if (override) {
// Remove any pre-existing handler with the same tag
it.filterKeys { it != tag.tag }
} else {
it
}
})
.put(tag.tag, tag)
.build()
}
}
} | mit | 9ed5c18b76ab5ef6d4feece9262d0e14 | 38.5 | 104 | 0.568304 | 4.907721 | false | false | false | false |
zamesilyasa/kandrextensions | lib/src/androidTest/kotlin/com/wnc_21/kandroidextensions/view/TestSupportFragmentManager.kt | 1 | 10475 | package com.wnc_21.kandroidextensions.view
import android.os.Bundle
import android.support.test.runner.AndroidJUnit4
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentTransaction
import android.view.View
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import java.io.FileDescriptor
import java.io.PrintWriter
@RunWith(AndroidJUnit4::class)
class TestSupportFragmentManager {
@Test
fun SupportFragmentManager_searchesForFragmentByTag() {
val mgrWithFragment: FragmentManager = object: MockSupportFragmentManager() {
override fun findFragmentByTag(tag: String?): Fragment? = Fragment()
}
assertTrue(mgrWithFragment.isFragmentAdded("ANY"))
val mgrWithoutFragment: FragmentManager = object : MockSupportFragmentManager() {
override fun findFragmentByTag(tag: String?): Fragment? {
return null
}
}
assertFalse(mgrWithoutFragment.isFragmentAdded("ANY"))
}
@Test
fun SupportFragmentManager_add_fragment_ifNot() {
var tag: String? = null
val tr = object: MockTransaction() {
override fun add(containerViewId: Int, fragment: Fragment?, trTag: String?): FragmentTransaction {
tag = trTag
return this
}
}
val fm = object: MockSupportFragmentManager() {
override fun findFragmentByTag(aTag: String?): Fragment? = if (tag == aTag) Fragment() else null
override fun beginTransaction(): FragmentTransaction {
return tr
}
}
assertFalse(fm.isFragmentAdded("TAG"))
assertTrue(fm.addIfNot("TAG", {it.add(1, Fragment(), "TAG")}))
assertTrue(fm.isFragmentAdded("TAG"))
assertFalse(fm.addIfNot("TAG", {it.add(1, Fragment(), "TAG")}))
}
}
abstract class MockSupportFragmentManager : FragmentManager() {
override fun saveFragmentInstanceState(f: Fragment?): Fragment.SavedState {
throw UnsupportedOperationException("Not mocked")
}
override fun findFragmentById(id: Int): Fragment {
throw UnsupportedOperationException("Not mocked")
}
override fun getFragments(): MutableList<Fragment>? {
throw UnsupportedOperationException("Not mocked")
}
override fun beginTransaction(): FragmentTransaction {
throw UnsupportedOperationException("Not mocked")
}
override fun putFragment(bundle: Bundle?, key: String?, fragment: Fragment?) {
throw UnsupportedOperationException("Not mocked")
}
override fun removeOnBackStackChangedListener(listener: OnBackStackChangedListener?) {
throw UnsupportedOperationException("Not mocked")
}
override fun getFragment(bundle: Bundle?, key: String?): Fragment {
throw UnsupportedOperationException("Not mocked")
}
override fun getBackStackEntryCount(): Int {
throw UnsupportedOperationException("Not mocked")
}
override fun isDestroyed(): Boolean {
throw UnsupportedOperationException("Not mocked")
}
override fun getBackStackEntryAt(index: Int): BackStackEntry {
throw UnsupportedOperationException("Not mocked")
}
override fun executePendingTransactions(): Boolean {
throw UnsupportedOperationException("Not mocked")
}
override fun popBackStackImmediate(): Boolean {
throw UnsupportedOperationException("Not mocked")
}
override fun popBackStackImmediate(name: String?, flags: Int): Boolean {
throw UnsupportedOperationException("Not mocked")
}
override fun popBackStackImmediate(id: Int, flags: Int): Boolean {
throw UnsupportedOperationException("Not mocked")
}
override fun findFragmentByTag(tag: String?): Fragment? {
throw UnsupportedOperationException("Not mocked")
}
override fun addOnBackStackChangedListener(listener: OnBackStackChangedListener?) {
throw UnsupportedOperationException("Not mocked")
}
override fun dump(prefix: String?, fd: FileDescriptor?, writer: PrintWriter?, args: Array<out String>?) {
throw UnsupportedOperationException("Not mocked")
}
override fun popBackStack() {
throw UnsupportedOperationException("Not mocked")
}
override fun popBackStack(name: String?, flags: Int) {
throw UnsupportedOperationException("Not mocked")
}
override fun popBackStack(id: Int, flags: Int) {
throw UnsupportedOperationException("Not mocked")
}
}
abstract class MockTransaction: FragmentTransaction() {
override fun setBreadCrumbShortTitle(res: Int): FragmentTransaction {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setBreadCrumbShortTitle(text: CharSequence?): FragmentTransaction {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun commit(): Int {
return 0
}
override fun add(fragment: Fragment?, tag: String?): FragmentTransaction {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun add(containerViewId: Int, fragment: Fragment?): FragmentTransaction {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun add(containerViewId: Int, fragment: Fragment?, tag: String?): FragmentTransaction {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun hide(fragment: Fragment?): FragmentTransaction {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun replace(containerViewId: Int, fragment: Fragment?): FragmentTransaction {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun replace(containerViewId: Int, fragment: Fragment?, tag: String?): FragmentTransaction {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun detach(fragment: Fragment?): FragmentTransaction {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun commitAllowingStateLoss(): Int {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setCustomAnimations(enter: Int, exit: Int): FragmentTransaction {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setCustomAnimations(enter: Int, exit: Int, popEnter: Int, popExit: Int): FragmentTransaction {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun addToBackStack(name: String?): FragmentTransaction {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun disallowAddToBackStack(): FragmentTransaction {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setTransitionStyle(styleRes: Int): FragmentTransaction {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setTransition(transit: Int): FragmentTransaction {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun attach(fragment: Fragment?): FragmentTransaction {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun show(fragment: Fragment?): FragmentTransaction {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isEmpty(): Boolean {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun remove(fragment: Fragment?): FragmentTransaction {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isAddToBackStackAllowed(): Boolean {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun addSharedElement(sharedElement: View?, name: String?): FragmentTransaction {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun commitNow() {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setBreadCrumbTitle(res: Int): FragmentTransaction {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setBreadCrumbTitle(text: CharSequence?): FragmentTransaction {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun commitNowAllowingStateLoss() {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
} | apache-2.0 | 59d7fb7a3fa36b0b34015adf74d8ede2 | 39.762646 | 138 | 0.716277 | 5.689842 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/editor/resources/TextHtmlGenerator.kt | 1 | 3920 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.editor.resources
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.project.ProjectManager
import com.intellij.psi.PsiFile
import com.vladsch.flexmark.html.HtmlRenderer
import com.vladsch.flexmark.parser.Parser
import com.vladsch.flexmark.util.ast.Document
import com.vladsch.flexmark.util.data.MutableDataHolder
import com.vladsch.flexmark.util.sequence.BasedSequence
import com.vladsch.flexmark.util.sequence.TagRange
import com.vladsch.md.nav.editor.PreviewFileEditorBase
import com.vladsch.md.nav.editor.util.HtmlGenerator
import com.vladsch.md.nav.parser.PegdownOptionsAdapter
import com.vladsch.md.nav.parser.api.HtmlPurpose
import com.vladsch.md.nav.parser.api.ParserPurpose
import com.vladsch.md.nav.parser.flexmark.MdNavigatorExtension
import com.vladsch.md.nav.settings.MdRenderingProfile
import com.vladsch.md.nav.vcs.MdLinkResolver
import com.vladsch.plugin.util.TimeIt
import java.util.function.Consumer
import java.util.function.Supplier
class TextHtmlGenerator(linkResolver: MdLinkResolver, renderingProfile: MdRenderingProfile) : HtmlGenerator(linkResolver, renderingProfile) {
protected var tagRanges: List<TagRange> = listOf()
override val htmlTagRanges: List<TagRange>
get() = tagRanges
override fun toHtml(
file: PsiFile?,
charSequence: CharSequence,
htmlPurpose: HtmlPurpose,
dataContext: DataContext?,
exportMap: MutableMap<String, String>?,
optionsAdjuster: Consumer<MutableDataHolder>?
): String {
val forHtmlExport = htmlPurpose == HtmlPurpose.EXPORT
@Suppress("NAME_SHADOWING")
var dataContext = dataContext
val optionAdapter = PegdownOptionsAdapter()
val options = optionAdapter.getFlexmarkOptions(ParserPurpose.HTML, htmlPurpose, linkResolver, renderingProfile).toMutable()
val project = linkResolver.project ?: ProjectManager.getInstance().defaultProject
options.set(MdNavigatorExtension.RENDERING_PROFILE, Supplier { renderingProfile })
if (renderingProfile.htmlSettings.noParaTags) {
options.set(HtmlRenderer.NO_P_TAGS_USE_BR, true)
}
if (forHtmlExport && dataContext != null) {
dataContext = addHtmlExportData(project, options, dataContext, exportMap)
}
optionsAdjuster?.accept(options)
val parser = Parser.builder(options).build()
val renderer = HtmlRenderer.builder(options).build()
val document: Document = TimeIt.logTimedValue(PreviewFileEditorBase.LOG, "TextHtmlGenerator::toHtml - parse document") {
parser.parse(BasedSequence.of(charSequence))
}
// see if document has includes
var useDocument = document
var useRenderer = renderer
TimeIt.logTime(PreviewFileEditorBase.LOG, "TextHtmlGenerator::toHtml - processIncludes") {
useDocument = processIncludes(parser, renderer, document, file)
if (useDocument !== document) {
// options need to be adjusted to match new document
useRenderer = HtmlRenderer.builder(useDocument).build()
}
}
val html = TimeIt.logTimedValue(PreviewFileEditorBase.LOG, "TextHtmlGenerator::toHtml - render document") {
useRenderer.render(useDocument)
}
val postProcessedHtml = postProcessHtml(html)
tagRanges = HtmlRenderer.TAG_RANGES[useDocument]
return makeHtmlPage(postProcessedHtml, forHtmlExport, dataContext, exportMap)
}
override fun makeHtmlPage(html: String, forHtmlExport: Boolean, dataContext: DataContext?, exportMap: MutableMap<String, String>?): String {
return html + "\n"
}
}
| apache-2.0 | 078f2c8af37404d6fb88dd13b4c3e000 | 42.076923 | 177 | 0.729847 | 4.526559 | false | false | false | false |
actions-on-google/actions-on-google-java | src/main/kotlin/com/google/actions/api/impl/AogRequest.kt | 1 | 17581 | /*
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.actions.api.impl
import com.google.actions.api.*
import com.google.actions.api.impl.io.*
import com.google.api.services.actions_fulfillment.v2.model.*
import com.google.api.services.dialogflow_fulfillment.v2.model.WebhookRequest
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonObject
import com.google.gson.reflect.TypeToken
import org.slf4j.LoggerFactory
import java.util.*
internal class AogRequest internal constructor(
override val appRequest: AppRequest) : ActionRequest {
override val webhookRequest: WebhookRequest? get() = null
override var userStorage: MutableMap<String, Any> = HashMap()
override var conversationData: MutableMap<String, Any> = HashMap()
override val intent: String
get() {
val inputs = appRequest.inputs
if (inputs == null || inputs.size == 0) {
LOG.warn("Request has no inputs.")
throw IllegalArgumentException("Request has no inputs")
}
return appRequest.inputs[0].intent
}
override val user: User? get() = appRequest.user
override val device: Device? get() = appRequest.device
override val surface: Surface? get() = appRequest.surface
override val availableSurfaces: List<Surface>?
get() =
appRequest.availableSurfaces
override val isInSandbox: Boolean get() = appRequest.isInSandbox
override val rawText: String?
get() = rawInput?.query
override val rawInput: RawInput?
get() {
val inputs = appRequest.inputs
if (inputs != null && inputs.size > 0) {
val rawInputs = inputs[0].rawInputs
if (rawInputs != null && rawInputs.size > 0) {
return rawInputs[0]
}
}
return null
}
override val locale: Locale
get() {
val localeString = user?.locale
val parts = localeString?.split("-")
if (parts != null) {
when (parts.size) {
1 -> return Locale(parts[0])
2 -> return Locale(parts[0], parts[1])
}
}
return Locale.getDefault()
}
override val repromptCount: Int?
get() {
val arg = getArgument(ARG_REPROMPT_COUNT)
arg ?: return null
return arg.intValue?.toInt()
}
override val isFinalPrompt: Boolean?
get() {
val arg = getArgument(ARG_IS_FINAL_REPROMPT)
arg ?: return false
return arg.boolValue
}
override val sessionId: String
get() {
return appRequest.conversation.conversationId
}
override fun getArgument(name: String): Argument? {
val inputs = appRequest.inputs
if (inputs == null || inputs.size == 0) {
return null
}
val arguments = inputs[0].arguments
arguments ?: return null
for (argument in arguments) {
if (argument.name == name) {
return argument
}
}
return null
}
override fun getParameter(name: String): Any? {
// Only valid for Dialogflow requests.
return null
}
override fun hasCapability(capability: String): Boolean {
// appRequest can be null for requests from Dialogflow simulator.
val surface = appRequest.surface
if (surface != null) {
val capabilityList = surface.capabilities
return capabilityList.stream()
.anyMatch { c -> capability == c.name }
}
return false
}
override fun isSignInGranted(): Boolean {
val arg = getArgument(ARG_SIGN_IN)
arg ?: return false
val map = arg.extension
val status = map!!["status"] as String
return (status == "OK")
}
override fun isUpdateRegistered(): Boolean {
val arg = getArgument(ARG_REGISTER_UPDATE)
arg ?: return false
val map = arg.extension
val status = map!!["status"] as String
return (status == "OK")
}
override fun getPlace(): Location? {
val arg = getArgument(ARG_PLACE)
arg ?: return null
return arg.placeValue
}
override fun isPermissionGranted(): Boolean {
val arg = getArgument(ARG_PERMISSION)
arg ?: return false
return arg.textValue != null && arg.textValue.equals("true")
}
override fun getUserConfirmation(): Boolean {
val arg = getArgument(ARG_CONFIRMATION)
arg ?: return false
return arg.boolValue
}
override fun getDateTime(): DateTime? {
val arg = getArgument(ARG_DATETIME)
arg ?: return null
return arg.datetimeValue
}
override fun getMediaStatus(): String? {
val arg = getArgument(ARG_MEDIA_STATUS)
arg ?: return null
return arg.extension?.get("status") as String
}
override fun getSelectedOption(): String? {
val arg = getArgument(ARG_OPTION)
arg ?: return null
return arg.textValue
}
override fun getContext(name: String): ActionContext? {
// Actions SDK does not support concept of Context.
return null
}
override fun getContexts(): List<ActionContext> {
// Actions SDK does not support concept of Context.
return ArrayList()
}
companion object {
private val LOG = LoggerFactory.getLogger(AogRequest::class.java.name)
fun create(appRequest: AppRequest): AogRequest {
return AogRequest(appRequest)
}
fun create(
body: String,
headers: Map<*, *>? = HashMap<String, Any>(),
partOfDialogflowRequest: Boolean = false):
AogRequest {
val gson = Gson()
return create(gson.fromJson(body, JsonObject::class.java), headers,
partOfDialogflowRequest)
}
fun create(
json: JsonObject,
headers: Map<*, *>? = HashMap<String, Any>(),
partOfDialogflowRequest: Boolean = false):
AogRequest {
val gsonBuilder = GsonBuilder()
gsonBuilder
.registerTypeAdapter(AppRequest::class.java,
AppRequestDeserializer())
.registerTypeAdapter(User::class.java,
UserDeserializer())
.registerTypeAdapter(Input::class.java,
InputDeserializer())
.registerTypeAdapter(Status::class.java,
StatusDeserializer())
.registerTypeAdapter(Surface::class.java,
SurfaceDeserializer())
.registerTypeAdapter(Device::class.java,
DeviceDeserializer())
.registerTypeAdapter(Location::class.java,
LocationDeserializer())
.registerTypeAdapter(Argument::class.java,
ArgumentDeserializer())
.registerTypeAdapter(RawInput::class.java,
RawInputDeserializer())
.registerTypeAdapter(PackageEntitlement::class.java,
PackageEntitlementDeserializer())
.registerTypeAdapter(Entitlement::class.java,
EntitlementDeserializer())
.registerTypeAdapter(SignedData::class.java,
SignedDataDeserializer())
.registerTypeAdapter(DateTime::class.java,
DateTimeValueDeserializer())
.registerTypeAdapter(Order::class.java,
OrderDeserializer())
.registerTypeAdapter(CustomerInfo::class.java,
CustomerInfoDeserializer())
.registerTypeAdapter(ProposedOrder::class.java,
ProposedOrderDeserializer())
.registerTypeAdapter(Cart::class.java,
CartDeserializer())
.registerTypeAdapter(LineItem::class.java,
LineItemDeserializer())
.registerTypeAdapter(LineItemSubLine::class.java,
LineItemSubLineDeserializer())
.registerTypeAdapter(Promotion::class.java,
PromotionDeserializer())
.registerTypeAdapter(Merchant::class.java,
MerchantDeserializer())
.registerTypeAdapter(Image::class.java,
ImageDeserializer())
.registerTypeAdapter(Price::class.java,
PriceDeserializer())
.registerTypeAdapter(Money::class.java,
MoneyDeserializer())
.registerTypeAdapter(PaymentInfo::class.java,
PaymentInfoDeserializer())
.registerTypeAdapter(PaymentInfoGoogleProvidedPaymentInstrument::class.java,
PaymentInfoGoogleProvidedPaymentInstrumentDeserializer())
.registerTypeAdapter(TransactionRequirementsCheckResult::class.java,
TransactionRequirementsCheckResultDeserializer())
.registerTypeAdapter(OrderV3::class.java,
OrderV3Deserializer())
.registerTypeAdapter(UserInfo::class.java,
UserInfoDeserializer())
.registerTypeAdapter(OrderContents::class.java,
OrderContentsDeserializer())
.registerTypeAdapter(PaymentData::class.java,
PaymentDataDeserializer())
.registerTypeAdapter(PurchaseOrderExtension::class.java,
PurchaseOrderExtensionDeserializer())
.registerTypeAdapter(TicketOrderExtension::class.java,
TicketOrderExtensionDeserializer())
.registerTypeAdapter(MerchantV3::class.java,
MerchantV3Deserializer())
.registerTypeAdapter(Disclosure::class.java,
DisclosureDeserializer())
.registerTypeAdapter(Action::class.java,
ActionDeserializer())
.registerTypeAdapter(PriceAttribute::class.java,
PriceAttributeDeserializer())
.registerTypeAdapter(PromotionV3::class.java,
PromotionV3Deserializer())
.registerTypeAdapter(PhoneNumber::class.java,
PhoneNumberDeserializer())
.registerTypeAdapter(LineItemV3::class.java,
LineItemV3Deserializer())
.registerTypeAdapter(PaymentInfoV3::class.java,
PaymentInfoV3Deserializer())
.registerTypeAdapter(PaymentResult::class.java,
PaymentResultDeserializer())
.registerTypeAdapter(PurchaseFulfillmentInfo::class.java,
PurchaseFulfillmentInfoDeserializer())
.registerTypeAdapter(PurchaseReturnsInfo::class.java,
PurchaseReturnsInfoDeserializer())
.registerTypeAdapter(PurchaseError::class.java,
PurchaseErrorDeserializer())
.registerTypeAdapter(TicketEvent::class.java,
TicketEventDeserializer())
.registerTypeAdapter(DisclosureText::class.java,
DisclosureTextDeserializer())
.registerTypeAdapter(DisclosurePresentationOptions::class.java,
DisclosurePresentationOptionsDeserializer())
.registerTypeAdapter(ActionActionMetadata::class.java,
ActionActionMetadataDeserializer())
.registerTypeAdapter(OpenUrlAction::class.java,
OpenUrlActionDeserializer())
.registerTypeAdapter(MoneyV3::class.java,
MoneyV3Deserializer())
.registerTypeAdapter(PurchaseItemExtension::class.java,
PurchaseItemExtensionDeserializer())
.registerTypeAdapter(ReservationItemExtension::class.java,
ReservationItemExtensionDeserializer())
.registerTypeAdapter(PaymentMethodDisplayInfo::class.java,
PaymentMethodDisplayInfoDeserializer())
.registerTypeAdapter(TimeV3::class.java,
TimeV3Deserializer())
.registerTypeAdapter(PickupInfo::class.java,
PickupInfoDeserializer())
.registerTypeAdapter(CheckInInfo::class.java,
CheckInInfoDeserializer())
.registerTypeAdapter(EventCharacter::class.java,
EventCharacterDeserializer())
.registerTypeAdapter(DisclosureTextTextLink::class.java,
DisclosureTextTextLinkDeserializer())
.registerTypeAdapter(AndroidApp::class.java,
AndroidAppDeserializer())
.registerTypeAdapter(ProductDetails::class.java,
ProductDetailsDeserializer())
.registerTypeAdapter(MerchantUnitMeasure::class.java,
MerchantUnitMeasureDeserializer())
.registerTypeAdapter(PurchaseItemExtensionItemOption::class.java,
PurchaseItemExtensionItemOptionDeserializer())
.registerTypeAdapter(StaffFacilitator::class.java,
StaffFacilitatorDeserializer())
.registerTypeAdapter(PickupInfoCurbsideInfo::class.java,
PickupInfoCurbsideInfoDeserializer())
.registerTypeAdapter(AndroidAppVersionFilter::class.java,
AndroidAppVersionFilterDeserializer())
.registerTypeAdapter(Vehicle::class.java,
VehicleDeserializer())
.registerTypeAdapter(genericType<Map<String, Any>>(),
ExtensionDeserializer())
val gson = gsonBuilder.create()
val appRequest = gson.fromJson<AppRequest>(json, AppRequest::class.java)
val aogRequest = create(appRequest)
val user = aogRequest.appRequest.user
if (user != null) {
aogRequest.userStorage = fromJson(user.userStorage)
}
if (!partOfDialogflowRequest) {
// Note: If the AogRequest is being created as part of a DF request,
// conversationToken is repurposed for some other values and does not
// contain conversation data.
val conversation = aogRequest.appRequest.conversation
val conversationToken: String? = conversation?.conversationToken
if (conversationToken != null) {
// Note that if the request is part of a Dialogflow request, the
// conversationData is empty here. DialogflowRequest should contain the
// values as it is read from outputContext.
aogRequest.conversationData = fromJson(
conversation.conversationToken)
}
}
return aogRequest
}
private fun fromJson(serializedValue: String?): MutableMap<String, Any> {
if (serializedValue != null && !serializedValue.isEmpty()) {
val gson = Gson()
try {
val map: Map<String, Any> = gson.fromJson(serializedValue,
object : TypeToken<Map<String, Any>>() {}.type)
// NOTE: The format of the opaque string is:
// keyValueData: {key:value; key:value; }
if (map["data"] != null) {
return map["data"] as MutableMap<String, Any>
}
} catch (e: Exception) {
LOG.warn("Error parsing conversation/user storage.", e)
}
}
return HashMap()
}
}
} | apache-2.0 | 210a8370045b4a4898cfe06598038bea | 42.305419 | 96 | 0.553438 | 6.016769 | false | false | false | false |
TeleSoftas/android-core | telesoftas-common/src/main/kotlin/com/telesoftas/core/common/presenter/BasePresenter.kt | 1 | 435 | package com.telesoftas.core.common.presenter
open class BasePresenter<V> : Presenter<V> {
protected open var view: V? = null
override fun takeView(view: V) {
this.view = view
}
override fun dropView() {
view = null // NOPMD
}
protected fun hasView() = view != null
protected fun onView(action: V.() -> Unit) {
if (hasView()) {
action.invoke(view!!)
}
}
} | apache-2.0 | baa0954a0098908f651baf565fce2ac6 | 19.761905 | 48 | 0.565517 | 3.815789 | false | false | false | false |
lgou2w/MoonLakeLauncher | src/main/kotlin/com/minecraft/moonlake/launcher/control/MuiResourceImage.kt | 1 | 2325 | /*
* Copyright (C) 2017 The MoonLake 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 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.minecraft.moonlake.launcher.control
import com.minecraft.moonlake.launcher.layout.MuiStackPane
import com.minecraft.moonlake.launcher.util.ClassUtils
import javafx.beans.property.SimpleStringProperty
import javafx.beans.property.StringProperty
import javafx.scene.image.Image
import javafx.scene.image.ImageView
class MuiResourceImage: MuiStackPane {
/**************************************************************************
*
* Private Member
*
**************************************************************************/
private var image: ImageView = ImageView()
/**************************************************************************
*
* Constructor
*
**************************************************************************/
constructor(): super() {
this.url.addListener { _, _, newValue -> run {
if(newValue != null) {
val stream = ClassUtils.loadResourceAsInputStream(MuiResourceImage::class.java, newValue)
this.image.image = Image(stream)
}
}}
this.children.add(0, image)
this.image.styleClass.add("mui-res-image")
}
/**************************************************************************
*
* Properties
*
**************************************************************************/
private var url: StringProperty = SimpleStringProperty()
fun urlProperty(): StringProperty
= url
fun getUrl(): String
= url.get()
fun setUrl(url: String)
= this.url.set(url)
}
| gpl-3.0 | 3d9f61776c299c537019a9a5bd634098 | 32.214286 | 105 | 0.536344 | 5.308219 | false | false | false | false |
quarkusio/quarkus | integration-tests/mongodb-panache-kotlin/src/main/kotlin/io/quarkus/it/mongodb/panache/book/BookEntity.kt | 1 | 1811 | package io.quarkus.it.mongodb.panache.book
import com.fasterxml.jackson.annotation.JsonFormat
import com.fasterxml.jackson.annotation.JsonFormat.Shape
import io.quarkus.mongodb.panache.common.MongoEntity
import io.quarkus.mongodb.panache.kotlin.PanacheMongoCompanion
import io.quarkus.mongodb.panache.kotlin.PanacheMongoEntity
import io.quarkus.mongodb.panache.kotlin.runtime.KotlinMongoOperations.Companion.INSTANCE
import org.bson.codecs.pojo.annotations.BsonIgnore
import org.bson.codecs.pojo.annotations.BsonProperty
import org.bson.types.ObjectId
import java.time.LocalDate
@MongoEntity(collection = "TheBookEntity", clientName = "cl2")
class BookEntity : PanacheMongoEntity() {
companion object : PanacheMongoCompanion<BookEntity> {
override fun findById(id: ObjectId): BookEntity {
return INSTANCE.findById(BookEntity::class.java, id) as BookEntity
}
}
@BsonProperty("bookTitle")
var title: String? = null
private set
var author: String? = null
private set
@BsonIgnore
var transientDescription: String? = null
@JsonFormat(shape = Shape.STRING, pattern = "yyyy-MM-dd")
var creationDate: LocalDate? = null
var categories = listOf<String>()
private set
private var details: BookDetail? = null
fun setTitle(title: String?): BookEntity {
this.title = title
return this
}
fun setAuthor(author: String?): BookEntity {
this.author = author
return this
}
fun setCategories(categories: List<String>): BookEntity {
this.categories = categories
return this
}
fun getDetails(): BookDetail? {
return details
}
fun setDetails(details: BookDetail?): BookEntity {
this.details = details
return this
}
}
| apache-2.0 | b7e94d905ebc8bea164c87d909d4dc00 | 29.183333 | 89 | 0.707344 | 4.417073 | false | false | false | false |
MitI-7/LamuneSoda | src/com/github/MitI_7/contest/POJ.kt | 1 | 3673 | package com.github.MitI_7.contest
import com.github.MitI_7.Settings
import com.intellij.openapi.components.ServiceManager
import com.squareup.okhttp.FormEncodingBuilder
import com.squareup.okhttp.OkHttpClient
import com.squareup.okhttp.Request
import com.squareup.okhttp.Response
import java.net.CookieManager
import java.util.concurrent.TimeUnit
class POJ() : ContestSite {
var client = OkHttpClient()
val settings = ServiceManager.getService(Settings::class.java)
init {
val cookieManager = CookieManager()
cookieManager.setCookiePolicy(java.net.CookiePolicy.ACCEPT_ALL)
this.client.cookieHandler = cookieManager
this.client.setConnectTimeout(Settings.TIMEOUT, TimeUnit.SECONDS)
this.login(settings.POJUserID, settings.POJPassword)
}
override fun submit(lesson_id: String, problem_no: String, language: String, source_code: String): String {
val form = FormEncodingBuilder().addEncoded("problem_id", problem_no)
.addEncoded("language", this.get_language_map()[language])
.add("source", source_code)
.addEncoded("submit", "Submit")
.addEncoded("encoded", "0")
val url = "http://poj.org/submit"
var response: Response? = null
try {
response = this.client.newCall(Request.Builder().url(url).post(form.build()).build()).execute()
if (!response.isSuccessful) {
return "submission error: code is ${response.code()}"
}
return this.make_message(response.body().string(), problem_no, language)
} catch (e: Exception) {
return "submission error: $e.toString()"
} finally {
response!!.body().close()
}
}
override fun get_language_set(lesson_id: String, problem_no: String): Set<String> = setOf(
"G++",
"GCC",
"Java",
"Pascal",
"C++",
"C",
"Fortran")
override fun get_default_language(): String {
return this.settings.POJDefaultLanguage
}
fun make_message(html: String, problem_id: String, language: String): String {
if ("No such problem" in html) {
return "submission error: problem_id \"$problem_id\" is invalid."
}
return "submit(problem_id: $problem_id, language: $language)"
}
fun login(user_id: String, password: String): Boolean {
val url = "http://poj.org/login"
val form = FormEncodingBuilder().addEncoded("user_id1", user_id)
.addEncoded("password1", password)
var response: Response? = null
try {
response = this.client.newCall(Request.Builder().url(url).post(form.build()).build()).execute()
val html = response.body().string()
if ("Login failed" in html) {
return false
}
return response.isSuccessful
} catch (e: Exception) {
return false
} finally {
response!!.body().close()
}
}
fun get_language_map() = mapOf("G++" to "0",
"GCC" to "1",
"Java" to "2",
"Pascal" to "3",
"C++" to "4",
"C" to "5",
"Fortran" to "6")
companion object {
val NAME = "POJ"
}
} | apache-2.0 | 7c0fc485a760c37cf45978c5585d7fa3 | 34.669903 | 111 | 0.53199 | 4.625945 | false | false | false | false |
jtransc/jtransc | jtransc-utils/src/com/jtransc/vfs/PathInfo.kt | 2 | 2089 | package com.jtransc.vfs
import com.jtransc.text.indexOfOrNull
import com.jtransc.text.lastIndexOfOrNull
class PathInfo(val fullpath: String) {
val fullpathNormalized: String = fullpath.replace('\\', '/')
val folder: String by lazy {
fullpath.substring(0, fullpathNormalized.lastIndexOfOrNull('/') ?: 0)
}
val folderWithSlash: String by lazy {
fullpath.substring(0, fullpathNormalized.lastIndexOfOrNull('/')?.plus(1) ?: 0)
}
val basename: String by lazy { fullpathNormalized.substringAfterLast('/') }
val pathWithoutExtension: String by lazy {
val startIndex = fullpathNormalized.lastIndexOfOrNull('/')?.plus(1) ?: 0
fullpath.substring(0, fullpathNormalized.indexOfOrNull('.', startIndex) ?: fullpathNormalized.length)
}
fun pathWithExtension(ext: String): String = if (ext.isEmpty()) pathWithoutExtension else "$pathWithoutExtension.$ext"
val fullnameWithoutExtension: String by lazy { fullpath.substringBeforeLast('.', fullpath) }
val basenameWithoutExtension: String by lazy { basename.substringBeforeLast('.', basename) }
val fullnameWithoutCompoundExtension: String by lazy { folderWithSlash + basenameWithoutCompoundExtension }
val basenameWithoutCompoundExtension: String by lazy { basename.substringBefore('.', basename) }
fun basenameWithExtension(ext: String): String = if (ext.isEmpty()) pathWithoutExtension else "$pathWithoutExtension.$ext"
val extension: String by lazy { basename.substringAfterLast('.', "") }
val extensionLC: String by lazy { extension.toLowerCase() }
val compoundExtension: String by lazy { basename.substringAfter('.', "") }
val compoundExtensionLC: String by lazy { compoundExtension.toLowerCase() }
//val mimeTypeByExtension get() = MimeType.getByExtension(extensionLC)
fun getComponents(): List<String> = fullpathNormalized.split('/')
fun getFullComponents(): List<String> {
val out = arrayListOf<String>()
for (n in fullpathNormalized.indices) {
when (fullpathNormalized[n]) {
'/', '\\' -> {
out += fullpathNormalized.substring(0, n)
}
}
}
out += fullpathNormalized
return out
}
}
| apache-2.0 | db72a0c68608eb2784582b4cf9ecb8f4 | 39.173077 | 123 | 0.745333 | 4.388655 | false | false | false | false |
weibaohui/korm | src/main/kotlin/com/sdibt/korm/core/callbacks/CallBackProcessors.kt | 1 | 2228 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sdibt.korm.core.callbacks
/** callBack
* <功能详细描述>
*/
class CallBackProcessors {
var name: String? = null // current callback's name
var before: String? = null // register current callback before a callback
var after: String? = null // register current callback after a callback
var replace: Boolean? = null // replace callbacks with same name
var remove: Boolean? = null // delete callbacks with same name
var kind: String? = null // callback type: create, update, delete, query, row_query
var processor: ((scope: Scope) -> Scope)? = null // callback handler
var parent: Callback
constructor(kind: String?, parent: Callback) {
this.kind = kind
this.parent = parent
}
fun reg(callBackName: String, block: (scope: Scope) -> Scope) {
this.name = callBackName
this.processor = block
this.parent.processors.add(this)
when (this.kind) {
"insert" -> this.parent.inserts.add(block)
"delete" -> this.parent.deletes.add(block)
"update" -> this.parent.updates.add(block)
"select" -> this.parent.selects.add(block)
"execute" -> this.parent.executes.add(block)
"batchInsert" -> this.parent.batchInserts.add(block)
}
}
}
| apache-2.0 | 949bdc3c7db701da3cd608ae03fadfa4 | 41.615385 | 98 | 0.643502 | 4.245211 | false | false | false | false |
http4k/http4k | http4k-core/src/main/kotlin/org/http4k/filter/ZipkinTraces.kt | 1 | 3115 | package org.http4k.filter
import org.http4k.core.HttpMessage
import org.http4k.core.with
import org.http4k.filter.SamplingDecision.Companion.SAMPLE
import org.http4k.lens.BiDiLensSpec
import org.http4k.lens.Header
import org.http4k.lens.composite
import org.http4k.util.Hex
import kotlin.random.Random
data class TraceId(val value: String) {
companion object {
fun new(random: Random = Random): TraceId {
val randomBytes = ByteArray(8)
random.nextBytes(randomBytes)
return TraceId(Hex.hex(randomBytes))
}
}
}
data class SamplingDecision(val value: String) {
companion object {
val SAMPLE = SamplingDecision("1")
val DO_NOT_SAMPLE = SamplingDecision("0")
private val VALID_VALUES = listOf("1", "0")
fun from(sampledHeaderValue: String?) =
sampledHeaderValue?.takeIf { it in VALID_VALUES }?.let(::SamplingDecision)
?: SAMPLE
}
}
data class ZipkinTraces(
val traceId: TraceId,
val spanId: TraceId,
val parentSpanId: TraceId?,
val samplingDecision: SamplingDecision = SAMPLE
) {
companion object {
private val X_B3_TRACEID = Header.map(::TraceId, TraceId::value).optional("x-b3-traceid")
private val X_B3_SPANID = Header.map(::TraceId, TraceId::value).optional("x-b3-spanid")
private val X_B3_PARENTSPANID = Header.map(::TraceId, TraceId::value).optional("x-b3-parentspanid")
private val X_B3_SAMPLED =
Header.map(SamplingDecision.Companion::from, SamplingDecision::value).optional("x-b3-sampled")
private fun set(): ZipkinTraces.(HttpMessage) -> HttpMessage = { it: HttpMessage ->
it.with(
X_B3_TRACEID of traceId,
X_B3_SPANID of spanId,
X_B3_PARENTSPANID of parentSpanId,
X_B3_SAMPLED of samplingDecision
)
}
private fun get(): BiDiLensSpec<HttpMessage, String>.(HttpMessage) -> ZipkinTraces = {
ZipkinTraces(
X_B3_TRACEID(it) ?: TraceId.new(),
X_B3_SPANID(it) ?: TraceId.new(),
X_B3_PARENTSPANID(it),
X_B3_SAMPLED(it) ?: SAMPLE
)
}
private val lens = Header.composite(get(), set())
operator fun invoke(target: HttpMessage): ZipkinTraces = lens(target)
operator fun <T : HttpMessage> invoke(value: ZipkinTraces, target: T): T = lens(value, target)
}
}
interface ZipkinTracesStorage {
fun setForCurrentThread(zipkinTraces: ZipkinTraces)
fun forCurrentThread(): ZipkinTraces
companion object {
internal val INTERNAL_THREAD_LOCAL = object : ThreadLocal<ZipkinTraces>() {
override fun initialValue() = ZipkinTraces(TraceId.new(), TraceId.new(), null, SAMPLE)
}
val THREAD_LOCAL = object : ZipkinTracesStorage {
override fun setForCurrentThread(zipkinTraces: ZipkinTraces) = INTERNAL_THREAD_LOCAL.set(zipkinTraces)
override fun forCurrentThread(): ZipkinTraces = INTERNAL_THREAD_LOCAL.get()
}
}
}
| apache-2.0 | 7443e2854600fd7bc0c502fd9d7db840 | 34.804598 | 114 | 0.638523 | 4.232337 | false | false | false | false |
Maxr1998/XGPM | app/src/main/java/de/Maxr1998/xposed/gpm/hooks/NowPlayingHelper.kt | 1 | 8705 | package de.Maxr1998.xposed.gpm.hooks
import android.content.Context
import android.content.res.Resources
import android.view.View
import android.view.ViewGroup
import de.Maxr1998.xposed.gpm.Common
import de.Maxr1998.xposed.gpm.hooks.Main.Companion.modRes
import de.robv.android.xposed.XposedBridge.log
import de.robv.android.xposed.XposedHelpers.*
import java.lang.reflect.Method
object NowPlayingHelper {
val headerBarId: Int by lazy {
modRes?.getIdentifier("custom_header_bar", "id", Common.XGPM) ?: 0
}
val titleBarId: Int by lazy {
modRes?.getIdentifier("custom_title_bar", "id", Common.XGPM) ?: 0
}
val mediaRouteWrapperId: Int by lazy {
modRes?.getIdentifier("media_route_wrapper", "id", Common.XGPM) ?: 0
}
val playQueueWrapperWrapperId: Int by lazy {
modRes?.getIdentifier("play_queue_wrapper", "id", Common.XGPM) ?: 0
}
val addViewInner: Method = findMethodBestMatch(ViewGroup::class.java, "addViewInner", View::class.java, Int::class.java, ViewGroup.LayoutParams::class.java, Boolean::class.java)
val removeViewInternal: Method = findMethodBestMatch(ViewGroup::class.java, "removeViewInternal", Int::class.java, View::class.java)
fun itemWidth(res: Resources) =
res.getDimensionPixelSize(res.getIdentifier("nowplaying_screen_info_block_width", "dimen", Common.GPM))
}
object ConstraintLayout {
fun create(context: Context): ViewGroup =
getClass(context.classLoader).getConstructor(Context::class.java).newInstance(context) as ViewGroup
fun getClass(classLoader: ClassLoader): Class<*> =
findClass("android.support.constraint.ConstraintLayout", classLoader)
}
class ConstraintSet(val classLoader: ClassLoader) {
private val constraintSetClass: Class<*> = findClass("android.support.constraint.ConstraintSet", classLoader)
private val constraintClass: Class<*> = findClass("android.support.constraint.ConstraintSet.Constraint", classLoader)
private val applyToInternalMethod = findMethodBestMatch(constraintSetClass, "applyToInternal", ConstraintLayout.getClass(classLoader))
private val instance: Any = constraintSetClass.newInstance()
fun applyTo(layout: ViewGroup) {
applyToInternalMethod.invoke(instance, layout)
callMethod(layout, "setConstraintSet", instance)
}
private fun getAll() = getObjectField(instance, "mConstraints") as HashMap<Int, Any>
fun get(view: View): Constraint {
val constraints = getAll()
val viewID = view.id
return if (!constraints.containsKey(viewID)) {
Constraint().apply {
setValue("mWidth", view.layoutParams.width)
setValue("mHeight", view.layoutParams.height)
setValue("visibility", view.visibility)
constraints[viewID] = instance
}
} else Constraint(constraints[viewID]!!)
}
fun connect(startView: View, startSide: Int, endID: Int, endSide: Int) {
val constraint = get(startView)
when (startSide) {
LEFT -> when (endSide) {
LEFT -> {
constraint.setValue("leftToLeft", endID)
constraint.setValue("leftToRight", UNSET)
}
RIGHT -> {
constraint.setValue("leftToRight", endID)
constraint.setValue("leftToLeft", UNSET)
}
else -> throw IllegalArgumentException("left to " + sideToString(endSide) + " undefined")
}
RIGHT -> when (endSide) {
LEFT -> {
constraint.setValue("rightToLeft", endID)
constraint.setValue("rightToRight", UNSET)
}
RIGHT -> {
constraint.setValue("rightToRight", endID)
constraint.setValue("rightToLeft", UNSET)
}
else -> throw IllegalArgumentException("right to " + sideToString(endSide) + " undefined")
}
TOP -> when (endSide) {
TOP -> {
constraint.setValue("topToTop", endID)
constraint.setValue("topToBottom", UNSET)
constraint.setValue("baselineToBaseline", UNSET)
}
BOTTOM -> {
constraint.setValue("topToBottom", endID)
constraint.setValue("topToTop", UNSET)
constraint.setValue("baselineToBaseline", UNSET)
}
else -> throw IllegalArgumentException("right to " + sideToString(endSide) + " undefined")
}
BOTTOM -> when (endSide) {
BOTTOM -> {
constraint.setValue("bottomToBottom", endID)
constraint.setValue("bottomToTop", UNSET)
constraint.setValue("baselineToBaseline", UNSET)
}
TOP -> {
constraint.setValue("bottomToTop", endID)
constraint.setValue("bottomToBottom", UNSET)
constraint.setValue("baselineToBaseline", UNSET)
}
else -> throw IllegalArgumentException("right to " + sideToString(endSide) + " undefined")
}
BASELINE -> if (endSide == BASELINE) {
constraint.setValue("baselineToBaseline", endID)
constraint.setValue("bottomToBottom", UNSET)
constraint.setValue("bottomToTop", UNSET)
constraint.setValue("topToTop", UNSET)
constraint.setValue("topToBottom", UNSET)
} else {
throw IllegalArgumentException("right to " + sideToString(endSide) + " undefined")
}
START -> when (endSide) {
START -> {
constraint.setValue("startToStart", endID)
constraint.setValue("startToEnd", UNSET)
}
END -> {
constraint.setValue("startToEnd", endID)
constraint.setValue("startToStart", UNSET)
}
else -> throw IllegalArgumentException("right to " + sideToString(endSide) + " undefined")
}
END -> when (endSide) {
END -> {
constraint.setValue("endToEnd", endID)
constraint.setValue("endToStart", UNSET)
}
START -> {
constraint.setValue("endToStart", endID)
constraint.setValue("endToEnd", UNSET)
}
else -> throw IllegalArgumentException("right to " + sideToString(endSide) + " undefined")
}
else -> throw IllegalArgumentException(sideToString(startSide) + " to " + sideToString(endSide) + " unknown")
}
}
fun spanWidth(view: View) {
connect(view, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START)
connect(view, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END)
}
fun print() {
getAll().forEach { k, v ->
log("$k: ${Constraint(v).print()}")
}
}
inner class Constraint(val instance: Any = constraintClass.getDeclaredConstructor().apply { isAccessible = true }.newInstance()) {
fun setValue(key: String, value: Int) {
setIntField(instance, key, value)
}
fun setValue(key: String, value: String) {
setObjectField(instance, key, value)
}
fun print(): String {
val output = StringBuilder()
output.appendln("Constraint {")
constraintClass.fields.forEach {
output.appendln(" ${it.name}: ${it.get(instance)}")
}
output.appendln("}")
return output.toString()
}
}
companion object {
const val MATCH_CONSTRAINT = 0
const val PARENT_ID = 0
const val UNSET = -1
const val HORIZONTAL = 0
const val VERTICAL = 1
const val LEFT = 1
const val RIGHT = 2
const val TOP = 3
const val BOTTOM = 4
const val BASELINE = 5
const val START = 6
const val END = 7
private fun sideToString(side: Int): String {
return when (side) {
LEFT -> "left"
RIGHT -> "right"
TOP -> "top"
BOTTOM -> "bottom"
BASELINE -> "baseline"
START -> "start"
END -> "end"
else -> "undefined"
}
}
}
} | gpl-3.0 | 9f2b116ce810632baf44abbb05b3f1cc | 39.493023 | 181 | 0.568294 | 5.108568 | false | false | false | false |
desilvai/mockito-kotlin | mockito-kotlin/src/main/kotlin/com/nhaarman/mockito_kotlin/Mockito.kt | 1 | 7436 | /*
* The MIT License
*
* Copyright (c) 2016 Niek Haarman
* Copyright (c) 2007 Mockito contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.nhaarman.mockito_kotlin
import org.mockito.InOrder
import org.mockito.MockSettings
import org.mockito.MockingDetails
import org.mockito.Mockito
import org.mockito.invocation.InvocationOnMock
import org.mockito.stubbing.Answer
import org.mockito.stubbing.OngoingStubbing
import org.mockito.stubbing.Stubber
import org.mockito.verification.VerificationMode
import org.mockito.verification.VerificationWithTimeout
import kotlin.reflect.KClass
fun after(millis: Long) = Mockito.after(millis)
/** Matches any object, excluding nulls. */
inline fun <reified T : Any> any() = Mockito.any(T::class.java) ?: createInstance<T>()
/** Matches anything, including nulls. */
inline fun <reified T : Any> anyOrNull(): T = Mockito.any<T>() ?: createInstance<T>()
/** Matches any vararg object, including nulls. */
inline fun <reified T : Any> anyVararg(): T = Mockito.any<T>() ?: createInstance<T>()
/** Matches any array of type T. */
inline fun <reified T : Any?> anyArray(): Array<T> = Mockito.any(Array<T>::class.java) ?: arrayOf()
inline fun <reified T : Any> argThat(noinline predicate: T.() -> Boolean) = Mockito.argThat<T> { it -> (it as T).predicate() } ?: createInstance(T::class)
inline fun <reified T : Any> argForWhich(noinline predicate: T.() -> Boolean) = argThat(predicate)
inline fun <reified T : Any> check(noinline predicate: (T) -> Unit) = Mockito.argThat<T> { it -> predicate(it); true } ?: createInstance(T::class)
fun atLeast(numInvocations: Int): VerificationMode = Mockito.atLeast(numInvocations)!!
fun atLeastOnce(): VerificationMode = Mockito.atLeastOnce()!!
fun atMost(maxNumberOfInvocations: Int): VerificationMode = Mockito.atMost(maxNumberOfInvocations)!!
fun calls(wantedNumberOfInvocations: Int): VerificationMode = Mockito.calls(wantedNumberOfInvocations)!!
fun <T> clearInvocations(vararg mocks: T) = Mockito.clearInvocations(*mocks)
fun description(description: String): VerificationMode = Mockito.description(description)
fun <T> doAnswer(answer: (InvocationOnMock) -> T?): Stubber = Mockito.doAnswer { answer(it) }!!
fun doCallRealMethod(): Stubber = Mockito.doCallRealMethod()!!
fun doNothing(): Stubber = Mockito.doNothing()!!
fun doReturn(value: Any?): Stubber = Mockito.doReturn(value)!!
fun doReturn(toBeReturned: Any?, vararg toBeReturnedNext: Any?): Stubber = Mockito.doReturn(toBeReturned, *toBeReturnedNext)!!
fun doThrow(toBeThrown: KClass<out Throwable>): Stubber = Mockito.doThrow(toBeThrown.java)!!
fun doThrow(vararg toBeThrown: Throwable): Stubber = Mockito.doThrow(*toBeThrown)!!
inline fun <reified T : Any> eq(value: T): T = Mockito.eq(value) ?: createInstance<T>()
fun ignoreStubs(vararg mocks: Any): Array<out Any> = Mockito.ignoreStubs(*mocks)!!
fun inOrder(vararg mocks: Any): InOrder = Mockito.inOrder(*mocks)!!
inline fun <reified T : Any> isA(): T? = Mockito.isA(T::class.java)
fun <T : Any> isNotNull(): T? = Mockito.isNotNull()
fun <T : Any> isNull(): T? = Mockito.isNull()
inline fun <reified T : Any> mock(): T = Mockito.mock(T::class.java)!!
inline fun <reified T : Any> mock(defaultAnswer: Answer<Any>): T = Mockito.mock(T::class.java, defaultAnswer)!!
inline fun <reified T : Any> mock(s: MockSettings): T = Mockito.mock(T::class.java, s)!!
inline fun <reified T : Any> mock(s: String): T = Mockito.mock(T::class.java, s)!!
inline fun <reified T : Any> mock(stubbing: KStubbing<T>.(T) -> Unit): T {
return mock<T>().apply {
KStubbing(this).stubbing(this)
}
}
class KStubbing<out T>(private val mock: T) {
fun <R> on(methodCall: R) = Mockito.`when`(methodCall)
fun <R> on(methodCall: T.() -> R) = Mockito.`when`(mock.methodCall())
}
infix fun <T> OngoingStubbing<T>.doReturn(t: T): OngoingStubbing<T> = thenReturn(t)
fun <T> OngoingStubbing<T>.doReturn(t: T, vararg ts: T): OngoingStubbing<T> = thenReturn(t, *ts)
inline infix fun <reified T> OngoingStubbing<T>.doReturn(ts: List<T>): OngoingStubbing<T> = thenReturn(ts[0], *ts.drop(1).toTypedArray())
infix fun <T> OngoingStubbing<T>.doThrow(t: Throwable): OngoingStubbing<T> = thenThrow(t)
fun <T> OngoingStubbing<T>.doThrow(t: Throwable, vararg ts: Throwable): OngoingStubbing<T> = thenThrow(t, *ts)
infix fun <T> OngoingStubbing<T>.doThrow(t: KClass<out Throwable>): OngoingStubbing<T> = thenThrow(t.java)
fun <T> OngoingStubbing<T>.doThrow(t: KClass<out Throwable>, vararg ts: KClass<out Throwable>): OngoingStubbing<T> = thenThrow(t.java, *ts.map { it.java }.toTypedArray())
fun mockingDetails(toInspect: Any): MockingDetails = Mockito.mockingDetails(toInspect)!!
fun never(): VerificationMode = Mockito.never()!!
fun <T : Any> notNull(): T? = Mockito.notNull()
fun only(): VerificationMode = Mockito.only()!!
fun <T> refEq(value: T, vararg excludeFields: String): T? = Mockito.refEq(value, *excludeFields)
fun <T> reset(vararg mocks: T) = Mockito.reset(*mocks)
fun <T> same(value: T): T? = Mockito.same(value)
inline fun <reified T : Any> spy(): T = Mockito.spy(T::class.java)!!
fun <T> spy(value: T): T = Mockito.spy(value)!!
fun timeout(millis: Long): VerificationWithTimeout = Mockito.timeout(millis)!!
fun times(numInvocations: Int): VerificationMode = Mockito.times(numInvocations)!!
fun validateMockitoUsage() = Mockito.validateMockitoUsage()
fun <T> verify(mock: T): T = Mockito.verify(mock)!!
fun <T> verify(mock: T, mode: VerificationMode): T = Mockito.verify(mock, mode)!!
fun <T> verifyNoMoreInteractions(vararg mocks: T) = Mockito.verifyNoMoreInteractions(*mocks)
fun verifyZeroInteractions(vararg mocks: Any) = Mockito.verifyZeroInteractions(*mocks)
fun <T> whenever(methodCall: T): OngoingStubbing<T> = Mockito.`when`(methodCall)!!
fun withSettings(): MockSettings = Mockito.withSettings()!!
@Deprecated("Use any() instead.", ReplaceWith("any()"), DeprecationLevel.ERROR)
inline fun <reified T : Any> anyCollection(): Collection<T> = any()
@Deprecated("Use any() instead.", ReplaceWith("any()"), DeprecationLevel.ERROR)
inline fun <reified T : Any> anyList(): List<T> = any()
@Deprecated("Use any() instead.", ReplaceWith("any()"), DeprecationLevel.ERROR)
inline fun <reified T : Any> anySet(): Set<T> = any()
@Deprecated("Use any() instead.", ReplaceWith("any()"), DeprecationLevel.ERROR)
inline fun <reified K : Any, reified V : Any> anyMap(): Map<K, V> = any()
| mit | ccc879ebf949d777e984542ee390efc1 | 51 | 170 | 0.729962 | 3.807476 | false | false | false | false |
ZsemberiDaniel/EgerBusz | app/src/main/java/com/zsemberidaniel/egerbuszuj/presenters/BothRoutePresenter.kt | 1 | 1439 | package com.zsemberidaniel.egerbuszuj.presenters
import com.zsemberidaniel.egerbuszuj.adapters.RouteAdapter
import com.zsemberidaniel.egerbuszuj.interfaces.presenters.IBothRoutePresenter
import com.zsemberidaniel.egerbuszuj.interfaces.views.IBothRouteView
import com.zsemberidaniel.egerbuszuj.realm.RealmData
/**
* Created by zsemberi.daniel on 2017. 05. 31..
*/
class BothRoutePresenter(val view: IBothRouteView) : IBothRoutePresenter {
var direction: Int = 1
get
private set
var route: String? = null
get
private set
override fun init() {
}
override fun destroy() {
}
/**
* Flips direction then notifies itself about the change
*/
override fun flipDirection() {
directionChanged(1 - direction)
}
override fun directionChanged(newDirection: Int) {
direction = newDirection
dirOrRouteChanged()
}
override fun routeChanged(newRoute: String) {
route = newRoute
dirOrRouteChanged()
}
fun dirOrRouteChanged() {
if (route == null) return
val items = RealmData
.getAllStopsInOrder(route!!, direction)
.filterNotNull()
.map { RouteAdapter.RouteAdapterItem(it) }
.toMutableList()
val headSignText = RealmData.getHeadSignOf(route!!, direction)
view.updateAdapterItems(items, headSignText)
}
} | apache-2.0 | 85497af08209aed47663c786a4aa6902 | 23 | 78 | 0.656706 | 4.539432 | false | false | false | false |
openMF/android-client | mifosng-android/src/main/java/com/mifos/mifosxdroid/online/clientlist/ClientListFragment.kt | 1 | 14867 | /*
* This project is licensed under the open source MPL V2.
* See https://github.com/openMF/android-client/blob/master/LICENSE.md
*/
package com.mifos.mifosxdroid.online.clientlist
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.view.*
import android.widget.ProgressBar
import androidx.appcompat.view.ActionMode
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.github.therajanmaurya.sweeterror.SweetUIErrorHandler
import com.mifos.mifosxdroid.R
import com.mifos.mifosxdroid.adapters.ClientNameListAdapter
import com.mifos.mifosxdroid.core.EndlessRecyclerViewScrollListener
import com.mifos.mifosxdroid.core.MifosBaseActivity
import com.mifos.mifosxdroid.core.MifosBaseFragment
import com.mifos.mifosxdroid.core.util.Toaster
import com.mifos.mifosxdroid.dialogfragments.syncclientsdialog.SyncClientsDialogFragment
import com.mifos.mifosxdroid.online.ClientActivity
import com.mifos.mifosxdroid.online.createnewclient.CreateNewClientFragment
import com.mifos.objects.client.Client
import com.mifos.utils.Constants
import com.mifos.utils.FragmentConstants
import javax.inject.Inject
/**
* Created by ishankhanna on 09/02/14.
*
*
* This class loading client, Here is two way to load the clients. First one to load clients
* from Rest API
*
*
* >demo.openmf.org/fineract-provider/api/v1/clients?paged=true&offset=offset_value&limit
* =limit_value>
*
*
* Offset : From Where index, client will be fetch.
* limit : Total number of client, need to fetch
*
*
* and showing in the ClientList.
*
*
* and Second one is showing Group Clients. Here Group load the ClientList and send the
* Client to ClientListFragment newInstance(List<Client> clientList,
* boolean isParentFragment) {...}
* and unregister the ScrollListener and SwipeLayout.
</Client> */
class ClientListFragment : MifosBaseFragment(), ClientListMvpView, OnRefreshListener {
@JvmField
@BindView(R.id.rv_clients)
var rv_clients: RecyclerView? = null
@JvmField
@BindView(R.id.swipe_container)
var swipeRefreshLayout: SwipeRefreshLayout? = null
@JvmField
@BindView(R.id.layout_error)
var errorView: View? = null
@JvmField
@BindView(R.id.pb_client)
var pb_client: ProgressBar? = null
val mClientNameListAdapter by lazy {
ClientNameListAdapter(
onClientNameClick = { position ->
if (actionMode != null) {
toggleSelection(position)
} else {
val clientActivityIntent = Intent(activity, ClientActivity::class.java)
clientActivityIntent.putExtra(Constants.CLIENT_ID, clientList!![position].id)
startActivity(clientActivityIntent)
clickedPosition = position
}
},
onClientNameLongClick = { position ->
if (actionMode == null) {
actionMode = (activity as MifosBaseActivity?)!!.startSupportActionMode(actionModeCallback!!)
}
toggleSelection(position)
}
)
}
@JvmField
@Inject
var mClientListPresenter: ClientListPresenter? = null
private lateinit var rootView: View
private var clientList: List<Client>? = null
private var selectedClients: MutableList<Client>? = null
private var actionModeCallback: ActionModeCallback? = null
private var actionMode: ActionMode? = null
private var isParentFragment = false
private var mLayoutManager: LinearLayoutManager? = null
private var clickedPosition = -1
private var sweetUIErrorHandler: SweetUIErrorHandler? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
clientList = ArrayList()
selectedClients = ArrayList()
actionModeCallback = ActionModeCallback()
if (arguments != null) {
clientList = requireArguments().getParcelableArrayList(Constants.CLIENTS)
isParentFragment = requireArguments()
.getBoolean(Constants.IS_A_PARENT_FRAGMENT)
}
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
rootView = inflater.inflate(R.layout.fragment_client, container, false)
(activity as MifosBaseActivity?)!!.activityComponent.inject(this)
setToolbarTitle(resources.getString(R.string.clients))
ButterKnife.bind(this, rootView)
mClientListPresenter!!.attachView(this)
//setting all the UI content to the view
showUserInterface()
/**
* This is the LoadMore of the RecyclerView. It called When Last Element of RecyclerView
* is shown on the Screen.
*/
rv_clients!!.addOnScrollListener(object : EndlessRecyclerViewScrollListener(mLayoutManager) {
override fun onLoadMore(page: Int, totalItemCount: Int) {
mClientListPresenter!!.loadClients(true, totalItemCount)
}
})
/**
* First Check the Parent Fragment is true or false. If parent fragment is true then no
* need to fetch clientList from Rest API, just need to showing parent fragment ClientList
* and is Parent Fragment is false then Presenter make the call to Rest API and fetch the
* Client Lis to show. and Presenter make transaction to Database to load saved clients.
*/
if (isParentFragment) {
mClientListPresenter!!.showParentClients(clientList)
} else {
mClientListPresenter!!.loadClients(false, 0)
}
mClientListPresenter!!.loadDatabaseClients()
return rootView
}
override fun onResume() {
super.onResume()
if (clickedPosition != -1) {
mClientNameListAdapter!!.updateItem(clickedPosition)
}
}
/**
* This method initializes the all Views.
*/
override fun showUserInterface() {
mLayoutManager = LinearLayoutManager(activity)
mLayoutManager!!.orientation = LinearLayoutManager.VERTICAL
rv_clients!!.layoutManager = mLayoutManager
rv_clients!!.setHasFixedSize(true)
rv_clients!!.adapter = mClientNameListAdapter
swipeRefreshLayout!!.setColorSchemeColors(*activity
?.getResources()!!.getIntArray(R.array.swipeRefreshColors))
swipeRefreshLayout!!.setOnRefreshListener(this)
sweetUIErrorHandler = SweetUIErrorHandler(activity, rootView)
}
@OnClick(R.id.fab_create_client)
fun onClickCreateNewClient() {
(activity as MifosBaseActivity?)!!.replaceFragment(CreateNewClientFragment.newInstance(),
true, R.id.container_a)
}
/**
* This method will be called when user will swipe down to Refresh the ClientList then
* Presenter make the Fresh call to Rest API to load ClientList from offset = 0 and fetch the
* first 100 clients and update the client list.
*/
override fun onRefresh() {
showUserInterface()
mClientListPresenter!!.loadClients(false, 0)
mClientListPresenter!!.loadDatabaseClients()
if (actionMode != null) actionMode!!.finish()
}
/**
* This Method unregister the RecyclerView OnScrollListener and SwipeRefreshLayout
* and NoClientIcon click event.
*/
override fun unregisterSwipeAndScrollListener() {
rv_clients!!.clearOnScrollListeners()
swipeRefreshLayout!!.isEnabled = false
}
/**
* This Method showing the Simple Taster Message to user.
*
* @param message String Message to show.
*/
override fun showMessage(message: Int) {
Toaster.show(rootView, getStringMessage(message))
}
/**
* Onclick Send Fresh Request for Client list.
*/
@OnClick(R.id.btn_try_again)
fun reloadOnError() {
sweetUIErrorHandler!!.hideSweetErrorLayoutUI(rv_clients, errorView)
mClientListPresenter!!.loadClients(false, 0)
mClientListPresenter!!.loadDatabaseClients()
}
/**
* Setting ClientList to the Adapter and updating the Adapter.
*/
override fun showClientList(clients: List<Client>?) {
clientList = clients
mClientNameListAdapter!!.setClients(clients ?: emptyList())
mClientNameListAdapter!!.notifyDataSetChanged()
}
/**
* Updating Adapter Attached ClientList
*
* @param clients List<Client></Client>>
*/
override fun showLoadMoreClients(clients: List<Client>?) {
clientList.addAll()
mClientNameListAdapter!!.notifyDataSetChanged()
}
/**
* Showing Fetched ClientList size is 0 and show there is no client to show.
*
* @param message String Message to show user.
*/
override fun showEmptyClientList(message: Int) {
sweetUIErrorHandler!!.showSweetEmptyUI(getString(R.string.client),
getString(message), R.drawable.ic_error_black_24dp, rv_clients, errorView)
}
/**
* This Method Will be called. When Presenter failed to First page of ClientList from Rest API.
* Then user look the Message that failed to fetch clientList.
*/
override fun showError() {
val errorMessage = getStringMessage(R.string.failed_to_load_client)
sweetUIErrorHandler!!.showSweetErrorUI(errorMessage, R.drawable.ic_error_black_24dp,
rv_clients, errorView)
}
/**
* show MifosBaseActivity ProgressBar, if mClientNameListAdapter.getItemCount() == 0
* otherwise show SwipeRefreshLayout.
*/
override fun showProgressbar(show: Boolean) {
swipeRefreshLayout!!.isRefreshing = show
if (show && mClientNameListAdapter!!.itemCount == 0) {
pb_client!!.visibility = View.VISIBLE
swipeRefreshLayout!!.isRefreshing = false
} else {
pb_client!!.visibility = View.GONE
}
}
override fun onDestroyView() {
super.onDestroyView()
hideMifosProgressBar()
mClientListPresenter!!.detachView()
//As the Fragment Detach Finish the ActionMode
if (actionMode != null) actionMode!!.finish()
}
/**
* Toggle the selection state of an item.
*
*
* If the item was the last one in the selection and is unselected, the selection is stopped.
* Note that the selection must already be started (actionMode must not be null).
*
* @param position Position of the item to toggle the selection state
*/
private fun toggleSelection(position: Int) {
mClientNameListAdapter!!.toggleSelection(position)
val count = mClientNameListAdapter!!.selectedItemCount
if (count == 0) {
actionMode!!.finish()
} else {
actionMode!!.title = count.toString()
actionMode!!.invalidate()
}
}
/**
* This ActionModeCallBack Class handling the User Event after the Selection of Clients. Like
* Click of Menu Sync Button and finish the ActionMode
*/
private inner class ActionModeCallback : ActionMode.Callback {
private val LOG_TAG = ActionModeCallback::class.java.simpleName
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
mode.menuInflater.inflate(R.menu.menu_sync, menu)
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
return false
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_sync -> {
selectedClients!!.clear()
for (position in mClientNameListAdapter!!.selectedItems) {
selectedClients!!.add(clientList!![position!!])
}
val syncClientsDialogFragment = SyncClientsDialogFragment.newInstance(selectedClients)
val fragmentTransaction = activity
?.getSupportFragmentManager()!!.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CLIENT_SYNC)
syncClientsDialogFragment.isCancelable = false
syncClientsDialogFragment.show(fragmentTransaction,
resources.getString(R.string.sync_clients))
mode.finish()
true
}
else -> false
}
}
override fun onDestroyActionMode(mode: ActionMode) {
mClientNameListAdapter!!.clearSelection()
actionMode = null
}
}
companion object {
val LOG_TAG = ClientListFragment::class.java.simpleName
/**
* This method will be called, whenever ClientListFragment will not have Parent Fragment.
* So, Presenter make the call to Rest API and fetch the Client List and show in UI
*
* @return ClientListFragment
*/
@JvmStatic
fun newInstance(): ClientListFragment {
val arguments = Bundle()
val clientListFragment = ClientListFragment()
clientListFragment.arguments = arguments
return clientListFragment
}
/**
* This Method will be called, whenever Parent (Fragment or Activity) will be true and Presenter
* do not need to make Rest API call to server. Parent (Fragment or Activity) already fetched
* the clients and for showing, they call ClientListFragment.
*
*
* Example : Showing Group Clients.
*
* @param clientList List<Client>
* @param isParentFragment true
* @return ClientListFragment
</Client> */
@JvmStatic
fun newInstance(clientList: List<Client?>?,
isParentFragment: Boolean): ClientListFragment {
val clientListFragment = ClientListFragment()
val args = Bundle()
if (isParentFragment && clientList != null) {
args.putParcelableArrayList(Constants.CLIENTS,
clientList as ArrayList<out Parcelable?>?)
args.putBoolean(Constants.IS_A_PARENT_FRAGMENT, true)
clientListFragment.arguments = args
}
return clientListFragment
}
}
}
private fun <E> List<E>?.addAll() {
}
| mpl-2.0 | 8bb2d2b38b5d68ea3e1f3280052ed6ea | 36.542929 | 116 | 0.656084 | 5.347842 | false | false | false | false |
damien5314/HoldTheNarwhal | app/src/main/java/com/ddiehl/android/htn/utils/RedditUtil.kt | 1 | 1124 | package com.ddiehl.android.htn.utils
import rxreddit.model.Comment
import rxreddit.model.CommentStub
import rxreddit.model.Listing
/**
* Flattens list of comments, marking each comment with depth
*/
fun flattenCommentList(commentList: MutableList<Listing>) {
var i = 0
while (i < commentList.size) {
val listing = commentList[i]
if (listing is Comment) {
val repliesListing = listing.replies
if (repliesListing != null) {
val replies = repliesListing.data.children
flattenCommentList(replies)
}
listing.depth = listing.depth + 1 // Increase depth by 1
if (listing.replies != null) {
// Add all of the replies to commentList
commentList.addAll(i + 1, listing.replies.data.children)
listing.replies = null // Remove replies for comment
}
} else { // Listing is a CommentStub
val moreComments = listing as CommentStub
moreComments.depth = moreComments.depth + 1 // Increase depth by 1
}
i++
}
}
| apache-2.0 | 85bce707c04d4ab16aa98d551a8b48ef | 34.125 | 78 | 0.604982 | 4.683333 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/address/AddHousenumberForm.kt | 1 | 13280 | package de.westnordost.streetcomplete.quests.address
import android.content.res.ColorStateList
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import android.text.InputType
import android.text.method.DigitsKeyListener
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import androidx.core.view.isInvisible
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.databinding.DialogQuestAddressNoHousenumberBinding
import de.westnordost.streetcomplete.ktx.showKeyboard
import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment
import de.westnordost.streetcomplete.quests.AnswerItem
import de.westnordost.streetcomplete.quests.building_type.BuildingType
import de.westnordost.streetcomplete.quests.building_type.asItem
import de.westnordost.streetcomplete.util.TextChangedWatcher
import de.westnordost.streetcomplete.view.image_select.ItemViewHolder
class AddHousenumberForm : AbstractQuestFormAnswerFragment<HousenumberAnswer>() {
override val otherAnswers = listOf(
AnswerItem(R.string.quest_address_answer_no_housenumber) { onNoHouseNumber() },
AnswerItem(R.string.quest_address_answer_house_name) { switchToHouseName() },
AnswerItem(R.string.quest_housenumber_multiple_numbers) { showMultipleNumbersHint() },
AnswerItem(R.string.quest_buildingType_answer_construction_site) { onBuildingConstruction() }
)
private var houseNumberInput: EditText? = null
private var houseNameInput: EditText? = null
private var conscriptionNumberInput: EditText? = null
private var streetNumberInput: EditText? = null
private var blockNumberInput: EditText? = null
private var toggleKeyboardButton: Button? = null
private var addButton: View? = null
private var subtractButton: View? = null
private var isHousename: Boolean = false
private var houseNumberInputTextColors: ColorStateList? = null
private val isShowingHouseNumberHint: Boolean get() = houseNumberInputTextColors != null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = super.onCreateView(inflater, container, savedInstanceState)
isHousename = savedInstanceState?.getBoolean(IS_HOUSENAME) ?: false
setLayout(if(isHousename) R.layout.quest_housename else R.layout.quest_housenumber)
return view
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean(IS_HOUSENAME, isHousename)
}
override fun onClickOk() {
createAnswer()?.let { answer ->
confirmHousenumber(answer.looksInvalid(countryInfo.additionalValidHousenumberRegex)) {
applyAnswer(answer)
if (answer.isRealHouseNumberAnswer) lastRealHousenumberAnswer = answer
}
}
}
override fun isFormComplete() = (!isShowingHouseNumberHint || isHousename) && createAnswer() != null
/* ------------------------------------- Other answers -------------------------------------- */
private fun switchToHouseName() {
isHousename = true
setLayout(R.layout.quest_housename)
houseNameInput?.requestFocus()
}
private fun showMultipleNumbersHint() {
activity?.let { AlertDialog.Builder(it)
.setMessage(R.string.quest_housenumber_multiple_numbers_description)
.setPositiveButton(android.R.string.ok, null)
.show()
}
}
private fun onNoHouseNumber() {
val buildingValue = osmElement!!.tags["building"]!!
val buildingType = BuildingType.getByTag("building", buildingValue)
if (buildingType != null) {
showNoHousenumberDialog(buildingType)
} else {
// fallback in case the type of building is known by Housenumber quest but not by
// building type quest
onClickCantSay()
}
}
private fun showNoHousenumberDialog(buildingType: BuildingType) {
val dialogBinding = DialogQuestAddressNoHousenumberBinding.inflate(layoutInflater)
ItemViewHolder(dialogBinding.root).bind(buildingType.asItem())
AlertDialog.Builder(requireContext())
.setView(dialogBinding.root)
.setPositiveButton(R.string.quest_generic_hasFeature_yes) { _, _ -> applyAnswer(NoHouseNumber) }
.setNegativeButton(R.string.quest_generic_hasFeature_no) { _, _ -> applyAnswer(WrongBuildingType) }
.show()
}
private fun onBuildingConstruction() {
val buildingValue = osmElement!!.tags["building"]!!
applyAnswer(StillBeingConstructed(buildingValue))
}
/* -------------------------- Set (different) housenumber layout --------------------------- */
private fun setLayout(layoutResourceId: Int) {
val view = setContentView(layoutResourceId)
toggleKeyboardButton = view.findViewById(R.id.toggleKeyboardButton)
houseNumberInput = view.findViewById(R.id.houseNumberInput)
houseNameInput = view.findViewById(R.id.houseNameInput)
conscriptionNumberInput = view.findViewById(R.id.conscriptionNumberInput)
streetNumberInput = view.findViewById(R.id.streetNumberInput)
blockNumberInput = view.findViewById(R.id.blockNumberInput)
addButton = view.findViewById(R.id.addButton)
subtractButton = view.findViewById(R.id.subtractButton)
addButton?.setOnClickListener { addToHouseNumberInput(+1) }
subtractButton?.setOnClickListener { addToHouseNumberInput(-1) }
// must be called before registering the text changed watchers because it changes the text
prefillBlockNumber()
initKeyboardButton()
// must be after initKeyboardButton because it re-sets the onFocusListener
showHouseNumberHint()
val onChanged = TextChangedWatcher { checkIsFormComplete() }
houseNumberInput?.addTextChangedListener(onChanged)
houseNameInput?.addTextChangedListener(onChanged)
conscriptionNumberInput?.addTextChangedListener(onChanged)
streetNumberInput?.addTextChangedListener(onChanged)
blockNumberInput?.addTextChangedListener(onChanged)
}
private fun prefillBlockNumber() {
/* the block number likely does not change from one input to the other, so let's prefill it
with the last selected value */
val input = blockNumberInput ?: return
val blockNumberAnswer = lastRealHousenumberAnswer as? HouseAndBlockNumber ?: return
input.setText(blockNumberAnswer.blockNumber)
}
private fun showHouseNumberHint() {
val input = houseNumberInput ?: return
val prev = lastRealHousenumberAnswer?.realHouseNumber ?: return
/* The Auto fit layout does not work with hints, so we workaround this by setting the "real"
* text instead and make it look like it is a hint. This little hack is much less effort
* than to fork and fix the external dependency. We need to revert back the color both on
* focus and on text changed (tapping on +/- button) */
houseNumberInputTextColors = input.textColors
input.setTextColor(input.hintTextColors)
input.setText(prev)
input.addTextChangedListener(TextChangedWatcher {
val colors = houseNumberInputTextColors
if (colors != null) input.setTextColor(colors)
houseNumberInputTextColors = null
})
input.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
updateKeyboardButtonVisibility()
if (hasFocus) input.showKeyboard()
val colors = houseNumberInputTextColors
if (hasFocus && colors != null) {
input.text = null
input.setTextColor(colors)
houseNumberInputTextColors = null
}
}
}
private fun addToHouseNumberInput(add: Int) {
val input = houseNumberInput ?: return
val prev = if (input.text.isEmpty()) {
lastRealHousenumberAnswer?.realHouseNumber
} else {
input.text.toString()
} ?: return
val newHouseNumber = prev.addToHouseNumber(add) ?: return
input.setText(newHouseNumber)
input.setSelection(newHouseNumber.length)
}
private fun initKeyboardButton() {
toggleKeyboardButton?.text = "abc"
toggleKeyboardButton?.setOnClickListener {
val focus = requireActivity().currentFocus
if (focus != null && focus is EditText) {
val start = focus.selectionStart
val end = focus.selectionEnd
if (focus.inputType and InputType.TYPE_CLASS_NUMBER != 0) {
focus.inputType = InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
toggleKeyboardButton?.text = "123"
} else {
focus.inputType = InputType.TYPE_CLASS_NUMBER
focus.keyListener = DigitsKeyListener.getInstance("0123456789.,- /")
toggleKeyboardButton?.text = "abc"
}
// for some reason, the cursor position gets lost first time the input type is set (#1093)
focus.setSelection(start, end)
focus.showKeyboard()
}
}
updateKeyboardButtonVisibility()
val onFocusChange = View.OnFocusChangeListener { v, hasFocus ->
updateKeyboardButtonVisibility()
if (hasFocus) v.showKeyboard()
}
houseNumberInput?.onFocusChangeListener = onFocusChange
streetNumberInput?.onFocusChangeListener = onFocusChange
blockNumberInput?.onFocusChangeListener = onFocusChange
}
private fun updateKeyboardButtonVisibility() {
toggleKeyboardButton?.isInvisible = !(
houseNumberInput?.hasFocus() == true ||
streetNumberInput?.hasFocus() == true ||
blockNumberInput?.hasFocus() == true
)
}
private fun confirmHousenumber(isUnusual: Boolean, onConfirmed: () -> Unit) {
if (isUnusual) {
AlertDialog.Builder(requireContext())
.setTitle(R.string.quest_generic_confirmation_title)
.setMessage(R.string.quest_address_unusualHousenumber_confirmation_description)
.setPositiveButton(R.string.quest_generic_confirmation_yes) { _, _ -> onConfirmed() }
.setNegativeButton(R.string.quest_generic_confirmation_no, null)
.show()
} else {
onConfirmed()
}
}
private fun createAnswer(): HousenumberAnswer? =
if (houseNameInput != null) {
houseNameInput?.nonEmptyInput?.let { HouseName(it) }
}
else if (conscriptionNumberInput != null && streetNumberInput != null) {
conscriptionNumberInput?.nonEmptyInput?.let { conscriptionNumber ->
val streetNumber = streetNumberInput?.nonEmptyInput // streetNumber is optional
ConscriptionNumber(conscriptionNumber, streetNumber)
}
}
else if (blockNumberInput != null && houseNumberInput != null) {
blockNumberInput?.nonEmptyInput?.let { blockNumber ->
houseNumberInput?.nonEmptyInput?.let { houseNumber ->
HouseAndBlockNumber(houseNumber, blockNumber)
}
}
}
else if (houseNumberInput != null) {
houseNumberInput?.nonEmptyInput?.let { HouseNumber(it) }
}
else null
private val EditText.nonEmptyInput:String? get() {
val input = text.toString().trim()
return if(input.isNotEmpty()) input else null
}
companion object {
private var lastRealHousenumberAnswer: HousenumberAnswer? = null
private const val IS_HOUSENAME = "is_housename"
}
}
private val HousenumberAnswer.isRealHouseNumberAnswer: Boolean get() = when(this) {
is HouseNumber -> true
is HouseAndBlockNumber -> true
else -> false
}
private val HousenumberAnswer.realHouseNumber: String? get() = when(this) {
is HouseNumber -> number
is HouseAndBlockNumber -> houseNumber
else -> null
}
private fun String.addToHouseNumber(add: Int): String? {
val parsed = parseHouseNumber(this) ?: return null
when {
add == 0 -> return this
add > 0 -> {
val max = when (val it = parsed.list.maxOrNull()) {
is HouseNumbersPartsRange -> maxOf(it.start, it.end)
is SingleHouseNumbersPart -> it.single
null -> return null
}
return (max.number + add).toString()
}
add < 0 -> {
val min = when (val it = parsed.list.minOrNull()) {
is HouseNumbersPartsRange -> minOf(it.start, it.end)
is SingleHouseNumbersPart -> it.single
null -> return null
}
val result = min.number + add
return if (result < 1) null else result.toString()
}
else -> return null
}
}
| gpl-3.0 | b9b8bd9bac03dbefc42b0b8988ab5c87 | 40.630094 | 116 | 0.657154 | 5.376518 | false | false | false | false |
SirWellington/alchemy-http | src/test/java/tech/sirwellington/alchemy/http/AlchemyHttpImplTest.kt | 1 | 4029 | /*
* Copyright © 2019. Sir Wellington.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tech.sirwellington.alchemy.http
import com.nhaarman.mockito_kotlin.*
import org.hamcrest.Matchers.*
import org.junit.Assert.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import sir.wellington.alchemy.collections.maps.Maps
import tech.sirwellington.alchemy.generator.AlchemyGenerator.Get.one
import tech.sirwellington.alchemy.generator.CollectionGenerators
import tech.sirwellington.alchemy.generator.StringGenerators.Companion.alphabeticStrings
import tech.sirwellington.alchemy.test.junit.ThrowableAssertion.assertThrows
import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner
import tech.sirwellington.alchemy.test.junit.runners.Repeat
/**
*
* @author SirWellington
*/
@RunWith(AlchemyTestRunner::class)
@Repeat(100)
class AlchemyHttpImplTest
{
@Mock
private lateinit var stateMachine: AlchemyHttpStateMachine
private lateinit var requestCaptor: KArgumentCaptor<HttpRequest>
private lateinit var defaultHeaders: Map<String, String>
private lateinit var instance: AlchemyHttp
@Before
fun setUp()
{
defaultHeaders = CollectionGenerators.mapOf(alphabeticStrings(), alphabeticStrings(), 20)
instance = AlchemyHttpImpl(defaultHeaders, stateMachine)
verifyZeroInteractions(stateMachine)
requestCaptor = argumentCaptor()
}
@Test
fun testDefaultHeadersArePassedToStateMachine()
{
val result = instance.go()
verify(stateMachine).begin(requestCaptor.capture())
val requestMade = requestCaptor.firstValue
assertThat(requestMade, notNullValue())
assertThat(requestMade.requestHeaders, equalTo(defaultHeaders))
}
@Test
fun testUsingDefaultHeader()
{
val key = one(alphabeticStrings())
val value = one(alphabeticStrings())
val result = instance.usingDefaultHeader(key, value)
assertThat(result, notNullValue())
assertThat(result, not(sameInstance(instance)))
result.go()
verify(stateMachine).begin(requestCaptor.capture())
val requestMade = requestCaptor.firstValue
assertThat(requestMade, notNullValue())
val expectedHeaders = Maps.mutableCopyOf(defaultHeaders)
expectedHeaders.put(key, value)
assertThat(requestMade.requestHeaders, equalTo(expectedHeaders))
}
@Test
fun testUsingDefaultHeaderEdgeCase()
{
val key = one(alphabeticStrings())
val value = one(alphabeticStrings())
assertThrows { instance.usingDefaultHeader("", "") }
.isInstanceOf(IllegalArgumentException::class.java)
assertThrows { instance.usingDefaultHeader("", value) }
.isInstanceOf(IllegalArgumentException::class.java)
//Key alone is OK
instance.usingDefaultHeader(key, "")
}
@Test
fun testGo()
{
val result = instance.go()
verify(stateMachine).begin(any())
}
@Test
fun testGetDefaultHeaders()
{
val result = instance.defaultHeaders
assertThat(result, equalTo(defaultHeaders))
val javaHeaders = result as? java.util.Map<String, String> ?: return
assertThrows { javaHeaders.clear() }
}
@Test
fun testToString()
{
val toString = instance.toString()
assertThat(toString, not(isEmptyOrNullString()))
}
}
| apache-2.0 | c52275fa990f29b717d4bec65d3c056c | 28.837037 | 97 | 0.709782 | 4.978986 | false | true | false | false |
matkoniecz/StreetComplete | buildSrc/src/main/java/UpdateAppTranslationCompletenessTask.kt | 2 | 1685 | import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction
import java.io.File
/** Update a resources file that specifies the current translation completeness for every language */
open class UpdateAppTranslationCompletenessTask : AUpdateFromPOEditorTask() {
@get:Input var targetFiles: ((androidResCode: String) -> String)? = null
@TaskAction fun run() {
val targetFiles = targetFiles ?: return
val localizationStatus = fetchLocalizations {
LocalizationStatus(it.string("code")!!, it.int("percentage")!!)
}
for (status in localizationStatus) {
val languageCode = status.languageCode
val completedPercentage = status.completedPercentage
val javaLanguageTag = bcp47LanguageTagToJavaLanguageTag(languageCode)
val androidResCodes = javaLanguageTagToAndroidResCodes(javaLanguageTag)
// create a metadata file that describes how complete the translation is
for (androidResCode in androidResCodes) {
// exclude default translation
if (androidResCode == "en-rUS") continue
val targetFile = File(targetFiles(androidResCode))
File(targetFile.parent).mkdirs()
targetFile.writeText("""
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="translation_completeness">${completedPercentage}</integer>
</resources>
""".trimIndent())
}
}
}
}
private data class LocalizationStatus(val languageCode: String, val completedPercentage: Int)
| gpl-3.0 | 311369a4ca8d1d00ac6cba9a99acd5ae | 40.097561 | 101 | 0.636795 | 5.200617 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/map/tangram/TangramExtensions.kt | 1 | 2497 | package de.westnordost.streetcomplete.map.tangram
import android.graphics.PointF
import android.graphics.RectF
import android.location.Location
import com.mapzen.tangram.LngLat
import com.mapzen.tangram.geometry.Geometry
import com.mapzen.tangram.geometry.Point
import com.mapzen.tangram.geometry.Polygon
import com.mapzen.tangram.geometry.Polyline
import de.westnordost.streetcomplete.data.osm.geometry.ElementGeometry
import de.westnordost.streetcomplete.data.osm.geometry.ElementPointGeometry
import de.westnordost.streetcomplete.data.osm.geometry.ElementPolygonsGeometry
import de.westnordost.streetcomplete.data.osm.geometry.ElementPolylinesGeometry
import de.westnordost.streetcomplete.data.osm.mapdata.LatLon
import de.westnordost.streetcomplete.util.distanceTo
fun ElementGeometry.toTangramGeometry(): List<Geometry> = when(this) {
is ElementPolylinesGeometry -> {
polylines.map { polyline ->
Polyline(polyline.map { it.toLngLat() }, mapOf("type" to "line"))
}
}
is ElementPolygonsGeometry -> {
listOf(
Polygon(
polygons.map { polygon ->
polygon.map { it.toLngLat() }
},
mapOf("type" to "poly")
)
)
}
is ElementPointGeometry -> {
listOf(Point(center.toLngLat(), mapOf("type" to "point")))
}
}
fun LngLat.toLatLon(): LatLon = LatLon(latitude, longitude)
fun LatLon.toLngLat(): LngLat = LngLat(longitude, latitude)
fun Location.toLngLat(): LngLat = LngLat(longitude, latitude)
fun KtMapController.screenAreaContains(g: ElementGeometry, offset: RectF): Boolean {
val p = PointF()
val mapView = glViewHolder!!.view
return when (g) {
is ElementPolylinesGeometry -> g.polylines
is ElementPolygonsGeometry -> g.polygons
else -> listOf(listOf(g.center))
}.flatten().all {
latLonToScreenPosition(it, p, false)
&& p.x >= offset.left
&& p.x <= mapView.width - offset.right
&& p.y >= offset.top
&& p.y <= mapView.height - offset.bottom
}
}
fun KtMapController.screenBottomToCenterDistance(): Double? {
val view = glViewHolder?.view ?: return null
val w = view.width
val h = view.height
if (w == 0 || h == 0) return null
val center = screenPositionToLatLon(PointF(w/2f, h/2f)) ?: return null
val bottom = screenPositionToLatLon(PointF(w/2f, h*1f)) ?: return null
return center.distanceTo(bottom)
}
| gpl-3.0 | 5c576a397affd445346e1f80b7a04633 | 34.671429 | 84 | 0.681618 | 4.086743 | false | false | false | false |
akvo/akvo-flow-mobile | app/src/main/java/org/akvo/flow/presentation/form/languages/LanguagesDialogFragment.kt | 1 | 4259 | /*
* Copyright (C) 2020 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Flow.
*
* Akvo Flow 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.
*
* Akvo Flow 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 Akvo Flow. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.flow.presentation.form.languages
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.AdapterView
import android.widget.ListView
import androidx.fragment.app.DialogFragment
import org.akvo.flow.R
import org.akvo.flow.app.FlowApp
import org.akvo.flow.injector.component.ApplicationComponent
import org.akvo.flow.injector.component.DaggerViewComponent
import org.akvo.flow.ui.adapter.LanguageAdapter
import org.akvo.flow.uicomponents.SnackBarManager
import org.akvo.flow.util.ConstantUtil
import java.util.ArrayList
import javax.inject.Inject
class LanguagesDialogFragment : DialogFragment() {
private var listener: LanguagesSelectionListener? = null
@Inject
lateinit var snackBarManager: SnackBarManager
private var languages = mutableListOf<Language>()
companion object {
const val TAG = "LanguagesDialogFragment"
@JvmStatic
fun newInstance(languages: ArrayList<Language>): LanguagesDialogFragment {
return LanguagesDialogFragment().apply {
arguments = Bundle().apply {
putParcelableArrayList(ConstantUtil.LANGUAGES_EXTRA, languages)
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initializeInjector()
val parcelableArrayList =
arguments!!.getParcelableArrayList<Language>(ConstantUtil.LANGUAGES_EXTRA)
if (parcelableArrayList != null) {
languages = parcelableArrayList.toMutableList()
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
try {
listener = activity as LanguagesSelectionListener
} catch (e: ClassCastException) {
throw ClassCastException("${activity.toString()} must implement LanguagesSelectionListener")
}
}
private fun initializeInjector() {
val viewComponent = DaggerViewComponent.builder()
.applicationComponent(getApplicationComponent())
.build()
viewComponent.inject(this)
}
private fun getApplicationComponent(): ApplicationComponent? {
return (activity!!.application as FlowApp).getApplicationComponent()
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val languageAdapter = LanguageAdapter(activity, languages)
val listView = LayoutInflater.from(activity)
.inflate(R.layout.languages_list, null) as ListView
listView.adapter = languageAdapter
listView.onItemClickListener =
AdapterView.OnItemClickListener { _, _, position, _ ->
languageAdapter.updateSelected(position)
}
return AlertDialog.Builder(activity)
.setTitle(R.string.surveylanglabel)
.setView(listView)
.setPositiveButton(R.string.okbutton) { _, _ ->
val selectedLanguages = (listView.adapter as LanguageAdapter).selectedLanguages
listener?.useSelectedLanguages(selectedLanguages, languages)
}.create()
}
override fun onDetach() {
super.onDetach()
listener = null
}
interface LanguagesSelectionListener {
fun useSelectedLanguages(
selectedLanguages: MutableSet<String>,
availableLanguages: List<Language>
)
}
}
| gpl-3.0 | 8960915eed5c3bed8c1c7e3240fa67ff | 33.909836 | 104 | 0.692651 | 5.156174 | false | false | false | false |
ursjoss/scipamato | core/core-persistence-jooq/src/test/kotlin/ch/difty/scipamato/core/persistence/user/JooqUserRepoTest.kt | 2 | 3235 | package ch.difty.scipamato.core.persistence.user
import ch.difty.scipamato.core.db.tables.ScipamatoUser
import ch.difty.scipamato.core.db.tables.ScipamatoUser.SCIPAMATO_USER
import ch.difty.scipamato.core.db.tables.records.ScipamatoUserRecord
import ch.difty.scipamato.core.entity.User
import ch.difty.scipamato.core.entity.search.UserFilter
import ch.difty.scipamato.core.persistence.EntityRepository
import ch.difty.scipamato.core.persistence.JooqEntityRepoTest
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.jooq.TableField
internal class JooqUserRepoTest :
JooqEntityRepoTest<ScipamatoUserRecord, User, Int, ScipamatoUser, UserRecordMapper, UserFilter>() {
private val userRoleRepoMock = mockk<UserRoleRepository>()
override val sampleId: Int = SAMPLE_ID
override val unpersistedEntity = mockk<User>()
override val persistedEntity = mockk<User>()
override val persistedRecord = mockk<ScipamatoUserRecord>()
override val unpersistedRecord = mockk<ScipamatoUserRecord>()
override val mapper = mockk<UserRecordMapper>()
override val filter = mockk<UserFilter>()
override val table: ScipamatoUser = SCIPAMATO_USER
override val tableId: TableField<ScipamatoUserRecord, Int> = SCIPAMATO_USER.ID
override val recordVersion: TableField<ScipamatoUserRecord, Int> = SCIPAMATO_USER.VERSION
override val repo: JooqUserRepo = JooqUserRepo(
dsl,
mapper,
sortMapper,
filterConditionMapper,
dateTimeService,
insertSetStepSetter,
updateSetStepSetter,
applicationProperties,
userRoleRepoMock
)
override fun makeRepoFindingEntityById(entity: User): EntityRepository<User, Int, UserFilter> =
object : JooqUserRepo(
dsl,
mapper,
sortMapper,
filterConditionMapper,
dateTimeService,
insertSetStepSetter,
updateSetStepSetter,
applicationProperties,
userRoleRepoMock
) {
override fun findById(id: Int, version: Int): User = entity
}
override fun makeRepoSavingReturning(returning: ScipamatoUserRecord): EntityRepository<User, Int, UserFilter> =
object : JooqUserRepo(
dsl,
mapper,
sortMapper,
filterConditionMapper,
dateTimeService,
insertSetStepSetter,
updateSetStepSetter,
applicationProperties,
userRoleRepoMock
) {
override fun doSave(entity: User, languageCode: String): ScipamatoUserRecord = returning
}
override fun expectEntityIdsWithValues() {
every { unpersistedEntity.id } returns SAMPLE_ID
every { persistedRecord.id } returns SAMPLE_ID
}
override fun expectUnpersistedEntityIdNull() {
every { unpersistedEntity.id } returns null
}
override fun verifyUnpersistedEntityId() {
verify { unpersistedEntity.id }
verify { unpersistedEntity.toString() }
}
override fun verifyPersistedRecordId() {
verify { persistedRecord.id }
}
companion object {
private const val SAMPLE_ID = 3
}
}
| bsd-3-clause | e287a8d4329ae4f1438cd4326384f064 | 32.010204 | 115 | 0.688717 | 5.126783 | false | false | false | false |
SimonVT/cathode | cathode/src/main/java/net/simonvt/cathode/ui/search/RecentsViewHolder.kt | 1 | 1897 | package net.simonvt.cathode.ui.search
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import net.simonvt.cathode.R
import net.simonvt.cathode.R.id
import net.simonvt.cathode.common.widget.find
import net.simonvt.cathode.ui.search.SearchAdapter.OnResultClickListener
class RecentsViewHolder constructor(view: View, listener: OnResultClickListener) :
ViewHolder(view) {
val query1: TextView = view.find(id.query1)
val query2: TextView = view.find(id.query2)
val query3: TextView = view.find(id.query3)
var queryOneQuery: String? = null
var queryTwoQuery: String? = null
var queryThreeQuery: String? = null
init {
val icon = VectorDrawableCompat.create(
view.context.resources,
R.drawable.ic_search_history_24dp, null
)
query1.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null)
query2.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null)
query3.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null)
query1.setOnClickListener { listener.onQueryClicked(queryOneQuery!!) }
query2.setOnClickListener { listener.onQueryClicked(queryTwoQuery!!) }
query3.setOnClickListener { listener.onQueryClicked(queryThreeQuery!!) }
}
fun update(recents: List<String>) {
val recentQueryCount = recents.size
queryOneQuery = recents[0]
query1.text = queryOneQuery
if (recentQueryCount >= 2) {
queryTwoQuery = recents[1]
query2.text = queryTwoQuery
query2.visibility = View.VISIBLE
} else {
query2.visibility = View.GONE
}
if (recentQueryCount >= 3) {
queryThreeQuery = recents[2]
query3.text = queryThreeQuery
query3.visibility = View.VISIBLE
} else {
query3.visibility = View.GONE
}
}
}
| apache-2.0 | 4ca098b14d16ee9cf80d3f656224c952 | 30.616667 | 82 | 0.74117 | 4.010571 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/inspections/latex/typesetting/LatexDiacriticIJInspection.kt | 1 | 2874 | package nl.hannahsten.texifyidea.inspections.latex.typesetting
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.impl.source.tree.LeafPsiElement
import nl.hannahsten.texifyidea.inspections.TexifyRegexInspection
import nl.hannahsten.texifyidea.lang.Diacritic
import nl.hannahsten.texifyidea.lang.magic.MagicCommentScope
import nl.hannahsten.texifyidea.psi.LatexMathContent
import nl.hannahsten.texifyidea.psi.LatexNormalText
import nl.hannahsten.texifyidea.psi.LatexTypes
import nl.hannahsten.texifyidea.util.hasParent
import nl.hannahsten.texifyidea.util.inMathContext
import nl.hannahsten.texifyidea.util.isComment
import java.util.*
import java.util.regex.Matcher
import java.util.regex.Pattern
/**
* @author Hannah Schellekens
*/
open class LatexDiacriticIJInspection : TexifyRegexInspection(
inspectionDisplayName = "Dotless versions of i and j should be used with diacritics",
inspectionId = "DiacriticIJ",
highlight = ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
errorMessage = { "Diacritic must be placed upon a dotless ${letter(it)}" },
pattern = Pattern.compile(
"(${Diacritic.allValues().joinToString("|") {
it.command.replace("\\", "\\\\")
.replace("^", "\\^")
.replace(".", "\\.")
}})\\{?([ij])}?"
),
replacement = this::replacement,
replacementRange = this::replaceRange,
quickFixName = { "Change to dotless ${letter(it)}" }
) {
companion object {
fun replacement(it: Matcher, file: PsiFile): String {
val group = it.group(2)
val element = file.findElementAt(it.start())
// Math mode.
if (element != null && element.inMathContext()) {
return when (group) {
"i" -> "\\imath"
else -> "\\jmath"
}
}
// Regular text.
return when (it.group(2)) {
"i" -> "{\\i}"
else -> "{\\j}"
}
}
fun replaceRange(it: Matcher) = it.groupRange(2)
fun letter(it: Matcher) = it.group(2)!!
}
override val outerSuppressionScopes = EnumSet.of(MagicCommentScope.COMMAND)!!
override fun checkContext(matcher: Matcher, element: PsiElement): Boolean {
if (element.isComment()) return false
val file = element.containingFile
val offset = matcher.end()
val foundAhead = file.findElementAt(offset)
if (foundAhead is LeafPsiElement && foundAhead.elementType == LatexTypes.COMMAND_TOKEN) {
return false
}
val found = file.findElementAt(offset - 1) ?: return false
return found.hasParent(LatexNormalText::class) || found.hasParent(LatexMathContent::class)
}
}
| mit | 3fd48517c9239e2efe9a17cb0e231556 | 34.04878 | 98 | 0.646486 | 4.483619 | false | false | false | false |
jamieadkins95/Roach | database/src/main/java/com/jamieadkins/gwent/database/KeywordDao.kt | 1 | 1174 | package com.jamieadkins.gwent.database
import androidx.room.*
import com.jamieadkins.gwent.database.entity.*
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Maybe
import io.reactivex.Single
@Dao
interface KeywordDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(entity: KeywordEntity): Long
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(items: Collection<KeywordEntity>)
@Query("SELECT * FROM ${GwentDatabase.KEYWORD_TABLE} WHERE keywordId = :keywordId AND locale = :locale")
fun getKeywordForLocale(keywordId: String, locale: String): Flowable<KeywordEntity>
@Query("SELECT * FROM ${GwentDatabase.KEYWORD_TABLE} WHERE locale = :locale")
fun getKeywordsForLocale(locale: String): Flowable<List<KeywordEntity>>
@Query("SELECT * FROM ${GwentDatabase.KEYWORD_TABLE} WHERE keywordId = :keywordId")
fun getKeyword(keywordId: String): Flowable<List<KeywordEntity>>
@Query("SELECT * FROM ${GwentDatabase.KEYWORD_TABLE}")
fun getAllKeywords(): Flowable<List<KeywordEntity>>
@Query("DELETE FROM ${GwentDatabase.KEYWORD_TABLE}")
fun clear(): Completable
}
| apache-2.0 | 83a49d08e306f7e505e2660ce6527782 | 34.575758 | 108 | 0.752981 | 4.463878 | false | false | false | false |
Geobert/radis | app/src/main/kotlin/fr/geobert/radis/tools/ExpandAnimation.kt | 1 | 2989 | package fr.geobert.radis.tools
import android.view.View
import android.view.animation.Animation
import android.view.animation.Transformation
import android.widget.LinearLayout.LayoutParams
/**
* This animation class is animating the expanding and reducing the size of a view.
* The animation toggles between the Expand and Reduce, depending on the current state of the view
* see https://github.com/Udinic/SmallExamples/blob/master/ExpandAnimationExample/src/com/udinic/expand_animation_example/ExpandAnimation.java
* @author Udinic
*/
class ExpandAnimation
/**
* Initialize the animation
* @param view The layout we want to animate
* *
* @param duration The duration of the animation, in ms
*/
(private val mAnimatedView: View, duration: Int, expand: Boolean) : Animation() {
private val mViewLayoutParams: LayoutParams
private var mMarginStart: Int = 0
private val mMarginEnd: Int
private var mIsVisibleAfter = false
private var mWasEndedAlready = false
init {
setDuration(duration.toLong())
isFillEnabled = true
fillAfter = true
mViewLayoutParams = mAnimatedView.layoutParams as LayoutParams
// decide to show or hide the view
mIsVisibleAfter = expand
if (expand) {
mMarginStart = -84
} else {
mMarginStart = 0
}
mMarginEnd = (if (mMarginStart == 0) -84 else 0)
mAnimatedView.visibility = View.VISIBLE
setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
}
override fun onAnimationEnd(animation: Animation) {
if (!mIsVisibleAfter) {
mViewLayoutParams.bottomMargin = -mAnimatedView.measuredHeight // -55
mAnimatedView.visibility = View.GONE
} else {
mViewLayoutParams.bottomMargin = 0
mAnimatedView.visibility = View.VISIBLE
}
}
override fun onAnimationRepeat(animation: Animation) {
}
})
}
override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
super.applyTransformation(interpolatedTime, t)
if (interpolatedTime < 1.0f) {
// Calculating the new bottom margin, and setting it
mViewLayoutParams.bottomMargin = mMarginStart + ((mMarginEnd - mMarginStart) * interpolatedTime).toInt()
// Invalidating the layout, making us seeing the changes we made
mAnimatedView.requestLayout()
// Making sure we didn't run the ending before (it happens!)
} else if (!mWasEndedAlready) {
mViewLayoutParams.bottomMargin = mMarginEnd
mAnimatedView.requestLayout()
if (!mIsVisibleAfter) {
mAnimatedView.visibility = View.GONE
}
mWasEndedAlready = true
}
}
}
| gpl-2.0 | 752a30db34ae7e76b80e1affbe2d2f45 | 31.846154 | 142 | 0.643694 | 5.234676 | false | false | false | false |
hartwigmedical/hmftools | cider/src/main/java/com/hartwig/hmftools/cider/CiderGeneDatastore.kt | 1 | 5930 | package com.hartwig.hmftools.cider
import org.apache.logging.log4j.LogManager
import org.eclipse.collections.api.collection.ImmutableCollection
import org.eclipse.collections.api.factory.Lists
import org.eclipse.collections.api.factory.Maps
import org.eclipse.collections.api.factory.Sets
import org.eclipse.collections.api.list.ImmutableList
import org.eclipse.collections.api.map.ImmutableMap
import org.eclipse.collections.api.map.MutableMap
import org.eclipse.collections.api.multimap.ImmutableMultimap
import org.eclipse.collections.api.multimap.MutableMultimap
import org.eclipse.collections.api.set.SetIterable
import org.eclipse.collections.impl.map.mutable.UnifiedMap
import org.eclipse.collections.impl.multimap.list.FastListMultimap
import java.util.stream.Collectors
// we use immutable collections here, data can be accessed by multiple threads
interface ICiderGeneDatastore
{
fun getAnchorSequenceSet(geneType: VJGeneType): SetIterable<String>
fun getByAnchorSequence(anchorSeq: String): ImmutableCollection<VJAnchorTemplate>
fun getByAnchorSequence(geneType: VJGeneType, anchorSeq: String): ImmutableCollection<VJAnchorTemplate>
fun getByGeneLocation(genomeRegionStrand: GenomeRegionStrand): ImmutableCollection<VJAnchorTemplate>
fun getVjAnchorGeneLocations(): ImmutableCollection<VJAnchorGenomeLocation>
fun getIgConstantRegions(): ImmutableCollection<IgTcrConstantRegion>
}
open class CiderGeneDatastore(vjAnchorTemplates: List<VJAnchorTemplate>, igTcrConstantRegions: List<IgTcrConstantRegion>) : ICiderGeneDatastore
{
private val sLogger = LogManager.getLogger(javaClass)
// all of the data here are immutable, so we access them from multiple threads.
private val mAnchorSequenceMap: ImmutableMultimap<String, VJAnchorTemplate>
private val mGeneTypeAnchorSeqMap: ImmutableMap<VJGeneType, ImmutableMultimap<String, VJAnchorTemplate>>
private val mGeneLocationTemplateMap: ImmutableMultimap<GenomeRegionStrand, VJAnchorTemplate>
private val mVjAnchorGenomeLocations: ImmutableList<VJAnchorGenomeLocation>
private val mIgTcrConstantRegions: ImmutableList<IgTcrConstantRegion>
override fun getAnchorSequenceSet(geneType: VJGeneType): SetIterable<String>
{
val anchorSeqMap = mGeneTypeAnchorSeqMap[geneType]
return if (anchorSeqMap != null) anchorSeqMap.keySet() else Sets.immutable.empty()
}
override fun getByAnchorSequence(anchorSeq: String): ImmutableCollection<VJAnchorTemplate>
{
return mAnchorSequenceMap[anchorSeq]
}
override fun getByAnchorSequence(geneType: VJGeneType, anchorSeq: String): ImmutableCollection<VJAnchorTemplate>
{
val anchorSeqMap = mGeneTypeAnchorSeqMap[geneType]
return if (anchorSeqMap != null) anchorSeqMap[anchorSeq] else Sets.immutable.empty()
}
override fun getByGeneLocation(genomeRegionStrand: GenomeRegionStrand): ImmutableCollection<VJAnchorTemplate>
{
return mGeneLocationTemplateMap[genomeRegionStrand]
}
override fun getVjAnchorGeneLocations(): ImmutableList<VJAnchorGenomeLocation>
{
return mVjAnchorGenomeLocations
}
override fun getIgConstantRegions(): ImmutableCollection<IgTcrConstantRegion>
{
return mIgTcrConstantRegions
}
init
{
val anchorSequenceMap: MutableMultimap<String, VJAnchorTemplate> = FastListMultimap()
val geneTypeAnchorSeqMap: MutableMap<VJGeneType, MutableMultimap<String, VJAnchorTemplate>> = UnifiedMap()
val geneLocationVJGeneMap: MutableMultimap<GenomeRegionStrand, VJAnchorTemplate> = FastListMultimap()
val vjAnchorGenomeLocationMap: MutableMap<GenomeRegionStrand, VJGeneType> = UnifiedMap()
// from this we find all the anchor sequence locations and fix them
for (gene in vjAnchorTemplates)
{
if (gene.anchorLocation != null)
{
geneLocationVJGeneMap.put(gene.anchorLocation, gene)
// we want to check that same location cannot be used by more than one VJ type
val existingVjGeneType: VJGeneType? = vjAnchorGenomeLocationMap[gene.anchorLocation]
if (existingVjGeneType != null && existingVjGeneType != gene.type)
{
sLogger.error(
"gene location: {} is used by multiple gene type: {} and {}",
gene.anchorLocation, existingVjGeneType, gene.type
)
throw RuntimeException("gene location: ${gene.anchorLocation} is used by multiple gene type: ${existingVjGeneType} and ${gene.type}")
}
vjAnchorGenomeLocationMap[gene.anchorLocation] = gene.type
}
if (gene.anchorSequence.isNotEmpty())
{
anchorSequenceMap.put(gene.anchorSequence, gene)
geneTypeAnchorSeqMap.computeIfAbsent(gene.type) { o: VJGeneType? -> FastListMultimap() }
.put(gene.anchorSequence, gene)
}
}
mAnchorSequenceMap = anchorSequenceMap.toImmutable()
// copy to immutable, have to convert each entry to immutable version as well
mGeneTypeAnchorSeqMap = Maps.immutable.ofMap(
geneTypeAnchorSeqMap.entries.stream().collect(
Collectors.toMap(
{ entry -> entry.key },
{ entry -> entry.value.toImmutable() }
)))
mGeneLocationTemplateMap = geneLocationVJGeneMap.toImmutable()
mVjAnchorGenomeLocations =
Lists.immutable.fromStream(vjAnchorGenomeLocationMap.entries.stream().map({ o -> VJAnchorGenomeLocation(o.value, o.key) }))
// also the constant region
mIgTcrConstantRegions = Lists.immutable.ofAll(igTcrConstantRegions)
sLogger.info("found {} gene locations", mGeneLocationTemplateMap.keySet().size())
}
} | gpl-3.0 | 593e8b15874c50e1ccdd104097be2217 | 46.448 | 153 | 0.724958 | 5.188101 | false | false | false | false |
gotev/android-upload-service | examples/SimpleMultipartUpload/app/src/main/java/it/gotev/testapp/MainActivity.kt | 2 | 2309 | package it.gotev.testapp
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import net.gotev.uploadservice.protocols.multipart.MultipartUploadRequest
class MainActivity : AppCompatActivity() {
companion object {
// Every intent for result needs a unique ID in your app.
// Choose the number which is good for you, here I'll use a random one.
const val pickFileRequestCode = 42
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<Button>(R.id.uploadButton).setOnClickListener {
pickFile()
}
}
// Pick a file with a content provider
fun pickFile() {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
// Filter to only show results that can be "opened", such as files
addCategory(Intent.CATEGORY_OPENABLE)
// search for all documents available via installed storage providers
type = "*/*"
// obtain permission to read and persistable permission
flags = (Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
}
startActivityForResult(intent, pickFileRequestCode)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
// The ACTION_OPEN_DOCUMENT intent was sent with the request code
// READ_REQUEST_CODE. If the request code seen here doesn't match, it's the
// response to some other intent, and the code below shouldn't run at all.
if (requestCode == pickFileRequestCode && resultCode == Activity.RESULT_OK) {
data?.let {
onFilePicked(it.data.toString())
}
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
fun onFilePicked(filePath: String) {
MultipartUploadRequest(this, serverUrl = "https://ptsv2.com/t/irntp-1574507866/post")
.setMethod("POST")
.addFileToUpload(
filePath = filePath,
parameterName = "myFile"
).startUpload()
}
}
| apache-2.0 | a4e263a4a0caa535b956f1a699f12b7b | 36.852459 | 107 | 0.651797 | 4.85084 | false | false | false | false |
BjoernPetersen/JMusicBot | src/test/kotlin/net/bjoernpetersen/musicbot/test/internal/player/DummyProvider.kt | 1 | 3158 | package net.bjoernpetersen.musicbot.test.internal.player
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import net.bjoernpetersen.musicbot.api.config.Config
import net.bjoernpetersen.musicbot.api.loader.NoResource
import net.bjoernpetersen.musicbot.api.player.Song
import net.bjoernpetersen.musicbot.api.player.song
import net.bjoernpetersen.musicbot.api.plugin.IdBase
import net.bjoernpetersen.musicbot.spi.loader.Resource
import net.bjoernpetersen.musicbot.spi.plugin.AbstractPlayback
import net.bjoernpetersen.musicbot.spi.plugin.NoSuchSongException
import net.bjoernpetersen.musicbot.spi.plugin.Playback
import net.bjoernpetersen.musicbot.spi.plugin.Provider
import net.bjoernpetersen.musicbot.spi.plugin.management.ProgressFeedback
import java.time.Duration
@IdBase("Dummy")
class DummyProvider : Provider {
override val name: String = "Dummy"
override val subject: String
get() = name
override val description: String
get() = name
val songs = listOf(createSong("one"), createSong("two"))
var loadingTime: Duration = LOADING_TIME
var closingTime: Duration = CLOSING_TIME
fun resetTimes() {
loadingTime = LOADING_TIME
closingTime = CLOSING_TIME
}
operator fun component1(): Song = songs[0]
operator fun component2(): Song = songs[1]
operator fun get(index: Int) = songs[index]
override suspend fun search(query: String, offset: Int): List<Song> {
return songs.filter { it.id in query }
}
override suspend fun lookup(id: String): Song {
return songs.firstOrNull { it.id == id } ?: throw NoSuchSongException(
id
)
}
override suspend fun supplyPlayback(song: Song, resource: Resource): Playback =
DummyPlayback()
override suspend fun loadSong(song: Song): Resource =
NoResource
override fun createConfigEntries(config: Config): List<Config.Entry<*>> = emptyList()
override fun createSecretEntries(secrets: Config): List<Config.Entry<*>> = emptyList()
override fun createStateEntries(state: Config) = Unit
override suspend fun initialize(progressFeedback: ProgressFeedback) = Unit
override suspend fun close() = Unit
private fun createSong(id: String): Song = song(id) {
title = "title-$id"
description = "description-$id"
duration = DURATION.seconds.toInt()
}
private inner class DummyPlayback : AbstractPlayback() {
private var started = false
override suspend fun play() {
if (!started) {
delay(loadingTime.toMillis())
launch {
delay(DURATION.toMillis())
markDone()
}
started = true
}
}
override suspend fun pause() = Unit
override suspend fun close() {
delay(closingTime.toMillis())
super.close()
}
}
companion object {
val DURATION: Duration = Duration.ofSeconds(5)
val LOADING_TIME: Duration = Duration.ofMillis(500)
val CLOSING_TIME: Duration = Duration.ofMillis(200)
}
}
| mit | d8eaba8ffefbf667112c31af18410e5f | 32.242105 | 90 | 0.673211 | 4.590116 | false | true | false | false |
karollewandowski/aem-intellij-plugin | src/main/kotlin/co/nums/intellij/aem/htl/editor/actions/backspace/AbstractBackspaceHandler.kt | 1 | 1286 | package co.nums.intellij.aem.htl.editor.actions.backspace
import co.nums.intellij.aem.extensions.removeText
import co.nums.intellij.aem.htl.extensions.isHtl
import com.intellij.codeInsight.editorActions.BackspaceHandlerDelegate
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiFile
abstract class AbstractBackspaceHandler : BackspaceHandlerDelegate() {
abstract val expectedDeletedChar: Char
abstract val expectedNextChar: Char
override fun beforeCharDeleted(deletedChar: Char, file: PsiFile, editor: Editor) {
// do nothing
}
override fun charDeleted(deletedChar: Char, file: PsiFile, editor: Editor): Boolean {
if (deletedChar == expectedDeletedChar && file.isHtl()) {
val offset = editor.caretModel.offset
if (offset < 1 || offset >= editor.document.textLength) {
return false
}
val document = editor.document
val nextChar = document.charsSequence[offset]
if (nextChar == expectedNextChar && shouldBeDeleted(file, offset)) {
document.removeText(offset, offset + 1)
return true
}
}
return false
}
abstract fun shouldBeDeleted(file: PsiFile, offset: Int): Boolean
}
| gpl-3.0 | 643248a6667a6af216458dbefb223687 | 34.722222 | 89 | 0.676516 | 4.65942 | false | false | false | false |
apixandru/intellij-community | platform/script-debugger/protocol/protocol-reader/src/FieldProcessor.kt | 30 | 7216 | package org.jetbrains.protocolReader
import com.intellij.openapi.util.text.StringUtil
import gnu.trove.THashSet
import org.jetbrains.jsonProtocol.JsonField
import org.jetbrains.jsonProtocol.JsonSubtypeCasting
import org.jetbrains.jsonProtocol.Optional
import org.jetbrains.jsonProtocol.ProtocolName
import java.lang.reflect.Method
import java.lang.reflect.ParameterizedType
import java.util.*
import kotlin.reflect.KCallable
import kotlin.reflect.KFunction
import kotlin.reflect.KProperty
import kotlin.reflect.jvm.javaGetter
import kotlin.reflect.jvm.javaMethod
import kotlin.reflect.jvm.javaType
internal class FieldLoader(val name: String, val jsonName: String, val valueReader: ValueReader, val skipRead: Boolean, val asImpl: Boolean, val defaultValue: String?)
internal fun TextOutput.appendName(loader: FieldLoader): TextOutput {
if (!loader.asImpl) {
append(FIELD_PREFIX)
}
append(loader.name)
return this
}
internal class FieldProcessor(private val reader: InterfaceReader, typeClass: Class<*>) {
val fieldLoaders = ArrayList<FieldLoader>()
val methodHandlerMap = LinkedHashMap<Method, MethodHandler>()
val volatileFields = ArrayList<VolatileFieldBinding>()
var lazyRead: Boolean = false
init {
val methods = typeClass.methods
// todo sort by source location
Arrays.sort(methods, { o1, o2 -> o1.name.compareTo(o2.name) })
val skippedNames = THashSet<String>()
for (method in methods) {
val annotation = method.getAnnotation<JsonField>(JsonField::class.java)
if (annotation != null && !annotation.primitiveValue.isEmpty()) {
skippedNames.add(annotation.primitiveValue)
skippedNames.add("${annotation.primitiveValue}Type")
}
}
val classPackage = typeClass.`package`
val kClass = typeClass.kotlin
for (member in kClass.members) {
val method = if (member is KProperty<*>) {
member.javaGetter!!
}
else if (member is KFunction<*>) {
member.javaMethod!!
}
else {
continue
}
val methodClass = method.declaringClass
// use method from super if super located in the same package
if (methodClass != typeClass) {
val methodPackage = methodClass.`package`
if (methodPackage != classPackage && !classPackage.name.startsWith("${methodPackage.name}.")) {
continue
}
}
if (method.parameterCount != 0) {
throw JsonProtocolModelParseException("No parameters expected in $method")
}
try {
val methodHandler: MethodHandler
val jsonSubtypeCaseAnnotation = method.getAnnotation(JsonSubtypeCasting::class.java)
if (jsonSubtypeCaseAnnotation == null) {
methodHandler = createMethodHandler(member, method, skippedNames.contains(method.name)) ?: continue
}
else {
methodHandler = processManualSubtypeMethod(member, method, jsonSubtypeCaseAnnotation)
lazyRead = true
}
methodHandlerMap.put(method, methodHandler)
}
catch (e: Exception) {
throw JsonProtocolModelParseException("Problem with method $method", e)
}
}
}
private fun createMethodHandler(member: KCallable<*>, method: Method, skipRead: Boolean): MethodHandler? {
var protocolName = member.annotation<ProtocolName>()?.name ?: member.name
val genericReturnType = member.returnType.javaType
val isNotNull: Boolean
val isPrimitive = if (genericReturnType is Class<*>) genericReturnType.isPrimitive else genericReturnType !is ParameterizedType
val optionalAnnotation = member.annotation<Optional>()
if (isPrimitive || optionalAnnotation != null) {
isNotNull = false
}
else {
val fieldAnnotation = member.annotation<JsonField>()
if (fieldAnnotation == null) {
isNotNull = !member.returnType.isMarkedNullable
}
else {
isNotNull = !fieldAnnotation.allowAnyPrimitiveValue && !fieldAnnotation.allowAnyPrimitiveValueAndMap
}
}
val fieldTypeParser = reader.getFieldTypeParser(member, genericReturnType, false, method)
val isProperty = member is KProperty<*>
val isAsImpl = isProperty && !isNotNull
if (fieldTypeParser != VOID_PARSER) {
fieldLoaders.add(FieldLoader(member.name, protocolName, fieldTypeParser, skipRead, isAsImpl, StringUtil.nullize(optionalAnnotation?.default)))
}
if (isAsImpl) {
return null
}
val effectiveFieldName = if (fieldTypeParser == VOID_PARSER) null else member.name
return object : MethodHandler {
override fun writeMethodImplementationJava(scope: ClassScope, method: Method, out: TextOutput) {
out.append("override ").append(if (isProperty) "val" else "fun")
out.append(" ").appendEscapedName(method.name)
if (isProperty) {
out.newLine()
out.indentIn()
out.append("get()")
// todo append type name
}
else {
out.append("()")
}
if (effectiveFieldName == null) {
out.openBlock()
out.closeBlock()
}
else {
out.append(" = ").append(FIELD_PREFIX).append(effectiveFieldName)
if (isNotNull) {
out.append("!!")
}
if (isProperty) {
out.indentOut()
}
}
}
}
}
private fun processManualSubtypeMethod(member: KCallable<*>, m: Method, jsonSubtypeCaseAnn: JsonSubtypeCasting): MethodHandler {
val fieldTypeParser = reader.getFieldTypeParser(member, m.genericReturnType, !jsonSubtypeCaseAnn.reinterpret, null)
val fieldInfo = allocateVolatileField(fieldTypeParser, true)
val handler = LazyCachedMethodHandler(fieldTypeParser, fieldInfo)
val parserAsObjectValueParser = fieldTypeParser.asJsonTypeParser()
if (parserAsObjectValueParser != null && parserAsObjectValueParser.isSubtyping()) {
reader.subtypeCasters.add(object : SubtypeCaster(parserAsObjectValueParser.type) {
override fun writeJava(out: TextOutput) {
out.append(m.name).append("()")
}
})
}
return handler
}
private fun allocateVolatileField(fieldTypeParser: ValueReader, internalType: Boolean): VolatileFieldBinding {
val position = volatileFields.size
val fieldTypeInfo: (scope: FileScope, out: TextOutput)->Unit
if (internalType) {
fieldTypeInfo = {scope, out -> fieldTypeParser.appendInternalValueTypeName(scope, out)}
}
else {
fieldTypeInfo = {scope, out -> fieldTypeParser.appendFinishedValueTypeName(out)}
}
val binding = VolatileFieldBinding(position, fieldTypeInfo)
volatileFields.add(binding)
return binding
}
}
internal inline fun <reified T : Annotation> KCallable<*>.annotation(): T? = annotations.firstOrNull() { it is T } as? T ?: (this as? KFunction<*>)?.javaMethod?.getAnnotation<T>(T::class.java)
/**
* An internal facility for navigating from object of base type to object of subtype. Used only
* when user wants to parse JSON object as subtype.
*/
internal abstract class SubtypeCaster(private val subtypeRef: TypeRef<*>) {
abstract fun writeJava(out: TextOutput)
fun getSubtypeHandler() = subtypeRef.type!!
} | apache-2.0 | c3fef522b99ea5de880fcf30343a6f9a | 35.634518 | 192 | 0.690965 | 4.719424 | false | false | false | false |
Ribesg/anko | dsl/src/org/jetbrains/android/anko/annotations/annotationProviders.kt | 1 | 2928 | /*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.android.anko.annotations
import java.io.File
import java.util.zip.ZipFile
enum class ExternalAnnotation {
NotNull,
GenerateLayout,
GenerateView
}
interface AnnotationProvider {
fun getExternalAnnotations(packageName: String): Map<String, Set<ExternalAnnotation>>
}
class ZipFileAnnotationProvider(val zipFile: File) : AnnotationProvider {
private val archive: ZipFile by lazy { ZipFile(zipFile) }
override fun getExternalAnnotations(packageName: String): Map<String, Set<ExternalAnnotation>> {
val entryName = packageName.replace('.', '/') + "/annotations.xml"
val entry = archive.getEntry(entryName) ?: return mapOf()
return archive.getInputStream(entry).reader().use {
parseAnnotations(parseXml(it.readText()))
}
}
}
class DirectoryAnnotationProvider(val directory: File) : AnnotationProvider {
override fun getExternalAnnotations(packageName: String): Map<String, Set<ExternalAnnotation>> {
val annotationFile = File(directory, packageName.replace('.', '/') + "/annotations.xml")
if (!annotationFile.exists()) return mapOf()
return parseAnnotations(parseXml(annotationFile.readText()))
}
}
class CachingAnnotationProvider(val underlyingProvider: AnnotationProvider) : AnnotationProvider {
private val cache = hashMapOf<String, Map<String, Set<ExternalAnnotation>>>()
override fun getExternalAnnotations(packageName: String) = cache.getOrPut(packageName) {
underlyingProvider.getExternalAnnotations(packageName)
}
}
class CompoundAnnotationProvider(vararg providers: AnnotationProvider) : AnnotationProvider {
private val providers = providers
override fun getExternalAnnotations(packageName: String): Map<String, Set<ExternalAnnotation>> {
val providerAnnotations = providers.map { it.getExternalAnnotations(packageName) }
val map = hashMapOf<String, Set<ExternalAnnotation>>()
for (providerAnnotationMap in providerAnnotations) {
for ((key, value) in providerAnnotationMap) {
val existingAnnotations = map[key]
if (existingAnnotations == null) map.put(key, value)
else map.put(key, (value + existingAnnotations).toSet())
}
}
return map
}
} | apache-2.0 | ebda11f525be88ce164d1373de0de375 | 34.289157 | 100 | 0.714481 | 4.823723 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/status/DestroyStatusDialogFragment.kt | 1 | 1963 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[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 de.vanita5.twittnuker.fragment.status
import android.os.Bundle
import android.support.v4.app.FragmentManager
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_STATUS
import de.vanita5.twittnuker.model.ParcelableStatus
class DestroyStatusDialogFragment : AbsSimpleStatusOperationDialogFragment() {
override val title: String?
get() = getString(R.string.destroy_status)
override val message: String
get() = getString(R.string.destroy_status_confirm_message)
override fun onPerformAction(status: ParcelableStatus) {
twitterWrapper.destroyStatusAsync(status.account_key, status.id)
}
companion object {
val FRAGMENT_TAG = "destroy_status"
fun show(fm: FragmentManager, status: ParcelableStatus): DestroyStatusDialogFragment {
val args = Bundle()
args.putParcelable(EXTRA_STATUS, status)
val f = DestroyStatusDialogFragment()
f.arguments = args
f.show(fm, FRAGMENT_TAG)
return f
}
}
} | gpl-3.0 | ed31a769ef4eb2596f23a881bcb5d3a5 | 34.709091 | 94 | 0.720835 | 4.295405 | false | false | false | false |
stripe/stripe-android | payments-model/src/main/java/com/stripe/android/model/parsers/CardJsonParser.kt | 1 | 4184 | package com.stripe.android.model.parsers
import androidx.annotation.RestrictTo
import com.stripe.android.core.model.StripeJsonUtils
import com.stripe.android.core.model.parsers.ModelJsonParser
import com.stripe.android.model.Card
import com.stripe.android.model.CardFunding
import com.stripe.android.model.TokenizationMethod
import org.json.JSONObject
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class CardJsonParser : ModelJsonParser<Card> {
override fun parse(json: JSONObject): Card? {
if (VALUE_CARD != json.optString(FIELD_OBJECT)) {
return null
}
// It's okay for the month to be missing, but not for it to be outside 1-12.
// We treat an invalid month the same way we would an invalid brand, by reading it as
// null.
val expMonth = (StripeJsonUtils.optInteger(json, FIELD_EXP_MONTH) ?: -1)
.takeUnless { it < 1 || it > 12 }
val expYear = (StripeJsonUtils.optInteger(json, FIELD_EXP_YEAR) ?: -1)
.takeUnless { it < 0 }
// Note that we'll never get the CVC or card number in JSON, so those values are null
return Card(
expMonth = expMonth,
expYear = expYear,
addressCity = StripeJsonUtils.optString(json, FIELD_ADDRESS_CITY),
addressLine1 = StripeJsonUtils.optString(json, FIELD_ADDRESS_LINE1),
addressLine1Check = StripeJsonUtils.optString(json, FIELD_ADDRESS_LINE1_CHECK),
addressLine2 = StripeJsonUtils.optString(json, FIELD_ADDRESS_LINE2),
addressCountry = StripeJsonUtils.optString(json, FIELD_ADDRESS_COUNTRY),
addressState = StripeJsonUtils.optString(json, FIELD_ADDRESS_STATE),
addressZip = StripeJsonUtils.optString(json, FIELD_ADDRESS_ZIP),
addressZipCheck = StripeJsonUtils.optString(json, FIELD_ADDRESS_ZIP_CHECK),
brand = Card.getCardBrand(StripeJsonUtils.optString(json, FIELD_BRAND)),
country = StripeJsonUtils.optCountryCode(json, FIELD_COUNTRY),
customerId = StripeJsonUtils.optString(json, FIELD_CUSTOMER),
currency = StripeJsonUtils.optCurrency(json, FIELD_CURRENCY),
cvcCheck = StripeJsonUtils.optString(json, FIELD_CVC_CHECK),
funding = CardFunding.fromCode(StripeJsonUtils.optString(json, FIELD_FUNDING)),
fingerprint = StripeJsonUtils.optString(json, FIELD_FINGERPRINT),
id = StripeJsonUtils.optString(json, FIELD_ID),
last4 = StripeJsonUtils.optString(json, FIELD_LAST4),
name = StripeJsonUtils.optString(json, FIELD_NAME),
tokenizationMethod = TokenizationMethod.fromCode(
StripeJsonUtils.optString(json, FIELD_TOKENIZATION_METHOD)
)
)
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
companion object {
internal const val VALUE_CARD = "card"
private const val FIELD_OBJECT = "object"
private const val FIELD_ADDRESS_CITY = "address_city"
private const val FIELD_ADDRESS_COUNTRY = "address_country"
private const val FIELD_ADDRESS_LINE1 = "address_line1"
private const val FIELD_ADDRESS_LINE1_CHECK = "address_line1_check"
private const val FIELD_ADDRESS_LINE2 = "address_line2"
private const val FIELD_ADDRESS_STATE = "address_state"
private const val FIELD_ADDRESS_ZIP = "address_zip"
private const val FIELD_ADDRESS_ZIP_CHECK = "address_zip_check"
private const val FIELD_BRAND = "brand"
private const val FIELD_COUNTRY = "country"
private const val FIELD_CURRENCY = "currency"
private const val FIELD_CUSTOMER = "customer"
private const val FIELD_CVC_CHECK = "cvc_check"
private const val FIELD_EXP_MONTH = "exp_month"
private const val FIELD_EXP_YEAR = "exp_year"
private const val FIELD_FINGERPRINT = "fingerprint"
private const val FIELD_FUNDING = "funding"
private const val FIELD_NAME = "name"
private const val FIELD_LAST4 = "last4"
private const val FIELD_ID = "id"
private const val FIELD_TOKENIZATION_METHOD = "tokenization_method"
}
}
| mit | 7383aa0bd13703afcf8dbfef9ad5a766 | 50.02439 | 93 | 0.67543 | 4.441614 | false | false | false | false |
mvarnagiris/expensius | app-core/src/test/kotlin/com/mvcoding/expensius/feature/reports/trends/TrendsReportSourceTest.kt | 1 | 5834 | /*
* Copyright (C) 2017 Mantas Varnagiris.
*
* 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.
*/
package com.mvcoding.expensius.feature.reports.trends
import com.mvcoding.expensius.data.DataSource
import com.mvcoding.expensius.data.ParameterDataSource
import com.mvcoding.expensius.model.*
import com.mvcoding.expensius.model.TransactionType.EXPENSE
import com.mvcoding.expensius.model.TransactionType.INCOME
import com.mvcoding.expensius.model.extensions.*
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import org.junit.Before
import org.junit.Test
import rx.Observable.just
import rx.observers.TestSubscriber
class TrendsReportSourceTest {
val transactionsSource = mock<DataSource<List<Transaction>>>()
val otherTransactionsSource = mock<DataSource<List<Transaction>>>()
val localFilterSource = mock<DataSource<LocalFilter>>()
val reportSettingsSource = mock<DataSource<ReportSettings>>()
val moneyConversionSource = mock<ParameterDataSource<MoneyConversion, Money>>()
val trendsSource = TrendsReportSource(transactionsSource, otherTransactionsSource, localFilterSource, reportSettingsSource, moneyConversionSource)
val subscriber = TestSubscriber<TrendsReport>()
@Before
fun setUp() {
whenever(transactionsSource.data()).thenReturn(just(someTransactions()))
whenever(otherTransactionsSource.data()).thenReturn(just(someTransactions()))
whenever(localFilterSource.data()).thenReturn(just(aLocalFilter()))
whenever(reportSettingsSource.data()).thenReturn(just(aReportSettings()))
whenever(moneyConversionSource.data(any())).thenAnswer { it.getArgument<MoneyConversion>(0).let { just(it.money) } }
}
@Test
fun `creates Trends from two transactions sources filtering them and then grouping and converting money to required currency`() {
val reportSettings = aReportSettings()
val reportPeriod = reportSettings.reportPeriod
val reportGroup = reportSettings.reportGroup
val currency = reportSettings.currency
val otherCurrency = aCurrency(excludeCode = currency.code)
val exchangeRate = anAmount()
val localFilter = aLocalFilter().withNoFilters().withTransactionType(EXPENSE)
val transactionFilteredOut = aTransaction().withTransactionType(INCOME)
val transactionWithRequiredCurrency = aTransaction().withTransactionType(EXPENSE).withMoney(aMoney().withCurrency(currency))
val transactionWithOtherCurrency = aTransaction()
.withTransactionType(EXPENSE)
.withMoney(aMoney().withCurrency(otherCurrency))
.withTimestamp(transactionWithRequiredCurrency.timestamp)
val totalAmount = transactionWithRequiredCurrency.money.amount + (transactionWithOtherCurrency.money.amount * exchangeRate)
val allTransactions = listOf(transactionFilteredOut, transactionWithRequiredCurrency, transactionWithOtherCurrency)
val filteredTransactionsWithCorrectCurrency = listOf(
transactionWithRequiredCurrency,
transactionWithOtherCurrency.withAmount(transactionWithOtherCurrency.money.amount * exchangeRate))
val otherTransactionFilteredOut = aTransaction().withTransactionType(INCOME)
val otherTransactionWithRequiredCurrency = aTransaction().withTransactionType(EXPENSE).withMoney(aMoney().withCurrency(currency))
val otherTransactionWithOtherCurrency = aTransaction()
.withTransactionType(EXPENSE)
.withMoney(aMoney().withCurrency(otherCurrency))
.withTimestamp(otherTransactionWithRequiredCurrency.timestamp)
val otherTotalAmount = otherTransactionWithRequiredCurrency.money.amount + (otherTransactionWithOtherCurrency.money.amount * exchangeRate)
val otherAllTransactions = listOf(otherTransactionFilteredOut, otherTransactionWithRequiredCurrency, otherTransactionWithOtherCurrency)
val otherFilteredTransactionsWithCorrectCurrency = listOf(
otherTransactionWithRequiredCurrency,
otherTransactionWithOtherCurrency.withAmount(otherTransactionWithOtherCurrency.money.amount * exchangeRate))
val expectedTrends = TrendsReport(
reportPeriod.groupToFillWholePeriod(filteredTransactionsWithCorrectCurrency, reportGroup, currency),
Money(totalAmount, currency),
reportPeriod.groupToFillWholePeriod(otherFilteredTransactionsWithCorrectCurrency, reportGroup, currency),
Money(otherTotalAmount, currency))
whenever(transactionsSource.data()).thenReturn(just(allTransactions))
whenever(otherTransactionsSource.data()).thenReturn(just(otherAllTransactions))
whenever(localFilterSource.data()).thenReturn(just(localFilter))
whenever(reportSettingsSource.data()).thenReturn(just(reportSettings))
whenever(moneyConversionSource.data(any()))
.thenAnswer {
it.getArgument<MoneyConversion>(0).let {
just(if (it.money.currency == it.toCurrency) it.money else Money(it.money.amount * exchangeRate, it.toCurrency))
}
}
trendsSource.data().subscribe(subscriber)
subscriber.assertValues(expectedTrends)
}
} | gpl-3.0 | 8645917056d492954ff47ea011bcd157 | 54.571429 | 150 | 0.748714 | 5.467666 | false | false | false | false |
kiruto/debug-bottle | components/src/main/kotlin/com/exyui/android/debugbottle/components/spviewer/SPViewerActivity.kt | 1 | 5572 | //package com.exyui.android.debugbottle.components.spviewer
//
//import android.content.SharedPreferences
//import android.support.v7.app.AppCompatActivity
//import android.os.Bundle
//import android.view.LayoutInflater
//import android.view.View
//import android.view.ViewGroup
//import android.widget.BaseExpandableListAdapter
//import android.widget.ExpandableListView
//import android.widget.SimpleExpandableListAdapter
//import android.widget.TextView
//import com.exyui.android.debugbottle.components.DialogsCollection
//import com.exyui.android.debugbottle.components.R
//import com.exyui.android.debugbottle.components.DTBaseActivity
//import java.util.zip.Inflater
//
//@Deprecated("")
//internal class SPViewerActivity : DTBaseActivity(), DialogsCollection.SPDialogAction {
//
// private val listView by lazy { findViewById(R.id.list_view) as ExpandableListView }
// private var adapter: ListAdapter? = null
// private val groupList by lazy { mutableMapOf<String, SharedPreferences>() }
//
// override val actionbarTitle: String by lazy { getString(R.string.__dt_sp_title) }
//
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
// setContentView(R.layout.__activity_spviewer)
// initSP()
// }
//
// private fun initSP() {
// val viewer = SPViewer(applicationContext)
// groupList.clear()
// groupList.putAll(viewer.getAll())
// adapter = ListAdapter()
// listView.setAdapter(adapter)
// }
//
// override fun updateSPViews() {
// initSP()
// }
//
// inner class ListAdapter: BaseExpandableListAdapter() {
//
// private val clickListener = View.OnClickListener { v ->
// val p = v.tag as ChildHolder
// if (null == p.position) return@OnClickListener
// val sp = getGroup(p.position!!.first)?.second?: return@OnClickListener
// val key = getChild(p.position!!.first, p.position!!.second)?.first?: return@OnClickListener
// val dialog = DialogsCollection.EditSPDialogFragment.newInstance(key, sp)
// dialog.show(fragmentManager, "dialog")
// }
//
// override fun isChildSelectable(groupPosition: Int, childPosition: Int) = true
//
// override fun getChildView(groupPosition: Int, childPosition: Int, isLastChild: Boolean, convertView: View?, parent: ViewGroup?): View? {
// var v = convertView
// val holder: ChildHolder
// if (null == v) {
// v = LayoutInflater.from(this@SPViewerActivity).inflate(R.layout.__child_sp_values, parent, false)
// holder = ChildHolder()
// holder.titleView = v.findViewById(R.id.__child_title) as TextView
// holder.contentView = v.findViewById(R.id.__child_content) as TextView
// v.tag = holder
// } else {
// holder = v.tag as ChildHolder
// }
//
// val content = getChild(groupPosition, childPosition)
// holder.titleView?.text = content?.first
// holder.contentView?.text = content?.second.toString()
// holder.position = Pair(groupPosition, childPosition)
//
// v?.setOnClickListener(clickListener)
//
// return v
// }
//
// override fun getChildId(groupPosition: Int, childPosition: Int): Long = groupPosition * 100L + childPosition
//
// override fun getGroupView(groupPosition: Int, isExpanded: Boolean, convertView: View?, parent: ViewGroup?): View? {
// var v = convertView
// val holder: GroupHolder
// if (null == v) {
// v = LayoutInflater.from(this@SPViewerActivity).inflate(R.layout.__group_sp_files, parent, false)
// holder = GroupHolder()
// holder.titleView = v.findViewById(R.id.group_title) as TextView
// v.tag = holder
// } else {
// holder = v.tag as GroupHolder
// }
//
// val content = getGroup(groupPosition)
// holder.titleView?.text = content?.first
// return v
// }
//
// override fun getGroupCount(): Int = groupList.size
//
// override fun getGroupId(groupPosition: Int): Long = groupPosition.toLong()
//
// override fun getChild(groupPosition: Int, childPosition: Int): Pair<String, Any?>? {
// val group = getGroup(groupPosition)
// var i = 0
// val sp = group?.second?: return null
// for ((k, v) in sp.all) {
// if (i == childPosition)
// return Pair(k, v)
// i ++
// }
// return null
// }
//
// override fun hasStableIds(): Boolean = false
//
// override fun getChildrenCount(groupPosition: Int): Int {
// val group = getGroup(groupPosition)
// return group?.second?.all?.size?: 0
// }
//
// override fun getGroup(groupPosition: Int): Pair<String, SharedPreferences>? {
// var i = 0
// for ((k, v) in groupList) {
// if (i == groupPosition)
// return Pair(k, v)
// i ++
// }
// return null
// }
// }
//
// inner class GroupHolder {
// var titleView: TextView? = null
// }
//
// inner class ChildHolder {
// var titleView: TextView? = null
// var contentView: TextView? = null
// var position: Pair<Int, Int>? = null
// }
//}
| apache-2.0 | fa0fc6161438bddb152fd13748351d62 | 37.965035 | 146 | 0.593503 | 4.208459 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/tasks/TaskRecyclerViewFragment.kt | 1 | 24162 | package com.habitrpg.android.habitica.ui.fragments.tasks
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.text.format.DateUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.NO_POSITION
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.ApiClient
import com.habitrpg.android.habitica.data.InventoryRepository
import com.habitrpg.android.habitica.data.TaskRepository
import com.habitrpg.android.habitica.data.UserRepository
import com.habitrpg.android.habitica.databinding.FragmentRefreshRecyclerviewBinding
import com.habitrpg.android.habitica.extensions.setScaledPadding
import com.habitrpg.android.habitica.extensions.subscribeWithErrorHandler
import com.habitrpg.android.habitica.helpers.AmplitudeManager
import com.habitrpg.android.habitica.helpers.AppConfigManager
import com.habitrpg.android.habitica.helpers.HapticFeedbackManager
import com.habitrpg.android.habitica.helpers.MainNavigationController
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.helpers.SoundManager
import com.habitrpg.android.habitica.helpers.TaskFilterHelper
import com.habitrpg.android.habitica.models.responses.TaskDirection
import com.habitrpg.android.habitica.models.responses.TaskScoringResult
import com.habitrpg.android.habitica.models.tasks.Task
import com.habitrpg.android.habitica.models.tasks.TaskType
import com.habitrpg.android.habitica.ui.activities.MainActivity
import com.habitrpg.android.habitica.ui.activities.TaskFormActivity
import com.habitrpg.android.habitica.ui.adapter.BaseRecyclerViewAdapter
import com.habitrpg.android.habitica.ui.adapter.tasks.DailiesRecyclerViewHolder
import com.habitrpg.android.habitica.ui.adapter.tasks.HabitsRecyclerViewAdapter
import com.habitrpg.android.habitica.ui.adapter.tasks.RewardsRecyclerViewAdapter
import com.habitrpg.android.habitica.ui.adapter.tasks.TaskRecyclerViewAdapter
import com.habitrpg.android.habitica.ui.adapter.tasks.TodosRecyclerViewAdapter
import com.habitrpg.android.habitica.ui.fragments.BaseFragment
import com.habitrpg.android.habitica.ui.helpers.EmptyItem
import com.habitrpg.android.habitica.ui.helpers.SafeDefaultItemAnimator
import com.habitrpg.android.habitica.ui.viewHolders.tasks.BaseTaskViewHolder
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.CompositeDisposable
import java.util.Date
import java.util.concurrent.TimeUnit
import javax.inject.Inject
open class TaskRecyclerViewFragment : BaseFragment<FragmentRefreshRecyclerviewBinding>(), androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener {
internal var canEditTasks: Boolean = true
internal var canScoreTaks: Boolean = true
override var binding: FragmentRefreshRecyclerviewBinding? = null
override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentRefreshRecyclerviewBinding {
return FragmentRefreshRecyclerviewBinding.inflate(inflater, container, false)
}
private var recyclerSubscription: CompositeDisposable = CompositeDisposable()
var recyclerAdapter: TaskRecyclerViewAdapter? = null
var itemAnimator = SafeDefaultItemAnimator()
@Inject
lateinit var apiClient: ApiClient
@Inject
lateinit var taskFilterHelper: TaskFilterHelper
@Inject
lateinit var userRepository: UserRepository
@Inject
lateinit var inventoryRepository: InventoryRepository
@Inject
lateinit var taskRepository: TaskRepository
@Inject
lateinit var soundManager: SoundManager
@Inject
lateinit var configManager: AppConfigManager
@Inject
lateinit var sharedPreferences: SharedPreferences
internal var layoutManager: RecyclerView.LayoutManager? = null
internal var taskType: TaskType = TaskType.HABIT
private var itemTouchCallback: ItemTouchHelper.Callback? = null
var refreshAction: ((() -> Unit) -> Unit)? = null
internal val className: TaskType
get() = this.taskType
private fun setInnerAdapter() {
if (binding?.recyclerView?.adapter != null && binding?.recyclerView?.adapter == recyclerAdapter && !recyclerSubscription.isDisposed) {
return
}
if (!recyclerSubscription.isDisposed) {
recyclerSubscription.dispose()
}
recyclerSubscription = CompositeDisposable()
val adapter: BaseRecyclerViewAdapter<*, *>? = when (this.taskType) {
TaskType.HABIT -> HabitsRecyclerViewAdapter(R.layout.habit_item_card, taskFilterHelper)
TaskType.DAILY -> DailiesRecyclerViewHolder(R.layout.daily_item_card, taskFilterHelper)
TaskType.TODO -> TodosRecyclerViewAdapter(R.layout.todo_item_card, taskFilterHelper)
TaskType.REWARD -> RewardsRecyclerViewAdapter(null, R.layout.reward_item_card)
else -> null
}
recyclerAdapter = adapter as? TaskRecyclerViewAdapter
recyclerAdapter?.canScoreTasks = canScoreTaks
binding?.recyclerView?.adapter = adapter
context?.let { recyclerAdapter?.taskDisplayMode = configManager.taskDisplayMode(it) }
recyclerAdapter?.errorButtonEvents?.subscribe(
{
taskRepository.syncErroredTasks().subscribe({}, RxErrorHandler.handleEmptyError())
},
RxErrorHandler.handleEmptyError()
)?.let { recyclerSubscription.add(it) }
recyclerAdapter?.taskOpenEvents?.subscribeWithErrorHandler {
openTaskForm(it.first, it.second)
}?.let { recyclerSubscription.add(it) }
recyclerAdapter?.taskScoreEvents
?.doOnNext { playSound(it.second) }
?.subscribeWithErrorHandler { scoreTask(it.first, it.second) }?.let { recyclerSubscription.add(it) }
recyclerAdapter?.checklistItemScoreEvents
?.flatMap {
taskRepository.scoreChecklistItem(it.first.id ?: "", it.second.id ?: "")
}?.subscribeWithErrorHandler {}?.let { recyclerSubscription.add(it) }
recyclerAdapter?.brokenTaskEvents?.subscribeWithErrorHandler { showBrokenChallengeDialog(it) }?.let { recyclerSubscription.add(it) }
recyclerAdapter?.adventureGuideOpenEvents?.subscribeWithErrorHandler { MainNavigationController.navigate(R.id.adventureGuideActivity) }?.let { recyclerSubscription.add(it) }
recyclerSubscription.add(
taskRepository.getTasks(this.taskType).subscribe(
{
this.recyclerAdapter?.updateUnfilteredData(it)
},
RxErrorHandler.handleEmptyError()
)
)
}
private fun handleTaskResult(result: TaskScoringResult, value: Int) {
if (taskType == TaskType.REWARD) {
(activity as? MainActivity)?.let { activity ->
HabiticaSnackbar.showSnackbar(
activity.snackbarContainer, null, getString(R.string.notification_purchase_reward),
BitmapDrawable(resources, HabiticaIconsHelper.imageOfGold()),
ContextCompat.getColor(activity, R.color.yellow_10),
"-$value",
HabiticaSnackbar.SnackbarDisplayType.DROP
)
}
} else {
(activity as? MainActivity)?.displayTaskScoringResponse(result)
}
}
private fun playSound(direction: TaskDirection) {
HapticFeedbackManager.tap(requireView())
val soundName = when (taskType) {
TaskType.HABIT -> if (direction == TaskDirection.UP) SoundManager.SoundPlusHabit else SoundManager.SoundMinusHabit
TaskType.DAILY -> SoundManager.SoundDaily
TaskType.TODO -> SoundManager.SoundTodo
TaskType.REWARD -> SoundManager.SoundReward
else -> null
}
soundName?.let { soundManager.loadAndPlayAudio(it) }
}
private fun allowReordering() {
val itemTouchHelper = itemTouchCallback?.let { ItemTouchHelper(it) }
itemTouchHelper?.attachToRecyclerView(binding?.recyclerView)
}
protected open fun getLayoutManager(context: Context?): androidx.recyclerview.widget.LinearLayoutManager {
return androidx.recyclerview.widget.LinearLayoutManager(context)
}
override fun onDestroyView() {
super.onDestroyView()
itemTouchCallback = null
}
override fun onDestroy() {
userRepository.close()
inventoryRepository.close()
super.onDestroy()
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
savedInstanceState?.let { this.taskType = TaskType.from(savedInstanceState.getString(CLASS_TYPE_KEY, "")) ?: TaskType.HABIT }
this.setInnerAdapter()
recyclerAdapter?.filter()
itemTouchCallback = object : ItemTouchHelper.Callback() {
override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
super.onSelectedChanged(viewHolder, actionState)
if (viewHolder == null || viewHolder.absoluteAdapterPosition == NO_POSITION) return
val taskViewHolder = viewHolder as? BaseTaskViewHolder
if (taskViewHolder != null) {
taskViewHolder.movingFromPosition = viewHolder.absoluteAdapterPosition
}
binding?.refreshLayout?.isEnabled = false
}
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
recyclerAdapter?.notifyItemMoved(viewHolder.absoluteAdapterPosition, target.absoluteAdapterPosition)
return true
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { /* no-on */ }
// defines the enabled move directions in each state (idle, swiping, dragging).
override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
return if (recyclerAdapter?.getItemViewType(viewHolder.absoluteAdapterPosition) ?: 0 != 0) {
makeFlag(ItemTouchHelper.ACTION_STATE_IDLE, 0)
} else {
makeFlag(
ItemTouchHelper.ACTION_STATE_DRAG,
ItemTouchHelper.DOWN or ItemTouchHelper.UP
)
}
}
override fun isItemViewSwipeEnabled(): Boolean = false
override fun isLongPressDragEnabled(): Boolean = true
override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
super.clearView(recyclerView, viewHolder)
binding?.refreshLayout?.isEnabled = true
if (viewHolder.absoluteAdapterPosition == NO_POSITION) return
val taskViewHolder = viewHolder as? BaseTaskViewHolder
val validTaskId = taskViewHolder?.task?.takeIf { it.isValid }?.id
if (viewHolder.absoluteAdapterPosition != taskViewHolder?.movingFromPosition) {
taskViewHolder?.movingFromPosition = null
updateTaskInRepository(validTaskId, viewHolder)
}
}
private fun updateTaskInRepository(validTaskId: String?, viewHolder: RecyclerView.ViewHolder) {
if (validTaskId != null) {
var newPosition = viewHolder.absoluteAdapterPosition
if (taskFilterHelper.howMany(taskType) > 0) {
newPosition = if ((newPosition + 1) == recyclerAdapter?.data?.size) {
recyclerAdapter?.data?.get(newPosition - 1)?.position ?: newPosition
} else {
(recyclerAdapter?.data?.get(newPosition + 1)?.position ?: newPosition) - 1
}
}
compositeSubscription.add(
taskRepository.updateTaskPosition(
taskType, validTaskId, newPosition
)
.delay(1, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
},
RxErrorHandler.handleEmptyError()
)
)
}
}
}
binding?.recyclerView?.setScaledPadding(context, 0, 0, 0, 108)
layoutManager = getLayoutManager(context)
binding?.recyclerView?.layoutManager = layoutManager
allowReordering()
binding?.recyclerView?.itemAnimator = itemAnimator
binding?.refreshLayout?.setOnRefreshListener(this)
setEmptyLabels()
binding?.recyclerView?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
binding?.refreshLayout?.isEnabled = (activity as? MainActivity)?.isAppBarExpanded ?: false
}
}
})
compositeSubscription.add(
userRepository.getUser()
.doOnNext { recyclerAdapter?.showAdventureGuide = !it.hasCompletedOnboarding }
.takeUntil { it.hasCompletedOnboarding }
.subscribe({ recyclerAdapter?.user = it }, RxErrorHandler.handleEmptyError())
)
}
protected fun showBrokenChallengeDialog(task: Task) {
context?.let {
if (!task.isValid) {
return
}
taskRepository.getTasksForChallenge(task.challengeID).firstElement().subscribe(
{ tasks ->
val taskCount = tasks.size
val dialog = HabiticaAlertDialog(it)
dialog.setTitle(R.string.broken_challenge)
dialog.setMessage(it.getString(R.string.broken_challenge_description, taskCount))
dialog.addButton(it.getString(R.string.keep_x_tasks, taskCount), true) { _, _ ->
if (!task.isValid) return@addButton
taskRepository.unlinkAllTasks(task.challengeID, "keep-all")
.flatMap { userRepository.retrieveUser(true, forced = true) }
.subscribe({}, RxErrorHandler.handleEmptyError())
}
dialog.addButton(
it.getString(R.string.delete_x_tasks, taskCount),
isPrimary = false,
isDestructive = true
) { _, _ ->
if (!task.isValid) return@addButton
taskRepository.unlinkAllTasks(task.challengeID, "remove-all")
.flatMap { userRepository.retrieveUser(true, forced = true) }
.subscribe({}, RxErrorHandler.handleEmptyError())
}
dialog.setExtraCloseButtonVisibility(View.VISIBLE)
dialog.show()
},
RxErrorHandler.handleEmptyError()
)
}
}
private fun setEmptyLabels() {
binding?.recyclerView?.emptyItem = if (taskFilterHelper.howMany(taskType) > 0) {
when (this.taskType) {
TaskType.HABIT -> {
EmptyItem(
getString(R.string.empty_title_habits_filtered),
getString(R.string.empty_description_habits_filtered),
R.drawable.icon_habits
)
}
TaskType.DAILY -> {
EmptyItem(
getString(R.string.empty_title_dailies_filtered),
getString(R.string.empty_description_dailies_filtered),
R.drawable.icon_dailies
)
}
TaskType.TODO -> {
EmptyItem(
getString(R.string.empty_title_todos_filtered),
getString(R.string.empty_description_todos_filtered),
R.drawable.icon_todos
)
}
TaskType.REWARD -> {
EmptyItem(
getString(R.string.empty_title_rewards_filtered),
null,
R.drawable.icon_rewards
)
}
else -> EmptyItem("")
}
} else {
when (this.taskType) {
TaskType.HABIT -> {
EmptyItem(
getString(R.string.empty_title_habits),
getString(R.string.empty_description_habits),
R.drawable.icon_habits
)
}
TaskType.DAILY -> {
EmptyItem(
getString(R.string.empty_title_dailies),
getString(R.string.empty_description_dailies),
R.drawable.icon_dailies
)
}
TaskType.TODO -> {
EmptyItem(
getString(R.string.empty_title_todos),
getString(R.string.empty_description_todos),
R.drawable.icon_todos
)
}
TaskType.REWARD -> {
EmptyItem(
getString(R.string.empty_title_rewards),
null,
R.drawable.icon_rewards
)
}
else -> EmptyItem("")
}
}
}
private fun scoreTask(task: Task, direction: TaskDirection) {
compositeSubscription.add(
taskRepository.taskChecked(null, task, direction == TaskDirection.UP, false) { result ->
handleTaskResult(result, task.value.toInt())
if (!DateUtils.isToday(sharedPreferences.getLong("last_task_reporting", 0))) {
AmplitudeManager.sendEvent(
"task scored",
AmplitudeManager.EVENT_CATEGORY_BEHAVIOUR,
AmplitudeManager.EVENT_HITTYPE_EVENT
)
sharedPreferences.edit {
putLong("last_task_reporting", Date().time)
}
}
}.subscribeWithErrorHandler {}
)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(CLASS_TYPE_KEY, this.taskType.value)
}
override val displayedClassName: String?
get() = this.taskType.value + super.displayedClassName
override fun onRefresh() {
binding?.refreshLayout?.isRefreshing = true
refreshAction?.invoke {
binding?.refreshLayout?.isRefreshing = false
}
}
override fun onStart() {
super.onStart()
if (taskFilterHelper.getActiveFilter(taskType) == null) {
when (taskType) {
TaskType.TODO -> taskFilterHelper.setActiveFilter(TaskType.TODO, Task.FILTER_ACTIVE)
TaskType.DAILY -> {
val user = (activity as? MainActivity)?.viewModel?.user?.value
if (user?.isValid == true && user.preferences?.dailyDueDefaultView == true) {
taskFilterHelper.setActiveFilter(TaskType.DAILY, Task.FILTER_ACTIVE)
}
}
}
}
}
override fun onResume() {
super.onResume()
context?.let { recyclerAdapter?.taskDisplayMode = configManager.taskDisplayMode(it) }
setInnerAdapter()
recyclerAdapter?.filter()
}
fun setActiveFilter(activeFilter: String) {
taskFilterHelper.setActiveFilter(taskType, activeFilter)
recyclerAdapter?.filter()
setEmptyLabels()
if (activeFilter == Task.FILTER_COMPLETED) {
compositeSubscription.add(taskRepository.retrieveCompletedTodos().subscribe({}, RxErrorHandler.handleEmptyError()))
}
}
private fun openTaskForm(task: Task, containerView: View) {
if (Date().time - (TasksFragment.lastTaskFormOpen?.time ?: 0) < 2000 || !task.isValid || !canEditTasks) {
return
}
val bundle = Bundle()
bundle.putString(TaskFormActivity.TASK_TYPE_KEY, task.type?.value)
bundle.putString(TaskFormActivity.TASK_ID_KEY, task.id)
bundle.putDouble(TaskFormActivity.TASK_VALUE_KEY, task.value)
val intent = Intent(activity, TaskFormActivity::class.java)
intent.putExtras(bundle)
TasksFragment.lastTaskFormOpen = Date()
if (isAdded) {
startActivity(intent)
}
}
companion object {
private const val CLASS_TYPE_KEY = "CLASS_TYPE_KEY"
fun newInstance(context: Context?, classType: TaskType): TaskRecyclerViewFragment {
val fragment = TaskRecyclerViewFragment()
fragment.taskType = classType
var tutorialTexts: List<String>? = null
if (context != null) {
when (fragment.taskType) {
TaskType.HABIT -> {
fragment.tutorialStepIdentifier = "habits"
tutorialTexts = listOf(context.getString(R.string.tutorial_overview), context.getString(R.string.tutorial_habits_1), context.getString(R.string.tutorial_habits_2), context.getString(R.string.tutorial_habits_3), context.getString(R.string.tutorial_habits_4))
}
TaskType.DAILY -> {
fragment.tutorialStepIdentifier = "dailies"
tutorialTexts = listOf(context.getString(R.string.tutorial_dailies_1), context.getString(R.string.tutorial_dailies_2))
}
TaskType.TODO -> {
fragment.tutorialStepIdentifier = "todos"
tutorialTexts = listOf(context.getString(R.string.tutorial_todos_1), context.getString(R.string.tutorial_todos_2))
}
}
}
if (tutorialTexts != null) {
fragment.tutorialTexts = ArrayList(tutorialTexts)
}
fragment.tutorialCanBeDeferred = false
return fragment
}
}
}
| gpl-3.0 | 0e169f22dca6c61cc51566f8cbb58c9e | 43.674858 | 281 | 0.604544 | 5.72017 | false | false | false | false |
androidx/androidx | health/connect/connect-client/src/main/java/androidx/health/connect/client/records/HeartRateRecord.kt | 3 | 5238 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.health.connect.client.records
import androidx.health.connect.client.aggregate.AggregateMetric
import androidx.health.connect.client.aggregate.AggregationResult
import androidx.health.connect.client.records.metadata.Metadata
import java.time.Instant
import java.time.ZoneOffset
/** Captures the user's heart rate. Each record represents a series of measurements. */
public class HeartRateRecord(
override val startTime: Instant,
override val startZoneOffset: ZoneOffset?,
override val endTime: Instant,
override val endZoneOffset: ZoneOffset?,
override val samples: List<Sample>,
override val metadata: Metadata = Metadata.EMPTY,
) : SeriesRecord<HeartRateRecord.Sample> {
init {
require(!startTime.isAfter(endTime)) { "startTime must not be after endTime." }
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is HeartRateRecord) return false
if (startTime != other.startTime) return false
if (startZoneOffset != other.startZoneOffset) return false
if (endTime != other.endTime) return false
if (endZoneOffset != other.endZoneOffset) return false
if (samples != other.samples) return false
if (metadata != other.metadata) return false
return true
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun hashCode(): Int {
var result = startTime.hashCode()
result = 31 * result + (startZoneOffset?.hashCode() ?: 0)
result = 31 * result + endTime.hashCode()
result = 31 * result + (endZoneOffset?.hashCode() ?: 0)
result = 31 * result + samples.hashCode()
result = 31 * result + metadata.hashCode()
return result
}
companion object {
private const val HEART_RATE_TYPE_NAME = "HeartRateSeries"
private const val BPM_FIELD_NAME = "bpm"
/** Metric identifier to retrieve the average heart rate from [AggregationResult]. */
@JvmField
val BPM_AVG: AggregateMetric<Long> =
AggregateMetric.longMetric(
HEART_RATE_TYPE_NAME,
AggregateMetric.AggregationType.AVERAGE,
BPM_FIELD_NAME
)
/** Metric identifier to retrieve the minimum heart rate from [AggregationResult]. */
@JvmField
val BPM_MIN: AggregateMetric<Long> =
AggregateMetric.longMetric(
HEART_RATE_TYPE_NAME,
AggregateMetric.AggregationType.MINIMUM,
BPM_FIELD_NAME
)
/** Metric identifier to retrieve the maximum heart rate from [AggregationResult]. */
@JvmField
val BPM_MAX: AggregateMetric<Long> =
AggregateMetric.longMetric(
HEART_RATE_TYPE_NAME,
AggregateMetric.AggregationType.MAXIMUM,
BPM_FIELD_NAME
)
/**
* Metric identifier to retrieve the number of heart rate measurements from
* [AggregationResult].
*/
@JvmField
val MEASUREMENTS_COUNT: AggregateMetric<Long> =
AggregateMetric.countMetric(HEART_RATE_TYPE_NAME)
}
/**
* Represents a single measurement of the heart rate.
*
* @param time The point in time when the measurement was taken.
* @param beatsPerMinute Heart beats per minute. Validation range: 1-300.
*
* @see HeartRateRecord
*/
public class Sample(
val time: Instant,
@androidx.annotation.IntRange(from = 1, to = 300) val beatsPerMinute: Long,
) {
init {
beatsPerMinute.requireNotLess(other = 1, name = "beatsPerMinute")
beatsPerMinute.requireNotMore(other = 300, name = "beatsPerMinute")
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Sample) return false
if (time != other.time) return false
if (beatsPerMinute != other.beatsPerMinute) return false
return true
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun hashCode(): Int {
var result = time.hashCode()
result = 31 * result + beatsPerMinute.hashCode()
return result
}
}
}
| apache-2.0 | b80564347b92113c87f48e7b8d0671ae | 34.391892 | 93 | 0.626193 | 4.86351 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/ide/intentions/StringDelimiterIntention.kt | 1 | 2041 | package org.elm.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.elm.lang.core.psi.ElmPsiFactory
import org.elm.lang.core.psi.ancestors
import org.elm.lang.core.psi.elements.ElmStringConstantExpr
/**
* Abstract base class for intentions which handle conversions between triple-quoted and regular strings.
*
* @param targetDelimiter The delimiter to use in the new string literal created by this intention.
*/
abstract class StringDelimiterIntention(private val targetDelimiter: String) :
ElmAtCaretIntentionActionBase<StringDelimiterIntention.Context>() {
data class Context(val stringConstant: ElmStringConstantExpr)
override fun getFamilyName() = text
/**
* Indicates whether `this` [ElmStringConstantExpr] is valid for replacement using this intention.
*/
protected abstract val ElmStringConstantExpr.isValidForReplacement: Boolean
/**
* Gets the string to use to replace `source`, where `source` is the content of the [ElmStringConstantExpr] (i.e.
* the text inside its delimiters/quotes).
*/
abstract fun getReplacement(source: String): String
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement) =
element.ancestors.filterIsInstance<ElmStringConstantExpr>()
.firstOrNull()
?.takeIf { it.isValidForReplacement }
?.let { Context(it) }
override fun invoke(project: Project, editor: Editor, context: Context) {
val newString =
ElmPsiFactory(project).createStringConstant(
"$targetDelimiter${getReplacement(context.stringConstant.textContent)}$targetDelimiter"
)
context.stringConstant.replace(newString)
}
companion object {
@JvmStatic
protected val DOUBLE_QUOTE = "\""
@JvmStatic
protected val ESCAPED_DOUBLE_QUOTE = "\\\""
@JvmStatic
protected val SLASH_N = "\\n"
}
}
| mit | a813d48edacbedb4d406a8f7f49855b2 | 36.109091 | 117 | 0.711416 | 4.836493 | false | false | false | false |
noemus/kotlin-eclipse | kotlin-eclipse-core/src/org/jetbrains/kotlin/core/model/CachedEnvironment.kt | 1 | 2804 | /*******************************************************************************
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.jetbrains.kotlin.core.model
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.impl.ZipHandler
import java.util.HashMap
import java.util.concurrent.ConcurrentHashMap
class CachedEnvironment<T, E : KotlinCommonEnvironment> {
private val environmentLock = Any()
private val environmentCache = ConcurrentHashMap<T, E>()
private val ideaProjectToEclipseResource = ConcurrentHashMap<Project, T>()
fun putEnvironment(resource: T, environment: E) {
synchronized(environmentLock) {
environmentCache.put(resource, environment)
ideaProjectToEclipseResource.put(environment.project, resource)
}
}
fun getOrCreateEnvironment(resource: T, createEnvironment: (T) -> E): E {
return synchronized(environmentLock) {
environmentCache.getOrPut(resource) {
val newEnvironment = createEnvironment(resource)
ideaProjectToEclipseResource.put(newEnvironment.project, resource)
newEnvironment
}
}
}
fun removeEnvironment(resource: T) {
synchronized(environmentLock) {
if (environmentCache.containsKey(resource)) {
val environment = environmentCache[resource]!!
ideaProjectToEclipseResource.remove(environment.project)
environmentCache.remove(resource)
Disposer.dispose(environment.javaApplicationEnvironment.getParentDisposable())
ZipHandler.clearFileAccessorCache()
}
}
}
fun replaceEnvironment(resource: T, createEnvironment: (T) -> E): E {
return synchronized(environmentLock) {
removeEnvironment(resource)
getOrCreateEnvironment(resource, createEnvironment)
}
}
fun getEclipseResource(ideaProject: Project): T? {
return synchronized(environmentLock) {
ideaProjectToEclipseResource.get(ideaProject)
}
}
} | apache-2.0 | 16a0662ce422acb1e6bf708ea5a59c3a | 36.4 | 94 | 0.649073 | 5.392308 | false | false | false | false |
BrianErikson/PushLocal-Android | PushLocal/src/main/java/com/beariksonstudios/automatic/pushlocal/pushlocal/server/tcp/TcpHandler.kt | 1 | 2551 | package com.beariksonstudios.automatic.pushlocal.pushlocal.server.tcp
import android.util.Log
import com.beariksonstudios.automatic.pushlocal.pushlocal.server.Server
import java.io.IOException
import java.net.ServerSocket
import java.net.Socket
import java.util.ArrayList
/**
* Created by BrianErikson on 8/17/2015.
*/
class TcpHandler(private val serverSock: ServerSocket, private val server: Server) : Runnable {
private val clients: ArrayList<TcpClient>
init {
this.clients = ArrayList<TcpClient>()
}
override fun run() {
while (Server.isRunning) {
try {
val newSocket = serverSock.accept()
addClient(newSocket)
} catch (e: IOException) {
e.printStackTrace()
}
}
}
// this thread
fun addClient(connection: Socket) {
var exists = false
for (client in clients) {
if (client.inetAddress === connection.inetAddress) {
exists = true
break
}
}
if (!exists) {
Log.v("PushLocal", "Adding client " + connection.inetAddress.hostName)
val tcpClient = TcpClient(connection, this)
tcpClient.start()
server.onDeviceConnection(connection.inetAddress.hostAddress)
clients.add(tcpClient)
}
}
// Server/Main thread
@Synchronized fun removeClient(ipAddress: String): Boolean {
var toRemove: TcpClient? = null
for (client in clients) {
if (client.inetAddress.hostName == ipAddress) {
toRemove = client
break
}
}
if (toRemove != null) {
try {
toRemove.dispose()
} catch (e: IOException) {
}
clients.remove(toRemove)
return true
}
return false
}
// Server/Main thread
@Synchronized fun broadcastMessageToClients(message: String) {
for (client in clients) {
try {
client.sendMessage(message)
} catch (e: IOException) {
e.printStackTrace()
}
}
}
// TcpClient(s) thread
@Synchronized fun removeClient(client: TcpClient) {
clients.remove(client)
Log.e("PushLocal", "Removing disconnected client")
}
@Synchronized @Throws(IOException::class)
fun dispose() {
for (client in clients) {
client.dispose()
}
}
}
| apache-2.0 | a85c61d37f7e59267ca1497c61d9a80b | 25.572917 | 95 | 0.560172 | 4.777154 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.