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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/operatorConventions/infixFunctionOverBuiltinMember.kt | 5 | 348 | infix fun Int.rem(other: Int) = 10
infix operator fun Int.minus(other: Int): Int = 20
fun box(): String {
val a = 5 rem 2
if (a != 10) return "fail 1"
val b = 5 minus 3
if (b != 20) return "fail 2"
val a1 = 5.rem(2)
if (a1 != 1) return "fail 3"
val b2 = 5.minus(3)
if (b2 != 2) return "fail 4"
return "OK"
} | apache-2.0 | 504f8736e0546178ca1873f73c5e8d87 | 18.388889 | 50 | 0.537356 | 2.740157 | false | false | false | false |
kohesive/kohesive-iac | model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/codegen/model/ModelFromAPIGenerator.kt | 1 | 13794 | package uy.kohesive.iac.model.aws.codegen.model
import com.amazonaws.codegen.C2jModels
import com.amazonaws.codegen.CodeGenerator
import com.amazonaws.codegen.model.config.BasicCodeGenConfig
import com.amazonaws.codegen.model.config.customization.CustomizationConfig
import com.amazonaws.codegen.model.service.*
import com.amazonaws.http.HttpMethodName
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration
import com.github.javaparser.ast.type.ClassOrInterfaceType
import org.reflections.Reflections
import org.reflections.scanners.TypeElementsScanner
import uy.klutter.core.common.mustNotStartWith
import uy.kohesive.iac.model.aws.utils.firstLetterToUpperCase
import uy.kohesive.iac.model.aws.utils.namespace
import uy.kohesive.iac.model.aws.utils.simpleName
import java.util.*
data class EnumHandler(
val enumClass: Class<*>,
val keys: List<String>
)
class ModelFromAPIGenerator(
val serviceInterface: Class<*>,
val serviceMetadata: ServiceMetadata,
val outputDir: String,
val verbToHttpMethod: Map<String, HttpMethodName>,
val fileNamePrefix: String,
val enumHandlers: List<EnumHandler>,
serviceSourcesDir: String
) {
private val interfaceSimpleName: String = serviceInterface.simpleName
private val packageName: String = serviceInterface.canonicalName.namespace()
private val modelPackage = packageName + ".model"
private val modelClassFqNamesBySimpleName = TypeElementsScanner().apply {
Reflections(modelPackage, this)
}.store.keySet().associateBy(String::simpleName).mapKeys {
if (it.key.contains("$")) {
it.key.substring(it.key.lastIndexOf('$') + 1)
} else {
it.key
}
} + listOf(
java.lang.String::class.java,
java.lang.Boolean::class.java,
java.lang.Integer::class.java,
java.lang.Long::class.java,
java.lang.Object::class.java
).associate { it.simpleName to it.name }
private val sources = SourceCache(serviceSourcesDir)
private val codeGenConfig = BasicCodeGenConfig(
interfaceSimpleName,
packageName,
null,
null,
null
)
private val classFqNameToShape = HashMap<String, Pair<String, Shape>>()
private fun getModelClassBySimpleName(simpleName: String) = modelClassFqNamesBySimpleName[simpleName]?.let { fqName ->
Class.forName(fqName)
} ?: throw IllegalArgumentException("Unknown model class: $simpleName")
private fun getOrCreateShape(
clazz: Class<*>,
typeParameterFqNames: List<Class<*>> = emptyList(),
shapeNameOverride: String? = null
): Pair<String, Shape> =
(clazz.name + (if (typeParameterFqNames.isEmpty()) "" else "<${typeParameterFqNames.joinToString(", ")}>")).let { classFqName ->
var fillWithMembers = false
classFqNameToShape.getOrPut(classFqName) {
val nameAndShape = if (clazz.isPrimitive) {
clazz.name.firstLetterToUpperCase() to Shape().apply { type = clazz.name.toLowerCase() }
} else if (clazz.isEnum) {
val enumHandler = enumHandlers.firstOrNull { it.enumClass == clazz}
?: throw IllegalArgumentException("No enum handler defined for ${clazz.simpleName}")
clazz.simpleName to Shape().apply {
enumValues = enumHandler.keys.filterNotNull()
type = "structure"
}
} else if (clazz.name == "java.lang.Object") {
// Looks weird, but seems to be correct. Raw Objects are used in Map values mapped to Strings.
"String" to Shape().apply { type = "string" }
} else if (clazz.name.startsWith("java.lang.")) {
clazz.simpleName to Shape().apply { type = clazz.simpleName.toLowerCase() }
} else if (clazz.name == "java.util.Date") {
"Date" to Shape().apply { type = "timestamp" }
} else if (clazz.name.endsWith("[]") || clazz.name.namespace().let { it == "java.io" || it == "java.net" }) {
throw UnModelableOperation()
} else if (List::class.java.isAssignableFrom(clazz) || Set::class.java.isAssignableFrom(clazz)) {
if (typeParameterFqNames.isEmpty()) {
throw IllegalStateException("Un-parameterized list")
}
val listParameter = typeParameterFqNames.first()
(listParameter.simpleName + if (Set::class.java.isAssignableFrom(clazz)) "Set" else "List") to Shape().apply {
type = "list"
listMember = Member().apply {
shape = getOrCreateShape(listParameter).first
}
}
} else if (Map::class.java.isAssignableFrom(clazz)) {
if (typeParameterFqNames.isEmpty()) {
throw UnModelableOperation("Un-parameterized map")
}
val mapKeyParameter = typeParameterFqNames[0]
val mapValueParameter = typeParameterFqNames[1]
mapValueParameter.simpleName + "Map" to Shape().apply {
type = "map"
mapKeyType = Member().apply {
shape = getOrCreateShape(mapKeyParameter).first
}
mapValueType = Member().apply {
shape = getOrCreateShape(mapValueParameter).first
}
}
} else {
fillWithMembers = true
clazz.simpleName to Shape().apply {
type = "structure"
}
}
// Override shape name
shapeNameOverride?.let { it to nameAndShape.second } ?: nameAndShape
}.apply {
// We fill shape members after shape is added to map to avoid infinite loops
if (fillWithMembers) {
val membersByGetters = clazz.declaredMethods.filter { method ->
method.name.startsWith("get") || method.name.startsWith("is")
}.map { getter ->
getter.name.mustNotStartWith("get").mustNotStartWith("is") to getter.returnType
}.toMap()
second.members = membersByGetters.mapValues {
val member = it.key
val memberClass = it.value
val typeArguments = getCollectionTypeArguments(clazz, "get$member", memberClass)
Member().apply {
shape = getOrCreateShape(memberClass, typeParameterFqNames = typeArguments).first
}
}
}
}
}
private fun getCollectionTypeArguments(clazz: Class<*>, memberName: String, memberClass: Class<*>): List<Class<*>> =
if (memberClass.simpleName.let { it == "List" || it == "Set" || it == "Map" }) {
val classifierFromSources = sources.get(clazz.name).let { compilationUnit ->
if (clazz.name.contains('$')) {
val pathArray = clazz.name.simpleName().split('$')
val initialType = compilationUnit.types.filterIsInstance<ClassOrInterfaceDeclaration>().first {
it.nameAsString == pathArray[0]
}
pathArray.drop(1).fold(initialType) { classifier, pathElement ->
classifier.childNodes.filterIsInstance<ClassOrInterfaceDeclaration>().first {
it.nameAsString == pathElement
}
}
} else {
if (clazz.isInterface) {
compilationUnit.getInterfaceByName(clazz.simpleName).get()
} else {
compilationUnit.getClassByName(clazz.simpleName).get()
}
}
}
classifierFromSources.getMethodsByName(memberName)?.firstOrNull()?.let { getter ->
(getter.type as? ClassOrInterfaceType)?.typeArguments?.get()?.map { typeArgument ->
(typeArgument as? ClassOrInterfaceType)?.nameAsString?.let { simpleName ->
getModelClassBySimpleName(simpleName)
}
}
}.orEmpty().filterNotNull()
} else {
emptyList()
}
private fun createOperations(): List<Operation> {
val requestMethodsToRequestClasses = serviceInterface.methods.groupBy { it.name }.mapValues {
// Here we take the method -> request class pair where request class is not null
it.value.map { method ->
method to method.parameters.firstOrNull { parameter ->
parameter.type.simpleName.endsWith("Request")
}?.type
}.firstOrNull {
it.second != null // it.second is request class
}
}.values.filterNotNull().toMap().filterValues { it != null }.mapValues { it.value!! }.filter {
"${it.key.name.firstLetterToUpperCase()}Request" == it.value.simpleName
}
return requestMethodsToRequestClasses.map {
try {
val requestMethod = it.key
val requestClass = it.value
val resultClass = it.key.returnType
val operationName = requestMethod.name.firstLetterToUpperCase()
val httpMethod = verbToHttpMethod.keys.firstOrNull { operationName.startsWith(it) }?.let { verb ->
verbToHttpMethod[verb]
}?.name ?: throw IllegalStateException("Can't figure out HTTP method for $operationName")
val http = Http()
.withMethod(httpMethod)
.withRequestUri("/")
val input = Input().apply {
shape = operationName + "Input"
}
getOrCreateShape(requestClass, shapeNameOverride = input.shape)
val output = Output().apply {
shape = if (resultClass.simpleName.endsWith("Result")) {
operationName + "Output"
} else {
resultClass.simpleName
}
}
val typeArguments = getCollectionTypeArguments(serviceInterface, requestMethod.name, resultClass)
getOrCreateShape(resultClass, shapeNameOverride = output.shape, typeParameterFqNames = typeArguments)
Operation()
.withName(operationName)
.withInput(input)
.withHttp(http).apply { setOutput(output) }
} catch (umo: UnModelableOperation) {
// ignore this operation
null
}
}.filterNotNull()
}
fun generate() {
// Create operations and shapes used in operations
val operations = createOperations().sortedBy { it.name }.associateBy { it.name }
val shapesFromOps = classFqNameToShape.values.toMap()
// Create shapes for the rest of model classes
val modelsClassesWithNoShape = (modelClassFqNamesBySimpleName - (modelClassFqNamesBySimpleName.keys.intersect(shapesFromOps.keys))).filter {
val simpleName = it.key
val fqName = it.value
fqName.namespace() == modelPackage &&
!simpleName.endsWith("marshaller", ignoreCase = true) &&
!simpleName.endsWith("Request") &&
!simpleName.startsWith("Abstract") &&
simpleName.first().isJavaIdentifierStart() &&
simpleName.all(Char::isJavaIdentifierPart)
}
val shapeFromModelsNames = modelsClassesWithNoShape.map {
try {
getOrCreateShape(getModelClassBySimpleName(it.key)).first
} catch (umo: UnModelableOperation) {
null
}
}.filterNotNull()
// Create a fake operation to reference the model shapes not used in real operations
val preserveModelsShape = "KohesiveModelPreserveInput" to Shape().apply {
type = "structure"
members = shapeFromModelsNames.associate { shapeName ->
shapeName to Member().apply {
shape = shapeName
}
}
}
val preserveModelsOp = "KohesivePreserveShapesOperation" to Operation()
.withName("KohesivePreserveShapesOperation")
.withInput(Input().apply {
shape = "KohesiveModelPreserveInput"
})
.withHttp(Http()
.withMethod("GET")
.withRequestUri("/")
)
// Build the models
val c2jModels = C2jModels.builder()
.codeGenConfig(codeGenConfig)
.customizationConfig(CustomizationConfig.DEFAULT)
.serviceModel(ServiceModel(
serviceMetadata,
operations + preserveModelsOp,
(classFqNameToShape.values.toMap() + preserveModelsShape).toSortedMap(),
emptyMap()
)
).build()
// Generate models JSON and service API
CodeGenerator(c2jModels, outputDir, outputDir, fileNamePrefix).execute()
}
}
class UnModelableOperation(override val message: String? = null) : Exception() | mit | ff85f73e14ec1e84362a8d180cb261a8 | 43.5 | 148 | 0.565463 | 5.295202 | false | false | false | false |
jotomo/AndroidAPS | danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Review_Bolus_Avg.kt | 1 | 1900 | package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.danars.encryption.BleEncryption
class DanaRS_Packet_Review_Bolus_Avg(
injector: HasAndroidInjector
) : DanaRS_Packet(injector) {
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__BOLUS_AVG
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(data: ByteArray) {
var dataIndex = DATA_START
var dataSize = 2
val bolusAvg03 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
val bolusAvg07 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
val bolusAvg14 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
val bolusAvg21 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
val bolusAvg28 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
val required = ((1 and 0x000000FF shl 8) + (1 and 0x000000FF)) / 100.0
if (bolusAvg03 == bolusAvg07 && bolusAvg07 == bolusAvg14 && bolusAvg14 == bolusAvg21 && bolusAvg21 == bolusAvg28 && bolusAvg28 == required) failed = true
aapsLogger.debug(LTag.PUMPCOMM, "Bolus average 3d: $bolusAvg03 U")
aapsLogger.debug(LTag.PUMPCOMM, "Bolus average 7d: $bolusAvg07 U")
aapsLogger.debug(LTag.PUMPCOMM, "Bolus average 14d: $bolusAvg14 U")
aapsLogger.debug(LTag.PUMPCOMM, "Bolus average 21d: $bolusAvg21 U")
aapsLogger.debug(LTag.PUMPCOMM, "Bolus average 28d: $bolusAvg28 U")
}
override fun getFriendlyName(): String {
return "REVIEW__BOLUS_AVG"
}
} | agpl-3.0 | a860dd0dee52ac51d85b62144af96b36 | 42.204545 | 161 | 0.68 | 4.130435 | false | false | false | false |
proff/teamcity-cachedSubversion | cachedSubversion-agent/src/main/java/com/proff/teamcity/cachedSubversion/cacheRule.kt | 1 | 1436 | package com.proff.teamcity.cachedSubversion
import org.tmatesoft.svn.core.SVNException
import org.tmatesoft.svn.core.SVNURL
import java.io.File
class cacheRule(rule: String) {
val source: SVNURL
val name: String?
val target: cacheTarget?
init {
val arr = rule.split(' ')
source = SVNURL.parseURIEncoded(arr[0])
name = if (arr.count() > 1) arr[1] else null
if (arr.count() > 2) {
var t: cacheTarget
try {
t = cacheTarget(SVNURL.parseURIEncoded(arr[2]))
} catch(e: SVNException) {
//is not url, try parse as File
t = cacheTarget(File(arr[2]))
}
target = t
} else
target = null
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as cacheRule
if (source != other.source) return false
if (name != other.name) return false
if (target != other.target) return false
return true
}
override fun hashCode(): Int {
var result = source.hashCode()
result = 31 * result + (name?.hashCode() ?: 0)
result = 31 * result + (target?.hashCode() ?: 0)
return result
}
override fun toString(): String {
return "cacheRule(source=$source, name=$name, target=$target)"
}
} | mit | c740df03e9defc29c13358f061e96161 | 26.634615 | 70 | 0.560585 | 4.211144 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/conventions/components/dataClassInsideDataClass.0.kt | 5 | 447 | // PSI_ELEMENT: org.jetbrains.kotlin.psi.KtParameter
// OPTIONS: usages
data class A(val <caret>x: Int, val y: Int, val z: String)
data class B(val a: A, val n: Int)
class C {
operator fun component1(): A = TODO()
operator fun component2() = 0
}
fun f(b: B, c: C) {
val (a, n) = b
val (x, y, z) = a
val (a1, n1) = c
val (x1, y1, z1) = a1
}
// FIR_COMPARISON
// FIR_COMPARISON_WITH_DISABLED_COMPONENTS
// IGNORE_FIR_LOG
| apache-2.0 | d262388429e6f85f71bbb9302b5e4f89 | 20.285714 | 58 | 0.604027 | 2.64497 | false | false | false | false |
HenningLanghorst/fancy-kotlin-stuff | src/main/kotlin/de/henninglanghorst/kotlinstuff/coroutines/Coroutines.kt | 1 | 2620 | package de.henninglanghorst.kotlinstuff.coroutines
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import org.slf4j.LoggerFactory
import java.io.ByteArrayInputStream
import java.io.IOException
import java.io.InputStream
import java.io.PrintStream
import java.net.HttpURLConnection
import java.net.URL
import java.util.stream.Collectors
private val logger = LoggerFactory.getLogger(Exception().stackTrace[0].className)
fun main(args: Array<String>) {
val message1 = httpRequestAsync("https://postman-echo.com/post?hhhhh=5") {
requestMethod = "POST"
setRequestProperty("Authorization", "Basic d2lraTpwZWRpYQ==")
setRequestProperty("Content-Type", "application/json; charset=utf-8")
body = json(6, "Miller")
}
val message2 = httpRequestAsync("https://postman-echo.com/get?s=5&aaa=43") {
requestMethod = "GET"
setRequestProperty("Authorization", "Basic d2lraTpwZWRpYQ==")
}
val message3 = httpRequestAsync("https://postman-echo.com/status/400") {
requestMethod = "GET"
setRequestProperty("Authorization", "Basic d2lraTpwZWRpYQ==")
}
runBlocking {
println(message1.await())
println(message2.await())
}
runBlocking { println(message3.await()) }
}
private fun json(id: Int, name: String) = """{"id": $id, "name": "$name"}"""
private fun httpRequestAsync(url: String, setup: HttpURLConnection.() -> Unit) = GlobalScope.async { httpRequest(url, setup) }
private fun httpRequest(url: String, setup: HttpURLConnection.() -> Unit): String {
return URL(url).openConnection()
.let { it as HttpURLConnection }
.apply { doInput = true }
.apply(setup)
.also { logger.info("HTTP ${it.requestMethod} call to $url") }
.run {
responseStream.bufferedReader(Charsets.UTF_8)
.lines()
.collect(Collectors.joining(System.lineSeparator()))
}
}
private val HttpURLConnection.responseStream: InputStream
get() =
try {
inputStream
} catch (e: IOException) {
errorStream ?: ByteArrayInputStream(byteArrayOf())
}
private var HttpURLConnection.body: String
set(value) {
doOutput = requestMethod != "GET" && value.isNotEmpty()
if (doOutput)
PrintStream(outputStream).use {
it.println(value)
it.flush()
}
}
get() = ""
private fun return5(): Int {
Thread.sleep(4000)
return 5
} | apache-2.0 | e807dc045d9d4a2e59a10b56487f2819 | 28.784091 | 126 | 0.639313 | 4.205457 | false | false | false | false |
JetBrains/xodus | utils/src/main/kotlin/jetbrains/exodus/core/dataStructures/hash/LongHashMap.kt | 1 | 5232 | /**
* Copyright 2010 - 2022 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
*
* 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 jetbrains.exodus.core.dataStructures.hash
import jetbrains.exodus.util.MathUtil
import java.lang.Integer.max
class LongHashMap<V> @JvmOverloads constructor(capacity: Int = 0, private val loadFactor: Float = HashUtil.DEFAULT_LOAD_FACTOR) : AbstractHashMap<Long, V>() {
private var table: Array<Entry<V>?> = emptyArray()
private var capacity = 0
private var mask = 0
init {
init(capacity)
}
override fun get(key: Long): V? = getEntry(key)?.value
override fun put(key: Long, value: V): V? {
table.let { table ->
val index = HashUtil.indexFor(key, table.size, mask)
var e = table[index]
while (e != null) {
if (e.key == key) {
return e.setValue(value)
}
e = e.hashNext
}
Entry(key, value).let { newEntry ->
newEntry.hashNext = table[index]
table[index] = newEntry
}
_size += 1
if (_size > capacity) {
rehash(HashUtil.nextCapacity(capacity))
}
return null
}
}
override fun containsKey(key: Long) = getEntry(key) != null
override fun remove(key: Long): V? {
table.let { table ->
val index = HashUtil.indexFor(key, table.size, mask)
var e: Entry<V> = table[index] ?: return null
var last: Entry<V>? = null
while (key != e.key) {
last = e
e = e.hashNext ?: return null
}
_size -= 1
if (last == null) {
table[index] = e.hashNext
} else {
last.hashNext = e.hashNext
}
return e.value
}
}
@Suppress("UNCHECKED_CAST")
override fun getEntry(key: Any): MutableMap.MutableEntry<Long, V>? {
return getEntry((key as Long).toLong()) as MutableMap.MutableEntry<Long, V>?
}
override fun init(capacity: Int) {
max(capacity, HashUtil.MIN_CAPACITY).let { c ->
allocateTable(HashUtil.getCeilingPrime((c / loadFactor).toInt()))
this.capacity = c
this._size = 0
}
}
override fun hashIterator(): HashMapIterator {
return HashIterator()
}
private fun getEntry(key: Long): Entry<V>? {
val table = table
val index = HashUtil.indexFor(key, table.size, mask)
var e = table[index]
while (e != null) {
if (e.key == key) {
return e
}
e = e.hashNext
}
return null
}
private fun allocateTable(length: Int) {
table = arrayOfNulls<Entry<V>?>(length)
mask = (1 shl MathUtil.integerLogarithm(table.size)) - 1
}
private fun rehash(capacity: Int) {
val length = HashUtil.getCeilingPrime((capacity / loadFactor).toInt())
this.capacity = capacity
if (length != table.size) {
val entries: Iterator<Map.Entry<Long, V>> = entries.iterator()
allocateTable(length)
val table = table
val mask = mask
while (entries.hasNext()) {
val e = entries.next() as Entry<V>
val index = HashUtil.indexFor(e.key, length, mask)
e.hashNext = table[index]
table[index] = e
}
}
}
private class Entry<V>(override val key: Long, override var value: V) : MutableMap.MutableEntry<Long?, V> {
var hashNext: Entry<V>? = null
override fun setValue(newValue: V) = value.also { value = newValue }
}
private inner class HashIterator internal constructor() : HashMapIterator() {
private val table = [email protected]
private var index = 0
private var e: Entry<V>? = null
private var last: Entry<V>? = null
init {
initNextEntry()
}
public override fun hasNext() = e != null
public override fun remove() {
[email protected](checkNotNull(last).key)
last = null
}
override fun nextEntry() = checkNotNull(e).also {
last = it
initNextEntry()
}
private fun initNextEntry() {
var result = e
if (result != null) {
result = result.hashNext
}
val table = this.table
while (result == null && index < table.size) {
result = table[index++]
}
e = result
}
}
} | apache-2.0 | aef25b3cca3a00cf9ea88254d17cffc1 | 29.782353 | 158 | 0.544343 | 4.35637 | false | false | false | false |
siosio/intellij-community | python/src/com/jetbrains/python/namespacePackages/PyNamespacePackageRootProvider.kt | 1 | 3768 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.namespacePackages
import com.intellij.openapi.Disposable
import com.intellij.openapi.extensions.ExtensionNotApplicableException
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.ContentEntry
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.roots.ui.configuration.actions.ContentEntryEditingAction
import com.intellij.openapi.util.Comparing
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.pointers.VirtualFilePointer
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager
import com.intellij.ui.JBColor
import com.intellij.util.PlatformIcons
import com.intellij.util.containers.MultiMap
import com.jetbrains.python.PyBundle
import com.jetbrains.python.module.PyContentEntriesEditor
import com.jetbrains.python.module.PyRootTypeProvider
import java.awt.Color
import javax.swing.Icon
import javax.swing.JTree
class PyNamespacePackageRootProvider: PyRootTypeProvider() {
private val myNamespacePackages = MultiMap<ContentEntry, VirtualFilePointer>()
init {
if (!Registry.`is`("python.explicit.namespace.packages")) {
throw ExtensionNotApplicableException.INSTANCE
}
}
override fun reset(disposable: Disposable, editor: PyContentEntriesEditor, module: Module) {
myNamespacePackages.clear()
val namespacePackages = PyNamespacePackagesService.getInstance(module).namespacePackageFoldersVirtualFiles
for (namespacePackage in namespacePackages) {
val contentEntry = findContentEntryForFile(namespacePackage, editor) ?: continue
val pointer = VirtualFilePointerManager.getInstance().create(namespacePackage, disposable, DUMMY_LISTENER)
myNamespacePackages.putValue(contentEntry, pointer)
}
}
override fun apply(module: Module) {
val instance = PyNamespacePackagesService.getInstance(module)
val currentNamespacePackages = getCurrentNamespacePackages()
if (!Comparing.haveEqualElements(instance.namespacePackageFoldersVirtualFiles, currentNamespacePackages)) {
instance.namespacePackageFoldersVirtualFiles = currentNamespacePackages
PyNamespacePackagesStatisticsCollector.logApplyInNamespacePackageRootProvider()
}
}
override fun isModified(module: Module): Boolean =
!Comparing.haveEqualElements(PyNamespacePackagesService.getInstance(module).namespacePackageFoldersVirtualFiles,
getCurrentNamespacePackages())
override fun getRoots(): MultiMap<ContentEntry, VirtualFilePointer> = myNamespacePackages
override fun getIcon(): Icon {
return PlatformIcons.PACKAGE_ICON
}
override fun getName(): String {
return PyBundle.message("python.namespace.packages.name")
}
override fun getDescription(): String {
return PyBundle.message("python.namespace.packages.description")
}
override fun getRootsGroupColor(): Color {
return EASTERN_BLUE
}
override fun createRootEntryEditingAction(tree: JTree?,
disposable: Disposable?,
editor: PyContentEntriesEditor?,
model: ModifiableRootModel?): ContentEntryEditingAction {
return RootEntryEditingAction(tree, disposable, editor, model)
}
private fun getCurrentNamespacePackages(): List<VirtualFile> = myNamespacePackages.values().mapNotNull { it.file }
companion object {
private val EASTERN_BLUE: Color = JBColor(0x29A5AD, 0x29A5AD)
}
} | apache-2.0 | ae00272b95e5a40b941b42df57417a3e | 41.829545 | 158 | 0.773355 | 5.190083 | false | false | false | false |
siosio/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/util/Borders.kt | 2 | 1024 | package com.jetbrains.packagesearch.intellij.plugin.ui.util
import com.intellij.util.ui.JBEmptyBorder
internal fun scaledEmptyBorder(@ScalableUnits size: Int = 0) = scaledEmptyBorder(size, size, size, size)
internal fun scaledEmptyBorder(@ScalableUnits vSize: Int = 0, @ScalableUnits hSize: Int = 0) = scaledEmptyBorder(vSize, hSize, vSize, hSize)
internal fun scaledEmptyBorder(
@ScalableUnits top: Int = 0,
@ScalableUnits left: Int = 0,
@ScalableUnits bottom: Int = 0,
@ScalableUnits right: Int = 0
) = emptyBorder(top.scaled(), left.scaled(), bottom.scaled(), right.scaled())
internal fun emptyBorder(@ScaledPixels size: Int = 0) = emptyBorder(size, size, size, size)
internal fun emptyBorder(@ScaledPixels vSize: Int = 0, @ScaledPixels hSize: Int = 0) = emptyBorder(vSize, hSize, vSize, hSize)
internal fun emptyBorder(
@ScaledPixels top: Int = 0,
@ScaledPixels left: Int = 0,
@ScaledPixels bottom: Int = 0,
@ScaledPixels right: Int = 0
) = JBEmptyBorder(top, left, bottom, right)
| apache-2.0 | 321900c5dcb80b83e17959e14d660c8e | 39.96 | 140 | 0.727539 | 3.723636 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/conversion/copy/DataForConversion.kt | 4 | 11310 | // 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.conversion.copy
import com.intellij.lang.java.JavaLanguage
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMap
import org.jetbrains.kotlin.name.FqNameUnsafe
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.elementsInRange
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.psi.psiUtil.siblings
data class DataForConversion private constructor(
val elementsAndTexts: ElementAndTextList /* list consisting of PsiElement's to convert and plain String's */,
val importsAndPackage: String,
val file: PsiJavaFile
) {
companion object {
fun prepare(copiedCode: CopiedJavaCode, project: Project): DataForConversion {
val startOffsets = copiedCode.startOffsets.clone()
val endOffsets = copiedCode.endOffsets.clone()
assert(startOffsets.size == endOffsets.size) { "Must have the same size" }
var fileText = copiedCode.fileText
var file = PsiFileFactory.getInstance(project).createFileFromText(JavaLanguage.INSTANCE, fileText) as PsiJavaFile
val importsAndPackage = buildImportsAndPackage(file)
val newFileText = clipTextIfNeeded(file, fileText, startOffsets, endOffsets)
if (newFileText != null) {
fileText = newFileText
file = PsiFileFactory.getInstance(project).createFileFromText(JavaLanguage.INSTANCE, newFileText) as PsiJavaFile
}
val elementsAndTexts = ElementAndTextList()
for (i in startOffsets.indices) {
elementsAndTexts.collectElementsToConvert(file, fileText, TextRange(startOffsets[i], endOffsets[i]))
}
return DataForConversion(elementsAndTexts, importsAndPackage, file)
}
private fun clipTextIfNeeded(file: PsiJavaFile, fileText: String, startOffsets: IntArray, endOffsets: IntArray): String? {
val ranges = startOffsets.indices.map { TextRange(startOffsets[it], endOffsets[it]) }.sortedBy { it.startOffset }
fun canDropRange(range: TextRange) = ranges.all { range !in it }
val rangesToDrop = ArrayList<TextRange>()
for (range in ranges) {
val start = range.startOffset
val end = range.endOffset
if (start == end) continue
val startToken = file.findElementAt(start)!!
val elementToClipLeft = startToken.maximalParentToClip(range)
if (elementToClipLeft != null) {
val elementStart = elementToClipLeft.textRange.startOffset
if (elementStart < start) {
val clipBound = tryClipLeftSide(elementToClipLeft, start)
if (clipBound != null) {
val rangeToDrop = TextRange(elementStart, clipBound)
if (canDropRange(rangeToDrop)) {
rangesToDrop.add(rangeToDrop)
}
}
}
}
val endToken = file.findElementAt(end - 1)!!
val elementToClipRight = endToken.maximalParentToClip(range)
if (elementToClipRight != null) {
val elementEnd = elementToClipRight.textRange.endOffset
if (elementEnd > end) {
val clipBound = tryClipRightSide(elementToClipRight, end)
if (clipBound != null) {
val rangeToDrop = TextRange(clipBound, elementEnd)
if (canDropRange(rangeToDrop)) {
rangesToDrop.add(rangeToDrop)
}
}
}
}
}
if (rangesToDrop.isEmpty()) return null
val newFileText = buildString {
var offset = 0
for (range in rangesToDrop) {
assert(range.startOffset >= offset)
append(fileText.substring(offset, range.startOffset))
offset = range.endOffset
}
append(fileText.substring(offset, fileText.length))
}
fun IntArray.update() {
for (range in rangesToDrop.asReversed()) {
for (i in indices) {
val offset = this[i]
if (offset >= range.endOffset) {
this[i] = offset - range.length
} else {
assert(offset <= range.startOffset)
}
}
}
}
startOffsets.update()
endOffsets.update()
return newFileText
}
private fun PsiElement.maximalParentToClip(range: TextRange): PsiElement? {
val firstNotInRange = parentsWithSelf
.takeWhile { it !is PsiDirectory }
.firstOrNull { it.textRange !in range }
?: return null
return firstNotInRange.parentsWithSelf.lastOrNull { it.minimizedTextRange() in range }
}
private fun PsiElement.minimizedTextRange(): TextRange {
val firstChild = firstChild?.siblings()?.firstOrNull { !canDropElementFromText(it) } ?: return textRange
val lastChild = lastChild.siblings(forward = false).first { !canDropElementFromText(it) }
return TextRange(firstChild.minimizedTextRange().startOffset, lastChild.minimizedTextRange().endOffset)
}
// element's text can be removed from file's text keeping parsing the same
private fun canDropElementFromText(element: PsiElement): Boolean {
return when (element) {
is PsiWhiteSpace, is PsiComment, is PsiModifierList, is PsiAnnotation -> true
is PsiJavaToken -> {
when (element.tokenType) {
// modifiers
JavaTokenType.PUBLIC_KEYWORD, JavaTokenType.PROTECTED_KEYWORD, JavaTokenType.PRIVATE_KEYWORD,
JavaTokenType.STATIC_KEYWORD, JavaTokenType.ABSTRACT_KEYWORD, JavaTokenType.FINAL_KEYWORD,
JavaTokenType.NATIVE_KEYWORD, JavaTokenType.SYNCHRONIZED_KEYWORD, JavaTokenType.STRICTFP_KEYWORD,
JavaTokenType.TRANSIENT_KEYWORD, JavaTokenType.VOLATILE_KEYWORD, JavaTokenType.DEFAULT_KEYWORD ->
element.getParent() is PsiModifierList
JavaTokenType.SEMICOLON -> true
else -> false
}
}
is PsiCodeBlock -> element.getParent() is PsiMethod
else -> element.firstChild == null
}
}
private fun tryClipLeftSide(element: PsiElement, leftBound: Int) =
tryClipSide(element, leftBound, { textRange }, { allChildren })
private fun tryClipRightSide(element: PsiElement, rightBound: Int): Int? {
fun Int.transform() = Int.MAX_VALUE - this
fun TextRange.transform() = TextRange(endOffset.transform(), startOffset.transform())
return tryClipSide(
element,
rightBound.transform(),
{ textRange.transform() },
{ lastChild.siblings(forward = false) }
)?.transform()
}
private fun tryClipSide(
element: PsiElement,
rangeBound: Int,
rangeFunction: PsiElement.() -> TextRange,
childrenFunction: PsiElement.() -> Sequence<PsiElement>
): Int? {
if (element.firstChild == null) return null
val elementRange = element.rangeFunction()
assert(elementRange.startOffset < rangeBound && rangeBound < elementRange.endOffset)
var clipTo = elementRange.startOffset
for (child in element.childrenFunction()) {
val childRange = child.rangeFunction()
if (childRange.startOffset >= rangeBound) { // we have cut enough already
break
} else if (childRange.endOffset <= rangeBound) { // need to drop the whole element
if (!canDropElementFromText(child)) return null
clipTo = childRange.endOffset
} else { // rangeBound is inside child's range
if (child is PsiWhiteSpace) break // no need to cut whitespace - we can leave it as is
return tryClipSide(child, rangeBound, rangeFunction, childrenFunction)
}
}
return clipTo
}
private fun ElementAndTextList.collectElementsToConvert(
file: PsiJavaFile,
fileText: String,
range: TextRange
) {
val elements = file.elementsInRange(range)
if (elements.isEmpty()) {
add(fileText.substring(range.startOffset, range.endOffset))
} else {
add(fileText.substring(range.startOffset, elements.first().textRange.startOffset))
elements.forEach {
if (shouldExpandToChildren(it))
this += it.allChildren.toList()
else
this += it
}
add(fileText.substring(elements.last().textRange.endOffset, range.endOffset))
}
}
// converting of PsiModifierList is not supported by converter, but converting of single annotations inside it is supported
private fun shouldExpandToChildren(element: PsiElement) = element is PsiModifierList
private fun buildImportsAndPackage(sourceFile: PsiJavaFile): String {
return buildString {
val packageName = sourceFile.packageName
if (packageName.isNotEmpty()) {
append("package $packageName\n")
}
val importList = sourceFile.importList
if (importList != null) {
for (import in importList.importStatements) {
val qualifiedName = import.qualifiedName ?: continue
if (import.isOnDemand) {
append("import $qualifiedName.*\n")
} else {
val fqName = FqNameUnsafe(qualifiedName)
// skip explicit imports of platform classes mapped into Kotlin classes
if (fqName.isSafe && JavaToKotlinClassMap.isJavaPlatformClass(fqName.toSafe())) continue
append("import $qualifiedName\n")
}
}
//TODO: static imports
}
}
}
}
}
| apache-2.0 | 2cb344e1820cdbb5c584ad9f2a0487a6 | 44.97561 | 158 | 0.567374 | 5.686275 | false | false | false | false |
faruktoptas/RetrofitRssConverterFactory | library/src/main/java/me/toptas/rssconverter/RssResponseBodyConverter.kt | 1 | 876 | package me.toptas.rssconverter
import org.xml.sax.InputSource
import javax.xml.parsers.SAXParserFactory
import okhttp3.ResponseBody
import retrofit2.Converter
internal class RssResponseBodyConverter : Converter<ResponseBody, RssFeed> {
override fun convert(value: ResponseBody): RssFeed {
val rssFeed = RssFeed()
try {
val parser = XMLParser()
val parserFactory = SAXParserFactory.newInstance()
val saxParser = parserFactory.newSAXParser()
val xmlReader = saxParser.xmlReader
xmlReader.contentHandler = parser
val inputSource = InputSource(value.charStream())
xmlReader.parse(inputSource)
val items = parser.items
rssFeed.items = items
} catch (e: Exception) {
e.printStackTrace()
}
return rssFeed
}
} | apache-2.0 | b6859a3fc59a9e150fa2d1b8b6e1a65c | 27.290323 | 76 | 0.648402 | 4.786885 | false | false | false | false |
matt-richardson/TeamCity.Node | server/src/com/jonnyzzz/teamcity/plugins/node/server/NodeJsRunType.kt | 2 | 2036 | /*
* Copyright 2013-2013 Eugene Petrenko
*
* 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.jonnyzzz.teamcity.plugins.node.server
import jetbrains.buildServer.requirements.Requirement
import jetbrains.buildServer.requirements.RequirementType
import jetbrains.buildServer.serverSide.InvalidProperty
import jetbrains.buildServer.serverSide.PropertiesProcessor
import com.jonnyzzz.teamcity.plugins.node.common.NodeBean
import com.jonnyzzz.teamcity.plugins.node.common.isEmptyOrSpaces
import java.util.InvalidPropertiesFormatException
import com.jonnyzzz.teamcity.plugins.node.common.ExecutionModes
public class NodeJsRunType : JsRunTypeBase() {
public override fun getType(): String = bean.runTypeNameNodeJs
public override fun getDisplayName(): String = "Node.js"
public override fun getDescription(): String = "Starts javascript files under Node.js runtime"
protected override fun getEditJsp(): String = "node.edit.jsp"
protected override fun getViewJsp(): String = "node.view.jsp"
public override fun getRunnerSpecificRequirements(runParameters: Map<String, String>): MutableList<Requirement> {
val result = arrayListOf<Requirement>()
val list = super.getRunnerSpecificRequirements(runParameters)
if (list != null) result addAll list
if (runParameters[bean.toolPathKey].isEmptyOrSpaces()) {
//for now there is the only option to use detected node.js
result.add(Requirement(bean.nodeJSConfigurationParameter, null, RequirementType.EXISTS))
}
return result
}
}
| apache-2.0 | e713a70a92072991404864c420f68029 | 41.416667 | 115 | 0.782908 | 4.55481 | false | false | false | false |
androidx/androidx | room/room-runtime/src/test/java/androidx/room/util/UUIDUtilTest.kt | 3 | 1560 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.util
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.nio.ByteBuffer
import java.util.UUID
import kotlin.random.Random
@RunWith(JUnit4::class)
class UUIDUtilTest {
@Test
fun convertToByte() {
val uuid = UUID.randomUUID()
val expected = ByteBuffer.wrap(ByteArray(16)).apply {
putLong(uuid.mostSignificantBits)
putLong(uuid.leastSignificantBits)
}.array()
val result = convertUUIDToByte(uuid)
assertThat(result).isEqualTo(expected)
}
@Test
fun convertToUUID() {
val byteArray = Random.Default.nextBytes(ByteArray(16))
val buffer = ByteBuffer.wrap(byteArray)
val expected = UUID(buffer.long, buffer.long)
val result = convertByteToUUID(byteArray)
assertThat(result).isEqualTo(expected)
}
} | apache-2.0 | f6a28a18aa303555020148692143b6cc | 27.381818 | 75 | 0.707051 | 4.227642 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/caches/PerModulePackageCacheService.kt | 1 | 18031 | // 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.caches
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.*
import com.intellij.psi.PsiManager
import com.intellij.psi.impl.PsiManagerEx
import com.intellij.psi.impl.PsiTreeChangeEventImpl
import com.intellij.psi.impl.PsiTreeChangePreprocessor
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.containers.CollectionFactory
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.indexing.DumbModeAccessType
import org.jetbrains.kotlin.idea.base.projectStructure.ModuleInfoProvider
import org.jetbrains.kotlin.idea.base.projectStructure.firstOrNull
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfoOrNull
import org.jetbrains.kotlin.idea.caches.PerModulePackageCacheService.Companion.DEBUG_LOG_ENABLE_PerModulePackageCache
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo
import org.jetbrains.kotlin.idea.base.indices.KotlinPackageIndexUtils
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.getSourceRoot
import org.jetbrains.kotlin.idea.util.isKotlinFileType
import org.jetbrains.kotlin.idea.util.sourceRoot
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPackageDirective
import org.jetbrains.kotlin.psi.NotNullableUserDataProperty
import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap
class KotlinPackageStatementPsiTreeChangePreprocessor(private val project: Project) : PsiTreeChangePreprocessor {
override fun treeChanged(event: PsiTreeChangeEventImpl) {
// skip events out of scope of this processor
when (event.code) {
PsiTreeChangeEventImpl.PsiEventType.CHILD_ADDED,
PsiTreeChangeEventImpl.PsiEventType.CHILD_MOVED,
PsiTreeChangeEventImpl.PsiEventType.CHILD_REPLACED,
PsiTreeChangeEventImpl.PsiEventType.CHILD_REMOVED,
PsiTreeChangeEventImpl.PsiEventType.CHILDREN_CHANGED -> Unit
else -> return
}
val eFile = event.file ?: event.child ?: run {
LOG.debugIfEnabled(project, true) { "Got PsiEvent: $event without file/child" }
return
}
val file = eFile as? KtFile ?: return
when (event.code) {
PsiTreeChangeEventImpl.PsiEventType.CHILD_ADDED,
PsiTreeChangeEventImpl.PsiEventType.CHILD_MOVED,
PsiTreeChangeEventImpl.PsiEventType.CHILD_REPLACED,
PsiTreeChangeEventImpl.PsiEventType.CHILD_REMOVED -> {
val child = event.child ?: run {
LOG.debugIfEnabled(project, true) { "Got PsiEvent: $event without child" }
return
}
if (child.getParentOfType<KtPackageDirective>(false) != null)
PerModulePackageCacheService.getInstance(project).notifyPackageChange(file)
}
PsiTreeChangeEventImpl.PsiEventType.CHILDREN_CHANGED -> {
val parent = event.parent ?: run {
LOG.debugIfEnabled(project, true) { "Got PsiEvent: $event without parent" }
return
}
val childrenOfType = parent.getChildrenOfType<KtPackageDirective>()
if (
(!event.isGenericChange && (childrenOfType.any() || parent is KtPackageDirective)) ||
(childrenOfType.any { it.name.isEmpty() } && parent is KtFile)
) {
PerModulePackageCacheService.getInstance(project).notifyPackageChange(file)
}
}
else -> error("unsupported event code ${event.code} for PsiEvent $event")
}
}
companion object {
val LOG = Logger.getInstance(this::class.java)
}
}
private typealias ImplicitPackageData = MutableMap<FqName, MutableList<VirtualFile>>
class ImplicitPackagePrefixCache(private val project: Project) {
private val implicitPackageCache = ConcurrentHashMap<VirtualFile, ImplicitPackageData>()
fun getPrefix(sourceRoot: VirtualFile): FqName {
val implicitPackageMap = implicitPackageCache.getOrPut(sourceRoot) { analyzeImplicitPackagePrefixes(sourceRoot) }
return implicitPackageMap.keys.singleOrNull() ?: FqName.ROOT
}
internal fun clear() {
implicitPackageCache.clear()
}
private fun analyzeImplicitPackagePrefixes(sourceRoot: VirtualFile): MutableMap<FqName, MutableList<VirtualFile>> {
val result = mutableMapOf<FqName, MutableList<VirtualFile>>()
val ktFiles = sourceRoot.children.filter(VirtualFile::isKotlinFileType)
for (ktFile in ktFiles) {
result.addFile(ktFile)
}
return result
}
private fun ImplicitPackageData.addFile(ktFile: VirtualFile) {
synchronized(this) {
val psiFile = PsiManager.getInstance(project).findFile(ktFile) as? KtFile ?: return
addPsiFile(psiFile, ktFile)
}
}
private fun ImplicitPackageData.addPsiFile(
psiFile: KtFile,
ktFile: VirtualFile
) = getOrPut(psiFile.packageFqName) { mutableListOf() }.add(ktFile)
private fun ImplicitPackageData.removeFile(file: VirtualFile) {
synchronized(this) {
for ((key, value) in this) {
if (value.remove(file)) {
if (value.isEmpty()) remove(key)
break
}
}
}
}
private fun ImplicitPackageData.updateFile(file: KtFile) {
synchronized(this) {
removeFile(file.virtualFile)
addPsiFile(file, file.virtualFile)
}
}
internal fun update(event: VFileEvent) {
when (event) {
is VFileCreateEvent -> checkNewFileInSourceRoot(event.file)
is VFileDeleteEvent -> checkDeletedFileInSourceRoot(event.file)
is VFileCopyEvent -> {
val newParent = event.newParent
if (newParent.isValid) {
checkNewFileInSourceRoot(newParent.findChild(event.newChildName))
}
}
is VFileMoveEvent -> {
checkNewFileInSourceRoot(event.file)
if (event.oldParent.getSourceRoot(project) == event.oldParent) {
implicitPackageCache[event.oldParent]?.removeFile(event.file)
}
}
}
}
private fun checkNewFileInSourceRoot(file: VirtualFile?) {
if (file == null) return
if (file.getSourceRoot(project) == file.parent) {
implicitPackageCache[file.parent]?.addFile(file)
}
}
private fun checkDeletedFileInSourceRoot(file: VirtualFile?) {
val directory = file?.parent
if (directory == null || !directory.isValid) return
if (directory.getSourceRoot(project) == directory) {
implicitPackageCache[directory]?.removeFile(file)
}
}
internal fun update(ktFile: KtFile) {
val parent = ktFile.virtualFile?.parent ?: return
if (ktFile.sourceRoot == parent) {
implicitPackageCache[parent]?.updateFile(ktFile)
}
}
}
class PerModulePackageCacheService(private val project: Project) : Disposable {
/*
* Actually an WeakMap<Module, ConcurrentMap<ModuleSourceInfo, ConcurrentMap<FqName, Boolean>>>
*/
private val cache = ContainerUtil.createConcurrentWeakMap<Module, ConcurrentMap<ModuleSourceInfo, ConcurrentMap<FqName, Boolean>>>()
private val implicitPackagePrefixCache = ImplicitPackagePrefixCache(project)
private val useStrongMapForCaching = Registry.`is`("kotlin.cache.packages.strong.map", false)
private val pendingVFileChanges: MutableSet<VFileEvent> = mutableSetOf()
private val pendingKtFileChanges: MutableSet<KtFile> = mutableSetOf()
private val projectScope = GlobalSearchScope.projectScope(project)
internal fun onTooComplexChange() {
clear()
}
private fun clear() {
synchronized(this) {
pendingVFileChanges.clear()
pendingKtFileChanges.clear()
cache.clear()
implicitPackagePrefixCache.clear()
}
}
internal fun notifyPackageChange(file: VFileEvent): Unit = synchronized(this) {
pendingVFileChanges += file
}
internal fun notifyPackageChange(file: KtFile): Unit = synchronized(this) {
pendingKtFileChanges += file
}
private fun invalidateCacheForModuleSourceInfo(moduleSourceInfo: ModuleSourceInfo) {
LOG.debugIfEnabled(project) { "Invalidated cache for $moduleSourceInfo" }
val perSourceInfoData = cache[moduleSourceInfo.module] ?: return
val dataForSourceInfo = perSourceInfoData[moduleSourceInfo] ?: return
dataForSourceInfo.clear()
}
private fun checkPendingChanges() = synchronized(this) {
if (pendingVFileChanges.size + pendingKtFileChanges.size >= FULL_DROP_THRESHOLD) {
onTooComplexChange()
} else {
pendingVFileChanges.processPending { event ->
val vfile = event.file ?: return@processPending
// When VirtualFile !isValid (deleted for example), it impossible to use getModuleInfoByVirtualFile
// For directory we must check both is it in some sourceRoot, and is it contains some sourceRoot
if (vfile.isDirectory || !vfile.isValid) {
for ((module, data) in cache) {
val sourceRootUrls = module.rootManager.sourceRootUrls
if (sourceRootUrls.any { url ->
vfile.containedInOrContains(url)
}) {
LOG.debugIfEnabled(project) { "Invalidated cache for $module" }
data.clear()
}
}
} else {
val infoByVirtualFile = ModuleInfoProvider.getInstance(project).firstOrNull(vfile)
if (infoByVirtualFile == null || infoByVirtualFile !is ModuleSourceInfo) {
LOG.debugIfEnabled(project) { "Skip $vfile as it has mismatched ModuleInfo=$infoByVirtualFile" }
}
(infoByVirtualFile as? ModuleSourceInfo)?.let {
invalidateCacheForModuleSourceInfo(it)
}
}
implicitPackagePrefixCache.update(event)
}
pendingKtFileChanges.processPending { file ->
if (file.virtualFile != null && file.virtualFile !in projectScope) {
LOG.debugIfEnabled(project) {
"Skip $file without vFile, or not in scope: ${file.virtualFile?.let { it !in projectScope }}"
}
return@processPending
}
val nullableModuleInfo = file.moduleInfoOrNull
(nullableModuleInfo as? ModuleSourceInfo)?.let { invalidateCacheForModuleSourceInfo(it) }
if (nullableModuleInfo == null || nullableModuleInfo !is ModuleSourceInfo) {
LOG.debugIfEnabled(project) { "Skip $file as it has mismatched ModuleInfo=$nullableModuleInfo" }
}
implicitPackagePrefixCache.update(file)
}
}
}
private inline fun <T> MutableCollection<T>.processPending(crossinline body: (T) -> Unit) {
this.removeIf { value ->
try {
body(value)
} catch (pce: ProcessCanceledException) {
throw pce
} catch (exc: Exception) {
// Log and proceed. Otherwise pending object processing won't be cleared and exception will be thrown forever.
LOG.error(exc)
}
return@removeIf true
}
}
private fun VirtualFile.containedInOrContains(root: String) =
(VfsUtilCore.isEqualOrAncestor(url, root)
|| isDirectory && VfsUtilCore.isEqualOrAncestor(root, url))
fun packageExists(packageFqName: FqName, moduleInfo: ModuleSourceInfo): Boolean {
val module = moduleInfo.module
checkPendingChanges()
val perSourceInfoCache = cache.getOrPut(module) {
if (useStrongMapForCaching) ConcurrentHashMap() else CollectionFactory.createConcurrentSoftMap()
}
val cacheForCurrentModuleInfo = perSourceInfoCache.getOrPut(moduleInfo) {
if (useStrongMapForCaching) ConcurrentHashMap() else CollectionFactory.createConcurrentSoftMap()
}
return try {
cacheForCurrentModuleInfo.getOrPut(packageFqName) {
val packageExists = KotlinPackageIndexUtils.packageExists(packageFqName, moduleInfo.contentScope)
LOG.debugIfEnabled(project) { "Computed cache value for $packageFqName in $moduleInfo is $packageExists" }
packageExists
}
} catch (e: IndexNotReadyException) {
DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode(ThrowableComputable {
KotlinPackageIndexUtils.packageExists(packageFqName, moduleInfo.contentScope)
})
}
}
fun getImplicitPackagePrefix(sourceRoot: VirtualFile): FqName {
checkPendingChanges()
return implicitPackagePrefixCache.getPrefix(sourceRoot)
}
override fun dispose() {
clear()
}
companion object {
const val FULL_DROP_THRESHOLD = 1000
private val LOG = Logger.getInstance(this::class.java)
fun getInstance(project: Project): PerModulePackageCacheService = project.service()
var Project.DEBUG_LOG_ENABLE_PerModulePackageCache: Boolean
by NotNullableUserDataProperty<Project, Boolean>(Key.create("debug.PerModulePackageCache"), false)
}
class PackageCacheBulkFileListener(private val project: Project) : BulkFileListener {
override fun before(events: MutableList<out VFileEvent>) = onEvents(events, false)
override fun after(events: List<VFileEvent>) = onEvents(events, true)
private fun isRelevant(event: VFileEvent): Boolean = when (event) {
is VFilePropertyChangeEvent -> false
is VFileCreateEvent -> true
is VFileMoveEvent -> true
is VFileDeleteEvent -> true
is VFileContentChangeEvent -> true
is VFileCopyEvent -> true
else -> {
LOG.warn("Unknown vfs event: ${event.javaClass}")
false
}
}
private fun onEvents(events: List<VFileEvent>, isAfter: Boolean) {
val service = getInstance(project)
val fileManager = PsiManagerEx.getInstanceEx(project).fileManager
if (events.size >= FULL_DROP_THRESHOLD) {
service.onTooComplexChange()
} else {
events.asSequence()
.filter(::isRelevant)
.filter {
(it.isValid || it !is VFileCreateEvent) && it.file != null
}
.filter {
val vFile = it.file!!
vFile.isDirectory || vFile.isKotlinFileType()
}
.filter {
// It expected that content change events will be duplicated with more precise PSI events and processed
// in KotlinPackageStatementPsiTreeChangePreprocessor, but events might have been missing if PSI view provider
// is absent.
if (it is VFileContentChangeEvent) {
isAfter && fileManager.findCachedViewProvider(it.file) == null
} else {
true
}
}
.filter {
when (val origin = it.requestor) {
is Project -> origin == project
is PsiManager -> origin.project == project
else -> true
}
}
.forEach { event -> service.notifyPackageChange(event) }
}
}
}
class PackageCacheModuleRootListener(private val project: Project) : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) {
getInstance(project).onTooComplexChange()
}
}
}
private fun Logger.debugIfEnabled(project: Project, withCurrentTrace: Boolean = false, message: () -> String) {
if (isUnitTestMode() && project.DEBUG_LOG_ENABLE_PerModulePackageCache) {
val msg = message()
if (withCurrentTrace) {
val e = Exception().apply { fillInStackTrace() }
this.debug(msg, e)
} else {
this.debug(msg)
}
}
} | apache-2.0 | bb080c9026298b13f8fbfdc6030ff9f4 | 41.729858 | 136 | 0.635628 | 5.297004 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/code-insight/utils/src/org/jetbrains/kotlin/idea/codeinsight/utils/KotlinPsiUtils.kt | 1 | 10186 | // 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.codeinsight.utils
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.IElementType
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.idea.base.psi.deleteBody
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.utils.NegatedBinaryExpressionSimplificationUtils.negate
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.StandardClassIds
import org.jetbrains.kotlin.parsing.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierTypeOrDefault
fun KtContainerNode.getControlFlowElementDescription(): String? {
when (node.elementType) {
KtNodeTypes.THEN -> return "if"
KtNodeTypes.ELSE -> return "else"
KtNodeTypes.BODY -> {
when (parent) {
is KtWhileExpression -> return "while"
is KtDoWhileExpression -> return "do...while"
is KtForExpression -> return "for"
}
}
}
return null
}
/**
* Returns whether the property accessor is a redundant getter or not.
* TODO: We place this function in kotlin.code-insight.utils because it looks specific for redundant-getter-inspection.
* However, if we find some cases later that need this function for a general-purpose, we should move it to kotlin.base.psi.
*/
fun KtPropertyAccessor.isRedundantGetter(): Boolean {
if (!isGetter) return false
val expression = bodyExpression ?: return canBeCompletelyDeleted()
if (expression.isBackingFieldReferenceTo(property)) return true
if (expression is KtBlockExpression) {
val statement = expression.statements.singleOrNull() ?: return false
val returnExpression = statement as? KtReturnExpression ?: return false
return returnExpression.returnedExpression?.isBackingFieldReferenceTo(property) == true
}
return false
}
fun KtExpression.isBackingFieldReferenceTo(property: KtProperty) =
this is KtNameReferenceExpression
&& text == KtTokens.FIELD_KEYWORD.value
&& property.isAncestor(this)
fun KtPropertyAccessor.canBeCompletelyDeleted(): Boolean {
if (modifierList == null) return true
if (annotationEntries.isNotEmpty()) return false
if (hasModifier(KtTokens.EXTERNAL_KEYWORD)) return false
return visibilityModifierTypeOrDefault() == property.visibilityModifierTypeOrDefault()
}
fun removeRedundantGetter(getter: KtPropertyAccessor) {
val property = getter.property
val accessorTypeReference = getter.returnTypeReference
if (accessorTypeReference != null && property.typeReference == null && property.initializer == null) {
property.typeReference = accessorTypeReference
}
if (getter.canBeCompletelyDeleted()) {
getter.delete()
} else {
getter.deleteBody()
}
}
fun removeProperty(ktProperty: KtProperty) {
val initializer = ktProperty.initializer
if (initializer != null && initializer !is KtConstantExpression) {
val commentSaver = CommentSaver(ktProperty)
val replaced = ktProperty.replace(initializer)
commentSaver.restore(replaced)
} else {
ktProperty.delete()
}
}
/**
* A function that returns whether this KtParameter is a parameter of a setter or not.
*
* Since the parent of a KtParameter is KtParameterList and the parent of KtParameterList is the function or
* the property accessor, this function checks whether `parent.parent` of KtParameter is a setter or not.
*/
val KtParameter.isSetterParameter: Boolean
get() = (parent.parent as? KtPropertyAccessor)?.isSetter == true
fun KtPropertyAccessor.isRedundantSetter(): Boolean {
if (!isSetter) return false
val expression = bodyExpression ?: return canBeCompletelyDeleted()
if (expression is KtBlockExpression) {
val statement = expression.statements.singleOrNull() ?: return false
val parameter = valueParameters.singleOrNull() ?: return false
val binaryExpression = statement as? KtBinaryExpression ?: return false
return binaryExpression.operationToken == KtTokens.EQ
&& binaryExpression.left?.isBackingFieldReferenceTo(property) == true
&& binaryExpression.right?.mainReference?.resolve() == parameter
}
return false
}
fun removeRedundantSetter(setter: KtPropertyAccessor) {
if (setter.canBeCompletelyDeleted()) {
setter.delete()
} else {
setter.deleteBody()
}
}
fun KtExpression.negate(reformat: Boolean = true, isBooleanExpression: (KtExpression) -> Boolean): KtExpression {
val specialNegation = specialNegation(reformat, isBooleanExpression)
if (specialNegation != null) return specialNegation
return KtPsiFactory(this).createExpressionByPattern(pattern = "!$0", this, reformat = reformat)
}
private fun KtExpression.specialNegation(reformat: Boolean, isBooleanExpression: (KtExpression) -> Boolean): KtExpression? {
val factory = KtPsiFactory(this)
when (this) {
is KtPrefixExpression -> {
if (operationReference.getReferencedName() == "!") {
val baseExpression = baseExpression
if (baseExpression != null) {
if (isBooleanExpression(baseExpression)) {
return KtPsiUtil.safeDeparenthesize(baseExpression)
}
}
}
}
is KtBinaryExpression -> {
val operator = operationToken
if (operator !in NEGATABLE_OPERATORS) return null
val left = left ?: return null
val right = right ?: return null
return factory.createExpressionByPattern(
"$0 $1 $2", left, getNegatedOperatorText(operator), right,
reformat = reformat
)
}
is KtIsExpression -> {
return factory.createExpressionByPattern(
"$0 $1 $2",
leftHandSide,
if (isNegated) "is" else "!is",
typeReference ?: return null,
reformat = reformat
)
}
is KtConstantExpression -> {
return when (text) {
"true" -> factory.createExpression("false")
"false" -> factory.createExpression("true")
else -> null
}
}
}
return null
}
private val NEGATABLE_OPERATORS = setOf(
KtTokens.EQEQ, KtTokens.EXCLEQ, KtTokens.EQEQEQ,
KtTokens.EXCLEQEQEQ, KtTokens.IS_KEYWORD, KtTokens.NOT_IS, KtTokens.IN_KEYWORD,
KtTokens.NOT_IN, KtTokens.LT, KtTokens.LTEQ, KtTokens.GT, KtTokens.GTEQ
)
private fun getNegatedOperatorText(token: IElementType): String {
val negatedOperator = token.negate() ?: throw IllegalArgumentException("The token $token does not have a negated equivalent.")
return negatedOperator.value
}
fun KtDotQualifiedExpression.getLeftMostReceiverExpression(): KtExpression =
(receiverExpression as? KtDotQualifiedExpression)?.getLeftMostReceiverExpression() ?: receiverExpression
fun KtDotQualifiedExpression.replaceFirstReceiver(
factory: KtPsiFactory,
newReceiver: KtExpression,
safeAccess: Boolean = false
): KtExpression {
val replacedExpression = when {
safeAccess -> this.replaced(factory.createExpressionByPattern("$0?.$1", receiverExpression, selectorExpression!!))
else -> this
} as KtQualifiedExpression
when (val receiver = replacedExpression.receiverExpression) {
is KtDotQualifiedExpression -> receiver.replace(receiver.replaceFirstReceiver(factory, newReceiver, safeAccess))
else -> receiver.replace(newReceiver)
}
return replacedExpression
}
/**
* Checks if there are any annotations in type or its type arguments.
*/
fun KtTypeReference.isAnnotatedDeep(): Boolean {
return this.anyDescendantOfType<KtAnnotationEntry>()
}
/**
* A best effort way to get the class id of expression's type without resolve.
*/
fun KtConstantExpression.getClassId(): ClassId? {
val convertedText: Any? = when (elementType) {
KtNodeTypes.INTEGER_CONSTANT, KtNodeTypes.FLOAT_CONSTANT -> when {
hasIllegalUnderscore(text, elementType) -> return null
else -> parseNumericLiteral(text, elementType)
}
KtNodeTypes.BOOLEAN_CONSTANT -> parseBoolean(text)
else -> null
}
return when (elementType) {
KtNodeTypes.INTEGER_CONSTANT -> when {
convertedText !is Long -> null
hasUnsignedLongSuffix(text) -> StandardClassIds.ULong
hasLongSuffix(text) -> StandardClassIds.Long
hasUnsignedSuffix(text) -> if (convertedText.toULong() > UInt.MAX_VALUE || convertedText.toULong() < UInt.MIN_VALUE) {
StandardClassIds.ULong
} else {
StandardClassIds.UInt
}
else -> if (convertedText > Int.MAX_VALUE || convertedText < Int.MIN_VALUE) {
StandardClassIds.Long
} else {
StandardClassIds.Int
}
}
KtNodeTypes.FLOAT_CONSTANT -> if (convertedText is Float) StandardClassIds.Float else StandardClassIds.Double
KtNodeTypes.CHARACTER_CONSTANT -> StandardClassIds.Char
KtNodeTypes.BOOLEAN_CONSTANT -> StandardClassIds.Boolean
else -> null
}
}
fun KtPsiFactory.appendSemicolonBeforeLambdaContainingElement(element: PsiElement) {
val previousElement = KtPsiUtil.skipSiblingsBackwardByPredicate(element) {
it!!.node.elementType in KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET
}
if (previousElement != null && previousElement is KtExpression) {
previousElement.parent.addAfter(createSemicolon(), previousElement)
}
}
| apache-2.0 | 04c46f3f6ac3c4193907cd548450bec6 | 38.789063 | 130 | 0.688789 | 5.121166 | false | false | false | false |
siosio/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/actions/ReaderModeListener.kt | 1 | 3958 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.actions
import com.intellij.application.options.colors.ReaderModeStatsCollector
import com.intellij.codeInsight.actions.ReaderModeSettings.Companion.applyReaderMode
import com.intellij.codeInsight.actions.ReaderModeSettingsListener.Companion.applyToAllEditors
import com.intellij.ide.DataManager
import com.intellij.ide.IdeBundle
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.colors.impl.AppEditorFontOptions
import com.intellij.openapi.editor.colors.impl.FontPreferencesImpl
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.options.ex.Settings
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.Disposer
import com.intellij.ui.HyperlinkLabel
import com.intellij.util.messages.Topic
import com.intellij.util.ui.UIUtil
import java.beans.PropertyChangeListener
import java.util.*
import javax.swing.event.HyperlinkListener
interface ReaderModeListener : EventListener {
fun modeChanged(project: Project)
}
class ReaderModeSettingsListener : ReaderModeListener {
companion object {
@Topic.ProjectLevel
@JvmStatic
val TOPIC = Topic(ReaderModeListener::class.java, Topic.BroadcastDirection.NONE)
fun applyToAllEditors(project: Project) {
FileEditorManager.getInstance(project).allEditors.forEach {
if (it !is TextEditor) return
applyReaderMode(project, it.editor, it.file, fileIsOpenAlready = true)
}
EditorFactory.getInstance().allEditors.forEach {
if (it !is EditorImpl) return
applyReaderMode(project, it, FileDocumentManager.getInstance().getFile(it.document),
fileIsOpenAlready = true)
}
}
fun createReaderModeComment() = HyperlinkLabel().apply {
setTextWithHyperlink(IdeBundle.message("checkbox.also.in.reader.mode"))
font = UIUtil.getFont(UIUtil.FontSize.SMALL, font)
foreground = UIUtil.getLabelFontColor(UIUtil.FontColor.BRIGHTER)
addHyperlinkListener(HyperlinkListener {
DataManager.getInstance().dataContextFromFocusAsync.onSuccess { context ->
context?.let { dataContext ->
Settings.KEY.getData(dataContext)?.let { settings ->
settings.select(settings.find("editor.reader.mode"))
ReaderModeStatsCollector.logSeeAlsoNavigation()
}
}
}
})
}
}
override fun modeChanged(project: Project) = applyToAllEditors(project)
}
internal class ReaderModeEditorSettingsListener : StartupActivity, DumbAware {
override fun runActivity(project: Project) {
val propertyChangeListener = PropertyChangeListener { event ->
when (event.propertyName) {
EditorSettingsExternalizable.PROP_DOC_COMMENT_RENDERING -> {
ReaderModeSettings.instance(project).showRenderedDocs = EditorSettingsExternalizable.getInstance().isDocCommentRenderingEnabled
applyToAllEditors(project)
}
}
}
EditorSettingsExternalizable.getInstance().addPropertyChangeListener(propertyChangeListener, project)
val fontPreferences = AppEditorFontOptions.getInstance().fontPreferences as FontPreferencesImpl
fontPreferences.changeListener = Runnable {
fontPreferences.changeListener
ReaderModeSettings.instance(project).showLigatures = fontPreferences.useLigatures()
applyToAllEditors(project)
}
Disposer.register(project) { fontPreferences.changeListener = null }
}
} | apache-2.0 | 83104b9cc7c22561311344c36e934ce8 | 41.569892 | 140 | 0.771097 | 4.856442 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/util/ProjectRootsUtil.kt | 1 | 12462 | // 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.util
import com.intellij.ide.highlighter.ArchiveFileType
import com.intellij.ide.highlighter.JavaClassFileType
import com.intellij.ide.scratch.ScratchUtil
import com.intellij.injected.editor.VirtualFileWindow
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModulePointerManager
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.FileIndex
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileSystemItem
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.KotlinModuleFileType
import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager
import org.jetbrains.kotlin.idea.decompiler.builtIns.KotlinBuiltInFileType
import org.jetbrains.kotlin.idea.decompiler.js.KotlinJavaScriptMetaFileType
import org.jetbrains.kotlin.idea.klib.KlibMetaFileType
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.scripting.definitions.findScriptDefinition
import kotlin.script.experimental.api.ScriptAcceptedLocation
import kotlin.script.experimental.api.ScriptCompilationConfiguration
import kotlin.script.experimental.api.acceptedLocations
import kotlin.script.experimental.api.ide
abstract class KotlinBinaryExtension(val fileType: FileType) {
companion object {
val EP_NAME: ExtensionPointName<KotlinBinaryExtension> =
ExtensionPointName.create<KotlinBinaryExtension>("org.jetbrains.kotlin.binaryExtension")
val kotlinBinaries: List<FileType> by lazy(LazyThreadSafetyMode.PUBLICATION) {
EP_NAME.extensions.map { it.fileType }
}
}
}
class JavaClassBinary : KotlinBinaryExtension(JavaClassFileType.INSTANCE)
class KotlinBuiltInBinary : KotlinBinaryExtension(KotlinBuiltInFileType)
class KotlinModuleBinary : KotlinBinaryExtension(KotlinModuleFileType.INSTANCE)
class KotlinJsMetaBinary : KotlinBinaryExtension(KotlinJavaScriptMetaFileType)
class KlibMetaBinary : KotlinBinaryExtension(KlibMetaFileType)
fun FileType.isKotlinBinary(): Boolean = this in KotlinBinaryExtension.kotlinBinaries
fun FileIndex.isInSourceContentWithoutInjected(file: VirtualFile): Boolean {
return file !is VirtualFileWindow && isInSourceContent(file)
}
fun VirtualFile.getSourceRoot(project: Project): VirtualFile? = ProjectRootManager.getInstance(project).fileIndex.getSourceRootForFile(this)
val PsiFileSystemItem.sourceRoot: VirtualFile?
get() = virtualFile?.getSourceRoot(project)
object ProjectRootsUtil {
@Suppress("DEPRECATION")
@JvmStatic
fun isInContent(
project: Project,
file: VirtualFile,
includeProjectSource: Boolean,
includeLibrarySource: Boolean,
includeLibraryClasses: Boolean,
includeScriptDependencies: Boolean,
includeScriptsOutsideSourceRoots: Boolean,
fileIndex: ProjectFileIndex = ProjectFileIndex.SERVICE.getInstance(project)
): Boolean {
ProgressManager.checkCanceled()
val fileType = FileTypeManager.getInstance().getFileTypeByFileName(file.nameSequence)
val kotlinExcludeLibrarySources = fileType == KotlinFileType.INSTANCE && !includeLibrarySource && !includeScriptsOutsideSourceRoots
if (kotlinExcludeLibrarySources && !includeProjectSource) return false
if (fileIndex.isInSourceContentWithoutInjected(file)) return includeProjectSource
if (kotlinExcludeLibrarySources) return false
val scriptDefinition = file.findScriptDefinition(project)
val scriptScope = scriptDefinition?.compilationConfiguration?.get(ScriptCompilationConfiguration.ide.acceptedLocations)
if (scriptScope != null) {
val includeAll = scriptScope.contains(ScriptAcceptedLocation.Everywhere)
|| scriptScope.contains(ScriptAcceptedLocation.Project)
|| ScratchUtil.isScratch(file)
val includeAllOrScriptLibraries = includeAll || scriptScope.contains(ScriptAcceptedLocation.Libraries)
return isInContentWithoutScriptDefinitionCheck(
project,
file,
fileType,
includeProjectSource && (
includeAll
|| scriptScope.contains(ScriptAcceptedLocation.Sources)
|| scriptScope.contains(ScriptAcceptedLocation.Tests)
),
includeLibrarySource && includeAllOrScriptLibraries,
includeLibraryClasses && includeAllOrScriptLibraries,
includeScriptDependencies && includeAllOrScriptLibraries,
includeScriptsOutsideSourceRoots && includeAll,
fileIndex
)
}
return isInContentWithoutScriptDefinitionCheck(
project,
file,
fileType,
includeProjectSource,
includeLibrarySource,
includeLibraryClasses,
includeScriptDependencies,
false,
fileIndex
)
}
@Suppress("DEPRECATION")
private fun isInContentWithoutScriptDefinitionCheck(
project: Project,
file: VirtualFile,
fileType: FileType,
includeProjectSource: Boolean,
includeLibrarySource: Boolean,
includeLibraryClasses: Boolean,
includeScriptDependencies: Boolean,
includeScriptsOutsideSourceRoots: Boolean,
fileIndex: ProjectFileIndex = ProjectFileIndex.SERVICE.getInstance(project)
): Boolean {
if (includeScriptsOutsideSourceRoots) {
if (ProjectRootManager.getInstance(project).fileIndex.isInContent(file) || ScratchUtil.isScratch(file)) {
return true
}
return file.findScriptDefinition(project)
?.compilationConfiguration
?.get(ScriptCompilationConfiguration.ide.acceptedLocations)
?.contains(ScriptAcceptedLocation.Everywhere) == true
}
if (!includeLibraryClasses && !includeLibrarySource) return false
// NOTE: the following is a workaround for cases when class files are under library source roots and source files are under class roots
val canContainClassFiles = fileType == ArchiveFileType.INSTANCE || file.isDirectory
val isBinary = fileType.isKotlinBinary()
val scriptConfigurationManager = if (includeScriptDependencies) ScriptConfigurationManager.getInstance(project) else null
if (includeLibraryClasses && (isBinary || canContainClassFiles)) {
if (fileIndex.isInLibraryClasses(file)) return true
if (scriptConfigurationManager?.getAllScriptsDependenciesClassFilesScope()?.contains(file) == true) return true
}
if (includeLibrarySource && !isBinary) {
if (fileIndex.isInLibrarySource(file)) return true
if (scriptConfigurationManager?.getAllScriptDependenciesSourcesScope()?.contains(file) == true &&
!fileIndex.isInSourceContentWithoutInjected(file)
) {
return true
}
}
return false
}
@JvmStatic
fun isInContent(
element: PsiElement,
includeProjectSource: Boolean,
includeLibrarySource: Boolean,
includeLibraryClasses: Boolean,
includeScriptDependencies: Boolean,
includeScriptsOutsideSourceRoots: Boolean
): Boolean = runReadAction {
val virtualFile = when (element) {
is PsiDirectory -> element.virtualFile
else -> element.containingFile?.virtualFile
} ?: return@runReadAction false
val project = element.project
return@runReadAction isInContent(
project,
virtualFile,
includeProjectSource,
includeLibrarySource,
includeLibraryClasses,
includeScriptDependencies,
includeScriptsOutsideSourceRoots
)
}
@JvmOverloads
@JvmStatic
fun isInProjectSource(element: PsiElement, includeScriptsOutsideSourceRoots: Boolean = false): Boolean {
return isInContent(
element,
includeProjectSource = true,
includeLibrarySource = false,
includeLibraryClasses = false,
includeScriptDependencies = false,
includeScriptsOutsideSourceRoots = includeScriptsOutsideSourceRoots
)
}
@JvmOverloads
@JvmStatic
fun isProjectSourceFile(project: Project, file: VirtualFile, includeScriptsOutsideSourceRoots: Boolean = false): Boolean {
return isInContent(
project,
file,
includeProjectSource = true,
includeLibrarySource = false,
includeLibraryClasses = false,
includeScriptDependencies = false,
includeScriptsOutsideSourceRoots = includeScriptsOutsideSourceRoots
)
}
@JvmOverloads
@JvmStatic
fun isInProjectOrLibSource(element: PsiElement, includeScriptsOutsideSourceRoots: Boolean = false): Boolean {
return isInContent(
element,
includeProjectSource = true,
includeLibrarySource = true,
includeLibraryClasses = false,
includeScriptDependencies = false,
includeScriptsOutsideSourceRoots = includeScriptsOutsideSourceRoots
)
}
@JvmStatic
fun isInProjectOrLibraryContent(element: PsiElement): Boolean {
return isInContent(
element,
includeProjectSource = true,
includeLibrarySource = true,
includeLibraryClasses = true,
includeScriptDependencies = true,
includeScriptsOutsideSourceRoots = false
)
}
@JvmStatic
fun isInProjectOrLibraryClassFile(element: PsiElement): Boolean {
return isInContent(
element,
includeProjectSource = true,
includeLibrarySource = false,
includeLibraryClasses = true,
includeScriptDependencies = false,
includeScriptsOutsideSourceRoots = false
)
}
@JvmStatic
fun isLibraryClassFile(project: Project, file: VirtualFile): Boolean {
return isInContent(
project,
file,
includeProjectSource = false,
includeLibrarySource = false,
includeLibraryClasses = true,
includeScriptDependencies = true,
includeScriptsOutsideSourceRoots = false
)
}
@JvmStatic
fun isLibrarySourceFile(project: Project, file: VirtualFile): Boolean {
return isInContent(
project,
file,
includeProjectSource = false,
includeLibrarySource = true,
includeLibraryClasses = false,
includeScriptDependencies = true,
includeScriptsOutsideSourceRoots = false
)
}
@JvmStatic
fun isLibraryFile(project: Project, file: VirtualFile): Boolean {
return isInContent(
project,
file,
includeProjectSource = false,
includeLibrarySource = true,
includeLibraryClasses = true,
includeScriptDependencies = true,
includeScriptsOutsideSourceRoots = false
)
}
}
val Module.rootManager: ModuleRootManager
get() = ModuleRootManager.getInstance(this)
val Module.sourceRoots: Array<VirtualFile>
get() = rootManager.sourceRoots
val PsiElement.module: Module?
get() = ModuleUtilCore.findModuleForPsiElement(this)
fun VirtualFile.findModule(project: Project) = ModuleUtilCore.findModuleForFile(this, project)
fun Module.createPointer() =
ModulePointerManager.getInstance(project).create(this) | apache-2.0 | 120f27fd371095f780dd5671e4f265b8 | 38.817891 | 158 | 0.69732 | 5.903363 | false | false | false | false |
JetBrains/kotlin-native | Interop/Runtime/src/main/kotlin/kotlinx/cinterop/StableRef.kt | 2 | 2596 | /*
* Copyright 2010-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 kotlinx.cinterop
@Deprecated("Use StableRef<T> instead", ReplaceWith("StableRef<T>"), DeprecationLevel.ERROR)
typealias StableObjPtr = StableRef<*>
/**
* This class provides a way to create a stable handle to any Kotlin object.
* After [converting to CPointer][asCPointer] it can be safely passed to native code e.g. to be received
* in a Kotlin callback.
*
* Any [StableRef] should be manually [disposed][dispose]
*/
@Suppress("NON_PUBLIC_PRIMARY_CONSTRUCTOR_OF_INLINE_CLASS")
public inline class StableRef<out T : Any> @PublishedApi internal constructor(
private val stablePtr: COpaquePointer
) {
companion object {
/**
* Creates a handle for given object.
*/
fun <T : Any> create(any: T) = StableRef<T>(createStablePointer(any))
/**
* Creates [StableRef] from given raw value.
*
* @param value must be a [value] of some [StableRef]
*/
@Deprecated("Use CPointer<*>.asStableRef<T>() instead", ReplaceWith("ptr.asStableRef<T>()"),
DeprecationLevel.ERROR)
fun fromValue(value: COpaquePointer) = value.asStableRef<Any>()
}
@Deprecated("Use .asCPointer() instead", ReplaceWith("this.asCPointer()"), DeprecationLevel.ERROR)
val value: COpaquePointer get() = this.asCPointer()
/**
* Converts the handle to C pointer.
* @see [asStableRef]
*/
fun asCPointer(): COpaquePointer = this.stablePtr
/**
* Disposes the handle. It must not be used after that.
*/
fun dispose() {
disposeStablePointer(this.stablePtr)
}
/**
* Returns the object this handle was [created][StableRef.create] for.
*/
@Suppress("UNCHECKED_CAST")
fun get() = derefStablePointer(this.stablePtr) as T
}
/**
* Converts to [StableRef] this opaque pointer produced by [StableRef.asCPointer].
*/
inline fun <reified T : Any> CPointer<*>.asStableRef(): StableRef<T> = StableRef<T>(this).also { it.get() }
| apache-2.0 | 3e4c109a2a9f8a97b6070083771dc450 | 32.714286 | 107 | 0.671803 | 4.200647 | false | false | false | false |
tribbloid/spookystuff | buildSrc/src/main/kotlin/Versions.kt | 1 | 837 | import org.gradle.api.Project
class Versions(self: Project) {
// TODO : how to group them?
val projectGroup = "com.tribbloids.spookstuff"
val projectRootID = "spookstuff"
val projectV = "0.8.0-SNAPSHOT"
val projectVMajor = projectV.removeSuffix("-SNAPSHOT")
// val projectVComposition = projectV.split('-')
val scalaGroup: String = self.properties.get("scalaGroup").toString()
val scalaV: String = self.properties.get("scalaVersion").toString()
protected val scalaVParts = scalaV.split('.')
val scalaBinaryV: String = scalaVParts.subList(0, 2).joinToString(".")
val scalaMinorV: String = scalaVParts[2]
val sparkV: String = self.properties.get("sparkVersion").toString()
val scalaTestV: String = "3.2.10"
val tikaV: String = "2.4.1"
val jacksonV: String = "2.9.10"
}
| apache-2.0 | 6d702b3d7c1a531df515758ba9865bf4 | 27.862069 | 74 | 0.681004 | 3.473029 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/maven/src/org/jetbrains/kotlin/idea/maven/configuration/KotlinMavenConfigurator.kt | 1 | 13760 | // 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.maven.configuration
import com.intellij.codeInsight.CodeInsightUtilCore
import com.intellij.codeInsight.daemon.impl.quickfix.OrderEntryFix
import com.intellij.ide.actions.OpenFileAction
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.DependencyScope
import com.intellij.openapi.roots.ExternalLibraryDescriptor
import com.intellij.openapi.roots.JavaProjectModelModificationService
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.vfs.WritingAccessProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.psi.search.FileTypeIndex
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.xml.XmlFile
import org.jetbrains.idea.maven.dom.MavenDomUtil
import org.jetbrains.idea.maven.dom.model.MavenDomPlugin
import org.jetbrains.idea.maven.model.MavenId
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.utils.MavenArtifactScope
import org.jetbrains.kotlin.config.ApiVersion
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.configuration.*
import org.jetbrains.kotlin.idea.facet.getRuntimeLibraryVersion
import org.jetbrains.kotlin.idea.facet.toApiVersion
import org.jetbrains.kotlin.idea.framework.ui.ConfigureDialogWithModulesAndVersion
import org.jetbrains.kotlin.idea.maven.*
import org.jetbrains.kotlin.idea.quickfix.ChangeGeneralLanguageFeatureSupportFix
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.versions.LibraryJarDescriptor
abstract class KotlinMavenConfigurator
protected constructor(
private val testArtifactId: String?,
private val addJunit: Boolean,
override val name: String,
override val presentableText: String
) : KotlinProjectConfigurator {
override fun getStatus(moduleSourceRootGroup: ModuleSourceRootGroup): ConfigureKotlinStatus {
val module = moduleSourceRootGroup.baseModule
if (module.getBuildSystemType() != BuildSystemType.Maven)
return ConfigureKotlinStatus.NON_APPLICABLE
val psi = runReadAction { findModulePomFile(module) }
if (psi == null
|| !psi.isValid
|| psi !is XmlFile
|| psi.virtualFile == null
) {
return ConfigureKotlinStatus.BROKEN
}
if (isKotlinModule(module)) {
return runReadAction { checkKotlinPlugin(module) }
}
return ConfigureKotlinStatus.CAN_BE_CONFIGURED
}
private fun checkKotlinPlugin(module: Module): ConfigureKotlinStatus {
val psi = findModulePomFile(module) as? XmlFile ?: return ConfigureKotlinStatus.BROKEN
val pom = PomFile.forFileOrNull(psi) ?: return ConfigureKotlinStatus.NON_APPLICABLE
if (hasKotlinPlugin(pom)) {
return ConfigureKotlinStatus.CONFIGURED
}
val mavenProjectsManager = MavenProjectsManager.getInstance(module.project)
val mavenProject = mavenProjectsManager.findProject(module) ?: return ConfigureKotlinStatus.BROKEN
val kotlinPluginId = kotlinPluginId(null)
val kotlinPlugin = mavenProject.plugins.find { it.mavenId.equals(kotlinPluginId.groupId, kotlinPluginId.artifactId) }
?: return ConfigureKotlinStatus.CAN_BE_CONFIGURED
if (kotlinPlugin.executions.any { it.goals.any(this::isRelevantGoal) }) {
return ConfigureKotlinStatus.CONFIGURED
}
return ConfigureKotlinStatus.CAN_BE_CONFIGURED
}
private fun hasKotlinPlugin(pom: PomFile): Boolean {
val plugin = pom.findPlugin(kotlinPluginId(null)) ?: return false
return plugin.executions.executions.any {
it.goals.goals.any { isRelevantGoal(it.stringValue ?: "") }
}
}
override fun configure(project: Project, excludeModules: Collection<Module>) {
val dialog = ConfigureDialogWithModulesAndVersion(project, this, excludeModules, getMinimumSupportedVersion())
dialog.show()
if (!dialog.isOK) return
WriteCommandAction.runWriteCommandAction(project) {
val collector = createConfigureKotlinNotificationCollector(project)
for (module in excludeMavenChildrenModules(project, dialog.modulesToConfigure)) {
val file = findModulePomFile(module)
if (file != null && canConfigureFile(file)) {
configureModule(module, file, dialog.kotlinVersion, collector)
OpenFileAction.openFile(file.virtualFile, project)
} else {
showErrorMessage(project, KotlinMavenBundle.message("error.cant.find.pom.for.module", module.name))
}
}
collector.showNotification()
}
}
protected open fun getMinimumSupportedVersion() = "1.0.0"
protected abstract fun isKotlinModule(module: Module): Boolean
protected abstract fun isRelevantGoal(goalName: String): Boolean
protected abstract fun createExecutions(pomFile: PomFile, kotlinPlugin: MavenDomPlugin, module: Module)
protected abstract fun getStdlibArtifactId(module: Module, version: String): String
open fun configureModule(module: Module, file: PsiFile, version: String, collector: NotificationMessageCollector): Boolean =
changePomFile(module, file, version, collector)
private fun changePomFile(
module: Module,
file: PsiFile,
version: String,
collector: NotificationMessageCollector
): Boolean {
val virtualFile = file.virtualFile ?: error("Virtual file should exists for psi file " + file.name)
val domModel = MavenDomUtil.getMavenDomProjectModel(module.project, virtualFile)
if (domModel == null) {
showErrorMessage(module.project, null)
return false
}
val pom = PomFile.forFileOrNull(file as XmlFile) ?: return false
pom.addProperty(KOTLIN_VERSION_PROPERTY, version)
pom.addDependency(
MavenId(GROUP_ID, getStdlibArtifactId(module, version), "\${$KOTLIN_VERSION_PROPERTY}"),
MavenArtifactScope.COMPILE,
null,
false,
null
)
if (testArtifactId != null) {
pom.addDependency(MavenId(GROUP_ID, testArtifactId, "\${$KOTLIN_VERSION_PROPERTY}"), MavenArtifactScope.TEST, null, false, null)
}
if (addJunit) {
// TODO currently it is always disabled: junit version selection could be shown in the configurator dialog
pom.addDependency(MavenId("junit", "junit", "4.12"), MavenArtifactScope.TEST, null, false, null)
}
val repositoryDescription = getRepositoryForVersion(version)
if (repositoryDescription != null) {
pom.addLibraryRepository(repositoryDescription)
pom.addPluginRepository(repositoryDescription)
}
val plugin = pom.addPlugin(MavenId(GROUP_ID, MAVEN_PLUGIN_ID, "\${$KOTLIN_VERSION_PROPERTY}"))
createExecutions(pom, plugin, module)
configurePlugin(pom, plugin, module, version)
CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement<PsiFile>(file)
collector.addMessage(KotlinMavenBundle.message("file.was.modified", virtualFile.path))
return true
}
protected open fun configurePlugin(pom: PomFile, plugin: MavenDomPlugin, module: Module, version: String) {
}
protected fun createExecution(
pomFile: PomFile,
kotlinPlugin: MavenDomPlugin,
executionId: String,
goalName: String,
module: Module,
isTest: Boolean
) {
pomFile.addKotlinExecution(module, kotlinPlugin, executionId, PomFile.getPhase(false, isTest), isTest, listOf(goalName))
if (hasJavaFiles(module)) {
pomFile.addJavacExecutions(module, kotlinPlugin)
}
}
override fun updateLanguageVersion(
module: Module,
languageVersion: String?,
apiVersion: String?,
requiredStdlibVersion: ApiVersion,
forTests: Boolean
) {
fun doUpdateMavenLanguageVersion(): PsiElement? {
val psi = findModulePomFile(module) as? XmlFile ?: return null
val pom = PomFile.forFileOrNull(psi) ?: return null
return pom.changeLanguageVersion(
languageVersion,
apiVersion
)
}
val runtimeUpdateRequired = getRuntimeLibraryVersion(module)?.let { ApiVersion.parse(it) }?.let { runtimeVersion ->
runtimeVersion < requiredStdlibVersion
} ?: false
if (runtimeUpdateRequired) {
Messages.showErrorDialog(
module.project,
KotlinMavenBundle.message("update.language.version.feature", requiredStdlibVersion),
KotlinMavenBundle.message("update.language.version.title")
)
return
}
val element = doUpdateMavenLanguageVersion()
if (element == null) {
Messages.showErrorDialog(
module.project,
KotlinMavenBundle.message("error.failed.update.pom"),
KotlinMavenBundle.message("update.language.version.title")
)
} else {
OpenFileDescriptor(module.project, element.containingFile.virtualFile, element.textRange.startOffset).navigate(true)
}
}
override fun addLibraryDependency(
module: Module,
element: PsiElement,
library: ExternalLibraryDescriptor,
libraryJarDescriptor: LibraryJarDescriptor,
scope: DependencyScope
) {
val scope = OrderEntryFix.suggestScopeByLocation(module, element)
JavaProjectModelModificationService.getInstance(module.project).addDependency(module, library, scope)
}
override fun changeGeneralFeatureConfiguration(
module: Module,
feature: LanguageFeature,
state: LanguageFeature.State,
forTests: Boolean
) {
val sinceVersion = feature.sinceApiVersion
val messageTitle = ChangeGeneralLanguageFeatureSupportFix.getFixText(feature, state)
if (state != LanguageFeature.State.DISABLED && getRuntimeLibraryVersion(module).toApiVersion() < sinceVersion) {
Messages.showErrorDialog(
module.project,
KotlinMavenBundle.message("update.language.version.feature.support", feature.presentableName, sinceVersion),
messageTitle
)
return
}
val element = changeMavenFeatureConfiguration(
module, feature, state, messageTitle
)
if (element != null) {
OpenFileDescriptor(module.project, element.containingFile.virtualFile, element.textRange.startOffset).navigate(true)
}
}
private fun changeMavenFeatureConfiguration(
module: Module,
feature: LanguageFeature,
state: LanguageFeature.State,
@NlsContexts.DialogTitle messageTitle: String
): PsiElement? {
val psi = findModulePomFile(module) as? XmlFile ?: return null
val pom = PomFile.forFileOrNull(psi) ?: return null
val element = pom.changeFeatureConfiguration(feature, state)
if (element == null) {
Messages.showErrorDialog(
module.project,
KotlinMavenBundle.message("error.failed.update.pom"),
messageTitle
)
}
return element
}
companion object {
const val GROUP_ID = "org.jetbrains.kotlin"
const val MAVEN_PLUGIN_ID = "kotlin-maven-plugin"
private const val KOTLIN_VERSION_PROPERTY = "kotlin.version"
private fun hasJavaFiles(module: Module): Boolean {
return !FileTypeIndex.getFiles(JavaFileType.INSTANCE, GlobalSearchScope.moduleScope(module)).isEmpty()
}
fun findModulePomFile(module: Module): PsiFile? {
val files = MavenProjectsManager.getInstance(module.project).projectsFiles
for (file in files) {
val fileModule = ModuleUtilCore.findModuleForFile(file, module.project)
if (module != fileModule) continue
val psiFile = PsiManager.getInstance(module.project).findFile(file) ?: continue
if (!MavenDomUtil.isProjectFile(psiFile)) continue
return psiFile
}
return null
}
private fun canConfigureFile(file: PsiFile): Boolean {
return WritingAccessProvider.isPotentiallyWritable(file.virtualFile, null)
}
private fun showErrorMessage(project: Project, @NlsContexts.DialogMessage message: String?) {
val cantConfigureAutomatically = KotlinMavenBundle.message("error.cant.configure.maven.automatically")
val seeInstructions = KotlinMavenBundle.message("error.see.installation.instructions")
Messages.showErrorDialog(
project,
"<html>$cantConfigureAutomatically<br/>${if (message != null) "$message</br>" else ""}$seeInstructions</html>",
KotlinMavenBundle.message("configure.title")
)
}
}
}
| apache-2.0 | ba6266bbe6f3906a5f41eec35f8403df | 40.321321 | 158 | 0.684302 | 5.385519 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/KotlinRawStringBackspaceHandler.kt | 6 | 1624 | // 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.editor
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.codeInsight.editorActions.BackspaceHandlerDelegate
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.RangeMarker
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
class KotlinRawStringBackspaceHandler : BackspaceHandlerDelegate() {
private var rangeMarker: RangeMarker? = null
override fun beforeCharDeleted(c: Char, file: PsiFile, editor: Editor) {
rangeMarker = null
if (!CodeInsightSettings.getInstance().AUTOINSERT_PAIR_QUOTE) {
return
}
if (file !is KtFile) {
return
}
val offset = editor.caretModel.offset
val psiElement = file.findElementAt(offset) ?: return
psiElement.parent?.let {
if (it is KtStringTemplateExpression && it.text == "\"\"\"\"\"\"") {
if (editor.caretModel.offset == it.textOffset + 3) {
rangeMarker = editor.document.createRangeMarker(it.textRange)
}
}
}
}
override fun charDeleted(c: Char, file: PsiFile, editor: Editor): Boolean {
rangeMarker?.let {
editor.document.deleteString(it.startOffset, it.endOffset)
rangeMarker = null
return true
}
return false
}
} | apache-2.0 | ea8254ee5d389d540bee9ef695238ae9 | 35.111111 | 158 | 0.66564 | 4.818991 | false | false | false | false |
ThatsNoMoon/KDA | src/main/kotlin/com/thatsnomoon/kda/entities/KEventWaiter.kt | 1 | 5218 | /*
* Copyright 2018 Benjamin Scherer
*
* 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.thatsnomoon.kda.entities
import com.thatsnomoon.kda.globalCoroutineContext
import java.time.Duration
import kotlinx.coroutines.experimental.*
import kotlinx.coroutines.experimental.time.delay
import net.dv8tion.jda.core.JDA
import net.dv8tion.jda.core.events.Event
/**
* Asynchronously waits for JDA events.
*
* This class will primarily be created by a helper function ([awaitEvents][com.thatsnomoon.kda.extensions.awaitEvents] or [awaitMessages][com.thatsnomoon.kda.extensions.awaitMessages]).
*
* This class is similar to a [Deferred], in that it will resolve to a value at some point in time.
* There is also a method to create a Deferred that will resolve to the same result, [asDeferred].
*
* Until this resolves, it will continue to listen for events, adding any events of the correct type that pass the provided predicate to an internal list.
* It will resolve to this internal list after either of these conditions are true:
* 1. The amount of events that have matched the predicate function equals the count parameter
* 2. The amount of time that has passed has exceeded the timeout parameter
*
* @param jda JDA instance to listen from
* @param type Type of event to listen for
* @param count Number of events to listen for before returning
* @param timeout [Duration] to wait for events before timing out (and resolving to an empty list) (default: null, no timeout).
* @param predicate Function to check each event received of the correct type against (default: none, all events of the correct type are returned)
*/
class KEventWaiter<out T: Event>(private val jda: JDA,
private val type: Class<T>,
private val count: Int = 1,
timeout: Duration? = null,
private val predicate: (T) -> Boolean = {true}
): KAsyncEventListener {
private var timeoutJob: Job? = null
private var result: CompletableDeferred<List<T>> = CompletableDeferred()
private var events: List<T> = mutableListOf()
init {
if (count < 1) throw IllegalArgumentException("Count parameter passed to KEventWaiter must be greater than zero")
jda.addEventListener(this)
if (timeout != null) {
timeoutJob = launch(globalCoroutineContext) {
delay(timeout)
result.complete(events)
deregister()
}
}
}
/**
* Internal event listening function.
*/
override suspend fun onEventAsync(event: Event) {
if (type.isInstance(event)) {
try {
@Suppress("UNCHECKED_CAST")
if (predicate(event as T)) {
events += event
if (events.size == count) {
result.complete(events)
deregister()
}
}
} catch (t: Throwable) {
result.completeExceptionally(t)
deregister()
}
}
}
/**
* Suspends until this event waiter is resolved.
*
* This function suspends until one of two things happens:
* 1. The amount of events that match the predicate function equals count.
* 2. The timeout duration has expired.
*
* @return A List of all the events collected.
*/
suspend fun await(): List<T> = result.await()
/**
* Returns a [Deferred] that resolves to this waiter's events when it is resolved.
*
* @return A [Deferred] that resolves when this waiter is resolved.
*/
fun asDeferred(): Deferred<List<T>> = result
/**
* Cancels this event waiter; no further events will be recorded.
*
* If this was not already resolved, any calls to [await] will throw [CancellationException] after this call, and any [Deferred]s returned by [asDeferred] will be cancelled.
* If this was already resolved, this call will throw [IllegalStateException]
*/
fun cancel() {
if (result.isActive) {
deregister()
result.cancel()
} else {
throw IllegalStateException("Cannot cancel a resolved event waiter")
}
}
/**
* Basically delete this event waiter, removing it from the jda instance and removing the timeout coroutine.
*/
private fun deregister() {
try {
jda.removeEventListener(this)
} catch (e: Exception) {/* ignore */}
if (timeoutJob?.isCancelled != true && timeoutJob?.isActive != true) timeoutJob?.cancel()
}
} | apache-2.0 | c13393208edbbd952c27b5f8c193e0c8 | 38.240602 | 186 | 0.641817 | 4.654773 | false | false | false | false |
smmribeiro/intellij-community | plugins/ide-features-trainer/src/training/util/PerformActionUtil.kt | 12 | 2301 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package training.util
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.KeyboardShortcut
import com.intellij.openapi.actionSystem.Shortcut
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.project.Project
import java.awt.event.InputEvent
import java.awt.event.KeyEvent
import java.awt.event.MouseEvent
import java.util.concurrent.ExecutionException
import javax.swing.JOptionPane
import javax.swing.KeyStroke
object PerformActionUtil {
private fun getInputEvent(actionName: String): InputEvent {
val shortcuts: Array<Shortcut> = KeymapManager.getInstance().activeKeymap.getShortcuts(actionName)
var keyStroke: KeyStroke? = null
for (each in shortcuts) {
if (each is KeyboardShortcut) {
keyStroke = each.firstKeyStroke
break
}
}
return if (keyStroke != null) {
KeyEvent(JOptionPane.getRootFrame(),
KeyEvent.KEY_PRESSED,
System.currentTimeMillis(),
keyStroke.modifiers,
keyStroke.keyCode,
keyStroke.keyChar,
KeyEvent.KEY_LOCATION_STANDARD)
}
else {
MouseEvent(JOptionPane.getRootFrame(), MouseEvent.MOUSE_PRESSED, 0, 0, 0, 0, 1, false, MouseEvent.BUTTON1)
}
}
@Throws(InterruptedException::class, ExecutionException::class)
fun performAction(actionName: String, editor: Editor, project: Project, withWriteAccess: Boolean = true, callback: () -> Unit = {}) {
val am: ActionManager = ActionManager.getInstance()
val targetAction = am.getAction(actionName)
val inputEvent = getInputEvent(actionName)
val runAction = {
am.tryToExecute(targetAction, inputEvent, editor.contentComponent, null, true).doWhenDone(callback)
}
ApplicationManager.getApplication().invokeLater {
if (withWriteAccess) {
WriteCommandAction.runWriteCommandAction(project) {
runAction()
}
}
else runAction()
}
}
} | apache-2.0 | 4eca6ab532c78389b45127b8855e8d48 | 37.366667 | 140 | 0.723598 | 4.715164 | false | false | false | false |
wn1/LNotes | app/src/main/java/ru/qdev/lnotes/db/entity/QDVDbFolder.kt | 1 | 574 | package ru.qdev.lnotes.db.entity
import android.support.annotation.AnyThread
import com.j256.ormlite.field.DataType
import com.j256.ormlite.field.DatabaseField
import com.j256.ormlite.table.DatabaseTable
import ru.qdev.lnotes.db.entity.QDVDbEntity
/**
* Created by Vladimir Kudashov on 28.09.18.
*/
@DatabaseTable(tableName="categories")
@AnyThread
open class QDVDbFolder(label: String? = null) : QDVDbEntity() {
enum class Special (val id: Long) {UNKNOWN_FOLDER(-1)}
@DatabaseField(dataType = DataType.STRING, canBeNull = true)
var label: String? = label
} | mit | 3e65a6a5a5d910f652cff1d9d80a73bc | 29.263158 | 64 | 0.763066 | 3.298851 | false | false | false | false |
sg26565/hott-transmitter-config | MdlViewer/src/main/kotlin/de/treichels/hott/mdlviewer/javafx/TreeFileInfo.kt | 1 | 3629 | /**
* HoTT Transmitter Config Copyright (C) 2013 Oliver Treichel
*
* 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:></http:>//www.gnu.org/licenses/>.
*/
package de.treichels.hott.mdlviewer.javafx
import de.treichels.hott.decoder.HoTTTransmitter
import de.treichels.hott.serial.FileInfo
import de.treichels.hott.serial.FileType
import javafx.scene.control.TreeItem
import javafx.scene.control.TreeView
import javafx.scene.image.ImageView
import tornadofx.*
import tornadofx.FX.Companion.messages
class TreeFileInfo(name: String, private val treeView: TreeView<String>, private val transmitter: HoTTTransmitter, internal val fileInfo: FileInfo? = null) : TreeItem<String>(name) {
companion object {
private val resources = ResourceLookup(TreeFileInfo)
private val fileImage = resources.image("/File.gif")
private val openFolderImage = resources.image("/Folder_open.gif")
private val closedFolderImage = resources.image("/Folder_closed.gif")
private val rootFolderImage = resources.image("/Root.gif")
}
// helper
private val isRoot = fileInfo == null
private val isDir = fileInfo?.type == FileType.Dir
private val isFile = fileInfo?.type == FileType.File
internal val isReady
get() = fileInfo != null && isFile && value.endsWith(".mdl") && fileInfo.size <= 0x3000 && fileInfo.size >= 0x2000
init {
isExpanded = false
// update treeItem children on expand
expandedProperty().addListener { _ -> update() }
when {
isRoot -> {
graphic = ImageView(rootFolderImage)
}
isDir -> {
graphic = ImageView(closedFolderImage)
}
isFile -> {
graphic = ImageView(fileImage)
}
}
}
private fun loading() {
// add loading pseudo child
children.clear()
children.add(TreeItem(messages["loading"]))
}
/**
* Update children of this tree item in a background task.
*/
private fun update() {
when {
isRoot -> {
if (isExpanded) {
loadFromSdCard("/")
} else {
loading()
}
}
isDir -> {
if (isExpanded) {
graphic = ImageView(openFolderImage)
loadFromSdCard(fileInfo!!.path)
} else {
graphic = ImageView(closedFolderImage)
loading()
}
}
}
}
private fun loadFromSdCard(path: String) {
treeView.runAsyncWithOverlay {
transmitter.listDir(path).map { name ->
transmitter.getFileInfo(name)
}.map { info ->
TreeFileInfo(info.name, treeView, transmitter, info).apply {
if (isDir) loading()
}
}
}.success { list ->
children.clear()
children.addAll(list)
}
}
}
| lgpl-3.0 | 13787764942f2d6cd4d75e1e9ae15d90 | 32.601852 | 182 | 0.596308 | 4.917344 | false | false | false | false |
chiken88/passnotes | app/src/main/kotlin/com/ivanovsky/passnotes/domain/interactor/debugmenu/DebugMenuInteractor.kt | 1 | 12716 | package com.ivanovsky.passnotes.domain.interactor.debugmenu
import com.ivanovsky.passnotes.data.entity.FSAuthority
import com.ivanovsky.passnotes.data.entity.FileDescriptor
import com.ivanovsky.passnotes.data.entity.Group
import com.ivanovsky.passnotes.data.entity.OperationError.*
import com.ivanovsky.passnotes.data.entity.OperationResult
import com.ivanovsky.passnotes.data.repository.EncryptedDatabaseRepository
import com.ivanovsky.passnotes.data.repository.GroupRepository
import com.ivanovsky.passnotes.data.repository.file.FileSystemResolver
import com.ivanovsky.passnotes.data.repository.file.FSOptions
import com.ivanovsky.passnotes.data.repository.file.OnConflictStrategy
import com.ivanovsky.passnotes.data.repository.keepass.KeepassDatabaseKey
import com.ivanovsky.passnotes.domain.DispatcherProvider
import com.ivanovsky.passnotes.domain.FileHelper
import com.ivanovsky.passnotes.domain.interactor.server_login.GetDebugCredentialsUseCase
import com.ivanovsky.passnotes.util.InputOutputUtils
import com.ivanovsky.passnotes.util.InputOutputUtils.newFileInputStreamOrNull
import com.ivanovsky.passnotes.util.InputOutputUtils.newFileOutputStreamOrNull
import com.ivanovsky.passnotes.util.Logger
import kotlinx.coroutines.withContext
import java.io.File
import java.io.InputStream
import java.io.OutputStream
class DebugMenuInteractor(
private val fileSystemResolver: FileSystemResolver,
private val dbRepository: EncryptedDatabaseRepository,
private val fileHelper: FileHelper,
private val getDebugCredentialsUseCase: GetDebugCredentialsUseCase,
private val dispatchers: DispatcherProvider
) {
fun getDebugWebDavCredentials() = getDebugCredentialsUseCase.getDebugWebDavCredentials()
fun getFileContent(file: FileDescriptor): OperationResult<Pair<FileDescriptor, File>> {
val result = OperationResult<Pair<FileDescriptor, File>>()
val provider = fileSystemResolver.resolveProvider(file.fsAuthority)
val descriptorResult = provider.getFile(file.path, FSOptions.DEFAULT)
if (descriptorResult.isSucceededOrDeferred) {
val descriptor = descriptorResult.obj
val contentResult =
provider.openFileForRead(descriptor, OnConflictStrategy.REWRITE, FSOptions.DEFAULT)
if (contentResult.isSucceededOrDeferred) {
val destinationResult = createNewLocalDestinationStream()
if (destinationResult.isSucceededOrDeferred) {
val content = contentResult.obj
val destinationFile = destinationResult.obj.first
val destinationStream = destinationResult.obj.second
try {
InputOutputUtils.copy(content, destinationStream, true)
result.obj = Pair(descriptor, destinationFile)
} catch (e: Exception) {
Logger.printStackTrace(e)
result.error = newGenericIOError(e.toString())
}
} else {
result.error = destinationResult.error
}
} else {
result.error = contentResult.error
}
} else {
result.error = descriptorResult.error
}
return result
}
private fun createNewLocalDestinationStream(): OperationResult<Pair<File, OutputStream>> {
val result = OperationResult<Pair<File, OutputStream>>()
val outFile = fileHelper.generateDestinationFileForRemoteFile()
if (outFile != null) {
val outStream = newFileOutputStreamOrNull(outFile)
if (outStream != null) {
result.obj = Pair(outFile, outStream)
} else {
result.error = newGenericIOError(MESSAGE_FAILED_TO_ACCESS_TO_PRIVATE_STORAGE)
}
} else {
result.error = newGenericIOError(MESSAGE_FAILED_TO_ACCESS_TO_PRIVATE_STORAGE)
}
return result
}
fun newDbFile(
password: String,
file: FileDescriptor
): OperationResult<Pair<FileDescriptor, File>> {
val result = OperationResult<Pair<FileDescriptor, File>>()
val anyFsProvider = fileSystemResolver.resolveProvider(file.fsAuthority)
val existsResult = anyFsProvider.exists(file)
if (existsResult.isSucceeded) {
val exists = existsResult.obj
if (!exists) {
val creationResult = createNewDatabaseInPrivateStorage(password)
if (creationResult.isSucceededOrDeferred) {
val openResult = anyFsProvider.openFileForWrite(
file,
OnConflictStrategy.CANCEL,
FSOptions.DEFAULT
)
if (openResult.isSucceededOrDeferred) {
val inputFile = creationResult.obj.first
val inputStream = creationResult.obj.second
val outStream = openResult.obj
val copyResult = copyStreamToStream(inputStream, outStream)
if (copyResult.isSucceededOrDeferred) {
val fileResult = anyFsProvider.getFile(file.path, FSOptions.DEFAULT)
if (fileResult.isSucceededOrDeferred) {
val outDescriptor = fileResult.obj
result.obj = Pair(outDescriptor, inputFile)
} else {
result.error = fileResult.error
}
} else {
result.error = copyResult.error
}
} else {
result.error = openResult.error
}
} else {
result.error = creationResult.error
}
} else {
result.error = newFileIsAlreadyExistsError()
}
} else {
result.error = existsResult.error
}
return result
}
private fun createNewDatabaseInPrivateStorage(password: String): OperationResult<Pair<File, InputStream>> {
val result = OperationResult<Pair<File, InputStream>>()
val dbFile = fileHelper.generateDestinationFileForRemoteFile()
if (dbFile != null) {
val dbDescriptor = FileDescriptor.fromRegularFile(dbFile)
val key = KeepassDatabaseKey(password)
val creationResult = dbRepository.createNew(key, dbDescriptor)
if (creationResult.isSucceededOrDeferred) {
val dbStream = newFileInputStreamOrNull(dbFile)
if (dbStream != null) {
result.obj = Pair(dbFile, dbStream)
} else {
result.error = newGenericIOError(MESSAGE_FAILED_TO_ACCESS_TO_PRIVATE_STORAGE)
}
} else {
result.error = creationResult.error
}
} else {
result.error = newGenericIOError(MESSAGE_FAILED_TO_ACCESS_TO_PRIVATE_STORAGE)
}
return result
}
private fun copyStreamToStream(
inStream: InputStream,
outStream: OutputStream
): OperationResult<Boolean> {
val result = OperationResult<Boolean>()
try {
InputOutputUtils.copy(inStream, outStream, true)
result.obj = true
} catch (e: Exception) {
Logger.printStackTrace(e)
result.error = newGenericIOError(e.toString())
}
return result
}
fun writeDbFile(
inFile: File,
outFile: FileDescriptor
): OperationResult<Pair<FileDescriptor, File>> {
val result = OperationResult<Pair<FileDescriptor, File>>()
val provider = fileSystemResolver.resolveProvider(outFile.fsAuthority)
val openResult = provider.openFileForWrite(
outFile,
OnConflictStrategy.REWRITE,
FSOptions.DEFAULT
)
if (openResult.isSucceededOrDeferred) {
val outStream = openResult.obj
val inStream = newFileInputStreamOrNull(inFile)
if (inStream != null) {
try {
InputOutputUtils.copy(inStream, outStream, true)
result.obj = Pair(outFile, inFile)
} catch (e: Exception) {
Logger.printStackTrace(e)
result.error = newGenericIOError(e.toString())
}
} else {
result.error = newGenericIOError(MESSAGE_FAILED_TO_ACCESS_TO_PRIVATE_STORAGE)
}
} else {
result.error = openResult.error
}
return result
}
fun openDbFile(password: String, file: File): OperationResult<Boolean> {
val result = OperationResult<Boolean>()
val key = KeepassDatabaseKey(password)
val openResult = dbRepository.open(key, FileDescriptor.fromRegularFile(file), FSOptions.DEFAULT)
if (openResult.isSucceededOrDeferred) {
result.obj = true
} else {
result.error = openResult.error
}
return result
}
fun closeDbFile(file: File): OperationResult<Boolean> {
val result = OperationResult<Boolean>()
val closeResult = dbRepository.close()
if (closeResult.isSucceededOrDeferred) {
file.setLastModified(System.currentTimeMillis())
result.obj = closeResult.obj
} else {
result.error = closeResult.error
}
return result
}
@Suppress("FoldInitializerAndIfToElvis")
fun addEntryToDb(): OperationResult<Boolean> {
val db = dbRepository.database
if (db == null) {
return OperationResult.error(newDbError(MESSAGE_FAILED_TO_GET_DATABASE))
}
val newGroupTitle = generateNewGroupTitle(db.groupRepository)
if (newGroupTitle == null) {
return OperationResult.error(newDbError(MESSAGE_UNKNOWN_ERROR))
}
val rootGroupResult = db.groupRepository.rootGroup
if (rootGroupResult.isFailed) {
return rootGroupResult.takeError()
}
val rootGroupUid = rootGroupResult.obj.uid
val newGroup = Group()
newGroup.title = newGroupTitle
val insertResult = db.groupRepository.insert(newGroup, rootGroupUid)
if (insertResult.isFailed) {
return insertResult.takeError()
}
return insertResult.takeStatusWith(true)
}
suspend fun isFileExists(file: FileDescriptor): OperationResult<Boolean> {
return withContext(dispatchers.IO) {
fileSystemResolver
.resolveProvider(file.fsAuthority)
.exists(file)
}
}
suspend fun getFileByPath(path: String, fsAuthority: FSAuthority): OperationResult<FileDescriptor> =
withContext(dispatchers.IO) {
fileSystemResolver
.resolveProvider(fsAuthority)
.getFile(path, FSOptions.DEFAULT)
}
private fun generateNewGroupTitle(groupRepository: GroupRepository): String? {
var title: String? = null
val groupsResult = groupRepository.allGroup
if (groupsResult.isSucceededOrDeferred) {
val indexesInGroups = extractIndexesFromGroups(groupsResult.obj)
val nextGroupIndex = findNextAvailableIndex(indexesInGroups)
title = "Group $nextGroupIndex"
}
return title
}
private fun extractIndexesFromGroups(groups: List<Group>): List<Int> {
return groups.filter { group -> group.title != null && group.title.startsWith("Group ") }
.mapNotNull { group -> extractIndexFromGroupTitle(group.title) }
.toSet()
.sorted()
}
private fun extractIndexFromGroupTitle(title: String): Int? {
var index: Int? = null
val spaceIdx = title.indexOf(" ")
if (spaceIdx + 1 < title.length) {
val titleIndexStr = title.substring(spaceIdx + 1, title.length)
if (titleIndexStr.all { ch -> ch.isDigit() }) {
index = Integer.parseInt(titleIndexStr)
}
}
return index
}
private fun findNextAvailableIndex(indexes: List<Int>): Int {
var result = 1
for (idx in 0 until indexes.size) {
if (indexes[idx] > result) {
break
} else {
result = indexes[idx] + 1
}
}
return result
}
} | gpl-2.0 | e95136d6675466fd2e5b9cf2292771a2 | 35.438395 | 111 | 0.610884 | 5.108879 | false | false | false | false |
gen0083/AdbFriendly | plugin/src/main/java/jp/gcreate/plugins/adbfriendly/adb/AdbAccelerometerRotation.kt | 1 | 3243 | /*
* ADB Friendly
* Copyright 2016 gen0083
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.gcreate.plugins.adbfriendly.adb
import com.android.ddmlib.IDevice
import jp.gcreate.plugins.adbfriendly.util.Logger
class AdbAccelerometerRotation(var device: IDevice) {
companion object {
const val URI = "content://settings/system"
const val COLUMN = "name:s:accelerometer_rotation"
const val ON = "value:i:1"
const val OFF = "value:i:0"
const val WHERE = "\"name='accelerometer_rotation'\""
const val COMMAND_INSERT_ON = "content insert --uri $URI --bind $COLUMN --bind $ON"
const val COMMAND_INSERT_OFF = "content insert --uri $URI --bind $COLUMN --bind $OFF"
const val COMMAND_UPDATE_ON = "content update --uri $URI --bind $ON --where $WHERE"
const val COMMAND_UPDATE_OFF = "content update --uri $URI --bind $OFF --where $WHERE"
const val COMMAND_QUERY = "content query --uri $URI --where $WHERE"
const val COMMAND_DELETE = "content delete --uri $URI --where $WHERE"
}
fun enableAccelerometerRotation(): Boolean {
val outputs = Command(device, COMMAND_INSERT_ON).execute()
val result = outputs.size == 0
Logger.d(this, "enableAccelerometerRotation output=${outputs.joinToString("\n")} result=$result")
return result
}
fun disableAccelerometerRotation(): Boolean {
val outputs = Command(device, COMMAND_INSERT_OFF).execute()
val result = outputs.size == 0
Logger.d(this, "disableAccelerometerRotation output=${outputs.joinToString("\n")} result=$result")
return result
}
fun deleteAccelerometerRotation(): Boolean {
val outputs = Command(device, COMMAND_DELETE).execute()
val result = outputs.size == 0
Logger.d(this, "delete output=${outputs.joinToString("\n")} result=$result")
return result
}
fun isAlreadyExist(): Boolean {
val outputs = Command(device, COMMAND_QUERY).execute()
val result = (outputs.size == 1 && outputs[0].contains("value="))
Logger.d(this, "isAlreadyExist output=${outputs.joinToString("\n")}} result=$result")
return result
}
fun isEnabled(): Boolean {
val outputs = Command(device, COMMAND_QUERY).execute()
val result = if (outputs.size == 1) {
if (outputs[0].contains("value=1")) {
true
} else {
false
}
} else {
throw RuntimeException("Entry is not exist. Insert accelerometer_rotation first")
}
Logger.d(this, "isEnabled output=${outputs.joinToString("\n")} result=$result")
return result
}
} | apache-2.0 | ab229c0a8689cf68604f89f40ff11de5 | 39.049383 | 106 | 0.645698 | 4.239216 | false | false | false | false |
chiken88/passnotes | app/src/main/kotlin/com/ivanovsky/passnotes/domain/DatabaseLockInteractor.kt | 1 | 2952 | package com.ivanovsky.passnotes.domain
import android.content.Context
import android.os.Handler
import android.os.Looper
import androidx.annotation.UiThread
import com.ivanovsky.passnotes.data.ObserverBus
import com.ivanovsky.passnotes.data.repository.file.FSOptions
import com.ivanovsky.passnotes.data.repository.settings.Settings
import com.ivanovsky.passnotes.domain.entity.DatabaseStatus
import com.ivanovsky.passnotes.domain.entity.ServiceState
import com.ivanovsky.passnotes.domain.usecases.LockDatabaseUseCase
import com.ivanovsky.passnotes.presentation.service.DatabaseLockService
import com.ivanovsky.passnotes.util.Logger
class DatabaseLockInteractor(
private val context: Context,
private val settings: Settings,
private val lockUseCase: LockDatabaseUseCase
) : ObserverBus.DatabaseOpenObserver,
ObserverBus.DatabaseCloseObserver {
private val handler = Handler(Looper.getMainLooper())
private val activeScreens = mutableSetOf<String>()
private var isDatabaseOpened = false
private var isTimerStarted = false
@UiThread
override fun onDatabaseOpened(fsOptions: FSOptions, status: DatabaseStatus) {
startServiceIfNeed()
isDatabaseOpened = true
}
@UiThread
override fun onDatabaseClosed() {
cancelLockTimer()
stopServiceIfNeed()
isDatabaseOpened = false
}
@UiThread
fun onScreenInteractionStarted(screenKey: String) {
activeScreens.add(screenKey)
cancelLockTimer()
}
@UiThread
fun onScreenInteractionStopped(screenKey: String) {
activeScreens.remove(screenKey)
if (isDatabaseOpened &&
activeScreens.size == 0 &&
settings.autoLockDelayInMs != -1) {
startLockTimer()
}
}
@UiThread
fun stopServiceIfNeed() {
if (DatabaseLockService.getCurrentState() != ServiceState.STOPPED) {
DatabaseLockService.stop(context)
}
}
private fun startServiceIfNeed() {
if (DatabaseLockService.getCurrentState() == ServiceState.STOPPED &&
settings.isLockNotificationVisible) {
DatabaseLockService.start(context)
}
}
private fun cancelLockTimer() {
if (isTimerStarted) {
isTimerStarted = false
Logger.d(TAG, "Auto-Lock timer cancelled")
}
handler.removeCallbacksAndMessages(null)
}
private fun startLockTimer() {
val delay = settings.autoLockDelayInMs
isTimerStarted = true
handler.postDelayed(
{
isTimerStarted = false
Logger.d(TAG, "Lock database by timer")
lockUseCase.lockIfNeed()
},
delay.toLong()
)
Logger.d(TAG, "Auto-Lock timer started with delay: %s milliseconds", delay)
}
companion object {
private val TAG = DatabaseLockInteractor::class.simpleName
}
} | gpl-2.0 | cd70717b6222b794369d8c1c43188ed4 | 28.53 | 83 | 0.680894 | 4.738363 | false | false | false | false |
hmemcpy/teamcity-vsix-gallery | teamcity-vsix-gallery-server/src/main/teamcity/vsix/index/VsixPackage.kt | 1 | 984 | package teamcity.vsix.index
import com.intellij.openapi.diagnostic.Logger
import jetbrains.buildServer.serverSide.metadata.BuildMetadataEntry
data class VsixPackage(val entry: BuildMetadataEntry) {
val log = Logger.getInstance("teamcity.vsix");
val metadata = entry.getMetadata();
init {
log.info("Metadata: " + metadata)
}
public val Id: String = metadata.get(ID).orEmpty();
public val Title: String = metadata.get(TITLE).orEmpty();
public val Summary: String = metadata.get(SUMMARY).orEmpty();
public val Version: String = metadata.get(VERSION).orEmpty();
public val Publisher: String = metadata.get(PUBLISHER).orEmpty();
public val LastUpdated: String = metadata.get(LAST_UPDATED).orEmpty();
public val ContentPath: String = metadata.get("teamcity.artifactPath").orEmpty();
public val BuildTypeId: String = metadata.get("teamcity.buildTypeId").orEmpty();
public val BuildId: String = entry.getBuildId().toString()
} | mit | da7ba5a28cec44b04abc81333447435c | 38.4 | 85 | 0.724593 | 4.223176 | false | false | false | false |
mgoodwin14/barcrawler | app/src/main/java/com/nonvoid/barcrawler/brewery/BreweryAdapter.kt | 2 | 2637 | package com.nonvoid.barcrawler.brewery
import android.support.v4.view.ViewCompat
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.nonvoid.barcrawler.R
import com.nonvoid.barcrawler.model.Brewery
import com.squareup.picasso.Picasso
/**
* Created by Matt on 7/1/2017.
*/
class BreweryAdapter(private val list: List<Brewery>, private val callback: Callback) : RecyclerView.Adapter<BreweryAdapter.BreweryViewHolder>() {
override fun onBindViewHolder(holder: BreweryViewHolder, position: Int) {
val brewery = list[position]
holder.setView(brewery)
holder.itemView.setOnClickListener { callback.onBrewerySelected(brewery, holder.imageView) }
ViewCompat.setTransitionName(holder.imageView, brewery.id)
}
override fun getItemCount(): Int = list.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BreweryViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.brewery_list_row, parent, false)
return BreweryViewHolder(view)
}
class BreweryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
val nameTextView = itemView.findViewById(R.id.brewery_list_name_textview) as TextView
val descriptionTextView = itemView.findViewById(R.id.brewery_list_brand_classification_textview) as TextView
val locationTextView = itemView.findViewById(R.id.brewery_list_location_textview) as TextView
val imageView = itemView.findViewById(R.id.brewery_image_view) as ImageView
fun setView(brewery: Brewery){
descriptionTextView.visibility = View.GONE
if(brewery.established != null && brewery.established.isNotEmpty()){
nameTextView.text = "${brewery.nameShortDisplay} est. ${brewery.established}"
} else {
nameTextView.text = brewery.nameShortDisplay
}
if(!brewery.breweryLocations.isEmpty()){
//need to turn on premium features at
//http://www.brewerydb.com/developers/premium
locationTextView.text = brewery.breweryLocations?.get(0)?.locality
} else {
locationTextView.visibility = View.GONE
}
Picasso.with(imageView.context)
.load(brewery.images?.large)
.into(imageView)
}
}
interface Callback{
fun onBrewerySelected(brewery: Brewery, imageView: ImageView)
}
} | gpl-3.0 | cf2723543c274ea821722807b8107016 | 37.794118 | 146 | 0.693591 | 4.294788 | false | false | false | false |
Nice3point/ScheduleMVP | app/src/main/java/nice3point/by/schedule/ScheduleDialogChanger/PScheduleChanger.kt | 1 | 3365 | package nice3point.by.schedule.ScheduleDialogChanger
import android.view.View
import nice3point.by.schedule.iUpdateViewPager
import org.jetbrains.annotations.Contract
class PScheduleChanger(private val view: iVScheduleChanger) : iPScheduleChanger {
private val model: iMScheduleChanger = MScheduleChanger(this)
private lateinit var uiListener: iUpdateViewPager
override fun createAppendDialog(uiListener: iUpdateViewPager) {
this.uiListener = uiListener
view.switchDeleteIconVisibility(View.INVISIBLE)
view.setConfirmButtonListener(addItemListener)
}
override fun createEditDialog(uiListener: iUpdateViewPager, teacher: String, subject: String, cabinet: String, time: String, type: String) {
this.uiListener = uiListener
val unzipTime = splitTime(time)
view.setTextViewData(teacher, subject, cabinet, unzipTime[0], unzipTime[1], type)
view.setConfirmButtonListener(getEditItemListener(teacher, subject, cabinet, time, type))
}
override fun deleteButtonPressed(databaseName: String, teacher: String, subject: String, cabinet: String, time: String, type: String) {
view.delBtEdit()
view.setConfirmButtonListener(getDeleteListener(databaseName, teacher, subject, cabinet, time, type))
}
private val addItemListener: View.OnClickListener
@Contract(pure = true)
get() {
val changerView = this.view
return View.OnClickListener {
val bundle = changerView.getTextViewData()
if (bundle[0]!!.isEmpty()) {
changerView.closeDialog()
} else {
model.addItemToRealm(bundle[0], bundle[1], bundle[2], bundle[3], bundle[4], bundle[5], bundle[6])
uiListener.refreshUI()
changerView.closeDialog()
}
}
}
@Contract(pure = true)
private fun getEditItemListener(teacher: String, subject: String, cabinet: String,
time: String, type: String): View.OnClickListener {
val changerView = this.view
return View.OnClickListener {
val bundle = changerView.getTextViewData()
model.editRealmItem(bundle, teacher, subject, cabinet, time, type)
uiListener.refreshUI()
changerView.closeDialog()
}
}
private fun getDeleteListener(databaseName: String, teacher: String, subject: String, cabinet: String, time: String, type: String): View.OnClickListener {
val changerView = this.view
return View.OnClickListener {
model.deleteRealmItem(databaseName, teacher, subject, cabinet, time, type)
uiListener.refreshUI()
changerView.closeDialog()
}
}
private fun splitTime(time: String): Array<String> {
val massive = time.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
return when {
massive.size == 1 -> arrayOf(massive[0], "")
time.isEmpty() -> arrayOf("", "")
else -> time.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
}
}
override fun dialogIsDead() {
model.closeRealm()
}
override fun showSnackBar(text: String) {
uiListener.showSnackBar(text)
}
}
| apache-2.0 | db87669096f25e017bf760deba2780f5 | 36.388889 | 158 | 0.641308 | 4.590723 | false | false | false | false |
TradeMe/MapMe | mapme/src/main/java/nz/co/trademe/mapme/MapMeAdapter.kt | 1 | 21445 | package nz.co.trademe.mapme
import android.content.Context
import androidx.annotation.RestrictTo
import androidx.annotation.VisibleForTesting
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.ListUpdateCallback
import androidx.recyclerview.widget.RecyclerView
import nz.co.trademe.mapme.annotations.*
const val TAG = "MapMeAdapter"
const val NO_POSITION = -1
abstract class MapMeAdapter<MapType>(var context: Context, var factory: AnnotationFactory<MapType>) : MapAdapterHelper.MapAdapterHelperCallback, ListUpdateCallback {
var mapView: View? = null
var map: MapType? = null
var annotations: ArrayList<MapAnnotation> = ArrayList()
var annotationClickListener: OnMapAnnotationClickListener? = null
var infoWindowClickListener: OnInfoWindowClickListener? = null
internal var debug = false
internal val observer = MapMeDataObserver()
private val registeredObservers = arrayListOf<RecyclerView.AdapterDataObserver>()
internal val mapAdapterHelper: MapAdapterHelper by lazy {
MapAdapterHelper(this, this.debug)
}
abstract fun onCreateAnnotation(factory: AnnotationFactory<@JvmSuppressWildcards MapType>, position: Int, annotationType: Int): MapAnnotation
abstract fun onBindAnnotation(annotation: MapAnnotation, position: Int, payload: Any?)
abstract fun getItemCount(): Int
fun attach(mapView: View, map: MapType) {
this.map = map
this.mapView = mapView
this.factory.setOnMarkerClickListener(map, { marker -> notifyAnnotatedMarkerClicked(marker) })
this.factory.setOnInfoWindowClickListener(map, { marker -> notifyInfowWindowClicked(marker) })
}
//default implementation
open fun getItemAnnotationType(position: Int): Int {
return 0
}
fun enableDebugLogging() {
this.debug = true
}
open fun setOnAnnotationClickListener(listener: OnMapAnnotationClickListener) {
this.annotationClickListener = listener
}
open fun setOnInfoWindowClickListener(listener: OnInfoWindowClickListener) {
this.infoWindowClickListener = listener
}
override fun onChanged(position: Int, count: Int, payload: Any?) {
observer.onItemRangeChanged(position, count, payload)
}
override fun onMoved(fromPosition: Int, toPosition: Int) {
observer.onItemRangeMoved(fromPosition, toPosition, 1)
}
override fun onInserted(position: Int, count: Int) {
observer.onItemRangeInserted(position, count)
}
override fun onRemoved(position: Int, count: Int) {
observer.onItemRangeRemoved(position, count)
}
fun registerObserver(observer: RecyclerView.AdapterDataObserver) {
registeredObservers.add(observer)
}
fun unregisterObserver(observer: RecyclerView.AdapterDataObserver) {
registeredObservers.remove(observer)
}
/**
* Internally creates an annotation for the given position.
*/
private fun createAnnotation(position: Int) {
val annotationType = getItemAnnotationType(position)
val annotation = onCreateAnnotation(this.factory, position, annotationType)
annotation.position = position
map?.let {
annotation.addToMap(map!!, context)
annotations.add(annotation)
onBindAnnotation(annotation, position, null)
onAnnotationAdded(annotation)
}
}
open fun onAnnotationAdded(annotation: MapAnnotation) {
}
/**
* Called after all DiffUtil updates have been dispatched.
*
* Removes any placeholders and replaces them with real annotations
*/
private fun applyUpdates() {
//update old annotations
this.annotations.forEach {
if (it.isDirty) {
updateAnnotation(it.position, null)
it.isDirty = false
}
}
//create new annotations
ArrayList(this.annotations).forEach {
if (it.placeholder) {
this.annotations.remove(it)
createAnnotation(it.position)
}
}
}
/**
* Removes an annotation at the given position
*/
private fun removeAnnotation(position: Int) {
val map = map ?: return
val annotation = findAnnotationForPosition(position)
if (annotation != null) {
annotation.removeFromMap(map, context)
annotations.remove(annotation)
} else {
Log.d(TAG, "annotation not found")
}
}
/**
* Updates an annotation at the given position
*/
private fun updateAnnotation(position: Int, payload: Any?) {
val annotation = findAnnotationForPosition(position)
annotation?.let {
onBindAnnotation(annotation, position, payload)
}
}
internal fun findAnnotationForPosition(position: Int): MapAnnotation? {
return annotations.find { it.position == position }
}
fun onItemsInserted(positionStart: Int, itemCount: Int) {
for (position in positionStart until positionStart + itemCount) {
this.annotations.add(Placeholder().apply { this.position = position })
}
}
fun onItemsMoved(positionStart: Int, itemCount: Int, payload: Any?) {
}
fun onItemsRemoved(positionStart: Int, itemCount: Int) {
for (position in positionStart until positionStart + itemCount) {
removeAnnotation(position)
}
}
fun onItemsChanged(positionStart: Int, itemCount: Int, payload: Any?) {
//don't do anything here. Annotations have already been marked as updated,
//and will be updated at the end of the 'layout'
}
/**
* Notify any registered observers that the data set has changed.
*
* <p>There are two different classes of data change events, item changes and structural
* changes. Item changes are when a single item has its data updated but no positional
* changes have occurred. Structural changes are when items are inserted, removed or moved
* within the data set.</p>
*
* <p>This event does not specify what about the data set has changed, forcing
* any observers to assume that all existing items and structure may no longer be valid.
* LayoutManagers will be forced to fully rebind and relayout all visible views.</p>
*
* <p><code>RecyclerView</code> will attempt to synthesize visible structural change events
* for adapters that report that they have {@link #hasStableIds() stable IDs} when
* this method is used. This can help for the purposes of animation and visual
* object persistence but individual item views will still need to be rebound
* and relaid out.</p>
*
* <p>If you are writing an adapter it will always be more efficient to use the more
* specific change events if you can. Rely on <code>notifyDataSetChanged()</code>
* as a last resort.</p>
*
* @see #notifyItemChanged(int)
* @see #notifyItemInserted(int)
* @see #notifyItemRemoved(int)
* @see #notifyItemRangeChanged(int, int)
* @see #notifyItemRangeInserted(int, int)
* @see #notifyItemRangeRemoved(int, int)
*/
fun notifyDataSetChanged() {
val map = map ?: return
onRemoved(0, annotations.size)
factory.clear(map)
annotations.clear()
mapAdapterHelper.clearPendingUpdates()
onInserted(0, getItemCount())
}
/**
* Notify any registered observers that the item at <code>position</code> has changed.
* Equivalent to calling <code>notifyItemChanged(position, null);</code>.
*
* <p>This is an item change event, not a structural change event. It indicates that any
* reflection of the data at <code>position</code> is out of date and should be updated.
* The item at <code>position</code> retains the same identity.</p>
*
* @param position Position of the item that has changed
*
* @see #notifyItemRangeChanged(int, int)
*/
fun notifyItemChanged(position: Int) {
notifyItemChanged(position, null)
}
/**
* Notify any registered observers that the item at <code>position</code> has changed with an
* optional payload object.
*
* <p>This is an item change event, not a structural change event. It indicates that any
* reflection of the data at <code>position</code> is out of date and should be updated.
* The item at <code>position</code> retains the same identity.
* </p>
*
* <p>
* Client can optionally pass a payload for partial change. These payloads will be merged
* and may be passed to adapter's {@link #onBindViewHolder(ViewHolder, int, List)} if the
* item is already represented by a ViewHolder and it will be rebound to the same
* ViewHolder. A notifyItemRangeChanged() with null payload will clear all existing
* payloads on that item and prevent future payload until
* {@link #onBindViewHolder(ViewHolder, int, List)} is called. Adapter should not assume
* that the payload will always be passed to onBindViewHolder(), e.g. when the view is not
* attached, the payload will be simply dropped.
*
* @param position Position of the item that has changed
* @param payload Optional parameter, use null to identify a "full" update
*
* @see #notifyItemRangeChanged(int, int)
*/
fun notifyItemChanged(position: Int, payload: Any?) {
observer.onItemRangeChanged(position, 1, payload)
}
/**
* Notify any registered observers that the item reflected at <code>position</code>
* has been newly inserted. The item previously at <code>position</code> is now at
* position <code>position + 1</code>.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.</p>
*
* @param position Position of the newly inserted item in the data set
*
* @see #notifyItemRangeInserted(int, int)
*/
fun notifyItemInserted(position: Int) {
observer.onItemRangeInserted(position, 1)
}
/**
* Notify any registered observers that the item previously located at <code>position</code>
* has been removed from the data set. The items previously located at and after
* <code>position</code> may now be found at <code>oldPosition - 1</code>.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.</p>
*
* @param position Position of the item that has now been removed
*
* @see #notifyItemRangeRemoved(int, int)
*/
fun notifyItemRemoved(position: Int) {
observer.onItemRangeRemoved(position, 1)
}
/**
* Notify any registered observers that the currently reflected <code>itemCount</code>
* items starting at <code>positionStart</code> have been newly inserted. The items
* previously located at <code>positionStart</code> and beyond can now be found starting
* at positionStart <code>positionStart + itemCount</code>.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.</p>
*
* @param positionStart Position of the first item that was inserted
* @param itemCount Number of items inserted
*
* @see #notifyItemInserted(int)
*/
fun notifyItemRangeInserted(positionStart: Int, itemCount: Int) {
for (position in positionStart until positionStart + itemCount) {
notifyItemInserted(position)
}
}
/**
* Notify any registered observers that the item previously located at <code>positionStart</code>
* has been removed from the data set. The items previously located at and after
* <code>positionStart</code> may now be found at <code>oldPosition - 1</code>.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.</p>
*
* @param positionStart Position of the item that has now been removed
*
* @see #notifyItemRangeRemoved(int, int)
*/
fun notifyItemRangeRemoved(positionStart: Int, itemCount: Int) {
for (position in positionStart + itemCount downTo positionStart) {
notifyItemRemoved(position)
}
}
/**
* Notify any registered observers that the item at <code>positionStart</code> has changed.
* Equivalent to calling <code>notifyItemChanged(positionStart, null);</code>.
*
* <p>This is an item change event, not a structural change event. It indicates that any
* reflection of the data at <code>positionStart</code> is out of date and should be updated.
* The item at <code>positionStart</code> retains the same identity.</p>
*
* @param positionStart Position of the item that has changed
*
* @see #notifyItemRangeChanged(int, int)
*/
fun notifyItemRangeChanged(positionStart: Int, itemCount: Int) {
notifyItemRangeChanged(positionStart, itemCount, null)
}
/**
* Notify any registered observers that the item at <code>positionStart</code> has changed with an
* optional payload object.
*
* <p>This is an item change event, not a structural change event. It indicates that any
* reflection of the data at <code>positionStart</code> is out of date and should be updated.
* The item at <code>positionStart</code> retains the same identity.
* </p>
*
* <p>
* Client can optionally pass a payload for partial change. These payloads will be merged
* and may be passed to adapter's {@link #onBindViewHolder(ViewHolder, int, List)} if the
* item is already represented by a ViewHolder and it will be rebound to the same
* ViewHolder. A notifyItemRangeChanged() with null payload will clear all existing
* payloads on that item and prevent future payload until
* {@link #onBindViewHolder(ViewHolder, int, List)} is called. Adapter should not assume
* that the payload will always be passed to onBindViewHolder(), e.g. when the view is not
* attached, the payload will be simply dropped.
*
* @param positionStart Position of the item that has changed
* @param payload Optional parameter, use null to identify a "full" update
*
* @see #notifyItemRangeChanged(int, int)
*/
fun notifyItemRangeChanged(positionStart: Int, itemCount: Int, payload: Any?) {
for (position in positionStart until positionStart + itemCount) {
notifyItemChanged(position, payload)
}
}
/**
* Notify any registered observers that the item reflected at `fromPosition`
* has been moved to `toPosition`.
*
* This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.
* @param fromPosition Previous position of the item.
* *
* @param toPosition New position of the item.
*/
fun notifyItemMoved(fromPosition: Int, toPosition: Int) {
observer.onItemRangeMoved(fromPosition, toPosition, 1)
mapAdapterHelper.dispatch()
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun notifyAnnotatedMarkerClicked(marker: Any): Boolean {
val clickListener = annotationClickListener ?: return false
val annotation = annotations.find { it.annotatesObject(marker) }
if (annotation != null) {
return clickListener.onMapAnnotationClick(annotation)
} else {
Log.e("MapMeAdapter", "Unable to find an annotation that annotates the marker")
}
return false
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun notifyInfowWindowClicked(marker: Any): Boolean {
val clickListener = infoWindowClickListener ?: return false
val annotation = annotations.find { it.annotatesObject(marker) }
if (annotation != null) {
return clickListener.onInfoWindowClick(annotation)
} else {
Log.e("MapMeAdapter", "Unable to find an annotation that annotates the marker")
}
return false
}
/**
* Marks an annotation as requiring an update (isDirty). The annotations will be updated
* at the end of the 'layout pass'
*/
override fun markAnnotationsUpdated(positionStart: Int, itemCount: Int) {
annotations.forEach { annotation ->
val position = annotation.position
if (position >= positionStart && position < positionStart + itemCount) {
annotation.isDirty = true
}
}
}
override fun offsetPositionsForAdd(positionStart: Int, itemCount: Int) {
annotations.forEach { annotation ->
val position = annotation.position
if (position >= positionStart) {
offsetPosition(annotation, itemCount)
}
}
}
override fun offsetPositionsForRemove(positionStart: Int, itemCount: Int) {
val positionEnd = positionStart + itemCount
annotations.forEach { annotation ->
if (annotation.position >= positionEnd) {
offsetPosition(annotation, -itemCount)
} else if (annotation.position >= positionStart) {
offsetPosition(annotation, -itemCount)
}
}
}
private fun offsetPosition(annotation: MapAnnotation, offset: Int) {
annotation.position += offset
}
override fun offsetPositionsForMove(from: Int, to: Int) {
val start: Int
val end: Int
val inBetweenOffset: Int
if (from < to) {
start = from
end = to
inBetweenOffset = -1
} else {
start = to
end = from
inBetweenOffset = 1
}
annotations
.filterNot { annotation ->
annotation.position < start || annotation.position > end
}
.forEach { annotation ->
val position = annotation.position
if (position == from) {
offsetPosition(annotation, to - from)
} else {
offsetPosition(annotation, inBetweenOffset)
}
}
}
internal val updateChildViewsRunnable: Runnable = Runnable {
consumePendingUpdateOperations()
}
internal fun consumePendingUpdateOperations() {
if (!mapAdapterHelper.hasPendingUpdates()) {
return
}
mapAdapterHelper.dispatch()
//after all updates have been dispatched, fill in any placeholder annotations
//with new annotations
applyUpdates()
}
@VisibleForTesting
open internal fun triggerUpdateProcessor(runnable: Runnable) {
mapView?.post(runnable)
}
inner class MapMeDataObserver : RecyclerView.AdapterDataObserver() {
override fun onItemRangeChanged(positionStart: Int, itemCount: Int, payload: Any?) {
if (mapAdapterHelper.onItemRangeChanged(positionStart, itemCount, payload)) {
triggerUpdateProcessor(updateChildViewsRunnable)
}
registeredObservers.forEach { it.onItemRangeChanged(positionStart, itemCount, payload) }
}
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
if (mapAdapterHelper.onItemRangeInserted(positionStart, itemCount)) {
triggerUpdateProcessor(updateChildViewsRunnable)
}
registeredObservers.forEach { it.onItemRangeInserted(positionStart, itemCount) }
}
override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
if (mapAdapterHelper.onItemRangeRemoved(positionStart, itemCount)) {
triggerUpdateProcessor(updateChildViewsRunnable)
}
registeredObservers.forEach { it.onItemRangeRemoved(positionStart, itemCount) }
}
override fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) {
if (mapAdapterHelper.onItemRangeMoved(fromPosition, toPosition, itemCount)) {
triggerUpdateProcessor(updateChildViewsRunnable)
}
registeredObservers.forEach { it.onItemRangeMoved(fromPosition, toPosition, itemCount) }
}
}
override fun dispatchUpdate(update: UpdateOp) {
when (update.cmd) {
UpdateOp.ADD -> onItemsInserted(update.positionStart, update.itemCount)
UpdateOp.REMOVE -> onItemsRemoved(update.positionStart, update.itemCount)
UpdateOp.UPDATE -> onItemsChanged(update.positionStart, update.itemCount, update.payload)
UpdateOp.MOVE -> onItemsMoved(update.positionStart, update.itemCount, update.payload)
}
}
}
| mit | 9e8d9e2eb1b72a5740b9072c765c98ad | 36.888693 | 165 | 0.662066 | 4.890536 | false | false | false | false |
tingtingths/jukebot | app/src/main/java/com/jukebot/jukebot/message/AuthFilter.kt | 1 | 1088 | package com.jukebot.jukebot.message
import com.jukebot.jukebot.Constant
import com.jukebot.jukebot.pojo.Command
import com.jukebot.jukebot.storage.VolatileStorage
import com.jukebot.jukebot.util.Util
import com.pengrad.telegrambot.model.Message
import com.pengrad.telegrambot.model.MessageEntity
import com.pengrad.telegrambot.model.Update
/**
* Created by Ting.
*/
class AuthFilter : UpdateHandler() {
override fun responsible(update: Update): Any? {
var pass: Boolean = false
val verifiedChatId: Long? = VolatileStorage.get(Constant.KEY_VERIFIED_CHAT_ID) as Long?
if (update.message()?.chat()?.id() == verifiedChatId)
pass = true
// if is verify command
if (update.message()?.entities()?.get(0)?.type() == MessageEntity.Type.bot_command) {
val cmd: Command = Util.parseCmd(update.message().text())
if (cmd.cmd != null && cmd.cmd.equals("/bind"))
pass = true
}
return pass
}
override fun handle(pair: Pair<Message, Any>) {
// do nothing...
}
}
| mit | f53b627e430db604e2b95e8a8b9f0255 | 27.631579 | 95 | 0.653493 | 3.985348 | false | false | false | false |
coil-kt/coil | coil-base/src/main/java/coil/memory/MemoryCacheService.kt | 1 | 9260 | package coil.memory
import android.graphics.drawable.BitmapDrawable
import android.util.Log
import androidx.annotation.VisibleForTesting
import coil.EventListener
import coil.ImageLoader
import coil.decode.DataSource
import coil.decode.DecodeUtils
import coil.intercept.EngineInterceptor.ExecuteResult
import coil.intercept.Interceptor
import coil.request.ImageRequest
import coil.request.Options
import coil.request.RequestService
import coil.request.SuccessResult
import coil.size.Scale
import coil.size.Size
import coil.size.isOriginal
import coil.size.pxOrElse
import coil.util.Logger
import coil.util.allowInexactSize
import coil.util.forEachIndexedIndices
import coil.util.isMinOrMax
import coil.util.isPlaceholderCached
import coil.util.log
import coil.util.safeConfig
import coil.util.toDrawable
import kotlin.math.abs
internal class MemoryCacheService(
private val imageLoader: ImageLoader,
private val requestService: RequestService,
private val logger: Logger?,
) {
/** Create a [MemoryCache.Key] for this request. */
fun newCacheKey(
request: ImageRequest,
mappedData: Any,
options: Options,
eventListener: EventListener
): MemoryCache.Key? {
// Fast path: an explicit memory cache key has been set.
request.memoryCacheKey?.let { return it }
// Slow path: create a new memory cache key.
eventListener.keyStart(request, mappedData)
val base = imageLoader.components.key(mappedData, options)
eventListener.keyEnd(request, base)
if (base == null) return null
// Optimize for the typical case where there are no transformations or parameters.
val transformations = request.transformations
val parameterKeys = request.parameters.memoryCacheKeys()
if (transformations.isEmpty() && parameterKeys.isEmpty()) {
return MemoryCache.Key(base)
}
// Else, create a memory cache key with extras.
val extras = parameterKeys.toMutableMap()
if (transformations.isNotEmpty()) {
request.transformations.forEachIndexedIndices { index, transformation ->
extras[EXTRA_TRANSFORMATION_INDEX + index] = transformation.cacheKey
}
extras[EXTRA_TRANSFORMATION_SIZE] = options.size.toString()
}
return MemoryCache.Key(base, extras)
}
/** Get the [MemoryCache.Value] for this request. */
fun getCacheValue(
request: ImageRequest,
cacheKey: MemoryCache.Key,
size: Size,
scale: Scale,
): MemoryCache.Value? {
if (!request.memoryCachePolicy.readEnabled) return null
val cacheValue = imageLoader.memoryCache?.get(cacheKey)
return cacheValue?.takeIf { isCacheValueValid(request, cacheKey, it, size, scale) }
}
/** Return 'true' if [cacheValue] satisfies the [request]. */
@VisibleForTesting
internal fun isCacheValueValid(
request: ImageRequest,
cacheKey: MemoryCache.Key,
cacheValue: MemoryCache.Value,
size: Size,
scale: Scale,
): Boolean {
// Ensure we don't return a hardware bitmap if the request doesn't allow it.
if (!requestService.isConfigValidForHardware(request, cacheValue.bitmap.safeConfig)) {
logger?.log(TAG, Log.DEBUG) {
"${request.data}: Cached bitmap is hardware-backed, " +
"which is incompatible with the request."
}
return false
}
// Ensure the size of the cached bitmap is valid for the request.
return isSizeValid(request, cacheKey, cacheValue, size, scale)
}
/** Return 'true' if [cacheValue]'s size satisfies the [request]. */
private fun isSizeValid(
request: ImageRequest,
cacheKey: MemoryCache.Key,
cacheValue: MemoryCache.Value,
size: Size,
scale: Scale,
): Boolean {
// The cached value must not be sampled if the image's original size is requested.
val isSampled = cacheValue.isSampled
if (size.isOriginal) {
if (isSampled) {
logger?.log(TAG, Log.DEBUG) {
"${request.data}: Requested original size, but cached image is sampled."
}
return false
} else {
return true
}
}
// The requested dimensions must match the transformation size exactly if it is present.
// Unlike standard, requests we can't assume transformed bitmaps for the same image have
// the same aspect ratio.
val transformationSize = cacheKey.extras[EXTRA_TRANSFORMATION_SIZE]
if (transformationSize != null) {
// 'Size.toString' is safe to use to determine equality.
return transformationSize == size.toString()
}
// Compute the scaling factor between the source dimensions and the requested dimensions.
val srcWidth = cacheValue.bitmap.width
val srcHeight = cacheValue.bitmap.height
val dstWidth = size.width.pxOrElse { Int.MAX_VALUE }
val dstHeight = size.height.pxOrElse { Int.MAX_VALUE }
val multiplier = DecodeUtils.computeSizeMultiplier(
srcWidth = srcWidth,
srcHeight = srcHeight,
dstWidth = dstWidth,
dstHeight = dstHeight,
scale = scale
)
// Short circuit the size check if the size is at most 1 pixel off in either dimension.
// This accounts for the fact that downsampling can often produce images with dimensions
// at most one pixel off due to rounding.
val allowInexactSize = request.allowInexactSize
if (allowInexactSize) {
val downsampleMultiplier = multiplier.coerceAtMost(1.0)
if (abs(dstWidth - (downsampleMultiplier * srcWidth)) <= 1 ||
abs(dstHeight - (downsampleMultiplier * srcHeight)) <= 1) {
return true
}
} else {
if ((dstWidth.isMinOrMax() || abs(dstWidth - srcWidth) <= 1) &&
(dstHeight.isMinOrMax() || abs(dstHeight - srcHeight) <= 1)) {
return true
}
}
// The cached value must be equal to the requested size if precision == exact.
if (multiplier != 1.0 && !allowInexactSize) {
logger?.log(TAG, Log.DEBUG) {
"${request.data}: Cached image's request size " +
"($srcWidth, $srcHeight) does not exactly match the requested size " +
"(${size.width}, ${size.height}, $scale)."
}
return false
}
// The cached value must be larger than the requested size if the cached value is sampled.
if (multiplier > 1.0 && isSampled) {
logger?.log(TAG, Log.DEBUG) {
"${request.data}: Cached image's request size " +
"($srcWidth, $srcHeight) is smaller than the requested size " +
"(${size.width}, ${size.height}, $scale)."
}
return false
}
return true
}
/** Write [drawable] to the memory cache. Return 'true' if it was added to the cache. */
fun setCacheValue(
cacheKey: MemoryCache.Key?,
request: ImageRequest,
result: ExecuteResult
): Boolean {
if (!request.memoryCachePolicy.writeEnabled) return false
val memoryCache = imageLoader.memoryCache
if (memoryCache == null || cacheKey == null) return false
val bitmap = (result.drawable as? BitmapDrawable)?.bitmap ?: return false
// Create and set the memory cache value.
val extras = mutableMapOf<String, Any>()
extras[EXTRA_IS_SAMPLED] = result.isSampled
result.diskCacheKey?.let { extras[EXTRA_DISK_CACHE_KEY] = it }
memoryCache[cacheKey] = MemoryCache.Value(bitmap, extras)
return true
}
/** Create a [SuccessResult] from the given [cacheKey] and [cacheValue]. */
fun newResult(
chain: Interceptor.Chain,
request: ImageRequest,
cacheKey: MemoryCache.Key,
cacheValue: MemoryCache.Value
) = SuccessResult(
drawable = cacheValue.bitmap.toDrawable(request.context),
request = request,
dataSource = DataSource.MEMORY_CACHE,
memoryCacheKey = cacheKey,
diskCacheKey = cacheValue.diskCacheKey,
isSampled = cacheValue.isSampled,
isPlaceholderCached = chain.isPlaceholderCached,
)
private val MemoryCache.Value.isSampled: Boolean
get() = (extras[EXTRA_IS_SAMPLED] as? Boolean) ?: false
private val MemoryCache.Value.diskCacheKey: String?
get() = extras[EXTRA_DISK_CACHE_KEY] as? String
companion object {
private const val TAG = "MemoryCacheService"
@VisibleForTesting internal const val EXTRA_TRANSFORMATION_INDEX = "coil#transformation_"
@VisibleForTesting internal const val EXTRA_TRANSFORMATION_SIZE = "coil#transformation_size"
@VisibleForTesting internal const val EXTRA_IS_SAMPLED = "coil#is_sampled"
@VisibleForTesting internal const val EXTRA_DISK_CACHE_KEY = "coil#disk_cache_key"
}
}
| apache-2.0 | 823d9946ca21acb34b9d4ea35867e84c | 38.404255 | 100 | 0.638337 | 4.76828 | false | false | false | false |
Geobert/Efficio | app/src/main/kotlin/fr/geobert/efficio/db/ItemTable.kt | 1 | 1889 | package fr.geobert.efficio.db
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.provider.BaseColumns
import fr.geobert.efficio.data.Item
import fr.geobert.efficio.extensions.normalize
object ItemTable : BaseTable() {
override val TABLE_NAME = "items"
val COL_NAME = "item_name"
val COL_NORM_NAME = "item_norm"
override fun CREATE_COLUMNS() = "$COL_NORM_NAME TEXT NOT NULL UNIQUE ON CONFLICT IGNORE, " +
"$COL_NAME TEXT NOT NULL"
override val COLS_TO_QUERY: Array<String> = arrayOf(BaseColumns._ID, COL_NAME)
val CREATE_TRIGGER_ON_ITEM_DEL by lazy {
"CREATE TRIGGER on_item_deleted " +
"AFTER DELETE ON ${ItemTable.TABLE_NAME} BEGIN " +
"DELETE FROM ${ItemWeightTable.TABLE_NAME} WHERE " +
"${ItemWeightTable.COL_ITEM_ID} = old.${BaseColumns._ID};" +
"DELETE FROM ${ItemDepTable.TABLE_NAME} WHERE " +
"${ItemDepTable.COL_ITEM_ID} = old.${BaseColumns._ID};" +
"DELETE FROM ${ItemWeightTable.TABLE_NAME} WHERE " +
"${ItemWeightTable.COL_ITEM_ID} = old.${BaseColumns._ID};" +
"END"
}
fun create(ctx: Context, item: Item): Long {
val v = ContentValues()
v.put(COL_NORM_NAME, item.normName())
v.put(COL_NAME, item.name)
return insert(ctx, v)
}
fun updateItem(activity: Context, item: Item): Int {
val v = ContentValues()
v.put(COL_NAME, item.name)
v.put(COL_NORM_NAME, item.normName())
return update(activity, item.id, v)
}
fun fetchItemByName(activity: Context, name: String): Cursor? {
return activity.contentResolver.query(ItemTable.CONTENT_URI, ItemTable.COLS_TO_QUERY,
"($COL_NORM_NAME = ?)", arrayOf(name.normalize()), null)
}
} | gpl-2.0 | 7ce4b139c7b4a04cc90e16ad0e44df12 | 36.058824 | 96 | 0.620963 | 3.823887 | false | false | false | false |
quarck/CalendarNotification | app/src/main/java/com/github/quarck/calnotify/ui/SnoozeAllActivity.kt | 1 | 19780 | //
// Calendar Notifications Plus
// Copyright (C) 2016 Sergey Parshin ([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, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
package com.github.quarck.calnotify.ui
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.text.format.DateUtils
import android.view.View
import android.widget.*
import com.github.quarck.calnotify.app.*
import com.github.quarck.calnotify.calendar.*
import com.github.quarck.calnotify.dismissedeventsstorage.EventDismissType
import com.github.quarck.calnotify.eventsstorage.EventsStorage
//import com.github.quarck.calnotify.logs.Logger
import com.github.quarck.calnotify.maps.MapsIntents
import com.github.quarck.calnotify.quiethours.QuietHoursManager
import com.github.quarck.calnotify.textutils.EventFormatter
import com.github.quarck.calnotify.textutils.EventFormatterInterface
import com.github.quarck.calnotify.utils.*
import java.util.*
import com.github.quarck.calnotify.*
import com.github.quarck.calnotify.logs.DevLog
import com.github.quarck.calnotify.permissions.PermissionsManager
import android.content.res.ColorStateList
import android.support.v4.content.ContextCompat
import android.text.method.ScrollingMovementMethod
open class SnoozeAllActivity : AppCompatActivity() {
var state = ViewEventActivityState()
lateinit var snoozePresets: LongArray
lateinit var settings: Settings
lateinit var formatter: EventFormatterInterface
val calendarReloadManager: CalendarReloadManagerInterface = CalendarReloadManager
val calendarProvider: CalendarProviderInterface = CalendarProvider
var snoozeAllIsChange = false
var snoozeFromMainActivity = false
val snoozePresetControlIds = intArrayOf(
R.id.snooze_view_snooze_present1,
R.id.snooze_view_snooze_present2,
R.id.snooze_view_snooze_present3,
R.id.snooze_view_snooze_present4,
R.id.snooze_view_snooze_present5,
R.id.snooze_view_snooze_present6
)
val snoozePresentQuietTimeReminderControlIds = intArrayOf(
R.id.snooze_view_snooze_present1_quiet_time_notice,
R.id.snooze_view_snooze_present2_quiet_time_notice,
R.id.snooze_view_snooze_present3_quiet_time_notice,
R.id.snooze_view_snooze_present4_quiet_time_notice,
R.id.snooze_view_snooze_present5_quiet_time_notice,
R.id.snooze_view_snooze_present6_quiet_time_notice
)
var baselineIds = intArrayOf(
R.id.snooze_view_snooze_present1_quiet_time_notice_baseline,
R.id.snooze_view_snooze_present2_quiet_time_notice_baseline,
R.id.snooze_view_snooze_present3_quiet_time_notice_baseline,
R.id.snooze_view_snooze_present4_quiet_time_notice_baseline,
R.id.snooze_view_snooze_present5_quiet_time_notice_baseline,
R.id.snooze_view_snooze_present6_quiet_time_notice_baseline
)
private val undoManager by lazy { UndoManager }
// These dialog controls moved here so saveInstanceState could store current time selection
var customSnooze_TimeIntervalPickerController: TimeIntervalPickerController? = null
var snoozeUntil_DatePicker: DatePicker? = null
var snoozeUntil_TimePicker: TimePicker? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState != null)
state = ViewEventActivityState.fromBundle(savedInstanceState)
setContentView(R.layout.activity_snooze_all)
val currentTime = System.currentTimeMillis()
settings = Settings(this)
formatter = EventFormatter(this)
snoozeAllIsChange = intent.getBooleanExtra(Consts.INTENT_SNOOZE_ALL_IS_CHANGE, false)
snoozeFromMainActivity = intent.getBooleanExtra(Consts.INTENT_SNOOZE_FROM_MAIN_ACTIVITY, false)
val toolbar = find<Toolbar?>(R.id.toolbar)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
// remove "MM minutes before event" snooze presents for "Snooze All"
// and when event time has passed already
snoozePresets = settings.snoozePresets.filter { it > 0L }.toLongArray()
val isQuiet =
QuietHoursManager(this).isInsideQuietPeriod(
settings,
snoozePresets.map { it -> currentTime + it }.toLongArray())
// Populate snooze controls
for ((idx, id) in snoozePresetControlIds.withIndex()) {
val snoozeLable = findOrThrow<TextView>(id);
val quietTimeNotice = findOrThrow<TextView>(snoozePresentQuietTimeReminderControlIds[idx])
val quietTimeNoticeBaseline = findOrThrow<TextView>(baselineIds[idx])
if (idx < snoozePresets.size) {
snoozeLable.text = formatPreset(snoozePresets[idx])
snoozeLable.visibility = View.VISIBLE;
quietTimeNoticeBaseline.visibility = View.VISIBLE
if (isQuiet[idx])
quietTimeNotice.visibility = View.VISIBLE
else
quietTimeNotice.visibility = View.GONE
}
else {
snoozeLable.visibility = View.GONE;
quietTimeNotice.visibility = View.GONE
quietTimeNoticeBaseline.visibility = View.GONE
}
}
// need to hide these guys
val showCustomSnoozeVisibility = View.VISIBLE
findOrThrow<TextView>(R.id.snooze_view_snooze_custom).visibility = showCustomSnoozeVisibility
val snoozeCustom = find<TextView?>(R.id.snooze_view_snooze_until)
if (snoozeCustom != null)
snoozeCustom.visibility = showCustomSnoozeVisibility
findOrThrow<TextView>(R.id.snooze_snooze_for).text =
if (!snoozeAllIsChange)
this.resources.getString(R.string.snooze_all_events)
else
this.resources.getString(R.string.change_all_events)
find<ImageView?>(R.id.snooze_view_img_custom_period)?.visibility = View.VISIBLE
find<ImageView?>(R.id.snooze_view_img_until)?.visibility = View.VISIBLE
this.title =
if (!snoozeAllIsChange)
resources.getString(R.string.snooze_all_title)
else
resources.getString(R.string.change_all_title)
restoreState(state)
}
private fun formatPreset(preset: Long): String {
val num: Long
val unit: String
val presetSeconds = preset / 1000L;
if (presetSeconds == 0L)
return resources.getString(R.string.until_event_time)
if (presetSeconds % Consts.DAY_IN_SECONDS == 0L) {
num = presetSeconds / Consts.DAY_IN_SECONDS;
unit =
if (num != 1L)
resources.getString(R.string.days)
else
resources.getString(R.string.day)
}
else if (presetSeconds % Consts.HOUR_IN_SECONDS == 0L) {
num = presetSeconds / Consts.HOUR_IN_SECONDS;
unit =
if (num != 1L)
resources.getString(R.string.hours)
else
resources.getString(R.string.hour)
}
else {
num = presetSeconds / Consts.MINUTE_IN_SECONDS;
unit =
if (num != 1L)
resources.getString(R.string.minutes)
else
resources.getString(R.string.minute)
}
if (num <= 0) {
val beforeEventString = resources.getString(R.string.before_event)
return "${-num} $unit $beforeEventString"
}
return "$num $unit"
}
@Suppress("unused", "UNUSED_PARAMETER")
fun onButtonCancelClick(v: View?) {
finish();
}
private fun snoozeEvent(snoozeDelay: Long) {
AlertDialog.Builder(this)
.setMessage(
if (snoozeAllIsChange)
R.string.change_all_notification
else
R.string.snooze_all_confirmation)
.setCancelable(false)
.setPositiveButton(android.R.string.yes) {
_, _ ->
DevLog.debug(LOG_TAG, "Snoozing (change=$snoozeAllIsChange) all requests, snoozeDelay=${snoozeDelay / 1000L}")
val result = ApplicationController.snoozeAllEvents(this, snoozeDelay, snoozeAllIsChange, false);
if (result != null) {
result.toast(this)
}
finish()
}
.setNegativeButton(R.string.cancel) {
_, _ ->
}
.create()
.show()
}
@Suppress("unused", "UNUSED_PARAMETER")
fun OnButtonSnoozeClick(v: View?) {
if (v == null)
return
for ((idx, id) in snoozePresetControlIds.withIndex()) {
if (id == v.id) {
snoozeEvent(snoozePresets[idx]);
break;
}
}
}
public override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
when (state.state) {
ViewEventActivityStateCode.Normal -> {
}
ViewEventActivityStateCode.CustomSnoozeOpened -> {
state.timeAMillis = customSnooze_TimeIntervalPickerController?.intervalMilliseconds ?: 0L
}
ViewEventActivityStateCode.SnoozeUntilOpenedDatePicker -> {
val datePicker = snoozeUntil_DatePicker
if (datePicker != null) {
datePicker.clearFocus()
val date = Calendar.getInstance()
date.set(datePicker.year, datePicker.month, datePicker.dayOfMonth, 0, 0, 0)
state.timeAMillis = date.timeInMillis
state.timeBMillis = 0L
}
}
ViewEventActivityStateCode.SnoozeUntilOpenedTimePicker -> {
val timePicker = snoozeUntil_TimePicker
if (timePicker != null) {
timePicker.clearFocus()
val time = Calendar.getInstance()
time.timeInMillis = state.timeAMillis
time.set(Calendar.HOUR_OF_DAY, timePicker.hour)
time.set(Calendar.MINUTE, timePicker.minute)
state.timeBMillis = time.timeInMillis
}
}
}
// val intervalMilliseconds = customSnooze_TimeIntervalPickerController?.intervalMilliseconds ?: 0L
state.toBundle(outState)
}
private fun restoreState(state: ViewEventActivityState) {
when (state.state) {
ViewEventActivityStateCode.Normal -> {
}
ViewEventActivityStateCode.CustomSnoozeOpened -> {
customSnoozeShowDialog(state.timeAMillis)
}
ViewEventActivityStateCode.SnoozeUntilOpenedDatePicker -> {
snoozeUntilShowDatePickerDialog(state.timeAMillis, state.timeBMillis)
}
ViewEventActivityStateCode.SnoozeUntilOpenedTimePicker -> {
snoozeUntilShowTimePickerDialog(state.timeAMillis, state.timeBMillis)
}
}
}
@Suppress("unused", "UNUSED_PARAMETER")
fun OnButtonCustomSnoozeClick(v: View?) {
customSnoozeShowSimplifiedDialog(persistentState.lastCustomSnoozeIntervalMillis)
}
fun customSnoozeShowSimplifiedDialog(initialTimeValue: Long) {
val intervalNames: Array<String> = this.resources.getStringArray(R.array.default_snooze_intervals)
val intervalValues = this.resources.getIntArray(R.array.default_snooze_intervals_seconds_values)
val builder = AlertDialog.Builder(this)
val adapter = ArrayAdapter<String>(this, R.layout.simple_list_item_medium)
adapter.addAll(intervalNames.toMutableList())
builder.setCancelable(true)
builder.setAdapter(adapter) {
_, which ->
if (which in 0..intervalValues.size-1) {
val intervalSeconds = intervalValues[which].toLong()
if (intervalSeconds != -1L) {
snoozeEvent(intervalSeconds * 1000L)
} else {
customSnoozeShowDialog(initialTimeValue)
}
}
}
builder.show()
}
fun customSnoozeShowDialog(initialTimeValue: Long) {
val dialogView = this.layoutInflater.inflate(R.layout.dialog_interval_picker, null);
val timeIntervalPicker = TimeIntervalPickerController(dialogView, R.string.snooze_for, 0, false)
timeIntervalPicker.intervalMilliseconds = initialTimeValue
state.state = ViewEventActivityStateCode.CustomSnoozeOpened
customSnooze_TimeIntervalPickerController = timeIntervalPicker
val builder = AlertDialog.Builder(this)
builder.setView(dialogView)
builder.setPositiveButton(R.string.snooze) {
_: DialogInterface?, _: Int ->
val intervalMilliseconds = timeIntervalPicker.intervalMilliseconds
this.persistentState.lastCustomSnoozeIntervalMillis = intervalMilliseconds
snoozeEvent(intervalMilliseconds)
state.state = ViewEventActivityStateCode.Normal
customSnooze_TimeIntervalPickerController = null
}
builder.setNegativeButton(R.string.cancel) {
_: DialogInterface?, _: Int ->
state.state = ViewEventActivityStateCode.Normal
customSnooze_TimeIntervalPickerController = null
}
builder.create().show()
}
@Suppress("unused", "UNUSED_PARAMETER")
fun OnButtonSnoozeUntilClick(v: View?) {
val currentlySnoozedUntil = 0L
snoozeUntilShowDatePickerDialog(currentlySnoozedUntil, currentlySnoozedUntil)
}
fun inflateDatePickerDialog() = layoutInflater?.inflate(R.layout.dialog_date_picker, null)
fun inflateTimePickerDialog() = layoutInflater?.inflate(R.layout.dialog_time_picker, null)
@SuppressLint("NewApi")
fun snoozeUntilShowDatePickerDialog(initialValueForDate: Long, initialValueForTime: Long) {
val dialogDate = inflateDatePickerDialog() ?: return
val datePicker = dialogDate.findOrThrow<DatePicker>(R.id.datePickerCustomSnooze)
state.state = ViewEventActivityStateCode.SnoozeUntilOpenedDatePicker
snoozeUntil_DatePicker = datePicker
val firstDayOfWeek = Settings(this).firstDayOfWeek
if (firstDayOfWeek != -1)
snoozeUntil_DatePicker?.firstDayOfWeek = firstDayOfWeek
if (initialValueForDate != 0L) {
val cal = Calendar.getInstance()
cal.timeInMillis = initialValueForDate
val year = cal.get(Calendar.YEAR)
val month = cal.get(Calendar.MONTH)
val day = cal.get(Calendar.DAY_OF_MONTH)
snoozeUntil_DatePicker?.updateDate(year, month, day)
}
val builder = AlertDialog.Builder(this)
builder.setView(dialogDate)
builder.setPositiveButton(R.string.next) {
_: DialogInterface?, _: Int ->
datePicker.clearFocus()
val date = Calendar.getInstance()
date.set(datePicker.year, datePicker.month, datePicker.dayOfMonth, 0, 0, 0)
snoozeUntilShowTimePickerDialog(date.timeInMillis, initialValueForTime)
}
builder.setNegativeButton(R.string.cancel) {
_: DialogInterface?, _: Int ->
state.state = ViewEventActivityStateCode.Normal
snoozeUntil_DatePicker = null
}
builder.create().show()
}
fun snoozeUntilShowTimePickerDialog(currentDateSelection: Long, initialTimeValue: Long) {
val date = Calendar.getInstance()
date.timeInMillis = currentDateSelection
val dialogTime = inflateTimePickerDialog() ?: return
val timePicker: TimePicker = dialogTime.findOrThrow<TimePicker>(R.id.timePickerCustomSnooze)
timePicker.setIs24HourView(android.text.format.DateFormat.is24HourFormat(this))
state.state = ViewEventActivityStateCode.SnoozeUntilOpenedTimePicker
state.timeAMillis = currentDateSelection
snoozeUntil_TimePicker = timePicker
snoozeUntil_DatePicker = null
if (initialTimeValue != 0L) {
val cal = Calendar.getInstance()
cal.timeInMillis = initialTimeValue
timePicker.hour = cal.get(Calendar.HOUR_OF_DAY)
timePicker.minute = cal.get(Calendar.MINUTE)
}
val title = dialogTime.findOrThrow<TextView>(R.id.textViewSnoozeUntilDate)
title.text =
String.format(
resources.getString(R.string.choose_time),
DateUtils.formatDateTime(this, date.timeInMillis, DateUtils.FORMAT_SHOW_DATE))
val builder = AlertDialog.Builder(this)
builder.setView(dialogTime)
builder.setPositiveButton(R.string.snooze) {
_: DialogInterface?, _: Int ->
state.state = ViewEventActivityStateCode.Normal
snoozeUntil_TimePicker = null
timePicker.clearFocus()
// grab time from timePicker + date picker
date.set(Calendar.HOUR_OF_DAY, timePicker.hour)
date.set(Calendar.MINUTE, timePicker.minute)
val snoozeFor = date.timeInMillis - System.currentTimeMillis() + Consts.ALARM_THRESHOLD
if (snoozeFor > 0L) {
snoozeEvent(snoozeFor)
}
else {
// Selected time is in the past
AlertDialog.Builder(this)
.setTitle(R.string.selected_time_is_in_the_past)
.setNegativeButton(R.string.cancel) {
_: DialogInterface?, _: Int ->
}
.create()
.show()
}
}
builder.setNegativeButton(R.string.cancel) {
_: DialogInterface?, _: Int ->
state.state = ViewEventActivityStateCode.Normal
snoozeUntil_TimePicker = null
}
builder.create().show()
}
@Suppress("unused", "UNUSED_PARAMETER")
fun OnButtonRescheduleCustomClick(v: View?) {
}
companion object {
private const val LOG_TAG = "ActivitySnoozeAll"
}
}
| gpl-3.0 | 2c896bd89e7757aef7d15ca0877eb5b2 | 35.62963 | 130 | 0.63094 | 4.782398 | false | false | false | false |
MaibornWolff/codecharta | analysis/model/src/main/kotlin/de/maibornwolff/codecharta/model/Project.kt | 1 | 1435 | package de.maibornwolff.codecharta.model
class Project(
val projectName: String,
private val nodes: List<Node> = listOf(Node("root", NodeType.Folder)),
val apiVersion: String = API_VERSION,
val edges: List<Edge> = listOf(),
val attributeTypes: Map<String, MutableMap<String, AttributeType>> = mapOf(),
val attributeDescriptors: Map<String, AttributeDescriptor> = mapOf(),
var blacklist: List<BlacklistItem> = listOf()
) {
init {
if (nodes.size != 1) throw IllegalStateException("no root node present in project")
}
val rootNode: Node
get() = nodes[0]
val size: Int
get() = rootNode.size
fun sizeOfEdges(): Int {
return edges.size
}
fun sizeOfBlacklist(): Int {
return blacklist.size
}
override fun toString(): String {
return "Project{projectName=$projectName, apiVersion=$apiVersion, nodes=$nodes, edges=$edges, attributeTypes=$attributeTypes, attributeDescriptors=$attributeDescriptors, blacklist=$blacklist}"
}
companion object {
private const val API_VERSION_MAJOR = "1"
private const val API_VERSION_MINOR = "3"
const val API_VERSION = "$API_VERSION_MAJOR.$API_VERSION_MINOR"
fun isAPIVersionCompatible(apiVersion: String): Boolean {
val apiVersion_major = apiVersion.split('.')[0]
return apiVersion_major == API_VERSION_MAJOR
}
}
}
| bsd-3-clause | fef011fbe4bed7840d90affcafa7e62b | 30.888889 | 200 | 0.654355 | 4.429012 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/misc/DiscordBotListTopLocalCommand.kt | 1 | 2809 | package net.perfectdreams.loritta.morenitta.commands.vanilla.misc
import net.perfectdreams.loritta.morenitta.tables.GuildProfiles
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.morenitta.messages.LorittaReply
import net.perfectdreams.loritta.common.utils.image.JVMImage
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands.DiscordAbstractCommandBase
import net.perfectdreams.loritta.morenitta.tables.BotVotes
import net.perfectdreams.loritta.morenitta.utils.RankingGenerator
import org.jetbrains.exposed.sql.*
class DiscordBotListTopLocalCommand(loritta: LorittaBot): DiscordAbstractCommandBase(loritta, listOf("dbl top local"), net.perfectdreams.loritta.common.commands.CommandCategory.MISC) {
companion object {
private const val LOCALE_PREFIX = "commands.command.dbltoplocal"
}
override fun command() = create {
localizedDescription("$LOCALE_PREFIX.description")
executesDiscord {
var page = args.getOrNull(0)?.toLongOrNull()
if (page != null && !RankingGenerator.isValidRankingPage(page)) {
reply(
LorittaReply(
locale["commands.invalidRankingPage"],
Constants.ERROR
)
)
return@executesDiscord
}
if (page != null)
page -= 1
if (page == null)
page = 0
val userId = BotVotes.userId
val userIdCount = BotVotes.userId.count()
val userData = loritta.newSuspendedTransaction {
BotVotes.innerJoin(GuildProfiles, { GuildProfiles.userId }, { userId })
.slice(userId, userIdCount)
.select {
GuildProfiles.guildId eq guild.idLong and (GuildProfiles.isInGuild eq true)
}
.groupBy(userId)
.orderBy(userIdCount, SortOrder.DESC)
.limit(5, page * 5)
.toList()
}
sendImage(
JVMImage(
RankingGenerator.generateRanking(
loritta,
guild.name,
guild.iconUrl,
userData.map {
RankingGenerator.UserRankInformation(
it[userId],
locale["${LOCALE_PREFIX}.votes", it[userIdCount]]
)
}
)
),
"rank.png",
getUserMention(true)
)
}
}
} | agpl-3.0 | 264880132db1e025cbffbf01215afb22 | 36.972973 | 184 | 0.553934 | 5.551383 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/magic/SetSelfBackgroundExecutor.kt | 1 | 1034 | package net.perfectdreams.loritta.morenitta.commands.vanilla.magic
import net.perfectdreams.loritta.morenitta.api.commands.CommandContext
import net.perfectdreams.loritta.morenitta.messages.LorittaReply
import net.perfectdreams.loritta.cinnamon.pudding.tables.Backgrounds
import net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands.DiscordCommandContext
import org.jetbrains.exposed.dao.id.EntityID
object SetSelfBackgroundExecutor : LoriToolsCommand.LoriToolsExecutor {
override val args = "set self_background <internalType>"
override fun executes(): suspend CommandContext.() -> Boolean = task@{
if (args.getOrNull(0) != "set")
return@task false
if (args.getOrNull(1) != "self_background")
return@task false
val context = checkType<DiscordCommandContext>(this)
loritta.pudding.transaction {
context.lorittaUser.profile.settings.activeBackgroundInternalName = EntityID(args[2], Backgrounds)
}
context.reply(
LorittaReply(
"Background alterado!"
)
)
return@task true
}
} | agpl-3.0 | 797ad316b1194ae1618201565715aa44 | 33.5 | 101 | 0.788201 | 3.976923 | false | false | false | false |
NoodleMage/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/manga/info/MangaInfoPresenter.kt | 2 | 6008 | package eu.kanade.tachiyomi.ui.manga.info
import android.os.Bundle
import com.jakewharton.rxrelay.BehaviorRelay
import com.jakewharton.rxrelay.PublishRelay
import eu.kanade.tachiyomi.data.cache.CoverCache
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Category
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.database.models.MangaCategory
import eu.kanade.tachiyomi.data.download.DownloadManager
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter
import eu.kanade.tachiyomi.util.isNullOrUnsubscribed
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.util.*
/**
* Presenter of MangaInfoFragment.
* Contains information and data for fragment.
* Observable updates should be called from here.
*/
class MangaInfoPresenter(
val manga: Manga,
val source: Source,
private val chapterCountRelay: BehaviorRelay<Float>,
private val lastUpdateRelay: BehaviorRelay<Date>,
private val mangaFavoriteRelay: PublishRelay<Boolean>,
private val db: DatabaseHelper = Injekt.get(),
private val downloadManager: DownloadManager = Injekt.get(),
private val coverCache: CoverCache = Injekt.get()
) : BasePresenter<MangaInfoController>() {
/**
* Subscription to send the manga to the view.
*/
private var viewMangaSubscription: Subscription? = null
/**
* Subscription to update the manga from the source.
*/
private var fetchMangaSubscription: Subscription? = null
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
sendMangaToView()
// Update chapter count
chapterCountRelay.observeOn(AndroidSchedulers.mainThread())
.subscribeLatestCache(MangaInfoController::setChapterCount)
// Update favorite status
mangaFavoriteRelay.observeOn(AndroidSchedulers.mainThread())
.subscribe { setFavorite(it) }
.apply { add(this) }
//update last update date
lastUpdateRelay.observeOn(AndroidSchedulers.mainThread())
.subscribeLatestCache(MangaInfoController::setLastUpdateDate)
}
/**
* Sends the active manga to the view.
*/
fun sendMangaToView() {
viewMangaSubscription?.let { remove(it) }
viewMangaSubscription = Observable.just(manga)
.subscribeLatestCache({ view, manga -> view.onNextManga(manga, source) })
}
/**
* Fetch manga information from source.
*/
fun fetchMangaFromSource() {
if (!fetchMangaSubscription.isNullOrUnsubscribed()) return
fetchMangaSubscription = Observable.defer { source.fetchMangaDetails(manga) }
.map { networkManga ->
manga.copyFrom(networkManga)
manga.initialized = true
db.insertManga(manga).executeAsBlocking()
manga
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext { sendMangaToView() }
.subscribeFirst({ view, _ ->
view.onFetchMangaDone()
}, { view, _ ->
view.onFetchMangaError()
})
}
/**
* Update favorite status of manga, (removes / adds) manga (to / from) library.
*
* @return the new status of the manga.
*/
fun toggleFavorite(): Boolean {
manga.favorite = !manga.favorite
if (!manga.favorite) {
coverCache.deleteFromCache(manga.thumbnail_url)
}
db.insertManga(manga).executeAsBlocking()
sendMangaToView()
return manga.favorite
}
private fun setFavorite(favorite: Boolean) {
if (manga.favorite == favorite) {
return
}
toggleFavorite()
}
/**
* Returns true if the manga has any downloads.
*/
fun hasDownloads(): Boolean {
return downloadManager.getDownloadCount(manga) > 0
}
/**
* Deletes all the downloads for the manga.
*/
fun deleteDownloads() {
downloadManager.deleteManga(manga, source)
}
/**
* Get the default, and user categories.
*
* @return List of categories, default plus user categories
*/
fun getCategories(): List<Category> {
return db.getCategories().executeAsBlocking()
}
/**
* Gets the category id's the manga is in, if the manga is not in a category, returns the default id.
*
* @param manga the manga to get categories from.
* @return Array of category ids the manga is in, if none returns default id
*/
fun getMangaCategoryIds(manga: Manga): Array<Int> {
val categories = db.getCategoriesForManga(manga).executeAsBlocking()
return categories.mapNotNull { it.id }.toTypedArray()
}
/**
* Move the given manga to categories.
*
* @param manga the manga to move.
* @param categories the selected categories.
*/
fun moveMangaToCategories(manga: Manga, categories: List<Category>) {
val mc = categories.filter { it.id != 0 }.map { MangaCategory.create(manga, it) }
db.setMangaCategories(mc, listOf(manga))
}
/**
* Move the given manga to the category.
*
* @param manga the manga to move.
* @param category the selected category, or null for default category.
*/
fun moveMangaToCategory(manga: Manga, category: Category?) {
moveMangaToCategories(manga, listOfNotNull(category))
}
}
| apache-2.0 | e8d96b633ec00fc158c1e8cbdc8c702f | 32.331429 | 105 | 0.630826 | 4.833467 | false | false | false | false |
kotlintest/kotlintest | kotest-assertions/src/jvmMain/kotlin/io/kotest/properties/default.kt | 1 | 3104 | package io.kotest.properties
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.lang.reflect.WildcardType
@Suppress("UNCHECKED_CAST")
actual inline fun <reified T> Gen.Companion.default(): Gen<T> {
return when (T::class.qualifiedName) {
List::class.qualifiedName -> {
val type = object : TypeReference<T>() {}.type as ParameterizedType
val first = type.actualTypeArguments.first() as WildcardType
val upper = first.upperBounds.first() as Class<*>
list(forClassName(upper.name) as Gen<Any>) as Gen<T>
}
Set::class.qualifiedName -> {
val type = object : TypeReference<T>() {}.type as ParameterizedType
val first = type.actualTypeArguments.first() as WildcardType
val upper = first.upperBounds.first() as Class<*>
set(forClassName(upper.name) as Gen<Any>) as Gen<T>
}
Pair::class.qualifiedName -> {
val type = object : TypeReference<T>() {}.type as ParameterizedType
val first = (type.actualTypeArguments[0] as WildcardType).upperBounds.first() as Class<*>
val second = (type.actualTypeArguments[1] as WildcardType).upperBounds.first() as Class<*>
pair(forClassName(first.name), forClassName(second.name)) as Gen<T>
}
Map::class.qualifiedName -> {
val type = object : TypeReference<T>() {}.type as ParameterizedType
//map key type can have or have not variance
val first = if (type.actualTypeArguments[0] is Class<*>) {
type.actualTypeArguments[0] as Class<*>
} else {
(type.actualTypeArguments[0] as WildcardType).upperBounds.first() as Class<*>
}
val second = (type.actualTypeArguments[1] as WildcardType).upperBounds.first() as Class<*>
map(forClassName(first.name), forClassName(second.name)) as Gen<T>
}
else -> Gen.forClassName(T::class.qualifiedName!!) as Gen<T>
}
}
fun Gen.Companion.forClassName(className: String): Gen<*> {
return when (className) {
"java.lang.String", "kotlin.String" -> Gen.string()
"java.lang.Integer", "kotlin.Int" -> Gen.int()
"java.lang.Short", "kotlin.Short" -> Gen.short()
"java.lang.Byte", "kotlin.Byte" -> Gen.byte()
"java.lang.Long", "kotlin.Long" -> Gen.long()
"java.lang.Boolean", "kotlin.Boolean" -> Gen.bool()
"java.lang.Float", "kotlin.Float" -> Gen.float()
"java.lang.Double", "kotlin.Double" -> Gen.double()
"java.util.UUID" -> Gen.uuid()
"java.io.File" -> Gen.file()
"java.time.LocalDate" -> Gen.localDate()
"java.time.LocalDateTime" -> Gen.localDateTime()
"java.time.LocalTime" -> Gen.localTime()
"java.time.Duration" -> Gen.duration()
"java.time.Period" -> Gen.period()
else -> throw IllegalArgumentException("Cannot infer generator for $className; specify generators explicitly")
}
}
// need some supertype that types a type param so it gets baked into the class file
abstract class TypeReference<T> : Comparable<TypeReference<T>> {
val type: Type = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0]
override fun compareTo(other: TypeReference<T>) = 0
}
| apache-2.0 | 496afb29c431ce13048b1d875411461b | 44.647059 | 114 | 0.678802 | 3.894605 | false | false | false | false |
JetBrains/resharper-unity | rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/debugger/breakpoints/UnityPausepointConstants.kt | 1 | 1262 | package com.jetbrains.rider.plugins.unity.debugger.breakpoints
import com.intellij.openapi.util.NlsActions.ActionText
import com.jetbrains.rider.plugins.unity.UnityBundle
import org.jetbrains.annotations.Nls
object UnityPausepointConstants {
const val pauseEditorCommand = "(UnityEditor.EditorApplication.isPaused = true) ? \"Unity pausepoint hit. Pausing Unity editor at the end of frame\" : \"Unable to pause Unity editor\""
@get:ActionText
val convertToPausepointActionText = UnityBundle.message("convert.to.unity.pausepoint.action.text")
@Nls(capitalization = Nls.Capitalization.Sentence)
val convertToPausepointLabelLinkText = UnityBundle.message("convert.to.unity.pausepoint.label.link")
@Nls(capitalization = Nls.Capitalization.Title)
val convertToLineBreakpointActionText = UnityBundle.message("action.text.convert.to.line.breakpoint")
@Nls(capitalization = Nls.Capitalization.Sentence)
val convertToLineBreakpointLabelLinkText = UnityBundle.message("label.link.convert.to.line.breakpoint")
const val unsupportedDebugTargetMessage = "Unity pausepoints are only available when debugging a Unity editor process"
const val unavailableWhenNotPlayingMessage = "Unity pausepoints are only available in play mode"
} | apache-2.0 | 125451836a800aa6d039f48b067655e4 | 65.473684 | 188 | 0.805864 | 4.443662 | false | false | false | false |
CarrotCodes/Warren | src/main/kotlin/chat/willow/warren/handler/CtcpHelper.kt | 1 | 1305 | package chat.willow.warren.handler
import chat.willow.kale.irc.CharacterCodes
enum class CtcpEnum {
NONE,
UNKNOWN,
ACTION;
companion object {
fun from(rawMessage: String): CtcpEnum {
val message = if (rawMessage.startsWith(CharacterCodes.CTCP)) {
rawMessage.substring(1)
} else {
return NONE
}
if (message.startsWith("ACTION ")) {
return ACTION
}
return UNKNOWN
}
}
}
object CtcpHelper {
val CTCP: String = Character.toString(CharacterCodes.CTCP)
fun isMessageCTCP(message: String): Boolean = (message.startsWith(CTCP) && message.endsWith(CTCP))
// Trims <ctcp><identifier><space><rest of message><ctcp> to <rest of message>
fun trimCTCP(rawMessage: String): String {
var message = rawMessage
if (message.startsWith(CTCP)) {
message = message.substring(1)
}
if (message.endsWith(CTCP)) {
message = message.substring(0, message.length - 1)
}
val spacePosition = message.indexOf(CharacterCodes.SPACE)
if (spacePosition > 0) {
message = message.substring(spacePosition + 1, message.length)
}
return message
}
} | isc | bad1902d2a109ca0aa28b61cd340617d | 23.641509 | 102 | 0.585441 | 4.264706 | false | false | false | false |
google/horologist | audio-ui/src/main/java/com/google/android/horologist/audio/ui/components/DeviceChip.kt | 1 | 2366 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.audio.ui.components
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.onClick
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.ui.text.style.TextOverflow
import androidx.wear.compose.material.Chip
import androidx.wear.compose.material.ChipDefaults
import androidx.wear.compose.material.Text
import com.google.android.horologist.audio.ui.R
@Composable
public fun DeviceChip(
volumeDescription: String,
deviceName: String,
icon: @Composable BoxScope.() -> Unit,
onAudioOutputClick: () -> Unit,
modifier: Modifier = Modifier
) {
val onClickLabel = stringResource(id = R.string.horologist_volume_screen_change_audio_output)
Chip(
modifier = modifier
.width(intrinsicSize = IntrinsicSize.Max)
.semantics {
stateDescription = volumeDescription
onClick(onClickLabel) { onAudioOutputClick(); true }
},
label = {
Text(
modifier = Modifier.fillMaxWidth(),
text = deviceName,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
},
icon = icon,
onClick = onAudioOutputClick,
// Device chip uses secondary colors (surface/onSurface)
colors = ChipDefaults.secondaryChipColors()
)
}
| apache-2.0 | 9451862adc4a9f7e9127c9467ae72ce1 | 35.4 | 97 | 0.714286 | 4.585271 | false | false | false | false |
googleapis/gax-kotlin | kgax-grpc-base/src/test/kotlin/com/google/api/kgax/grpc/BasicInterceptorTest.kt | 1 | 3888 | /*
* 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.api.kgax.grpc
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockito_kotlin.check
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.reset
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import io.grpc.CallOptions
import io.grpc.Channel
import io.grpc.ClientCall
import io.grpc.Metadata
import io.grpc.MethodDescriptor
import io.grpc.Status
import kotlin.test.BeforeTest
import kotlin.test.Test
class BasicInterceptorTest {
val method: MethodDescriptor<String, String> = mock()
val clientCall: ClientCall<String, String> = mock()
val channel: Channel = mock()
val callOptions: CallOptions = mock()
val responseListener: ClientCall.Listener<String> = mock()
@BeforeTest
fun before() {
reset(method, clientCall, channel, callOptions, responseListener)
whenever(channel.newCall(method, callOptions)).doReturn(clientCall)
}
@Test
fun `calls onReady`() {
val message = "hey"
val metadata = Metadata()
var isReady = false
val interceptor = BasicInterceptor(onReady = { isReady = true })
interceptor.interceptCall(method, callOptions, channel)
.start(responseListener, metadata)
verify(clientCall).start(check {
simulateCall(it, metadata, message)
}, eq(metadata))
assertThat(isReady).isTrue()
}
@Test
fun `calls onClose`() {
val metadata = Metadata()
var isClosed = false
val interceptor = BasicInterceptor(onClose = { _, _ -> isClosed = true })
interceptor.interceptCall(method, callOptions, channel)
.start(responseListener, metadata)
verify(clientCall).start(check {
simulateCall(it, metadata, "")
}, eq(metadata))
assertThat(isClosed).isTrue()
}
@Test
fun `calls onHeaders`() {
val message = "hey"
val metadata = Metadata()
var capturedMetadata: Metadata? = null
val interceptor = BasicInterceptor(onHeaders = { capturedMetadata = it })
interceptor.interceptCall(method, callOptions, channel)
.start(responseListener, metadata)
verify(clientCall).start(check {
simulateCall(it, metadata, message)
}, eq(metadata))
assertThat(capturedMetadata).isEqualTo(metadata)
}
@Test
fun `calls onMessage`() {
val message = "hi there"
val metadata = Metadata()
var capturedMessage: String? = null
val interceptor = BasicInterceptor(onMessage = { capturedMessage = it as? String })
interceptor.interceptCall(method, callOptions, channel)
.start(responseListener, metadata)
verify(clientCall).start(check {
simulateCall(it, metadata, message)
}, eq(metadata))
assertThat(capturedMessage).isEqualTo("hi there")
}
private fun <T> simulateCall(listener: ClientCall.Listener<T>, metadata: Metadata, message: T) {
listener.onReady()
listener.onHeaders(metadata)
listener.onMessage(message)
listener.onClose(Status.OK, Metadata())
}
} | apache-2.0 | ccc71c1d34c92f820e99cc0ddd4b3268 | 31.680672 | 100 | 0.676955 | 4.428246 | false | true | false | false |
emufog/emufog | src/main/kotlin/emufog/container/Container.kt | 1 | 2405 | /*
* MIT License
*
* Copyright (c) 2018 emufog 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 emufog.container
/**
* Abstract class of a container that can be deployed in the final experiment. Consists of a name and tag as well as
* limits on memory and cpu share.
*
* @property name name of container image to deploy
* @property tag version tag of container image to deploy
* @property memoryLimit upper limit of memory to use in Bytes `>= 0`
* @property cpuShare share of the sum of available computing resources `>= 0`
* @throws IllegalArgumentException thrown if [memoryLimit] is `< 0`, [cpuShare] is `< 0`, [name] or [tag] are blank
*/
abstract class Container(
val name: String,
val tag: String,
val memoryLimit: Int,
val cpuShare: Float
) {
init {
require(name.isNotBlank()) { "The container's name can not be blank." }
require(tag.isNotBlank()) { "The container's tag can not be blank." }
require(memoryLimit >= 0) { "The container's memory limit can not be negative." }
require(cpuShare >= 0) { "The container's cpu share can not be negative." }
}
/**
* Returns the full name of the container in the form of name:tag.
*/
fun fullName(): String = "$name:$tag"
override fun toString(): String = "[${fullName()}, memory=$memoryLimit, cpu=$cpuShare]"
}
| mit | 5842533bf30a394e027fc627abb394f0 | 41.946429 | 116 | 0.711435 | 4.317774 | false | false | false | false |
FredJul/TaskGame | TaskGame/src/main/java/net/fred/taskgame/utils/date/ReminderPickers.kt | 1 | 3364 | /*
* Copyright (c) 2012-2017 Frederic Julian
*
* 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:></http:>//www.gnu.org/licenses/>.
*/
package net.fred.taskgame.utils.date
import android.app.DatePickerDialog
import android.app.DatePickerDialog.OnDateSetListener
import android.app.TimePickerDialog
import android.app.TimePickerDialog.OnTimeSetListener
import android.support.v4.app.FragmentActivity
import android.text.format.DateFormat
import android.widget.DatePicker
import android.widget.TimePicker
import net.fred.taskgame.listeners.OnReminderPickedListener
import java.util.*
class ReminderPickers(private val mActivity: FragmentActivity, private val mOnReminderPickedListener: OnReminderPickedListener?) : OnDateSetListener, OnTimeSetListener {
private var mReminderYear: Int = 0
private var mReminderMonth: Int = 0
private var mReminderDay: Int = 0
private var mPresetDateTime: Long = 0
fun pick(presetDateTime: Long) {
mPresetDateTime = presetDateTime
showDatePickerDialog(mPresetDateTime)
}
private fun showDatePickerDialog(presetDateTime: Long) {
// Use the current date as the default date in the picker
val cal = DateHelper.getCalendar(presetDateTime)
val y = cal.get(Calendar.YEAR)
val m = cal.get(Calendar.MONTH)
val d = cal.get(Calendar.DAY_OF_MONTH)
val picker = DatePickerDialog(mActivity, android.R.style.Theme_Material_Light_Dialog_Alert, this, y, m, d)
picker.setOnDismissListener {
mOnReminderPickedListener?.onReminderDismissed()
}
picker.show()
}
private fun showTimePickerDialog(presetDateTime: Long) {
val cal = DateHelper.getCalendar(presetDateTime)
val hour = cal.get(Calendar.HOUR_OF_DAY)
val minute = cal.get(Calendar.MINUTE)
// Create a new instance of TimePickerDialog and return it
val is24HourMode = DateFormat.is24HourFormat(mActivity)
val picker = TimePickerDialog(mActivity, android.R.style.Theme_Material_Light_Dialog_Alert, this, hour, minute, is24HourMode)
picker.setOnDismissListener {
mOnReminderPickedListener?.onReminderDismissed()
}
picker.show()
}
override fun onTimeSet(view: TimePicker, hourOfDay: Int, minute: Int) {
// Setting alarm time in milliseconds
val c = Calendar.getInstance()
c.set(mReminderYear, mReminderMonth, mReminderDay, hourOfDay, minute)
mOnReminderPickedListener?.onReminderPicked(c.timeInMillis)
}
override fun onDateSet(view: DatePicker, year: Int, monthOfYear: Int, dayOfMonth: Int) {
mReminderYear = year
mReminderMonth = monthOfYear
mReminderDay = dayOfMonth
showTimePickerDialog(mPresetDateTime)
}
}
| gpl-3.0 | e27b199658f7e0468a26c772758e5546 | 38.116279 | 169 | 0.726516 | 4.461538 | false | false | false | false |
fnberta/PopularMovies | app/src/main/java/ch/berta/fabio/popularmovies/data/dtos/Video.kt | 1 | 1063 | /*
* Copyright (c) 2017 Fabio Berta
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.berta.fabio.popularmovies.data.dtos
const val YOUTUBE_BASE_URL = "https://www.youtube.com/watch?v="
const val YOU_TUBE = "YouTube"
/**
* Represents a video (e.g. trailer) of a movie, obtained from TheMovieDb.
*/
data class Video(
val name: String,
val key: String,
val site: String,
val size: Int,
val type: String
) {
fun siteIsYouTube(): Boolean = site == ch.berta.fabio.popularmovies.data.dtos.YOU_TUBE
}
| apache-2.0 | 2e763b42fb64777838fc1c9d5fa78cbb | 31.212121 | 90 | 0.700847 | 3.742958 | false | false | false | false |
chrisbanes/tivi | data/src/main/java/app/tivi/data/RetrofitExtensions.kt | 1 | 2827 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("NOTHING_TO_INLINE")
package app.tivi.data
import kotlinx.coroutines.delay
import retrofit2.HttpException
import retrofit2.Response
import java.io.IOException
inline fun <T> Response<T>.bodyOrThrow(): T = if (isSuccessful) body()!! else throw HttpException(this)
suspend fun <T> withRetry(
defaultDelay: Long = 100,
maxAttempts: Int = 3,
shouldRetry: (Throwable) -> Boolean = ::defaultShouldRetry,
block: suspend () -> T
): T {
repeat(maxAttempts) { attempt ->
val response = runCatching { block() }
when {
response.isSuccess -> return response.getOrThrow()
response.isFailure -> {
val exception = response.exceptionOrNull()!!
// The response failed, so lets see if we should retry again
if (attempt == maxAttempts - 1 || !shouldRetry(exception)) {
throw exception
}
var nextDelay = attempt * attempt * defaultDelay
if (exception is HttpException) {
// If we have a HttpException, check whether we have a Retry-After
// header to decide how long to delay
exception.retryAfter?.let {
nextDelay = it.coerceAtLeast(defaultDelay)
}
}
delay(nextDelay)
}
}
}
// We should never hit here
throw IllegalStateException("Unknown exception from executeWithRetry")
}
private val HttpException.retryAfter: Long?
get() {
val retryAfterHeader = response()?.headers()?.get("Retry-After")
if (retryAfterHeader != null && retryAfterHeader.isNotEmpty()) {
// Got a Retry-After value, try and parse it to an long
try {
return retryAfterHeader.toLong() + 10
} catch (nfe: NumberFormatException) {
// Probably won't happen, ignore the value and use the generated default above
}
}
return null
}
private fun defaultShouldRetry(throwable: Throwable) = when (throwable) {
is HttpException -> throwable.code() == 429
is IOException -> true
else -> false
}
| apache-2.0 | b724309edc246beb2d6483961ab706e5 | 32.654762 | 103 | 0.616908 | 4.767285 | false | false | false | false |
pnemonic78/RemoveDuplicates | duplicates-android/app/src/main/java/com/github/duplicates/alarm/SamsungAlarmProvider.kt | 1 | 5808 | /*
* Copyright 2016, Moshe Waisberg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.duplicates.alarm
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.provider.BaseColumns._ID
import com.github.duplicates.DaysOfWeek
import com.github.duplicates.DuplicateProvider
/**
* Provide duplicate messages for Samsung devices.
*
* @author moshe.w
*/
class SamsungAlarmProvider(context: Context) : DuplicateProvider<AlarmItem>(context) {
override fun getContentUri(): Uri? {
return Uri.parse("content://com.samsung.sec.android.clockpackage/alarm")
}
override fun getCursorProjection(): Array<String> {
return PROJECTION
}
override fun createItem(cursor: Cursor): AlarmItem {
return AlarmItem()
}
override fun populateItem(cursor: Cursor, item: AlarmItem) {
item.id = cursor.getLong(INDEX_ID)
item.activate = cursor.getInt(INDEX_ACTIVE)
item.soundTone = cursor.getInt(INDEX_ALARMSOUND)
item.alarmTime = cursor.getInt(INDEX_ALARMTIME)
item.soundTone = cursor.getInt(INDEX_ALARMTONE)
item.soundUri = cursor.getString(INDEX_ALARMURI)
item.alertTime = cursor.getLong(INDEX_ALERTTIME)
item.createTime = cursor.getLong(INDEX_CREATETIME)
item.isDailyBriefing = cursor.getInt(INDEX_DAILYBRIEF) != 0
item.name = empty(cursor, INDEX_NAME)
item.notificationType = cursor.getInt(INDEX_NOTITYPE)
item.repeat = toDaysOfWeek(cursor.getInt(INDEX_REPEATTYPE))
item.isSubdueActivate = cursor.getInt(INDEX_SBDACTIVE) != 0
item.subdueDuration = cursor.getInt(INDEX_SBDDURATION)
item.subdueTone = cursor.getInt(INDEX_SBDTONE)
item.subdueUri = cursor.getInt(INDEX_SBDURI)
item.isSnoozeActivate = cursor.getInt(INDEX_SNZACTIVE) != 0
item.snoozeDoneCount = cursor.getInt(INDEX_SNZCOUNT)
item.snoozeDuration = cursor.getInt(INDEX_SNZDURATION)
item.snoozeRepeat = cursor.getInt(INDEX_SNZREPEAT)
item.volume = cursor.getInt(INDEX_VOLUME)
}
override fun getReadPermissions(): Array<String> {
return PERMISSIONS_READ
}
override fun getDeletePermissions(): Array<String> {
return PERMISSIONS_WRITE
}
protected fun toDaysOfWeek(repeat: Int): DaysOfWeek? {
if (repeat and REPEAT_WEEKLY != REPEAT_WEEKLY) {
return null
}
val daysOfWeek = DaysOfWeek(0)
daysOfWeek.set(0, repeat and DAY_SUNDAY == DAY_SUNDAY)
daysOfWeek.set(1, repeat and DAY_MONDAY == DAY_MONDAY)
daysOfWeek.set(2, repeat and DAY_TUESDAY == DAY_TUESDAY)
daysOfWeek.set(3, repeat and DAY_WEDNESDAY == DAY_WEDNESDAY)
daysOfWeek.set(4, repeat and DAY_THURSDAY == DAY_THURSDAY)
daysOfWeek.set(5, repeat and DAY_FRIDAY == DAY_FRIDAY)
daysOfWeek.set(6, repeat and DAY_SATURDAY == DAY_SATURDAY)
return daysOfWeek
}
companion object {
const val PACKAGE = "com.sec.android.app.clockpackage"
private val PERMISSIONS_READ =
arrayOf("com.sec.android.app.clockpackage.permission.READ_ALARM")
private val PERMISSIONS_WRITE =
arrayOf("com.sec.android.app.clockpackage.permission.WRITE_ALARM")
private val PROJECTION = arrayOf(
_ID,
"active",
"createtime",
"alerttime",
"alarmtime",
"repeattype",
"notitype",
"snzactive",
"snzduration",
"snzrepeat",
"snzcount",
"dailybrief",
"sbdactive",
"sbdduration",
"sbdtone",
"alarmsound",
"alarmtone",
"volume",
"sbduri",
"alarmuri",
"name"
)
private const val INDEX_ID = 0
private const val INDEX_ACTIVE = 1
private const val INDEX_CREATETIME = 2
private const val INDEX_ALERTTIME = 3
private const val INDEX_ALARMTIME = 4
private const val INDEX_REPEATTYPE = 5
private const val INDEX_NOTITYPE = 6
private const val INDEX_SNZACTIVE = 7
private const val INDEX_SNZDURATION = 8
private const val INDEX_SNZREPEAT = 9
private const val INDEX_SNZCOUNT = 10
private const val INDEX_DAILYBRIEF = 11
private const val INDEX_SBDACTIVE = 12
private const val INDEX_SBDDURATION = 13
private const val INDEX_SBDTONE = 14
private const val INDEX_ALARMSOUND = 15
private const val INDEX_ALARMTONE = 16
private const val INDEX_VOLUME = 17
private const val INDEX_SBDURI = 18
private const val INDEX_ALARMURI = 19
private const val INDEX_NAME = 20
private const val REPEAT_WEEKLY = 0x00000005
private const val REPEAT_TOMORROW = 0x00000001
private const val DAY_SUNDAY = 0x10000000
private const val DAY_MONDAY = 0x01000000
private const val DAY_TUESDAY = 0x00100000
private const val DAY_WEDNESDAY = 0x00010000
private const val DAY_THURSDAY = 0x00001000
private const val DAY_FRIDAY = 0x00000100
private const val DAY_SATURDAY = 0x10000010
}
}
| apache-2.0 | 7003d8a93197ae68057ddd7ca260a3d1 | 35.993631 | 86 | 0.653409 | 4.202605 | false | false | false | false |
rock3r/detekt | detekt-cli/src/test/kotlin/io/gitlab/arturbosch/detekt/cli/ExtensionsSpec.kt | 1 | 1278 | package io.gitlab.arturbosch.detekt.cli
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.SetupContext
import io.gitlab.arturbosch.detekt.api.UnstableApi
import io.gitlab.arturbosch.detekt.rules.documentation.LicenceHeaderLoaderExtension
import io.gitlab.arturbosch.detekt.test.NullPrintStream
import org.assertj.core.api.Assertions.assertThatCode
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.io.PrintStream
import java.net.URI
@UnstableApi
class ExtensionsSpec : Spek({
describe("Licence header extension - #2503") {
it("should not crash when using resources") {
assertThatCode {
val uris = CliArgs {
configResource = "extensions/config.yml"
}.extractUris()
LicenceHeaderLoaderExtension().init(object : SetupContext {
override val configUris: Collection<URI> = uris
override val config: Config = Config.empty
override val outPrinter: PrintStream = NullPrintStream()
override val errPrinter: PrintStream = NullPrintStream()
})
}.doesNotThrowAnyException()
}
}
})
| apache-2.0 | 384657d8f64e5e046ba73ae04572dc54 | 36.588235 | 83 | 0.681534 | 4.786517 | false | true | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/wildplot/android/parsing/Term.kt | 1 | 4837 | /****************************************************************************************
* Copyright (c) 2014 Michael Goldbach <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.wildplot.android.parsing
class Term(termString: String, private val parser: TopLevelParser) : TreeElement {
enum class TermType {
TERM_MUL_FACTOR, TERM_DIV_FACTOR, FACTOR, INVALID
}
var termType = TermType.INVALID
private set
private var factor: Factor? = null
private var term: Term? = null
private fun initAsTermMulOrDivFactor(termString: String): Boolean {
var bracketChecker = 0
for (i in 0 until termString.length) {
if (termString[i] == '(') {
bracketChecker++
}
if (termString[i] == ')') {
bracketChecker--
}
if ((termString[i] == '*' || termString[i] == '/') && bracketChecker == 0) {
val leftSubString = termString.substring(0, i)
if (!TopLevelParser.stringHasValidBrackets(leftSubString)) {
continue
}
val leftTerm = Term(leftSubString, parser)
val isValidFirstPartTerm = leftTerm.termType != TermType.INVALID
if (!isValidFirstPartTerm) {
continue
}
val rightSubString = termString.substring(i + 1)
if (!TopLevelParser.stringHasValidBrackets(rightSubString)) {
continue
}
val rightFactor = Factor(rightSubString, parser)
val isValidSecondPartFactor = rightFactor.factorType != Factor.FactorType.INVALID
if (isValidSecondPartFactor) {
if (termString[i] == '*') {
termType = TermType.TERM_MUL_FACTOR
} else {
termType = TermType.TERM_DIV_FACTOR
}
term = leftTerm
factor = rightFactor
return true
}
}
}
return false
}
private fun initAsFactor(termString: String): Boolean {
val factor = Factor(termString, parser)
val isValidTerm = factor.factorType != Factor.FactorType.INVALID
if (isValidTerm) {
termType = TermType.FACTOR
this.factor = factor
return true
}
return false
}
@get:Throws(ExpressionFormatException::class)
override val value: Double
get() = when (termType) {
TermType.TERM_MUL_FACTOR -> term!!.value * factor!!.value
TermType.TERM_DIV_FACTOR -> term!!.value / factor!!.value
TermType.FACTOR -> factor!!.value
TermType.INVALID -> throw ExpressionFormatException("could not parse Term")
}
@get:Throws(ExpressionFormatException::class)
override val isVariable: Boolean
get() = when (termType) {
TermType.TERM_MUL_FACTOR, TermType.TERM_DIV_FACTOR -> term!!.isVariable || factor!!.isVariable
TermType.FACTOR -> factor!!.isVariable
TermType.INVALID -> throw ExpressionFormatException("could not parse Term")
}
init {
if (!TopLevelParser.stringHasValidBrackets(termString)) {
termType = TermType.INVALID
} else {
var isReady = initAsTermMulOrDivFactor(termString)
if (!isReady) {
isReady = initAsFactor(termString)
}
if (!isReady) {
termType = TermType.INVALID
}
}
}
}
| gpl-3.0 | 5152202fcf2d6026cdb99863f6cef5d7 | 43.787037 | 106 | 0.501137 | 5.274809 | false | false | false | false |
infinum/android_dbinspector | dbinspector/src/test/kotlin/com/infinum/dbinspector/domain/connection/ConnectionRepositoryTest.kt | 1 | 2311 | package com.infinum.dbinspector.domain.connection
import com.infinum.dbinspector.domain.Control
import com.infinum.dbinspector.domain.Interactors
import com.infinum.dbinspector.shared.BaseTest
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.koin.core.module.Module
import org.koin.dsl.module
import org.koin.test.get
import org.mockito.kotlin.any
@DisplayName("ConnectionRepository tests")
internal class ConnectionRepositoryTest : BaseTest() {
override fun modules(): List<Module> = listOf(
module {
factory { mockk<Interactors.OpenConnection>() }
factory { mockk<Interactors.CloseConnection>() }
factory { mockk<Control.Connection>() }
}
)
@Test
fun `Connection repository open calls open interactor`() {
val interactor: Interactors.OpenConnection = get()
val control: Control.Connection = get()
val repository = ConnectionRepository(
interactor,
get(),
control
)
coEvery { interactor.invoke(any()) } returns mockk()
coEvery { control.mapper.invoke(any()) } returns mockk()
coEvery { control.converter.invoke(any()) } returns ""
test {
repository.open(any())
}
coVerify(exactly = 1) { interactor.invoke(any()) }
coVerify(exactly = 1) { control.mapper.invoke(any()) }
coVerify(exactly = 1) { control.converter.invoke(any()) }
}
@Test
fun `Connection repository close calls close interactor`() {
val interactor: Interactors.CloseConnection = get()
val control: Control.Connection = get()
val repository = ConnectionRepository(
get(),
interactor,
control
)
coEvery { interactor.invoke(any()) } returns Unit
coEvery { control.mapper.invoke(any()) } returns mockk()
coEvery { control.converter.invoke(any()) } returns ""
test {
repository.close(any())
}
coVerify(exactly = 1) { interactor.invoke(any()) }
coVerify(exactly = 0) { control.mapper.invoke(any()) }
coVerify(exactly = 1) { control.converter.invoke(any()) }
}
}
| apache-2.0 | 12a692d981f1e5429f41f374b9a78e74 | 31.097222 | 65 | 0.635656 | 4.567194 | false | true | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/GeekListActivity.kt | 1 | 4335 | package com.boardgamegeek.ui
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.boardgamegeek.R
import com.boardgamegeek.entities.Status
import com.boardgamegeek.extensions.*
import com.boardgamegeek.provider.BggContract
import com.boardgamegeek.ui.viewmodel.GeekListViewModel
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.logEvent
class GeekListActivity : TabActivity() {
private var geekListId = BggContract.INVALID_ID
private var geekListTitle: String = ""
private val viewModel by viewModels<GeekListViewModel>()
private val adapter: GeekListPagerAdapter by lazy { GeekListPagerAdapter(this) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
geekListId = intent.getIntExtra(KEY_ID, BggContract.INVALID_ID)
geekListTitle = intent.getStringExtra(KEY_TITLE).orEmpty()
safelySetTitle(geekListTitle)
if (savedInstanceState == null) {
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_ITEM) {
param(FirebaseAnalytics.Param.CONTENT_TYPE, "GeekList")
param(FirebaseAnalytics.Param.ITEM_ID, geekListId.toString())
param(FirebaseAnalytics.Param.ITEM_NAME, geekListTitle)
}
}
viewModel.setId(geekListId)
viewModel.geekList.observe(this) {
it?.let { (status, data, _) ->
if (status == Status.SUCCESS && data != null) {
geekListTitle = data.title
safelySetTitle(geekListTitle)
}
}
}
}
override val optionsMenuId = R.menu.view_share
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_view -> linkToBgg("geeklist", geekListId)
R.id.menu_share -> {
val description = String.format(getString(R.string.share_geeklist_text), geekListTitle)
val uri = createBggUri("geeklist", geekListId)
share(getString(R.string.share_geeklist_subject), "$description\n\n$uri")
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SHARE) {
param(FirebaseAnalytics.Param.CONTENT_TYPE, "GeekList")
param(FirebaseAnalytics.Param.ITEM_ID, geekListId.toString())
param(FirebaseAnalytics.Param.ITEM_ID, geekListTitle)
}
}
else -> super.onOptionsItemSelected(item)
}
return true
}
override fun createAdapter(): FragmentStateAdapter {
return adapter
}
override fun getPageTitle(position: Int): CharSequence {
return when (position) {
0 -> getString(R.string.title_description)
1 -> getString(R.string.title_items)
2 -> getString(R.string.title_comments)
else -> ""
}
}
private class GeekListPagerAdapter(activity: FragmentActivity) :
FragmentStateAdapter(activity) {
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> GeekListDescriptionFragment()
1 -> GeekListItemsFragment()
2 -> GeekListCommentsFragment()
else -> ErrorFragment()
}
}
override fun getItemCount() = 3
}
companion object {
private const val KEY_ID = "GEEK_LIST_ID"
private const val KEY_TITLE = "GEEK_LIST_TITLE"
fun start(context: Context, id: Int, title: String) {
context.startActivity(createIntent(context, id, title))
}
fun startUp(context: Context, id: Int, title: String) {
context.startActivity(createIntent(context, id, title).clearTop())
}
private fun createIntent(context: Context, id: Int, title: String): Intent {
return context.intentFor<GeekListActivity>(
KEY_ID to id,
KEY_TITLE to title,
)
}
}
}
| gpl-3.0 | 665611ac6aa9f65ed2c69426e02737c9 | 35.428571 | 103 | 0.635294 | 4.676375 | false | false | false | false |
debop/debop4k | debop4k-core/src/main/kotlin/debop4k/core/nio/Pathx.kt | 1 | 2397 | /*
* Copyright (c) 2016. Sunghyouk Bae <[email protected]>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
@file:JvmName("Pathx")
package debop4k.core.nio
import debop4k.core.loggerOf
import org.slf4j.Logger
import java.io.File
import java.io.IOException
import java.lang.Exception
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.Path
import java.nio.file.Paths
private val log: Logger = loggerOf("Pathx")
/** Path 경로가 존재하는지 여부 */
fun Path.exists(vararg options: LinkOption): Boolean
= !Files.exists(this, *options)
/** Path 경로가 존재하지 않는지 검사 */
fun Path.nonExists(vararg options: LinkOption): Boolean
= !this.exists(*options)
/** 경로들을 결합합니다 */
fun Path.combine(vararg subpaths: String): Path
= this.toString().combinePath(*subpaths)
/** 경로들을 결합합니다 */
fun String.combinePath(vararg subpaths: String): Path
= Paths.get(this, *subpaths)
/** 지정현 경로와 하위 폴더를 삭제합니다. */
fun Path.deleteRecursively(): Boolean {
try {
if (nonExists())
return false
return this.toFile().deleteRecursively()
} catch(e: Exception) {
log.warn("지정한 경로를 삭제하는데 실패했습니다. path=$this", e)
return false
}
}
/** 지정한 경로와 하위 경로의 모든 파일을 대상 경로로 복사합니다 */
@JvmOverloads
fun Path.copyRecursively(target: Path,
overwrite: Boolean = false,
onError: (File, IOException) -> OnErrorAction = { file, exception -> OnErrorAction.SKIP }
): Boolean {
log.debug("copy recursively. src=$this, target=$target")
return this.toFile().copyRecursively(target.toFile(), overwrite, onError)
}
//
// TODO: AsyncFileChannel 을 이용한 비동기 파일 처리 관련 추가
// | apache-2.0 | 078654975f09478841327426a5ecd906 | 28.726027 | 114 | 0.692485 | 3.481541 | false | false | false | false |
debop/debop4k | debop4k-core/src/test/kotlin/debop4k/core/result/ValidationKotlinTest.kt | 1 | 1599 | /*
* Copyright (c) 2016. Sunghyouk Bae <[email protected]>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package debop4k.core.result
import debop4k.core.loggerOf
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class ValidationKotlinTest {
private val log = loggerOf(javaClass)
@Test
fun testValidationWithNoError() {
val r1 = Result.of(1)
val r2 = Result.of(2)
val r3 = Result.of(3)
val validation = Validation(r1, r2, r3)
assertThat(validation.hasFailure).isFalse()
assertThat(validation.failures).isEmpty()
}
@Test
fun testValidationWithError() {
val r1 = Result.of(1)
val r2 = Result.of { throw Exception("Not a number") }
val r3 = Result.of(3)
val r4 = Result.of { throw Exception("Divide by zero") }
val validation = Validation(r1, r2, r3, r4)
assertThat(validation.hasFailure).isTrue()
assertThat(validation.failures)
.isNotEmpty().hasSize(2)
assertThat(validation.failures.map { it.message })
.containsExactly("Not a number", "Divide by zero")
}
} | apache-2.0 | 2eb4d75f7c2edc172978fd7680c83c64 | 28.62963 | 75 | 0.70419 | 3.744731 | false | true | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/services/MimeTypeHelper.kt | 1 | 2809 | package com.pr0gramm.app.services
import com.pr0gramm.app.util.readAsMuchAsPossible
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStream
/**
* Guesses the mime type of a file or input stream
*/
object MimeTypeHelper {
fun guess(bytes: ByteArray): String? {
if (indexOf(bytes, MAGIC_JPEG) == 0)
return "image/jpeg"
if (indexOf(bytes, MAGIC_GIF) == 0)
return "image/gif"
if (indexOf(bytes, MAGIC_PNG) == 0)
return "image/png"
if (MAGIC_MP4.any { q -> indexOf(bytes, q) != -1 })
return "video/mp4"
if (MAGIC_WEBM.any { q -> indexOf(bytes, q) != -1 })
return "video/webm"
return null
}
fun guess(file: File): String? {
return try {
FileInputStream(file).use { input -> guess(input) }
} catch (err: IOException) {
guessFromFileExtension(file.name)
}
}
fun guessFromFileExtension(name: String): String? {
return EXTENSION_TO_TYPE.entries.firstOrNull { (ext, _) ->
name.endsWith(ext, ignoreCase = true)
}?.value
}
fun guess(input: InputStream): String? {
return guess(ByteArray(512).also { input.readAsMuchAsPossible(it) })
}
fun extension(type: String): String? {
return TYPE_TO_EXTENSION[type]
}
private val TYPE_TO_EXTENSION = mapOf(
"image/jpeg" to "jpeg",
"image/png" to "png",
"image/gif" to "gif",
"video/webm" to "webm",
"video/mp4" to "mp4")
private val EXTENSION_TO_TYPE = mapOf(
"txt" to "text/plain",
"jpeg" to "image/jpeg",
"jpg" to "image/jpeg",
"png" to "image/png",
"gif" to "image/gif",
"webm" to "video/webm",
"mp4" to "video/mp4")
private val MAGIC_PNG = byteArrayOf(0x89.toByte(), 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a)
private val MAGIC_JPEG = byteArrayOf(0xff.toByte(), 0xd8.toByte())
private val MAGIC_GIF = "GIF89a".toByteArray()
private val MAGIC_MP4 = listOf(
"ftypmp42".toByteArray(),
"moov".toByteArray(),
"isom".toByteArray())
private val MAGIC_WEBM = listOf(
byteArrayOf(0x1a, 0x54, 0xdf.toByte(), 0xa3.toByte()),
"webm".toByteArray())
fun indexOf(array: ByteArray, target: ByteArray): Int {
if (target.isEmpty()) {
return 0
}
outer@ for (i in 0 until array.size - target.size + 1) {
for (j in target.indices) {
if (array[i + j] != target[j]) {
continue@outer
}
}
return i
}
return -1
}
}
| mit | 63dc70888949e2fcca72a2899e5291c8 | 27.09 | 96 | 0.541474 | 3.676702 | false | false | false | false |
if710/if710.github.io | 2019-09-04/DataManagement/app/src/main/java/br/ufpe/cin/android/datamanagement/PrefsMenuActivity.kt | 1 | 2350 | package br.ufpe.cin.android.datamanagement
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
class PrefsMenuActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//Carrega um layout que contem um fragmento
setContentView(R.layout.activity_prefs_menu)
supportFragmentManager
.beginTransaction()
.replace(R.id.settings_container, UserPreferenceFragment())
.commit()
}
// Fragmento que mostra a preference com username
class UserPreferenceFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
// Carrega preferences a partir de um XML
addPreferencesFromResource(R.xml.user_prefs)
}
private var mListener: SharedPreferences.OnSharedPreferenceChangeListener? = null
private var mUserNamePreference: Preference? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
/*
// pega a Preference especifica do username
mUserNamePreference = preferenceManager.findPreference(PrefsActivity.USERNAME)
// Define um listener para atualizar descricao ao modificar preferences
mListener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
mUserNamePreference!!.summary = sharedPreferences.getString(
PrefsActivity.USERNAME, "Nada ainda")
}
// Pega objeto SharedPreferences gerenciado pelo PreferenceManager para este Fragmento
val prefs = preferenceManager
.sharedPreferences
// Registra listener no objeto SharedPreferences
prefs.registerOnSharedPreferenceChangeListener(mListener)
// Invoca callback manualmente para exibir username atual
mListener!!.onSharedPreferenceChanged(prefs, PrefsActivity.USERNAME)
*/
}
companion object {
protected val TAG = "UserPrefsFragment"
}
}
}
| mit | 92a8c36726ebf20a8fff284f82098058 | 36.903226 | 102 | 0.685106 | 5.845771 | false | false | false | false |
jraska/github-client | feature/performance/src/main/java/com/jraska/github/client/performance/startup/StartupAnalyticsReporter.kt | 1 | 1910 | package com.jraska.github.client.performance.startup
import android.os.Process
import android.os.SystemClock
import com.jraska.github.client.Owner
import com.jraska.github.client.analytics.AnalyticsEvent
import com.jraska.github.client.analytics.EventAnalytics
import timber.log.Timber
import javax.inject.Inject
class StartupAnalyticsReporter @Inject constructor(
private val eventAnalytics: EventAnalytics
) {
fun reportForegroundLaunch(launchedActivity: String, startupSavedStatePresent: Boolean) {
val launchTimeNow = launchTimeNow()
Timber.d("AppStartup is %s ms, activity: %s, savedState: %s", launchTimeNow, launchedActivity, startupSavedStatePresent)
val eventBuilder = if (startupSavedStatePresent) {
AnalyticsEvent.builder(ANALYTICS_AFTER_KILL_START)
} else {
AnalyticsEvent.builder(ANALYTICS_COLD_START)
}
eventBuilder.addProperty("time", launchTimeNow)
eventBuilder.addProperty("activity", launchedActivity)
eventAnalytics.report(eventBuilder.build())
}
fun reportBackgroundLaunch() {
Timber.d("AppStartup in the background")
eventAnalytics.report(AnalyticsEvent.create(ANALYTICS_BACKGROUND_START))
}
fun reportForegroundLaunchWithoutActivity() {
Timber.d("App started as foreground, but post ran before any Activity onCreate()")
eventAnalytics.report(AnalyticsEvent.create(ANALYTICS_UNDEFINED))
}
private fun launchTimeNow() = SystemClock.uptimeMillis() - Process.getStartUptimeMillis()
companion object {
val ANALYTICS_COLD_START = AnalyticsEvent.Key("start_cold", Owner.PERFORMANCE_TEAM)
val ANALYTICS_AFTER_KILL_START = AnalyticsEvent.Key("start_warm_after_kill", Owner.PERFORMANCE_TEAM)
val ANALYTICS_BACKGROUND_START = AnalyticsEvent.Key("start_background", Owner.PERFORMANCE_TEAM)
val ANALYTICS_UNDEFINED = AnalyticsEvent.Key("start_foreground_undefined", Owner.PERFORMANCE_TEAM)
}
}
| apache-2.0 | 70aefe9dc33458ec5a1ecc593b3b3213 | 37.2 | 124 | 0.779058 | 4.321267 | false | false | false | false |
nextcloud/android | app/src/main/java/com/nextcloud/client/database/migrations/RoomMigration.kt | 1 | 9260 | /*
* Nextcloud Android client application
*
* @author Álvaro Brey
* Copyright (C) 2022 Álvaro Brey
* Copyright (C) 2022 Nextcloud GmbH
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or 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 AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.nextcloud.client.database.migrations
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.nextcloud.client.database.NextcloudDatabase
class RoomMigration : Migration(NextcloudDatabase.FIRST_ROOM_DB_VERSION - 1, NextcloudDatabase.FIRST_ROOM_DB_VERSION) {
override fun migrate(database: SupportSQLiteDatabase) {
migrateFilesystemTable(database)
migrateUploadsTable(database)
migrateCapabilitiesTable(database)
migrateFilesTable(database)
}
/**
* filesystem table: STRING converted to TEXT
*/
private fun migrateFilesystemTable(database: SupportSQLiteDatabase) {
val newColumns = mapOf(
"_id" to TYPE_INTEGER_PRIMARY_KEY,
"local_path" to TYPE_TEXT,
"is_folder" to TYPE_INTEGER,
"found_at" to TYPE_INTEGER,
"upload_triggered" to TYPE_INTEGER,
"syncedfolder_id" to TYPE_TEXT,
"crc32" to TYPE_TEXT,
"modified_at" to TYPE_INTEGER
)
migrateTable(database, "filesystem", newColumns)
}
/**
* uploads table: LONG converted to INTEGER
*/
private fun migrateUploadsTable(database: SupportSQLiteDatabase) {
val newColumns = mapOf(
"_id" to TYPE_INTEGER_PRIMARY_KEY,
"local_path" to TYPE_TEXT,
"remote_path" to TYPE_TEXT,
"account_name" to TYPE_TEXT,
"file_size" to TYPE_INTEGER,
"status" to TYPE_INTEGER,
"local_behaviour" to TYPE_INTEGER,
"upload_time" to TYPE_INTEGER,
"name_collision_policy" to TYPE_INTEGER,
"is_create_remote_folder" to TYPE_INTEGER,
"upload_end_timestamp" to TYPE_INTEGER,
"last_result" to TYPE_INTEGER,
"is_while_charging_only" to TYPE_INTEGER,
"is_wifi_only" to TYPE_INTEGER,
"created_by" to TYPE_INTEGER,
"folder_unlock_token" to TYPE_TEXT
)
migrateTable(database, "list_of_uploads", newColumns)
}
/**
* capabilities table: "files_drop" column removed
*/
private fun migrateCapabilitiesTable(database: SupportSQLiteDatabase) {
val newColumns = mapOf(
"_id" to TYPE_INTEGER_PRIMARY_KEY,
"account" to TYPE_TEXT,
"version_mayor" to TYPE_INTEGER,
"version_minor" to TYPE_INTEGER,
"version_micro" to TYPE_INTEGER,
"version_string" to TYPE_TEXT,
"version_edition" to TYPE_TEXT,
"extended_support" to TYPE_INTEGER,
"core_pollinterval" to TYPE_INTEGER,
"sharing_api_enabled" to TYPE_INTEGER,
"sharing_public_enabled" to TYPE_INTEGER,
"sharing_public_password_enforced" to TYPE_INTEGER,
"sharing_public_expire_date_enabled" to TYPE_INTEGER,
"sharing_public_expire_date_days" to TYPE_INTEGER,
"sharing_public_expire_date_enforced" to TYPE_INTEGER,
"sharing_public_send_mail" to TYPE_INTEGER,
"sharing_public_upload" to TYPE_INTEGER,
"sharing_user_send_mail" to TYPE_INTEGER,
"sharing_resharing" to TYPE_INTEGER,
"sharing_federation_outgoing" to TYPE_INTEGER,
"sharing_federation_incoming" to TYPE_INTEGER,
"files_bigfilechunking" to TYPE_INTEGER,
"files_undelete" to TYPE_INTEGER,
"files_versioning" to TYPE_INTEGER,
"external_links" to TYPE_INTEGER,
"server_name" to TYPE_TEXT,
"server_color" to TYPE_TEXT,
"server_text_color" to TYPE_TEXT,
"server_element_color" to TYPE_TEXT,
"server_slogan" to TYPE_TEXT,
"server_logo" to TYPE_TEXT,
"background_url" to TYPE_TEXT,
"end_to_end_encryption" to TYPE_INTEGER,
"activity" to TYPE_INTEGER,
"background_default" to TYPE_INTEGER,
"background_plain" to TYPE_INTEGER,
"richdocument" to TYPE_INTEGER,
"richdocument_mimetype_list" to TYPE_TEXT,
"richdocument_direct_editing" to TYPE_INTEGER,
"richdocument_direct_templates" to TYPE_INTEGER,
"richdocument_optional_mimetype_list" to TYPE_TEXT,
"sharing_public_ask_for_optional_password" to TYPE_INTEGER,
"richdocument_product_name" to TYPE_TEXT,
"direct_editing_etag" to TYPE_TEXT,
"user_status" to TYPE_INTEGER,
"user_status_supports_emoji" to TYPE_INTEGER,
"etag" to TYPE_TEXT,
"files_locking_version" to TYPE_TEXT
)
migrateTable(database, "capabilities", newColumns)
}
/**
* files table: "public_link" column removed
*/
private fun migrateFilesTable(database: SupportSQLiteDatabase) {
val newColumns = mapOf(
"_id" to TYPE_INTEGER_PRIMARY_KEY,
"filename" to TYPE_TEXT,
"encrypted_filename" to TYPE_TEXT,
"path" to TYPE_TEXT,
"path_decrypted" to TYPE_TEXT,
"parent" to TYPE_INTEGER,
"created" to TYPE_INTEGER,
"modified" to TYPE_INTEGER,
"content_type" to TYPE_TEXT,
"content_length" to TYPE_INTEGER,
"media_path" to TYPE_TEXT,
"file_owner" to TYPE_TEXT,
"last_sync_date" to TYPE_INTEGER,
"last_sync_date_for_data" to TYPE_INTEGER,
"modified_at_last_sync_for_data" to TYPE_INTEGER,
"etag" to TYPE_TEXT,
"etag_on_server" to TYPE_TEXT,
"share_by_link" to TYPE_INTEGER,
"permissions" to TYPE_TEXT,
"remote_id" to TYPE_TEXT,
"update_thumbnail" to TYPE_INTEGER,
"is_downloading" to TYPE_INTEGER,
"favorite" to TYPE_INTEGER,
"is_encrypted" to TYPE_INTEGER,
"etag_in_conflict" to TYPE_TEXT,
"shared_via_users" to TYPE_INTEGER,
"mount_type" to TYPE_INTEGER,
"has_preview" to TYPE_INTEGER,
"unread_comments_count" to TYPE_INTEGER,
"owner_id" to TYPE_TEXT,
"owner_display_name" to TYPE_TEXT,
"note" to TYPE_TEXT,
"sharees" to TYPE_TEXT,
"rich_workspace" to TYPE_TEXT,
"metadata_size" to TYPE_TEXT,
"locked" to TYPE_INTEGER,
"lock_type" to TYPE_INTEGER,
"lock_owner" to TYPE_TEXT,
"lock_owner_display_name" to TYPE_TEXT,
"lock_owner_editor" to TYPE_TEXT,
"lock_timestamp" to TYPE_INTEGER,
"lock_timeout" to TYPE_INTEGER,
"lock_token" to TYPE_TEXT
)
migrateTable(database, "filelist", newColumns)
}
private fun migrateTable(database: SupportSQLiteDatabase, tableName: String, newColumns: Map<String, String>) {
require(newColumns.isNotEmpty())
val newTableTempName = "${tableName}_new"
createNewTable(database, newTableTempName, newColumns)
copyData(database, tableName, newTableTempName, newColumns.keys)
replaceTable(database, tableName, newTableTempName)
}
private fun createNewTable(
database: SupportSQLiteDatabase,
newTableName: String,
columns: Map<String, String>
) {
val columnsString = columns.entries.joinToString(",") { "${it.key} ${it.value}" }
database.execSQL("CREATE TABLE $newTableName ($columnsString)")
}
private fun copyData(
database: SupportSQLiteDatabase,
tableName: String,
newTableName: String,
columnNames: Iterable<String>
) {
val columnsString = columnNames.joinToString(",")
database.execSQL(
"INSERT INTO $newTableName ($columnsString) " +
"SELECT $columnsString FROM $tableName"
)
}
private fun replaceTable(
database: SupportSQLiteDatabase,
tableName: String,
newTableTempName: String
) {
database.execSQL("DROP TABLE $tableName")
database.execSQL("ALTER TABLE $newTableTempName RENAME TO $tableName")
}
companion object {
private const val TYPE_TEXT = "TEXT"
private const val TYPE_INTEGER = "INTEGER"
private const val TYPE_INTEGER_PRIMARY_KEY = "INTEGER PRIMARY KEY"
}
}
| gpl-2.0 | c8dec6e1118e1b2930a91f89db58856f | 38.063291 | 119 | 0.609959 | 4.155296 | false | false | false | false |
kiruto/kotlin-android-mahjong | app/src/main/java/dev/yuriel/mahjan/texture/TileMgr.kt | 1 | 2839 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 yuriel<[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package dev.yuriel.mahjan.texture
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.graphics.g2d.TextureRegion
import dev.yuriel.kotmahjan.models.Hai
import dev.yuriel.kotmahjan.models.HaiType
import dev.yuriel.kotmahjan.models.UnbelievableException
/**
* Created by yuriel on 8/5/16.
*/
object TileMgr: NormalTextureMgr("tiles.txt") {
operator fun get(hai: Hai): TextureRegion? {
val name = findTextureNameByHai(hai)
return this[name]
}
fun getBack(): TextureRegion? {
return this["back"]
}
fun getObverse(): TextureRegion? {
return this["back_side"]
}
private fun findTextureNameByHai(hai: Hai): String {
fun normal(hai: Hai): String {
val fileName: String
val haiName = hai.toString()
when (haiName.length) {
2 -> fileName = haiName
3 -> {
when(haiName.first()) {
'p' -> fileName = "aka1"
's' -> fileName = "aka2"
'm' -> fileName = "aka3"
else -> throw UnbelievableException()
}
}
else -> throw UnbelievableException()
}
return fileName
}
return when(hai.type) {
HaiType.E -> "ji1"
HaiType.S -> "ji2"
HaiType.W -> "ji3"
HaiType.N -> "ji4"
HaiType.D -> "ji5"
HaiType.H -> "ji6"
HaiType.T -> "ji7"
else -> normal(hai)
}
}
} | mit | 102dbaa84710bf7caa3e6ed6b7ea6325 | 33.634146 | 81 | 0.620641 | 4.175 | false | false | false | false |
HedvigInsurance/bot-service | src/main/java/com/hedvig/botService/chat/StatusBuilderImpl.kt | 1 | 5799 | package com.hedvig.botService.chat
import com.hedvig.libs.translations.Translations
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.Month
import java.util.Locale
import org.springframework.stereotype.Component
@Component
class StatusBuilderImpl(
private val translations: Translations
) : StatusBuilder {
override fun getStatusReplyMessage(now: LocalDateTime, locale: Locale): String {
val today = LocalDate.from(now)
val dayOfWeek = today.dayOfWeek!!
val hour = now.hour
val minute = now.minute
if (isChristmasPeriod(today)) {
return getRepliesOnChristmasDayReply(locale)
}
if (isUnderstaffedDay(today)) {
return getLongResponseWindowDayReply(
locale = locale,
dayStartHour = 10,
dayEndHour = 18,
hour = hour
)
}
if (isRedDay(today)) {
return getLongResponseWindowDayReply(
locale = locale,
dayStartHour = 10,
dayEndHour = 18,
hour = hour
)
}
if (isHedvigParty(today)){
return getHedvigPartyReply(
locale = locale,
hour = hour
)
}
return when (dayOfWeek) {
DayOfWeek.MONDAY,
DayOfWeek.TUESDAY,
DayOfWeek.WEDNESDAY,
DayOfWeek.THURSDAY,
DayOfWeek.FRIDAY -> getRegularWeekdayReply(locale, dayOfWeek, hour, minute)
DayOfWeek.SATURDAY,
DayOfWeek.SUNDAY -> getLongResponseWindowDayReply(
locale = locale,
dayStartHour = 10,
dayEndHour = 22,
hour = hour
)
}
}
private fun getRegularWeekdayReply(
locale: Locale,
dayOfWeek: DayOfWeek,
hour: Int,
minute: Int
) = when {
isRetroMeeting(dayOfWeek, hour, minute) ->
getRepliesWithinMinutes(locale, maxOf(RETRO_END_MINUTE - minute + minute % 5, 10))
hour < 3 -> getRepliesTomorrow(locale)
hour < 8 -> getRepliesAfterHour(locale, 8)
hour < 17 -> getRepliesWithinMinutes(locale, 10)
hour < 20 -> getRepliesWithinMinutes(locale, 20)
hour < 22 -> getRepliesWithinMinutes(locale, 30)
else -> getRepliesTomorrow(locale)
}
private fun getLongResponseWindowDayReply(
locale: Locale,
dayStartHour: Int,
dayEndHour: Int,
hour: Int
) = when {
hour < 3 -> getRepliesTomorrow(locale)
hour < dayStartHour -> getRepliesAfterHour(locale, dayStartHour)
hour < dayEndHour -> getRepliesWithinAnHour(locale)
else -> getRepliesTomorrow(locale)
}
private fun isRetroMeeting(dayOfWeek: DayOfWeek, hour: Int, minute: Int) =
dayOfWeek == RETRO_DAY && hour == RETRO_START_HOUR && minute <= RETRO_END_MINUTE
private fun getRepliesTomorrow(locale: Locale): String =
translations.get("BOT_SERVICE_STATUS_REPLY_TOMORROW", locale)
?: "BOT_SERVICE_STATUS_REPLY_TOMORROW"
private fun getRepliesAfterHour(locale: Locale, hour: Int): String {
val text = translations.get("BOT_SERVICE_STATUS_REPLY_AFTER_HOUR_OF_DAY", locale)
?: "BOT_SERVICE_STATUS_REPLY_AFTER_HOUR_OF_DAY"
return text.replace("{HOUR_OF_DAY}", hour.toString())
}
private fun getRepliesWithinAnHour(locale: Locale) =
translations.get("BOT_SERVICE_STATUS_REPLY_WITHIN_AN_HOUR", locale)
?: "BOT_SERVICE_STATUS_REPLY_WITHIN_AN_HOUR"
private fun getRepliesWithinMinutes(locale: Locale, minutes: Int): String {
val text = translations.get("BOT_SERVICE_STATUS_REPLY_WITHIN_MIN", locale)
?: "BOT_SERVICE_STATUS_REPLY_WITHIN_MIN"
return text.replace("{MINUTES}", minutes.toString())
}
private fun getRepliesOnChristmasDayReply(locale: Locale) =
translations.get("BOT_SERVICE_STATUS_REPLY_CHRISTMAS_DAY", locale)
?: "BOT_SERVICE_STATUS_REPLY_CHRISTMAS_DAY"
private fun isChristmasPeriod(date: LocalDate) =
date.month == Month.DECEMBER && (date.dayOfMonth == 23 || date.dayOfMonth == 24)
private fun isUnderstaffedDay(date: LocalDate) = UNDERSTAFFED_DAYS.contains(date)
private fun isRedDay(date: LocalDate) = RED_DAYS.contains(date)
private fun isHedvigParty(date: LocalDate) = date == LocalDate.of(2021, 8,31)
private fun getHedvigPartyReply(
locale: Locale,
hour: Int
) = when {
hour < 7 -> getRepliesTomorrow(locale)
hour < 8 -> getRepliesAfterHour(locale, 8)
hour < 16 -> getRepliesWithinMinutes(locale, 10)
else -> getRepliesTomorrow(locale)
}
companion object {
private val RETRO_DAY = DayOfWeek.FRIDAY
const val RETRO_START_HOUR = 11
const val RETRO_END_MINUTE = 45
private val UNDERSTAFFED_DAYS = setOf(
LocalDate.of(2020, 12, 25),
LocalDate.of(2020, 12, 26),
LocalDate.of(2020, 12, 27),
LocalDate.of(2020, 12, 31),
LocalDate.of(2021, 1, 1)
)
private val RED_DAYS = setOf(
LocalDate.of(2021, 1, 1),
LocalDate.of(2021, 1, 6),
LocalDate.of(2021, 4, 2),
LocalDate.of(2021, 4, 4),
LocalDate.of(2021, 4, 5),
LocalDate.of(2021, 5, 1),
LocalDate.of(2021, 5, 13),
LocalDate.of(2021, 5, 23),
LocalDate.of(2021, 6, 6),
LocalDate.of(2021, 6, 26),
LocalDate.of(2021, 11, 6),
LocalDate.of(2021, 12, 25),
LocalDate.of(2021, 12, 26)
)
}
}
| agpl-3.0 | f4106e8bfa3b43cdfaafcae204a525af | 34.359756 | 94 | 0.596827 | 4.156989 | false | false | false | false |
shlusiak/Freebloks-Android | game/src/main/java/de/saschahlusiak/freebloks/network/message/MessageRequestPlayer.kt | 1 | 1040 | package de.saschahlusiak.freebloks.network.message
import de.saschahlusiak.freebloks.network.*
import de.saschahlusiak.freebloks.utils.put
import java.nio.ByteBuffer
data class MessageRequestPlayer(val player: Int, val name: String?): Message(MessageType.RequestPlayer, 17) {
init {
assert(player in -1..3) { "player $player must be between -1 and 3"}
}
override fun write(buffer: ByteBuffer) {
super.write(buffer)
buffer.put(player.toByte())
val bytes = name?.toByteArray() ?: ByteArray(0)
buffer.put(bytes, 15).put(0)
}
companion object {
fun from(data: ByteBuffer): MessageRequestPlayer {
val player = data.get().toInt()
val bytes = ByteArray(16) { data.get() }
val length = bytes.indexOfFirst { it == 0.toByte() }
val name = if (length < 0) String(bytes, Charsets.UTF_8) else String(bytes, 0, length, Charsets.UTF_8)
return MessageRequestPlayer(player, name.trimEnd().ifEmpty { null })
}
}
} | gpl-2.0 | ebdf904b6c6a5e5b5649dd6ac080cb29 | 34.896552 | 114 | 0.641346 | 3.984674 | false | false | false | false |
BilledTrain380/sporttag-psa | app/psa-runtime-service/psa-service-group/src/main/kotlin/ch/schulealtendorf/psa/service/group/business/GroupImportManagerImpl.kt | 1 | 3748 | /*
* Copyright (c) 2018 by Nicolas Märchy
*
* This file is part of Sporttag PSA.
*
* Sporttag PSA 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.
*
* Sporttag PSA 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 Sporttag PSA. If not, see <http://www.gnu.org/licenses/>.
*
* Diese Datei ist Teil von Sporttag PSA.
*
* Sporttag PSA ist Freie Software: Sie können es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren
* veröffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Sporttag PSA wird in der Hoffnung, dass es nützlich sein wird, aber
* OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License für weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*
*
*/
package ch.schulealtendorf.psa.service.group.business
import ch.schulealtendorf.psa.service.group.business.parsing.FlatParticipant
import ch.schulealtendorf.psa.service.standard.entity.CoachEntity
import ch.schulealtendorf.psa.service.standard.entity.GroupEntity
import ch.schulealtendorf.psa.service.standard.entity.ParticipantEntity
import ch.schulealtendorf.psa.service.standard.entity.TownEntity
import ch.schulealtendorf.psa.service.standard.repository.CoachRepository
import ch.schulealtendorf.psa.service.standard.repository.GroupRepository
import ch.schulealtendorf.psa.service.standard.repository.ParticipantRepository
import ch.schulealtendorf.psa.service.standard.repository.TownRepository
import mu.KotlinLogging
import org.springframework.stereotype.Component
/**
* A {@link GroupManager} which uses repositories to process its data.
*
* @author nmaerchy <[email protected]>
* @since 2.0.0
*/
@Component
class GroupImportManagerImpl(
private val groupRepository: GroupRepository,
private val participantRepository: ParticipantRepository,
private val coachRepository: CoachRepository,
private val townRepository: TownRepository
) : GroupImportManager {
private val log = KotlinLogging.logger {}
override fun import(participant: FlatParticipant) {
log.debug { "Import Participant ${participant.prename} ${participant.surname}" }
val town = townRepository.findByZipAndName(participant.zipCode, participant.town)
.orElseGet { TownEntity(zip = participant.zipCode, name = participant.town) }
val coach = coachRepository.findByName(participant.coach)
.orElseGet { CoachEntity(name = participant.coach) }
val group = groupRepository.findByName(participant.group)
.orElseGet { GroupEntity(participant.group, coach) }
val participantEntity = ParticipantEntity(
surname = participant.surname,
prename = participant.prename,
gender = participant.gender,
birthday = participant.birthday.value,
address = participant.address,
town = town,
group = group
)
participantRepository.save(participantEntity)
}
}
| gpl-3.0 | 345c664be7b9a7552c2cf6b04158107b | 40.533333 | 89 | 0.752274 | 4.487395 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/feed/FeedFragment.kt | 1 | 15812 | package org.wikipedia.feed
import android.net.Uri
import android.os.Bundle
import android.util.Pair
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import org.wikipedia.BackPressedHandler
import org.wikipedia.Constants.InvokeSource
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.activity.FragmentUtil.getCallback
import org.wikipedia.analytics.FeedFunnel
import org.wikipedia.databinding.FragmentFeedBinding
import org.wikipedia.feed.FeedCoordinatorBase.FeedUpdateListener
import org.wikipedia.feed.configure.ConfigureActivity
import org.wikipedia.feed.configure.ConfigureItemLanguageDialogView
import org.wikipedia.feed.configure.LanguageItemAdapter
import org.wikipedia.feed.image.FeaturedImage
import org.wikipedia.feed.image.FeaturedImageCard
import org.wikipedia.feed.model.Card
import org.wikipedia.feed.model.WikiSiteCard
import org.wikipedia.feed.news.NewsCard
import org.wikipedia.feed.news.NewsItemView
import org.wikipedia.feed.random.RandomCardView
import org.wikipedia.feed.topread.TopReadArticlesActivity
import org.wikipedia.feed.topread.TopReadListCard
import org.wikipedia.feed.view.FeedAdapter
import org.wikipedia.history.HistoryEntry
import org.wikipedia.language.AppLanguageLookUpTable
import org.wikipedia.random.RandomActivity
import org.wikipedia.readinglist.sync.ReadingListSyncAdapter
import org.wikipedia.settings.Prefs
import org.wikipedia.settings.SettingsActivity
import org.wikipedia.settings.languages.WikipediaLanguagesActivity
import org.wikipedia.util.FeedbackUtil
import org.wikipedia.util.ResourceUtil
import org.wikipedia.util.UriUtil
class FeedFragment : Fragment(), BackPressedHandler {
private var _binding: FragmentFeedBinding? = null
private val binding get() = _binding!!
private lateinit var feedAdapter: FeedAdapter<View>
private val feedCallback = FeedCallback()
private val feedScrollListener = FeedScrollListener()
private val callback get() = getCallback(this, Callback::class.java)
private var app: WikipediaApp = WikipediaApp.instance
private var coordinator: FeedCoordinator = FeedCoordinator(app)
private var funnel: FeedFunnel = FeedFunnel(app)
private var shouldElevateToolbar = false
interface Callback {
fun onFeedSearchRequested(view: View)
fun onFeedVoiceSearchRequested()
fun onFeedSelectPage(entry: HistoryEntry, openInNewBackgroundTab: Boolean)
fun onFeedSelectPageWithAnimation(entry: HistoryEntry, sharedElements: Array<Pair<View, String>>)
fun onFeedAddPageToList(entry: HistoryEntry, addToDefault: Boolean)
fun onFeedMovePageToList(sourceReadingListId: Long, entry: HistoryEntry)
fun onFeedNewsItemSelected(card: NewsCard, view: NewsItemView)
fun onFeedSeCardFooterClicked()
fun onFeedShareImage(card: FeaturedImageCard)
fun onFeedDownloadImage(image: FeaturedImage)
fun onFeaturedImageSelected(card: FeaturedImageCard)
fun onLoginRequested()
fun updateToolbarElevation(elevate: Boolean)
}
private val requestFeedConfigurationLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == SettingsActivity.ACTIVITY_RESULT_FEED_CONFIGURATION_CHANGED) {
coordinator.updateHiddenCards()
refresh()
}
}
private val requestLanguageChangeLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == SettingsActivity.ACTIVITY_RESULT_LANGUAGE_CHANGED) {
refresh()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
coordinator.more(app.wikiSite)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
super.onCreateView(inflater, container, savedInstanceState)
_binding = FragmentFeedBinding.inflate(inflater, container, false)
feedAdapter = FeedAdapter(coordinator, feedCallback)
binding.feedView.adapter = feedAdapter
binding.feedView.addOnScrollListener(feedScrollListener)
binding.swipeRefreshLayout.setColorSchemeResources(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.colorAccent))
binding.swipeRefreshLayout.setOnRefreshListener { refresh() }
binding.customizeButton.setOnClickListener { showConfigureActivity(-1) }
coordinator.setFeedUpdateListener(object : FeedUpdateListener {
override fun insert(card: Card, pos: Int) {
if (isAdded) {
binding.swipeRefreshLayout.isRefreshing = false
feedAdapter.notifyItemInserted(pos)
}
}
override fun remove(card: Card, pos: Int) {
if (isAdded) {
binding.swipeRefreshLayout.isRefreshing = false
feedAdapter.notifyItemRemoved(pos)
}
}
override fun finished(shouldUpdatePreviousCard: Boolean) {
if (!isAdded) {
return
}
if (feedAdapter.itemCount < 2) {
binding.emptyContainer.visibility = View.VISIBLE
} else {
if (shouldUpdatePreviousCard) {
feedAdapter.notifyItemChanged(feedAdapter.itemCount - 1)
}
}
}
})
callback?.updateToolbarElevation(shouldElevateToolbar())
ReadingListSyncAdapter.manualSync()
Prefs.incrementExploreFeedVisitCount()
return binding.root
}
private fun showRemoveChineseVariantPrompt() {
if (app.languageState.appLanguageCodes.contains(AppLanguageLookUpTable.TRADITIONAL_CHINESE_LANGUAGE_CODE) &&
app.languageState.appLanguageCodes.contains(AppLanguageLookUpTable.SIMPLIFIED_CHINESE_LANGUAGE_CODE) &&
Prefs.shouldShowRemoveChineseVariantPrompt) {
AlertDialog.Builder(requireActivity())
.setTitle(R.string.dialog_of_remove_chinese_variants_from_app_lang_title)
.setMessage(R.string.dialog_of_remove_chinese_variants_from_app_lang_text)
.setPositiveButton(R.string.dialog_of_remove_chinese_variants_from_app_lang_edit) { _, _ -> showLanguagesActivity(InvokeSource.LANG_VARIANT_DIALOG) }
.setNegativeButton(R.string.dialog_of_remove_chinese_variants_from_app_lang_no, null)
.show()
}
Prefs.shouldShowRemoveChineseVariantPrompt = false
}
override fun onResume() {
super.onResume()
showRemoveChineseVariantPrompt()
funnel.enter()
// Explicitly invalidate the feed adapter, since it occasionally crashes the StaggeredGridLayout
// on certain devices. (TODO: investigate further)
feedAdapter.notifyDataSetChanged()
}
override fun onPause() {
super.onPause()
funnel.exit()
}
override fun onDestroyView() {
coordinator.setFeedUpdateListener(null)
binding.swipeRefreshLayout.setOnRefreshListener(null)
binding.feedView.removeOnScrollListener(feedScrollListener)
binding.feedView.adapter = null
_binding = null
super.onDestroyView()
}
override fun onDestroy() {
super.onDestroy()
coordinator.reset()
}
override fun onBackPressed(): Boolean {
return false
}
fun shouldElevateToolbar(): Boolean {
return shouldElevateToolbar
}
fun scrollToTop() {
binding.feedView.smoothScrollToPosition(0)
}
fun onGoOffline() {
feedAdapter.notifyDataSetChanged()
coordinator.requestOfflineCard()
}
fun onGoOnline() {
feedAdapter.notifyDataSetChanged()
coordinator.removeOfflineCard()
coordinator.incrementAge()
coordinator.more(app.wikiSite)
}
fun refresh() {
funnel.refresh(coordinator.age)
binding.emptyContainer.visibility = View.GONE
coordinator.reset()
feedAdapter.notifyDataSetChanged()
coordinator.more(app.wikiSite)
}
fun updateHiddenCards() {
coordinator.updateHiddenCards()
}
private inner class FeedCallback : FeedAdapter.Callback {
override fun onShowCard(card: Card?) {
card?.let {
funnel.cardShown(it.type(), getCardLanguageCode(it))
}
}
override fun onRequestMore() {
funnel.requestMore(coordinator.age)
binding.feedView.post {
if (isAdded) {
coordinator.incrementAge()
coordinator.more(app.wikiSite)
}
}
}
override fun onRetryFromOffline() {
refresh()
}
override fun onError(t: Throwable) {
FeedbackUtil.showError(requireActivity(), t)
}
override fun onSelectPage(card: Card, entry: HistoryEntry, openInNewBackgroundTab: Boolean) {
callback?.let {
it.onFeedSelectPage(entry, openInNewBackgroundTab)
funnel.cardClicked(card.type(), getCardLanguageCode(card))
}
}
override fun onSelectPage(card: Card, entry: HistoryEntry, sharedElements: Array<Pair<View, String>>) {
callback?.let {
it.onFeedSelectPageWithAnimation(entry, sharedElements)
funnel.cardClicked(card.type(), getCardLanguageCode(card))
}
}
override fun onAddPageToList(entry: HistoryEntry, addToDefault: Boolean) {
callback?.onFeedAddPageToList(entry, addToDefault)
}
override fun onMovePageToList(sourceReadingListId: Long, entry: HistoryEntry) {
callback?.onFeedMovePageToList(sourceReadingListId, entry)
}
override fun onSearchRequested(view: View) {
callback?.onFeedSearchRequested(view)
}
override fun onVoiceSearchRequested() {
callback?.onFeedVoiceSearchRequested()
}
override fun onRequestDismissCard(card: Card): Boolean {
val position = coordinator.dismissCard(card)
if (position < 0) {
return false
}
funnel.dismissCard(card.type(), position)
showDismissCardUndoSnackbar(card, position)
return true
}
override fun onRequestEditCardLanguages(card: Card) {
showCardLangSelectDialog(card)
}
override fun onRequestCustomize(card: Card) {
showConfigureActivity(card.type().code())
}
override fun onNewsItemSelected(card: NewsCard, view: NewsItemView) {
callback?.let {
it.onFeedNewsItemSelected(card, view)
funnel.cardClicked(card.type(), card.wikiSite().languageCode)
}
}
override fun onShareImage(card: FeaturedImageCard) {
callback?.onFeedShareImage(card)
}
override fun onDownloadImage(image: FeaturedImage) {
callback?.onFeedDownloadImage(image)
}
override fun onFeaturedImageSelected(card: FeaturedImageCard) {
callback?.let {
it.onFeaturedImageSelected(card)
funnel.cardClicked(card.type(), null)
}
}
override fun onAnnouncementPositiveAction(card: Card, uri: Uri) {
funnel.cardClicked(card.type(), getCardLanguageCode(card))
when {
uri.toString() == UriUtil.LOCAL_URL_LOGIN -> callback?.onLoginRequested()
uri.toString() == UriUtil.LOCAL_URL_SETTINGS -> requestLanguageChangeLauncher.launch(SettingsActivity.newIntent(requireContext()))
uri.toString() == UriUtil.LOCAL_URL_CUSTOMIZE_FEED -> {
showConfigureActivity(card.type().code())
onRequestDismissCard(card)
}
uri.toString() == UriUtil.LOCAL_URL_LANGUAGES -> showLanguagesActivity(InvokeSource.ANNOUNCEMENT)
else -> UriUtil.handleExternalLink(requireContext(), uri)
}
}
override fun onAnnouncementNegativeAction(card: Card) {
onRequestDismissCard(card)
}
override fun onRandomClick(view: RandomCardView) {
view.card?.let {
startActivity(RandomActivity.newIntent(requireActivity(), it.wikiSite(), InvokeSource.FEED))
}
}
override fun onFooterClick(card: Card) {
if (card is TopReadListCard) {
startActivity(TopReadArticlesActivity.newIntent(requireContext(), card))
}
}
override fun onSeCardFooterClicked() {
callback?.onFeedSeCardFooterClicked()
}
}
private inner class FeedScrollListener : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val shouldElevate = binding.feedView.firstVisibleItemPosition != 0
if (shouldElevate != shouldElevateToolbar) {
shouldElevateToolbar = shouldElevate
requireActivity().invalidateOptionsMenu()
callback?.updateToolbarElevation(shouldElevateToolbar())
}
}
}
private fun showDismissCardUndoSnackbar(card: Card, position: Int) {
val snackbar = FeedbackUtil.makeSnackbar(requireActivity(), getString(R.string.menu_feed_card_dismissed))
snackbar.setAction(R.string.reading_list_item_delete_undo) { coordinator.undoDismissCard(card, position) }
snackbar.show()
}
private fun showCardLangSelectDialog(card: Card) {
val contentType = card.type().contentType()
if (contentType != null && contentType.isPerLanguage) {
val adapter = LanguageItemAdapter(requireContext(), contentType)
val view = ConfigureItemLanguageDialogView(requireContext())
val tempDisabledList = ArrayList(contentType.langCodesDisabled)
view.setContentType(adapter.langList, tempDisabledList)
AlertDialog.Builder(requireContext())
.setView(view)
.setTitle(contentType.titleId)
.setPositiveButton(R.string.feed_lang_selection_dialog_ok_button_text) { _, _ ->
contentType.langCodesDisabled.clear()
contentType.langCodesDisabled.addAll(tempDisabledList)
refresh()
}
.setNegativeButton(R.string.feed_lang_selection_dialog_cancel_button_text, null)
.create()
.show()
}
}
private fun showConfigureActivity(invokeSource: Int) {
requestFeedConfigurationLauncher.launch(ConfigureActivity.newIntent(requireActivity(), invokeSource))
}
private fun showLanguagesActivity(invokeSource: InvokeSource) {
requestLanguageChangeLauncher.launch(WikipediaLanguagesActivity.newIntent(requireActivity(), invokeSource))
}
private fun getCardLanguageCode(card: Card?): String? {
return if (card is WikiSiteCard) card.wikiSite().languageCode else null
}
companion object {
fun newInstance(): FeedFragment {
return FeedFragment().apply {
retainInstance = true
}
}
}
}
| apache-2.0 | 7575bce16baabc4e25a8488d211a649b | 38.333333 | 165 | 0.664432 | 5.099 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/preference/HiddenSettingEntryPreference.kt | 1 | 2157 | /*
* 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.preference
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.support.v7.preference.Preference
import android.support.v7.preference.PreferenceManager
import android.util.AttributeSet
import de.vanita5.twittnuker.constant.IntentConstants.INTENT_ACTION_HIDDEN_SETTINGS_ENTRY
class HiddenSettingEntryPreference(
context: Context,
attrs: AttributeSet? = null
) : TintedPreferenceCategory(context, attrs) {
@SuppressLint("RestrictedApi")
override fun onAttachedToHierarchy(preferenceManager: PreferenceManager?, id: Long) {
super.onAttachedToHierarchy(preferenceManager, id)
removeAll()
val entryIntent = Intent(INTENT_ACTION_HIDDEN_SETTINGS_ENTRY)
entryIntent.`package` = context.packageName
context.packageManager.queryIntentActivities(entryIntent, 0).forEach { resolveInfo ->
val activityInfo = resolveInfo.activityInfo
addPreference(Preference(context).apply {
title = activityInfo.loadLabel(context.packageManager)
intent = Intent(INTENT_ACTION_HIDDEN_SETTINGS_ENTRY).setClassName(context, activityInfo.name)
})
}
}
} | gpl-3.0 | 28762008b596ed35d1283151807f616b | 40.5 | 109 | 0.736208 | 4.447423 | false | false | false | false |
stripe/stripe-android | payments-core/src/test/java/com/stripe/android/model/CardFixtures.kt | 1 | 2894 | package com.stripe.android.model
import com.stripe.android.model.parsers.CardJsonParser
import org.json.JSONObject
object CardFixtures {
internal val CARD = Card(
expMonth = 8,
expYear = 2050,
addressLine1 = AddressFixtures.ADDRESS.line1,
addressLine2 = AddressFixtures.ADDRESS.line2,
addressCity = AddressFixtures.ADDRESS.city,
addressCountry = AddressFixtures.ADDRESS.country,
addressState = AddressFixtures.ADDRESS.state,
addressZip = AddressFixtures.ADDRESS.postalCode,
currency = "USD",
name = "Jenny Rosen",
brand = CardBrand.Visa,
last4 = "4242",
id = "id"
)
internal val CARD_USD_JSON = JSONObject(
"""
{
"id": "card_189fi32eZvKYlo2CHK8NPRME",
"object": "card",
"address_city": "San Francisco",
"address_country": "US",
"address_line1": "123 Market St",
"address_line1_check": "unavailable",
"address_line2": "#345",
"address_state": "CA",
"address_zip": "94107",
"address_zip_check": "unavailable",
"brand": "Visa",
"country": "US",
"currency": "usd",
"customer": "customer77",
"cvc_check": "unavailable",
"exp_month": 8,
"exp_year": 2017,
"funding": "credit",
"fingerprint": "abc123",
"last4": "4242",
"name": "Jenny Rosen",
"metadata": {
"color": "blue",
"animal": "dog"
}
}
""".trimIndent()
)
internal val CARD_USD = requireNotNull(CardJsonParser().parse(CARD_USD_JSON))
internal val CARD_GOOGLE_PAY = requireNotNull(
CardJsonParser().parse(
JSONObject(
"""
{
"id": "card_189fi32eZvKYlo2CHK8NPRME",
"object": "card",
"address_city": "Des Moines",
"address_country": "US",
"address_line1": "123 Any Street",
"address_line1_check": "unavailable",
"address_line2": "456",
"address_state": "IA",
"address_zip": "50305",
"address_zip_check": "unavailable",
"brand": "Visa",
"country": "US",
"currency": "usd",
"customer": "customer77",
"cvc_check": "unavailable",
"exp_month": 8,
"exp_year": 2017,
"funding": "credit",
"fingerprint": "abc123",
"last4": "4242",
"name": "John Cardholder",
"tokenization_method": "android_pay",
"metadata": {
"color": "blue",
"animal": "dog"
}
}
""".trimIndent()
)
)
)
}
| mit | f35f972517ae68aa8fe7dc58542c98fc | 30.11828 | 81 | 0.480995 | 4.224818 | false | false | false | false |
joffrey-bion/mc-mining-optimizer | src/main/kotlin/org/hildan/minecraft/mining/optimizer/patterns/tunnels/TunnelSection.kt | 1 | 1259 | package org.hildan.minecraft.mining.optimizer.patterns.tunnels
import org.hildan.minecraft.mining.optimizer.blocks.Sample
/**
* Describes the dimensions of a 2D section of a tunnel.
*/
data class TunnelSection(val width: Int, val height: Int) {
fun digInto(sample: Sample, originX: Int, originY: Int, originZ: Int, length: Int, direction: Axis) {
val xMax = originX + getSizeOnAxis(Axis.X, direction, length)
val yMax = originY + getSizeOnAxis(Axis.Y, direction, length)
val zMax = originZ + getSizeOnAxis(Axis.Z, direction, length)
for (x in originX until Math.min(xMax, sample.dimensions.width)) {
for (y in originY until Math.min(yMax, sample.dimensions.height)) {
for (z in originZ until Math.min(zMax, sample.dimensions.length)) {
sample.digBlock(x, y, z)
}
}
}
}
private fun getSizeOnAxis(axis: Axis, tunnelDirection: Axis, length: Int): Int = when (axis) {
tunnelDirection -> length
Axis.Y -> height
else -> width
}
companion object {
val MAN_SIZED = TunnelSection(1, 2)
val DOUBLE_MAN_SIZED = TunnelSection(2, 2)
val BIG_CORRIDOR = TunnelSection(2, 3)
}
}
| mit | 1f4464083977c493c7877b7410461bb9 | 36.029412 | 105 | 0.628276 | 3.713864 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/sensors/modules/MagnetometerModule.kt | 2 | 1799 | // Copyright 2015-present 650 Industries. All rights reserved.
package abi44_0_0.expo.modules.sensors.modules
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorManager
import android.os.Bundle
import abi44_0_0.expo.modules.interfaces.sensors.SensorServiceInterface
import abi44_0_0.expo.modules.interfaces.sensors.services.MagnetometerServiceInterface
import abi44_0_0.expo.modules.core.Promise
import abi44_0_0.expo.modules.core.interfaces.ExpoMethod
class MagnetometerModule(reactContext: Context?) : BaseSensorModule(reactContext) {
override val eventName: String = "magnetometerDidUpdate"
override fun getName(): String = "ExponentMagnetometer"
override fun getSensorService(): SensorServiceInterface {
return moduleRegistry.getModule(MagnetometerServiceInterface::class.java)
}
override fun eventToMap(sensorEvent: SensorEvent): Bundle {
return Bundle().apply {
putDouble("x", sensorEvent.values[0].toDouble())
putDouble("y", sensorEvent.values[1].toDouble())
putDouble("z", sensorEvent.values[2].toDouble())
}
}
@ExpoMethod
fun startObserving(promise: Promise) {
super.startObserving()
promise.resolve(null)
}
@ExpoMethod
fun stopObserving(promise: Promise) {
super.stopObserving()
promise.resolve(null)
}
@ExpoMethod
fun setUpdateInterval(updateInterval: Int, promise: Promise) {
super.setUpdateInterval(updateInterval)
promise.resolve(null)
}
@ExpoMethod
fun isAvailableAsync(promise: Promise) {
val mSensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
val isAvailable = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) != null
promise.resolve(isAvailable)
}
}
| bsd-3-clause | 93286f64e45bc2a627fad1cfef0cd93a | 31.709091 | 90 | 0.770428 | 4.293556 | false | false | false | false |
joaoevangelista/Convertx | app/src/main/kotlin/io/github/joaoevangelista/convertx/op/ConversionExecutor.kt | 1 | 937 | package io.github.joaoevangelista.convertx.op
import io.github.joaoevangelista.convertx.activity.UnitsSelectedHolder
/**
* @author Joao Pedro Evangelista
*/
class ConversionExecutor {
fun execute(input: String,
onResult: (result: Double) -> Unit): Unit {
if (!input.isBlank()) {
val number = input.toDouble()
val from = UnitsSelectedHolder.fromUnit
val to = UnitsSelectedHolder.toUnit
if (to != null && from != null) {
when (from) {
is Lengths -> onResult(Conversions.ofLength(number, from, to as Lengths?).value as Double)
is Temperatures -> onResult(
Conversions.ofTemperature(number, from, to as Temperatures?).value as Double)
is Areas -> onResult(Conversions.ofArea(number, from, to as Areas?).value as Double)
is Volumes -> onResult(Conversions.ofVolume(number, from, to as Volumes?).value as Double)
}
}
}
}
}
| apache-2.0 | f108d99e40bc9df88c6f5e17095d506c | 32.464286 | 100 | 0.65635 | 3.82449 | false | false | false | false |
peervalhoegen/SudoQ | sudoq-app/sudoqapp/src/main/kotlin/de/sudoq/controller/menus/SudokuLoadingActivity.kt | 1 | 16407 | /*
* SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least.
* Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele
* 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.sudoq.controller.menus
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.AdapterView
import android.widget.AdapterView.OnItemClickListener
import android.widget.AdapterView.OnItemLongClickListener
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import com.google.android.material.floatingactionbutton.FloatingActionButton
import de.sudoq.R
import de.sudoq.controller.SudoqListActivity
import de.sudoq.controller.sudoku.SudokuActivity
import de.sudoq.model.game.GameData
import de.sudoq.model.game.GameManager
import de.sudoq.model.persistence.xml.game.IGamesListRepo
import de.sudoq.model.profile.ProfileManager
import de.sudoq.persistence.game.GameRepo
import de.sudoq.persistence.game.GamesListRepo
import de.sudoq.persistence.profile.ProfileRepo
import de.sudoq.persistence.profile.ProfilesListRepo
import de.sudoq.persistence.sudokuType.SudokuTypeRepo
import java.io.*
import java.nio.charset.Charset
import java.util.*
/**
* Diese Klasse repräsentiert den Lade-Controller des Sudokuspiels. Mithilfe von
* SudokuLoading können Sudokus geladen werden und daraufhin zur SudokuActivity
* gewechselt werden.
*/
class SudokuLoadingActivity : SudoqListActivity(), OnItemClickListener, OnItemLongClickListener {
/** Attributes */
private var profileManager: ProfileManager? = null
private var adapter: SudokuLoadingAdapter? = null
private var games: List<GameData>? = null
private lateinit var profilesDir: File
private lateinit var sudokuDir: File
private lateinit var sudokuTypeRepo: SudokuTypeRepo
private lateinit var gameManager: GameManager
/* protected static MenuItem menuDeleteFinished;
private static final int MENU_DELETE_FINISHED = 0;
protected static MenuItem menuDeleteSpecific;
private static final int MENU_DELETE_SPECIFIC = 1; commented out to make sure it's not needed*/
private enum class FabStates {
DELETE, INACTIVE, GO_BACK
} //Floating Action Button
private var fabState = FabStates.INACTIVE
/**
* Wird aufgerufen, wenn SudokuLoading nach Programmstart zum ersten Mal
* geladen aufgerufen wird. Hier wird das Layout inflated und es werden
* nötige Initialisierungen vorgenommen.
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
profilesDir = getDir(getString(R.string.path_rel_profiles), MODE_PRIVATE)
sudokuDir = getDir(getString(R.string.path_rel_sudokus), MODE_PRIVATE)
sudokuTypeRepo = SudokuTypeRepo(sudokuDir)
profileManager = ProfileManager(profilesDir, ProfileRepo(profilesDir),
ProfilesListRepo(profilesDir))
///init params for game*repos
profileManager!!.loadCurrentProfile()
val gameRepo = GameRepo(
profileManager!!.profilesDir!!,
profileManager!!.currentProfileID,
sudokuTypeRepo)
val gamesFile = File(profileManager!!.currentProfileDir, "games.xml")
val gamesDir = File(profileManager!!.currentProfileDir, "games")
val gamesListRepo : IGamesListRepo = GamesListRepo(gamesDir, gamesFile)
gameManager = GameManager(profileManager!!, gameRepo, gamesListRepo, sudokuTypeRepo)
//needs to be called before setcontentview which calls onContentChanged
check(!profileManager!!.noProfiles()) { "there are no profiles. this is unexpected. they should be initialized in splashActivity" }
profileManager!!.loadCurrentProfile()
setContentView(R.layout.sudokuloading)
//toolbar
initToolBar()
initFAB(this)
initialiseGames()
}
private fun initToolBar() {
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
val ab = supportActionBar
ab!!.setHomeAsUpIndicator(R.drawable.launcher)
ab.setDisplayHomeAsUpEnabled(true)
ab.setDisplayShowTitleEnabled(true)
}
private fun initFAB(ctx: Context) {
val fab = findViewById<FloatingActionButton>(R.id.fab)
fab.setOnClickListener(object : View.OnClickListener {
var trash = ContextCompat.getDrawable(ctx, R.drawable.ic_delete_white_24dp)
var close = ContextCompat.getDrawable(ctx, R.drawable.ic_close_white_24dp)
override fun onClick(view: View) {
when (fabState) {
FabStates.INACTIVE -> {
// ...
fabState = FabStates.DELETE
fab.setImageDrawable(close)
Toast.makeText(ctx, R.string.fab_go_back, Toast.LENGTH_LONG).show()
}
FabStates.DELETE -> {
fabState = FabStates.INACTIVE
fab.setImageDrawable(trash)
}
FabStates.GO_BACK -> goBack(view)
}
}
})
}
/// Action Bar
/**
* Wird beim ersten Anzeigen des Options-Menü von SudokuLoading aufgerufen
* und initialisiert das Optionsmenü indem das Layout inflated wird.
*
* @return true falls das Options-Menü angezeigt werden kann, sonst false
*/
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.action_bar_sudoku_loading, menu)
return true
}
/**
* Wird beim Auswählen eines Menü-Items im Options-Menü aufgerufen. Ist das
* spezifizierte MenuItem null oder ungültig, so wird nichts getan.
*
* @param item
* Das ausgewählte Menü-Item
* @return true, falls die Selection hier bearbeitet wird, false falls nicht
*/
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_sudokuloading_delete_finished -> {
gameManager.deleteFinishedGames()
}
R.id.action_sudokuloading_delete_all -> {
gameManager.gameList.forEach { gameManager.deleteGame(it.id) }
}
else -> super.onOptionsItemSelected(item)
}
onContentChanged()
return false
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
super.onPrepareOptionsMenu(menu)
val noGames = gameManager.gameList.isEmpty()
menu.findItem(R.id.action_sudokuloading_delete_finished).isVisible = !noGames
menu.findItem(R.id.action_sudokuloading_delete_all).isVisible = !noGames
return true
}
/**
* {@inheritDoc}
*/
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
/**
* {@inheritDoc}
*/
override fun onContentChanged() {
super.onContentChanged()
initialiseGames()
profileManager!!.currentGame = if (adapter!!.isEmpty) -1 else adapter!!.getItem(0)!!.id
}
/**
* Wird aufgerufen, falls ein Element (eine View) in der AdapterView
* angeklickt wird.
*
* @param parent
* AdapterView in welcher die View etwas angeklickt wurde
* @param view
* View, welche angeklickt wurde
* @param position
* Position der angeklickten View im Adapter
* @param id
* ID der angeklickten View
*/
override fun onItemClick(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
Log.d(LOG_TAG, position.toString() + "")
if (fabState == FabStates.INACTIVE) {
/* selected in order to play */
profileManager!!.currentGame = adapter!!.getItem(position)!!.id
startActivity(Intent(this, SudokuActivity::class.java))
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
} else {
/*selected in order to delete*/
gameManager.deleteGame(adapter!!.getItem(position)!!.id)
onContentChanged()
}
}
override fun onItemLongClick(
parent: AdapterView<*>?,
view: View,
position: Int,
id: Long
): Boolean {
Log.d(LOG_TAG, "LongClick on $position")
/*gather all options */
val temp_items: MutableList<CharSequence> = ArrayList()
val specialcase = false
if (specialcase) {
} else {
temp_items.add(getString(R.string.sudokuloading_dialog_play))
temp_items.add(getString(R.string.sudokuloading_dialog_delete))
if (profileManager!!.appSettings.isDebugSet) {
temp_items.add("export as text")
temp_items.add("export as file")
}
}
val builder = AlertDialog.Builder(this)
val profilesDir = getDir(getString(R.string.path_rel_profiles), MODE_PRIVATE)
val pm = ProfileManager(profilesDir, ProfileRepo(profilesDir),
ProfilesListRepo(profilesDir))
val gameRepo = GameRepo(pm.profilesDir!!, pm.currentProfileID, sudokuTypeRepo)
builder.setItems(temp_items.toTypedArray()) { dialog, item ->
val gameID = adapter!!.getItem(position)!!.id
when (item) {
0 -> { // play
profileManager!!.currentGame = gameID
val i = Intent(this@SudokuLoadingActivity, SudokuActivity::class.java)
startActivity(i)
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
}
1 -> { // delete
gameManager.deleteGame(gameID)
onContentChanged()
}
2 -> {
val gameFile = gameRepo.getGameFile(gameID)
var str = "there was an error reading the file, sorry"
var fis: FileInputStream? = null
try {
fis = FileInputStream(gameFile)
val data = ByteArray(gameFile.length().toInt())
fis.read(data)
fis.close()
str = String(data, Charset.forName("UTF-8"))
} catch (e: FileNotFoundException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
val sendIntent = Intent()
sendIntent.action = Intent.ACTION_SEND //
//sendIntent.putExtra(Intent.EXTRA_FROM_STORAGE, gameFile);
sendIntent.putExtra(Intent.EXTRA_TEXT, str)
sendIntent.type = "text/plain"
startActivity(sendIntent)
}
3 -> {
//already defined under 2
val gameFile = gameRepo.getGameFile(gameID)
/* we can only copy from 'files' subdir, so we have to move the file there first */
val tmpFile = File(filesDir, gameFile.name)
val `in`: InputStream
val out: OutputStream
try {
`in` = FileInputStream(gameFile)
out = FileOutputStream(tmpFile)
Utility.copyFileOnStreamLevel(`in`, out)
`in`.close()
out.flush()
out.close()
} catch (e: IOException) {
e.message?.let { Log.e(LOG_TAG, it) }
Log.e(LOG_TAG, "there seems to be an io exception")
} catch (e: FileNotFoundException) {
e.message?.let { Log.e(LOG_TAG, it) }
Log.e(LOG_TAG, "there seems to be a file not found exception")
}
Log.v("file-share", "tmpfile: " + tmpFile.absolutePath)
Log.v("file-share", "gamefile is null? " + (gameFile == null))
Log.v("file-share", "gamefile getPath " + gameFile.path)
Log.v("file-share", "gamefile getAbsolutePath " + gameFile.absolutePath)
Log.v("file-share", "gamefile getName " + gameFile.name)
Log.v("file-share", "gamefile getParent " + gameFile.parent)
val fileUri = FileProvider.getUriForFile(
this@SudokuLoadingActivity,
"de.sudoq.fileprovider", tmpFile
)
Log.v("file-share", "uri is null? " + (fileUri == null))
val sendIntent = Intent()
sendIntent.action = Intent.ACTION_SEND //
//sendIntent.putExtra(Intent.EXTRA_FROM_STORAGE, gameFile);
sendIntent.putExtra(Intent.EXTRA_STREAM, fileUri)
sendIntent.type = "text/plain"
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
//startActivity(Intent.createChooser(sendIntent, "Share to"));
startActivity(sendIntent)
}
}
}
val alert = builder.create()
alert.show()
return true //prevent itemclick from fire-ing as well
}
private fun initialiseGames() {
games = gameManager.gameList
// initialize ArrayAdapter for the profile names and set it
adapter = SudokuLoadingAdapter(this, games!!)
listAdapter = adapter
listView!!.onItemClickListener = this
listView!!.onItemLongClickListener = this
val noGamesTextView = findViewById<TextView>(R.id.no_games_text_view)
if (games!!.isEmpty()) {
noGamesTextView.visibility = View.VISIBLE
val fab = findViewById<FloatingActionButton>(R.id.fab)
fab.setImageDrawable(
ContextCompat.getDrawable(
this,
R.drawable.ic_arrow_back_white_24dp
)
)
fabState = FabStates.GO_BACK
} else {
noGamesTextView.visibility = View.INVISIBLE
//pass
}
}
/**
* Führt die onBackPressed-Methode aus.
*
* @param view
* unbenutzt
*/
fun goBack(view: View?) {
super.onBackPressed()
}
/**
* Just for testing!
* @return
* number of saved games
*/
val size: Int
get() = games!!.size
private inner class FAB(context: Context?) : FloatingActionButton(context) {
private var fs: FabStates? = null
fun setState(fs: FabStates?) {
this.fs = fs
val id: Int = when (fs) {
FabStates.DELETE -> R.drawable.ic_close_white_24dp
FabStates.INACTIVE -> R.drawable.ic_delete_white_24dp
else -> R.drawable.ic_arrow_back_white_24dp
}
super.setImageDrawable(ContextCompat.getDrawable(this.context, id))
}
}
companion object {
/**
* Der Log-Tag für das LogCat
*/
private val LOG_TAG = SudokuLoadingActivity::class.java.simpleName
}
} | gpl-3.0 | 90edaadfba63d13e30075655ade4bbec | 39.778607 | 243 | 0.605722 | 4.644942 | false | false | false | false |
JoachimR/Bible2net | app/src/main/java/de/reiss/bible2net/theword/main/content/FontSizePreferenceDialog.kt | 1 | 2397 | package de.reiss.bible2net.theword.main.content
import android.app.Dialog
import android.os.Bundle
import android.view.View
import android.widget.SeekBar
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import de.reiss.bible2net.theword.App
import de.reiss.bible2net.theword.R
import de.reiss.bible2net.theword.preferences.AppPreferences
class FontSizePreferenceDialog : DialogFragment() {
companion object {
fun createInstance() = FontSizePreferenceDialog()
}
private val appPreferences: AppPreferences by lazy {
App.component.appPreferences
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog =
activity.let { activity ->
if (activity == null) {
throw NullPointerException()
}
AlertDialog.Builder(activity)
.setTitle(getString(R.string.fontsize_dialog_title))
.setCancelable(true)
.setPositiveButton(activity.getString(R.string.fontsize_dialog_ok)) { _, _ ->
dismiss()
}
.setView(initDialogUi())
.create()
}
private fun initDialogUi(): View {
activity.let { activity ->
if (activity == null) {
throw NullPointerException()
}
val view = activity.layoutInflater.inflate(R.layout.fontsize_dialog, null)
view.findViewById<SeekBar>(R.id.fontsize_dialog_seekbar).apply {
progress = appPreferences.fontSize()
setOnSeekBarChangeListener(
object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(
seekBar: SeekBar,
progress: Int,
fromUser: Boolean
) {
if (fromUser) {
appPreferences.changeFontSize(newFontSize = progress)
}
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
}
}
)
}
return view
}
}
}
| gpl-3.0 | 3f8571851be1f30bbb857d28a2d9dfd2 | 30.96 | 93 | 0.539424 | 5.762019 | false | false | false | false |
androidx/androidx | bluetooth/bluetooth-core/src/main/java/androidx/bluetooth/core/ScanFilter.kt | 3 | 15760 | /*
* 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.bluetooth.core
import android.bluetooth.le.ScanFilter as FwkScanFilter
import android.bluetooth.le.ScanResult as FwkScanResult
import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.os.ParcelUuid
import androidx.annotation.RequiresApi
import androidx.annotation.RestrictTo
/**
* Criteria for filtering result from Bluetooth LE scans. A {@link ScanFilter} allows clients to
* restrict scan results to only those that are of interest to them.
* <p>
* Current filtering on the following fields are supported:
* <li>Service UUIDs which identify the bluetooth gatt services running on the device.
* <li>Name of remote Bluetooth LE device.
* <li>Mac address of the remote device.
* <li>Service data which is the data associated with a service.
* <li>Manufacturer specific data which is the data associated with a particular manufacturer.
* <li>Advertising data type and corresponding data.
*
* @see BluetoothLeScanner
*/
// TODO: Add @See ScanResult once ScanResult added
@SuppressWarnings("HiddenSuperclass") // Bundleable
class ScanFilter internal constructor(
internal val impl: ScanFilterImpl
) : Bundleable {
companion object {
internal const val FIELD_FWK_SCAN_FILTER = 0
internal const val FIELD_SERVICE_SOLICITATION_UUID = 1
internal const val FIELD_SERVICE_SOLICITATION_UUID_MASK = 2
internal const val FIELD_ADVERTISING_DATA = 3
internal const val FIELD_ADVERTISING_DATA_MASK = 4
internal const val FIELD_ADVERTISING_DATA_TYPE = 5
/**
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
@JvmField
val CREATOR: Bundleable.Creator<ScanFilter> =
object : Bundleable.Creator<ScanFilter> {
override fun fromBundle(bundle: Bundle): ScanFilter {
return bundle.getScanFilter()
}
}
internal fun keyForField(field: Int): String {
return field.toString(Character.MAX_RADIX)
}
internal fun Bundle.putScanFilter(filter: ScanFilter) {
this.putParcelable(
keyForField(FIELD_FWK_SCAN_FILTER), filter.impl.fwkInstance)
if (Build.VERSION.SDK_INT < 29) {
if (filter.serviceSolicitationUuid != null) {
this.putParcelable(
keyForField(FIELD_SERVICE_SOLICITATION_UUID),
filter.serviceSolicitationUuid)
}
if (filter.serviceSolicitationUuidMask != null) {
this.putParcelable(
keyForField(FIELD_SERVICE_SOLICITATION_UUID_MASK),
filter.serviceSolicitationUuidMask)
}
}
if (Build.VERSION.SDK_INT < 33) {
if (filter.advertisingData != null) {
this.putByteArray(
keyForField(FIELD_ADVERTISING_DATA),
filter.advertisingData)
this.putByteArray(
keyForField(FIELD_ADVERTISING_DATA_MASK),
filter.advertisingDataMask)
this.putInt(
keyForField(FIELD_ADVERTISING_DATA_TYPE),
filter.advertisingDataType)
}
}
}
internal fun Bundle.getScanFilter(): ScanFilter {
val fwkScanFilter =
Utils.getParcelableFromBundle(
this,
keyForField(FIELD_FWK_SCAN_FILTER),
android.bluetooth.le.ScanFilter::class.java
) ?: throw IllegalArgumentException(
"Bundle doesn't include a framework scan filter"
)
var args = ScanFilterArgs()
if (Build.VERSION.SDK_INT < 33) {
args.advertisingDataType = this.getInt(
keyForField(FIELD_ADVERTISING_DATA_TYPE), -1)
args.advertisingData = this.getByteArray(
keyForField(FIELD_ADVERTISING_DATA))
args.advertisingDataMask = this.getByteArray(
keyForField(FIELD_ADVERTISING_DATA_MASK))
}
if (Build.VERSION.SDK_INT < 29) {
args.serviceSolicitationUuid =
Utils.getParcelableFromBundle(
this,
keyForField(FIELD_SERVICE_SOLICITATION_UUID),
ParcelUuid::class.java
)
args.serviceSolicitationUuidMask =
Utils.getParcelableFromBundle(
this,
keyForField(FIELD_SERVICE_SOLICITATION_UUID_MASK),
ParcelUuid::class.java
)
}
return ScanFilter(fwkScanFilter, args)
}
}
val deviceName: String?
get() = impl.deviceName
val deviceAddress: String?
get() = impl.deviceAddress
val serviceUuid: ParcelUuid?
get() = impl.serviceUuid
val serviceUuidMask: ParcelUuid?
get() = impl.serviceUuidMask
val serviceDataUuid: ParcelUuid?
get() = impl.serviceDataUuid
val serviceData: ByteArray?
get() = impl.serviceData
val serviceDataMask: ByteArray?
get() = impl.serviceDataMask
val manufacturerId: Int
get() = impl.manufacturerId
val manufacturerData: ByteArray?
get() = impl.manufacturerData
val manufacturerDataMask: ByteArray?
get() = impl.manufacturerDataMask
val serviceSolicitationUuid: ParcelUuid?
get() = impl.serviceSolicitationUuid
val serviceSolicitationUuidMask: ParcelUuid?
get() = impl.serviceSolicitationUuidMask
val advertisingData: ByteArray?
get() = impl.advertisingData
val advertisingDataMask: ByteArray?
get() = impl.advertisingDataMask
val advertisingDataType: Int
get() = impl.advertisingDataType
internal constructor(fwkInstance: FwkScanFilter) : this(
if (Build.VERSION.SDK_INT >= 33) {
ScanFilterImplApi33(fwkInstance)
} else if (Build.VERSION.SDK_INT >= 29) {
ScanFilterImplApi29(fwkInstance)
} else {
ScanFilterImplApi21(fwkInstance)
}
)
constructor(
deviceName: String? = null,
deviceAddress: String? = null,
serviceUuid: ParcelUuid? = null,
serviceUuidMask: ParcelUuid? = null,
serviceDataUuid: ParcelUuid? = null,
serviceData: ByteArray? = null,
serviceDataMask: ByteArray? = null,
manufacturerId: Int = -1,
manufacturerData: ByteArray? = null,
manufacturerDataMask: ByteArray? = null,
serviceSolicitationUuid: ParcelUuid? = null,
serviceSolicitationUuidMask: ParcelUuid? = null,
advertisingData: ByteArray? = null,
advertisingDataMask: ByteArray? = null,
advertisingDataType: Int = -1 // TODO: Use ScanRecord.DATA_TYPE_NONE
) : this(ScanFilterArgs(
deviceName,
deviceAddress,
serviceUuid,
serviceUuidMask,
serviceDataUuid,
serviceData,
serviceDataMask,
manufacturerId,
manufacturerData,
manufacturerDataMask,
serviceSolicitationUuid,
serviceSolicitationUuidMask,
advertisingData,
advertisingDataMask,
advertisingDataType
))
internal constructor(args: ScanFilterArgs) : this(args.toFwkScanFilter(), args)
internal constructor(fwkInstance: FwkScanFilter, args: ScanFilterArgs) : this(
if (Build.VERSION.SDK_INT >= 33) {
ScanFilterImplApi33(fwkInstance)
} else if (Build.VERSION.SDK_INT >= 29) {
ScanFilterImplApi29(fwkInstance, args)
} else {
ScanFilterImplApi21(fwkInstance, args)
}
)
/**
* Check if the scan filter matches a {@code scanResult}. A scan result is considered as a match
* if it matches all the field filters.
*/
// TODO: add test for this method
fun matches(scanResult: FwkScanResult?): Boolean = impl.matches(scanResult)
/**
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
override fun toBundle(): Bundle {
val bundle = Bundle()
bundle.putScanFilter(this)
return bundle
}
}
internal data class ScanFilterArgs(
var deviceName: String? = null,
var deviceAddress: String? = null,
var serviceUuid: ParcelUuid? = null,
var serviceUuidMask: ParcelUuid? = null,
var serviceDataUuid: ParcelUuid? = null,
var serviceData: ByteArray? = null,
var serviceDataMask: ByteArray? = null,
var manufacturerId: Int = -1,
var manufacturerData: ByteArray? = null,
var manufacturerDataMask: ByteArray? = null,
var serviceSolicitationUuid: ParcelUuid? = null,
var serviceSolicitationUuidMask: ParcelUuid? = null,
var advertisingData: ByteArray? = null,
var advertisingDataMask: ByteArray? = null,
var advertisingDataType: Int = -1 // TODO: Use ScanRecord.DATA_TYPE_NONE
) {
// "ClassVerificationFailure" for FwkScanFilter.Builder
// "WrongConstant" for AdvertisingDataType
@SuppressLint("ClassVerificationFailure", "WrongConstant")
internal fun toFwkScanFilter(): FwkScanFilter {
val builder = FwkScanFilter.Builder()
.setDeviceName(deviceName)
.setDeviceAddress(deviceAddress)
.setServiceUuid(serviceUuid)
if (serviceDataUuid != null) {
if (serviceDataMask == null) {
builder.setServiceData(serviceDataUuid, serviceData)
} else {
builder.setServiceData(
serviceDataUuid, serviceData, serviceDataMask)
}
}
if (manufacturerId >= 0) {
if (manufacturerDataMask == null) {
builder.setManufacturerData(manufacturerId, manufacturerData)
} else {
builder.setManufacturerData(
manufacturerId, manufacturerData, manufacturerDataMask)
}
}
if (Build.VERSION.SDK_INT >= 29 && serviceSolicitationUuid != null) {
if (serviceSolicitationUuidMask == null) {
builder.setServiceSolicitationUuid(serviceSolicitationUuid)
} else {
builder.setServiceSolicitationUuid(
serviceSolicitationUuid, serviceSolicitationUuidMask
)
}
}
if (Build.VERSION.SDK_INT >= 33 && advertisingDataType > 0) {
if (advertisingData != null && advertisingDataMask != null) {
builder.setAdvertisingDataTypeWithData(advertisingDataType,
advertisingData!!, advertisingDataMask!!)
} else {
builder.setAdvertisingDataType(advertisingDataType)
}
}
return builder.build()
}
}
internal interface ScanFilterImpl {
val deviceName: String?
val deviceAddress: String?
val serviceUuid: ParcelUuid?
val serviceUuidMask: ParcelUuid?
val serviceDataUuid: ParcelUuid?
val serviceData: ByteArray?
val serviceDataMask: ByteArray?
val manufacturerId: Int
val manufacturerData: ByteArray?
val manufacturerDataMask: ByteArray?
val serviceSolicitationUuid: ParcelUuid?
val serviceSolicitationUuidMask: ParcelUuid?
val advertisingData: ByteArray?
val advertisingDataMask: ByteArray?
val advertisingDataType: Int
val fwkInstance: FwkScanFilter
fun matches(scanResult: FwkScanResult?): Boolean
}
internal abstract class ScanFilterFwkImplApi21 internal constructor(
override val fwkInstance: FwkScanFilter
) : ScanFilterImpl {
override val deviceName: String?
get() = fwkInstance.deviceName
override val deviceAddress: String?
get() = fwkInstance.deviceAddress
override val serviceUuid: ParcelUuid?
get() = fwkInstance.serviceUuid
override val serviceUuidMask: ParcelUuid?
get() = fwkInstance.serviceUuidMask
override val serviceDataUuid: ParcelUuid?
get() = fwkInstance.serviceDataUuid
override val serviceData: ByteArray?
get() = fwkInstance.serviceData
override val serviceDataMask: ByteArray?
get() = fwkInstance.serviceDataMask
override val manufacturerId: Int
get() = fwkInstance.manufacturerId
override val manufacturerData: ByteArray?
get() = fwkInstance.manufacturerData
override val manufacturerDataMask: ByteArray?
get() = fwkInstance.manufacturerDataMask
override fun matches(scanResult: android.bluetooth.le.ScanResult?): Boolean {
return fwkInstance.matches(scanResult)
}
}
internal class ScanFilterImplApi21 internal constructor(
fwkInstance: FwkScanFilter,
override val serviceSolicitationUuid: ParcelUuid? = null,
override val serviceSolicitationUuidMask: ParcelUuid? = null,
override val advertisingData: ByteArray? = null,
override val advertisingDataMask: ByteArray? = null,
override val advertisingDataType: Int = -1 // TODO: Use ScanRecord.DATA_TYPE_NONE
) : ScanFilterFwkImplApi21(fwkInstance) {
internal constructor(fwkInstance: FwkScanFilter, args: ScanFilterArgs) : this(
fwkInstance, args.serviceSolicitationUuid, args.serviceSolicitationUuidMask,
args.advertisingData, args.advertisingDataMask, args.advertisingDataType
)
}
@RequiresApi(Build.VERSION_CODES.Q)
internal abstract class ScanFilterFwkImplApi29(
fwkInstance: FwkScanFilter
) : ScanFilterFwkImplApi21(fwkInstance) {
override val serviceSolicitationUuid: ParcelUuid?
get() = fwkInstance.serviceSolicitationUuid
override val serviceSolicitationUuidMask: ParcelUuid?
get() = fwkInstance.serviceSolicitationUuidMask
}
@RequiresApi(Build.VERSION_CODES.Q)
internal class ScanFilterImplApi29 internal constructor(
fwkInstance: FwkScanFilter,
override val advertisingData: ByteArray? = null,
override val advertisingDataMask: ByteArray? = null,
override val advertisingDataType: Int = -1 // TODO: Use ScanRecord.DATA_TYPE_NONE
) : ScanFilterFwkImplApi29(fwkInstance) {
internal constructor(fwkInstance: FwkScanFilter, args: ScanFilterArgs) : this(
fwkInstance, args.advertisingData, args.advertisingDataMask, args.advertisingDataType
)
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
internal abstract class ScanFilterFwkImplApi33(fwkInstance: FwkScanFilter) :
ScanFilterFwkImplApi29(fwkInstance) {
override val advertisingData: ByteArray?
get() = fwkInstance.advertisingData
override val advertisingDataMask: ByteArray?
get() = fwkInstance.advertisingDataMask
override val advertisingDataType: Int
get() = fwkInstance.advertisingDataType
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
internal class ScanFilterImplApi33 internal constructor(
fwkInstance: FwkScanFilter
) : ScanFilterFwkImplApi33(fwkInstance)
| apache-2.0 | 51494d7265ae86710f4d1238513dfe24 | 37.439024 | 100 | 0.653173 | 4.696067 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/util/SystemWindowInsetsSetter.kt | 1 | 1839 | package org.thoughtcrime.securesms.util
import android.os.Build
import android.view.View
import androidx.core.graphics.Insets
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
object SystemWindowInsetsSetter {
/**
* Updates the view whenever a layout occurs to properly set the system bar insets. setPadding is safe here because it will only trigger an extra layout
* call IF the values actually changed.
*/
fun attach(view: View, lifecycleOwner: LifecycleOwner, @WindowInsetsCompat.Type.InsetsType insetType: Int = WindowInsetsCompat.Type.systemBars()) {
val listener = view.doOnEachLayout {
val insets: Insets? = ViewCompat.getRootWindowInsets(view)?.getInsets(insetType)
if (Build.VERSION.SDK_INT > 29 && insets != null && !insets.isEmpty()) {
view.setPadding(
insets.left,
insets.top,
insets.right,
insets.bottom
)
} else {
val top = if (insetType and WindowInsetsCompat.Type.statusBars() != 0) {
ViewUtil.getStatusBarHeight(view)
} else {
0
}
val bottom = if (insetType and WindowInsetsCompat.Type.navigationBars() != 0) {
ViewUtil.getNavigationBarHeight(view)
} else {
0
}
view.setPadding(
0,
top,
0,
bottom
)
}
}
val lifecycleObserver = object : DefaultLifecycleObserver {
override fun onDestroy(owner: LifecycleOwner) {
view.removeOnLayoutChangeListener(listener)
}
}
lifecycleOwner.lifecycle.addObserver(lifecycleObserver)
}
private fun Insets.isEmpty(): Boolean {
return (top + bottom + right + left) == 0
}
}
| gpl-3.0 | 2e370a00dbe757ea57077682b520f7f5 | 29.147541 | 154 | 0.660685 | 4.776623 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/forum/TopicActivity.kt | 1 | 4412 | package me.proxer.app.forum
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.core.app.ShareCompat
import androidx.fragment.app.commitNow
import com.jakewharton.rxbinding3.view.clicks
import com.mikepenz.iconics.utils.IconicsMenuInflaterUtil
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable
import me.proxer.app.R
import me.proxer.app.base.DrawerActivity
import me.proxer.app.util.extension.getSafeStringExtra
import me.proxer.app.util.extension.intentFor
import me.proxer.app.util.extension.multilineSnackbar
import me.proxer.app.util.extension.startActivity
import me.proxer.app.util.extension.subscribeAndLogErrors
import me.proxer.library.util.ProxerUrls
/**
* @author Ruben Gees
*/
class TopicActivity : DrawerActivity() {
companion object {
private const val ID_EXTRA = "id"
private const val CATEGORY_ID_EXTRA = "category_id"
private const val TOPIC_EXTRA = "topic"
private const val TOUZAI_PATH = "/touzai"
private const val TOUZAI_CATEGORY = "310"
fun navigateTo(context: Activity, id: String, categoryId: String, topic: String? = null) {
context.startActivity<TopicActivity>(
ID_EXTRA to id,
CATEGORY_ID_EXTRA to categoryId,
TOPIC_EXTRA to topic
)
}
fun getIntent(context: Context, id: String, categoryId: String, topic: String? = null): Intent {
return context.intentFor<TopicActivity>(
ID_EXTRA to id,
CATEGORY_ID_EXTRA to categoryId,
TOPIC_EXTRA to topic
)
}
}
val id: String
get() = when (intent.hasExtra(ID_EXTRA)) {
true -> intent.getSafeStringExtra(ID_EXTRA)
false -> when (intent.data?.path == TOUZAI_PATH) {
true -> intent.data?.getQueryParameter("id") ?: "-1"
else -> intent.data?.pathSegments?.getOrNull(2) ?: "-1"
}
}
val categoryId: String
get() = when (intent.hasExtra(CATEGORY_ID_EXTRA)) {
true -> intent.getSafeStringExtra(CATEGORY_ID_EXTRA)
false -> when (intent.data?.path == TOUZAI_PATH) {
true -> TOUZAI_CATEGORY
else -> intent.data?.pathSegments?.getOrNull(1) ?: "-1"
}
}
var topic: String?
get() = intent.getStringExtra(TOPIC_EXTRA)
set(value) {
intent.putExtra(TOPIC_EXTRA, value)
title = value
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupToolbar()
if (savedInstanceState == null) {
supportFragmentManager.commitNow {
replace(R.id.container, TopicFragment.newInstance())
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
IconicsMenuInflaterUtil.inflate(menuInflater, this, R.menu.activity_share, menu, true)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_share -> topic
?.let {
val url = when (intent.action) {
Intent.ACTION_VIEW -> intent.dataString
else -> ProxerUrls.forumWeb(categoryId, id).toString()
}
it to url
}
?.let { (topic, url) ->
ShareCompat.IntentBuilder
.from(this)
.setText(getString(R.string.share_topic, topic, url))
.setType("text/plain")
.setChooserTitle(getString(R.string.share_title))
.startChooser()
}
}
return super.onOptionsItemSelected(item)
}
private fun setupToolbar() {
supportActionBar?.setDisplayHomeAsUpEnabled(true)
title = topic
toolbar.clicks()
.autoDisposable(this.scope())
.subscribeAndLogErrors {
topic?.also { topic ->
multilineSnackbar(topic)
}
}
}
}
| gpl-3.0 | c9abd7721208c22ece891145db82c7f8 | 31.925373 | 104 | 0.589529 | 4.688629 | false | false | false | false |
solkin/drawa-android | app/src/main/java/com/tomclaw/drawa/share/ShareAdapter.kt | 1 | 1034 | package com.tomclaw.drawa.share
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.jakewharton.rxrelay2.PublishRelay
import com.tomclaw.drawa.R
import com.tomclaw.drawa.util.DataProvider
class ShareAdapter(
private val layoutInflater: LayoutInflater,
private val dataProvider: DataProvider<ShareItem>
) : RecyclerView.Adapter<ShareItemHolder>() {
var itemRelay: PublishRelay<ShareItem>? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ShareItemHolder {
val view = layoutInflater.inflate(R.layout.share_item_view, parent, false)
return ShareItemHolder(view, itemRelay)
}
override fun onBindViewHolder(holder: ShareItemHolder, position: Int) {
val item = dataProvider.getItem(position)
holder.bind(item)
}
override fun getItemId(position: Int): Long = dataProvider.getItem(position).id.toLong()
override fun getItemCount(): Int = dataProvider.size()
}
| apache-2.0 | ed401ca528ea7cdab51f0ebebf3865ec | 32.354839 | 92 | 0.752418 | 4.535088 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/adapter/viewholder/AwardChildViewHolder.kt | 2 | 2217 | package ru.fantlab.android.ui.adapter.viewholder
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import kotlinx.android.synthetic.main.work_awards_child_row_item.view.*
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.model.WorkAwardsChild
import ru.fantlab.android.provider.scheme.LinkParserHelper
import ru.fantlab.android.ui.widgets.FontTextView
import ru.fantlab.android.ui.widgets.ForegroundImageView
import ru.fantlab.android.ui.widgets.treeview.TreeNode
import ru.fantlab.android.ui.widgets.treeview.TreeViewAdapter
import ru.fantlab.android.ui.widgets.treeview.TreeViewBinder
class AwardChildViewHolder : TreeViewBinder<AwardChildViewHolder.ViewHolder>() {
override val layoutId: Int = R.layout.work_awards_child_row_item
override fun provideViewHolder(itemView: View) = ViewHolder(itemView)
override fun bindView(
holder: RecyclerView.ViewHolder,
position: Int,
node: TreeNode<*>,
onTreeNodeListener: TreeViewAdapter.OnTreeNodeListener?
) {
val childNode = node.content as WorkAwardsChild?
holder as AwardChildViewHolder.ViewHolder
if (childNode != null) {
Glide.with(holder.itemView.context).load("https://${LinkParserHelper.HOST_DATA}/images/awards/${childNode.awardId}")
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(holder.awardIcon)
holder.nameRus.text = childNode.nameRus
if (childNode.nameOrig.isNotEmpty()) {
holder.name.text = childNode.nameOrig
holder.name.visibility = View.VISIBLE
} else holder.name.visibility = View.GONE
if (!childNode.type.isNullOrEmpty()) {
holder.type.text = childNode.type
holder.type.visibility = View.VISIBLE
} else holder.type.visibility = View.GONE
holder.date.text = childNode.date.toString()
}
}
inner class ViewHolder(rootView: View) : TreeViewBinder.ViewHolder(rootView) {
var awardIcon: ForegroundImageView = rootView.awardIcon
var name: FontTextView = rootView.name
var nameRus: FontTextView = rootView.nameRus
var country: FontTextView = rootView.country
var type: FontTextView = rootView.type
var date: FontTextView = rootView.date
}
}
| gpl-3.0 | 4c86c04c392d79fd8475106f9d798c67 | 36.576271 | 119 | 0.784844 | 3.802744 | false | false | false | false |
TUWien/DocScan | app/src/main/java/at/ac/tuwien/caa/docscan/logic/GlideHelper.kt | 1 | 7759 | package at.ac.tuwien.caa.docscan.logic
import android.content.Context
import android.graphics.drawable.Drawable
import android.widget.ImageView
import at.ac.tuwien.caa.docscan.DocScanApp
import at.ac.tuwien.caa.docscan.R
import at.ac.tuwien.caa.docscan.db.model.Page
import at.ac.tuwien.caa.docscan.db.model.exif.Rotation
import at.ac.tuwien.caa.docscan.glidemodule.CropRectTransform
import at.ac.tuwien.caa.docscan.glidemodule.GlideApp
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory
import com.bumptech.glide.signature.MediaStoreSignature
import com.bumptech.glide.signature.ObjectKey
import org.koin.java.KoinJavaComponent.inject
import timber.log.Timber
import java.io.File
/**
* A helper utility class for glide for summarizing all loading functions and styles across the app.
*/
object GlideHelper {
private val fileHandler: FileHandler by inject(FileHandler::class.java)
private val app: DocScanApp by inject(DocScanApp::class.java)
fun loadFileIntoImageView(
file: File,
rotation: Rotation,
imageView: ImageView,
style: GlideStyles,
onResourceReady: (isFirstResource: Boolean) -> Unit = {},
onResourceFailed: (isFirstResource: Boolean, e: GlideException?) -> Unit = { _, _ -> }
) {
loadIntoView(
app,
imageView,
null,
null,
file,
PageFileType.JPEG,
rotation,
style,
onResourceReady,
onResourceFailed
)
}
fun loadPageIntoImageView(
page: Page?,
imageView: ImageView,
style: GlideStyles,
callback: GlideLegacyCallback
) {
loadPageIntoImageView(
page,
imageView,
style,
page?.fileHash,
callback::onResourceReady,
callback::onResourceFailed
)
}
fun loadPageIntoImageView(
page: Page?,
imageView: ImageView,
style: GlideStyles
) {
loadPageIntoImageView(page, imageView, style, page?.fileHash, {}, { _, _ -> })
}
private fun loadPageIntoImageView(
page: Page?,
imageView: ImageView,
style: GlideStyles,
fileHash: String?,
onResourceReady: (isFirstResource: Boolean) -> Unit = {},
onResourceFailed: (isFirstResource: Boolean, e: GlideException?) -> Unit = { _, _ -> }
) {
if (page != null) {
val file = fileHandler.getFileByPage(page)
if (file != null) {
loadIntoView(
app,
imageView,
CropRectTransform(page, imageView.context),
fileHash,
file,
PageFileType.JPEG,
page.rotation,
style,
onResourceReady,
onResourceFailed
)
return
}
onResourceFailed.invoke(false, null)
}
Timber.w("Image file doesn't exist and cannot be shown with Glide!")
// clear the image view in case that the file or even the page doesn't exist
GlideApp.with(app).clear(imageView)
}
/**
* Loads an image into a imageview with Glide.
* @param fileHash if available, then this will be used as a key for caching, otherwise it fall
* backs to [MediaStoreSignature].
*
* Please note, that any kind of manipulation of the [file] during an image load may lead to very
* bad issues, where the app may crash and the file gets corrupted, always ensure that when this
* function is called, no modifications to the [file] will happen.
*/
private fun loadIntoView(
context: Context,
imageView: ImageView,
transformation: BitmapTransformation?,
fileHash: String?,
file: File,
@Suppress("SameParameterValue") fileType: PageFileType,
rotation: Rotation,
style: GlideStyles,
onResourceReady: (isFirstResource: Boolean) -> Unit = {},
onResourceFailed: (isFirstResource: Boolean, e: GlideException?) -> Unit = { _, _ -> }
) {
// Needs to be added via factory to prevent issues with partially transparent images
// see http://bumptech.github.io/glide/doc/transitions.html#cross-fading-with-placeholders-and-transparent-images
val factory = DrawableCrossFadeFactory.Builder().setCrossFadeEnabled(false).build()
val glideRequest = GlideApp.with(context)
.load(file)
// disable caching temporarily to test
// .skipMemoryCache(true)
// .diskCacheStrategy(DiskCacheStrategy.NONE)
.signature(
if (fileHash != null) {
ObjectKey(fileHash)
} else {
MediaStoreSignature(
fileType.mimeType,
file.lastModified(),
rotation.exifOrientation
)
}
)
.listener(object : RequestListener<Drawable?> {
override fun onLoadFailed(
e: GlideException?,
model: Any,
target: Target<Drawable?>,
isFirstResource: Boolean
): Boolean {
onResourceFailed(isFirstResource, e)
return false
}
override fun onResourceReady(
resource: Drawable?,
model: Any,
target: Target<Drawable?>,
dataSource: DataSource,
isFirstResource: Boolean
): Boolean {
onResourceReady(isFirstResource)
return false
}
})
val glideTransformRequest = when (style) {
GlideStyles.DEFAULT -> {
glideRequest
}
GlideStyles.CAMERA_THUMBNAIL -> {
glideRequest.transform(CircleCrop()).transition(withCrossFade(factory))
}
GlideStyles.DOCUMENT_PREVIEW -> {
glideRequest.transform(
CenterCrop(),
RoundedCorners(context.resources.getDimensionPixelSize(R.dimen.document_preview_corner_radius))
).transition(withCrossFade(factory))
}
GlideStyles.IMAGE_CROPPED -> {
glideRequest.transition(withCrossFade(factory))
}
GlideStyles.IMAGES_UNCROPPED -> {
transformation?.let {
glideRequest.transform(it).transition(withCrossFade(factory))
} ?: glideRequest.transition(withCrossFade(factory))
}
}
glideTransformRequest.into(imageView)
}
enum class GlideStyles {
DEFAULT,
CAMERA_THUMBNAIL,
DOCUMENT_PREVIEW,
IMAGE_CROPPED,
IMAGES_UNCROPPED
}
}
interface GlideLegacyCallback {
fun onResourceReady(isFirstResource: Boolean)
fun onResourceFailed(isFirstResource: Boolean, e: GlideException?)
}
| lgpl-3.0 | bef00172504cd66b8af2ddb6b41ee728 | 34.75576 | 121 | 0.593375 | 5.044863 | false | false | false | false |
develar/mapsforge-tile-server | pixi/src/PixiPointTextContainer.kt | 1 | 2844 | package org.develar.mapsforgeTileServer.pixi
import org.mapsforge.core.graphics.Canvas
import org.mapsforge.core.graphics.Matrix
import org.mapsforge.core.graphics.Paint
import org.mapsforge.core.graphics.Position
import org.mapsforge.core.mapelements.MapElementContainer
import org.mapsforge.core.mapelements.SymbolContainer
import org.mapsforge.core.model.Point
import org.mapsforge.core.model.Rectangle
import org.mapsforge.map.layer.renderer.CanvasEx
import org.mapsforge.map.layer.renderer.MapElementContainerEx
class PixiPointTextContainer(private val text:String, point:Point, priority:Int, private val paintFront:Paint, private val paintBack:Paint?, symbolContainer:SymbolContainer?, position:Position, maxTextWidth:Int) : MapElementContainer(point, priority), MapElementContainerEx {
init {
boundary = computeBoundary(((paintBack ?: paintFront) as PixiPaint).getTextVisualBounds(text), maxTextWidth, position)
}
override fun draw(canvas:CanvasEx, origin:Point) {
canvas.drawText(text, (xy.x - origin.x) + boundary.left, (xy.y - origin.y) + boundary.top, paintFront, paintBack)
}
override fun clashesWith(other:MapElementContainer):Boolean {
if (super<MapElementContainer>.clashesWith(other)) {
return true;
}
return other is PixiPointTextContainer && text == other.text && getPoint().distance(other.getPoint()) < 200
}
override fun draw(canvas:Canvas, origin:Point, matrix:Matrix) = throw IllegalStateException()
override fun equals(other:Any?):Boolean {
if (!super<MapElementContainer>.equals(other)) {
return false;
}
return other is PixiPointTextContainer && text == other.text;
}
override fun hashCode():Int {
return 31 * super<MapElementContainer>.hashCode() + text.hashCode();
}
private fun computeBoundary(textVisualBounds:java.awt.Point, maxTextWidth:Int, position:Position):Rectangle {
val lines = textVisualBounds.x / maxTextWidth + 1
var boxWidth = textVisualBounds.x.toDouble()
var boxHeight = textVisualBounds.y.toDouble()
if (lines > 1) {
// a crude approximation of the size of the text box
//boxWidth = maxTextWidth.toDouble()
//boxHeight = (textHeight * lines).toDouble()
}
when (position) {
Position.CENTER -> {
return Rectangle(-boxWidth / 2, -boxHeight / 2, boxWidth / 2, boxHeight / 2)
}
Position.BELOW -> {
return Rectangle(-boxWidth / 2, 0.0, boxWidth / 2, boxHeight)
}
Position.ABOVE -> {
return Rectangle(-boxWidth / 2, -boxHeight, boxWidth / 2, 0.0)
}
Position.LEFT -> {
return Rectangle(-boxWidth, -boxHeight / 2, 0.0, boxHeight / 2)
}
Position.RIGHT -> {
return Rectangle(0.0, -boxHeight / 2, boxWidth, boxHeight / 2)
}
else -> throw UnsupportedOperationException()
}
}
} | mit | 067bd6f5e3dcf9859be267527d6e9579 | 37.972603 | 275 | 0.71097 | 3.939058 | false | false | false | false |
xdtianyu/CallerInfo | app/src/main/java/org/xdty/callerinfo/service/MarkWindow.kt | 1 | 4497 | package org.xdty.callerinfo.service
import android.app.Service
import android.content.Context
import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.View.OnFocusChangeListener
import android.view.WindowManager
import android.widget.FrameLayout
import com.pkmmte.view.CircularImageView
import org.xdty.callerinfo.R
import org.xdty.callerinfo.model.setting.Setting
import org.xdty.callerinfo.model.setting.SettingImpl
import org.xdty.callerinfo.utils.Utils
import wei.mark.standout.StandOutWindow
import wei.mark.standout.StandOutWindow.StandOutLayoutParams
import wei.mark.standout.constants.StandOutFlags
import wei.mark.standout.ui.Window
// MarkWindow is not used
class MarkWindow : StandOutWindow() {
private var mWindowManager: WindowManager? = null
private var mSettings: Setting? = null
override fun onCreate() {
super.onCreate()
mWindowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
try {
mSettings = SettingImpl.instance
return super.onStartCommand(intent, flags, startId)
} catch (e: IllegalArgumentException) {
e.printStackTrace()
stopSelf(startId)
}
return Service.START_NOT_STICKY
}
override fun getAppName(): String {
return resources.getString(R.string.mark_window)
}
override fun getAppIcon(): Int {
return R.drawable.status_icon
}
override fun createAndAttachView(id: Int, frame: FrameLayout) {
val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val view = inflater.inflate(R.layout.mark_window, frame, true)
bindCircleImage(view, R.id.express)
bindCircleImage(view, R.id.takeout)
bindCircleImage(view, R.id.selling)
bindCircleImage(view, R.id.harass)
bindCircleImage(view, R.id.bilk)
}
override fun attachBaseContext(newBase: Context) {
val context: Context = Utils.changeLang(newBase)
super.attachBaseContext(context)
}
private fun bindCircleImage(view: View, id: Int) {
val circularImageView = view.findViewById<View>(id) as CircularImageView
circularImageView.onFocusChangeListener = OnFocusChangeListener { v, hasFocus -> Log.e(TAG, "$v: $hasFocus") }
circularImageView.setOnClickListener { v -> Log.e(TAG, v.toString() + "xxx") }
}
override fun onMove(id: Int, window: Window, view: View, event: MotionEvent) {
super.onMove(id, window, view, event)
val x = window.layoutParams.x
val width = mSettings!!.screenWidth
val layout = window.findViewById<View>(R.id.content)
val alpha = ((width - Math.abs(x) * 1.2) / width).toFloat()
layout.alpha = alpha
when (event.action) {
MotionEvent.ACTION_UP -> if (alpha < 0.6) {
hide(id)
} else {
reset(id)
layout.alpha = 1.0f
}
}
}
fun reset(id: Int) {
val window = getWindow(id)
mWindowManager!!.updateViewLayout(window, getParams(id, window))
}
override fun getParams(id: Int, window: Window): StandOutLayoutParams {
val params = StandOutLayoutParams(id, mSettings!!.screenWidth,
mSettings!!.windowHeight, StandOutLayoutParams.CENTER,
StandOutLayoutParams.CENTER)
val x = mSettings!!.windowX
val y = mSettings!!.windowY
if (x != -1 && y != -1) {
params.x = x
params.y = y
}
params.y = (mSettings!!.defaultHeight * 1.5).toInt()
params.minWidth = mSettings!!.screenWidth
params.maxWidth = Math.max(mSettings!!.screenWidth, mSettings!!.screenHeight)
params.minHeight = mSettings!!.defaultHeight * 2
params.height = mSettings!!.defaultHeight * 5
return params
}
override fun getFlags(id: Int): Int {
return (StandOutFlags.FLAG_BODY_MOVE_ENABLE
or StandOutFlags.FLAG_WINDOW_FOCUS_INDICATOR_DISABLE)
}
override fun getThemeStyle(): Int {
return R.style.AppTheme
}
override fun isDisableMove(id: Int): Boolean {
return false
}
companion object {
private val TAG = MarkWindow::class.java.simpleName
}
} | gpl-3.0 | 5183246e5dd60911f4519f6459053de9 | 34.140625 | 118 | 0.66133 | 4.238454 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/tumui/lectures/adapter/LectureAppointmentsListAdapter.kt | 1 | 3751 | package de.tum.`in`.tumcampusapp.component.tumui.lectures.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.component.tumui.lectures.activity.LecturesAppointmentsActivity
import de.tum.`in`.tumcampusapp.component.tumui.lectures.model.LectureAppointment
import de.tum.`in`.tumcampusapp.utils.DateTimeUtils
import de.tum.`in`.tumcampusapp.utils.Utils
import org.joda.time.format.DateTimeFormat
/**
* Generates the output of the ListView on the [LecturesAppointmentsActivity] activity.
*/
class LectureAppointmentsListAdapter(
context: Context, // list of Appointments to one lecture
private val appointmentList: List<LectureAppointment>
) : BaseAdapter() {
private val inflater: LayoutInflater = LayoutInflater.from(context)
// date formats for the day output
private val endHoursOutput = DateTimeFormat.mediumTime()
private val startDateOutput = DateTimeFormat.mediumDateTime()
private val endDateOutput = DateTimeFormat.mediumDateTime()
override fun getCount() = appointmentList.size
override fun getItem(position: Int) = appointmentList[position]
override fun getItemId(position: Int) = position.toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val holder: ViewHolder
val view: View
if (convertView == null) {
view = inflater.inflate(R.layout.activity_lecturesappointments_listview, parent, false)
// save UI elements in view holder
holder = ViewHolder()
holder.appointmentTime = view.findViewById(R.id.tvTerminZeit)
holder.appointmentLocation = view.findViewById(R.id.tvTerminOrt)
holder.appointmentDetails = view.findViewById(R.id.tvTerminBetreff)
view.tag = holder
} else {
view = convertView
holder = view.tag as ViewHolder
}
val lvItem = appointmentList[position]
holder.appointmentLocation?.text = lvItem.location
holder.appointmentDetails?.text = getAppointmentDetails(lvItem)
holder.appointmentTime?.text = Utils.fromHtml(getAppointmentTime(lvItem))
return view
}
private fun getAppointmentTime(lvItem: LectureAppointment): String {
val start = lvItem.startTime
val end = lvItem.endTime
// output if same day: we only show the date once
val output = StringBuilder()
if (DateTimeUtils.isSameDay(start, end)) {
output.append(startDateOutput.print(start))
.append("–")
.append(endHoursOutput.print(end))
} else {
// show it normally
output.append(startDateOutput.print(start))
.append("–")
.append(endDateOutput.print(end))
}
// grey it, if in past
if (start.isBeforeNow) {
output.insert(0, "<font color=\"#444444\">")
output.append("</font>")
}
return output.toString()
}
private fun getAppointmentDetails(lvItem: LectureAppointment): String {
val details = StringBuilder(lvItem.type ?: "")
val title = lvItem.title
if (title != null && title.isNotEmpty()) {
details.append(" - ").append(lvItem.title)
}
return details.toString()
}
// the layout
internal class ViewHolder {
var appointmentDetails: TextView? = null
var appointmentLocation: TextView? = null
var appointmentTime: TextView? = null
}
}
| gpl-3.0 | 260e2fd57641e21864c2a9d5b2e2b6d0 | 35.028846 | 99 | 0.668001 | 4.614532 | false | false | false | false |
naosim/RPGSample | rpglib/src/main/kotlin/com/naosim/rpglib/model/script/ScriptSet.kt | 1 | 863 | package com.naosim.rpglib.model.script
class ScriptSet(val messageScriptList: Array<MessageScript>, val onEnd: () -> Unit)
class ScriptSetBuilder {
var messageScriptList: Array<MessageScript> = emptyArray()
private set
private var onEnd :() -> Unit = {}
private set
fun messageScript(vararg messageScriptList: MessageScript): ScriptSetBuilder {
this.messageScriptList = this.messageScriptList.plus(messageScriptList)
return this
}
fun messageScriptList(messageScriptList: Array<MessageScript>): ScriptSetBuilder {
this.messageScriptList = this.messageScriptList.plus(messageScriptList)
return this
}
fun onEnd(onEnd: () -> Unit): ScriptSetBuilder {
this.onEnd = onEnd
return this
}
fun build(): ScriptSet {
return ScriptSet(messageScriptList, onEnd)
}
} | mit | 1d223e6d534bf2249fc90f6c42c35caa | 28.793103 | 86 | 0.696408 | 4.315 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/domain/progress/interactor/LocalProgressInteractor.kt | 1 | 3592 | package org.stepik.android.domain.progress.interactor
import io.reactivex.Completable
import io.reactivex.Single
import io.reactivex.rxkotlin.Singles.zip
import io.reactivex.rxkotlin.toObservable
import io.reactivex.subjects.PublishSubject
import ru.nobird.android.core.model.PagedList
import org.stepik.android.domain.assignment.repository.AssignmentRepository
import org.stepik.android.domain.course.repository.CourseRepository
import org.stepik.android.domain.progress.mapper.getProgresses
import org.stepik.android.domain.progress.repository.ProgressRepository
import org.stepik.android.domain.section.repository.SectionRepository
import org.stepik.android.domain.step.repository.StepRepository
import org.stepik.android.domain.unit.repository.UnitRepository
import org.stepik.android.model.Assignment
import org.stepik.android.model.Course
import org.stepik.android.model.Progress
import org.stepik.android.model.Section
import org.stepik.android.model.Step
import org.stepik.android.model.Unit
import javax.inject.Inject
class LocalProgressInteractor
@Inject
constructor(
private val progressRepository: ProgressRepository,
private val assignmentRepository: AssignmentRepository,
private val stepRepository: StepRepository,
private val unitRepository: UnitRepository,
private val sectionRepository: SectionRepository,
private val courseRepository: CourseRepository,
private val progressesPublisher: PublishSubject<Progress>
) {
fun updateStepsProgress(vararg stepIds: Long): Completable =
stepRepository
.getSteps(*stepIds)
.flatMapCompletable(::updateStepsProgress)
fun updateStepsProgress(steps: List<Step>): Completable =
getUnits(steps)
.flatMap { units ->
zip(getSections(units), getAssignments(steps, units))
.flatMap { (sections, assignments) ->
getCourses(sections)
.map { courses ->
assignments.getProgresses() + steps.getProgresses() + units.getProgresses() + sections.getProgresses() + courses.getProgresses()
}
}
}
.flatMap { progressIds ->
progressRepository
.getProgresses(progressIds)
}
.doOnSuccess { progresses ->
progresses.forEach(progressesPublisher::onNext)
}
.ignoreElement()
private fun getAssignments(steps: List<Step>, units: List<Unit>): Single<List<Assignment>> =
assignmentRepository
.getAssignments(units.mapNotNull(Unit::assignments).flatten().distinct())
.map { assignments ->
assignments
.filter { assignment ->
steps.any { it.id == assignment.step }
}
}
private fun getUnits(steps: List<Step>): Single<List<Unit>> =
steps
.map(Step::lesson)
.distinct()
.toObservable()
.flatMapSingle { lessonId ->
unitRepository
.getUnitsByLessonId(lessonId)
}
.reduce(emptyList()) { a, b -> a + b }
private fun getSections(units: List<Unit>): Single<List<Section>> =
sectionRepository
.getSections(units.map(Unit::section).distinct())
private fun getCourses(sections: List<Section>): Single<PagedList<Course>> =
courseRepository
.getCourses(sections.map(Section::course).distinct())
} | apache-2.0 | cb569e49f9201512214dce5556cb6049 | 39.370787 | 160 | 0.660078 | 5.01676 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepic/droid/model/code/ProgrammingLanguage.kt | 2 | 7745 | @file:Suppress("DEPRECATION")
package org.stepic.droid.model.code
import android.content.Context
import android.os.Parcel
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import org.stepic.droid.R
@Deprecated("Use string literal instead. This class is only for knowledge what programming languages are existed")
enum class ProgrammingLanguage(val serverPrintableName: String) : Parcelable {
@SerializedName("python3")
PYTHON("python3"),
@SerializedName("c++11")
CPP11("c++11"),
@SerializedName("c++")
CPP("c++"),
@SerializedName("c")
C("c"),
@SerializedName("haskell")
HASKELL("haskell"),
@SerializedName("haskell 7.10")
HASKELL7("haskell 7.10"),
@SerializedName("haskell 8.0")
HASKELL8("haskell 8.0"),
@SerializedName("java")
JAVA("java"),
@SerializedName("java8")
JAVA8("java8"),
@SerializedName("octave")
OCTAVE("octave"),
@SerializedName("asm32")
ASM32("asm32"),
@SerializedName("asm64")
ASM64("asm64"),
@SerializedName("shell")
SHELL("shell"),
@SerializedName("rust")
RUST("rust"),
@SerializedName("r")
R("r"),
@SerializedName("ruby")
RUBY("ruby"),
@SerializedName("clojure")
CLOJURE("clojure"),
@SerializedName("mono c#")
CS("mono c#"),
@SerializedName("javascript")
JAVASCRIPT("javascript"),
@SerializedName("scala")
SCALA("scala"),
@SerializedName("kotlin")
KOTLIN("kotlin"),
@SerializedName("go")
GO("go"),
@SerializedName("pascalabc")
PASCAL("pascalabc"),
@SerializedName("perl")
PERL("perl"),
SQL("sql");
override fun describeContents(): Int = 0
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(ordinal)
}
companion object CREATOR : Parcelable.Creator<ProgrammingLanguage> {
override fun createFromParcel(parcel: Parcel): ProgrammingLanguage =
ProgrammingLanguage.values()[parcel.readInt()]
override fun newArray(size: Int): Array<ProgrammingLanguage?> = arrayOfNulls(size)
//make it public and resolve highlighting
@Suppress("unused")
private fun highlighting(serverName: String) {
val language = serverNameToLanguage(serverName)
when (language) {
ProgrammingLanguage.PYTHON -> TODO()
ProgrammingLanguage.CPP11 -> TODO()
ProgrammingLanguage.CPP -> TODO()
ProgrammingLanguage.C -> TODO()
ProgrammingLanguage.HASKELL -> TODO()
ProgrammingLanguage.HASKELL7 -> TODO()
ProgrammingLanguage.HASKELL8 -> TODO()
ProgrammingLanguage.JAVA -> TODO()
ProgrammingLanguage.JAVA8 -> TODO()
ProgrammingLanguage.OCTAVE -> TODO()
ProgrammingLanguage.ASM32 -> TODO()
ProgrammingLanguage.ASM64 -> TODO()
ProgrammingLanguage.SHELL -> TODO()
ProgrammingLanguage.RUST -> TODO()
ProgrammingLanguage.R -> TODO()
ProgrammingLanguage.RUBY -> TODO()
ProgrammingLanguage.CLOJURE -> TODO()
ProgrammingLanguage.CS -> TODO()
ProgrammingLanguage.JAVASCRIPT -> TODO()
ProgrammingLanguage.SCALA -> TODO()
ProgrammingLanguage.KOTLIN -> TODO()
ProgrammingLanguage.GO -> TODO()
ProgrammingLanguage.PASCAL -> TODO()
ProgrammingLanguage.PERL -> TODO()
ProgrammingLanguage.SQL -> TODO()
null -> TODO()
}
}
}
}
private fun serverNameToLanguage(serverName: String): ProgrammingLanguage? {
return ProgrammingLanguage.values()
.find {
it.serverPrintableName.equals(serverName, ignoreCase = true)
}
}
fun symbolsForLanguage(lang: String, context: Context): Array<String> {
val programmingLanguage = serverNameToLanguage(lang)
with(context.resources) {
return when (programmingLanguage) {
ProgrammingLanguage.PYTHON ->
getStringArray(R.array.frequent_symbols_py)
ProgrammingLanguage.CPP11, ProgrammingLanguage.CPP, ProgrammingLanguage.C ->
getStringArray(R.array.frequent_symbols_cpp)
ProgrammingLanguage.HASKELL, ProgrammingLanguage.HASKELL7, ProgrammingLanguage.HASKELL8 ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.JAVA, ProgrammingLanguage.JAVA8 ->
getStringArray(R.array.frequent_symbols_java)
ProgrammingLanguage.OCTAVE ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.ASM32, ProgrammingLanguage.ASM64 ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.SHELL ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.RUST ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.R ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.RUBY ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.CLOJURE ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.CS ->
getStringArray(R.array.frequent_symbols_cs)
ProgrammingLanguage.JAVASCRIPT ->
getStringArray(R.array.frequent_symbols_js)
ProgrammingLanguage.SCALA ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.KOTLIN ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.GO ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.PASCAL ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.PERL ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.SQL ->
getStringArray(R.array.frequent_symbols_sql)
null ->
getStringArray(R.array.frequent_symbols_default)
}
}
}
fun extensionForLanguage(lang: String) : String =
when (serverNameToLanguage(lang)) {
ProgrammingLanguage.PYTHON -> "py"
ProgrammingLanguage.CPP11,
ProgrammingLanguage.CPP,
ProgrammingLanguage.C -> "cpp"
ProgrammingLanguage.HASKELL,
ProgrammingLanguage.HASKELL7,
ProgrammingLanguage.HASKELL8 -> "hs"
ProgrammingLanguage.JAVA,
ProgrammingLanguage.JAVA8 -> "java"
ProgrammingLanguage.OCTAVE -> "matlab"
ProgrammingLanguage.ASM32,
ProgrammingLanguage.ASM64 -> "asm"
ProgrammingLanguage.SHELL -> "sh"
ProgrammingLanguage.RUST -> "rust"
ProgrammingLanguage.R -> "r"
ProgrammingLanguage.RUBY -> "rb"
ProgrammingLanguage.CLOJURE -> "clj"
ProgrammingLanguage.CS -> "cs"
ProgrammingLanguage.JAVASCRIPT -> "js"
ProgrammingLanguage.SCALA -> "scala"
ProgrammingLanguage.KOTLIN -> "kt"
ProgrammingLanguage.GO -> "go"
ProgrammingLanguage.PASCAL -> "pascal"
ProgrammingLanguage.PERL -> "perl"
ProgrammingLanguage.SQL -> "sql"
null -> ""
} | apache-2.0 | 97024b8087e5c3e5dd0fe33958b16d71 | 37.537313 | 114 | 0.602324 | 4.745711 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/cache/course_collection/dao/CourseCollectionDaoImpl.kt | 2 | 3073 | package org.stepik.android.cache.course_collection.dao
import android.content.ContentValues
import android.database.Cursor
import org.stepic.droid.storage.dao.DaoBase
import org.stepic.droid.storage.operations.DatabaseOperations
import org.stepic.droid.util.DbParseHelper
import org.stepic.droid.util.getInt
import org.stepic.droid.util.getLong
import org.stepic.droid.util.getString
import org.stepik.android.cache.course_collection.structure.DbStructureCourseCollection
import org.stepik.android.model.CourseCollection
import javax.inject.Inject
class CourseCollectionDaoImpl
@Inject
constructor(databaseOperations: DatabaseOperations) : DaoBase<CourseCollection>(databaseOperations) {
override fun getDefaultPrimaryColumn(): String =
DbStructureCourseCollection.Columns.ID
override fun getDbName(): String =
DbStructureCourseCollection.TABLE_NAME
override fun getDefaultPrimaryValue(persistentObject: CourseCollection): String =
persistentObject.id.toString()
override fun getContentValues(persistentObject: CourseCollection): ContentValues =
ContentValues(9)
.apply {
put(DbStructureCourseCollection.Columns.ID, persistentObject.id)
put(DbStructureCourseCollection.Columns.POSITION, persistentObject.position)
put(DbStructureCourseCollection.Columns.TITLE, persistentObject.title)
put(DbStructureCourseCollection.Columns.LANGUAGE, persistentObject.language)
put(DbStructureCourseCollection.Columns.COURSES, DbParseHelper.parseLongListToString(persistentObject.courses))
put(DbStructureCourseCollection.Columns.DESCRIPTION, persistentObject.description)
put(DbStructureCourseCollection.Columns.PLATFORM, persistentObject.platform)
put(DbStructureCourseCollection.Columns.SIMILAR_AUTHORS, DbParseHelper.parseLongListToString(persistentObject.similarAuthors))
put(DbStructureCourseCollection.Columns.SIMILAR_COURSE_LISTS, DbParseHelper.parseLongListToString(persistentObject.similarCourseLists))
}
override fun parsePersistentObject(cursor: Cursor): CourseCollection =
CourseCollection(
cursor.getLong(DbStructureCourseCollection.Columns.ID),
cursor.getInt(DbStructureCourseCollection.Columns.POSITION),
cursor.getString(DbStructureCourseCollection.Columns.TITLE)!!,
cursor.getString(DbStructureCourseCollection.Columns.LANGUAGE)!!,
DbParseHelper.parseStringToLongList(cursor.getString(DbStructureCourseCollection.Columns.COURSES)) ?: listOf(),
cursor.getString(DbStructureCourseCollection.Columns.DESCRIPTION)!!,
cursor.getInt(DbStructureCourseCollection.Columns.PLATFORM),
DbParseHelper.parseStringToLongList(cursor.getString(DbStructureCourseCollection.Columns.SIMILAR_AUTHORS)) ?: listOf(),
DbParseHelper.parseStringToLongList(cursor.getString(DbStructureCourseCollection.Columns.SIMILAR_COURSE_LISTS)) ?: listOf()
)
} | apache-2.0 | ff288081d96f40c82c62b462d636422f | 57 | 151 | 0.772535 | 5.546931 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadStore.kt | 2 | 3973 | package eu.kanade.tachiyomi.data.download
import android.content.Context
import com.google.gson.Gson
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.download.model.Download
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.source.online.HttpSource
import uy.kohesive.injekt.injectLazy
/**
* This class is used to persist active downloads across application restarts.
*
* @param context the application context.
*/
class DownloadStore(
context: Context,
private val sourceManager: SourceManager
) {
/**
* Preference file where active downloads are stored.
*/
private val preferences = context.getSharedPreferences("active_downloads", Context.MODE_PRIVATE)
/**
* Gson instance to serialize/deserialize downloads.
*/
private val gson: Gson by injectLazy()
/**
* Database helper.
*/
private val db: DatabaseHelper by injectLazy()
/**
* Counter used to keep the queue order.
*/
private var counter = 0
/**
* Adds a list of downloads to the store.
*
* @param downloads the list of downloads to add.
*/
fun addAll(downloads: List<Download>) {
val editor = preferences.edit()
downloads.forEach { editor.putString(getKey(it), serialize(it)) }
editor.apply()
}
/**
* Removes a download from the store.
*
* @param download the download to remove.
*/
fun remove(download: Download) {
preferences.edit().remove(getKey(download)).apply()
}
/**
* Removes all the downloads from the store.
*/
fun clear() {
preferences.edit().clear().apply()
}
/**
* Returns the preference's key for the given download.
*
* @param download the download.
*/
private fun getKey(download: Download): String {
return download.chapter.id!!.toString()
}
/**
* Returns the list of downloads to restore. It should be called in a background thread.
*/
fun restore(): List<Download> {
val objs = preferences.all
.mapNotNull { it.value as? String }
.mapNotNull { deserialize(it) }
.sortedBy { it.order }
val downloads = mutableListOf<Download>()
if (objs.isNotEmpty()) {
val cachedManga = mutableMapOf<Long, Manga?>()
for ((mangaId, chapterId) in objs) {
val manga = cachedManga.getOrPut(mangaId) {
db.getManga(mangaId).executeAsBlocking()
} ?: continue
val source = sourceManager.get(manga.source) as? HttpSource ?: continue
val chapter = db.getChapter(chapterId).executeAsBlocking() ?: continue
downloads.add(Download(source, manga, chapter))
}
}
// Clear the store, downloads will be added again immediately.
clear()
return downloads
}
/**
* Converts a download to a string.
*
* @param download the download to serialize.
*/
private fun serialize(download: Download): String {
val obj = DownloadObject(download.manga.id!!, download.chapter.id!!, counter++)
return gson.toJson(obj)
}
/**
* Restore a download from a string.
*
* @param string the download as string.
*/
private fun deserialize(string: String): DownloadObject? {
return try {
gson.fromJson(string, DownloadObject::class.java)
} catch (e: Exception) {
null
}
}
/**
* Class used for download serialization
*
* @param mangaId the id of the manga.
* @param chapterId the id of the chapter.
* @param order the order of the download in the queue.
*/
data class DownloadObject(val mangaId: Long, val chapterId: Long, val order: Int)
}
| apache-2.0 | 13c0b4cd828dd8c9a8f54e4cc16c33a1 | 28 | 100 | 0.616159 | 4.625146 | false | false | false | false |
google/filament | android/samples/sample-texture-view/src/main/java/com/google/android/filament/textureview/MainActivity.kt | 1 | 13002 | /*
* Copyright (C) 2018 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.google.android.filament.textureview
import android.animation.ValueAnimator
import android.app.Activity
import android.opengl.Matrix
import android.os.Bundle
import android.view.Choreographer
import android.view.Surface
import android.view.TextureView
import android.view.animation.LinearInterpolator
import com.google.android.filament.*
import com.google.android.filament.RenderableManager.PrimitiveType
import com.google.android.filament.VertexBuffer.AttributeType
import com.google.android.filament.VertexBuffer.VertexAttribute
import com.google.android.filament.android.DisplayHelper
import com.google.android.filament.android.UiHelper
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.channels.Channels
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.sin
class MainActivity : Activity() {
// Make sure to initialize Filament first
// This loads the JNI library needed by most API calls
companion object {
init {
Filament.init()
}
}
// The View we want to render into
private lateinit var textureView: TextureView
// UiHelper is provided by Filament to manage SurfaceView and SurfaceTexture
private lateinit var uiHelper: UiHelper
// DisplayHelper is provided by Filament to manage the display
private lateinit var displayHelper: DisplayHelper
// Choreographer is used to schedule new frames
private lateinit var choreographer: Choreographer
// Engine creates and destroys Filament resources
// Each engine must be accessed from a single thread of your choosing
// Resources cannot be shared across engines
private lateinit var engine: Engine
// A renderer instance is tied to a single surface (SurfaceView, TextureView, etc.)
private lateinit var renderer: Renderer
// A scene holds all the renderable, lights, etc. to be drawn
private lateinit var scene: Scene
// A view defines a viewport, a scene and a camera for rendering
private lateinit var view: View
// Should be pretty obvious :)
private lateinit var camera: Camera
private lateinit var material: Material
private lateinit var vertexBuffer: VertexBuffer
private lateinit var indexBuffer: IndexBuffer
// Filament entity representing a renderable object
@Entity private var renderable = 0
// A swap chain is Filament's representation of a surface
private var swapChain: SwapChain? = null
// Performs the rendering and schedules new frames
private val frameScheduler = FrameCallback()
private val animator = ValueAnimator.ofFloat(0.0f, 360.0f)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
textureView = TextureView(this)
setContentView(textureView)
choreographer = Choreographer.getInstance()
displayHelper = DisplayHelper(this)
setupSurfaceView()
setupFilament()
setupView()
setupScene()
}
private fun setupSurfaceView() {
uiHelper = UiHelper(UiHelper.ContextErrorPolicy.DONT_CHECK)
uiHelper.renderCallback = SurfaceCallback()
// NOTE: To choose a specific rendering resolution, add the following line:
// uiHelper.setDesiredSize(1280, 720)
uiHelper.attachTo(textureView)
}
private fun setupFilament() {
engine = Engine.create()
renderer = engine.createRenderer()
scene = engine.createScene()
view = engine.createView()
camera = engine.createCamera(engine.entityManager.create())
}
private fun setupView() {
scene.skybox = Skybox.Builder().color(0.035f, 0.035f, 0.035f, 1.0f).build(engine)
// NOTE: Try to disable post-processing (tone-mapping, etc.) to see the difference
// view.isPostProcessingEnabled = false
// Tell the view which camera we want to use
view.camera = camera
// Tell the view which scene we want to render
view.scene = scene
}
private fun setupScene() {
loadMaterial()
createMesh()
// To create a renderable we first create a generic entity
renderable = EntityManager.get().create()
// We then create a renderable component on that entity
// A renderable is made of several primitives; in this case we declare only 1
RenderableManager.Builder(1)
// Overall bounding box of the renderable
.boundingBox(Box(0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.01f))
// Sets the mesh data of the first primitive
.geometry(0, PrimitiveType.TRIANGLES, vertexBuffer, indexBuffer, 0, 3)
// Sets the material of the first primitive
.material(0, material.defaultInstance)
.build(engine, renderable)
// Add the entity to the scene to render it
scene.addEntity(renderable)
startAnimation()
}
private fun loadMaterial() {
readUncompressedAsset("materials/baked_color.filamat").let {
material = Material.Builder().payload(it, it.remaining()).build(engine)
}
}
private fun createMesh() {
val intSize = 4
val floatSize = 4
val shortSize = 2
// A vertex is a position + a color:
// 3 floats for XYZ position, 1 integer for color
val vertexSize = 3 * floatSize + intSize
// Define a vertex and a function to put a vertex in a ByteBuffer
data class Vertex(val x: Float, val y: Float, val z: Float, val color: Int)
fun ByteBuffer.put(v: Vertex): ByteBuffer {
putFloat(v.x)
putFloat(v.y)
putFloat(v.z)
putInt(v.color)
return this
}
// We are going to generate a single triangle
val vertexCount = 3
val a1 = PI * 2.0 / 3.0
val a2 = PI * 4.0 / 3.0
val vertexData = ByteBuffer.allocate(vertexCount * vertexSize)
// It is important to respect the native byte order
.order(ByteOrder.nativeOrder())
.put(Vertex(1.0f, 0.0f, 0.0f, 0xffff0000.toInt()))
.put(Vertex(cos(a1).toFloat(), sin(a1).toFloat(), 0.0f, 0xff00ff00.toInt()))
.put(Vertex(cos(a2).toFloat(), sin(a2).toFloat(), 0.0f, 0xff0000ff.toInt()))
// Make sure the cursor is pointing in the right place in the byte buffer
.flip()
// Declare the layout of our mesh
vertexBuffer = VertexBuffer.Builder()
.bufferCount(1)
.vertexCount(vertexCount)
// Because we interleave position and color data we must specify offset and stride
// We could use de-interleaved data by declaring two buffers and giving each
// attribute a different buffer index
.attribute(VertexAttribute.POSITION, 0, AttributeType.FLOAT3, 0, vertexSize)
.attribute(VertexAttribute.COLOR, 0, AttributeType.UBYTE4, 3 * floatSize, vertexSize)
// We store colors as unsigned bytes but since we want values between 0 and 1
// in the material (shaders), we must mark the attribute as normalized
.normalized(VertexAttribute.COLOR)
.build(engine)
// Feed the vertex data to the mesh
// We only set 1 buffer because the data is interleaved
vertexBuffer.setBufferAt(engine, 0, vertexData)
// Create the indices
val indexData = ByteBuffer.allocate(vertexCount * shortSize)
.order(ByteOrder.nativeOrder())
.putShort(0)
.putShort(1)
.putShort(2)
.flip()
indexBuffer = IndexBuffer.Builder()
.indexCount(3)
.bufferType(IndexBuffer.Builder.IndexType.USHORT)
.build(engine)
indexBuffer.setBuffer(engine, indexData)
}
private fun startAnimation() {
// Animate the triangle
animator.interpolator = LinearInterpolator()
animator.duration = 4000
animator.repeatMode = ValueAnimator.RESTART
animator.repeatCount = ValueAnimator.INFINITE
animator.addUpdateListener(object : ValueAnimator.AnimatorUpdateListener {
val transformMatrix = FloatArray(16)
override fun onAnimationUpdate(a: ValueAnimator) {
Matrix.setRotateM(transformMatrix, 0, -(a.animatedValue as Float), 0.0f, 0.0f, 1.0f)
val tcm = engine.transformManager
tcm.setTransform(tcm.getInstance(renderable), transformMatrix)
}
})
animator.start()
}
override fun onResume() {
super.onResume()
choreographer.postFrameCallback(frameScheduler)
animator.start()
}
override fun onPause() {
super.onPause()
choreographer.removeFrameCallback(frameScheduler)
animator.cancel()
}
override fun onDestroy() {
super.onDestroy()
// Stop the animation and any pending frame
choreographer.removeFrameCallback(frameScheduler)
animator.cancel();
// Always detach the surface before destroying the engine
uiHelper.detach()
// Cleanup all resources
engine.destroyEntity(renderable)
engine.destroyRenderer(renderer)
engine.destroyVertexBuffer(vertexBuffer)
engine.destroyIndexBuffer(indexBuffer)
engine.destroyMaterial(material)
engine.destroyView(view)
engine.destroyScene(scene)
engine.destroyCameraComponent(camera.entity)
// Engine.destroyEntity() destroys Filament related resources only
// (components), not the entity itself
val entityManager = EntityManager.get()
entityManager.destroy(renderable)
entityManager.destroy(camera.entity)
// Destroying the engine will free up any resource you may have forgotten
// to destroy, but it's recommended to do the cleanup properly
engine.destroy()
}
inner class FrameCallback : Choreographer.FrameCallback {
override fun doFrame(frameTimeNanos: Long) {
// Schedule the next frame
choreographer.postFrameCallback(this)
// This check guarantees that we have a swap chain
if (uiHelper.isReadyToRender) {
// If beginFrame() returns false you should skip the frame
// This means you are sending frames too quickly to the GPU
if (renderer.beginFrame(swapChain!!, frameTimeNanos)) {
renderer.render(view)
renderer.endFrame()
}
}
}
}
inner class SurfaceCallback : UiHelper.RendererCallback {
override fun onNativeWindowChanged(surface: Surface) {
swapChain?.let { engine.destroySwapChain(it) }
swapChain = engine.createSwapChain(surface, uiHelper.swapChainFlags)
displayHelper.attach(renderer, textureView.display)
}
override fun onDetachedFromSurface() {
displayHelper.detach()
swapChain?.let {
engine.destroySwapChain(it)
// Required to ensure we don't return before Filament is done executing the
// destroySwapChain command, otherwise Android might destroy the Surface
// too early
engine.flushAndWait()
swapChain = null
}
}
override fun onResized(width: Int, height: Int) {
val zoom = 1.5
val aspect = width.toDouble() / height.toDouble()
camera.setProjection(Camera.Projection.ORTHO,
-aspect * zoom, aspect * zoom, -zoom, zoom, 0.0, 10.0)
view.viewport = Viewport(0, 0, width, height)
}
}
private fun readUncompressedAsset(assetName: String): ByteBuffer {
assets.openFd(assetName).use { fd ->
val input = fd.createInputStream()
val dst = ByteBuffer.allocate(fd.length.toInt())
val src = Channels.newChannel(input)
src.read(dst)
src.close()
return dst.apply { rewind() }
}
}
}
| apache-2.0 | 480f07076522423f18199524746a7ad8 | 36.686957 | 104 | 0.640671 | 4.95692 | false | false | false | false |
jdiazcano/modulartd | editor/core/src/main/kotlin/com/jdiazcano/modulartd/ui/widgets/AnimatedButton.kt | 1 | 2772 | package com.jdiazcano.modulartd.ui.widgets
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.InputListener
import com.badlogic.gdx.scenes.scene2d.ui.Button
import com.jdiazcano.modulartd.beans.MapObject
import com.jdiazcano.modulartd.beans.Resource
import com.jdiazcano.modulartd.ui.AnimatedActor
import com.kotcrab.vis.ui.Focusable
import com.kotcrab.vis.ui.VisUI
import com.kotcrab.vis.ui.widget.VisImageButton
class AnimatedButton(mapObject: MapObject = MapObject.EMPTY) : Button(), Focusable {
private lateinit var style: VisImageButton.VisImageButtonStyle
var mapObject: MapObject = mapObject
set(value) {
field = value
actor.rotation = value.rotationAngle
actor.swapResource(value.resource)
}
private var drawBorder: Boolean = false
val actor = AnimatedActor(mapObject.resource)
init {
setStyle(VisImageButton.VisImageButtonStyle(VisUI.getSkin().get(VisImageButton.VisImageButtonStyle::class.java)))
add(actor).size(50F)
setSize(prefWidth, prefHeight)
addListener(object : InputListener() {
override fun touchDown(event: InputEvent?, x: Float, y: Float, pointer: Int, button: Int): Boolean {
//TODO fix this if (!isDisabled) FocusManager.getFocus(this@AnimatedButton)
return false
}
})
}
override fun setRotation(degrees: Float) {
actor.rotation = degrees
mapObject.rotationAngle = degrees
}
override fun getRotation(): Float {
return actor.rotation
}
var resource: Resource
get() = mapObject.resource
set(value) {
actor.swapResource(value)
mapObject.resource = value
}
var animationTimer: Float
get() = actor.spriteTimer
set(value) {
actor.spriteTimer = value
}
override fun setStyle(style: Button.ButtonStyle) {
if (style !is VisImageButton.VisImageButtonStyle) throw IllegalArgumentException("style must be an ImageButtonStyle.")
super.setStyle(style)
this.style = style
}
override fun getStyle(): VisImageButton.VisImageButtonStyle {
return style
}
override fun draw(batch: Batch, parentAlpha: Float) {
super.draw(batch, parentAlpha)
if (drawBorder) style.focusBorder.draw(batch, x, y, width, height)
}
override fun setDisabled(disabled: Boolean) {
super.setDisabled(disabled)
// TODO Fix this if (disabled) FocusManager.getFocus()
}
override fun focusLost() {
drawBorder = false
}
override fun focusGained() {
drawBorder = true
}
} | apache-2.0 | 301056e72df845f7ba5dc5e048f06496 | 30.157303 | 126 | 0.669913 | 4.5 | false | false | false | false |
Heiner1/AndroidAPS | wear/src/test/java/info/nightscout/androidaps/testing/mocks/SharedPreferencesMock.kt | 1 | 3393 | package info.nightscout.androidaps.testing.mocks
import android.content.SharedPreferences
import android.content.SharedPreferences.OnSharedPreferenceChangeListener
class SharedPreferencesMock : SharedPreferences {
private val editor = EditorInternals()
internal class EditorInternals : SharedPreferences.Editor {
var innerMap: MutableMap<String, Any?> = HashMap()
override fun putString(k: String, v: String?): SharedPreferences.Editor {
innerMap[k] = v
return this
}
override fun putStringSet(k: String, set: Set<String>?): SharedPreferences.Editor {
innerMap[k] = set
return this
}
override fun putInt(k: String, i: Int): SharedPreferences.Editor {
innerMap[k] = i
return this
}
override fun putLong(k: String, l: Long): SharedPreferences.Editor {
innerMap[k] = l
return this
}
override fun putFloat(k: String, v: Float): SharedPreferences.Editor {
innerMap[k] = v
return this
}
override fun putBoolean(k: String, b: Boolean): SharedPreferences.Editor {
innerMap[k] = b
return this
}
override fun remove(k: String): SharedPreferences.Editor {
innerMap.remove(k)
return this
}
override fun clear(): SharedPreferences.Editor {
innerMap.clear()
return this
}
override fun commit(): Boolean {
return true
}
override fun apply() {}
}
override fun getAll(): Map<String, *> {
return editor.innerMap
}
override fun getString(k: String, s: String?): String? {
return if (editor.innerMap.containsKey(k)) {
editor.innerMap[k] as String?
} else {
s
}
}
@Suppress("UNCHECKED_CAST")
override fun getStringSet(k: String, set: Set<String>?): Set<String>? {
return if (editor.innerMap.containsKey(k)) {
editor.innerMap[k] as Set<String>?
} else {
set
}
}
override fun getInt(k: String, i: Int): Int {
return if (editor.innerMap.containsKey(k)) {
editor.innerMap[k] as Int
} else {
i
}
}
override fun getLong(k: String, l: Long): Long {
return if (editor.innerMap.containsKey(k)) {
editor.innerMap[k] as Long
} else {
l
}
}
override fun getFloat(k: String, v: Float): Float {
return if (editor.innerMap.containsKey(k)) {
editor.innerMap[k] as Float
} else {
v
}
}
override fun getBoolean(k: String, b: Boolean): Boolean {
return if (editor.innerMap.containsKey(k)) {
editor.innerMap[k] as Boolean
} else {
b
}
}
override fun contains(k: String): Boolean {
return editor.innerMap.containsKey(k)
}
override fun edit(): SharedPreferences.Editor {
return editor
}
override fun registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener: OnSharedPreferenceChangeListener) {}
override fun unregisterOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener: OnSharedPreferenceChangeListener) {}
} | agpl-3.0 | ad1747d7da3502ca95a6ebbf5f818331 | 26.593496 | 130 | 0.58326 | 4.938865 | false | false | false | false |
slak44/gitforandroid | fslistview/src/main/java/slak/fslistview/FSArrayAdapter.kt | 1 | 1147 | package slak.fslistview
import android.content.Context
import android.support.annotation.LayoutRes
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import java.io.File
import java.util.ArrayList
internal class FSArrayAdapter(context: Context,
@LayoutRes resource: Int,
private val nodes: ArrayList<SelectableAdapterModel<File>>,
private val lv: FSListView
) : ArrayAdapter<SelectableAdapterModel<File>>(context, resource, nodes) {
override fun getViewTypeCount(): Int = 2
override fun getItemViewType(position: Int): Int = when (true) {
nodes[position].thing.isDirectory -> 0
nodes[position].thing.isFile -> 1
else -> 1
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val v = lv.onChildViewPrepare(context, nodes[position].thing, convertView, parent)
v.text = nodes[position].thing.name
v.type = when (getItemViewType(position)) {
0 -> FSItemType.FOLDER
1 -> FSItemType.FILE
else -> FSItemType.NONE
}
return v
}
}
| mit | af226ae932afdc6f9d7e889eb4d92d9f | 31.771429 | 89 | 0.679163 | 4.411538 | false | false | false | false |
Heiner1/AndroidAPS | medtronic/src/test/java/info/nightscout/androidaps/TestBase.kt | 1 | 4451 | package info.nightscout.androidaps
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil
import info.nightscout.androidaps.plugins.pump.common.sync.PumpSyncStorage
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.MedtronicPumpHistoryDecoder
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntryType
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import info.nightscout.shared.sharedPreferences.SP
import org.junit.Before
import org.junit.Rule
import org.mockito.Answers
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import java.util.*
open class TestBase {
val aapsLogger = AAPSLoggerTest()
val aapsSchedulers: AapsSchedulers = TestAapsSchedulers()
var rxBus: RxBus = RxBus(TestAapsSchedulers(), aapsLogger)
var byteUtil = ByteUtil()
var rileyLinkUtil = RileyLinkUtil()
@Mock lateinit var pumpSync: PumpSync
@Mock lateinit var pumpSyncStorage: PumpSyncStorage
@Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var activePlugin: ActivePlugin
@Mock lateinit var sp: SP
@Mock lateinit var rh: ResourceHelper
lateinit var medtronicUtil : MedtronicUtil
lateinit var decoder : MedtronicPumpHistoryDecoder
val packetInjector = HasAndroidInjector {
AndroidInjector {
}
}
// Add a JUnit rule that will setup the @Mock annotated vars and log.
// Another possibility would be to add `MockitoAnnotations.initMocks(this) to the setup method.
@get:Rule
val mockitoRule: MockitoRule = MockitoJUnit.rule()
@Before
fun setupLocale() {
Locale.setDefault(Locale.ENGLISH)
System.setProperty("disableFirebase", "true")
}
// Workaround for Kotlin nullability.
// https://medium.com/@elye.project/befriending-kotlin-and-mockito-1c2e7b0ef791
// https://stackoverflow.com/questions/30305217/is-it-possible-to-use-mockito-in-kotlin
fun <T> anyObject(): T {
Mockito.any<T>()
return uninitialized()
}
fun preProcessListTBR(inputList: MutableList<PumpHistoryEntry>) {
var tbrs: MutableList<PumpHistoryEntry> = mutableListOf()
for (pumpHistoryEntry in inputList) {
if (pumpHistoryEntry.entryType === PumpHistoryEntryType.TempBasalRate ||
pumpHistoryEntry.entryType === PumpHistoryEntryType.TempBasalDuration) {
tbrs.add(pumpHistoryEntry)
}
}
inputList.removeAll(tbrs)
inputList.addAll(preProcessTBRs(tbrs))
sort(inputList)
//return inputList
}
private fun preProcessTBRs(TBRs_Input: MutableList<PumpHistoryEntry>): MutableList<PumpHistoryEntry> {
val tbrs: MutableList<PumpHistoryEntry> = mutableListOf()
val map: MutableMap<String?, PumpHistoryEntry?> = HashMap()
for (pumpHistoryEntry in TBRs_Input) {
if (map.containsKey(pumpHistoryEntry.DT)) {
decoder.decodeTempBasal(map[pumpHistoryEntry.DT]!!, pumpHistoryEntry)
pumpHistoryEntry.setEntryType(medtronicUtil.medtronicPumpModel, PumpHistoryEntryType.TempBasalCombined)
tbrs.add(pumpHistoryEntry)
map.remove(pumpHistoryEntry.DT)
} else {
map[pumpHistoryEntry.DT] = pumpHistoryEntry
}
}
return tbrs
}
private fun sort(list: MutableList<PumpHistoryEntry>) {
// if (list != null && !list.isEmpty()) {
// Collections.sort(list, PumpHistoryEntry.Comparator())
// }
list.sortWith(PumpHistoryEntry.Comparator())
}
@Suppress("Unchecked_Cast")
fun <T> uninitialized(): T = null as T
} | agpl-3.0 | c1cb870e4fdda7e8cff345f418a114d3 | 35.195122 | 119 | 0.728376 | 4.680336 | false | false | false | false |
Maccimo/intellij-community | plugins/ide-features-trainer/src/training/learn/lesson/general/navigation/RecentFilesLesson.kt | 3 | 8785 | // 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 training.learn.lesson.general.navigation
import com.intellij.CommonBundle
import com.intellij.ide.IdeBundle
import com.intellij.ide.actions.Switcher
import com.intellij.ide.actions.ui.JBListWithOpenInRightSplit
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.ui.Messages
import com.intellij.ui.SearchTextField
import com.intellij.ui.SimpleColoredComponent
import com.intellij.ui.components.JBList
import com.intellij.ui.components.fields.ExtendableTextField
import com.intellij.ui.speedSearch.SpeedSearchSupply
import com.intellij.util.ui.UIUtil
import training.FeaturesTrainerIcons
import training.dsl.*
import training.dsl.LessonUtil.restoreIfModifiedOrMoved
import training.learn.LearnBundle
import training.learn.LessonsBundle
import training.learn.course.KLesson
import training.learn.lesson.LessonManager
import training.util.isToStringContains
import java.awt.event.KeyEvent
import javax.swing.JComponent
import javax.swing.JLabel
import kotlin.math.min
abstract class RecentFilesLesson : KLesson("Recent Files and Locations", LessonsBundle.message("recent.files.lesson.name")) {
abstract override val sampleFilePath: String
abstract val transitionMethodName: String
abstract val transitionFileName: String
abstract val stringForRecentFilesSearch: String // should look like transitionMethodName
abstract fun LessonContext.setInitialPosition()
private val countOfFilesToOpen: Int = 20
private val countOfFilesToDelete: Int = 5
override val lessonContent: LessonContext.() -> Unit = {
sdkConfigurationTasks()
setInitialPosition()
task("GotoDeclaration") {
text(LessonsBundle.message("recent.files.first.transition", code(transitionMethodName), action(it)))
stateCheck { virtualFile.name.contains(transitionFileName) }
restoreIfModifiedOrMoved()
test { actions(it) }
}
waitBeforeContinue(500)
prepareRuntimeTask {
if (!TaskTestContext.inTestMode) {
val userDecision = Messages.showOkCancelDialog(
LessonsBundle.message("recent.files.dialog.message"),
LessonsBundle.message("recent.files.dialog.title"),
CommonBundle.message("button.ok"),
LearnBundle.message("learn.stop.lesson"),
FeaturesTrainerIcons.Img.PluginIcon
)
if (userDecision != Messages.OK) {
LessonManager.instance.stopLesson()
}
}
}
openManyFiles()
task("RecentFiles") {
text(LessonsBundle.message("recent.files.show.recent.files", action(it)))
triggerOnRecentFilesShown()
test { actions(it) }
}
task("rfd") {
text(LessonsBundle.message("recent.files.search.typing", code(it)))
triggerUI().component { ui: ExtendableTextField ->
ui.javaClass.name.contains("SpeedSearchBase\$SearchField")
}
stateCheck { checkRecentFilesSearch(it) }
restoreByUi()
test {
ideFrame {
waitComponent(Switcher.SwitcherPanel::class.java)
}
type(it)
}
}
task {
text(LessonsBundle.message("recent.files.search.jump", LessonUtil.rawEnter()))
stateCheck { virtualFile.name == sampleFilePath.substringAfterLast("/") }
restoreState {
!checkRecentFilesSearch("rfd") || previous.ui?.isShowing != true
}
test(waitEditorToBeReady = false) {
invokeActionViaShortcut("ENTER")
}
}
task("RecentFiles") {
text(LessonsBundle.message("recent.files.use.recent.files.again", action(it)))
triggerOnRecentFilesShown()
test { actions(it) }
}
var initialRecentFilesCount = -1
var curRecentFilesCount: Int
task {
text(LessonsBundle.message("recent.files.delete", strong(countOfFilesToDelete.toString()),
LessonUtil.rawKeyStroke(KeyEvent.VK_DELETE)))
triggerUI().component l@{ list: JBListWithOpenInRightSplit<*> ->
if (list != focusOwner) return@l false
if (initialRecentFilesCount == -1) {
initialRecentFilesCount = list.itemsCount
}
curRecentFilesCount = list.itemsCount
initialRecentFilesCount - curRecentFilesCount >= countOfFilesToDelete
}
restoreByUi()
test {
repeat(countOfFilesToDelete) {
invokeActionViaShortcut("DELETE")
}
}
}
task {
text(LessonsBundle.message("recent.files.close.popup", LessonUtil.rawKeyStroke(KeyEvent.VK_ESCAPE)))
stateCheck { previous.ui?.isShowing != true }
test { invokeActionViaShortcut("ESCAPE") }
}
task("RecentLocations") {
text(LessonsBundle.message("recent.files.show.recent.locations", action(it)))
val recentLocationsText = IdeBundle.message("recent.locations.popup.title")
triggerUI().component { ui: SimpleColoredComponent ->
ui.getCharSequence(true) == recentLocationsText
}
test { actions(it) }
}
task(stringForRecentFilesSearch) {
text(LessonsBundle.message("recent.files.locations.search.typing", code(it)))
stateCheck { checkRecentLocationsSearch(it) }
triggerUI().component { _: SearchTextField -> true } // needed in next task to restore if search field closed
restoreByUi()
test {
ideFrame {
waitComponent(JBList::class.java)
}
type(it)
}
}
task {
text(LessonsBundle.message("recent.files.locations.search.jump", LessonUtil.rawEnter()))
triggerAndBorderHighlight().listItem { item ->
item.isToStringContains(transitionFileName)
}
stateCheck { virtualFile.name.contains(transitionFileName) }
restoreState {
!checkRecentLocationsSearch(stringForRecentFilesSearch) || previous.ui?.isShowing != true
}
test {
waitAndUsePreviouslyFoundListItem { it.doubleClick() }
}
}
}
// Should open (countOfFilesToOpen - 1) files
open fun LessonContext.openManyFiles() {
task {
addFutureStep {
val curFile = virtualFile
val task = object : Task.Backgroundable(project, LessonsBundle.message("recent.files.progress.title"), true) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = false
val files = curFile.parent?.children?.filter { it.name != curFile.name }
?: throw IllegalStateException("Not found neighbour files for ${curFile.name}")
for (i in 0 until min(countOfFilesToOpen - 1, files.size)) {
invokeAndWaitIfNeeded(ModalityState.NON_MODAL) {
if (!indicator.isCanceled) {
FileEditorManager.getInstance(project).openFile(files[i], true)
indicator.fraction = (i + 1).toDouble() / (countOfFilesToOpen - 1)
}
}
}
taskInvokeLater { completeStep() }
}
}
ProgressManager.getInstance().run(task)
}
}
}
private fun TaskRuntimeContext.checkRecentFilesSearch(expected: String): Boolean {
val focusOwner = UIUtil.getParentOfType(Switcher.SwitcherPanel::class.java, focusOwner)
return focusOwner != null && checkWordInSearch(expected, focusOwner)
}
private fun TaskRuntimeContext.checkRecentLocationsSearch(expected: String): Boolean {
val focusOwner = focusOwner
return focusOwner is JBList<*> && checkWordInSearch(expected, focusOwner)
}
private fun checkWordInSearch(expected: String, component: JComponent): Boolean {
val supply = SpeedSearchSupply.getSupply(component)
val enteredPrefix = supply?.enteredPrefix ?: return false
return enteredPrefix.equals(expected, ignoreCase = true)
}
private fun TaskContext.triggerOnRecentFilesShown() {
val recentFilesText = IdeBundle.message("title.popup.recent.files")
triggerUI().component { ui: JLabel ->
ui.text == recentFilesText
}
}
override val testScriptProperties: TaskTestContext.TestScriptProperties
get() = TaskTestContext.TestScriptProperties(duration = 20)
override val suitableTips = listOf("recent-locations", "RecentFiles")
override val helpLinks: Map<String, String> get() = mapOf(
Pair(LessonsBundle.message("recent.files.locations.help.link"),
LessonUtil.getHelpLink("navigating-through-the-source-code.html#recent_locations")),
)
} | apache-2.0 | 85376c4dffeb21f81ade8b4622569d52 | 36.228814 | 158 | 0.698463 | 4.813699 | false | true | false | false |
JetBrains/ideavim | src/main/java/com/maddyhome/idea/vim/vimscript/model/functions/handlers/HasFunctionHandler.kt | 1 | 1416 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.vimscript.model.functions.handlers
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.statistic.VimscriptState
import com.maddyhome.idea.vim.vimscript.model.VimLContext
import com.maddyhome.idea.vim.vimscript.model.datatypes.VimDataType
import com.maddyhome.idea.vim.vimscript.model.datatypes.VimInt
import com.maddyhome.idea.vim.vimscript.model.expressions.Expression
import com.maddyhome.idea.vim.vimscript.model.functions.FunctionHandler
object HasFunctionHandler : FunctionHandler() {
override val name = "has"
override val minimumNumberOfArguments = 1
override val maximumNumberOfArguments = 2
private val supportedFeatures = setOf("ide")
override fun doFunction(
argumentValues: List<Expression>,
editor: VimEditor,
context: ExecutionContext,
vimContext: VimLContext,
): VimDataType {
val feature = argumentValues[0].evaluate(editor, context, vimContext).asString()
if (feature == "ide") {
VimscriptState.isIDESpecificConfigurationUsed = true
}
return if (supportedFeatures.contains(feature))
VimInt.ONE
else
VimInt.ZERO
}
}
| mit | 5a3eba48b8c23366e16c37cfcf5fe349 | 32.714286 | 84 | 0.769774 | 4.116279 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/vfilefinder/IdeVirtualFileFinder.kt | 4 | 2214 | // 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.vfilefinder
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.indexing.FileBasedIndex
import com.intellij.util.indexing.ID
import org.jetbrains.kotlin.load.kotlin.VirtualFileFinder
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import java.io.FileNotFoundException
import java.io.InputStream
class IdeVirtualFileFinder(private val scope: GlobalSearchScope) : VirtualFileFinder() {
override fun findMetadata(classId: ClassId): InputStream? {
val file = findVirtualFileWithHeader(classId.asSingleFqName(), KotlinMetadataFileIndex.KEY)?.takeIf { it.exists() } ?: return null
return try {
file.inputStream
} catch (e: FileNotFoundException) {
null
}
}
override fun hasMetadataPackage(fqName: FqName): Boolean = KotlinMetadataFilePackageIndex.hasSomethingInPackage(fqName, scope)
override fun findBuiltInsData(packageFqName: FqName): InputStream? =
findVirtualFileWithHeader(packageFqName, KotlinBuiltInsMetadataIndex.KEY)?.inputStream
override fun findSourceOrBinaryVirtualFile(classId: ClassId) = findVirtualFileWithHeader(classId)
init {
if (scope != GlobalSearchScope.EMPTY_SCOPE && scope.project == null) {
LOG.warn("Scope with null project $scope")
}
}
override fun findVirtualFileWithHeader(classId: ClassId): VirtualFile? =
findVirtualFileWithHeader(classId.asSingleFqName(), KotlinClassFileIndex.KEY)
private fun findVirtualFileWithHeader(fqName: FqName, key: ID<FqName, Void>): VirtualFile? {
val iterator = FileBasedIndex.getInstance().getContainingFilesIterator(key, fqName, scope)
return if (iterator.hasNext()) {
iterator.next()
} else {
null
}
}
companion object {
private val LOG = Logger.getInstance(IdeVirtualFileFinder::class.java)
}
}
| apache-2.0 | f5d084bd5044d70fb877a4f923b4c904 | 39.254545 | 158 | 0.735321 | 4.834061 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/hierarchy/overrides/KotlinOverrideTreeStructure.kt | 1 | 1924 | // 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.hierarchy.overrides
import com.intellij.icons.AllIcons
import com.intellij.ide.hierarchy.HierarchyNodeDescriptor
import com.intellij.ide.hierarchy.HierarchyTreeStructure
import com.intellij.openapi.project.Project
import com.intellij.util.ArrayUtil
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors
import org.jetbrains.kotlin.idea.base.util.useScope
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
class KotlinOverrideTreeStructure(project: Project, declaration: KtCallableDeclaration) : HierarchyTreeStructure(project, null) {
init {
setBaseElement(KotlinOverrideHierarchyNodeDescriptor(null, declaration.containingClassOrObject!!, declaration))
}
private val baseElement = declaration.createSmartPointer()
override fun buildChildren(nodeDescriptor: HierarchyNodeDescriptor): Array<Any> {
val baseElement = baseElement.element ?: return ArrayUtil.EMPTY_OBJECT_ARRAY
val psiElement = nodeDescriptor.psiElement ?: return ArrayUtil.EMPTY_OBJECT_ARRAY
val subclasses = HierarchySearchRequest(psiElement, psiElement.useScope(), false).searchInheritors().findAll()
return subclasses.mapNotNull {
val subclass = it.unwrapped ?: return@mapNotNull null
KotlinOverrideHierarchyNodeDescriptor(nodeDescriptor, subclass, baseElement)
}
.filter { it.calculateState() != AllIcons.Hierarchy.MethodNotDefined }
.toTypedArray()
}
}
| apache-2.0 | d7b20e93b737d766e164980e2e11a1bd | 52.444444 | 158 | 0.786902 | 5.130667 | false | false | false | false |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/ui/navigation/radio/RadioActivity.kt | 1 | 4207 | package com.kelsos.mbrc.ui.navigation.radio;
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import butterknife.BindView
import butterknife.ButterKnife
import com.google.android.material.snackbar.Snackbar
import com.kelsos.mbrc.R
import com.kelsos.mbrc.data.RadioStation
import com.kelsos.mbrc.ui.activities.BaseActivity
import com.kelsos.mbrc.ui.navigation.radio.RadioAdapter.OnRadioPressedListener
import com.kelsos.mbrc.ui.widgets.EmptyRecyclerView
import com.kelsos.mbrc.ui.widgets.MultiSwipeRefreshLayout
import com.raizlabs.android.dbflow.list.FlowCursorList
import toothpick.Scope
import toothpick.Toothpick
import toothpick.smoothie.module.SmoothieActivityModule
import javax.inject.Inject
class RadioActivity : BaseActivity(),
RadioView,
SwipeRefreshLayout.OnRefreshListener,
OnRadioPressedListener {
private val PRESENTER_SCOPE: Class<*> = Presenter::class.java
@BindView(R.id.swipe_layout) lateinit var swipeLayout: MultiSwipeRefreshLayout
@BindView(R.id.radio_list) lateinit var radioView: EmptyRecyclerView
@BindView(R.id.empty_view) lateinit var emptyView: View
@BindView(R.id.list_empty_title) lateinit var emptyViewTitle: TextView
@BindView(R.id.list_empty_icon) lateinit var emptyViewIcon: ImageView
@BindView(R.id.list_empty_subtitle) lateinit var emptyViewSubTitle: TextView
@BindView(R.id.empty_view_progress_bar) lateinit var emptyViewProgress: ProgressBar
@Inject lateinit var presenter: RadioPresenter
@Inject lateinit var adapter: RadioAdapter
override fun active(): Int {
return R.id.nav_radio
}
private lateinit var scope: Scope
override fun onCreate(savedInstanceState: Bundle?) {
Toothpick.openScope(PRESENTER_SCOPE).installModules(RadioModule())
scope = Toothpick.openScopes(application, PRESENTER_SCOPE, this)
scope.installModules(SmoothieActivityModule(this))
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_radio)
Toothpick.inject(this, scope)
ButterKnife.bind(this)
super.setup()
swipeLayout.setOnRefreshListener(this)
swipeLayout.setSwipeableChildren(R.id.radio_list, R.id.empty_view)
emptyViewTitle.setText(R.string.radio__no_radio_stations)
emptyViewIcon.setImageResource(R.drawable.ic_radio_black_80dp)
radioView.adapter = adapter
radioView.emptyView = emptyView
radioView.layoutManager = LinearLayoutManager(this)
}
override fun onStart() {
super.onStart()
presenter.attach(this)
presenter.load()
adapter.setOnRadioPressedListener(this)
}
override fun onStop() {
super.onStop()
presenter.detach()
adapter.setOnRadioPressedListener(null)
}
override fun onDestroy() {
super.onDestroy()
if (isFinishing) {
Toothpick.closeScope(PRESENTER_SCOPE)
}
Toothpick.closeScope(this)
}
override fun update(data: FlowCursorList<RadioStation>) {
adapter.update(data)
}
override fun error(error: Throwable) {
Snackbar.make(radioView, R.string.radio__loading_failed, Snackbar.LENGTH_SHORT).show()
}
override fun onRadioPressed(path: String) {
presenter.play(path)
}
override fun onRefresh() {
presenter.refresh()
}
override fun radioPlayFailed() {
Snackbar.make(radioView, R.string.radio__play_failed, Snackbar.LENGTH_SHORT).show()
}
override fun radioPlaySuccessful() {
Snackbar.make(radioView, R.string.radio__play_successful, Snackbar.LENGTH_SHORT).show()
}
override fun showLoading() {
emptyViewProgress.visibility = View.VISIBLE
emptyViewIcon.visibility = View.GONE
emptyViewTitle.visibility = View.GONE
emptyViewSubTitle.visibility = View.GONE
}
override fun hideLoading() {
emptyViewProgress.visibility = View.GONE
emptyViewIcon.visibility = View.VISIBLE
emptyViewTitle.visibility = View.VISIBLE
emptyViewSubTitle.visibility = View.VISIBLE
swipeLayout.isRefreshing = false
}
@javax.inject.Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class Presenter
}
| gpl-3.0 | f7406c2ee50ce73c3f88693d7e63f5b1 | 31.361538 | 91 | 0.772997 | 4.190239 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/components/TextFieldComponent.kt | 5 | 2147 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.wizard.ui.components
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.tools.projectWizard.core.Context
import org.jetbrains.kotlin.tools.projectWizard.core.entity.SettingValidator
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.componentWithCommentAtBottom
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.textField
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import javax.swing.JComponent
class TextFieldComponent(
context: Context,
labelText: String? = null,
description: String? = null,
initialValue: String? = null,
validator: SettingValidator<String>? = null,
onValueUpdate: (String, isByUser: Boolean) -> Unit = { _, _ -> }
) : UIComponent<String>(
context,
labelText,
validator,
onValueUpdate
) {
private var isDisabled: Boolean = false
private var cachedValueWhenDisabled: String? = null
@Suppress("HardCodedStringLiteral")
private val textField = textField(initialValue.orEmpty(), ::fireValueUpdated)
override val alignTarget: JComponent get() = textField
override val uiComponent = componentWithCommentAtBottom(textField, description)
override fun updateUiValue(newValue: String) = safeUpdateUi {
textField.text = newValue
}
fun onUserType(action: () -> Unit) {
textField.addKeyListener(object : KeyAdapter() {
override fun keyReleased(e: KeyEvent?) = action()
})
}
fun disable(@Nls message: String) {
cachedValueWhenDisabled = getUiValue()
textField.isEditable = false
textField.foreground = UIUtil.getLabelDisabledForeground()
isDisabled = true
updateUiValue(message)
}
override fun validate(value: String) {
if (isDisabled) return
super.validate(value)
}
override fun getUiValue(): String = cachedValueWhenDisabled ?: textField.text
} | apache-2.0 | 53def59331cd876ea907db24b611da5f | 34.213115 | 158 | 0.726129 | 4.539112 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/zolotayakorona/RussiaTaxCodes.kt | 1 | 4254 | package au.id.micolous.metrodroid.transit.zolotayakorona
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.time.MetroTimeZone
import au.id.micolous.metrodroid.util.NumberUtils
// Tax codes assigned by Russian Tax agency for places both inside Russia (e.g. Moscow) and outside (e.g. Baikonur)
// They are used by Zolotaya Korona and Umarsh
// This dataset may also include additional codes used by those systems
object RussiaTaxCodes {
@Suppress("FunctionName")
fun BCDToTimeZone(bcd: Int): MetroTimeZone = TAX_CODES[bcd]?.second ?: MetroTimeZone.MOSCOW
fun codeToName(regionNum: Int): String = TAX_CODES[NumberUtils.intToBCD(regionNum)]?.first?.let { Localizer.localizeString(it) } ?: Localizer.localizeString(R.string.unknown_format, regionNum)
@Suppress("FunctionName")
fun BCDToName(regionNum: Int): String = TAX_CODES[regionNum]?.first?.let { Localizer.localizeString(it) } ?: Localizer.localizeString(R.string.unknown_format, regionNum.toString(16))
private val TAX_CODES = mapOf(
// List of cities is taken from Zolotaya Korona website. Regions match
// license plate regions
//
// Gorno-Altaysk
0x04 to Pair(R.string.russia_region_04_altai_republic, MetroTimeZone.KRASNOYARSK),
// Syktyvkar and Ukhta
0x11 to Pair(R.string.russia_region_11_komi, MetroTimeZone.KIROV),
0x12 to Pair(R.string.russia_region_12_mari_el, MetroTimeZone.MOSCOW),
0x18 to Pair(R.string.russia_region_18_udmurt, MetroTimeZone.SAMARA),
// Biysk
0x22 to Pair(R.string.russia_region_22_altai, MetroTimeZone.KRASNOYARSK),
// Krasnodar and Sochi
0x23 to Pair(R.string.russia_region_23_krasnodar, MetroTimeZone.MOSCOW),
// Vladivostok
0x25 to Pair(R.string.russia_region_25_primorsky, MetroTimeZone.VLADIVOSTOK),
// Khabarovsk
0x27 to Pair(R.string.russia_region_27_khabarovsk, MetroTimeZone.VLADIVOSTOK),
// Blagoveshchensk
0x28 to Pair(R.string.russia_region_28_amur, MetroTimeZone.YAKUTSK),
// Arkhangelsk
0x29 to Pair(R.string.russia_region_29_arkhangelsk, MetroTimeZone.MOSCOW),
// Petropavlovsk-Kamchatsky
0x41 to Pair(R.string.russia_region_41_kamchatka, MetroTimeZone.KAMCHATKA),
// Kemerovo and Novokuznetsk
0x42 to Pair(R.string.russia_region_42_kemerovo, MetroTimeZone.NOVOKUZNETSK),
0x43 to Pair(R.string.russia_region_43_kirov, MetroTimeZone.KIROV),
// Kurgan
0x45 to Pair(R.string.russia_region_45_kurgan, MetroTimeZone.YEKATERINBURG),
0x52 to Pair(R.string.russia_region_52_nizhnij_novgorod, MetroTimeZone.MOSCOW),
// Veliky Novgorod
0x53 to Pair(R.string.russia_region_53_novgorod, MetroTimeZone.MOSCOW),
// Novosibirsk
0x54 to Pair(R.string.russia_region_54_novosibirsk, MetroTimeZone.NOVOSIBIRSK),
// Omsk
0x55 to Pair(R.string.russia_region_55_omsk, MetroTimeZone.OMSK),
// Orenburg
0x56 to Pair(R.string.russia_region_56_orenburg, MetroTimeZone.YEKATERINBURG),
0x58 to Pair(R.string.russia_region_58_penza, MetroTimeZone.MOSCOW),
// Pskov
0x60 to Pair(R.string.russia_region_60_pskov, MetroTimeZone.MOSCOW),
// Samara
0x63 to Pair(R.string.russia_region_63_samara, MetroTimeZone.SAMARA),
// Kholmsk
0x65 to Pair(R.string.russia_region_65_sakhalin, MetroTimeZone.SAKHALIN),
0x66 to Pair(R.string.russia_region_66_sverdlovsk, MetroTimeZone.YEKATERINBURG),
0x74 to Pair(R.string.russia_region_74_chelyabinsk, MetroTimeZone.YEKATERINBURG),
// Yaroslavl
0x76 to Pair(R.string.russia_region_76_yaroslavl, MetroTimeZone.MOSCOW),
// Birobidzhan
0x79 to Pair(R.string.russia_region_79_jewish_autonomous, MetroTimeZone.VLADIVOSTOK),
// 91 = Code used by Umarsh for Crimea
0x91 to Pair(R.string.umarsh_91_crimea, MetroTimeZone.SIMFEROPOL)
)
} | gpl-3.0 | 4daa7740a777b24a85eb48ef41b941c3 | 58.097222 | 196 | 0.672543 | 3.169896 | false | false | false | false |
spinnaker/orca | orca-kayenta/src/test/kotlin/com/netflix/spinnaker/orca/kayenta/pipeline/DeployCanaryServerGroupsStageTest.kt | 4 | 5273 | /*
* Copyright 2018 Netflix, 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.netflix.spinnaker.orca.kayenta.pipeline
import com.netflix.spinnaker.orca.api.pipeline.graph.StageDefinitionBuilder
import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution
import com.netflix.spinnaker.orca.api.test.pipeline
import com.netflix.spinnaker.orca.api.test.stage
import com.netflix.spinnaker.orca.clouddriver.pipeline.cluster.FindImageFromClusterStage
import com.netflix.spinnaker.orca.kato.pipeline.ParallelDeployStage
import com.netflix.spinnaker.orca.pipeline.graph.StageGraphBuilderImpl
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.fail
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
internal object DeployCanaryServerGroupsStageTest : Spek({
describe("constructing synthetic stages") {
val subject = DeployCanaryServerGroupsStage()
given("a canary deployment pipeline") {
val baseline = mapOf(
"application" to "spindemo",
"account" to "prod",
"cluster" to "spindemo-prestaging-prestaging"
)
val controlServerGroupA = serverGroup {
mapOf(
"application" to "spindemo",
"stack" to "prestaging",
"freeFormDetails" to "baseline-a"
)
}
val controlServerGroupB = serverGroup {
mapOf(
"application" to "spindemo",
"stack" to "prestaging",
"freeFormDetails" to "baseline-b"
)
}
val experimentServerGroupA = serverGroup {
mapOf(
"application" to "spindemo",
"stack" to "prestaging",
"freeFormDetails" to "canary-a"
)
}
val experimentServerGroupB = serverGroup {
mapOf(
"application" to "spindemo",
"stack" to "prestaging",
"freeFormDetails" to "canary-b"
)
}
val pipeline = pipeline {
stage {
refId = "1"
type = KayentaCanaryStage.STAGE_TYPE
context["deployments"] = mapOf(
"baseline" to baseline,
"serverGroupPairs" to listOf(
mapOf(
"control" to controlServerGroupA,
"experiment" to experimentServerGroupA
),
mapOf(
"control" to controlServerGroupB,
"experiment" to experimentServerGroupB
)
)
)
stage {
refId = "1<1"
type = DeployCanaryServerGroupsStage.STAGE_TYPE
}
}
}
val canaryDeployStage = pipeline.stageByRef("1<1")
val beforeStages = subject.beforeStages(canaryDeployStage)
it("creates a find image and deploy stages for the control serverGroup") {
beforeStages.named("Find baseline image") {
assertThat(type).isEqualTo(FindImageFromClusterStage.PIPELINE_CONFIG_TYPE)
assertThat(requisiteStageRefIds).isEmpty()
assertThat(context["application"]).isEqualTo(baseline["application"])
assertThat(context["account"]).isEqualTo(baseline["account"])
assertThat(context["serverGroup"]).isEqualTo(baseline["serverGroup"])
assertThat(context["cloudProvider"]).isEqualTo("aws")
assertThat(context["regions"]).isEqualTo(setOf("us-west-1"))
}
beforeStages.named("Deploy control server groups") {
assertThat(type).isEqualTo(ParallelDeployStage.PIPELINE_CONFIG_TYPE)
assertThat(requisiteStageRefIds).hasSize(1)
assertThat(pipeline.stageByRef(requisiteStageRefIds.first()).name)
.isEqualTo("Find baseline image")
assertThat(context["clusters"]).isEqualTo(listOf(controlServerGroupA, controlServerGroupB))
}
}
it("creates a deploy stage for the experiment serverGroup") {
beforeStages.named("Deploy experiment server groups") {
assertThat(type).isEqualTo(ParallelDeployStage.PIPELINE_CONFIG_TYPE)
assertThat(requisiteStageRefIds).isEmpty()
assertThat(context["clusters"]).isEqualTo(listOf(experimentServerGroupA, experimentServerGroupB))
}
}
}
}
})
fun List<StageExecution>.named(name: String, block: StageExecution.() -> Unit) {
find { it.name == name }
?.apply(block)
?: fail("Expected a stage named '$name' but found ${map(StageExecution::getName)}")
}
fun StageDefinitionBuilder.beforeStages(stage: StageExecution) =
StageGraphBuilderImpl.beforeStages(stage).let { graph ->
beforeStages(stage, graph)
graph.build().toList().also {
stage.execution.stages.addAll(it)
}
}
| apache-2.0 | dd6913f76d48dc292da8fc971da226fd | 36.133803 | 107 | 0.662811 | 4.577257 | false | false | false | false |
andgate/Ikou | core/src/com/andgate/ikou/graphics/player/PlayerModel.kt | 1 | 2122 | /*
This file is part of Ikou.
Ikou is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License.
Ikou 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 Ikou. If not, see <http://www.gnu.org/licenses/>.
*/
package com.andgate.ikou.graphics.player;
import com.andgate.ikou.constants.*
import com.andgate.ikou.graphics.util.CubeMesher
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.Mesh
import com.badlogic.gdx.graphics.g3d.Material
import com.badlogic.gdx.graphics.g3d.Renderable
import com.badlogic.gdx.graphics.g3d.RenderableProvider
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute
import com.badlogic.gdx.math.Matrix4
import com.badlogic.gdx.utils.Array
import com.badlogic.gdx.utils.Disposable
import com.badlogic.gdx.utils.Pool
class PlayerModel : RenderableProvider, Disposable
{
val material = Material(TILE_MATERIAL)
val mesh: Mesh
val transform = Matrix4()
init {
val mesher = CubeMesher()
mesher.calculateVerts(0f, TILE_HEIGHT, 0f, TILE_SPAN, TILE_HEIGHT, TILE_SPAN)
mesher.addAll(PLAYER_TILE_COLOR)
mesh = mesher.build()
}
override fun getRenderables(renderables: Array<Renderable>, pool: Pool<Renderable>)
{
val renderable: Renderable = pool.obtain()
renderable.material = material
renderable.meshPart.offset = 0
renderable.meshPart.size = mesh.getNumIndices()
renderable.meshPart.primitiveType = GL20.GL_TRIANGLES
renderable.meshPart.mesh = mesh
renderables.add(renderable)
renderable.worldTransform.set(transform)
}
override fun dispose()
{
mesh.dispose();
}
}
| gpl-2.0 | 960846ee3cd66badc761028b6aa4e6ad | 34.366667 | 87 | 0.730914 | 3.973783 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.