repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
siosio/intellij-community | python/python-terminal/src/com/jetbrains/python/sdk/PyVirtualEnvTerminalCustomizer.kt | 2 | 4267 | // 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.jetbrains.python.sdk
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.options.UnnamedConfigurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.SystemInfo
import com.jetbrains.python.run.findActivateScript
import org.jetbrains.plugins.terminal.LocalTerminalCustomizer
import org.jetbrains.plugins.terminal.TerminalOptionsProvider
import java.io.File
import javax.swing.JCheckBox
class PyVirtualEnvTerminalCustomizer : LocalTerminalCustomizer() {
override fun customizeCommandAndEnvironment(project: Project,
command: Array<out String>,
envs: MutableMap<String, String>): Array<out String> {
val sdk: Sdk? = findSdk(project)
if (sdk != null &&
(PythonSdkUtil.isVirtualEnv(sdk) || PythonSdkUtil.isConda(sdk)) &&
PyVirtualEnvTerminalSettings.getInstance(project).virtualEnvActivate) {
// in case of virtualenv sdk on unix we activate virtualenv
val path = sdk.homePath
if (path != null && command.isNotEmpty()) {
val shellPath = command[0]
if (isShellIntegrationAvailable(shellPath)) { //fish shell works only for virtualenv and not for conda
//for bash we pass activate script to jediterm shell integration (see jediterm-bash.in) to source it there
//TODO: fix conda for fish
findActivateScript(path, shellPath)?.let { activate ->
envs.put("JEDITERM_SOURCE", activate.first)
envs.put("JEDITERM_SOURCE_ARGS", activate.second?:"")
}
}
else {
//for other shells we read envs from activate script by the default shell and pass them to the process
envs.putAll(PySdkUtil.activateVirtualEnv(sdk))
}
}
}
return command
}
private fun isShellIntegrationAvailable(shellPath: String) : Boolean {
if (TerminalOptionsProvider.instance.shellIntegration()) {
val shellName = File(shellPath).name
return shellName == "bash" || (SystemInfo.isMac && shellName == "sh") || shellName == "zsh" || shellName == "fish"
}
return false
}
private fun findSdk(project: Project): Sdk? {
for (m in ModuleManager.getInstance(project).modules) {
val sdk: Sdk? = PythonSdkUtil.findPythonSdk(m)
if (sdk != null && !PythonSdkUtil.isRemote(sdk)) {
return sdk
}
}
return null
}
override fun getDefaultFolder(project: Project): String? {
return null
}
override fun getConfigurable(project: Project): UnnamedConfigurable = object : UnnamedConfigurable {
val settings = PyVirtualEnvTerminalSettings.getInstance(project)
var myCheckbox: JCheckBox = JCheckBox(PyTerminalBundle.message("activate.virtualenv.checkbox.text"))
override fun createComponent() = myCheckbox
override fun isModified() = myCheckbox.isSelected != settings.virtualEnvActivate
override fun apply() {
settings.virtualEnvActivate = myCheckbox.isSelected
}
override fun reset() {
myCheckbox.isSelected = settings.virtualEnvActivate
}
}
}
class SettingsState {
var virtualEnvActivate: Boolean = true
}
@State(name = "PyVirtualEnvTerminalCustomizer", storages = [(Storage("python-terminal.xml"))])
class PyVirtualEnvTerminalSettings : PersistentStateComponent<SettingsState> {
var myState: SettingsState = SettingsState()
var virtualEnvActivate: Boolean
get() = myState.virtualEnvActivate
set(value) {
myState.virtualEnvActivate = value
}
override fun getState(): SettingsState = myState
override fun loadState(state: SettingsState) {
myState.virtualEnvActivate = state.virtualEnvActivate
}
companion object {
fun getInstance(project: Project): PyVirtualEnvTerminalSettings {
return project.getService(PyVirtualEnvTerminalSettings::class.java)
}
}
}
| apache-2.0 | 4014df7d23ea7dea829039f4e21b147c | 33.691057 | 140 | 0.708695 | 4.84336 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/declarations/KotlinUParameter.kt | 4 | 2138 | // 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.uast.kotlin
import com.intellij.psi.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UParameter
import org.jetbrains.uast.UParameterEx
@ApiStatus.Internal
open class KotlinUParameter(
psi: PsiParameter,
final override val sourcePsi: KtElement?,
givenParent: UElement?
) : AbstractKotlinUVariable(givenParent), UParameterEx, PsiParameter by psi {
final override val javaPsi = unwrap<UParameter, PsiParameter>(psi)
override val psi = javaPsi
private val isLightConstructorParam by lz { psi.getParentOfType<PsiMethod>(true)?.isConstructor }
private val isKtConstructorParam by lz { sourcePsi?.getParentOfType<KtCallableDeclaration>(true)?.let { it is KtConstructor<*> } }
override fun acceptsAnnotationTarget(target: AnnotationUseSiteTarget?): Boolean {
if (sourcePsi !is KtParameter) return false
if (isKtConstructorParam == isLightConstructorParam && target == null) return true
if (sourcePsi.parent.parent is KtCatchClause && target == null) return true
when (target) {
AnnotationUseSiteTarget.CONSTRUCTOR_PARAMETER -> return isLightConstructorParam == true
AnnotationUseSiteTarget.SETTER_PARAMETER -> return isLightConstructorParam != true
else -> return false
}
}
override fun getInitializer(): PsiExpression? {
return super<AbstractKotlinUVariable>.getInitializer()
}
override fun getOriginalElement(): PsiElement? {
return super<AbstractKotlinUVariable>.getOriginalElement()
}
override fun getNameIdentifier(): PsiIdentifier {
return super.getNameIdentifier()
}
override fun getContainingFile(): PsiFile {
return super.getContainingFile()
}
}
| apache-2.0 | 07b0b8660386ba4ae6cc00142fa3585e | 38.592593 | 158 | 0.744621 | 5.279012 | false | false | false | false |
JetBrains/kotlin-native | runtime/src/main/kotlin/kotlin/Primitives.kt | 2 | 72104 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
@file:Suppress("OVERRIDE_BY_INLINE", "NOTHING_TO_INLINE")
package kotlin
import kotlin.native.internal.CanBePrecreated
import kotlin.native.internal.IntrinsicType
import kotlin.native.internal.NumberConverter
import kotlin.native.internal.TypedIntrinsic
/**
* Represents a 8-bit signed integer.
*/
public final class Byte private constructor() : Number(), Comparable<Byte> {
@CanBePrecreated
companion object {
/**
* A constant holding the minimum value an instance of Byte can have.
*/
public const val MIN_VALUE: Byte = -128
/**
* A constant holding the maximum value an instance of Byte can have.
*/
public const val MAX_VALUE: Byte = 127
/**
* The number of bytes used to represent an instance of Byte in a binary form.
*/
@SinceKotlin("1.3")
public const val SIZE_BYTES: Int = 1
/**
* The number of bits used to represent an instance of Byte in a binary form.
*/
@SinceKotlin("1.3")
public const val SIZE_BITS: Int = 8
}
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
@TypedIntrinsic(IntrinsicType.SIGNED_COMPARE_TO)
external public override operator fun compareTo(other: Byte): Int
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public inline operator fun compareTo(other: Short): Int =
this.toShort().compareTo(other)
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public inline operator fun compareTo(other: Int): Int =
this.toInt().compareTo(other)
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public inline operator fun compareTo(other: Long): Int =
this.toLong().compareTo(other)
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public inline operator fun compareTo(other: Float): Int =
this.toFloat().compareTo(other)
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public inline operator fun compareTo(other: Double): Int =
this.toDouble().compareTo(other)
/** Adds the other value to this value. */
public inline operator fun plus(other: Byte): Int =
this.toInt() + other.toInt()
/** Adds the other value to this value. */
public inline operator fun plus(other: Short): Int =
this.toInt() + other.toInt()
/** Adds the other value to this value. */
public inline operator fun plus(other: Int): Int =
this.toInt() + other
/** Adds the other value to this value. */
public inline operator fun plus(other: Long): Long =
this.toLong() + other
/** Adds the other value to this value. */
public inline operator fun plus(other: Float): Float =
this.toFloat() + other
/** Adds the other value to this value. */
public inline operator fun plus(other: Double): Double =
this.toDouble() + other
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Byte): Int =
this.toInt() - other.toInt()
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Short): Int =
this.toInt() - other.toInt()
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Int): Int =
this.toInt() - other
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Long): Long =
this.toLong() - other
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Float): Float =
this.toFloat() - other
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Double): Double =
this.toDouble() - other
/** Multiplies this value by the other value. */
public inline operator fun times(other: Byte): Int =
this.toInt() * other.toInt()
/** Multiplies this value by the other value. */
public inline operator fun times(other: Short): Int =
this.toInt() * other.toInt()
/** Multiplies this value by the other value. */
public inline operator fun times(other: Int): Int =
this.toInt() * other
/** Multiplies this value by the other value. */
public inline operator fun times(other: Long): Long =
this.toLong() * other
/** Multiplies this value by the other value. */
public inline operator fun times(other: Float): Float =
this.toFloat() * other
/** Multiplies this value by the other value. */
public inline operator fun times(other: Double): Double =
this.toDouble() * other
/** Divides this value by the other value. */
public inline operator fun div(other: Byte): Int =
this.toInt() / other.toInt()
/** Divides this value by the other value. */
public inline operator fun div(other: Short): Int =
this.toInt() / other.toInt()
/** Divides this value by the other value. */
public inline operator fun div(other: Int): Int =
this.toInt() / other
/** Divides this value by the other value. */
public inline operator fun div(other: Long): Long =
this.toLong() / other
/** Divides this value by the other value. */
public inline operator fun div(other: Float): Float =
this.toFloat() / other
/** Divides this value by the other value. */
public inline operator fun div(other: Double): Double =
this.toDouble() / other
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Byte): Int =
this.toInt() % other.toInt()
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Short): Int =
this.toInt() % other.toInt()
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Int): Int =
this.toInt() % other
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Long): Long =
this.toLong() % other
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Float): Float =
this.toFloat() % other
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Double): Double =
this.toDouble() % other
/** Increments this value. */
@TypedIntrinsic(IntrinsicType.INC)
external public operator fun inc(): Byte
/** Decrements this value. */
@TypedIntrinsic(IntrinsicType.DEC)
external public operator fun dec(): Byte
/** Returns this value. */
public inline operator fun unaryPlus(): Int =
this.toInt()
/** Returns the negative of this value. */
public inline operator fun unaryMinus(): Int =
-this.toInt()
/** Returns this value. */
public inline override fun toByte(): Byte =
this
/**
* Converts this [Byte] value to [Char].
*
* If this value is non-negative, the resulting `Char` code is equal to this value.
*
* The least significant 8 bits of the resulting `Char` code are the same as the bits of this `Byte` value,
* whereas the most significant 8 bits are filled with the sign bit of this value.
*/
@TypedIntrinsic(IntrinsicType.SIGN_EXTEND)
external public override fun toChar(): Char
/**
* Converts this [Byte] value to [Short].
*
* The resulting `Short` value represents the same numerical value as this `Byte`.
*
* The least significant 8 bits of the resulting `Short` value are the same as the bits of this `Byte` value,
* whereas the most significant 8 bits are filled with the sign bit of this value.
*/
@TypedIntrinsic(IntrinsicType.SIGN_EXTEND)
external public override fun toShort(): Short
/**
* Converts this [Byte] value to [Int].
*
* The resulting `Int` value represents the same numerical value as this `Byte`.
*
* The least significant 8 bits of the resulting `Int` value are the same as the bits of this `Byte` value,
* whereas the most significant 24 bits are filled with the sign bit of this value.
*/
@TypedIntrinsic(IntrinsicType.SIGN_EXTEND)
external public override fun toInt(): Int
/**
* Converts this [Byte] value to [Long].
*
* The resulting `Long` value represents the same numerical value as this `Byte`.
*
* The least significant 8 bits of the resulting `Long` value are the same as the bits of this `Byte` value,
* whereas the most significant 56 bits are filled with the sign bit of this value.
*/
@TypedIntrinsic(IntrinsicType.SIGN_EXTEND)
external public override fun toLong(): Long
/**
* Converts this [Byte] value to [Float].
*
* The resulting `Float` value represents the same numerical value as this `Byte`.
*/
@TypedIntrinsic(IntrinsicType.SIGNED_TO_FLOAT)
external public override fun toFloat(): Float
/**
* Converts this [Byte] value to [Double].
*
* The resulting `Double` value represents the same numerical value as this `Byte`.
*/
@TypedIntrinsic(IntrinsicType.SIGNED_TO_FLOAT)
external public override fun toDouble(): Double
/** Creates a range from this value to the specified [other] value. */
public operator fun rangeTo(other: Byte): IntRange {
return IntRange(this.toInt(), other.toInt())
}
/** Creates a range from this value to the specified [other] value. */
public operator fun rangeTo(other: Short): IntRange {
return IntRange(this.toInt(), other.toInt())
}
/** Creates a range from this value to the specified [other] value. */
public operator fun rangeTo(other: Int): IntRange {
return IntRange(this.toInt(), other.toInt())
}
/** Creates a range from this value to the specified [other] value. */
public operator fun rangeTo(other: Long): LongRange {
return LongRange(this.toLong(), other.toLong())
}
// Konan-specific.
public fun equals(other: Byte): Boolean = kotlin.native.internal.areEqualByValue(this, other)
public override fun equals(other: Any?): Boolean =
other is Byte && kotlin.native.internal.areEqualByValue(this, other)
@SymbolName("Kotlin_Byte_toString")
external public override fun toString(): String
public override fun hashCode(): Int {
return this.toInt()
}
}
/**
* Represents a 16-bit signed integer.
*/
public final class Short private constructor() : Number(), Comparable<Short> {
@CanBePrecreated
companion object {
/**
* A constant holding the minimum value an instance of Short can have.
*/
public const val MIN_VALUE: Short = -32768
/**
* A constant holding the maximum value an instance of Short can have.
*/
public const val MAX_VALUE: Short = 32767
/**
* The number of bytes used to represent an instance of Short in a binary form.
*/
@SinceKotlin("1.3")
public const val SIZE_BYTES: Int = 2
/**
* The number of bits used to represent an instance of Short in a binary form.
*/
@SinceKotlin("1.3")
public const val SIZE_BITS: Int = 16
}
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public inline operator fun compareTo(other: Byte): Int =
this.compareTo(other.toShort())
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
@TypedIntrinsic(IntrinsicType.SIGNED_COMPARE_TO)
external public override operator fun compareTo(other: Short): Int
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public inline operator fun compareTo(other: Int): Int =
this.toInt().compareTo(other)
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public inline operator fun compareTo(other: Long): Int =
this.toLong().compareTo(other)
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public inline operator fun compareTo(other: Float): Int =
this.toFloat().compareTo(other)
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public inline operator fun compareTo(other: Double): Int =
this.toDouble().compareTo(other)
/** Adds the other value to this value. */
public inline operator fun plus(other: Byte): Int =
this.toInt() + other.toInt()
/** Adds the other value to this value. */
public inline operator fun plus(other: Short): Int =
this.toInt() + other.toInt()
/** Adds the other value to this value. */
public inline operator fun plus(other: Int): Int =
this.toInt() + other
/** Adds the other value to this value. */
public inline operator fun plus(other: Long): Long =
this.toLong() + other
/** Adds the other value to this value. */
public inline operator fun plus(other: Float): Float =
this.toFloat() + other
/** Adds the other value to this value. */
public inline operator fun plus(other: Double): Double =
this.toDouble() + other
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Byte): Int =
this.toInt() - other.toInt()
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Short): Int =
this.toInt() - other.toInt()
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Int): Int =
this.toInt() - other
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Long): Long =
this.toLong() - other
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Float): Float =
this.toFloat() - other
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Double): Double =
this.toDouble() - other
/** Multiplies this value by the other value. */
public inline operator fun times(other: Byte): Int =
this.toInt() * other.toInt()
/** Multiplies this value by the other value. */
public inline operator fun times(other: Short): Int =
this.toInt() * other.toInt()
/** Multiplies this value by the other value. */
public inline operator fun times(other: Int): Int =
this.toInt() * other
/** Multiplies this value by the other value. */
public inline operator fun times(other: Long): Long =
this.toLong() * other
/** Multiplies this value by the other value. */
public inline operator fun times(other: Float): Float =
this.toFloat() * other
/** Multiplies this value by the other value. */
public inline operator fun times(other: Double): Double =
this.toDouble() * other
/** Divides this value by the other value. */
public inline operator fun div(other: Byte): Int =
this.toInt() / other.toInt()
/** Divides this value by the other value. */
public inline operator fun div(other: Short): Int =
this.toInt() / other.toInt()
/** Divides this value by the other value. */
public inline operator fun div(other: Int): Int =
this.toInt() / other
/** Divides this value by the other value. */
public inline operator fun div(other: Long): Long =
this.toLong() / other
/** Divides this value by the other value. */
public inline operator fun div(other: Float): Float =
this.toFloat() / other
/** Divides this value by the other value. */
public inline operator fun div(other: Double): Double =
this.toDouble() / other
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Byte): Int =
this.toInt() % other.toInt()
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Short): Int =
this.toInt() % other.toInt()
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Int): Int =
this.toInt() % other
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Long): Long =
this.toLong() % other
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Float): Float =
this.toFloat() % other
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Double): Double =
this.toDouble() % other
/** Increments this value. */
@TypedIntrinsic(IntrinsicType.INC)
external public operator fun inc(): Short
/** Decrements this value. */
@TypedIntrinsic(IntrinsicType.DEC)
external public operator fun dec(): Short
/** Returns this value. */
public operator fun unaryPlus(): Int =
this.toInt()
/** Returns the negative of this value. */
public inline operator fun unaryMinus(): Int =
-this.toInt()
/** Creates a range from this value to the specified [other] value. */
public operator fun rangeTo(other: Byte): IntRange {
return IntRange(this.toInt(), other.toInt())
}
/** Creates a range from this value to the specified [other] value. */
public operator fun rangeTo(other: Short): IntRange {
return IntRange(this.toInt(), other.toInt())
}
/** Creates a range from this value to the specified [other] value. */
public operator fun rangeTo(other: Int): IntRange {
return IntRange(this.toInt(), other.toInt())
}
/** Creates a range from this value to the specified [other] value. */
public operator fun rangeTo(other: Long): LongRange {
return LongRange(this.toLong(), other.toLong())
}
/**
* Converts this [Short] value to [Byte].
*
* If this value is in [Byte.MIN_VALUE]..[Byte.MAX_VALUE], the resulting `Byte` value represents
* the same numerical value as this `Short`.
*
* The resulting `Byte` value is represented by the least significant 8 bits of this `Short` value.
*/
@TypedIntrinsic(IntrinsicType.INT_TRUNCATE)
external public override fun toByte(): Byte
/**
* Converts this [Short] value to [Char].
*
* The resulting `Char` code is equal to this value reinterpreted as an unsigned number,
* i.e. it has the same binary representation as this `Short`.
*/
@TypedIntrinsic(IntrinsicType.ZERO_EXTEND)
external public override fun toChar(): Char
/** Returns this value. */
public inline override fun toShort(): Short =
this
/**
* Converts this [Short] value to [Int].
*
* The resulting `Int` value represents the same numerical value as this `Short`.
*
* The least significant 16 bits of the resulting `Int` value are the same as the bits of this `Short` value,
* whereas the most significant 16 bits are filled with the sign bit of this value.
*/
@TypedIntrinsic(IntrinsicType.SIGN_EXTEND)
external public override fun toInt(): Int
/**
* Converts this [Short] value to [Long].
*
* The resulting `Long` value represents the same numerical value as this `Short`.
*
* The least significant 16 bits of the resulting `Long` value are the same as the bits of this `Short` value,
* whereas the most significant 48 bits are filled with the sign bit of this value.
*/
@TypedIntrinsic(IntrinsicType.SIGN_EXTEND)
external public override fun toLong(): Long
/**
* Converts this [Short] value to [Float].
*
* The resulting `Float` value represents the same numerical value as this `Short`.
*/
@TypedIntrinsic(IntrinsicType.SIGNED_TO_FLOAT)
external public override fun toFloat(): Float
/**
* Converts this [Short] value to [Double].
*
* The resulting `Double` value represents the same numerical value as this `Short`.
*/
@TypedIntrinsic(IntrinsicType.SIGNED_TO_FLOAT)
external public override fun toDouble(): Double
// Konan-specific.
public fun equals(other: Short): Boolean = kotlin.native.internal.areEqualByValue(this, other)
public override fun equals(other: Any?): Boolean =
other is Short && kotlin.native.internal.areEqualByValue(this, other)
@SymbolName("Kotlin_Short_toString")
external public override fun toString(): String
public override fun hashCode(): Int {
return this.toInt()
}
}
/**
* Represents a 32-bit signed integer.
*/
public final class Int private constructor() : Number(), Comparable<Int> {
@CanBePrecreated
companion object {
/**
* A constant holding the minimum value an instance of Int can have.
*/
public const val MIN_VALUE: Int = -2147483648
/**
* A constant holding the maximum value an instance of Int can have.
*/
public const val MAX_VALUE: Int = 2147483647
/**
* The number of bytes used to represent an instance of Int in a binary form.
*/
@SinceKotlin("1.3")
public const val SIZE_BYTES: Int = 4
/**
* The number of bits used to represent an instance of Int in a binary form.
*/
@SinceKotlin("1.3")
public const val SIZE_BITS: Int = 32
}
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public inline operator fun compareTo(other: Byte): Int =
this.compareTo(other.toInt())
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public inline operator fun compareTo(other: Short): Int =
this.compareTo(other.toInt())
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
@TypedIntrinsic(IntrinsicType.SIGNED_COMPARE_TO)
external public override operator fun compareTo(other: Int): Int
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public inline operator fun compareTo(other: Long): Int =
this.toLong().compareTo(other)
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public inline operator fun compareTo(other: Float): Int =
this.toFloat().compareTo(other)
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public inline operator fun compareTo(other: Double): Int =
this.toDouble().compareTo(other)
/** Adds the other value to this value. */
public inline operator fun plus(other: Byte): Int =
this + other.toInt()
/** Adds the other value to this value. */
public inline operator fun plus(other: Short): Int =
this + other.toInt()
/** Adds the other value to this value. */
@TypedIntrinsic(IntrinsicType.PLUS)
external public operator fun plus(other: Int): Int
/** Adds the other value to this value. */
public inline operator fun plus(other: Long): Long =
this.toLong() + other
/** Adds the other value to this value. */
public inline operator fun plus(other: Float): Float =
this.toFloat() + other
/** Adds the other value to this value. */
public inline operator fun plus(other: Double): Double =
this.toDouble() + other
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Byte): Int =
this - other.toInt()
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Short): Int =
this - other.toInt()
/** Subtracts the other value from this value. */
@TypedIntrinsic(IntrinsicType.MINUS)
external public operator fun minus(other: Int): Int
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Long): Long =
this.toLong() - other
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Float): Float =
this.toFloat() - other
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Double): Double =
this.toDouble() - other
/** Multiplies this value by the other value. */
public inline operator fun times(other: Byte): Int =
this * other.toInt()
/** Multiplies this value by the other value. */
public inline operator fun times(other: Short): Int =
this * other.toInt()
/** Multiplies this value by the other value. */
@TypedIntrinsic(IntrinsicType.TIMES)
external public operator fun times(other: Int): Int
/** Multiplies this value by the other value. */
public inline operator fun times(other: Long): Long =
this.toLong() * other
/** Multiplies this value by the other value. */
public inline operator fun times(other: Float): Float =
this.toFloat() * other
/** Multiplies this value by the other value. */
public inline operator fun times(other: Double): Double =
this.toDouble() * other
/** Divides this value by the other value. */
public inline operator fun div(other: Byte): Int =
this / other.toInt()
/** Divides this value by the other value. */
public inline operator fun div(other: Short): Int =
this / other.toInt()
/** Divides this value by the other value. */
@TypedIntrinsic(IntrinsicType.SIGNED_DIV)
external public operator fun div(other: Int): Int
/** Divides this value by the other value. */
public inline operator fun div(other: Long): Long =
this.toLong() / other
/** Divides this value by the other value. */
public inline operator fun div(other: Float): Float =
this.toFloat() / other
/** Divides this value by the other value. */
public inline operator fun div(other: Double): Double =
this.toDouble() / other
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Byte): Int =
this % other.toInt()
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Short): Int =
this % other.toInt()
/** Calculates the remainder of dividing this value by the other value. */
@TypedIntrinsic(IntrinsicType.SIGNED_REM)
external public operator fun rem(other: Int): Int
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Long): Long =
this.toLong() % other
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Float): Float =
this.toFloat() % other
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Double): Double =
this.toDouble() % other
/** Increments this value. */
@TypedIntrinsic(IntrinsicType.INC)
external public operator fun inc(): Int
/** Decrements this value. */
@TypedIntrinsic(IntrinsicType.DEC)
external public operator fun dec(): Int
/** Returns this value. */
@TypedIntrinsic(IntrinsicType.UNARY_PLUS)
external public operator fun unaryPlus(): Int
/** Returns the negative of this value. */
@TypedIntrinsic(IntrinsicType.UNARY_MINUS)
external public operator fun unaryMinus(): Int
/** Shifts this value left by the [bitCount] number of bits. */
@TypedIntrinsic(IntrinsicType.SHL)
external public infix fun shl(bitCount: Int): Int
/** Shifts this value right by the [bitCount] number of bits, filling the leftmost bits with copies of the sign bit. */
@TypedIntrinsic(IntrinsicType.SHR)
external public infix fun shr(bitCount: Int): Int
/** Shifts this value right by the [bitCount] number of bits, filling the leftmost bits with zeros. */
@TypedIntrinsic(IntrinsicType.USHR)
external public infix fun ushr(bitCount: Int): Int
/** Performs a bitwise AND operation between the two values. */
@TypedIntrinsic(IntrinsicType.AND)
external public infix fun and(other: Int): Int
/** Performs a bitwise OR operation between the two values. */
@TypedIntrinsic(IntrinsicType.OR)
external public infix fun or(other: Int): Int
/** Performs a bitwise XOR operation between the two values. */
@TypedIntrinsic(IntrinsicType.XOR)
external public infix fun xor(other: Int): Int
/** Inverts the bits in this value. */
@TypedIntrinsic(IntrinsicType.INV)
external public fun inv(): Int
/** Creates a range from this value to the specified [other] value. */
public operator fun rangeTo(other: Byte): IntRange {
return IntRange(this, other.toInt())
}
/** Creates a range from this value to the specified [other] value. */
public operator fun rangeTo(other: Short): IntRange {
return IntRange(this, other.toInt())
}
/** Creates a range from this value to the specified [other] value. */
public operator fun rangeTo(other: Int): IntRange {
return IntRange(this, other.toInt())
}
/** Creates a range from this value to the specified [other] value. */
public operator fun rangeTo(other: Long): LongRange {
return LongRange(this.toLong(), other.toLong())
}
/**
* Converts this [Int] value to [Byte].
*
* If this value is in [Byte.MIN_VALUE]..[Byte.MAX_VALUE], the resulting `Byte` value represents
* the same numerical value as this `Int`.
*
* The resulting `Byte` value is represented by the least significant 8 bits of this `Int` value.
*/
@TypedIntrinsic(IntrinsicType.INT_TRUNCATE)
external public override fun toByte(): Byte
/**
* Converts this [Int] value to [Char].
*
* If this value is in the range of `Char` codes `Char.MIN_VALUE..Char.MAX_VALUE`,
* the resulting `Char` code is equal to this value.
*
* The resulting `Char` code is represented by the least significant 16 bits of this `Int` value.
*/
@TypedIntrinsic(IntrinsicType.INT_TRUNCATE)
external public override fun toChar(): Char
/**
* Converts this [Int] value to [Short].
*
* If this value is in [Short.MIN_VALUE]..[Short.MAX_VALUE], the resulting `Short` value represents
* the same numerical value as this `Int`.
*
* The resulting `Short` value is represented by the least significant 16 bits of this `Int` value.
*/
@TypedIntrinsic(IntrinsicType.INT_TRUNCATE)
external public override fun toShort(): Short
/** Returns this value. */
public inline override fun toInt(): Int =
this
/**
* Converts this [Int] value to [Long].
*
* The resulting `Long` value represents the same numerical value as this `Int`.
*
* The least significant 32 bits of the resulting `Long` value are the same as the bits of this `Int` value,
* whereas the most significant 32 bits are filled with the sign bit of this value.
*/
@TypedIntrinsic(IntrinsicType.SIGN_EXTEND)
external public override fun toLong(): Long
/**
* Converts this [Int] value to [Float].
*
* The resulting value is the closest `Float` to this `Int` value.
* In case when this `Int` value is exactly between two `Float`s,
* the one with zero at least significant bit of mantissa is selected.
*/
@TypedIntrinsic(IntrinsicType.SIGNED_TO_FLOAT)
external public override fun toFloat(): Float
/**
* Converts this [Int] value to [Double].
*
* The resulting `Double` value represents the same numerical value as this `Int`.
*/
@TypedIntrinsic(IntrinsicType.SIGNED_TO_FLOAT)
external public override fun toDouble(): Double
// Konan-specific.
public fun equals(other: Int): Boolean = kotlin.native.internal.areEqualByValue(this, other)
public override fun equals(other: Any?): Boolean =
other is Int && kotlin.native.internal.areEqualByValue(this, other)
@SymbolName("Kotlin_Int_toString")
external public override fun toString(): String
public override fun hashCode(): Int {
return this
}
}
/**
* Represents a 64-bit signed integer.
*/
public final class Long private constructor() : Number(), Comparable<Long> {
@CanBePrecreated
companion object {
/**
* A constant holding the minimum value an instance of Long can have.
*/
public const val MIN_VALUE: Long = -9223372036854775807L - 1L
/**
* A constant holding the maximum value an instance of Long can have.
*/
public const val MAX_VALUE: Long = 9223372036854775807L
/**
* The number of bytes used to represent an instance of Long in a binary form.
*/
@SinceKotlin("1.3")
public const val SIZE_BYTES: Int = 8
/**
* The number of bits used to represent an instance of Long in a binary form.
*/
@SinceKotlin("1.3")
public const val SIZE_BITS: Int = 64
}
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public inline operator fun compareTo(other: Byte): Int =
this.compareTo(other.toLong())
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public inline operator fun compareTo(other: Short): Int =
this.compareTo(other.toLong())
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public inline operator fun compareTo(other: Int): Int =
this.compareTo(other.toLong())
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
@TypedIntrinsic(IntrinsicType.SIGNED_COMPARE_TO)
external public override operator fun compareTo(other: Long): Int
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public inline operator fun compareTo(other: Float): Int =
this.toFloat().compareTo(other)
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public inline operator fun compareTo(other: Double): Int =
this.toDouble().compareTo(other)
/** Adds the other value to this value. */
public inline operator fun plus(other: Byte): Long =
this + other.toLong()
/** Adds the other value to this value. */
public inline operator fun plus(other: Short): Long =
this + other.toLong()
/** Adds the other value to this value. */
public inline operator fun plus(other: Int): Long =
this + other.toLong()
/** Adds the other value to this value. */
@TypedIntrinsic(IntrinsicType.PLUS)
external public operator fun plus(other: Long): Long
/** Adds the other value to this value. */
public inline operator fun plus(other: Float): Float =
this.toFloat() + other
/** Adds the other value to this value. */
public inline operator fun plus(other: Double): Double =
this.toDouble() + other
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Byte): Long =
this - other.toLong()
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Short): Long =
this - other.toLong()
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Int): Long =
this - other.toLong()
/** Subtracts the other value from this value. */
@TypedIntrinsic(IntrinsicType.MINUS)
external public operator fun minus(other: Long): Long
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Float): Float =
this.toFloat() - other
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Double): Double =
this.toDouble() - other
/** Multiplies this value by the other value. */
public inline operator fun times(other: Byte): Long =
this * other.toLong()
/** Multiplies this value by the other value. */
public inline operator fun times(other: Short): Long =
this * other.toLong()
/** Multiplies this value by the other value. */
public inline operator fun times(other: Int): Long =
this * other.toLong()
/** Multiplies this value by the other value. */
@TypedIntrinsic(IntrinsicType.TIMES)
external public operator fun times(other: Long): Long
/** Multiplies this value by the other value. */
public inline operator fun times(other: Float): Float =
this.toFloat() * other
/** Multiplies this value by the other value. */
public inline operator fun times(other: Double): Double =
this.toDouble() * other
/** Divides this value by the other value. */
public inline operator fun div(other: Byte): Long =
this / other.toLong()
/** Divides this value by the other value. */
public inline operator fun div(other: Short): Long =
this / other.toLong()
/** Divides this value by the other value. */
public inline operator fun div(other: Int): Long =
this / other.toLong()
/** Divides this value by the other value. */
@TypedIntrinsic(IntrinsicType.SIGNED_DIV)
external public operator fun div(other: Long): Long
/** Divides this value by the other value. */
public inline operator fun div(other: Float): Float =
this.toFloat() / other
/** Divides this value by the other value. */
public inline operator fun div(other: Double): Double =
this.toDouble() / other
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Byte): Long =
this % other.toLong()
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Short): Long =
this % other.toLong()
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Int): Long =
this % other.toLong()
/** Calculates the remainder of dividing this value by the other value. */
@TypedIntrinsic(IntrinsicType.SIGNED_REM)
external public operator fun rem(other: Long): Long
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Float): Float =
this.toFloat() % other
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Double): Double =
this.toDouble() % other
/** Increments this value. */
@TypedIntrinsic(IntrinsicType.INC)
external public operator fun inc(): Long
/** Decrements this value. */
@TypedIntrinsic(IntrinsicType.DEC)
external public operator fun dec(): Long
/** Returns this value. */
public inline operator fun unaryPlus(): Long =
this
/** Returns the negative of this value. */
@TypedIntrinsic(IntrinsicType.UNARY_MINUS)
external public operator fun unaryMinus(): Long
/** Creates a range from this value to the specified [other] value. */
public operator fun rangeTo(other: Byte): LongRange {
return LongRange(this, other.toLong())
}
/** Creates a range from this value to the specified [other] value. */
public operator fun rangeTo(other: Short): LongRange {
return LongRange(this, other.toLong())
}
/** Creates a range from this value to the specified [other] value. */
public operator fun rangeTo(other: Int): LongRange {
return LongRange(this, other.toLong())
}
/** Creates a range from this value to the specified [other] value. */
public operator fun rangeTo(other: Long): LongRange {
return LongRange(this, other.toLong())
}
/** Shifts this value left by the [bitCount] number of bits. */
@TypedIntrinsic(IntrinsicType.SHL)
external public infix fun shl(bitCount: Int): Long
/** Shifts this value right by the [bitCount] number of bits, filling the leftmost bits with copies of the sign bit. */
@TypedIntrinsic(IntrinsicType.SHR)
external public infix fun shr(bitCount: Int): Long
/** Shifts this value right by the [bitCount] number of bits, filling the leftmost bits with zeros. */
@TypedIntrinsic(IntrinsicType.USHR)
external public infix fun ushr(bitCount: Int): Long
/** Performs a bitwise AND operation between the two values. */
@TypedIntrinsic(IntrinsicType.AND)
external public infix fun and(other: Long): Long
/** Performs a bitwise OR operation between the two values. */
@TypedIntrinsic(IntrinsicType.OR)
external public infix fun or(other: Long): Long
/** Performs a bitwise XOR operation between the two values. */
@TypedIntrinsic(IntrinsicType.XOR)
external public infix fun xor(other: Long): Long
/** Inverts the bits in this value. */
@TypedIntrinsic(IntrinsicType.INV)
external public fun inv(): Long
/**
* Converts this [Long] value to [Byte].
*
* If this value is in [Byte.MIN_VALUE]..[Byte.MAX_VALUE], the resulting `Byte` value represents
* the same numerical value as this `Long`.
*
* The resulting `Byte` value is represented by the least significant 8 bits of this `Long` value.
*/
@TypedIntrinsic(IntrinsicType.INT_TRUNCATE)
external public override fun toByte(): Byte
/**
* Converts this [Long] value to [Char].
*
* If this value is in the range of `Char` codes `Char.MIN_VALUE..Char.MAX_VALUE`,
* the resulting `Char` code is equal to this value.
*
* The resulting `Char` code is represented by the least significant 16 bits of this `Long` value.
*/
@TypedIntrinsic(IntrinsicType.INT_TRUNCATE)
external public override fun toChar(): Char
/**
* Converts this [Long] value to [Short].
*
* If this value is in [Short.MIN_VALUE]..[Short.MAX_VALUE], the resulting `Short` value represents
* the same numerical value as this `Long`.
*
* The resulting `Short` value is represented by the least significant 16 bits of this `Long` value.
*/
@TypedIntrinsic(IntrinsicType.INT_TRUNCATE)
external public override fun toShort(): Short
/**
* Converts this [Long] value to [Int].
*
* If this value is in [Int.MIN_VALUE]..[Int.MAX_VALUE], the resulting `Int` value represents
* the same numerical value as this `Long`.
*
* The resulting `Int` value is represented by the least significant 32 bits of this `Long` value.
*/
@TypedIntrinsic(IntrinsicType.INT_TRUNCATE)
external public override fun toInt(): Int
/** Returns this value. */
public inline override fun toLong(): Long =
this
/**
* Converts this [Long] value to [Float].
*
* The resulting value is the closest `Float` to this `Long` value.
* In case when this `Long` value is exactly between two `Float`s,
* the one with zero at least significant bit of mantissa is selected.
*/
@TypedIntrinsic(IntrinsicType.SIGNED_TO_FLOAT)
external public override fun toFloat(): Float
/**
* Converts this [Long] value to [Double].
*
* The resulting value is the closest `Double` to this `Long` value.
* In case when this `Long` value is exactly between two `Double`s,
* the one with zero at least significant bit of mantissa is selected.
*/
@TypedIntrinsic(IntrinsicType.SIGNED_TO_FLOAT)
external public override fun toDouble(): Double
// Konan-specific.
public fun equals(other: Long): Boolean = kotlin.native.internal.areEqualByValue(this, other)
public override fun equals(other: Any?): Boolean =
other is Long && kotlin.native.internal.areEqualByValue(this, other)
@SymbolName("Kotlin_Long_toString")
external public override fun toString(): String
public override fun hashCode(): Int {
return ((this ushr 32) xor this).toInt()
}
}
/**
* Represents a single-precision 32-bit IEEE 754 floating point number.
*/
public final class Float private constructor() : Number(), Comparable<Float> {
companion object {
/**
* A constant holding the smallest *positive* nonzero value of Float.
*/
public const val MIN_VALUE: Float = 1.40129846432481707e-45f
/**
* A constant holding the largest positive finite value of Float.
*/
public const val MAX_VALUE: Float = 3.40282346638528860e+38f
/**
* A constant holding the positive infinity value of Float.
*/
@Suppress("DIVISION_BY_ZERO")
public const val POSITIVE_INFINITY: Float = 1.0f / 0.0f
/**
* A constant holding the negative infinity value of Float.
*/
@Suppress("DIVISION_BY_ZERO")
public const val NEGATIVE_INFINITY: Float = -1.0f / 0.0f
/**
* A constant holding the "not a number" value of Float.
*/
@Suppress("DIVISION_BY_ZERO")
public const val NaN: Float = -(0.0f / 0.0f)
/**
* The number of bytes used to represent an instance of Float in a binary form.
*/
@SinceKotlin("1.4")
public const val SIZE_BYTES: Int = 4
/**
* The number of bits used to represent an instance of Float in a binary form.
*/
@SinceKotlin("1.4")
public const val SIZE_BITS: Int = 32
}
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public operator fun compareTo(other: Byte): Int = compareTo(other.toFloat())
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public operator fun compareTo(other: Short): Int = compareTo(other.toFloat())
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public operator fun compareTo(other: Int): Int = compareTo(other.toFloat())
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public operator fun compareTo(other: Long): Int = compareTo(other.toFloat())
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public override operator fun compareTo(other: Float): Int {
// if any of values in NaN both comparisons return false
if (this > other) return 1
if (this < other) return -1
val thisBits = this.toBits()
val otherBits = other.toBits()
// Canonical NaN bits representation higher than any other bit representvalue
return thisBits.compareTo(otherBits)
}
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public operator fun compareTo(other: Double): Int = - other.compareTo(this)
/** Adds the other value to this value. */
public inline operator fun plus(other: Byte): Float =
this + other.toFloat()
/** Adds the other value to this value. */
public inline operator fun plus(other: Short): Float =
this + other.toFloat()
/** Adds the other value to this value. */
public inline operator fun plus(other: Int): Float =
this + other.toFloat()
/** Adds the other value to this value. */
public inline operator fun plus(other: Long): Float =
this + other.toFloat()
/** Adds the other value to this value. */
@TypedIntrinsic(IntrinsicType.PLUS)
external public operator fun plus(other: Float): Float
/** Adds the other value to this value. */
public inline operator fun plus(other: Double): Double =
this.toDouble() + other
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Byte): Float =
this - other.toFloat()
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Short): Float =
this - other.toFloat()
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Int): Float =
this - other.toFloat()
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Long): Float =
this - other.toFloat()
/** Subtracts the other value from this value. */
@TypedIntrinsic(IntrinsicType.MINUS)
external public operator fun minus(other: Float): Float
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Double): Double =
this.toDouble() - other
/** Multiplies this value by the other value. */
public inline operator fun times(other: Byte): Float =
this * other.toFloat()
/** Multiplies this value by the other value. */
public inline operator fun times(other: Short): Float =
this * other.toFloat()
/** Multiplies this value by the other value. */
public inline operator fun times(other: Int): Float =
this * other.toFloat()
/** Multiplies this value by the other value. */
public inline operator fun times(other: Long): Float =
this * other.toFloat()
/** Multiplies this value by the other value. */
@TypedIntrinsic(IntrinsicType.TIMES)
external public operator fun times(other: Float): Float
/** Multiplies this value by the other value. */
public inline operator fun times(other: Double): Double =
this.toDouble() * other
/** Divides this value by the other value. */
public inline operator fun div(other: Byte): Float =
this / other.toFloat()
/** Divides this value by the other value. */
public inline operator fun div(other: Short): Float =
this / other.toFloat()
/** Divides this value by the other value. */
public inline operator fun div(other: Int): Float =
this / other.toFloat()
/** Divides this value by the other value. */
public inline operator fun div(other: Long): Float =
this / other.toFloat()
/** Divides this value by the other value. */
@TypedIntrinsic(IntrinsicType.SIGNED_DIV)
external public operator fun div(other: Float): Float
/** Divides this value by the other value. */
public inline operator fun div(other: Double): Double =
this.toDouble() / other
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Byte): Float =
this % other.toFloat()
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Short): Float =
this % other.toFloat()
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Int): Float =
this % other.toFloat()
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Long): Float =
this % other.toFloat()
/** Calculates the remainder of dividing this value by the other value. */
@TypedIntrinsic(IntrinsicType.SIGNED_REM)
external public operator fun rem(other: Float): Float
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Double): Double =
this.toDouble() % other
/** Increments this value. */
@TypedIntrinsic(IntrinsicType.INC)
external public operator fun inc(): Float
/** Decrements this value. */
@TypedIntrinsic(IntrinsicType.DEC)
external public operator fun dec(): Float
/** Returns this value. */
@TypedIntrinsic(IntrinsicType.UNARY_PLUS)
external public operator fun unaryPlus(): Float
/** Returns the negative of this value. */
@TypedIntrinsic(IntrinsicType.UNARY_MINUS)
external public operator fun unaryMinus(): Float
/**
* Converts this [Float] value to [Byte].
*
* The resulting `Byte` value is equal to `this.toInt().toByte()`.
*/
@Deprecated("Unclear conversion. To achieve the same result convert to Int explicitly and then to Byte.", ReplaceWith("toInt().toByte()"))
public override fun toByte(): Byte = this.toInt().toByte()
/**
* Converts this [Float] value to [Char].
*
* The resulting `Char` value is equal to `this.toInt().toChar()`.
*/
public override fun toChar(): Char = this.toInt().toChar()
/**
* Converts this [Float] value to [Short].
*
* The resulting `Short` value is equal to `this.toInt().toShort()`.
*/
@Deprecated("Unclear conversion. To achieve the same result convert to Int explicitly and then to Short.", ReplaceWith("toInt().toShort()"))
public override fun toShort(): Short = this.toInt().toShort()
/**
* Converts this [Float] value to [Int].
*
* The fractional part, if any, is rounded down.
* Returns zero if this `Float` value is `NaN`, [Int.MIN_VALUE] if it's less than `Int.MIN_VALUE`,
* [Int.MAX_VALUE] if it's bigger than `Int.MAX_VALUE`.
*/
@SymbolName("Kotlin_Float_toInt")
external public override fun toInt(): Int
/**
* Converts this [Float] value to [Long].
*
* The fractional part, if any, is rounded down.
* Returns zero if this `Float` value is `NaN`, [Long.MIN_VALUE] if it's less than `Long.MIN_VALUE`,
* [Long.MAX_VALUE] if it's bigger than `Long.MAX_VALUE`.
*/
@SymbolName("Kotlin_Float_toLong")
external public override fun toLong(): Long
/** Returns this value. */
public inline override fun toFloat(): Float =
this
/**
* Converts this [Float] value to [Double].
*
* The resulting `Double` value represents the same numerical value as this `Float`.
*/
@TypedIntrinsic(IntrinsicType.FLOAT_EXTEND)
external public override fun toDouble(): Double
public fun equals(other: Float): Boolean = toBits() == other.toBits()
public override fun equals(other: Any?): Boolean = other is Float && this.equals(other)
public override fun toString() = NumberConverter.convert(this)
public override fun hashCode(): Int {
return bits()
}
@TypedIntrinsic(IntrinsicType.REINTERPRET)
@PublishedApi
external internal fun bits(): Int
}
/**
* Represents a double-precision 64-bit IEEE 754 floating point number.
*/
public final class Double private constructor() : Number(), Comparable<Double> {
companion object {
/**
* A constant holding the smallest *positive* nonzero value of Double.
*/
public const val MIN_VALUE: Double = 4.9e-324
/**
* A constant holding the largest positive finite value of Double.
*/
public const val MAX_VALUE: Double = 1.7976931348623157e+308
/**
* A constant holding the positive infinity value of Double.
*/
@Suppress("DIVISION_BY_ZERO")
public const val POSITIVE_INFINITY: Double = 1.0 / 0.0
/**
* A constant holding the negative infinity value of Double.
*/
@Suppress("DIVISION_BY_ZERO")
public const val NEGATIVE_INFINITY: Double = -1.0 / 0.0
/**
* A constant holding the "not a number" value of Double.
*/
@Suppress("DIVISION_BY_ZERO")
public const val NaN: Double = -(0.0 / 0.0)
/**
* The number of bytes used to represent an instance of Double in a binary form.
*/
@SinceKotlin("1.4")
public const val SIZE_BYTES: Int = 8
/**
* The number of bits used to represent an instance of Double in a binary form.
*/
@SinceKotlin("1.4")
public const val SIZE_BITS: Int = 64
}
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public operator fun compareTo(other: Byte): Int = compareTo(other.toDouble())
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public operator fun compareTo(other: Short): Int = compareTo(other.toDouble())
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public operator fun compareTo(other: Int): Int = compareTo(other.toDouble())
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public operator fun compareTo(other: Long): Int = compareTo(other.toDouble())
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public operator fun compareTo(other: Float): Int = compareTo(other.toDouble())
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
public override operator fun compareTo(other: Double): Int {
// if any of values in NaN both comparisons return false
if (this > other) return 1
if (this < other) return -1
val thisBits = this.toBits()
val otherBits = other.toBits()
// Canonical NaN bits representation higher than any other bit representvalue
return thisBits.compareTo(otherBits)
}
/** Adds the other value to this value. */
public inline operator fun plus(other: Byte): Double =
this + other.toDouble()
/** Adds the other value to this value. */
public inline operator fun plus(other: Short): Double =
this + other.toDouble()
/** Adds the other value to this value. */
public inline operator fun plus(other: Int): Double =
this + other.toDouble()
/** Adds the other value to this value. */
public inline operator fun plus(other: Long): Double =
this + other.toDouble()
/** Adds the other value to this value. */
public inline operator fun plus(other: Float): Double =
this + other.toDouble()
/** Adds the other value to this value. */
@TypedIntrinsic(IntrinsicType.PLUS)
external public operator fun plus(other: Double): Double
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Byte): Double =
this - other.toDouble()
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Short): Double =
this - other.toDouble()
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Int): Double =
this - other.toDouble()
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Long): Double =
this - other.toDouble()
/** Subtracts the other value from this value. */
public inline operator fun minus(other: Float): Double =
this - other.toDouble()
/** Subtracts the other value from this value. */
@TypedIntrinsic(IntrinsicType.MINUS)
external public operator fun minus(other: Double): Double
/** Multiplies this value by the other value. */
public inline operator fun times(other: Byte): Double =
this * other.toDouble()
/** Multiplies this value by the other value. */
public inline operator fun times(other: Short): Double =
this * other.toDouble()
/** Multiplies this value by the other value. */
public inline operator fun times(other: Int): Double =
this * other.toDouble()
/** Multiplies this value by the other value. */
public inline operator fun times(other: Long): Double =
this * other.toDouble()
/** Multiplies this value by the other value. */
public inline operator fun times(other: Float): Double =
this * other.toDouble()
/** Multiplies this value by the other value. */
@TypedIntrinsic(IntrinsicType.TIMES)
external public operator fun times(other: Double): Double
/** Divides this value by the other value. */
public inline operator fun div(other: Byte): Double =
this / other.toDouble()
/** Divides this value by the other value. */
public inline operator fun div(other: Short): Double =
this / other.toDouble()
/** Divides this value by the other value. */
public inline operator fun div(other: Int): Double =
this / other.toDouble()
/** Divides this value by the other value. */
public inline operator fun div(other: Long): Double =
this / other.toDouble()
/** Divides this value by the other value. */
public inline operator fun div(other: Float): Double =
this / other.toDouble()
/** Divides this value by the other value. */
@TypedIntrinsic(IntrinsicType.SIGNED_DIV)
external public operator fun div(other: Double): Double
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Byte): Double =
this % other.toDouble()
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Short): Double =
this % other.toDouble()
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Int): Double =
this % other.toDouble()
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Long): Double =
this % other.toDouble()
/** Calculates the remainder of dividing this value by the other value. */
public inline operator fun rem(other: Float): Double =
this % other.toDouble()
/** Calculates the remainder of dividing this value by the other value. */
@TypedIntrinsic(IntrinsicType.SIGNED_REM)
external public operator fun rem(other: Double): Double
/** Increments this value. */
@TypedIntrinsic(IntrinsicType.INC)
external public operator fun inc(): Double
/** Decrements this value. */
@TypedIntrinsic(IntrinsicType.DEC)
external public operator fun dec(): Double
/** Returns this value. */
@TypedIntrinsic(IntrinsicType.UNARY_PLUS)
external public operator fun unaryPlus(): Double
/** Returns the negative of this value. */
@TypedIntrinsic(IntrinsicType.UNARY_MINUS)
external public operator fun unaryMinus(): Double
/**
* Converts this [Double] value to [Byte].
*
* The resulting `Byte` value is equal to `this.toInt().toByte()`.
*/
@Deprecated("Unclear conversion. To achieve the same result convert to Int explicitly and then to Byte.", ReplaceWith("toInt().toByte()"))
public override fun toByte(): Byte = this.toInt().toByte()
/**
* Converts this [Double] value to [Char].
*
* The resulting `Char` value is equal to `this.toInt().toChar()`.
*/
public override fun toChar(): Char = this.toInt().toChar()
/**
* Converts this [Double] value to [Short].
*
* The resulting `Short` value is equal to `this.toInt().toShort()`.
*/
@Deprecated("Unclear conversion. To achieve the same result convert to Int explicitly and then to Short.", ReplaceWith("toInt().toShort()"))
public override fun toShort(): Short = this.toInt().toShort()
/**
* Converts this [Double] value to [Int].
*
* The fractional part, if any, is rounded down.
* Returns zero if this `Double` value is `NaN`, [Int.MIN_VALUE] if it's less than `Int.MIN_VALUE`,
* [Int.MAX_VALUE] if it's bigger than `Int.MAX_VALUE`.
*/
@SymbolName("Kotlin_Double_toInt")
external public override fun toInt(): Int
/**
* Converts this [Double] value to [Long].
*
* The fractional part, if any, is rounded down.
* Returns zero if this `Double` value is `NaN`, [Long.MIN_VALUE] if it's less than `Long.MIN_VALUE`,
* [Long.MAX_VALUE] if it's bigger than `Long.MAX_VALUE`.
*/
@SymbolName("Kotlin_Double_toLong")
external public override fun toLong(): Long
/**
* Converts this [Double] value to [Float].
*
* The resulting value is the closest `Float` to this `Double` value.
* In case when this `Double` value is exactly between two `Float`s,
* the one with zero at least significant bit of mantissa is selected.
*/
@TypedIntrinsic(IntrinsicType.FLOAT_TRUNCATE)
external public override fun toFloat(): Float
/** Returns this value. */
public inline override fun toDouble(): Double =
this
public fun equals(other: Double): Boolean = toBits() == other.toBits()
public override fun equals(other: Any?): Boolean = other is Double && this.equals(other)
public override fun toString(): String = NumberConverter.convert(this)
public override fun hashCode(): Int = bits().hashCode()
@TypedIntrinsic(IntrinsicType.REINTERPRET)
@PublishedApi
external internal fun bits(): Long
}
| apache-2.0 | c17f4b31ca9d7c7599586f3c13a23487 | 41.817102 | 144 | 0.648022 | 4.546567 | false | false | false | false |
loxal/FreeEthereum | free-ethereum-core/src/test/java/org/ethereum/vm/MemoryTest.kt | 1 | 14947 | /*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* 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 org.ethereum.vm
import org.ethereum.vm.program.Memory
import org.junit.Assert.*
import org.junit.Test
import org.spongycastle.util.encoders.Hex
import java.lang.Math.ceil
import java.util.*
class MemoryTest {
@Test
fun testExtend() {
checkMemoryExtend(0)
checkMemoryExtend(1)
checkMemoryExtend(WORD_SIZE)
checkMemoryExtend(WORD_SIZE * 2)
checkMemoryExtend(CHUNK_SIZE - 1)
checkMemoryExtend(CHUNK_SIZE)
checkMemoryExtend(CHUNK_SIZE + 1)
checkMemoryExtend(2000)
}
@Test
fun memorySave_1() {
val memoryBuffer = Memory()
val data = byteArrayOf(1, 1, 1, 1)
memoryBuffer.write(0, data, data.size, false)
assertTrue(1 == memoryBuffer.chunks.size)
val chunk = memoryBuffer.chunks[0]
assertTrue(chunk[0].toInt() == 1)
assertTrue(chunk[1].toInt() == 1)
assertTrue(chunk[2].toInt() == 1)
assertTrue(chunk[3].toInt() == 1)
assertTrue(chunk[4].toInt() == 0)
assertTrue(memoryBuffer.size() == 32)
}
@Test
fun memorySave_2() {
val memoryBuffer = Memory()
val data = Hex.decode("0101010101010101010101010101010101010101010101010101010101010101")
memoryBuffer.write(0, data, data.size, false)
assertTrue(1 == memoryBuffer.chunks.size)
val chunk = memoryBuffer.chunks[0]
assertTrue(chunk[0].toInt() == 1)
assertTrue(chunk[1].toInt() == 1)
assertTrue(chunk[30].toInt() == 1)
assertTrue(chunk[31].toInt() == 1)
assertTrue(chunk[32].toInt() == 0)
assertTrue(memoryBuffer.size() == 32)
}
@Test
fun memorySave_3() {
val memoryBuffer = Memory()
val data = Hex.decode("010101010101010101010101010101010101010101010101010101010101010101")
memoryBuffer.write(0, data, data.size, false)
assertTrue(1 == memoryBuffer.chunks.size)
val chunk = memoryBuffer.chunks[0]
assertTrue(chunk[0].toInt() == 1)
assertTrue(chunk[1].toInt() == 1)
assertTrue(chunk[30].toInt() == 1)
assertTrue(chunk[31].toInt() == 1)
assertTrue(chunk[32].toInt() == 1)
assertTrue(chunk[33].toInt() == 0)
assertTrue(memoryBuffer.size() == 64)
}
@Test
fun memorySave_4() {
val memoryBuffer = Memory()
val data = ByteArray(1024)
Arrays.fill(data, 1.toByte())
memoryBuffer.write(0, data, data.size, false)
assertTrue(1 == memoryBuffer.chunks.size)
val chunk = memoryBuffer.chunks[0]
assertTrue(chunk[0].toInt() == 1)
assertTrue(chunk[1].toInt() == 1)
assertTrue(chunk[1022].toInt() == 1)
assertTrue(chunk[1023].toInt() == 1)
assertTrue(memoryBuffer.size() == 1024)
}
@Test
fun memorySave_5() {
val memoryBuffer = Memory()
val data = ByteArray(1025)
Arrays.fill(data, 1.toByte())
memoryBuffer.write(0, data, data.size, false)
assertTrue(2 == memoryBuffer.chunks.size)
val chunk1 = memoryBuffer.chunks[0]
assertTrue(chunk1[0].toInt() == 1)
assertTrue(chunk1[1].toInt() == 1)
assertTrue(chunk1[1022].toInt() == 1)
assertTrue(chunk1[1023].toInt() == 1)
val chunk2 = memoryBuffer.chunks[1]
assertTrue(chunk2[0].toInt() == 1)
assertTrue(chunk2[1].toInt() == 0)
assertTrue(memoryBuffer.size() == 1056)
}
@Test
fun memorySave_6() {
val memoryBuffer = Memory()
val data1 = ByteArray(1024)
Arrays.fill(data1, 1.toByte())
val data2 = ByteArray(1024)
Arrays.fill(data2, 2.toByte())
memoryBuffer.write(0, data1, data1.size, false)
memoryBuffer.write(1024, data2, data2.size, false)
assertTrue(2 == memoryBuffer.chunks.size)
val chunk1 = memoryBuffer.chunks[0]
assertTrue(chunk1[0].toInt() == 1)
assertTrue(chunk1[1].toInt() == 1)
assertTrue(chunk1[1022].toInt() == 1)
assertTrue(chunk1[1023].toInt() == 1)
val chunk2 = memoryBuffer.chunks[1]
assertTrue(chunk2[0].toInt() == 2)
assertTrue(chunk2[1].toInt() == 2)
assertTrue(chunk2[1022].toInt() == 2)
assertTrue(chunk2[1023].toInt() == 2)
assertTrue(memoryBuffer.size() == 2048)
}
@Test
fun memorySave_7() {
val memoryBuffer = Memory()
val data1 = ByteArray(1024)
Arrays.fill(data1, 1.toByte())
val data2 = ByteArray(1024)
Arrays.fill(data2, 2.toByte())
val data3 = ByteArray(1)
Arrays.fill(data3, 3.toByte())
memoryBuffer.write(0, data1, data1.size, false)
memoryBuffer.write(1024, data2, data2.size, false)
memoryBuffer.write(2048, data3, data3.size, false)
assertTrue(3 == memoryBuffer.chunks.size)
val chunk1 = memoryBuffer.chunks[0]
assertTrue(chunk1[0].toInt() == 1)
assertTrue(chunk1[1].toInt() == 1)
assertTrue(chunk1[1022].toInt() == 1)
assertTrue(chunk1[1023].toInt() == 1)
val chunk2 = memoryBuffer.chunks[1]
assertTrue(chunk2[0].toInt() == 2)
assertTrue(chunk2[1].toInt() == 2)
assertTrue(chunk2[1022].toInt() == 2)
assertTrue(chunk2[1023].toInt() == 2)
val chunk3 = memoryBuffer.chunks[2]
assertTrue(chunk3[0].toInt() == 3)
assertTrue(memoryBuffer.size() == 2080)
}
@Test
fun memorySave_8() {
val memoryBuffer = Memory()
val data1 = ByteArray(128)
Arrays.fill(data1, 1.toByte())
memoryBuffer.extendAndWrite(0, 256, data1)
var ones = 0
var zeroes = 0
for (i in 0..memoryBuffer.size() - 1) {
if (memoryBuffer.readByte(i).toInt() == 1) ++ones
if (memoryBuffer.readByte(i).toInt() == 0) ++zeroes
}
assertTrue(ones == zeroes)
assertTrue(256 == memoryBuffer.size())
}
@Test
fun memoryLoad_1() {
val memoryBuffer = Memory()
val value = memoryBuffer.readWord(100)
assertTrue(value.intValue() == 0)
assertTrue(memoryBuffer.chunks.size == 1)
assertTrue(memoryBuffer.size() == 32 * 5)
}
@Test
fun memoryLoad_2() {
val memoryBuffer = Memory()
val value = memoryBuffer.readWord(2015)
assertTrue(value.intValue() == 0)
assertTrue(memoryBuffer.chunks.size == 2)
assertTrue(memoryBuffer.size() == 2048)
}
@Test
fun memoryLoad_3() {
val memoryBuffer = Memory()
val value = memoryBuffer.readWord(2016)
assertTrue(value.intValue() == 0)
assertTrue(memoryBuffer.chunks.size == 2)
assertTrue(memoryBuffer.size() == 2048)
}
@Test
fun memoryLoad_4() {
val memoryBuffer = Memory()
val value = memoryBuffer.readWord(2017)
assertTrue(value.intValue() == 0)
assertTrue(memoryBuffer.chunks.size == 3)
assertTrue(memoryBuffer.size() == 2080)
}
@Test
fun memoryLoad_5() {
val memoryBuffer = Memory()
val data1 = ByteArray(1024)
Arrays.fill(data1, 1.toByte())
val data2 = ByteArray(1024)
Arrays.fill(data2, 2.toByte())
memoryBuffer.write(0, data1, data1.size, false)
memoryBuffer.write(1024, data2, data2.size, false)
assertTrue(memoryBuffer.chunks.size == 2)
assertTrue(memoryBuffer.size() == 2048)
val val1 = memoryBuffer.readWord(0x3df)
val val2 = memoryBuffer.readWord(0x3e0)
val val3 = memoryBuffer.readWord(0x3e1)
assertArrayEquals(
Hex.decode("0101010101010101010101010101010101010101010101010101010101010101"),
val1.data)
assertArrayEquals(
Hex.decode("0101010101010101010101010101010101010101010101010101010101010101"),
val2.data)
assertArrayEquals(
Hex.decode("0101010101010101010101010101010101010101010101010101010101010102"),
val3.data)
assertTrue(memoryBuffer.size() == 2048)
}
@Test
fun memoryChunk_1() {
val memoryBuffer = Memory()
val data1 = ByteArray(32)
Arrays.fill(data1, 1.toByte())
val data2 = ByteArray(32)
Arrays.fill(data2, 2.toByte())
memoryBuffer.write(0, data1, data1.size, false)
memoryBuffer.write(32, data2, data2.size, false)
val data = memoryBuffer.read(0, 64)
assertArrayEquals(
Hex.decode("0101010101010101010101010101010101010101010101010101010101010101" + "0202020202020202020202020202020202020202020202020202020202020202"),
data
)
assertEquals(64, memoryBuffer.size().toLong())
}
@Test
fun memoryChunk_2() {
val memoryBuffer = Memory()
val data1 = ByteArray(32)
Arrays.fill(data1, 1.toByte())
memoryBuffer.write(0, data1, data1.size, false)
assertTrue(32 == memoryBuffer.size())
val data = memoryBuffer.read(0, 64)
assertArrayEquals(
Hex.decode("0101010101010101010101010101010101010101010101010101010101010101" + "0000000000000000000000000000000000000000000000000000000000000000"),
data
)
assertEquals(64, memoryBuffer.size().toLong())
}
@Test
fun memoryChunk_3() {
val memoryBuffer = Memory()
val data1 = ByteArray(1024)
Arrays.fill(data1, 1.toByte())
val data2 = ByteArray(1024)
Arrays.fill(data2, 2.toByte())
memoryBuffer.write(0, data1, data1.size, false)
memoryBuffer.write(1024, data2, data2.size, false)
val data = memoryBuffer.read(0, 2048)
var ones = 0
var twos = 0
for (aData in data) {
if (aData.toInt() == 1) ++ones
if (aData.toInt() == 2) ++twos
}
assertTrue(ones == twos)
assertTrue(2048 == memoryBuffer.size())
}
@Test
fun memoryChunk_4() {
val memoryBuffer = Memory()
val data1 = ByteArray(1024)
Arrays.fill(data1, 1.toByte())
val data2 = ByteArray(1024)
Arrays.fill(data2, 2.toByte())
memoryBuffer.write(0, data1, data1.size, false)
memoryBuffer.write(1024, data2, data2.size, false)
val data = memoryBuffer.read(0, 2049)
var ones = 0
var twos = 0
var zero = 0
for (aData in data) {
if (aData.toInt() == 1) ++ones
if (aData.toInt() == 2) ++twos
if (aData.toInt() == 0) ++zero
}
assertTrue(zero == 1)
assertTrue(ones == twos)
assertTrue(2080 == memoryBuffer.size())
}
@Test
fun memoryWriteLimited_1() {
val memoryBuffer = Memory()
memoryBuffer.extend(0, 3072)
val data1 = ByteArray(6272)
Arrays.fill(data1, 1.toByte())
memoryBuffer.write(2720, data1, data1.size, true)
val lastZero = memoryBuffer.readByte(2719)
val firstOne = memoryBuffer.readByte(2721)
assertTrue(memoryBuffer.size() == 3072)
assertTrue(lastZero.toInt() == 0)
assertTrue(firstOne.toInt() == 1)
val data = memoryBuffer.read(2720, 352)
var ones = 0
var zero = 0
for (aData in data) {
if (aData.toInt() == 1) ++ones
if (aData.toInt() == 0) ++zero
}
assertTrue(ones == data.size)
assertTrue(zero == 0)
}
@Test
fun memoryWriteLimited_2() {
val memoryBuffer = Memory()
memoryBuffer.extend(0, 3072)
val data1 = ByteArray(6272)
Arrays.fill(data1, 1.toByte())
memoryBuffer.write(2720, data1, 300, true)
val lastZero = memoryBuffer.readByte(2719)
val firstOne = memoryBuffer.readByte(2721)
assertTrue(memoryBuffer.size() == 3072)
assertTrue(lastZero.toInt() == 0)
assertTrue(firstOne.toInt() == 1)
val data = memoryBuffer.read(2720, 352)
var ones = 0
var zero = 0
for (aData in data) {
if (aData.toInt() == 1) ++ones
if (aData.toInt() == 0) ++zero
}
assertTrue(ones == 300)
assertTrue(zero == 52)
}
@Test
fun memoryWriteLimited_3() {
val memoryBuffer = Memory()
memoryBuffer.extend(0, 128)
val data1 = ByteArray(20)
Arrays.fill(data1, 1.toByte())
memoryBuffer.write(10, data1, 40, true)
val lastZero = memoryBuffer.readByte(9)
val firstOne = memoryBuffer.readByte(10)
assertTrue(memoryBuffer.size() == 128)
assertTrue(lastZero.toInt() == 0)
assertTrue(firstOne.toInt() == 1)
val data = memoryBuffer.read(10, 30)
var ones = 0
var zero = 0
for (aData in data) {
if (aData.toInt() == 1) ++ones
if (aData.toInt() == 0) ++zero
}
assertTrue(ones == 20)
assertTrue(zero == 10)
}
companion object {
private val WORD_SIZE = 32
private val CHUNK_SIZE = 1024
private fun checkMemoryExtend(dataSize: Int) {
val memory = Memory()
memory.extend(0, dataSize)
assertEquals(calcSize(dataSize, CHUNK_SIZE).toLong(), memory.internalSize().toLong())
assertEquals(calcSize(dataSize, WORD_SIZE).toLong(), memory.size().toLong())
}
private fun calcSize(dataSize: Int, chunkSize: Int): Int {
return ceil(dataSize.toDouble() / chunkSize).toInt() * chunkSize
}
}
} | mit | 645d6981f1ccb2dec8b7c52bb64479f1 | 26.477941 | 164 | 0.594768 | 3.859282 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/analysis-api-providers-ide-impl/test/org/jetbrains/kotlin/idea/fir/analysis/providers/trackers/KotlinModuleOutOfBlockTrackerTest.kt | 1 | 8180 | // 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.fir.analysis.providers.trackers
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ModificationTracker
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiManager
import com.intellij.testFramework.PsiTestUtil
import junit.framework.Assert
import org.jetbrains.kotlin.analysis.providers.createModuleWithoutDependenciesOutOfBlockModificationTracker
import org.jetbrains.kotlin.analysis.providers.createProjectWideOutOfBlockModificationTracker
import org.jetbrains.kotlin.idea.caches.project.productionSourceInfo
import org.jetbrains.kotlin.idea.fir.analysis.project.structure.getMainKtSourceModule
import org.jetbrains.kotlin.idea.stubs.AbstractMultiModuleTest
import org.jetbrains.kotlin.idea.util.sourceRoots
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtPsiFactory
import java.io.File
import java.nio.file.Files
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.writeText
class KotlinModuleOutOfBlockTrackerTest : AbstractMultiModuleTest() {
override fun getTestDataDirectory(): File = error("Should not be called")
fun testThatModuleOutOfBlockChangeInfluenceOnlySingleModule() {
val moduleA = createModuleWithModificationTracker("a") {
listOf(
FileWithText("main.kt", "fun main() = 10")
)
}
val moduleB = createModuleWithModificationTracker("b")
val moduleC = createModuleWithModificationTracker("c")
val moduleAWithTracker = ModuleWithModificationTracker(moduleA)
val moduleBWithTracker = ModuleWithModificationTracker(moduleB)
val moduleCWithTracker = ModuleWithModificationTracker(moduleC)
moduleA.typeInFunctionBody("main.kt", textAfterTyping = "fun main() = hello10")
Assert.assertTrue(
"Out of block modification count for module A with out of block should change after typing, modification count is ${moduleAWithTracker.modificationCount}",
moduleAWithTracker.changed()
)
Assert.assertFalse(
"Out of block modification count for module B without out of block should not change after typing, modification count is ${moduleBWithTracker.modificationCount}",
moduleBWithTracker.changed()
)
Assert.assertFalse(
"Out of block modification count for module C without out of block should not change after typing, modification count is ${moduleCWithTracker.modificationCount}",
moduleCWithTracker.changed()
)
}
fun testThatInEveryModuleOutOfBlockWillHappenAfterContentRootChange() {
val moduleA = createModuleWithModificationTracker("a")
val moduleB = createModuleWithModificationTracker("b")
val moduleC = createModuleWithModificationTracker("c")
val moduleAWithTracker = ModuleWithModificationTracker(moduleA)
val moduleBWithTracker = ModuleWithModificationTracker(moduleB)
val moduleCWithTracker = ModuleWithModificationTracker(moduleC)
runWriteAction {
moduleA.sourceRoots.first().createChildData(/* requestor = */ null, "file.kt")
}
Assert.assertTrue(
"Out of block modification count for module A should change after content root change, modification count is ${moduleAWithTracker.modificationCount}",
moduleAWithTracker.changed()
)
Assert.assertTrue(
"Out of block modification count for module B should change after content root change, modification count is ${moduleBWithTracker.modificationCount}",
moduleBWithTracker.changed()
)
Assert.assertTrue(
"Out of block modification count for module C should change after content root change modification count is ${moduleCWithTracker.modificationCount}",
moduleCWithTracker.changed()
)
}
fun testThatNonPhysicalFileChangeNotCausingBOOM() {
val moduleA = createModuleWithModificationTracker("a") {
listOf(
FileWithText("main.kt", "fun main() {}")
)
}
val moduleB = createModuleWithModificationTracker("b")
val moduleAWithTracker = ModuleWithModificationTracker(moduleA)
val moduleBWithTracker = ModuleWithModificationTracker(moduleB)
val projectWithModificationTracker = ProjectWithModificationTracker(project)
runWriteAction {
val nonPhysicalPsi = KtPsiFactory(moduleA.project).createFile("nonPhysical", "val a = c")
nonPhysicalPsi.add(KtPsiFactory(moduleA.project).createFunction("fun x(){}"))
}
Assert.assertFalse(
"Out of block modification count for module A should not change after non physical file change, modification count is ${moduleAWithTracker.modificationCount}",
moduleAWithTracker.changed()
)
Assert.assertFalse(
"Out of block modification count for module B should not change after non physical file change, modification count is ${moduleBWithTracker.modificationCount}",
moduleBWithTracker.changed()
)
Assert.assertFalse(
"Out of block modification count for project should not change after non physical file change, modification count is ${projectWithModificationTracker.modificationCount}",
projectWithModificationTracker.changed()
)
}
private fun Module.typeInFunctionBody(fileName: String, textAfterTyping: String) {
val file = "${sourceRoots.first().url}/$fileName"
val virtualFile = VirtualFileManager.getInstance().findFileByUrl(file)!!
val ktFile = PsiManager.getInstance(project).findFile(virtualFile) as KtFile
configureByExistingFile(virtualFile)
val singleFunction = ktFile.declarations.single() as KtNamedFunction
editor.caretModel.moveToOffset(singleFunction.bodyExpression!!.textOffset)
type("hello")
PsiDocumentManager.getInstance(project).commitAllDocuments()
Assert.assertEquals(textAfterTyping, ktFile.text)
}
@OptIn(ExperimentalPathApi::class)
private fun createModuleWithModificationTracker(
name: String,
createFiles: () -> List<FileWithText> = { emptyList() },
): Module {
val tmpDir = createTempDirectory().toPath()
createFiles().forEach { file ->
Files.createFile(tmpDir.resolve(file.name)).writeText(file.text)
}
val module: Module = createModule("$tmpDir/$name", moduleType)
val root = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tmpDir.toFile())!!
WriteCommandAction.writeCommandAction(module.project).run<RuntimeException> {
root.refresh(false, true)
}
PsiTestUtil.addSourceContentToRoots(module, root)
return module
}
private data class FileWithText(val name: String, val text: String)
abstract class WithModificationTracker(protected val modificationTracker: ModificationTracker) {
private val initialModificationCount = modificationTracker.modificationCount
val modificationCount: Long get() = modificationTracker.modificationCount
fun changed(): Boolean =
modificationTracker.modificationCount != initialModificationCount
}
private class ModuleWithModificationTracker(module: Module) : WithModificationTracker(
module.getMainKtSourceModule()!!.createModuleWithoutDependenciesOutOfBlockModificationTracker(module.project)
)
private class ProjectWithModificationTracker(project: Project) : WithModificationTracker(
project.createProjectWideOutOfBlockModificationTracker()
)
} | apache-2.0 | 66edf82c932fe02f1ad5ec4d318536f2 | 46.017241 | 182 | 0.732641 | 5.842857 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/uast/uast-kotlin/src/org/jetbrains/uast/kotlin/kotlinPsiElementMapping.kt | 5 | 33951 | // 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.uast.kotlin
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.elements.*
import org.jetbrains.kotlin.kdoc.psi.impl.KDocName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.uast.*
import org.jetbrains.uast.expressions.UInjectionHost
import org.jetbrains.uast.kotlin.psi.*
import org.jetbrains.uast.psi.UElementWithLocation
import org.jetbrains.uast.util.ClassSet
import org.jetbrains.uast.util.classSetOf
import org.jetbrains.uast.util.emptyClassSet
private val checkCanConvert = Registry.`is`("kotlin.uast.use.psi.type.precheck", true)
internal fun canConvert(element: PsiElement, targets: Array<out Class<out UElement>>): Boolean {
if (!checkCanConvert) return true
val psiElementClass = element.javaClass
if (targets.any { getPossibleSourceTypes(it).let { psiElementClass in it } })
return true
val ktOriginalCls = (element as? KtLightElementBase)?.kotlinOrigin?.javaClass ?: return false
return targets.any { getPossibleSourceTypes(it).let { ktOriginalCls in it } }
}
internal fun getPossibleSourceTypes(uastType: Class<out UElement>) =
possibleSourceTypes[uastType] ?: emptyClassSet()
/**
* For every [UElement] subtype states from which [PsiElement] subtypes it can be obtained.
*
* This map is machine generated by `KotlinUastMappingsAccountantOverLargeProjectTest`
*/
@Suppress("DEPRECATION", "RemoveExplicitTypeArguments", "DuplicatedCode")
private val possibleSourceTypes = mapOf<Class<*>, ClassSet<PsiElement>>(
UAnchorOwner::class.java to classSetOf<PsiElement>(
KtAnnotationEntry::class.java,
KtCallExpression::class.java,
KtClass::class.java,
KtDestructuringDeclarationEntry::class.java,
KtEnumEntry::class.java,
KtFile::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightClass::class.java,
KtLightDeclaration::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtLightParameter::class.java,
KtNamedFunction::class.java,
KtObjectDeclaration::class.java,
KtParameter::class.java,
KtPrimaryConstructor::class.java,
KtProperty::class.java,
KtPropertyAccessor::class.java,
KtSecondaryConstructor::class.java,
KtTypeReference::class.java,
UastFakeLightMethod::class.java,
UastFakeLightPrimaryConstructor::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java,
UastKotlinPsiVariable::class.java
),
UAnnotated::class.java to classSetOf<PsiElement>(
FakeFileForLightClass::class.java,
KtAnnotatedExpression::class.java,
KtArrayAccessExpression::class.java,
KtBinaryExpression::class.java,
KtBinaryExpressionWithTypeRHS::class.java,
KtBlockExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtBreakExpression::class.java,
KtCallExpression::class.java,
KtCallableReferenceExpression::class.java,
KtClass::class.java,
KtClassBody::class.java,
KtClassInitializer::class.java,
KtClassLiteralExpression::class.java,
KtCollectionLiteralExpression::class.java,
KtConstantExpression::class.java,
KtConstructorCalleeExpression::class.java,
KtConstructorDelegationCall::class.java,
KtConstructorDelegationReferenceExpression::class.java,
KtContinueExpression::class.java,
KtDelegatedSuperTypeEntry::class.java,
KtDestructuringDeclaration::class.java,
KtDestructuringDeclarationEntry::class.java,
KtDoWhileExpression::class.java,
KtDotQualifiedExpression::class.java,
KtEnumEntry::class.java,
KtEnumEntrySuperclassReferenceExpression::class.java,
KtEscapeStringTemplateEntry::class.java,
KtFile::class.java,
KtForExpression::class.java,
KtFunctionLiteral::class.java,
KtIfExpression::class.java,
KtIsExpression::class.java,
KtLabelReferenceExpression::class.java,
KtLabeledExpression::class.java,
KtLambdaArgument::class.java,
KtLambdaExpression::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightClass::class.java,
KtLightDeclaration::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtLightParameter::class.java,
KtLightPsiArrayInitializerMemberValue::class.java,
KtLightPsiLiteral::class.java,
KtLiteralStringTemplateEntry::class.java,
KtNameReferenceExpression::class.java,
KtNamedFunction::class.java,
KtObjectDeclaration::class.java,
KtObjectLiteralExpression::class.java,
KtOperationReferenceExpression::class.java,
KtParameter::class.java,
KtParameterList::class.java,
KtParenthesizedExpression::class.java,
KtPostfixExpression::class.java,
KtPrefixExpression::class.java,
KtPrimaryConstructor::class.java,
KtProperty::class.java,
KtPropertyAccessor::class.java,
KtReturnExpression::class.java,
KtSafeQualifiedExpression::class.java,
KtScript::class.java,
KtScriptInitializer::class.java,
KtSecondaryConstructor::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtSuperExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtThisExpression::class.java,
KtThrowExpression::class.java,
KtTryExpression::class.java,
KtTypeAlias::class.java,
KtTypeParameter::class.java,
KtTypeReference::class.java,
KtWhenConditionInRange::class.java,
KtWhenConditionIsPattern::class.java,
KtWhenConditionWithExpression::class.java,
KtWhenEntry::class.java,
KtWhenExpression::class.java,
KtWhileExpression::class.java,
UastFakeLightMethod::class.java,
UastFakeLightPrimaryConstructor::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java,
UastKotlinPsiVariable::class.java
),
UAnnotation::class.java to classSetOf<PsiElement>(
KtAnnotationEntry::class.java,
KtCallExpression::class.java,
KtLightAnnotationForSourceEntry::class.java
),
UAnnotationEx::class.java to classSetOf<PsiElement>(
KtAnnotationEntry::class.java,
KtCallExpression::class.java,
KtLightAnnotationForSourceEntry::class.java
),
UAnnotationMethod::class.java to classSetOf<PsiElement>(
KtLightDeclaration::class.java,
KtParameter::class.java
),
UAnonymousClass::class.java to classSetOf<PsiElement>(
KtLightClass::class.java,
KtObjectDeclaration::class.java
),
UArrayAccessExpression::class.java to classSetOf<PsiElement>(
KtArrayAccessExpression::class.java,
KtBlockStringTemplateEntry::class.java
),
UBinaryExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBinaryExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtWhenConditionInRange::class.java,
KtWhenConditionWithExpression::class.java
),
UBinaryExpressionWithType::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBinaryExpressionWithTypeRHS::class.java,
KtIsExpression::class.java,
KtWhenConditionIsPattern::class.java,
KtWhenConditionWithExpression::class.java
),
UBlockExpression::class.java to classSetOf<PsiElement>(
KtBlockExpression::class.java
),
UBreakExpression::class.java to classSetOf<PsiElement>(
KtBreakExpression::class.java
),
UCallExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtCallExpression::class.java,
KtCollectionLiteralExpression::class.java,
KtConstructorDelegationCall::class.java,
KtEnumEntry::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightField::class.java,
KtObjectLiteralExpression::class.java,
KtStringTemplateExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtWhenConditionWithExpression::class.java,
KtLightPsiArrayInitializerMemberValue::class.java
),
UCallExpressionEx::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtCallExpression::class.java,
KtCollectionLiteralExpression::class.java,
KtConstructorDelegationCall::class.java,
KtEnumEntry::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightField::class.java,
KtObjectLiteralExpression::class.java,
KtStringTemplateExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtWhenConditionWithExpression::class.java,
KtLightPsiArrayInitializerMemberValue::class.java
),
UCallableReferenceExpression::class.java to classSetOf<PsiElement>(
KtCallableReferenceExpression::class.java
),
UCatchClause::class.java to classSetOf<PsiElement>(
KtCatchClause::class.java
),
UClass::class.java to classSetOf<PsiElement>(
KtClass::class.java,
KtFile::class.java,
KtLightClass::class.java,
KtObjectDeclaration::class.java
),
UClassInitializer::class.java to classSetOf<PsiElement>(
),
UClassInitializerEx::class.java to classSetOf<PsiElement>(
),
UClassLiteralExpression::class.java to classSetOf<PsiElement>(
KtClassLiteralExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UComment::class.java to classSetOf<PsiElement>(
PsiComment::class.java
),
UContinueExpression::class.java to classSetOf<PsiElement>(
KtContinueExpression::class.java
),
UDeclaration::class.java to classSetOf<PsiElement>(
KtClass::class.java,
KtDestructuringDeclarationEntry::class.java,
KtEnumEntry::class.java,
KtFile::class.java,
KtLightClass::class.java,
KtLightDeclaration::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtLightParameter::class.java,
KtNamedFunction::class.java,
KtObjectDeclaration::class.java,
KtParameter::class.java,
KtPrimaryConstructor::class.java,
KtProperty::class.java,
KtPropertyAccessor::class.java,
KtSecondaryConstructor::class.java,
KtTypeReference::class.java,
UastFakeLightMethod::class.java,
UastFakeLightPrimaryConstructor::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java,
UastKotlinPsiVariable::class.java
),
UDeclarationEx::class.java to classSetOf<PsiElement>(
KtDestructuringDeclarationEntry::class.java,
KtEnumEntry::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtLightParameter::class.java,
KtParameter::class.java,
KtProperty::class.java,
KtTypeReference::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java,
UastKotlinPsiVariable::class.java
),
UDeclarationsExpression::class.java to classSetOf<PsiElement>(
KtClass::class.java,
KtDestructuringDeclaration::class.java,
KtEnumEntry::class.java,
KtFunctionLiteral::class.java,
KtLightDeclaration::class.java,
KtNamedFunction::class.java,
KtObjectDeclaration::class.java,
KtParameterList::class.java,
KtPrimaryConstructor::class.java,
KtSecondaryConstructor::class.java
),
UDoWhileExpression::class.java to classSetOf<PsiElement>(
KtDoWhileExpression::class.java
),
UElement::class.java to classSetOf<PsiElement>(
FakeFileForLightClass::class.java,
KDocName::class.java,
KtAnnotatedExpression::class.java,
KtAnnotationEntry::class.java,
KtArrayAccessExpression::class.java,
KtBinaryExpression::class.java,
KtBinaryExpressionWithTypeRHS::class.java,
KtBlockExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtBreakExpression::class.java,
KtCallExpression::class.java,
KtCallableReferenceExpression::class.java,
KtCatchClause::class.java,
KtClass::class.java,
KtClassBody::class.java,
KtClassInitializer::class.java,
KtClassLiteralExpression::class.java,
KtCollectionLiteralExpression::class.java,
KtConstantExpression::class.java,
KtConstructorCalleeExpression::class.java,
KtConstructorDelegationCall::class.java,
KtConstructorDelegationReferenceExpression::class.java,
KtContinueExpression::class.java,
KtDelegatedSuperTypeEntry::class.java,
KtDestructuringDeclaration::class.java,
KtDestructuringDeclarationEntry::class.java,
KtDoWhileExpression::class.java,
KtDotQualifiedExpression::class.java,
KtEnumEntry::class.java,
KtEnumEntrySuperclassReferenceExpression::class.java,
KtEscapeStringTemplateEntry::class.java,
KtFile::class.java,
KtForExpression::class.java,
KtFunctionLiteral::class.java,
KtIfExpression::class.java,
KtImportDirective::class.java,
KtIsExpression::class.java,
KtLabelReferenceExpression::class.java,
KtLabeledExpression::class.java,
KtLambdaArgument::class.java,
KtLambdaExpression::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightClass::class.java,
KtLightDeclaration::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtLightParameter::class.java,
KtLightPsiArrayInitializerMemberValue::class.java,
KtLightPsiLiteral::class.java,
KtLiteralStringTemplateEntry::class.java,
KtNameReferenceExpression::class.java,
KtNamedFunction::class.java,
KtObjectDeclaration::class.java,
KtObjectLiteralExpression::class.java,
KtOperationReferenceExpression::class.java,
KtParameter::class.java,
KtParameterList::class.java,
KtParenthesizedExpression::class.java,
KtPostfixExpression::class.java,
KtPrefixExpression::class.java,
KtPrimaryConstructor::class.java,
KtProperty::class.java,
KtPropertyAccessor::class.java,
KtReturnExpression::class.java,
KtSafeQualifiedExpression::class.java,
KtScript::class.java,
KtScriptInitializer::class.java,
KtSecondaryConstructor::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtSuperExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtThisExpression::class.java,
KtThrowExpression::class.java,
KtTryExpression::class.java,
KtTypeAlias::class.java,
KtTypeParameter::class.java,
KtTypeReference::class.java,
KtWhenConditionInRange::class.java,
KtWhenConditionIsPattern::class.java,
KtWhenConditionWithExpression::class.java,
KtWhenEntry::class.java,
KtWhenExpression::class.java,
KtWhileExpression::class.java,
LeafPsiElement::class.java,
PsiComment::class.java,
UastFakeLightMethod::class.java,
UastFakeLightPrimaryConstructor::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java,
UastKotlinPsiVariable::class.java
),
UElementWithLocation::class.java to classSetOf<PsiElement>(
),
UEnumConstant::class.java to classSetOf<PsiElement>(
KtEnumEntry::class.java,
KtLightField::class.java
),
UEnumConstantEx::class.java to classSetOf<PsiElement>(
KtEnumEntry::class.java,
KtLightField::class.java
),
UExpression::class.java to classSetOf<PsiElement>(
KDocName::class.java,
KtAnnotatedExpression::class.java,
KtArrayAccessExpression::class.java,
KtBinaryExpression::class.java,
KtBinaryExpressionWithTypeRHS::class.java,
KtBlockExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtBreakExpression::class.java,
KtCallExpression::class.java,
KtCallableReferenceExpression::class.java,
KtClass::class.java,
KtClassBody::class.java,
KtClassInitializer::class.java,
KtClassLiteralExpression::class.java,
KtCollectionLiteralExpression::class.java,
KtConstantExpression::class.java,
KtConstructorCalleeExpression::class.java,
KtConstructorDelegationCall::class.java,
KtConstructorDelegationReferenceExpression::class.java,
KtContinueExpression::class.java,
KtDelegatedSuperTypeEntry::class.java,
KtDestructuringDeclaration::class.java,
KtDoWhileExpression::class.java,
KtDotQualifiedExpression::class.java,
KtEnumEntry::class.java,
KtEnumEntrySuperclassReferenceExpression::class.java,
KtEscapeStringTemplateEntry::class.java,
KtForExpression::class.java,
KtFunctionLiteral::class.java,
KtIfExpression::class.java,
KtIsExpression::class.java,
KtLabelReferenceExpression::class.java,
KtLabeledExpression::class.java,
KtLambdaArgument::class.java,
KtLambdaExpression::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightDeclaration::class.java,
KtLightField::class.java,
KtLightPsiArrayInitializerMemberValue::class.java,
KtLightPsiLiteral::class.java,
KtLiteralStringTemplateEntry::class.java,
KtNameReferenceExpression::class.java,
KtNamedFunction::class.java,
KtObjectDeclaration::class.java,
KtObjectLiteralExpression::class.java,
KtOperationReferenceExpression::class.java,
KtParameter::class.java,
KtParameterList::class.java,
KtParenthesizedExpression::class.java,
KtPostfixExpression::class.java,
KtPrefixExpression::class.java,
KtPrimaryConstructor::class.java,
KtProperty::class.java,
KtPropertyAccessor::class.java,
KtReturnExpression::class.java,
KtSafeQualifiedExpression::class.java,
KtScript::class.java,
KtScriptInitializer::class.java,
KtSecondaryConstructor::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtSuperExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtThisExpression::class.java,
KtThrowExpression::class.java,
KtTryExpression::class.java,
KtTypeAlias::class.java,
KtTypeParameter::class.java,
KtTypeReference::class.java,
KtWhenConditionInRange::class.java,
KtWhenConditionIsPattern::class.java,
KtWhenConditionWithExpression::class.java,
KtWhenEntry::class.java,
KtWhenExpression::class.java,
KtWhileExpression::class.java
),
UExpressionList::class.java to classSetOf<PsiElement>(
KtBinaryExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtClassBody::class.java,
KtDelegatedSuperTypeEntry::class.java,
KtWhenConditionWithExpression::class.java
),
UField::class.java to classSetOf<PsiElement>(
KtEnumEntry::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtParameter::class.java,
KtProperty::class.java
),
UFieldEx::class.java to classSetOf<PsiElement>(
KtLightFieldForSourceDeclarationSupport::class.java,
KtParameter::class.java,
KtProperty::class.java
),
UFile::class.java to classSetOf<PsiElement>(
FakeFileForLightClass::class.java,
KtFile::class.java
),
UForEachExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtForExpression::class.java
),
UForExpression::class.java to classSetOf<PsiElement>(
),
UIdentifier::class.java to classSetOf<PsiElement>(
LeafPsiElement::class.java
),
UIfExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtIfExpression::class.java
),
UImportStatement::class.java to classSetOf<PsiElement>(
KtImportDirective::class.java
),
UInjectionHost::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtLightPsiArrayInitializerMemberValue::class.java,
KtLightPsiLiteral::class.java,
KtStringTemplateExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UInstanceExpression::class.java to classSetOf<PsiElement>(
KtBlockStringTemplateEntry::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtSuperExpression::class.java,
KtThisExpression::class.java
),
UJumpExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBreakExpression::class.java,
KtContinueExpression::class.java,
KtReturnExpression::class.java
),
ULabeled::class.java to classSetOf<PsiElement>(
KtBlockStringTemplateEntry::class.java,
KtLabeledExpression::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtSuperExpression::class.java,
KtThisExpression::class.java
),
ULabeledExpression::class.java to classSetOf<PsiElement>(
KtLabeledExpression::class.java
),
ULambdaExpression::class.java to classSetOf<PsiElement>(
KtFunctionLiteral::class.java,
KtLambdaArgument::class.java,
KtLambdaExpression::class.java,
KtLightDeclaration::class.java,
KtNamedFunction::class.java,
KtPrimaryConstructor::class.java
),
ULiteralExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtConstantExpression::class.java,
KtEscapeStringTemplateEntry::class.java,
KtLightPsiArrayInitializerMemberValue::class.java,
KtLightPsiLiteral::class.java,
KtLiteralStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtWhenConditionWithExpression::class.java
),
ULocalVariable::class.java to classSetOf<PsiElement>(
KtDestructuringDeclarationEntry::class.java,
KtProperty::class.java,
UastKotlinPsiVariable::class.java
),
ULocalVariableEx::class.java to classSetOf<PsiElement>(
KtDestructuringDeclarationEntry::class.java,
KtProperty::class.java,
UastKotlinPsiVariable::class.java
),
ULoopExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtDoWhileExpression::class.java,
KtForExpression::class.java,
KtWhileExpression::class.java
),
UMethod::class.java to classSetOf<PsiElement>(
KtClass::class.java,
KtLightDeclaration::class.java,
KtNamedFunction::class.java,
KtParameter::class.java,
KtPrimaryConstructor::class.java,
KtProperty::class.java,
KtPropertyAccessor::class.java,
KtSecondaryConstructor::class.java,
UastFakeLightMethod::class.java,
UastFakeLightPrimaryConstructor::class.java
),
UMultiResolvable::class.java to classSetOf<PsiElement>(
KDocName::class.java,
KtAnnotatedExpression::class.java,
KtAnnotationEntry::class.java,
KtBlockStringTemplateEntry::class.java,
KtCallExpression::class.java,
KtCallableReferenceExpression::class.java,
KtCollectionLiteralExpression::class.java,
KtConstructorDelegationCall::class.java,
KtDotQualifiedExpression::class.java,
KtEnumEntry::class.java,
KtImportDirective::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightField::class.java,
KtObjectLiteralExpression::class.java,
KtPostfixExpression::class.java,
KtSafeQualifiedExpression::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtSuperExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtThisExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UNamedExpression::class.java to classSetOf<PsiElement>(
),
UObjectLiteralExpression::class.java to classSetOf<PsiElement>(
KtObjectLiteralExpression::class.java,
KtSuperTypeCallEntry::class.java
),
UParameter::class.java to classSetOf<PsiElement>(
KtLightParameter::class.java,
KtParameter::class.java,
KtTypeReference::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java
),
UParameterEx::class.java to classSetOf<PsiElement>(
KtLightParameter::class.java,
KtParameter::class.java,
KtTypeReference::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java
),
UParenthesizedExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtParenthesizedExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UPolyadicExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBinaryExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtLightPsiArrayInitializerMemberValue::class.java,
KtLightPsiLiteral::class.java,
KtStringTemplateExpression::class.java,
KtWhenConditionInRange::class.java,
KtWhenConditionWithExpression::class.java
),
UPostfixExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtPostfixExpression::class.java
),
UPrefixExpression::class.java to classSetOf<PsiElement>(
KtBlockStringTemplateEntry::class.java,
KtPrefixExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UQualifiedReferenceExpression::class.java to classSetOf<PsiElement>(
KDocName::class.java,
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtDotQualifiedExpression::class.java,
KtSafeQualifiedExpression::class.java,
KtStringTemplateExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UReferenceExpression::class.java to classSetOf<PsiElement>(
KDocName::class.java,
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtCallableReferenceExpression::class.java,
KtDotQualifiedExpression::class.java,
KtEnumEntrySuperclassReferenceExpression::class.java,
KtLabelReferenceExpression::class.java,
KtNameReferenceExpression::class.java,
KtOperationReferenceExpression::class.java,
KtSafeQualifiedExpression::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UResolvable::class.java to classSetOf<PsiElement>(
KDocName::class.java,
KtAnnotatedExpression::class.java,
KtAnnotationEntry::class.java,
KtBlockStringTemplateEntry::class.java,
KtCallExpression::class.java,
KtCallableReferenceExpression::class.java,
KtCollectionLiteralExpression::class.java,
KtConstructorDelegationCall::class.java,
KtDotQualifiedExpression::class.java,
KtEnumEntry::class.java,
KtEnumEntrySuperclassReferenceExpression::class.java,
KtImportDirective::class.java,
KtLabelReferenceExpression::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightField::class.java,
KtNameReferenceExpression::class.java,
KtObjectLiteralExpression::class.java,
KtOperationReferenceExpression::class.java,
KtPostfixExpression::class.java,
KtSafeQualifiedExpression::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtSuperExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtThisExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UReturnExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtReturnExpression::class.java
),
USimpleNameReferenceExpression::class.java to classSetOf<PsiElement>(
KDocName::class.java,
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtEnumEntrySuperclassReferenceExpression::class.java,
KtLabelReferenceExpression::class.java,
KtNameReferenceExpression::class.java,
KtOperationReferenceExpression::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtWhenConditionWithExpression::class.java
),
USuperExpression::class.java to classSetOf<PsiElement>(
KtSuperExpression::class.java
),
USwitchClauseExpression::class.java to classSetOf<PsiElement>(
KtWhenEntry::class.java
),
USwitchClauseExpressionWithBody::class.java to classSetOf<PsiElement>(
KtWhenEntry::class.java
),
USwitchExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtWhenExpression::class.java
),
UThisExpression::class.java to classSetOf<PsiElement>(
KtBlockStringTemplateEntry::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtThisExpression::class.java
),
UThrowExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtThrowExpression::class.java
),
UTryExpression::class.java to classSetOf<PsiElement>(
KtBlockStringTemplateEntry::class.java,
KtTryExpression::class.java
),
UTypeReferenceExpression::class.java to classSetOf<PsiElement>(
KtTypeReference::class.java
),
UUnaryExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtPostfixExpression::class.java,
KtPrefixExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UVariable::class.java to classSetOf<PsiElement>(
KtDestructuringDeclarationEntry::class.java,
KtEnumEntry::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtLightParameter::class.java,
KtParameter::class.java,
KtProperty::class.java,
KtTypeReference::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java,
UastKotlinPsiVariable::class.java
),
UVariableEx::class.java to classSetOf<PsiElement>(
KtDestructuringDeclarationEntry::class.java,
KtEnumEntry::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtLightParameter::class.java,
KtParameter::class.java,
KtProperty::class.java,
KtTypeReference::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java,
UastKotlinPsiVariable::class.java
),
UWhileExpression::class.java to classSetOf<PsiElement>(
KtWhileExpression::class.java
),
UYieldExpression::class.java to classSetOf<PsiElement>(
),
UastEmptyExpression::class.java to classSetOf<PsiElement>(
KtBinaryExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtClass::class.java,
KtEnumEntry::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtObjectDeclaration::class.java,
KtStringTemplateExpression::class.java
),
UnknownKotlinExpression::class.java to classSetOf<PsiElement>(
KtClassInitializer::class.java,
KtConstructorCalleeExpression::class.java,
KtConstructorDelegationReferenceExpression::class.java,
KtLightDeclaration::class.java,
KtParameter::class.java,
KtPropertyAccessor::class.java,
KtScript::class.java,
KtScriptInitializer::class.java,
KtTypeAlias::class.java,
KtTypeParameter::class.java
)
)
| apache-2.0 | 45824d007987df9af648bb52bbf3145a | 39.757503 | 158 | 0.702836 | 5.583128 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/src/git4idea/util/CollectionUtil.kt | 10 | 1664 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.util
import org.jetbrains.annotations.NonNls
fun <K, V> Map<K, V>.without(removed: K): Map<K, V> {
val result = this.toMutableMap()
result.remove(removed)
return result
}
fun <R> List<*>.lastInstance(klass: Class<R>): R? {
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
val element = iterator.previous()
@Suppress("UNCHECKED_CAST")
if (klass.isInstance(element)) return element as R
}
return null
}
fun <T> Collection<T>.toShortenedLogString(separator: @NonNls String = ", ", limit: Int = 20,
transform: ((T) -> @NonNls CharSequence)? = null): @NonNls String {
return joinToString(prefix = "[", postfix = "]",
separator = separator, limit = limit, truncated = truncated(limit),
transform = transform)
}
fun <K, V> Map<K, V>.toShortenedLogString(separator: @NonNls String = ", ",
limit: Int = 20,
transform: ((Map.Entry<K, V>) -> @NonNls CharSequence)? = null): @NonNls String {
return asIterable().joinToString(prefix = "[", postfix = "]",
separator = separator, limit = limit, truncated = truncated(size, limit),
transform = transform)
}
private fun truncated(size: Int, limit: Int) : @NonNls String = " ... +${size - limit} more"
private fun Collection<*>.truncated(limit: Int) = truncated(size, limit) | apache-2.0 | 49d22a36373d801bd03c937f5e679293 | 42.815789 | 140 | 0.591346 | 4.255754 | false | false | false | false |
smmribeiro/intellij-community | platform/remoteDev-util/src/com/intellij/remoteDev/util/UrlParameterKeys.kt | 1 | 404 | package com.intellij.remoteDev.util
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Experimental
class UrlParameterKeys {
companion object {
const val projectPath = "projectPath"
const val idePath = "idePath"
const val host = "host"
const val user = "user"
const val port = "port"
const val type = "type"
const val deploy = "deploy"
const val sshId = "ssh"
}
} | apache-2.0 | 5799625dc9c4386b3bb2750f0fefd1a3 | 22.823529 | 42 | 0.688119 | 3.847619 | false | false | false | false |
smmribeiro/intellij-community | platform/execution-impl/src/com/intellij/execution/runToolbar/RunToolbarExecutorGroupAction.kt | 9 | 2349 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.runToolbar
import com.intellij.execution.Executor
import com.intellij.execution.ExecutorRegistryImpl
import com.intellij.execution.executors.ExecutorGroup
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.ShortcutSet
import com.intellij.openapi.actionSystem.SplitButtonAction
import java.util.function.Function
internal class RunToolbarExecutorGroupAction(private val group: RunToolbarExecutorGroup) : SplitButtonAction(group), ExecutorRunToolbarAction {
override val process: RunToolbarProcess
get() = group.process
override fun checkMainSlotVisibility(state: RunToolbarMainSlotState): Boolean {
return state == RunToolbarMainSlotState.CONFIGURATION
}
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.isVisible = !e.isActiveProcess() && e.presentation.isVisible
if (!RunToolbarProcess.isExperimentalUpdatingEnabled) {
e.mainState()?.let {
e.presentation.isVisible = e.presentation.isVisible && checkMainSlotVisibility(it)
}
}
}
override fun setShortcutSet(shortcutSet: ShortcutSet) {}
}
internal class RunToolbarExecutorGroup(executorGroup: ExecutorGroup<*>,
childConverter: Function<in Executor, out AnAction>, override val process: RunToolbarProcess) :
ExecutorRunToolbarAction, ExecutorRegistryImpl.ExecutorGroupActionGroup(executorGroup, childConverter) {
override fun getRightSideType(): RTBarAction.Type = RTBarAction.Type.RIGHT_FLEXIBLE
override fun displayTextInToolbar(): Boolean {
return true
}
override fun setShortcutSet(shortcutSet: ShortcutSet) {}
override fun checkMainSlotVisibility(state: RunToolbarMainSlotState): Boolean {
return state == RunToolbarMainSlotState.CONFIGURATION
}
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.isVisible = !e.isActiveProcess()
if (!RunToolbarProcess.isExperimentalUpdatingEnabled) {
e.mainState()?.let {
e.presentation.isVisible = e.presentation.isVisible && checkMainSlotVisibility(it)
}
}
}
} | apache-2.0 | 6e5d2c0e5d45fa9ca354b4e6090c1b7f | 36.301587 | 158 | 0.770541 | 4.976695 | false | false | false | false |
smmribeiro/intellij-community | plugins/github/src/org/jetbrains/plugins/github/api/data/request/GHRepoRequestParams.kt | 6 | 1382 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.api.data.request
/**
* Additional params for [`GET /user/repos`](https://developer.github.com/v3/repos/#list-your-repositories) request
*/
enum class Type(private val value: String) {
ALL(""),
OWNER("owner"),
PUBLIC("public"),
PRIVATE("private"),
@Suppress("unused") // API
MEMBER("member");
companion object {
val DEFAULT = ALL
}
override fun toString() = if (value.isEmpty()) value else "type=$value"
}
enum class Visibility(private val value: String) {
ALL(""),
PUBLIC("public"),
PRIVATE("private");
companion object {
val DEFAULT = ALL
}
override fun toString() = if (value.isEmpty()) value else "visibility=$value"
}
class Affiliation private constructor(private val value: String) {
companion object {
val OWNER = Affiliation("owner")
val COLLABORATOR = Affiliation("collaborator")
@Suppress("unused") // API
val ORG_MEMBER = Affiliation("organization_member")
val DEFAULT = Affiliation("")
fun combine(vararg affiliations: Affiliation): Affiliation {
return Affiliation(affiliations.toSet().joinToString(",") { it.value })
}
}
override fun toString() = if (value.isEmpty()) value else "affiliation=$value"
}
| apache-2.0 | 3aa2ff65cf57b56aaac39e557b2f02ce | 27.791667 | 140 | 0.686686 | 4.052786 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/openapi/client/ClientAwareComponentManager.kt | 1 | 4613 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.client
import com.intellij.codeWithMe.ClientId
import com.intellij.ide.plugins.IdeaPluginDescriptorImpl
import com.intellij.openapi.application.Application
import com.intellij.openapi.components.ServiceDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.progress.ProgressIndicatorProvider
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.serviceContainer.PrecomputedExtensionModel
import com.intellij.serviceContainer.throwAlreadyDisposedError
import org.jetbrains.annotations.ApiStatus
import java.util.concurrent.CompletableFuture
@ApiStatus.Internal
abstract class ClientAwareComponentManager @JvmOverloads constructor(
internal val parent: ComponentManagerImpl?,
setExtensionsRootArea: Boolean = parent == null) : ComponentManagerImpl(parent, setExtensionsRootArea) {
override fun <T : Any> getService(serviceClass: Class<T>): T? {
return getFromSelfOrCurrentSession(serviceClass, true)
}
override fun <T : Any> getServiceIfCreated(serviceClass: Class<T>): T? {
return getFromSelfOrCurrentSession(serviceClass, false)
}
override fun <T : Any> getServices(serviceClass: Class<T>, includeLocal: Boolean): List<T> {
val sessionsManager = super.getService(ClientSessionsManager::class.java)!!
return sessionsManager.getSessions(includeLocal)
.mapNotNull { (it as? ClientSessionImpl)?.doGetService(serviceClass, true, false) }
}
private fun <T : Any> getFromSelfOrCurrentSession(serviceClass: Class<T>, createIfNeeded: Boolean): T? {
val fromSelf = if (createIfNeeded) {
super.getService(serviceClass)
}
else {
super.getServiceIfCreated(serviceClass)
}
if (fromSelf != null) return fromSelf
val sessionsManager = if (containerState.get() == ContainerState.DISPOSE_COMPLETED) {
if (createIfNeeded) {
throwAlreadyDisposedError(serviceClass.name, this, ProgressIndicatorProvider.getGlobalProgressIndicator())
}
super.doGetService(ClientSessionsManager::class.java, false)
}
else {
super.getService(ClientSessionsManager::class.java)
}
val session = sessionsManager?.getSession(ClientId.current) as? ClientSessionImpl
return session?.doGetService(serviceClass, createIfNeeded, false)
}
override fun registerComponents(modules: Sequence<IdeaPluginDescriptorImpl>,
app: Application?,
precomputedExtensionModel: PrecomputedExtensionModel?,
listenerCallbacks: List<Runnable>?) {
super.registerComponents(modules, app, precomputedExtensionModel, listenerCallbacks)
val sessionsManager = super.getService(ClientSessionsManager::class.java)!!
for (session in sessionsManager.getSessions(true)) {
(session as? ClientSessionImpl)?.registerComponents(modules, app, precomputedExtensionModel, listenerCallbacks)
}
}
override fun unloadServices(services: List<ServiceDescriptor>, pluginId: PluginId) {
super.unloadServices(services, pluginId)
val sessionsManager = super.getService(ClientSessionsManager::class.java)!!
for (session in sessionsManager.getSessions(true)) {
(session as? ClientSessionImpl)?.unloadServices(services, pluginId)
}
}
override fun preloadServices(modules: Sequence<IdeaPluginDescriptorImpl>,
activityPrefix: String,
onlyIfAwait: Boolean): PreloadServicesResult {
val result = super.preloadServices(modules, activityPrefix, onlyIfAwait)
val sessionsManager = super.getService(ClientSessionsManager::class.java)!!
val syncPreloadFutures = mutableListOf<CompletableFuture<*>>()
val asyncPreloadFutures = mutableListOf<CompletableFuture<*>>()
for (session in sessionsManager.getSessions(true)) {
session as? ClientSessionImpl ?: continue
val sessionResult = session.preloadServices(modules, activityPrefix, onlyIfAwait)
syncPreloadFutures.add(sessionResult.sync)
asyncPreloadFutures.add(sessionResult.async)
}
return PreloadServicesResult(
sync = CompletableFuture.allOf(result.sync, *syncPreloadFutures.toTypedArray()),
async = CompletableFuture.allOf(result.async, *asyncPreloadFutures.toTypedArray())
)
}
override fun isPreInitialized(component: Any): Boolean {
return super.isPreInitialized(component) || component is ClientSessionsManager<*>
}
} | apache-2.0 | 0bef562283b6f61e1ff20961a4be5d2c | 43.365385 | 120 | 0.748537 | 5.314516 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/tests/git4idea/tests/GitChangeProviderNestedRepositoriesTest.kt | 10 | 4343 | // 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 git4idea.tests
import com.intellij.openapi.vcs.Executor.*
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.FileStatus
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcsUtil.VcsUtil
import git4idea.test.*
import java.io.File
class GitChangeProviderNestedRepositoriesTest : GitPlatformTest() {
private lateinit var dirtyScopeManager: VcsDirtyScopeManager
@Throws(Exception::class)
public override fun setUp() {
super.setUp()
dirtyScopeManager = VcsDirtyScopeManager.getInstance(project)
}
override fun getDebugLogCategories() = super.getDebugLogCategories().plus(listOf("#com.intellij.openapi.vcs.changes", "#GitStatus"))
// IDEA-149060
fun `test changes in 3-level nested root`() {
// 1. prepare roots and files
val repo = createRepository(project, projectPath)
val childRepo = repo.createSubRepository("child")
val grandChildRepo = childRepo.createSubRepository("grand")
createFileStructure(repo.root, "a.txt")
createFileStructure(childRepo.root, "in1.txt", "in2.txt", "grand/inin1.txt", "grand/inin2.txt")
repo.addCommit("committed file structure")
childRepo.addCommit("committed file structure")
grandChildRepo.addCommit("committed file structure")
refresh()
// 2. make changes and make sure they are recognized
cd(repo)
overwrite("a.txt", "321")
overwrite("child/in1.txt", "321")
overwrite("child/in2.txt", "321")
overwrite("child/grand/inin1.txt", "321")
dirtyScopeManager.markEverythingDirty()
changeListManager.ensureUpToDate()
assertFileStatus("a.txt", FileStatus.MODIFIED)
assertFileStatus("child/in1.txt", FileStatus.MODIFIED)
assertFileStatus("child/in2.txt", FileStatus.MODIFIED)
assertFileStatus("child/grand/inin1.txt", FileStatus.MODIFIED)
// refresh parent root recursively
dirtyScopeManager.filePathsDirty(listOf(getFilePath("child/in1.txt")), listOf(VcsUtil.getFilePath(repo.root)))
changeListManager.ensureUpToDate()
assertFileStatus("a.txt", FileStatus.MODIFIED)
assertFileStatus("child/in1.txt", FileStatus.MODIFIED)
assertFileStatus("child/in2.txt", FileStatus.MODIFIED)
assertFileStatus("child/grand/inin1.txt", FileStatus.MODIFIED)
assertEquals(4, changeListManager.allChanges.size)
}
fun `test new rename forcing old file path refresh`() {
// 1. prepare roots and files
val repo = createRepository(project, projectPath)
cd(repo)
touch("a.txt", "some file content")
repo.addCommit("committed file structure")
rm("a.txt")
touch("b.txt", "some file content")
dirtyScopeManager.markEverythingDirty()
changeListManager.ensureUpToDate()
updateUntrackedFiles(repo)
assertEquals(1, changeListManager.allChanges.size)
assertFileStatus("a.txt", FileStatus.DELETED)
assertFileStatus("b.txt", FileStatus.UNKNOWN)
git("add b.txt")
dirtyScopeManager.fileDirty(getFilePath("b.txt"))
changeListManager.ensureUpToDate()
assertEquals(2, changeListManager.allChanges.size)
assertFileStatus("a.txt", FileStatus.DELETED)
assertFileStatus("b.txt", FileStatus.ADDED)
git("add a.txt")
dirtyScopeManager.fileDirty(getFilePath("a.txt"))
changeListManager.ensureUpToDate()
assertEquals(1, changeListManager.allChanges.size)
assertFileStatus("b.txt", FileStatus.MODIFIED)
}
private fun assertFileStatus(relativePath: String, fileStatus: FileStatus) {
if (fileStatus == FileStatus.UNKNOWN) {
val vf = getVirtualFile(relativePath)
assertTrue("$vf is not known as unversioned", changeListManager.isUnversioned(vf))
}
else {
val change = changeListManager.getChange(getFilePath(relativePath))
assertEquals(fileStatus, change?.fileStatus ?: FileStatus.NOT_CHANGED)
}
}
private fun getVirtualFile(relativePath: String): VirtualFile {
return VfsUtil.findFileByIoFile(File(projectPath, relativePath), true)!!
}
private fun getFilePath(relativePath: String): FilePath {
return VcsUtil.getFilePath(File(projectPath, relativePath))
}
}
| apache-2.0 | 2315a6a1f220e5b7c50434f87905c466 | 34.598361 | 140 | 0.742344 | 4.373615 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/reflect/KotlinTargetReflection.kt | 5 | 3787 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradleTooling.reflect
import org.gradle.api.Named
import org.jetbrains.kotlin.idea.gradleTooling.getMethodOrNull
import org.jetbrains.kotlin.idea.gradleTooling.loadClassOrNull
fun KotlinTargetReflection(kotlinTarget: Any): KotlinTargetReflection = KotlinTargetReflectionImpl(kotlinTarget)
interface KotlinTargetReflection {
val isMetadataTargetClass: Boolean
val targetName: String
val presetName: String?
val disambiguationClassifier: String?
val platformType: String?
val gradleTarget: Named
val compilations: Collection<KotlinCompilationReflection>?
val nativeMainRunTasks: Collection<KotlinNativeMainRunTaskReflection>?
val artifactsTaskName: String?
val konanArtifacts: Collection<Any>?
}
private class KotlinTargetReflectionImpl(private val instance: Any) : KotlinTargetReflection {
override val gradleTarget: Named
get() = instance as Named
override val isMetadataTargetClass: Boolean by lazy {
val metadataTargetClass =
instance.javaClass.classLoader.loadClassOrNull("org.jetbrains.kotlin.gradle.plugin.mpp.KotlinMetadataTarget")
metadataTargetClass?.isInstance(instance) == true
}
override val targetName: String by lazy {
gradleTarget.name
}
override val presetName: String? by lazy {
instance.callReflectiveAnyGetter("getPreset", logger)
?.callReflectiveGetter("getName", logger)
}
override val disambiguationClassifier: String? by lazy {
val getterConditionMethod = "getUseDisambiguationClassifierAsSourceSetNamePrefix"
val useDisambiguationClassifier = if (instance.javaClass.getMethodOrNull(getterConditionMethod) != null)
instance.callReflectiveGetter(getterConditionMethod, logger)!!
else true
instance.callReflectiveGetter(
(if (useDisambiguationClassifier) "getDisambiguationClassifier"
else "getOverrideDisambiguationClassifierOnIdeImport"), logger
)
}
override val platformType: String? by lazy {
instance.callReflectiveAnyGetter("getPlatformType", logger)?.callReflectiveGetter("getName", logger)
}
override val compilations: Collection<KotlinCompilationReflection>? by lazy {
instance.callReflective("getCompilations", parameters(), returnType<Iterable<Any>>(), logger)?.map { compilation ->
KotlinCompilationReflection(compilation)
}
}
override val nativeMainRunTasks: Collection<KotlinNativeMainRunTaskReflection>? by lazy {
val executableClass = instance.javaClass.classLoader.loadClassOrNull(EXECUTABLE_CLASS) ?: return@lazy null
instance.callReflective("getBinaries", parameters(), returnType<Iterable<Any>>(), logger)
?.filterIsInstance(executableClass)
?.map { KotlinNativeMainRunTaskReflection(it) }
}
override val artifactsTaskName: String? by lazy {
instance.callReflectiveGetter("getArtifactsTaskName", logger)
}
override val konanArtifacts: Collection<Any>? by lazy {
if (!instance.javaClass.classLoader.loadClass(KOTLIN_NATIVE_TARGET_CLASS).isInstance(instance))
null
else
instance.callReflective("getBinaries", parameters(), returnType<Iterable<Any?>>(), logger)?.filterNotNull()
}
companion object {
private val logger = ReflectionLogger(KotlinTargetReflection::class.java)
private const val EXECUTABLE_CLASS = "org.jetbrains.kotlin.gradle.plugin.mpp.Executable"
private const val KOTLIN_NATIVE_TARGET_CLASS = "org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget"
}
} | apache-2.0 | 7f82def22761c69990ca181fffa107dc | 45.195122 | 123 | 0.738579 | 5.34887 | false | false | false | false |
DuckDeck/AndroidDemo | app/src/main/java/stan/androiddemo/project/petal/Widget/ScrollAwareFABBehavior.kt | 1 | 3773 | package stan.androiddemo.project.petal.Widget
import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.FloatingActionButton
import android.support.v4.view.ViewCompat
import android.support.v4.view.ViewPropertyAnimatorListener
import android.support.v4.view.animation.FastOutSlowInInterpolator
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
class ScrollAwareFABBehavior(context: Context, attrs: AttributeSet) : FloatingActionButton.Behavior() {
private var mIsAnimatingOut = false
override fun onStartNestedScroll(coordinatorLayout: CoordinatorLayout, child: FloatingActionButton,
directTargetChild: View, target: View, nestedScrollAxes: Int): Boolean {
// Ensure we react to vertical scrolling
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes)
}
override fun onNestedScroll(coordinatorLayout: CoordinatorLayout, child: FloatingActionButton,
target: View, dxConsumed: Int, dyConsumed: Int,
dxUnconsumed: Int, dyUnconsumed: Int) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed)
if (dyConsumed > 0 && !this.mIsAnimatingOut && child.visibility == View.VISIBLE) {
// User scrolled down and the FAB is currently visible -> hide the FAB
animateOut(child)
} else if (dyConsumed < 0 && child.visibility != View.VISIBLE) {
// User scrolled up and the FAB is currently not visible -> show the FAB
animateIn(child)
}
}
// Same animation that FloatingActionButton.Behavior uses to hide the FAB when the AppBarLayout exits
@SuppressLint("ObsoleteSdkInt")
private fun animateOut(button: FloatingActionButton) {
if (Build.VERSION.SDK_INT >= 14) {
ViewCompat.animate(button).translationY((button.height + getMarginBottom(button)).toFloat()).setInterpolator(INTERPOLATOR).withLayer()
.setListener(object : ViewPropertyAnimatorListener {
override fun onAnimationStart(view: View) {
[email protected] = true
}
override fun onAnimationCancel(view: View) {
[email protected] = false
}
override fun onAnimationEnd(view: View) {
[email protected] = false
view.visibility = View.INVISIBLE
}
}).start()
} else {
}
}
// Same animation that FloatingActionButton.Behavior uses to show the FAB when the AppBarLayout enters
private fun animateIn(button: FloatingActionButton) {
button.visibility = View.VISIBLE
if (Build.VERSION.SDK_INT >= 14) {
ViewCompat.animate(button).translationY(0f)
.setInterpolator(INTERPOLATOR).withLayer().setListener(null)
.start()
} else {
}
}
private fun getMarginBottom(v: View): Int {
var marginBottom = 0
val layoutParams = v.layoutParams
if (layoutParams is ViewGroup.MarginLayoutParams) {
marginBottom = layoutParams.bottomMargin
}
return marginBottom
}
companion object {
private val INTERPOLATOR = FastOutSlowInInterpolator()
}
} | mit | 51198167a8d8da250c9926f59119565c | 43.928571 | 166 | 0.657567 | 5.556701 | false | false | false | false |
TachiWeb/TachiWeb-Server | Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/source/online/russian/Readmanga.kt | 1 | 10198 | package eu.kanade.tachiyomi.source.online.russian
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.*
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.Headers
import okhttp3.HttpUrl
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
import java.util.*
import java.util.regex.Pattern
class Readmanga : ParsedHttpSource() {
override val id: Long = 5
override val name = "Readmanga"
override val baseUrl = "http://readmanga.me"
override val lang = "ru"
override val supportsLatest = true
override fun popularMangaSelector() = "div.tile"
override fun latestUpdatesSelector() = "div.tile"
override fun popularMangaRequest(page: Int): Request =
GET("$baseUrl/list?sortType=rate&offset=${70 * (page - 1)}&max=70", headers)
override fun latestUpdatesRequest(page: Int): Request =
GET("$baseUrl/list?sortType=updated&offset=${70 * (page - 1)}&max=70", headers)
override fun popularMangaFromElement(element: Element): SManga {
val manga = SManga.create()
manga.thumbnail_url = element.select("img.lazy").first()?.attr("data-original")
element.select("h3 > a").first().let {
manga.setUrlWithoutDomain(it.attr("href"))
manga.title = it.attr("title")
}
return manga
}
override fun latestUpdatesFromElement(element: Element): SManga =
popularMangaFromElement(element)
override fun popularMangaNextPageSelector() = "a.nextLink"
override fun latestUpdatesNextPageSelector() = "a.nextLink"
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val url = HttpUrl.parse("$baseUrl/search/advanced")!!.newBuilder()
(if (filters.isEmpty()) getFilterList() else filters).forEach { filter ->
when (filter) {
is GenreList -> filter.state.forEach { genre ->
if (genre.state != Filter.TriState.STATE_IGNORE) {
url.addQueryParameter(genre.id, arrayOf("=", "=in", "=ex")[genre.state])
}
}
is Category -> filter.state.forEach { category ->
if (category.state != Filter.TriState.STATE_IGNORE) {
url.addQueryParameter(category.id, arrayOf("=", "=in", "=ex")[category.state])
}
}
}
}
if (!query.isEmpty()) {
url.addQueryParameter("q", query)
}
return GET(url.toString().replace("=%3D", "="), headers)
}
override fun searchMangaSelector() = popularMangaSelector()
override fun searchMangaFromElement(element: Element): SManga = popularMangaFromElement(element)
// max 200 results
override fun searchMangaNextPageSelector(): Nothing? = null
override fun mangaDetailsParse(document: Document): SManga {
val infoElement = document.select("div.leftContent").first()
val manga = SManga.create()
manga.author = infoElement.select("span.elem_author").first()?.text()
manga.genre = infoElement.select("span.elem_genre").text().replace(" ,", ",")
manga.description = infoElement.select("div.manga-description").text()
manga.status = parseStatus(infoElement.html())
manga.thumbnail_url = infoElement.select("img").attr("data-full")
return manga
}
private fun parseStatus(element: String): Int = when {
element.contains("<h3>Запрещена публикация произведения по копирайту</h3>") -> SManga.LICENSED
element.contains("<h1 class=\"names\"> Сингл") || element.contains("<b>Перевод:</b> завершен") -> SManga.COMPLETED
element.contains("<b>Перевод:</b> продолжается") -> SManga.ONGOING
else -> SManga.UNKNOWN
}
override fun chapterListSelector() = "div.chapters-link tbody tr"
override fun chapterFromElement(element: Element): SChapter {
val urlElement = element.select("a").first()
val urlText = urlElement.text()
val chapter = SChapter.create()
chapter.setUrlWithoutDomain(urlElement.attr("href") + "?mtr=1")
if (urlText.endsWith(" новое")) {
chapter.name = urlText.dropLast(6)
} else {
chapter.name = urlText
}
chapter.date_upload = element.select("td.hidden-xxs").last()?.text()?.let {
SimpleDateFormat("dd/MM/yy", Locale.US).parse(it).time
} ?: 0
return chapter
}
override fun prepareNewChapter(chapter: SChapter, manga: SManga) {
val basic = Regex("""\s*([0-9]+)(\s-\s)([0-9]+)\s*""")
val extra = Regex("""\s*([0-9]+\sЭкстра)\s*""")
val single = Regex("""\s*Сингл\s*""")
when {
basic.containsMatchIn(chapter.name) -> {
basic.find(chapter.name)?.let {
val number = it.groups[3]?.value!!
chapter.chapter_number = number.toFloat()
}
}
extra.containsMatchIn(chapter.name) -> // Extra chapters doesn't contain chapter number
chapter.chapter_number = -2f
single.containsMatchIn(chapter.name) -> // Oneshoots, doujinshi and other mangas with one chapter
chapter.chapter_number = 1f
}
}
override fun pageListParse(response: Response): List<Page> {
val html = response.body()!!.string()
val beginIndex = html.indexOf("rm_h.init( [")
val endIndex = html.indexOf("], 0, false);", beginIndex)
val trimmedHtml = html.substring(beginIndex, endIndex)
val p = Pattern.compile("'.*?','.*?',\".*?\"")
val m = p.matcher(trimmedHtml)
val pages = mutableListOf<Page>()
var i = 0
while (m.find()) {
val urlParts = m.group().replace("[\"\']+".toRegex(), "").split(',')
val url = if (urlParts[1].isEmpty() && urlParts[2].startsWith("/static/")) {
baseUrl + urlParts[2]
} else {
urlParts[1] + urlParts[0] + urlParts[2]
}
pages.add(Page(i++, "", url))
}
return pages
}
override fun pageListParse(document: Document): List<Page> {
throw Exception("Not used")
}
override fun imageUrlParse(document: Document) = ""
override fun imageRequest(page: Page): Request {
val imgHeader = Headers.Builder().apply {
add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64)")
add("Referer", baseUrl)
}.build()
return GET(page.imageUrl!!, imgHeader)
}
private class Genre(name: String, val id: String) : Filter.TriState(name)
private class GenreList(genres: List<Genre>) : Filter.Group<Genre>("Genres", genres)
private class Category(categories: List<Genre>) : Filter.Group<Genre>("Category", categories)
/* [...document.querySelectorAll("tr.advanced_option:nth-child(1) > td:nth-child(3) span.js-link")]
* .map(el => `Genre("${el.textContent.trim()}", $"{el.getAttribute('onclick')
* .substr(31,el.getAttribute('onclick').length-33)"})`).join(',\n')
* on http://readmanga.me/search/advanced
*/
override fun getFilterList() = FilterList(
Category(getCategoryList()),
GenreList(getGenreList())
)
private fun getCategoryList() = listOf(
Genre("В цвете", "el_7290"),
Genre("Веб", "el_2160"),
Genre("Выпуск приостановлен", "el_8033"),
Genre("Ёнкома", "el_2161"),
Genre("Комикс западный", "el_3515"),
Genre("Манхва", "el_3001"),
Genre("Маньхуа", "el_3002"),
Genre("Ранобэ", "el_8575"),
Genre("Сборник", "el_2157")
)
private fun getGenreList() = listOf(
Genre("арт", "el_5685"),
Genre("боевик", "el_2155"),
Genre("боевые искусства", "el_2143"),
Genre("вампиры", "el_2148"),
Genre("гарем", "el_2142"),
Genre("гендерная интрига", "el_2156"),
Genre("героическое фэнтези", "el_2146"),
Genre("детектив", "el_2152"),
Genre("дзёсэй", "el_2158"),
Genre("додзинси", "el_2141"),
Genre("драма", "el_2118"),
Genre("игра", "el_2154"),
Genre("история", "el_2119"),
Genre("киберпанк", "el_8032"),
Genre("кодомо", "el_2137"),
Genre("комедия", "el_2136"),
Genre("махо-сёдзё", "el_2147"),
Genre("меха", "el_2126"),
Genre("мистика", "el_2132"),
Genre("научная фантастика", "el_2133"),
Genre("повседневность", "el_2135"),
Genre("постапокалиптика", "el_2151"),
Genre("приключения", "el_2130"),
Genre("психология", "el_2144"),
Genre("романтика", "el_2121"),
Genre("самурайский боевик", "el_2124"),
Genre("сверхъестественное", "el_2159"),
Genre("сёдзё", "el_2122"),
Genre("сёдзё-ай", "el_2128"),
Genre("сёнэн", "el_2134"),
Genre("сёнэн-ай", "el_2139"),
Genre("спорт", "el_2129"),
Genre("сэйнэн", "el_2138"),
Genre("трагедия", "el_2153"),
Genre("триллер", "el_2150"),
Genre("ужасы", "el_2125"),
Genre("фантастика", "el_2140"),
Genre("фэнтези", "el_2131"),
Genre("школа", "el_2127"),
Genre("этти", "el_2149"),
Genre("юри", "el_2123")
)
} | apache-2.0 | cad15f59b35827db475d92a9c8f515dd | 38.198381 | 122 | 0.572978 | 3.949816 | false | false | false | false |
batagliao/onebible.android | app/src/main/java/com/claraboia/bibleandroid/activities/ReadActivity.kt | 1 | 7300 | package com.claraboia.bibleandroid.activities
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.support.design.widget.BottomSheetBehavior
import android.support.design.widget.NavigationView
import android.support.v4.view.GravityCompat
import android.support.v4.view.WindowCompat
import android.support.v7.app.AppCompatActivity
import android.view.*
import android.view.animation.DecelerateInterpolator
import com.claraboia.bibleandroid.R
import com.claraboia.bibleandroid.adapters.CENTER
import com.claraboia.bibleandroid.adapters.ReadViewPagerAdapter
import com.claraboia.bibleandroid.bibleApplication
import com.claraboia.bibleandroid.helpers.CheatSheet
import com.claraboia.bibleandroid.helpers.asFullText
import com.claraboia.bibleandroid.helpers.getAddressText
import com.claraboia.bibleandroid.models.BibleAddress
import com.google.firebase.analytics.FirebaseAnalytics
import kotlinx.android.synthetic.main.activity_read.*
import kotlinx.android.synthetic.main.app_bar_read.*
import kotlinx.android.synthetic.main.content_read.*
class ReadActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
private val firebaseAnalytics by lazy { FirebaseAnalytics.getInstance(this) }
private var isShowingBars = false
private val UI_ANIMATION_DELAY = 300L
private val mHideHandler = Handler()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_read)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayShowTitleEnabled(false)
supportActionBar?.setDisplayShowHomeEnabled(false)
supportActionBar?.setDisplayHomeAsUpEnabled(false)
supportActionBar?.setDisplayShowCustomEnabled(true)
supportActionBar?.setShowHideAnimationEnabled(true)
val navigationView = findViewById(R.id.nav_view) as NavigationView
navigationView.setNavigationItemSelectedListener(this)
//menu definition
btnOpenMenu.setOnClickListener { drawer.openDrawer(GravityCompat.START, true) }
val openBooksIntent = Intent(this, SelectBooksActivity::class.java)
//val openBooksIntent = Intent(this, TestFullscreenActivity::class.java)
btnBooks.setOnClickListener { startActivity(openBooksIntent) }
val openChapterIntent = Intent(this, SelectChapterActivity::class.java)
readTitle.setOnClickListener { startActivity(openChapterIntent) }
readTitle.text = bibleApplication.currentAddress.asFullText()
btnTranslations.setOnClickListener { drawer.openDrawer(GravityCompat.END, true) }
//set tooltips
CheatSheet.setup(btnOpenMenu)
CheatSheet.setup(btnBooks)
CheatSheet.setup(btnTranslations)
setupViewPager()
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
mHideHandler.removeCallbacks { hideSystemUI }
mHideHandler.postDelayed({
hide()
}, 3000)
}
override fun onBackPressed() {
//val drawer = findViewById(R.id.drawer_layout) as DrawerLayout
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
//menuInflater.inflate(R.menu.read, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId
//noinspection SimplifiableIfStatement
// if (id == R.id.action_settings) {
// return true
// }
return super.onOptionsItemSelected(item)
}
@SuppressWarnings("StatementWithEmptyBody")
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
val id = item.itemId
if (id == R.id.nav_translation) {
val openTranslationsItent = Intent(this, SelectTranslationActivity::class.java)
startActivity(openTranslationsItent)
}
//val drawer = findViewById(R.id.drawer_layout) as DrawerLayout
drawer.closeDrawer(GravityCompat.START)
return false
}
private fun setupViewPager() {
val adapter = ReadViewPagerAdapter(viewpagerRead, supportFragmentManager)
adapter.setPageChangedListener {
readTitle.text = it.asFullText()
}
viewpagerRead.adapter = adapter
viewpagerRead.setCurrentItem(CENTER, false)
}
private val hideSystemUI = Runnable {
// Set the IMMERSIVE flag.
// Set the content to appear under the system bars so that the content
// doesn't resize when the system bars hide and show.
content_read.systemUiVisibility =
View.SYSTEM_UI_FLAG_LOW_PROFILE or
View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or // hide nav bar //TODO: maybe remove this before
View.SYSTEM_UI_FLAG_FULLSCREEN or // hide status bar
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
}
private val showSystemUI = Runnable {
showActionBar()
//TODO: show bottom bar
}
fun toggleVisibility() {
if (isShowingBars)
hide()
else
show()
}
private fun hideActionBar() {
appbarlayout.animate()
.translationY((-toolbar.height).toFloat())
.setDuration(UI_ANIMATION_DELAY)
.setInterpolator(DecelerateInterpolator())
}
private fun hide() {
//TODO: hide bottom bar
isShowingBars = false
// Schedule a runnable to remove the status and navigation bar after a delay
mHideHandler.removeCallbacks(showSystemUI)
mHideHandler.postDelayed(hideSystemUI, UI_ANIMATION_DELAY)
hideActionBar()
}
private fun showActionBar() {
appbarlayout.animate()
.translationY(0F)
.setDuration(UI_ANIMATION_DELAY)
.setInterpolator(DecelerateInterpolator())
}
private fun show() {
content_read.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
isShowingBars = true
// Schedule a runnable to display UI elements after a delay
mHideHandler.removeCallbacks(hideSystemUI)
mHideHandler.postDelayed(showSystemUI, UI_ANIMATION_DELAY)
}
}
| apache-2.0 | 38d3a6efda97798640eecb378d76f7b1 | 33.761905 | 111 | 0.685068 | 5 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/ui/src/main/java/jp/hazuki/yuzubrowser/ui/widget/progress/BaseProgressLayerDrawable.kt | 1 | 3887 | /*
* Copyright (C) 2017-2021 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (c) 2017 Zhang Hai <[email protected]>
* All Rights Reserved.
*/
package jp.hazuki.yuzubrowser.ui.widget.progress
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.graphics.drawable.LayerDrawable
import android.util.Log
import androidx.annotation.ColorInt
import androidx.core.graphics.ColorUtils
import androidx.core.graphics.drawable.TintAwareDrawable
import jp.hazuki.yuzubrowser.ui.R
import jp.hazuki.yuzubrowser.ui.extensions.getColorFromAttrRes
import jp.hazuki.yuzubrowser.ui.extensions.getFloatFromAttrRes
@Suppress("LeakingThis", "UNCHECKED_CAST")
internal open class BaseProgressLayerDrawable<BackgroundDrawableType : TintAwareDrawable, ProgressDrawableType : TintAwareDrawable>(layers: Array<Drawable>, context: Context) : LayerDrawable(layers), MaterialProgressDrawable, TintAwareDrawable {
private val backgroundAlpha: Float = context.getFloatFromAttrRes(android.R.attr.disabledAlpha, 0f)
private val backgroundDrawable: BackgroundDrawableType
private val secondaryProgressDrawable: ProgressDrawableType
private val progressDrawable: ProgressDrawableType
init {
setId(0, android.R.id.background)
backgroundDrawable = getDrawable(0) as BackgroundDrawableType
setId(1, android.R.id.secondaryProgress)
secondaryProgressDrawable = getDrawable(1) as ProgressDrawableType
setId(2, android.R.id.progress)
progressDrawable = getDrawable(2) as ProgressDrawableType
val controlActivatedColor = context.getColorFromAttrRes(R.attr.colorControlActivated, Color.BLACK)
setTint(controlActivatedColor)
}
/**
* {@inheritDoc}
*/
@SuppressLint("NewApi")
override fun setTint(@ColorInt tintColor: Int) {
// Modulate alpha of tintColor against mBackgroundAlpha.
val backgroundTintColor = ColorUtils.setAlphaComponent(tintColor, Math.round(Color.alpha(
tintColor) * backgroundAlpha))
backgroundDrawable.setTint(backgroundTintColor)
secondaryProgressDrawable.setTint(backgroundTintColor)
progressDrawable.setTint(tintColor)
}
/**
* {@inheritDoc}
*/
@SuppressLint("NewApi")
override fun setTintList(tint: ColorStateList?) {
val backgroundTint: ColorStateList?
if (tint != null) {
if (!tint.isOpaque) {
Log.w(javaClass.simpleName, "setTintList() called with a non-opaque" + " ColorStateList, its original alpha will be discarded")
}
backgroundTint = tint.withAlpha(Math.round(backgroundAlpha * 255))
} else {
backgroundTint = null
}
backgroundDrawable.setTintList(backgroundTint)
secondaryProgressDrawable.setTintList(backgroundTint)
progressDrawable.setTintList(tint)
}
/**
* {@inheritDoc}
*/
@SuppressLint("NewApi")
override fun setTintMode(tintMode: PorterDuff.Mode?) {
backgroundDrawable.setTintMode(tintMode)
secondaryProgressDrawable.setTintMode(tintMode)
progressDrawable.setTintMode(tintMode)
}
}
| apache-2.0 | f4808ce8c4b30d72acbd17584ff4d790 | 36.019048 | 245 | 0.733471 | 4.643967 | false | false | false | false |
outware/neanderthal | neanderthal/src/main/kotlin/au/com/outware/neanderthal/Neanderthal.kt | 1 | 1127 | package au.com.outware.neanderthal
import android.content.Context
import au.com.outware.neanderthal.data.factory.ConfigurationFactoryImpl
import au.com.outware.neanderthal.data.model.ConfigurationFactory
import au.com.outware.neanderthal.data.repository.VariantRepository
import au.com.outware.neanderthal.data.repository.VariantSharedPreferencesRepository
/**
* @author timmutton
*/
class Neanderthal {
companion object {
var variantRepository: VariantRepository? = null
var configurationRepository: ConfigurationFactory? = null
@JvmStatic
fun initialise(context: Context, baseVariants: Map<String, Any>, defaultVariant: String) {
val klass = baseVariants.get(defaultVariant)!!.javaClass
variantRepository = VariantSharedPreferencesRepository(klass, context, baseVariants, defaultVariant)
configurationRepository = ConfigurationFactoryImpl(klass)
}
@Suppress("UNCHECKED_CAST")
@JvmStatic
fun <T> getConfiguration(): T {
return variantRepository?.getCurrentVariant()?.configuration as T
}
}
} | mit | 621fe8f00045983e2500ac9401d0ad0b | 35.387097 | 112 | 0.733807 | 4.986726 | false | true | false | false |
Laimiux/sqlin | sqlin/src/main/kotlin/com/laimiux/sqlin/Dao.kt | 1 | 2710 | package com.laimiux.sqlin
import android.database.sqlite.SQLiteDatabase
import android.database.Cursor
import android.content.ContentValues
import java.util.ArrayList
import java.util.HashMap
/**
* Dao class that provides query functionality
*/
public class Dao<T>(val database: SQLiteDatabase, val table: Table<T>) {
fun save(item: T): Long {
val values = ContentValues()
table.converter.toContentValues(values, item)
return database.insertWithOnConflict(table.tableName, null, values, SQLiteDatabase.CONFLICT_REPLACE)
}
fun getAll(): List<T> {
val cursor = database.query(table.tableName, table.getColumnNames(), null, null, null, null, null)
return getAll(cursor)
}
private fun getAll(cursor: Cursor): List<T> {
val items = ArrayList<T>()
cursor.moveToFirst()
while (!cursor.isAfterLast()) {
val item = table.converter.toItem(cursor)
items.add(item)
cursor.moveToNext()
}
cursor.close()
return items
}
fun query(): QueryBuilder {
return QueryBuilder()
}
public inner class QueryBuilder {
private var orderList: MutableList<String>? = null
private var whereMap: MutableMap<String, String>? = null
fun <T> orderBy(column: Column<T>, order: Order): QueryBuilder {
if(orderList == null) {
orderList = ArrayList()
}
orderList!!.add("${column.getColumnName()} ${order.name}")
return this
}
fun <K> equals(column: Column<K>, value: Any): QueryBuilder {
if(whereMap == null) {
whereMap = HashMap()
}
whereMap!!.put("${column.getColumnName()} = ?", value.toString())
return this
}
fun run(): List<T> {
val orderBy: String? =
if(orderList == null) null
else orderList!!.reduce { (computed, s) -> computed + "," }
var (selection: String?, selectionArgs: Array<String>?) = fromWhereMap()
val cursor = database.query(table.tableName, table.getColumnNames(), selection, selectionArgs, null, null, orderBy)
return getAll(cursor)
}
private fun fromWhereMap(): Pair<String?, Array<String>?> {
if(whereMap == null) {
return Pair<String?, Array<String>?>(null, null)
}
var selection: String = whereMap!!.keySet().reduce{(computed, s) -> "${computed} and ${s}"}
var selectionArgs = whereMap!!.values().copyToArray()
return Pair(selection, selectionArgs)
}
}
} | apache-2.0 | e32072c16b19941c7bab414675e9fa63 | 29.122222 | 127 | 0.581919 | 4.624573 | false | false | false | false |
hendraanggrian/picasso-transformations | pikasso-transformations/src/com/hendraanggrian/pikasso/internal/CropCircleTransformation.kt | 1 | 1250 | package com.hendraanggrian.pikasso.internal
import android.graphics.Bitmap
import android.graphics.Bitmap.Config.ARGB_8888
import android.graphics.Bitmap.createBitmap
import android.graphics.BitmapShader
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Shader.TileMode.CLAMP
import com.squareup.picasso.Transformation
import kotlin.math.min
internal class CropCircleTransformation : Transformation {
override fun transform(source: Bitmap): Bitmap {
val size = min(source.width, source.height)
val width = (source.width - size) / 2
val height = (source.height - size) / 2
val target = createBitmap(size, size, ARGB_8888)
val r = size / 2f
Canvas(target).drawCircle(r, r, r, Paint().apply {
isAntiAlias = true
shader = BitmapShader(source, CLAMP, CLAMP)
// source isn't square, move viewport to center
if (width != 0 || height != 0) shader.setLocalMatrix(Matrix().apply {
setTranslate(-width.toFloat(), -height.toFloat())
})
})
source.recycle()
return target
}
override fun key(): String = "CropCircleTransformation()"
}
| mit | 578c3463b25e234ce4a05c053e2dda9a | 34.714286 | 81 | 0.6776 | 4.416961 | false | false | false | false |
alt236/Under-the-Hood---Android | app/src/main/java/aws/apps/underthehood/ui/sharing/ExportFileWriter.kt | 1 | 1337 | package aws.apps.underthehood.ui.sharing
import android.content.Context
import android.os.Environment
import android.util.Log
import aws.apps.underthehood.ui.views.UserNotify
import java.io.File
import java.io.FileOutputStream
class ExportFileWriter(context: Context) {
private val userNotify = UserNotify(context.applicationContext)
fun exportData(sharePayload: SharePayload) {
val directory = Environment.getExternalStorageDirectory()
val filename = sharePayload.fileName
val contents = sharePayload.text
if (directory == null) {
Log.w(TAG, "Unable to write to SD. Folder was null!")
} else {
val fullPath = File(directory, filename)
writeToFile(fullPath, contents)
}
}
private fun writeToFile(file: File, contents: String) {
try {
FileOutputStream(file).use { output ->
output.write(contents.toByteArray(Charsets.UTF_8))
}
Log.d(TAG, "Wrote $file")
userNotify.notify("Wrote '$file'")
} catch (e: Exception) {
Log.e(TAG, "Error writing file: " + e.message)
userNotify.notify("Could not write file: ${e.message}")
}
}
private companion object {
val TAG = ExportFileWriter::class.java.simpleName
}
} | apache-2.0 | 3fec82286e262e13ab3421724bba5092 | 30.857143 | 67 | 0.637248 | 4.398026 | false | false | false | false |
shymmq/librus-client-kotlin | app/src/main/kotlin/com/wabadaba/dziennik/ui/timetable/LessonHeaderItem.kt | 1 | 2886 | package com.wabadaba.dziennik.ui.timetable
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.StyleSpan
import android.view.View
import com.wabadaba.dziennik.R
import com.wabadaba.dziennik.ui.*
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.items.AbstractExpandableHeaderItem
import eu.davidea.flexibleadapter.items.AbstractSectionableItem
import eu.davidea.flexibleadapter.items.IFlexible
import eu.davidea.viewholders.ExpandableViewHolder
import kotlinx.android.synthetic.main.item_lesson_header.view.*
import org.joda.time.LocalDate
import java.util.*
class LessonHeaderItem(val date: LocalDate)
: AbstractExpandableHeaderItem<LessonHeaderItem.ViewHolder, AbstractSectionableItem<*, *>>() {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LessonHeaderItem
if (date != other.date) return false
return true
}
override fun hashCode() = date.hashCode()
override fun createViewHolder(view: View, adapter: FlexibleAdapter<out IFlexible<*>>) = ViewHolder(view, adapter)
override fun getLayoutRes() = R.layout.item_lesson_header
override fun bindViewHolder(adapter: FlexibleAdapter<out IFlexible<*>>?, holder: ViewHolder, position: Int, payloads: MutableList<Any?>?) {
with(holder.itemView) {
item_lesson_header_title.text = getDateText()
item_lesson_header_summary.text = getSummaryText()
if (isExpanded) {
item_lesson_header_arrow.rotate(180f).disabled()
item_lesson_header_divider.gone()
} else {
item_lesson_header_arrow.rotate(0f).secondary()
item_lesson_header_divider.visible()
}
}
}
private fun getSummaryText(): String = when {
subItemsCount == 0 -> "Brak lekcji"
subItemsCount == 1 -> "$subItemsCount lekcja"
subItemsCount % 10 in 2..4 && subItemsCount % 100 !in 12..14 -> "$subItemsCount lekcje"
else -> "$subItemsCount lekcji"
}
private fun getDateText(): SpannableStringBuilder {
val title: String = when (date) {
LocalDate.now() -> "Dzisiaj"
LocalDate.now().plusDays(1) -> "Jutro"
else -> date.toString("EEEE", Locale("pl"))
}
val subtitle = date.toString("d.M")
return SpannableStringBuilder()
.append(title.capitalize(), StyleSpan(Typeface.BOLD), Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
.append(' ')
.append(subtitle)
}
class ViewHolder(view: View, adapter: FlexibleAdapter<*>) : ExpandableViewHolder(view, adapter) {
override fun shouldNotifyParentOnClick() = true
}
} | gpl-3.0 | d8d564ec0461f0e6faad57eb5984e6a0 | 36.012821 | 143 | 0.672557 | 4.516432 | false | false | false | false |
industrial-data-space/trusted-connector | ids-infomodel-manager/src/main/kotlin/de/fhg/aisec/ids/informationmodelmanager/deserializer/CustomObjectMapper.kt | 1 | 1159 | /*-
* ========================LICENSE_START=================================
* ids-infomodel-manager
* %%
* Copyright (C) 2017 - 2018 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.informationmodelmanager.deserializer
import com.fasterxml.jackson.databind.ObjectMapper
// use CostumModule allows Jackson to deserialize custom object types
class CustomObjectMapper : ObjectMapper() {
init {
this.registerModule(CustomModule())
}
companion object {
const val serialVersionUID = 1L
}
}
| apache-2.0 | bd731c065a4195b8b7b88e99dbbc10cb | 34.121212 | 75 | 0.654012 | 4.654618 | false | false | false | false |
kishmakov/Kitchen | server/src/io/magnaura/server/v1/handles/compile.kt | 1 | 2711 | package io.magnaura.server.v1.handles
import io.ktor.application.*
import io.ktor.http.*
import io.ktor.request.*
import io.ktor.response.*
import io.magnaura.platform.SupportedType
import io.magnaura.protocol.v1.CompileHandle
import io.magnaura.protocol.CompiledClass
import io.magnaura.server.Handler
import io.magnaura.server.compiler.*
import io.magnaura.server.md5
import io.magnaura.server.storage.COMMAND_STORAGE
import io.magnaura.server.storage.CONTEXT_STORAGE
import io.magnaura.server.v1.V1Frontend
import kotlinx.coroutines.*
sealed class CompilationResult {
data class Failure(val errors: List<String>) : CompilationResult()
data class Success(val commandType: SupportedType) : CompilationResult()
// fun toProtocolResponse(): CompileHandle.Response = when (this) {
// is Failure -> {
// CompileHandle.Response(failure = CompileHandle.Failure(errors))
// }
// is Success -> {
// val commandType = commandType.id
// CompileHandle.Response(success = CompileHandle.Success(commandType))
// }
// }
}
fun compileCommand(hash: String, context: String, command: String): CompilationResult {
val processor = CommandProcessor(hash, context, command)
val fileForCompilation = processor.fileForCompilation()
val analyser = ErrorAnalyzer(listOf(fileForCompilation))
with (analyser.messageCollector) {
if (hasErrors()) {
return CompilationResult.Failure(errors = errors() + warnings())
}
}
val compilation = KotlinCompiler(analyser).compile()
val compiledClasses = ArrayList<CompiledClass>()
return CompilationResult.Success(processor.commandType)
// listOf("command computer = ${fileForCompilation.text}") +
// compilation.files.map { "${it.key} -> ${it.value.size}" }
}
// val result = compileCommand(hash, context, command).toProtocolResponse()
suspend fun compileProcessor(call: ApplicationCall) {
val (context, command) = call.receive<CompileHandle.Request>()
val contextId = context.md5()
val commandId = (contextId + command).md5()
GlobalScope.launch(V1Frontend.dispatcher) {
val view = CompilationView(contextId, commandId, context, command)
if (!CONTEXT_STORAGE.contains(contextId)) {
CONTEXT_STORAGE.put(contextId, view.compileContext())
}
if (!COMMAND_STORAGE.contains(commandId)) {
COMMAND_STORAGE.put(commandId, view.compileCommand())
}
}
call.response.status(HttpStatusCode.Accepted)
call.respond(CompileHandle.Response(contextId, commandId))
}
val CompileHandler = Handler(
CompileHandle,
postProcessor = ::compileProcessor
) | gpl-3.0 | aed542282ec1b8ab2ec19954fdcd944e | 31.674699 | 87 | 0.70675 | 4.177196 | false | false | false | false |
hea3ven/Malleable | src/main/java/com/hea3ven/malleable/block/BlockMetalBase.kt | 1 | 2076 | package com.hea3ven.malleable.block
import com.hea3ven.malleable.item.ItemBlockMetal
import com.hea3ven.malleable.metal.Metal
import com.hea3ven.tools.commonutils.block.metadata.MetadataManagerBuilder
import com.hea3ven.tools.commonutils.client.renderer.color.IColorHandler
import net.minecraft.block.Block
import net.minecraft.block.material.Material
import net.minecraft.block.state.BlockStateContainer
import net.minecraft.block.state.IBlockState
import net.minecraft.creativetab.CreativeTabs
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.util.math.BlockPos
import net.minecraft.world.IBlockAccess
import net.minecraftforge.fml.relauncher.Side
import net.minecraftforge.fml.relauncher.SideOnly
abstract class BlockMetalBase(material: Material, override val metals: Array<Metal>) :
Block(material), BlockMetal {
val metaManager = MetadataManagerBuilder(this).map(4, getMetalProperty()).build()
override fun createBlockState() = BlockStateContainer(this, getMetalProperty())
override fun getMetaFromState(state: IBlockState) = metaManager.getMeta(state)
override fun getStateFromMeta(meta: Int) = metaManager.getState(meta)
override fun damageDropped(state: IBlockState) = getMetaFromState(state)
override fun getSubBlocks(item: Item, tab: CreativeTabs?, list: MutableList<ItemStack>) {
metals.forEach { list.add(createStack(it)) }
}
fun createStack(metal: Metal) = createStack(metal, 1)
fun createStack(metal: Metal, size: Int) = ItemStack(this, size,
damageDropped(getDefaultState().withProperty(getMetalProperty(), metal)))
companion object {
@SideOnly(Side.CLIENT)
fun getColorHandler() = object : IColorHandler {
override fun getColorFromItemstack(stack: ItemStack, tintIndex: Int): Int {
return ((stack.item as ItemBlockMetal).block as BlockMetal).getMetalFromStack(stack).color
}
override fun colorMultiplier(state: IBlockState, world: IBlockAccess?, pos: BlockPos?,
tintIndex: Int): Int {
return (state.block as BlockMetal).getMetalFromState(state).color
}
}
}
} | mit | da3b2537367168cbdc53081c0f73f7c5 | 36.089286 | 94 | 0.795279 | 3.774545 | false | true | false | false |
ujpv/intellij-rust | src/test/kotlin/org/rust/lang/core/resolve/RustResolveTestBase.kt | 1 | 2222 | package org.rust.lang.core.resolve
import com.intellij.psi.PsiElement
import org.assertj.core.api.Assertions.assertThat
import org.intellij.lang.annotations.Language
import org.rust.lang.RustTestCaseBase
import org.rust.lang.core.psi.RustNamedElement
import org.rust.lang.core.psi.RustReferenceElement
import org.rust.lang.core.resolve.ref.RustReference
abstract class RustResolveTestBase : RustTestCaseBase() {
override val dataPath = "org/rust/lang/core/resolve/fixtures"
private fun assertIsValidDeclaration(declaration: PsiElement, usage: RustReference,
expectedOffset: Int?) {
assertThat(declaration).isInstanceOf(RustNamedElement::class.java)
declaration as RustNamedElement
if (expectedOffset != null) {
assertThat(declaration.textOffset).isEqualTo(expectedOffset)
} else {
assertThat(declaration.name).isEqualTo(usage.canonicalText)
}
}
protected fun checkIsBound(atOffset: Int? = null) {
val usage = getReference()
assertThat(usage.resolve())
.withFailMessage("Failed to resolve `${usage.element.text}`.")
.isNotNull()
val declaration = usage.resolve()!!
assertIsValidDeclaration(declaration, usage, atOffset)
}
protected fun checkIsUnbound() {
val declaration = getReference().resolve()
assertThat(declaration).isNull()
}
protected fun checkByCode(@Language("Rust") code: String) {
InlineFile(code)
val (refElement, data) = findElementAndDataInEditor<RustReferenceElement>("^")
if (data == "unresolved") {
assertThat(refElement.reference.resolve()).isNull()
return
}
val resolved = checkNotNull(refElement.reference.resolve()) {
"Failed to resolve ${refElement.text}"
}
val target = findElementInEditor<RustNamedElement>("X")
assertThat(resolved).isEqualTo(target)
}
private fun getReference(): RustReference {
return requireNotNull(myFixture.getReferenceAtCaretPosition(fileName)) {
"No reference at caret in `$fileName`"
} as RustReference
}
}
| mit | e47bb2e6e79045125a71ae1934117600 | 31.676471 | 87 | 0.669217 | 4.982063 | false | false | false | false |
weisterjie/FamilyLedger | app/src/main/java/ycj/com/familyledger/ui/KLoginActivity.kt | 1 | 5107 | package ycj.com.familyledger.ui
import android.text.InputFilter
import android.text.InputType
import android.view.Gravity
import android.widget.EditText
import org.jetbrains.anko.*
import ycj.com.familyledger.Consts
import ycj.com.familyledger.R
import ycj.com.familyledger.bean.BaseResponse
import ycj.com.familyledger.bean.UserBean
import ycj.com.familyledger.http.HttpUtils
import ycj.com.familyledger.impl.BaseCallBack
import ycj.com.familyledger.utils.RegexUtils
import ycj.com.familyledger.utils.SPUtils
class KLoginActivity : KBaseActivity(), BaseCallBack<UserBean> {
private var edxPhone: EditText? = null
private var btnGo: android.widget.Button? = null
private var edxPassword: EditText? = null
override fun initialize() {
val phone = SPUtils.getInstance().getString(Consts.SP_PHONE)
val password = SPUtils.getInstance().getString(Consts.SP_PASSWORD)
edxPhone!!.setText(phone)
edxPassword!!.setText(password)
}
override fun initView() {
linearLayout {
lparams(height = matchParent, width = matchParent) {
orientation = android.widget.LinearLayout.VERTICAL
}
linearLayout {
textView("登录") {
textSize = resources.getDimension(R.dimen.title_size)
gravity = Gravity.CENTER
textColor = resources.getColor(R.color.white)
backgroundResource = R.color.color_title_bar
}.lparams(height = dip(48), width = matchParent)
}
linearLayout {
lparams(height = matchParent, width = matchParent) {
gravity = Gravity.CENTER
orientation = android.widget.LinearLayout.VERTICAL
topMargin = dip(40)
}
edxPhone = editText {
id = R.id.edx_phone_main
maxLines = 1
maxEms = 11
inputType = InputType.TYPE_CLASS_PHONE
filters = arrayOf<InputFilter>(InputFilter.LengthFilter(11))
backgroundResource = R.drawable.edx_input_bg
hint = "请输入手机号"
textSize = sp(4).toFloat()
}.lparams(width = matchParent, height = dip(40)) {
bottomMargin = dip(40)
leftMargin = dip(40)
rightMargin = dip(40)
}
edxPassword = editText {
id = R.id.edx_password_main
maxLines = 1
inputType = InputType.TYPE_TEXT_VARIATION_PASSWORD
filters = arrayOf<InputFilter>(InputFilter.LengthFilter(20))
backgroundResource = R.drawable.edx_input_bg
hint = "请输密码"
textSize = sp(4).toFloat()
}.lparams(width = matchParent, height = dip(40)) {
bottomMargin = dip(40)
leftMargin = dip(40)
rightMargin = dip(40)
}
btnGo = button {
id = R.id.btn_go_main
text = "进入应用"
textSize = sp(4).toFloat()
gravity = Gravity.CENTER
textColor = resources.getColor(R.color.white)
backgroundResource = R.drawable.bg_btn
}.lparams(width = matchParent, height = dip(40)) {
leftMargin = dip(40)
rightMargin = dip(40)
}
}
}
}
override fun initListener() {
btnGo!!.setOnClickListener {
val phone = edxPhone!!.text.toString().trim()
val password = edxPassword!!.text.toString().trim()
if (phone.length < 11) {
toast(getString(R.string.error_phone_number))
} else if (password.length < 3) {
toast(getString(R.string.password_not_full_six))
} else if (!RegexUtils.create().isMobileExact(phone)) {
toast(getString(R.string.not_phone_number))
} else {
showLoading()
HttpUtils.getInstance().login(phone, password, this@KLoginActivity)
}
}
}
override fun onSuccess(data: BaseResponse<UserBean>) {
hideLoading()
if (data.result == 1) {
saveData(data.data)
startActivity<KHomeActivity>()
finish()
toast("登录成功")
} else {
toast(data.error.message)
}
}
override fun onFail(msg: String) {
hideLoading()
toast(getString(R.string.fail_login_in))
}
private fun saveData(user: UserBean) {
SPUtils.getInstance().putString(Consts.SP_PHONE, edxPhone!!.text.toString())
SPUtils.getInstance().putString(Consts.SP_PASSWORD, edxPassword!!.text.toString())
SPUtils.getInstance().putLong(Consts.SP_USER_ID, user.userId!!)
}
} | apache-2.0 | d7dee4e579a291e9a67b5ddd4dcf6d70 | 35.460432 | 90 | 0.545885 | 4.848804 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/moderation/declarations/BanCommand.kt | 1 | 1200 | package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.moderation.declarations
import dev.kord.common.entity.Permission
import dev.kord.common.entity.Permissions
import net.perfectdreams.loritta.common.locale.LanguageManager
import net.perfectdreams.loritta.common.utils.TodoFixThisData
import net.perfectdreams.loritta.i18n.I18nKeysData
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandDeclarationWrapper
import net.perfectdreams.loritta.common.commands.CommandCategory
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.moderation.ban.BanExecutor
class BanCommand(languageManager: LanguageManager) : CinnamonSlashCommandDeclarationWrapper(languageManager) {
companion object {
val I18N_PREFIX = I18nKeysData.Commands.Command.Ban
val CATEGORY_I18N_PREFIX = I18nKeysData.Commands.Category.Moderation
}
override fun declaration() = slashCommand(I18N_PREFIX.Label, CommandCategory.MODERATION, I18N_PREFIX.Description) {
dmPermission = false
defaultMemberPermissions = Permissions {
+ Permission.BanMembers
}
executor = { BanExecutor(it) }
}
} | agpl-3.0 | e2417186948cc51917e36ea748a1e218 | 45.192308 | 119 | 0.8025 | 4.580153 | false | false | false | false |
darakeon/dfm | android/TestUtils/src/main/kotlin/com/darakeon/dfm/testutils/context/MockContext.kt | 1 | 5756 | package com.darakeon.dfm.testutils.context
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.ActivityInfo
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.content.res.Configuration
import android.content.res.Resources
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.os.Build
import android.util.TypedValue
import android.view.LayoutInflater
import androidx.annotation.RequiresApi
import com.darakeon.dfm.testutils.R
import org.mockito.ArgumentMatchers.any
import org.mockito.ArgumentMatchers.anyBoolean
import org.mockito.ArgumentMatchers.anyInt
import org.mockito.ArgumentMatchers.anyString
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.mockito.invocation.InvocationOnMock
import kotlin.reflect.KClass
class MockContext<A: Activity>(type: KClass<A>) {
val activity: A = mock(type.java)
private val manager = mock(ConnectivityManager::class.java)
private var themeId = 0
fun mockInternet(type: Int = 0): MockContext<A> {
`when`(
activity.getSystemService(
Context.CONNECTIVITY_SERVICE
)
).thenReturn(manager)
mockConnection(true, type)
return this
}
private fun mockConnection(succeeded: Boolean, type: Int = 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
mockConnectionNew(succeeded, type)
else
mockConnectionOld(succeeded)
}
@RequiresApi(Build.VERSION_CODES.M)
private fun mockConnectionNew(hasTransport: Boolean, type: Int = 0) {
val network = mock(Network::class.java)
`when`(manager.activeNetwork).thenReturn(network)
val capabilities = mock(NetworkCapabilities::class.java)
`when`(manager.getNetworkCapabilities(network))
.thenReturn(capabilities)
`when`(capabilities.hasTransport(anyInt()))
.thenAnswer {
(type == 0 && hasTransport)
|| (type != 0 && it.arguments[0] as Int == type)
}
}
@Suppress("DEPRECATION")
private fun mockConnectionOld(connected: Boolean) {
val info = mock(android.net.NetworkInfo::class.java)
`when`(manager.activeNetworkInfo).thenReturn(info)
`when`(info.state).thenReturn(
if (connected)
android.net.NetworkInfo.State.CONNECTED
else
android.net.NetworkInfo.State.DISCONNECTED
)
}
fun mockFailConnection() {
mockConnection(false)
}
fun mockEmptyConnection() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
mockEmptyConnectionNew()
else
mockEmptyConnectionOld()
}
@RequiresApi(Build.VERSION_CODES.M)
private fun mockEmptyConnectionNew() {
`when`(manager.activeNetwork).thenReturn(null)
}
@Suppress("DEPRECATION")
private fun mockEmptyConnectionOld() {
`when`(manager.activeNetworkInfo).thenReturn(null)
}
fun mockResources(): MockContext<A> {
val resources = mock(Resources::class.java)
`when`(activity.resources).thenReturn(resources)
val configuration = mock(Configuration::class.java)
`when`(resources.configuration)
.thenReturn(configuration)
return this
}
fun addStringResource(key: Int, value: String): MockContext<A> {
`when`(activity.getString(key))
.thenReturn(value)
return this
}
@SuppressLint("CommitPrefEdits")
fun mockSharedPreferences(): MockContext<A> {
val prefs = mock(SharedPreferences::class.java)
`when`(activity.getSharedPreferences("DfM", Context.MODE_PRIVATE))
.thenReturn(prefs)
val editor = mock(SharedPreferences.Editor::class.java)
`when`(prefs.edit()).thenReturn(editor)
val dic = HashMap<String, String>()
`when`(editor.putString(anyString(), anyString()))
.then {
val key = it.arguments[0].toString()
val value = it.arguments[1].toString()
dic[key] = value
null
}
`when`(prefs.getString(anyString(), anyString()))
.then {
val key = it.arguments[0].toString()
val defaultValue = it.arguments[1].toString()
if (dic.containsKey(key))
dic[key]
else
defaultValue
}
return this
}
fun mockExternalCall(): MockContext<A> {
val packManager = mock(PackageManager::class.java)
`when`(activity.packageManager).thenReturn(packManager)
val info = ResolveInfo()
info.activityInfo = ActivityInfo()
info.activityInfo.name = ""
info.activityInfo.applicationInfo = ApplicationInfo()
info.activityInfo.applicationInfo.packageName = ""
`when`(packManager.resolveActivity(any(), anyInt()))
.thenReturn(info)
return this
}
fun mockInflater(): LayoutInflater {
val inflater = mock(LayoutInflater::class.java)
`when`(activity.getSystemService(
Context.LAYOUT_INFLATER_SERVICE
)).thenReturn(inflater)
return inflater
}
fun mockTheme(): MockContext<A> {
val theme = mock(Resources.Theme::class.java)
`when`(theme.resolveAttribute(anyInt(), any(), anyBoolean()))
.then { getColor(it) }
`when`(activity.theme)
.thenReturn(theme)
`when`(activity.setTheme(anyInt()))
.then {
themeId = it.arguments[0] as Int
true
}
return this
}
private val darkColor = android.R.color.holo_orange_dark
private val lightColor = android.R.color.holo_orange_light
private val colors = hashMapOf(
R.style.DarkMagic to darkColor,
R.style.DarkSober to darkColor,
R.style.DarkNature to darkColor,
R.style.LightMagic to lightColor,
R.style.LightSober to lightColor,
R.style.LightNature to lightColor,
)
private fun getColor(invocation: InvocationOnMock): Boolean {
val attr = invocation.arguments[0] as Int
val typedValue = invocation.arguments[1] as TypedValue
if (attr == R.attr.background_highlight) {
typedValue.data = colors[themeId] ?: 0
return true
}
return false
}
}
| gpl-3.0 | 09cd353744a93db3de45bd4e14bcbc64 | 26.023474 | 70 | 0.741313 | 3.586293 | false | false | false | false |
EmmanuelMess/Simple-Accounting | SimpleAccounting/app/src/androidTest/java/com/emmanuelmess/simpleaccounting/TestExtensions.kt | 1 | 2261 | package com.emmanuelmess.simpleaccounting
import android.content.Context
import android.content.SharedPreferences
import android.view.View
import android.widget.TableRow
import android.widget.TextView
import androidx.test.espresso.NoMatchingViewException
import androidx.test.espresso.ViewAssertion
import androidx.test.espresso.ViewInteraction
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.withParent
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.platform.app.InstrumentationRegistry
import com.emmanuelmess.simpleaccounting.activities.MainActivity
import com.emmanuelmess.simpleaccounting.activities.views.LedgerRow
import com.emmanuelmess.simpleaccounting.activities.views.LedgerView
import junit.framework.AssertionFailedError
import org.hamcrest.BaseMatcher
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.allOf
import org.hamcrest.TypeSafeMatcher
internal fun Any.getPrefs(): SharedPreferences {
val context = InstrumentationRegistry.getInstrumentation().getTargetContext()
return context.getSharedPreferences(MainActivity.PREFS_NAME, Context.MODE_PRIVATE)
}
fun Any.lastRowOf(tableMatch: Matcher<View>) = object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("last row of: ")
tableMatch.describeTo(description)
}
override fun matchesSafely(row: View): Boolean {
if (row !is LedgerRow) return false
val table = row.parent as? LedgerView ?: return false
if (!tableMatch.matches(table)) return false
return row == table.getChildAt(table.childCount - 1)
}
}
fun Any.hasSameTextAs(sameTextInView: ViewInteraction) = ViewAssertion { view, noViewFoundException ->
noViewFoundException ?: return@ViewAssertion
if(view !is TextView) throw AssertionFailedError("expected TextView")
sameTextInView.check(matches(withText(view.text.toString())))
}
fun ViewInteraction.eitherOf(lhs: ViewAssertion, rhs: ViewAssertion): ViewInteraction {
return try {
check(lhs)
} catch (e: AssertionError) {
check(rhs)
}
}
fun Matcher<View>.andParent(parentMatcher: Matcher<View>): Matcher<View> {
return allOf(this, withParent(parentMatcher))
}
| gpl-3.0 | de73092e283a013dcaeed28112268d6f | 35.467742 | 102 | 0.819991 | 4.258004 | false | true | false | false |
DevCharly/kotlin-ant-dsl | src/main/kotlin/com/devcharly/kotlin/ant/taskdefs/javadoc.kt | 1 | 11889 | /*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import org.apache.tools.ant.taskdefs.Javadoc
import org.apache.tools.ant.taskdefs.Javadoc.ExtensionInfo
import org.apache.tools.ant.taskdefs.Javadoc.Html
import org.apache.tools.ant.taskdefs.Javadoc.PackageName
import org.apache.tools.ant.taskdefs.Javadoc.SourceFile
import org.apache.tools.ant.types.DirSet
import org.apache.tools.ant.types.FileSet
import org.apache.tools.ant.types.Path
import org.apache.tools.ant.types.Reference
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
fun Ant.javadoc(
useexternalfile: Boolean? = null,
defaultexcludes: Boolean? = null,
maxmemory: String? = null,
additionalparam: String? = null,
sourcepath: String? = null,
sourcepathref: String? = null,
destdir: String? = null,
sourcefiles: String? = null,
packagenames: String? = null,
excludepackagenames: String? = null,
overview: String? = null,
public: Boolean? = null,
protected: Boolean? = null,
Package: Boolean? = null,
private: Boolean? = null,
access: AccessType? = null,
doclet: String? = null,
docletpath: String? = null,
docletpathref: String? = null,
old: Boolean? = null,
classpath: String? = null,
classpathref: String? = null,
bootclasspath: String? = null,
bootclasspathref: String? = null,
extdirs: String? = null,
verbose: Boolean? = null,
locale: String? = null,
encoding: String? = null,
version: Boolean? = null,
use: Boolean? = null,
author: Boolean? = null,
splitindex: Boolean? = null,
windowtitle: String? = null,
doctitle: String? = null,
header: String? = null,
footer: String? = null,
bottom: String? = null,
linkoffline: String? = null,
group: String? = null,
link: String? = null,
nodeprecated: Boolean? = null,
nodeprecatedlist: Boolean? = null,
notree: Boolean? = null,
noindex: Boolean? = null,
nohelp: Boolean? = null,
nonavbar: Boolean? = null,
serialwarn: Boolean? = null,
stylesheetfile: String? = null,
helpfile: String? = null,
docencoding: String? = null,
packagelist: String? = null,
charset: String? = null,
failonerror: Boolean? = null,
failonwarning: Boolean? = null,
source: String? = null,
executable: String? = null,
linksource: Boolean? = null,
breakiterator: Boolean? = null,
noqualifier: String? = null,
includenosourcepackages: Boolean? = null,
docfilessubdirs: Boolean? = null,
excludedocfilessubdir: String? = null,
postprocessgeneratedjavadocs: Boolean? = null,
nested: (KJavadoc.() -> Unit)? = null)
{
Javadoc().execute("javadoc") { task ->
if (useexternalfile != null)
task.setUseExternalFile(useexternalfile)
if (defaultexcludes != null)
task.setDefaultexcludes(defaultexcludes)
if (maxmemory != null)
task.setMaxmemory(maxmemory)
if (additionalparam != null)
task.setAdditionalparam(additionalparam)
if (sourcepath != null)
task.setSourcepath(Path(project, sourcepath))
if (sourcepathref != null)
task.setSourcepathRef(Reference(project, sourcepathref))
if (destdir != null)
task.setDestdir(project.resolveFile(destdir))
if (sourcefiles != null)
task.setSourcefiles(sourcefiles)
if (packagenames != null)
task.setPackagenames(packagenames)
if (excludepackagenames != null)
task.setExcludePackageNames(excludepackagenames)
if (overview != null)
task.setOverview(project.resolveFile(overview))
if (public != null)
task.setPublic(public)
if (protected != null)
task.setProtected(protected)
if (Package != null)
task.setPackage(Package)
if (private != null)
task.setPrivate(private)
if (access != null)
task.setAccess(Javadoc.AccessType().apply { this.value = access.value })
if (doclet != null)
task.setDoclet(doclet)
if (docletpath != null)
task.setDocletPath(Path(project, docletpath))
if (docletpathref != null)
task.setDocletPathRef(Reference(project, docletpathref))
if (old != null)
task.setOld(old)
if (classpath != null)
task.setClasspath(Path(project, classpath))
if (classpathref != null)
task.setClasspathRef(Reference(project, classpathref))
if (bootclasspath != null)
task.setBootclasspath(Path(project, bootclasspath))
if (bootclasspathref != null)
task.setBootClasspathRef(Reference(project, bootclasspathref))
if (extdirs != null)
task.setExtdirs(Path(project, extdirs))
if (verbose != null)
task.setVerbose(verbose)
if (locale != null)
task.setLocale(locale)
if (encoding != null)
task.setEncoding(encoding)
if (version != null)
task.setVersion(version)
if (use != null)
task.setUse(use)
if (author != null)
task.setAuthor(author)
if (splitindex != null)
task.setSplitindex(splitindex)
if (windowtitle != null)
task.setWindowtitle(windowtitle)
if (doctitle != null)
task.setDoctitle(doctitle)
if (header != null)
task.setHeader(header)
if (footer != null)
task.setFooter(footer)
if (bottom != null)
task.setBottom(bottom)
if (linkoffline != null)
task.setLinkoffline(linkoffline)
if (group != null)
task.setGroup(group)
if (link != null)
task.setLink(link)
if (nodeprecated != null)
task.setNodeprecated(nodeprecated)
if (nodeprecatedlist != null)
task.setNodeprecatedlist(nodeprecatedlist)
if (notree != null)
task.setNotree(notree)
if (noindex != null)
task.setNoindex(noindex)
if (nohelp != null)
task.setNohelp(nohelp)
if (nonavbar != null)
task.setNonavbar(nonavbar)
if (serialwarn != null)
task.setSerialwarn(serialwarn)
if (stylesheetfile != null)
task.setStylesheetfile(project.resolveFile(stylesheetfile))
if (helpfile != null)
task.setHelpfile(project.resolveFile(helpfile))
if (docencoding != null)
task.setDocencoding(docencoding)
if (packagelist != null)
task.setPackageList(packagelist)
if (charset != null)
task.setCharset(charset)
if (failonerror != null)
task.setFailonerror(failonerror)
if (failonwarning != null)
task.setFailonwarning(failonwarning)
if (source != null)
task.setSource(source)
if (executable != null)
task.setExecutable(executable)
if (linksource != null)
task.setLinksource(linksource)
if (breakiterator != null)
task.setBreakiterator(breakiterator)
if (noqualifier != null)
task.setNoqualifier(noqualifier)
if (includenosourcepackages != null)
task.setIncludeNoSourcePackages(includenosourcepackages)
if (docfilessubdirs != null)
task.setDocFilesSubDirs(docfilessubdirs)
if (excludedocfilessubdir != null)
task.setExcludeDocFilesSubDir(excludedocfilessubdir)
if (postprocessgeneratedjavadocs != null)
task.setPostProcessGeneratedJavadocs(postprocessgeneratedjavadocs)
if (nested != null)
nested(KJavadoc(task))
}
}
class KJavadoc(override val component: Javadoc) :
IFileSetNested
{
fun arg(value: String? = null, line: String? = null, path: String? = null, pathref: String? = null, file: String? = null, prefix: String? = null, suffix: String? = null) {
component.createArg().apply {
component.project.setProjectReference(this)
_init(value, line, path, pathref, file, prefix, suffix)
}
}
fun sourcepath(location: String? = null, path: String? = null, cache: Boolean? = null, nested: (KPath.() -> Unit)? = null) {
component.createSourcepath().apply {
component.project.setProjectReference(this)
_init(location, path, cache, nested)
}
}
fun source(file: String? = null) {
component.addSource(SourceFile().apply {
_init(component.project, file)
})
}
fun Package(name: String? = null) {
component.addPackage(PackageName().apply {
_init(name)
})
}
fun excludepackage(name: String? = null) {
component.addExcludePackage(PackageName().apply {
_init(name)
})
}
fun doclet(name: String? = null, path: String? = null, pathref: String? = null, nested: (KDocletInfo.() -> Unit)? = null) {
component.createDoclet().apply {
component.project.setProjectReference(this)
_init(name, path, pathref, nested)
}
}
fun taglet(name: String? = null, path: String? = null, pathref: String? = null, nested: (KExtensionInfo.() -> Unit)? = null) {
component.addTaglet(ExtensionInfo().apply {
component.project.setProjectReference(this)
_init(name, path, pathref, nested)
})
}
fun classpath(location: String? = null, path: String? = null, cache: Boolean? = null, nested: (KPath.() -> Unit)? = null) {
component.createClasspath().apply {
component.project.setProjectReference(this)
_init(location, path, cache, nested)
}
}
fun bootclasspath(location: String? = null, path: String? = null, cache: Boolean? = null, nested: (KPath.() -> Unit)? = null) {
component.createBootclasspath().apply {
component.project.setProjectReference(this)
_init(location, path, cache, nested)
}
}
fun doctitle(nested: (KHtml.() -> Unit)? = null) {
component.addDoctitle(Html().apply {
_init(nested)
})
}
fun header(nested: (KHtml.() -> Unit)? = null) {
component.addHeader(Html().apply {
_init(nested)
})
}
fun footer(nested: (KHtml.() -> Unit)? = null) {
component.addFooter(Html().apply {
_init(nested)
})
}
fun bottom(nested: (KHtml.() -> Unit)? = null) {
component.addBottom(Html().apply {
_init(nested)
})
}
fun link(href: String? = null, packagelistloc: String? = null, packagelisturl: String? = null, offline: Boolean? = null, resolvelink: Boolean? = null) {
component.createLink().apply {
_init(component.project, href, packagelistloc, packagelisturl, offline, resolvelink)
}
}
fun tag(dir: String? = null, file: String? = null, includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, defaultexcludes: Boolean? = null, casesensitive: Boolean? = null, followsymlinks: Boolean? = null, maxlevelsofsymlinks: Int? = null, erroronmissingdir: Boolean? = null, name: String? = null, scope: String? = null, enabled: Boolean? = null, nested: (KTagArgument.() -> Unit)? = null) {
component.createTag().apply {
component.project.setProjectReference(this)
_init(dir, file, includes, excludes, includesfile, excludesfile, defaultexcludes, casesensitive, followsymlinks, maxlevelsofsymlinks, erroronmissingdir, name, scope, enabled, nested)
}
}
fun group(title: String? = null, packages: String? = null, nested: (KGroupArgument.() -> Unit)? = null) {
component.createGroup().apply {
_init(title, packages, nested)
}
}
fun packageset(dir: String? = null, file: String? = null, includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, defaultexcludes: Boolean? = null, casesensitive: Boolean? = null, followsymlinks: Boolean? = null, maxlevelsofsymlinks: Int? = null, erroronmissingdir: Boolean? = null, nested: (KDirSet.() -> Unit)? = null) {
component.addPackageset(DirSet().apply {
component.project.setProjectReference(this)
_init(dir, file, includes, excludes, includesfile, excludesfile, defaultexcludes, casesensitive, followsymlinks, maxlevelsofsymlinks, erroronmissingdir, nested)
})
}
override fun _addFileSet(value: FileSet) = component.addFileset(value)
}
enum class AccessType(val value: String) { PROTECTED("protected"), PUBLIC("public"), PACKAGE("package"), PRIVATE("private") }
| apache-2.0 | ce148f2517d946f0a309bb7f397d563e | 35.027273 | 448 | 0.700648 | 3.261728 | false | false | false | false |
cliffano/swaggy-jenkins | clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/GithubScm.kt | 1 | 1329 | package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import org.openapitools.model.GithubScmlinks
import javax.validation.constraints.DecimalMax
import javax.validation.constraints.DecimalMin
import javax.validation.constraints.Email
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
import javax.validation.Valid
import io.swagger.v3.oas.annotations.media.Schema
/**
*
* @param propertyClass
* @param links
* @param credentialId
* @param id
* @param uri
*/
data class GithubScm(
@Schema(example = "null", description = "")
@field:JsonProperty("_class") val propertyClass: kotlin.String? = null,
@field:Valid
@Schema(example = "null", description = "")
@field:JsonProperty("_links") val links: GithubScmlinks? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("credentialId") val credentialId: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("id") val id: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("uri") val uri: kotlin.String? = null
) {
}
| mit | 6057961879d2061878e18e579148d20b | 28.533333 | 80 | 0.737397 | 3.990991 | false | false | false | false |
sampsonjoliver/Firestarter | app/src/main/java/com/sampsonjoliver/firestarter/models/Session.kt | 1 | 1122 | package com.sampsonjoliver.firestarter.models
import com.google.android.gms.maps.model.LatLng
import com.google.firebase.database.Exclude
import java.util.*
class Session(
var userId: String,
var username: String,
var topic: String,
var description: String,
var bannerUrl: String,
var lat: Double,
var lng: Double,
var address: String,
var url: String,
var tags: MutableMap<String, Boolean>,
var startDate: Long,
var durationMs: Long
) {
@Exclude var sessionId: String? = null
@Exclude var startDateAsDate: Date = Date()
@Exclude get() = Date(startDate)
@Exclude var endDate: Long = 0
@Exclude get() = startDate + durationMs
@Exclude var endDateAsDate: Date = Date()
@Exclude get() = Date(startDate + durationMs)
@Exclude fun getLocation(): LatLng = LatLng(lat, lng)
@Exclude fun setLocation(value: LatLng) {
lat = value.latitude
lng = value.longitude
}
constructor() : this("", "", "", "", "", 0.0, 0.0, "", "", mutableMapOf(), 0, 0)
} | apache-2.0 | aa324bc624e8898733fbaad6cab98780 | 28.552632 | 84 | 0.606952 | 4.25 | false | false | false | false |
tgirard12/kotlin-talk | talk/src/main/kotlin/com/tgirard12/kotlintalk/03_Function.kt | 1 | 2750 | package com.tgirard12.kotlintalk
import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import java.time.LocalTime
import java.util.*
fun main(args: Array<String>) {
// Can declare function in function -> scope
// Better solution than private function because parent args are available one child
fun double(x: Int): Int = x * 2 // Single expression function -> no {} required
println(double(2))
// Name param
println(double(x = 2))
// type inference
fun double1(x: Int) = x * 2 // type inference
println(double1(x = 2))
// Default Param
fun doubleDefault(x: Int = 2) = double(x)
println(doubleDefault(8))
// Exemple with split function
println("kotlin".split("t"))
// Extension function only ToChar()
fun String.only2Char() = this.substring(0, 2)
println("kotlin".only2Char())
// Nullable extension type
fun String?.only2Char() = this?.substring(0, 2)
println((null as String?).only2Char())
// with generic types
// listof is an extension function
fun List<String>.countFirst() = this.get(0).length
println(listOf("a", "bc", "def").countFirst())
// println(listOf(1, 5).countTotal()) not available for Int
// Infix for better readability
// Usefull also for big decimal, assertion
infix fun Int.hours(minute: Int) = LocalTime.of(this, minute)
println(5 hours 40)
//
// Hight order function
//
// A higher-order function is a function that takes functions as parameters, or returns a function
fun log(f: () -> Unit) {
println("begin")
try {
f()
println("end")
} catch (ex: Exception) {
println("EX ${ex.message}")
}
}
// Execute code
log({ println("kotlin") })
log({ throw NullPointerException("null") })
// Better with database in Android to execute a transaction
fun SQLiteDatabase.inTx(f: SQLiteDatabase.() -> Unit) {
this.beginTransaction()
try {
f()
this.setTransactionSuccessful()
} finally {
this.endTransaction()
}
}
val db = SQLiteDatabase.openDatabase("", null, 0)
db.inTx {
insert("TABLE", null, ContentValues(1))
update("TABLE", ContentValues(1), "col=?", arrayOf())
}
// apply, let, run, with
// instanciate object with local variable to modify it
GregorianCalendar().apply {
timeInMillis = System.currentTimeMillis()
}
val str: String? = null
// not with if (str != null)
// if only one argument, it's it (like in Groovy)
// run only if not null
str?.let { println(it.length) }
// inline
// no inline
}
| apache-2.0 | 7a28aba2e8a5182d047b6c595f1b87cd | 26.777778 | 102 | 0.612 | 4.147813 | false | false | false | false |
mcxiaoke/kotlin-koi | samples/src/main/kotlin/com/mcxiaoke/koi/samples/CursorSample.kt | 1 | 3098 | package com.mcxiaoke.koi.samples
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import com.mcxiaoke.koi.ext.*
/**
* Author: mcxiaoke
* Date: 2016/2/2 21:10
*/
// sample data class
data class UserInfo(val name: String, val age: Int, val bio: String?, val hasPet: Boolean)
class CursorExtensionSample(context: Context, name: String,
factory: SQLiteDatabase.CursorFactory?, version: Int)
: SQLiteOpenHelper(context, name, factory, version) {
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
throw UnsupportedOperationException()
}
override fun onCreate(db: SQLiteDatabase?) {
throw UnsupportedOperationException()
}
// available for Cursor
fun cursorValueExtensions() {
val cursor = this.writableDatabase.query("table", null, null, null, null, null, null)
cursor.moveToFirst()
do {
val intVal = cursor.intValue("column-a")
val stringVal = cursor.stringValue("column-b")
val longVal = cursor.longValue("column-c")
val booleanValue = cursor.booleanValue("column-d")
val doubleValue = cursor.doubleValue("column-e")
val floatValue = cursor.floatValue("column-f")
// no need to do like this, so verbose
cursor.getInt(cursor.getColumnIndexOrThrow("column-a"))
cursor.getString(cursor.getColumnIndexOrThrow("column-b"))
} while (cursor.moveToNext())
}
// available for Cursor
// transform cursor to model object
fun cursorToModels() {
val where = " age>? "
val whereArgs = arrayOf("20")
val cursor = this.readableDatabase.query("users", null, where, whereArgs, null, null, null)
val users1 = cursor.map {
UserInfo(
stringValue("name"),
intValue("age"),
stringValue("bio"),
booleanValue("pet_flag"))
}
// or using mapAndClose
val users2 = cursor.mapAndClose {
UserInfo(
stringValue("name"),
intValue("age"),
stringValue("bio"),
booleanValue("pet_flag"))
}
// or using Cursor?mapTo(collection, transform())
}
// available for SQLiteDatabase and SQLiteOpenHelper
// auto apply transaction to db operations
fun inTransaction() {
val db = this.writableDatabase
val values = ContentValues()
// or db.transaction
transaction {
db.execSQL("insert into users (?,?,?) (1,2,3)")
db.insert("users", null, values)
}
// equal to
db.beginTransaction()
try {
db.execSQL("insert into users (?,?,?) (1,2,3)")
db.insert("users", null, values)
db.setTransactionSuccessful()
} finally {
db.endTransaction()
}
}
} | apache-2.0 | 808c23396fcfffddfdda7f0115cc8fe4 | 31.621053 | 99 | 0.589413 | 4.833073 | false | false | false | false |
meh/watch_doge | src/main/java/meh/watchdoge/request/Request.kt | 1 | 810 | package meh.watchdoge.request;
import android.os.Message;
class Request(id: Int): Builder {
private val _id = id;
private lateinit var family: Family;
override fun build(msg: Message) {
msg.what = _id;
family.build(msg);
}
fun control(body: Control.() -> Unit) {
val next = Control();
next.body();
family = next;
}
fun sniffer(id: Int?, body: Sniffer.() -> Unit) {
val next = Sniffer(id);
next.body();
family = next;
}
fun sniffer(body: Sniffer.() -> Unit) {
sniffer(null, body);
}
fun wireless(body: Wireless.() -> Unit) {
val next = Wireless();
next.body();
family = next;
}
fun pinger(id: Int?, body: Pinger.() -> Unit) {
val next = Pinger(id);
next.body();
family = next;
}
fun pinger(body: Pinger.() -> Unit) {
pinger(null, body);
}
}
| agpl-3.0 | 2532587302d213457c375987b493500f | 15.530612 | 50 | 0.597531 | 2.718121 | false | false | false | false |
camsteffen/polite | src/main/java/me/camsteffen/polite/model/CalendarRuleKeyword.kt | 1 | 787 | package me.camsteffen.polite.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.ForeignKey.CASCADE
import androidx.room.Ignore
import androidx.room.PrimaryKey
@Entity(
tableName = "calendar_rule_keyword",
foreignKeys = [
ForeignKey(
entity = RuleEntity::class,
parentColumns = ["id"],
childColumns = ["rule_id"],
onDelete = CASCADE,
onUpdate = CASCADE
)
]
)
class CalendarRuleKeyword(
@PrimaryKey(autoGenerate = true)
val id: Long,
@ColumnInfo(name = "rule_id", index = true)
val ruleId: Long,
val keyword: String
) {
@Ignore
constructor(ruleId: Long, keyword: String) : this(0L, ruleId, keyword)
}
| mpl-2.0 | d65c57b3126b6453b19b36219e2c1beb | 22.848485 | 74 | 0.650572 | 4.208556 | false | false | false | false |
InnoFang/Android-Code-Demos | JetPackDemo/app/src/main/java/io/github/innofang/jetpackdemo/MainActivity.kt | 1 | 2083 | package io.github.innofang.jetpackdemo
import android.app.Activity
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import android.arch.lifecycle.ViewModelProviders
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
companion object {
const val NEW_WORD_ACTIVITY_REQUEST_CODE = 1
}
private lateinit var wordViewModel: WordViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
val adapter = WordListAdapter(this)
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(this)
val newWordFAB = findViewById<FloatingActionButton>(R.id.new_word_fab)
newWordFAB.setOnClickListener {
startActivityForResult(
Intent(this, NewWordActivity::class.java), NEW_WORD_ACTIVITY_REQUEST_CODE)
}
wordViewModel = ViewModelProviders.of(this).get(WordViewModel::class.java)
wordViewModel.allWords.observe(this,
Observer<List<Word>> { words -> words?.let { adapter.words = it } })
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == NEW_WORD_ACTIVITY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
data?.let {
val word = Word(it.getStringExtra(NewWordActivity.EXTRA_REPLY))
wordViewModel.insert(word)
}
} else {
Toast.makeText(this, R.string.empty_not_saved, Toast.LENGTH_LONG).show()
}
}
}
| apache-2.0 | 443c922319daaa23169a9e17f4225e49 | 36.872727 | 96 | 0.710514 | 4.567982 | false | false | false | false |
emufog/emufog | src/main/kotlin/emufog/backbone/BackboneConnector.kt | 1 | 3788 | /*
* 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.backbone
import emufog.graph.AS
import emufog.graph.Node
import emufog.graph.NodeType
import emufog.graph.NodeType.BACKBONE_NODE
import emufog.graph.NodeType.EDGE_NODE
import java.util.ArrayDeque
import java.util.BitSet
import java.util.Queue
/**
* The backbone connector picks an arbitrary backbone node and connects it to any other backbone node it can find
* within the given autonomous system. This way it can establish a connected backbone for the AS.
*/
internal class BackboneConnector(private val system: AS) {
private val visited = BitSet()
private val seen = BitSet()
private val queue: Queue<Node> = ArrayDeque()
private val predecessors: MutableMap<Node, Node?> = HashMap()
private fun Node?.isType(type: NodeType) = this != null && this.type == type
/**
* Creates a single connected backbone by using the Breadth-First-Algorithm.
*/
internal fun connectBackbone() {
val backboneNodes = system.backboneNodes
if (backboneNodes.isEmpty()) {
return
}
// start with any backbone node
val node = backboneNodes.first()
predecessors[node] = null
queue.add(node)
while (queue.isNotEmpty()) {
processNode(queue.poll())
}
}
private fun processNode(node: Node) {
if (visited[node.id]) {
return
}
visited.set(node.id)
// follow a trace via the predecessor to convert all on this way
if (node.isType(BACKBONE_NODE) && predecessors[node].isType(EDGE_NODE)) {
connectTwoBackbones(node)
}
// add or update neighborhood
node.edges
.filterNot { it.isCrossASEdge() }
.map { it.getDestinationForSource(node) }
.filterNot { it == null || visited[it.id] }
.forEach { updateNeighborNode(it!!, node) }
}
private fun updateNeighborNode(neighbor: Node, node: Node) {
if (seen[neighbor.id]) {
// update the predecessor if necessary
if (node.isType(BACKBONE_NODE) && predecessors[neighbor].isType(EDGE_NODE)) {
predecessors[neighbor] = node
}
} else {
// push a new node to the queue
predecessors[neighbor] = node
queue.add(neighbor)
seen.set(neighbor.id)
}
}
private fun connectTwoBackbones(node: Node) {
var predecessor = predecessors[node]
while (predecessor.isType(EDGE_NODE)) {
predecessor.toBackboneNode()
predecessor = predecessors[predecessor]
}
}
}
| mit | 5db349861303d13bb4e46d1308fb043a | 33.126126 | 113 | 0.661563 | 4.440797 | false | false | false | false |
emufog/emufog | src/test/kotlin/emufog/backbone/BackboneTest.kt | 1 | 4545 | /*
* MIT License
*
* Copyright (c) 2019 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.backbone
import emufog.graph.Graph
import emufog.graph.Node
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Test
internal class BackboneWorkerTest {
private val defaultBaseAddress = "1.2.3.4"
@Test
fun `identify a backbone for a line topology with one autonomous system`() {
val n = 10
val graph = Graph(defaultBaseAddress)
val system = graph.getOrCreateAutonomousSystem(0)
for (i in 0 until n) {
val edgeNode = graph.createEdgeNode(i, system)
if (i > 0) {
graph.createEdge(i, edgeNode, graph.getEdgeNode(i - 1)!!, 1F, 1F)
}
}
assertEquals(n, graph.edgeNodes.size)
assertEquals(0, graph.backboneNodes.size)
assertEquals(n - 1, graph.edges.size)
identifyBackbone(graph)
assertEquals(n - 2, graph.backboneNodes.size)
for (i in 1 until n - 1) {
assertNotNull(graph.getBackboneNode(i))
}
assertEquals(2, graph.edgeNodes.size)
assertEquals(n - 1, graph.edges.size)
}
@Test
fun `identify cross as edges as backbone connections`() {
val graph = Graph(defaultBaseAddress)
val system0 = graph.getOrCreateAutonomousSystem(0)
val system1 = graph.getOrCreateAutonomousSystem(1)
val node0 = graph.createEdgeNode(0, system0)
val node1 = graph.createEdgeNode(1, system1)
graph.createEdge(0, node0, node1, 1F, 1000F)
assertEquals(2, graph.edgeNodes.size)
assertEquals(0, graph.backboneNodes.size)
assertEquals(1, graph.edges.size)
convertCrossAsEdges(graph.edges)
assertEquals(2, graph.backboneNodes.size)
assertEquals(0, graph.edgeNodes.size)
assertEquals(1, graph.edges.size)
}
@Test
fun `identify a circle as no backbone connection`() {
val graph = Graph(defaultBaseAddress)
val system = graph.getOrCreateAutonomousSystem(0)
val node0 = graph.createEdgeNode(0, system)
val node1 = graph.createEdgeNode(1, system)
val node2 = graph.createEdgeNode(2, system)
graph.createEdge(0, node0, node1, 1F, 1000F)
graph.createEdge(1, node2, node1, 1F, 1000F)
graph.createEdge(2, node2, node0, 1F, 1000F)
assertEquals(3, graph.edgeNodes.size)
assertEquals(0, graph.backboneNodes.size)
assertEquals(3, graph.edges.size)
identifyBackbone(graph)
assertEquals(0, graph.backboneNodes.size)
assertEquals(3, graph.edgeNodes.size)
assertEquals(3, graph.edges.size)
}
@Test
fun `toBackboneNode should do nothing if null`() {
val node: Node? = null
assertNull(node.toBackboneNode())
}
@Test
fun `toBackboneNode should replace a node with a backbone node`() {
val graph = Graph(defaultBaseAddress)
val system = graph.getOrCreateAutonomousSystem(0)
val node = graph.createEdgeNode(0, system)
val backboneNode = node.toBackboneNode()
assertNotNull(backboneNode)
assertEquals(system, backboneNode!!.system)
assertEquals(0, backboneNode.id)
assertNull(graph.getEdgeNode(0))
assertNotNull(graph.getBackboneNode(0))
}
} | mit | fbab95d47debac9e6e8906e36a2d9a96 | 34.795276 | 81 | 0.681408 | 4.196676 | false | true | false | false |
HendraAnggrian/kota | kota-design/src/layouts/WidgetsDesign.kt | 1 | 7439 | @file:Suppress("NOTHING_TO_INLINE", "UNUSED")
package kota
import android.app.Dialog
import android.content.Context
import android.support.design.widget.*
import android.support.v4.app.Fragment
//region Layouts
inline fun Context.appBarLayout(init: (@KotaDsl _AppBarLayout).() -> Unit): AppBarLayout = _AppBarLayout(this).apply(init)
inline fun android.app.Fragment.appBarLayout(init: (@KotaDsl _AppBarLayout).() -> Unit): AppBarLayout = _AppBarLayout(activity).apply(init)
inline fun Fragment.appBarLayout(init: (@KotaDsl _AppBarLayout).() -> Unit): AppBarLayout = _AppBarLayout(context!!).apply(init)
inline fun Dialog.appBarLayout(init: (@KotaDsl _AppBarLayout).() -> Unit): AppBarLayout = _AppBarLayout(context).apply(init)
inline fun ViewRoot.appBarLayout(init: (@KotaDsl _AppBarLayout).() -> Unit): AppBarLayout = _AppBarLayout(getContext()).apply(init).add()
inline fun Context.bottomNavigationView(init: (@KotaDsl _BottomNavigationView).() -> Unit): BottomNavigationView = _BottomNavigationView(this).apply(init)
inline fun android.app.Fragment.bottomNavigationView(init: (@KotaDsl _BottomNavigationView).() -> Unit): BottomNavigationView = _BottomNavigationView(activity).apply(init)
inline fun Fragment.bottomNavigationView(init: (@KotaDsl _BottomNavigationView).() -> Unit): BottomNavigationView = _BottomNavigationView(context!!).apply(init)
inline fun Dialog.bottomNavigationView(init: (@KotaDsl _BottomNavigationView).() -> Unit): BottomNavigationView = _BottomNavigationView(context).apply(init)
inline fun ViewRoot.bottomNavigationView(init: (@KotaDsl _BottomNavigationView).() -> Unit): BottomNavigationView = _BottomNavigationView(getContext()).apply(init).add()
inline fun Context.collapsingToolbarLayout(init: (@KotaDsl _CollapsingToolbarLayout).() -> Unit): CollapsingToolbarLayout = _CollapsingToolbarLayout(this).apply(init)
inline fun android.app.Fragment.collapsingToolbarLayout(init: (@KotaDsl _CollapsingToolbarLayout).() -> Unit): CollapsingToolbarLayout = _CollapsingToolbarLayout(activity).apply(init)
inline fun Fragment.collapsingToolbarLayout(init: (@KotaDsl _CollapsingToolbarLayout).() -> Unit): CollapsingToolbarLayout = _CollapsingToolbarLayout(context!!).apply(init)
inline fun Dialog.collapsingToolbarLayout(init: (@KotaDsl _CollapsingToolbarLayout).() -> Unit): CollapsingToolbarLayout = _CollapsingToolbarLayout(context).apply(init)
inline fun ViewRoot.collapsingToolbarLayout(init: (@KotaDsl _CollapsingToolbarLayout).() -> Unit): CollapsingToolbarLayout = _CollapsingToolbarLayout(getContext()).apply(init).add()
inline fun Context.coordinatorLayout(init: (@KotaDsl _CoordinatorLayout).() -> Unit): CoordinatorLayout = _CoordinatorLayout(this).apply(init)
inline fun android.app.Fragment.coordinatorLayout(init: (@KotaDsl _CoordinatorLayout).() -> Unit): CoordinatorLayout = _CoordinatorLayout(activity).apply(init)
inline fun Fragment.coordinatorLayout(init: (@KotaDsl _CoordinatorLayout).() -> Unit): CoordinatorLayout = _CoordinatorLayout(context!!).apply(init)
inline fun Dialog.coordinatorLayout(init: (@KotaDsl _CoordinatorLayout).() -> Unit): CoordinatorLayout = _CoordinatorLayout(context).apply(init)
inline fun ViewRoot.coordinatorLayout(init: (@KotaDsl _CoordinatorLayout).() -> Unit): CoordinatorLayout = _CoordinatorLayout(getContext()).apply(init).add()
inline fun Context.tabLayout(init: (@KotaDsl _TabLayout).() -> Unit): TabLayout = _TabLayout(this).apply(init)
inline fun android.app.Fragment.tabLayout(init: (@KotaDsl _TabLayout).() -> Unit): TabLayout = _TabLayout(activity).apply(init)
inline fun Fragment.tabLayout(init: (@KotaDsl _TabLayout).() -> Unit): TabLayout = _TabLayout(context!!).apply(init)
inline fun Dialog.tabLayout(init: (@KotaDsl _TabLayout).() -> Unit): TabLayout = _TabLayout(context).apply(init)
inline fun ViewRoot.tabLayout(init: (@KotaDsl _TabLayout).() -> Unit): TabLayout = _TabLayout(getContext()).apply(init).add()
inline fun Context.textInputLayout(init: (@KotaDsl _TextInputLayout).() -> Unit): TextInputLayout = _TextInputLayout(this).apply(init)
inline fun android.app.Fragment.textInputLayout(init: (@KotaDsl _TextInputLayout).() -> Unit): TextInputLayout = _TextInputLayout(activity).apply(init)
inline fun Fragment.textInputLayout(init: (@KotaDsl _TextInputLayout).() -> Unit): TextInputLayout = _TextInputLayout(context!!).apply(init)
inline fun Dialog.textInputLayout(init: (@KotaDsl _TextInputLayout).() -> Unit): TextInputLayout = _TextInputLayout(context).apply(init)
inline fun ViewRoot.textInputLayout(init: (@KotaDsl _TextInputLayout).() -> Unit): TextInputLayout = _TextInputLayout(getContext()).apply(init).add()
//endregion
//region Views
inline fun Context.floatingActionButton(init: (@KotaDsl FloatingActionButton).() -> Unit): FloatingActionButton = FloatingActionButton(this).apply(init)
inline fun android.app.Fragment.floatingActionButton(init: (@KotaDsl FloatingActionButton).() -> Unit): FloatingActionButton = FloatingActionButton(activity).apply(init)
inline fun Fragment.floatingActionButton(init: (@KotaDsl FloatingActionButton).() -> Unit): FloatingActionButton = FloatingActionButton(context).apply(init)
inline fun Dialog.floatingActionButton(init: (@KotaDsl FloatingActionButton).() -> Unit): FloatingActionButton = FloatingActionButton(context).apply(init)
inline fun ViewRoot.floatingActionButton(init: (@KotaDsl FloatingActionButton).() -> Unit): FloatingActionButton = FloatingActionButton(getContext()).apply(init).add()
inline fun Context.navigationView(init: (@KotaDsl NavigationView).() -> Unit): NavigationView = NavigationView(this).apply(init)
inline fun android.app.Fragment.navigationView(init: (@KotaDsl NavigationView).() -> Unit): NavigationView = NavigationView(activity).apply(init)
inline fun Fragment.navigationView(init: (@KotaDsl NavigationView).() -> Unit): NavigationView = NavigationView(context).apply(init)
inline fun Dialog.navigationView(init: (@KotaDsl NavigationView).() -> Unit): NavigationView = NavigationView(context).apply(init)
inline fun ViewRoot.navigationView(init: (@KotaDsl NavigationView).() -> Unit): NavigationView = NavigationView(getContext()).apply(init).add()
inline fun Context.tabItem(init: (@KotaDsl TabItem).() -> Unit): TabItem = TabItem(this).apply(init)
inline fun android.app.Fragment.tabItem(init: (@KotaDsl TabItem).() -> Unit): TabItem = TabItem(activity).apply(init)
inline fun Fragment.tabItem(init: (@KotaDsl TabItem).() -> Unit): TabItem = TabItem(context).apply(init)
inline fun Dialog.tabItem(init: (@KotaDsl TabItem).() -> Unit): TabItem = TabItem(context).apply(init)
inline fun ViewRoot.tabItem(init: (@KotaDsl TabItem).() -> Unit): TabItem = TabItem(getContext()).apply(init)
inline fun Context.textInputEditText(init: (@KotaDsl TextInputEditText).() -> Unit): TextInputEditText = TextInputEditText(this).apply(init)
inline fun android.app.Fragment.textInputEditText(init: (@KotaDsl TextInputEditText).() -> Unit): TextInputEditText = TextInputEditText(activity).apply(init)
inline fun Fragment.textInputEditText(init: (@KotaDsl TextInputEditText).() -> Unit): TextInputEditText = TextInputEditText(context).apply(init)
inline fun Dialog.textInputEditText(init: (@KotaDsl TextInputEditText).() -> Unit): TextInputEditText = TextInputEditText(context).apply(init)
inline fun ViewRoot.textInputEditText(init: (@KotaDsl TextInputEditText).() -> Unit): TextInputEditText = TextInputEditText(getContext()).apply(init).add()
//endregion | apache-2.0 | 9b0533b89b5cd50fb2a595ca124d4495 | 99.540541 | 183 | 0.777927 | 4.524939 | false | false | false | false |
Shynixn/BlockBall | blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/business/commandmenu/OpenPage.kt | 1 | 5185 | package com.github.shynixn.blockball.core.logic.business.commandmenu
import com.github.shynixn.blockball.api.business.enumeration.*
import com.github.shynixn.blockball.api.business.service.PersistenceArenaService
import com.github.shynixn.blockball.api.business.service.ProxyService
import com.github.shynixn.blockball.api.persistence.entity.ChatBuilder
import com.github.shynixn.blockball.core.logic.persistence.entity.ChatBuilderEntity
import com.google.inject.Inject
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
class OpenPage @Inject constructor(private val arenaRepository: PersistenceArenaService, private val proxyService: ProxyService) :
Page(OpenPage.ID, OpenPage.ID) {
/**
* Returns the key of the command when this page should be executed.
*
* @return key
*/
override fun getCommandKey(): MenuPageKey {
return MenuPageKey.OPEN
}
companion object {
/** Id of the page. */
const val ID = 1
}
/**
* Executes actions for this page.
*
* @param cache cache
*/
override fun <P> execute(player: P, command: MenuCommand, cache: Array<Any?>, args: Array<String>): MenuCommandResult {
if (command == MenuCommand.OPEN_EDIT_ARENA) {
var builder: ChatBuilder? = null
for (arena in this.arenaRepository.getArenas()) {
if (builder == null) {
builder = ChatBuilderEntity()
}
builder.component("- Arena: Id: " + arena.name + " Name: " + arena.displayName).builder()
.component(" [page..]").setColor(ChatColor.YELLOW)
.setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.ARENA_EDIT.command + arena.name)
.setHoverText("Opens the arena with the id " + arena.name + ".").builder().nextLine()
}
if (builder != null) {
proxyService.sendMessage(player, builder)
}
return MenuCommandResult.CANCEL_MESSAGE
} else if (command == MenuCommand.OPEN_DELETE_ARENA) {
var builder: ChatBuilder? = null
for (arena in this.arenaRepository.getArenas()) {
if (builder == null) {
builder = ChatBuilderEntity()
}
builder.component("- Arena: Id: " + arena.name + " Name: " + arena.displayName).builder()
.component(" [delete..]").setColor(ChatColor.DARK_RED)
.setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.ARENA_DELETE.command + arena.name)
.setHoverText("Deletes the arena with the id " + arena.name + ".").builder().nextLine()
}
if (builder != null) {
proxyService.sendMessage(player, builder)
}
return MenuCommandResult.CANCEL_MESSAGE
}
return super.execute(player, command, cache, args)
}
/**
* Builds this page for the player.
*
* @param cache cache.
* @return page
*/
override fun buildPage(cache: Array<Any?>): ChatBuilder? {
return ChatBuilderEntity()
.component("- Create arena:").builder()
.component(" [create..]").setColor(ChatColor.AQUA)
.setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.TEMPLATE_OPEN.command)
.setHoverText("Creates a new blockball arena.").builder().nextLine()
.component("- Edit arena:").builder()
.component(" [page..]").setColor(ChatColor.YELLOW)
.setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.OPEN_EDIT_ARENA.command)
.setHoverText("Opens the arena selection list.").builder().nextLine()
.component("- Remove arena:").builder()
.component(" [page..]").setColor(ChatColor.YELLOW)
.setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.OPEN_DELETE_ARENA.command)
.setHoverText("Deletes a blockball arena.").builder()
}
}
| apache-2.0 | 3619b4cfa66cea2b87f89d3dee639ea5 | 41.85124 | 130 | 0.64243 | 4.508696 | false | false | false | false |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/main/java/com/garpr/android/data/models/FullTournament.kt | 1 | 2907 | package com.garpr.android.data.models
import android.os.Parcel
import android.os.Parcelable
import androidx.core.os.ParcelCompat
import com.garpr.android.extensions.createParcel
import com.garpr.android.extensions.optAbsPlayerList
import com.garpr.android.extensions.requireAbsPlayer
import com.garpr.android.extensions.requireParcelable
import com.garpr.android.extensions.requireString
import com.garpr.android.extensions.writeAbsPlayer
import com.garpr.android.extensions.writeAbsPlayerList
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
class FullTournament(
@Json(name = "regions") regions: List<String>? = null,
@Json(name = "date") date: SimpleDate,
@Json(name = "id") id: String,
@Json(name = "name") name: String,
@Json(name = "players") val players: List<AbsPlayer>? = null,
@Json(name = "matches") val matches: List<Match>? = null,
@Json(name = "url") val url: String? = null
) : AbsTournament(
regions,
date,
id,
name
), Parcelable {
override val kind: Kind
get() = Kind.FULL
override fun writeToParcel(dest: Parcel, flags: Int) {
super.writeToParcel(dest, flags)
dest.writeAbsPlayerList(players, flags)
dest.writeTypedList(matches)
dest.writeString(url)
}
companion object {
@JvmField
val CREATOR = createParcel {
FullTournament(
it.createStringArrayList(),
it.requireParcelable(SimpleDate::class.java.classLoader),
it.requireString(),
it.requireString(),
it.optAbsPlayerList(),
it.createTypedArrayList(Match.CREATOR),
it.readString()
)
}
}
@JsonClass(generateAdapter = false)
data class Match(
val loser: AbsPlayer,
val winner: AbsPlayer,
val excluded: Boolean,
val matchId: Int
) : Parcelable {
override fun equals(other: Any?): Boolean {
return other is Match && matchId == other.matchId
}
override fun hashCode(): Int = matchId.hashCode()
override fun describeContents(): Int = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeAbsPlayer(loser, flags)
dest.writeAbsPlayer(winner, flags)
ParcelCompat.writeBoolean(dest, excluded)
dest.writeInt(matchId)
}
companion object {
@JvmField
val CREATOR = createParcel {
Match(
it.requireAbsPlayer(),
it.requireAbsPlayer(),
ParcelCompat.readBoolean(it),
it.readInt()
)
}
}
}
}
| unlicense | 3e2c1bd03acff034a89487e27567e63a | 30.258065 | 77 | 0.590643 | 4.696284 | false | false | false | false |
wuseal/JsonToKotlinClass | src/main/kotlin/wu/seal/jsontokotlin/model/classscodestruct/SealedClass.kt | 1 | 2274 | package wu.seal.jsontokotlin.model.classscodestruct
import wu.seal.jsontokotlin.model.builder.ICodeBuilder
import wu.seal.jsontokotlin.utils.getIndent
import wu.seal.jsontokotlin.utils.toAnnotationComments
import wu.seal.jsontokotlin.utils.addIndent
data class SealedClass(
override val name: String,
override val generic: KotlinClass,
override val referencedClasses: List<KotlinClass> = listOf(generic),
val discriminatoryProperties: List<Property>,
val comments: String = "",
override val modifiable: Boolean = true,
override val codeBuilder: ICodeBuilder<*> = ICodeBuilder.EMPTY
) : ModifiableKotlinClass, NoGenericKotlinClass {
override fun rename(newName: String): KotlinClass = copy(name = newName)
override fun getCode(): String {
return getOnlyCurrentCode()
}
private fun getDiscriminatoryPropertiesCode(): String {
return discriminatoryPropertiesCode(this.discriminatoryProperties)
}
override fun getOnlyCurrentCode(): String {
val indent = getIndent()
val innerReferencedClasses =
referencedClasses.flatMap { it.referencedClasses }.distinctBy { it.name }
.filter { it.modifiable }
return buildString {
append(comments.toAnnotationComments())
append("sealed class $name(${getDiscriminatoryPropertiesCode()}) {\n")
referencedClasses.forEach { it ->
// TODO: Ensure that `referencedClasses` are actually of type `DataClass`
append((it as DataClass).withExtends(
discriminatoryProperties.map { it.name },
this@SealedClass).getOnlyCurrentCode().addIndent(indent))
append("\n")
}
append("}\n\n")
innerReferencedClasses.forEach {
append(it.getCode())
append("\n")
}
}
}
override fun replaceReferencedClasses(replaceRule: Map<KotlinClass, KotlinClass>): KotlinClass {
TODO("Not yet implemented")
}
companion object {
fun discriminatoryPropertiesCode(properties: List<Property>): String {
return properties.joinToString(", ") {
it.getCode()
}
}
}
}
| gpl-3.0 | becd0a7636e8d44101bf3c56382fa834 | 35.677419 | 100 | 0.646878 | 5.008811 | false | false | false | false |
kvnxiao/kommandant | kommandant-core/src/main/kotlin/com/github/kvnxiao/kommandant/impl/CommandParser.kt | 2 | 4646 | /*
* Copyright 2017 Ze Hao Xiao
*
* 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.kvnxiao.kommandant.impl
import com.github.kvnxiao.kommandant.ICommandParser
import com.github.kvnxiao.kommandant.Kommandant.Companion.LOGGER
import com.github.kvnxiao.kommandant.command.CommandAnn
import com.github.kvnxiao.kommandant.command.CommandContext
import com.github.kvnxiao.kommandant.command.CommandDefaults
import com.github.kvnxiao.kommandant.command.ICommand
import com.github.kvnxiao.kommandant.utility.CommandMap
import com.github.kvnxiao.kommandant.utility.CommandStack
import com.github.kvnxiao.kommandant.utility.CommandStringMap
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method
import java.util.Stack
/**
* The default implementation of [ICommandParser]. Parses a class containing the [CommandAnn] annotation to create
* commands from these annotations.
*/
open class CommandParser : ICommandParser {
/**
* Parse [CommandAnn] annotations in a class and returns a list of commands created from those annotations.
*
* @param[instance] The instance object for which its class is to be parsed.
* @return[List] The list of commands created after parsing.
*/
override fun parseAnnotations(instance: Any): List<ICommand<*>> {
// Instantiate new instance of class to reference method invocations
val clazz = instance::class.java
// Use hashmaps to link sub commands to parent commands
val subCommands: CommandStringMap = mutableMapOf()
val commands: CommandMap = mutableMapOf()
val mainCommands: CommandStack = Stack()
// Create and add command to bank for each methods with 'executable' signature type
for (method in clazz.methods) {
if (method.isAnnotationPresent(CommandAnn::class.java)) {
val annotation: CommandAnn = method.getAnnotation(CommandAnn::class.java)
// Create command to add to bank
val command: ICommand<*> = this.createCommand(instance, method, annotation)
// Add main commands and chainable main commands to command bank
if (annotation.parentName != CommandDefaults.PARENT || annotation.parentName == annotation.uniqueName) {
subCommands.put(command, annotation.parentName)
}
if (annotation.parentName == CommandDefaults.PARENT || annotation.parentName == annotation.uniqueName) {
mainCommands.push(command)
}
commands.put(annotation.uniqueName, command)
}
}
// Link sub commands to parent
for ((subCommand, parentName) in subCommands) {
commands[parentName]?.addSubcommand(subCommand)
LOGGER.debug("Registered command '${subCommand.props.uniqueName}' as a subcommand of parent '$parentName'")
}
// Clear utility containers as we are done adding all commands
subCommands.clear()
commands.clear()
return mainCommands.toList()
}
/**
* Creates a command by parsing a single [CommandAnn] annotation, with its execution method set as the method
* targeted by the annotation.
*
* @param[instance] The instance object for which its class is to be parsed.
* @param[method] The method to invoke for command execution.
* @param[annotation] The annotation to parse.
* @return[ICommand] A newly created command with properties taken from the annotation.
*/
override fun createCommand(instance: Any, method: Method, annotation: CommandAnn): ICommand<Any?> {
return object : ICommand<Any?>(annotation.prefix, annotation.uniqueName, annotation.description, annotation.usage, annotation.execWithSubcommands, annotation.isDisabled, *annotation.aliases) {
@Throws(InvocationTargetException::class, IllegalAccessException::class)
override fun execute(context: CommandContext, vararg opt: Any?): Any? {
return method.invoke(instance, context, opt)
}
}
}
} | apache-2.0 | c65b7e7243ab8acf25aed8d44fa0bc46 | 44.558824 | 200 | 0.700818 | 4.789691 | false | false | false | false |
square/moshi | moshi/src/main/java/com/squareup/moshi/-MoshiKotlinExtensions.kt | 1 | 2230 | /*
* Copyright (C) 2019 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("EXTENSION_SHADOWED_BY_MEMBER")
package com.squareup.moshi
import com.squareup.moshi.internal.NonNullJsonAdapter
import com.squareup.moshi.internal.NullSafeJsonAdapter
import kotlin.reflect.KType
import kotlin.reflect.javaType
import kotlin.reflect.typeOf
/**
* @return a [JsonAdapter] for [T], creating it if necessary. Note that while nullability of [T]
* itself is handled, nested types (such as in generics) are not resolved.
*/
@Deprecated("Use the Moshi instance version instead", level = DeprecationLevel.HIDDEN)
@ExperimentalStdlibApi
public inline fun <reified T> Moshi.adapter(): JsonAdapter<T> = adapter(typeOf<T>())
@Deprecated("Use the Moshi instance version instead", level = DeprecationLevel.HIDDEN)
@ExperimentalStdlibApi
public inline fun <reified T> Moshi.Builder.addAdapter(adapter: JsonAdapter<T>): Moshi.Builder = add(typeOf<T>().javaType, adapter)
/**
* @return a [JsonAdapter] for [ktype], creating it if necessary. Note that while nullability of
* [ktype] itself is handled, nested types (such as in generics) are not resolved.
*/
@Deprecated("Use the Moshi instance version instead", level = DeprecationLevel.HIDDEN)
@ExperimentalStdlibApi
public fun <T> Moshi.adapter(ktype: KType): JsonAdapter<T> {
val adapter = adapter<T>(ktype.javaType)
return if (adapter is NullSafeJsonAdapter || adapter is NonNullJsonAdapter) {
// TODO CR - Assume that these know what they're doing? Or should we defensively avoid wrapping for matching nullability?
adapter
} else if (ktype.isMarkedNullable) {
adapter.nullSafe()
} else {
adapter.nonNull()
}
}
| apache-2.0 | 559416ae9f2ce8fcaa6ae4577e8dd89b | 40.296296 | 131 | 0.74843 | 4.183865 | false | false | false | false |
orbit/orbit | src/orbit-client/src/main/kotlin/orbit/client/net/ClientAuthInterceptor.kt | 1 | 1598 | /*
Copyright (C) 2015 - 2019 Electronic Arts Inc. All rights reserved.
This file is part of the Orbit Project <https://www.orbit.cloud>.
See license in LICENSE.
*/
package orbit.client.net
import io.grpc.CallOptions
import io.grpc.Channel
import io.grpc.ClientCall
import io.grpc.ClientInterceptor
import io.grpc.ForwardingClientCall
import io.grpc.Metadata
import io.grpc.MethodDescriptor
import orbit.shared.proto.Headers
internal class ClientAuthInterceptor(private val localNode: LocalNode) : ClientInterceptor {
override fun <ReqT : Any?, RespT : Any?> interceptCall(
method: MethodDescriptor<ReqT, RespT>,
callOptions: CallOptions,
next: Channel
): ClientCall<ReqT, RespT> {
return object :
ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
override fun start(responseListener: Listener<RespT>?, headers: Metadata) {
val nodeId = localNode.status.nodeInfo?.id
if (nodeId == null) {
headers.put(NAMESPACE, localNode.status.namespace)
} else {
headers.put(NAMESPACE, nodeId.namespace)
headers.put(NODE_KEY, nodeId.key)
}
super.start(responseListener, headers)
}
}
}
companion object {
private val NAMESPACE = Metadata.Key.of(Headers.NAMESPACE_NAME, Metadata.ASCII_STRING_MARSHALLER)
private val NODE_KEY = Metadata.Key.of(Headers.NODE_KEY_NAME, Metadata.ASCII_STRING_MARSHALLER)
}
} | bsd-3-clause | a534cb2b55cc23c8860ff84cc5a68329 | 33.76087 | 109 | 0.662078 | 4.295699 | false | false | false | false |
Vavassor/Tusky | app/src/main/java/com/keylesspalace/tusky/service/SendTootService.kt | 1 | 12534 | package com.keylesspalace.tusky.service
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.ClipData
import android.content.ClipDescription
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.IBinder
import android.os.Parcelable
import androidx.core.app.NotificationCompat
import androidx.core.app.ServiceCompat
import androidx.core.content.ContextCompat
import com.keylesspalace.tusky.R
import com.keylesspalace.tusky.appstore.EventHub
import com.keylesspalace.tusky.appstore.StatusComposedEvent
import com.keylesspalace.tusky.db.AccountEntity
import com.keylesspalace.tusky.db.AccountManager
import com.keylesspalace.tusky.db.AppDatabase
import com.keylesspalace.tusky.di.Injectable
import com.keylesspalace.tusky.entity.Status
import com.keylesspalace.tusky.network.MastodonApi
import com.keylesspalace.tusky.util.SaveTootHelper
import com.keylesspalace.tusky.util.randomAlphanumericString
import dagger.android.AndroidInjection
import kotlinx.android.parcel.Parcelize
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class SendTootService : Service(), Injectable {
@Inject
lateinit var mastodonApi: MastodonApi
@Inject
lateinit var accountManager: AccountManager
@Inject
lateinit var eventHub: EventHub
@Inject
lateinit var database: AppDatabase
private lateinit var saveTootHelper: SaveTootHelper
private val tootsToSend = ConcurrentHashMap<Int, TootToSend>()
private val sendCalls = ConcurrentHashMap<Int, Call<Status>>()
private val timer = Timer()
private val notificationManager by lazy { getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager }
override fun onCreate() {
AndroidInjection.inject(this)
saveTootHelper = SaveTootHelper(database.tootDao(), this)
super.onCreate()
}
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
if (intent.hasExtra(KEY_TOOT)) {
val tootToSend = intent.getParcelableExtra<TootToSend>(KEY_TOOT)
?: throw IllegalStateException("SendTootService started without $KEY_TOOT extra")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(CHANNEL_ID, getString(R.string.send_toot_notification_channel_name), NotificationManager.IMPORTANCE_LOW)
notificationManager.createNotificationChannel(channel)
}
var notificationText = tootToSend.warningText
if (notificationText.isBlank()) {
notificationText = tootToSend.text
}
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notify)
.setContentTitle(getString(R.string.send_toot_notification_title))
.setContentText(notificationText)
.setProgress(1, 0, true)
.setOngoing(true)
.setColor(ContextCompat.getColor(this, R.color.tusky_blue))
.addAction(0, getString(android.R.string.cancel), cancelSendingIntent(sendingNotificationId))
if (tootsToSend.size == 0 || Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_DETACH)
startForeground(sendingNotificationId, builder.build())
} else {
notificationManager.notify(sendingNotificationId, builder.build())
}
tootsToSend[sendingNotificationId] = tootToSend
sendToot(sendingNotificationId--)
} else {
if (intent.hasExtra(KEY_CANCEL)) {
cancelSending(intent.getIntExtra(KEY_CANCEL, 0))
}
}
return START_NOT_STICKY
}
private fun sendToot(tootId: Int) {
// when tootToSend == null, sending has been canceled
val tootToSend = tootsToSend[tootId] ?: return
// when account == null, user has logged out, cancel sending
val account = accountManager.getAccountById(tootToSend.accountId)
if (account == null) {
tootsToSend.remove(tootId)
notificationManager.cancel(tootId)
stopSelfWhenDone()
return
}
tootToSend.retries++
val sendCall = mastodonApi.createStatus(
"Bearer " + account.accessToken,
account.domain,
tootToSend.text,
tootToSend.inReplyToId,
tootToSend.warningText,
tootToSend.visibility,
tootToSend.sensitive,
tootToSend.mediaIds,
tootToSend.idempotencyKey
)
sendCalls[tootId] = sendCall
val callback = object : Callback<Status> {
override fun onResponse(call: Call<Status>, response: Response<Status>) {
tootsToSend.remove(tootId)
if (response.isSuccessful) {
// If the status was loaded from a draft, delete the draft and associated media files.
if (tootToSend.savedTootUid != 0) {
saveTootHelper.deleteDraft(tootToSend.savedTootUid)
}
response.body()?.let(::StatusComposedEvent)?.let(eventHub::dispatch)
notificationManager.cancel(tootId)
} else {
// the server refused to accept the toot, save toot & show error message
saveTootToDrafts(tootToSend)
val builder = NotificationCompat.Builder(this@SendTootService, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notify)
.setContentTitle(getString(R.string.send_toot_notification_error_title))
.setContentText(getString(R.string.send_toot_notification_saved_content))
.setColor(ContextCompat.getColor(this@SendTootService, R.color.tusky_blue))
notificationManager.cancel(tootId)
notificationManager.notify(errorNotificationId--, builder.build())
}
stopSelfWhenDone()
}
override fun onFailure(call: Call<Status>, t: Throwable) {
var backoff = TimeUnit.SECONDS.toMillis(tootToSend.retries.toLong())
if (backoff > MAX_RETRY_INTERVAL) {
backoff = MAX_RETRY_INTERVAL
}
timer.schedule(object : TimerTask() {
override fun run() {
sendToot(tootId)
}
}, backoff)
}
}
sendCall.enqueue(callback)
}
private fun stopSelfWhenDone() {
if (tootsToSend.isEmpty()) {
ServiceCompat.stopForeground(this@SendTootService, ServiceCompat.STOP_FOREGROUND_REMOVE)
stopSelf()
}
}
private fun cancelSending(tootId: Int) {
val tootToCancel = tootsToSend.remove(tootId)
if (tootToCancel != null) {
val sendCall = sendCalls.remove(tootId)
sendCall?.cancel()
saveTootToDrafts(tootToCancel)
val builder = NotificationCompat.Builder(this@SendTootService, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notify)
.setContentTitle(getString(R.string.send_toot_notification_cancel_title))
.setContentText(getString(R.string.send_toot_notification_saved_content))
.setColor(ContextCompat.getColor(this@SendTootService, R.color.tusky_blue))
notificationManager.notify(tootId, builder.build())
timer.schedule(object : TimerTask() {
override fun run() {
notificationManager.cancel(tootId)
stopSelfWhenDone()
}
}, 5000)
}
}
private fun saveTootToDrafts(toot: TootToSend) {
saveTootHelper.saveToot(toot.text,
toot.warningText,
toot.savedJsonUrls,
toot.mediaUris,
toot.mediaDescriptions,
toot.savedTootUid,
toot.inReplyToId,
toot.replyingStatusContent,
toot.replyingStatusAuthorUsername,
Status.Visibility.byString(toot.visibility))
}
private fun cancelSendingIntent(tootId: Int): PendingIntent {
val intent = Intent(this, SendTootService::class.java)
intent.putExtra(KEY_CANCEL, tootId)
return PendingIntent.getService(this, tootId, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
companion object {
private const val KEY_TOOT = "toot"
private const val KEY_CANCEL = "cancel_id"
private const val CHANNEL_ID = "send_toots"
private val MAX_RETRY_INTERVAL = TimeUnit.MINUTES.toMillis(1)
private var sendingNotificationId = -1 // use negative ids to not clash with other notis
private var errorNotificationId = Int.MIN_VALUE // use even more negative ids to not clash with other notis
@JvmStatic
fun sendTootIntent(context: Context,
text: String,
warningText: String,
visibility: Status.Visibility,
sensitive: Boolean,
mediaIds: List<String>,
mediaUris: List<Uri>,
mediaDescriptions: List<String>,
inReplyToId: String?,
replyingStatusContent: String?,
replyingStatusAuthorUsername: String?,
savedJsonUrls: String?,
account: AccountEntity,
savedTootUid: Int
): Intent {
val intent = Intent(context, SendTootService::class.java)
val idempotencyKey = randomAlphanumericString(16)
val tootToSend = TootToSend(text,
warningText,
visibility.serverString(),
sensitive,
mediaIds,
mediaUris.map { it.toString() },
mediaDescriptions,
inReplyToId,
replyingStatusContent,
replyingStatusAuthorUsername,
savedJsonUrls,
account.id,
savedTootUid,
idempotencyKey,
0)
intent.putExtra(KEY_TOOT, tootToSend)
if(mediaUris.isNotEmpty()) {
// forward uri permissions
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
val uriClip = ClipData(
ClipDescription("Toot Media", arrayOf("image/*", "video/*")),
ClipData.Item(mediaUris[0])
)
mediaUris
.drop(1)
.forEach { mediaUri ->
uriClip.addItem(ClipData.Item(mediaUri))
}
intent.clipData = uriClip
}
return intent
}
}
}
@Parcelize
data class TootToSend(val text: String,
val warningText: String,
val visibility: String,
val sensitive: Boolean,
val mediaIds: List<String>,
val mediaUris: List<String>,
val mediaDescriptions: List<String>,
val inReplyToId: String?,
val replyingStatusContent: String?,
val replyingStatusAuthorUsername: String?,
val savedJsonUrls: String?,
val accountId: Long,
val savedTootUid: Int,
val idempotencyKey: String,
var retries: Int) : Parcelable
| gpl-3.0 | 8c013c22fd8404ec1f69038b3325fce7 | 35.225434 | 154 | 0.587442 | 5.047926 | false | false | false | false |
czyzby/gdx-setup | src/main/kotlin/com/github/czyzby/setup/data/gradle/rootGradle.kt | 1 | 1761 | package com.github.czyzby.setup.data.gradle
import com.github.czyzby.setup.data.platforms.Android
import com.github.czyzby.setup.data.project.Project
/**
* Gradle file of the root project. Manages build script and global settings.
* @author MJ
*/
class RootGradleFile(val project: Project) : GradleFile("") {
val plugins = mutableSetOf<String>()
val buildRepositories = mutableSetOf<String>()
init {
buildDependencies.add("\"com.badlogicgames.gdx:gdx-tools:\$gdxVersion\"")
buildRepositories.add("mavenLocal()")
buildRepositories.add("mavenCentral()")
buildRepositories.add("jcenter()")
buildRepositories.add("google()")
buildRepositories.add("maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' }")
}
override fun getContent(): String = """buildscript {
repositories {
${buildRepositories.joinToString(separator = "\n") { " $it" }}
}
dependencies {
${joinDependencies(buildDependencies, type = "classpath", tab = " ")} }
}
allprojects {
apply plugin: 'eclipse'
apply plugin: 'idea'
}
configure(subprojects${if (project.hasPlatform(Android.ID)) {
" - project(':android')"
} else {
""
}}) {
${plugins.joinToString(separator = "\n") { " apply plugin: '$it'" }}
sourceCompatibility = ${project.advanced.javaVersion}
}
subprojects {
version = '${project.advanced.version}'
ext.appName = '${project.basic.name}'
repositories {
mavenLocal()
mavenCentral()
jcenter()
google()
maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' }
}
}
// Clearing Eclipse project data in root folder:
tasks.eclipse.doLast {
delete '.project'
delete '.classpath'
delete '.settings/'
}
"""
}
| unlicense | eef03ada438e393899373214ae194dab | 26.092308 | 105 | 0.667235 | 4.133803 | false | false | false | false |
mingdroid/tumbviewer | app/src/main/java/com/nutrition/express/ui/post/blog/BlogViewModel.kt | 1 | 1272 | package com.nutrition.express.ui.post.blog
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.switchMap
import androidx.lifecycle.viewModelScope
import com.nutrition.express.model.api.repo.BlogRepo
import java.util.*
class BlogViewModel : ViewModel() {
private val blogRepo = BlogRepo(viewModelScope.coroutineContext)
private val _deletePostData = MutableLiveData<DeleteRequest>()
val deletePostData = _deletePostData.switchMap { blogRepo.deletePost(it.blogName, it.postId) }
private val _blogPosts = MutableLiveData<PostsRequest>()
val blogPostsData = _blogPosts.switchMap {
val para = HashMap<String, String>()
para["limit"] = (20).toString()
para["offset"] = it.offset.toString()
blogRepo.getBlogPosts(it.blogName, it.type, para)
}
fun deletePost(blogName: String, postId: String) {
_deletePostData.value = DeleteRequest(blogName, postId)
}
fun fetchBlogPosts(blogName: String, type: String, offset: Int) {
_blogPosts.value = PostsRequest(blogName, type, offset)
}
data class DeleteRequest(val blogName: String, val postId: String)
data class PostsRequest(val blogName: String, val type: String, val offset: Int)
} | apache-2.0 | e2ba1374f0c495c96e0252e9f8667929 | 37.575758 | 98 | 0.732704 | 4.170492 | false | false | false | false |
facebook/react-native | packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt | 1 | 5876 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react
import com.facebook.react.utils.projectPathToLibraryName
import javax.inject.Inject
import org.gradle.api.Project
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
abstract class ReactExtension @Inject constructor(project: Project) {
private val objects = project.objects
/**
* The path to the root of your project. This is the path to where the `package.json` lives. All
* the CLI commands will be invoked from this folder as working directory.
*
* Default: ${rootProject.dir}/../
*/
val root: DirectoryProperty =
objects.directoryProperty().convention(project.rootProject.layout.projectDirectory.dir("../"))
/**
* The path to the react-native NPM package folder.
*
* Default: ${rootProject.dir}/../node_modules/react-native-codegen
*/
val reactNativeDir: DirectoryProperty =
objects.directoryProperty().convention(root.dir("node_modules/react-native"))
/**
* The path to the JS entry file. If not specified, the plugin will try to resolve it using a list
* of known locations (e.g. `index.android.js`, `index.js`, etc.).
*/
val entryFile: RegularFileProperty = objects.fileProperty()
/**
* The reference to the React Native CLI. If not specified, the plugin will try to resolve it
* looking for `react-native` CLI inside `node_modules` in [root].
*/
val cliFile: RegularFileProperty =
objects.fileProperty().convention(reactNativeDir.file("cli.js"))
/**
* The path to the Node executable and extra args. By default it assumes that you have `node`
* installed and configured in your $PATH. Default: ["node"]
*/
val nodeExecutableAndArgs: ListProperty<String> =
objects.listProperty(String::class.java).convention(listOf("node"))
/** The command to use to invoke bundle. Default is `bundle` and will be invoked on [root]. */
val bundleCommand: Property<String> = objects.property(String::class.java).convention("bundle")
/**
* Custom configuration file for the [bundleCommand]. If provided, it will be passed over with a
* `--config` flag to the bundle command.
*/
val bundleConfig: RegularFileProperty = objects.fileProperty()
/**
* The Bundle Asset name. This name will be used also for deriving other bundle outputs such as
* the packager source map, the compiler source map and the output source map file.
*
* Default: index.android.bundle
*/
val bundleAssetName: Property<String> =
objects.property(String::class.java).convention("index.android.bundle")
/**
* Toggles the .so Cleanup step. If enabled, we will clean up all the unnecessary files before the
* bundle task. If disabled, the developers will have to manually cleanup the files. Default: true
*/
val enableSoCleanup: Property<Boolean> = objects.property(Boolean::class.java).convention(true)
/** Extra args that will be passed to the [bundleCommand] Default: [] */
val extraPackagerArgs: ListProperty<String> =
objects.listProperty(String::class.java).convention(emptyList())
/**
* Allows to specify the debuggable variants (by default just 'debug'). Variants in this list
* will:
* - Not be bundled (the bundle file will not be created and won't be copied over).
* - Have the Hermes Debug flags set. That's useful if you have another variant (say `canary`)
* where you want dev mode to be enabled. Default: ['debug']
*/
val debuggableVariants: ListProperty<String> =
objects.listProperty(String::class.java).convention(listOf("debug"))
/** Hermes Config */
/**
* The command to use to invoke hermesc (the hermes compiler). Default is "", the plugin will
* autodetect it.
*/
val hermesCommand: Property<String> = objects.property(String::class.java).convention("")
/**
* Whether to enable Hermes only on certain variants. If specified as a non-empty list, hermesc
* and the .so cleanup for Hermes will be executed only for variants in this list. An empty list
* assumes you're either using Hermes for all variants or not (see [enableHermes]).
*
* Default: []
*/
val enableHermesOnlyInVariants: ListProperty<String> =
objects.listProperty(String::class.java).convention(emptyList())
/** Flags to pass to Hermesc. Default: ["-O", "-output-source-map"] */
val hermesFlags: ListProperty<String> =
objects.listProperty(String::class.java).convention(listOf("-O", "-output-source-map"))
/** Codegen Config */
/**
* The path to the react-native-codegen NPM package folder.
*
* Default: ${rootProject.dir}/../node_modules/react-native-codegen
*/
val codegenDir: DirectoryProperty =
objects.directoryProperty().convention(root.dir("node_modules/react-native-codegen"))
/**
* The root directory for all JS files for the app.
*
* Default: [root] (i.e. ${rootProject.dir}/../)
*/
val jsRootDir: DirectoryProperty = objects.directoryProperty().convention(root.get())
/**
* The library name that will be used for the codegen artifacts.
*
* Default: <UpperCamelVersionOfProjectPath>Spec (e.g. for :example:project it will be
* ExampleProjectSpec).
*/
val libraryName: Property<String> =
objects.property(String::class.java).convention(projectPathToLibraryName(project.path))
/**
* Java package name to use for any codegen artifacts produced during build time. Default:
* com.facebook.fbreact.specs
*/
val codegenJavaPackageName: Property<String> =
objects.property(String::class.java).convention("com.facebook.fbreact.specs")
}
| mit | a7ec39578cc3d3035129bc0e83b2ffdf | 37.913907 | 100 | 0.711709 | 4.209169 | false | false | false | false |
SpryServers/sprycloud-android | src/main/java/com/owncloud/android/db/OCUploadComparator.kt | 3 | 2563 | /*
* NextCloud Android client application
*
* @copyright Copyright (C) 2019 Daniele Fognini <[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 <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.db
/**
* Sorts OCUpload by (uploadStatus, uploadingNow, uploadEndTimeStamp, uploadId).
*/
class OCUploadComparator : Comparator<OCUpload?> {
@Suppress("ReturnCount")
override fun compare(upload1: OCUpload?, upload2: OCUpload?): Int {
if (upload1 == null && upload2 == null) {
return 0
}
if (upload1 == null) {
return -1
}
if (upload2 == null) {
return 1
}
val compareUploadStatus = compareUploadStatus(upload1, upload2)
if (compareUploadStatus != 0) {
return compareUploadStatus
}
val compareUploadingNow = compareUploadingNow(upload1, upload2)
if (compareUploadingNow != 0) {
return compareUploadingNow
}
val compareUpdateTime = compareUpdateTime(upload1, upload2)
if (compareUpdateTime != 0) {
return compareUpdateTime
}
val compareUploadId = compareUploadId(upload1, upload2)
if (compareUploadId != 0) {
return compareUploadId
}
return 0
}
private fun compareUploadStatus(upload1: OCUpload, upload2: OCUpload): Int {
return upload1.fixedUploadStatus.compareTo(upload2.fixedUploadStatus)
}
private fun compareUploadingNow(upload1: OCUpload, upload2: OCUpload): Int {
return upload2.isFixedUploadingNow.compareTo(upload1.isFixedUploadingNow)
}
private fun compareUpdateTime(upload1: OCUpload, upload2: OCUpload): Int {
return upload2.fixedUploadEndTimeStamp.compareTo(upload1.fixedUploadEndTimeStamp)
}
private fun compareUploadId(upload1: OCUpload, upload2: OCUpload): Int {
return upload1.fixedUploadId.compareTo(upload2.fixedUploadId)
}
}
| gpl-2.0 | cb4b1e5d50a8da9ed2b433569a80f8db | 33.173333 | 89 | 0.678112 | 4.388699 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | fluxc/src/main/java/org/wordpress/android/fluxc/store/stats/time/SearchTermsStore.kt | 2 | 2405 | package org.wordpress.android.fluxc.store.stats.time
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.stats.LimitMode
import org.wordpress.android.fluxc.model.stats.time.TimeStatsMapper
import org.wordpress.android.fluxc.network.rest.wpcom.stats.time.SearchTermsRestClient
import org.wordpress.android.fluxc.network.utils.StatsGranularity
import org.wordpress.android.fluxc.persistence.TimeStatsSqlUtils.SearchTermsSqlUtils
import org.wordpress.android.fluxc.store.StatsStore.OnStatsFetched
import org.wordpress.android.fluxc.store.StatsStore.StatsError
import org.wordpress.android.fluxc.store.StatsStore.StatsErrorType.INVALID_RESPONSE
import org.wordpress.android.fluxc.tools.CoroutineEngine
import org.wordpress.android.util.AppLog.T.STATS
import java.util.Date
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class SearchTermsStore
@Inject constructor(
private val restClient: SearchTermsRestClient,
private val sqlUtils: SearchTermsSqlUtils,
private val timeStatsMapper: TimeStatsMapper,
private val coroutineEngine: CoroutineEngine
) {
suspend fun fetchSearchTerms(
site: SiteModel,
granularity: StatsGranularity,
limitMode: LimitMode.Top,
date: Date,
forced: Boolean = false
) = coroutineEngine.withDefaultContext(STATS, this, "fetchSearchTerms") {
if (!forced && sqlUtils.hasFreshRequest(site, granularity, date, limitMode.limit)) {
return@withDefaultContext OnStatsFetched(getSearchTerms(site, granularity, limitMode, date), cached = true)
}
val payload = restClient.fetchSearchTerms(site, granularity, date, limitMode.limit + 1, forced)
return@withDefaultContext when {
payload.isError -> OnStatsFetched(payload.error)
payload.response != null -> {
sqlUtils.insert(site, payload.response, granularity, date, limitMode.limit)
OnStatsFetched(timeStatsMapper.map(payload.response, limitMode))
}
else -> OnStatsFetched(StatsError(INVALID_RESPONSE))
}
}
fun getSearchTerms(site: SiteModel, period: StatsGranularity, limitMode: LimitMode, date: Date) =
coroutineEngine.run(STATS, this, "getSearchTerms") {
sqlUtils.select(site, period, date)?.let { timeStatsMapper.map(it, limitMode) }
}
}
| gpl-2.0 | 1b37579bec53a278edf2c4bc6b192d33 | 46.156863 | 119 | 0.743035 | 4.580952 | false | false | false | false |
ekager/focus-android | app/src/main/java/org/mozilla/focus/searchsuggestions/ui/SearchSuggestionsFragment.kt | 1 | 11412 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.searchsuggestions.ui
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.graphics.Color
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.support.v7.util.DiffUtil
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import kotlinx.android.synthetic.main.fragment_search_suggestions.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.Job
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import mozilla.components.browser.session.Session
import org.mozilla.focus.R
import org.mozilla.focus.ext.components
import org.mozilla.focus.searchsuggestions.SearchSuggestionsViewModel
import org.mozilla.focus.searchsuggestions.State
import org.mozilla.focus.utils.SupportUtils
import org.mozilla.focus.utils.UrlUtils
import kotlin.coroutines.CoroutineContext
class SearchSuggestionsFragment : Fragment(), CoroutineScope {
private var job = Job()
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
lateinit var searchSuggestionsViewModel: SearchSuggestionsViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
searchSuggestionsViewModel = ViewModelProviders.of(parentFragment!!).get(SearchSuggestionsViewModel::class.java)
}
override fun onResume() {
super.onResume()
if (job.isCancelled) {
job = Job()
}
searchSuggestionsViewModel.refresh()
}
override fun onPause() {
job.cancel()
super.onPause()
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
searchSuggestionsViewModel.searchQuery.observe(this, Observer {
searchView.text = it
searchView.contentDescription = context!!.getString(R.string.search_hint, it)
})
searchSuggestionsViewModel.suggestions.observe(this, Observer { suggestions ->
launch(IO) {
suggestions?.apply { (suggestionList.adapter as SuggestionsAdapter).refresh(this) }
}
})
searchSuggestionsViewModel.state.observe(this, Observer { state ->
enable_search_suggestions_container.visibility = View.GONE
no_suggestions_container.visibility = View.GONE
suggestionList.visibility = View.GONE
when (state) {
is State.ReadyForSuggestions ->
suggestionList.visibility = View.VISIBLE
is State.NoSuggestionsAPI ->
no_suggestions_container.visibility = if (state.givePrompt) {
View.VISIBLE
} else {
View.GONE
}
is State.Disabled ->
enable_search_suggestions_container.visibility = if (state.givePrompt) {
View.VISIBLE
} else {
View.GONE
}
}
})
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? = inflater.inflate(R.layout.fragment_search_suggestions, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
enable_search_suggestions_subtitle.text = buildEnableSearchSuggestionsSubtitle()
enable_search_suggestions_subtitle.movementMethod = LinkMovementMethod.getInstance()
enable_search_suggestions_subtitle.highlightColor = Color.TRANSPARENT
suggestionList.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
suggestionList.adapter = SuggestionsAdapter {
searchSuggestionsViewModel.selectSearchSuggestion(it)
}
searchView.setOnClickListener {
val textView = it
if (textView is TextView) {
searchSuggestionsViewModel.selectSearchSuggestion(textView.text.toString(), true)
}
}
enable_search_suggestions_button.setOnClickListener {
searchSuggestionsViewModel.enableSearchSuggestions()
}
disable_search_suggestions_button.setOnClickListener {
searchSuggestionsViewModel.disableSearchSuggestions()
}
dismiss_no_suggestions_message.setOnClickListener {
searchSuggestionsViewModel.dismissNoSuggestionsMessage()
}
}
private fun buildEnableSearchSuggestionsSubtitle(): SpannableString {
val subtitle = resources.getString(R.string.enable_search_suggestion_subtitle)
val appName = resources.getString(R.string.app_name)
val learnMore = resources.getString(R.string.enable_search_suggestion_subtitle_learnmore)
val spannable = SpannableString(String.format(subtitle, appName, learnMore))
val startIndex = spannable.indexOf(learnMore)
val endIndex = startIndex + learnMore.length
val learnMoreSpan = object : ClickableSpan() {
override fun onClick(textView: View) {
val context = textView.context
val url = SupportUtils.getSumoURLForTopic(context, SupportUtils.SumoTopic.SEARCH_SUGGESTIONS)
val session = Session(url, source = Session.Source.MENU)
context.components.sessionManager.add(session, selected = true)
}
override fun updateDrawState(ds: TextPaint?) {
ds?.isUnderlineText = false
}
}
spannable.setSpan(learnMoreSpan, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
val color = ForegroundColorSpan(
ContextCompat.getColor(context!!, R.color.searchSuggestionPromptButtonTextColor))
spannable.setSpan(color, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
return spannable
}
companion object {
fun create() = SearchSuggestionsFragment()
}
inner class SuggestionsAdapter(
private val clickListener: (String) -> Unit
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
inner class DiffCallback(
private val oldSuggestions: List<SpannableStringBuilder>,
private val newSuggestions: List<SpannableStringBuilder>
) : DiffUtil.Callback() {
override fun getOldListSize(): Int = oldSuggestions.size
override fun getNewListSize(): Int = newSuggestions.size
override fun areItemsTheSame(p0: Int, p1: Int): Boolean = true
override fun areContentsTheSame(p0: Int, p1: Int): Boolean =
oldSuggestions[p0] == newSuggestions[p1]
override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? =
newSuggestions[newItemPosition]
}
private var suggestions: List<SpannableStringBuilder> = listOf()
private var pendingJob: Job? = null
suspend fun refresh(suggestions: List<SpannableStringBuilder>) = coroutineScope {
pendingJob?.cancel()
pendingJob = launch(IO) {
val result = DiffUtil.calculateDiff(DiffCallback([email protected], suggestions))
launch(Main) {
result.dispatchUpdatesTo(this@SuggestionsAdapter)
[email protected] = suggestions
}
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int, payloads: MutableList<Any>) {
if (payloads.isEmpty()) {
super.onBindViewHolder(holder, position, payloads)
} else {
val payload = payloads[0] as? SpannableStringBuilder ?: return
val view = holder as? SuggestionViewHolder ?: return
view.bind(payload)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is SuggestionViewHolder) {
holder.bind(suggestions[position])
}
}
override fun getItemCount(): Int = suggestions.count()
override fun getItemViewType(position: Int): Int {
return SuggestionViewHolder.LAYOUT_ID
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return SuggestionViewHolder(
LayoutInflater.from(parent.context).inflate(viewType, parent, false),
clickListener)
}
}
}
/**
* ViewHolder implementation for a suggestion item in the list.
*/
private class SuggestionViewHolder(
itemView: View,
private val clickListener: (String) -> Unit
) : RecyclerView.ViewHolder(itemView) {
companion object {
const val LAYOUT_ID = R.layout.item_suggestion
}
val suggestionText: TextView = itemView.findViewById(R.id.suggestion)
fun bind(suggestion: SpannableStringBuilder) {
suggestionText.text = suggestion
suggestionText.setPaddingRelative(
itemView.resources.getDimensionPixelSize(R.dimen.search_suggestions_padding_with_icon),
0,
0,
0
)
val backgroundDrawableArray =
suggestionText.context.obtainStyledAttributes(intArrayOf(R.attr.selectableItemBackground))
val backgroundDrawable = backgroundDrawableArray.getDrawable(0)
backgroundDrawableArray.recycle()
suggestionText.background = backgroundDrawable
val size = itemView.resources.getDimension(R.dimen.preference_icon_drawable_size).toInt()
if (UrlUtils.isUrl(suggestionText.text.toString())) {
val icon = ContextCompat.getDrawable(itemView.context, R.drawable.ic_link)
icon?.setBounds(0, 0, size, size)
suggestionText.contentDescription = suggestionText.text
suggestionText.setCompoundDrawables(icon, null, null, null)
} else {
val icon = ContextCompat.getDrawable(itemView.context, R.drawable.ic_search)
icon?.setBounds(0, 0, size, size)
suggestionText.contentDescription = itemView.context.getString(R.string.search_hint, suggestionText.text)
suggestionText.setCompoundDrawables(icon, null, null, null)
}
itemView.setOnClickListener { clickListener(suggestion.toString()) }
}
}
| mpl-2.0 | 37613c00a3246db3dcfc601974aaf4c8 | 38.763066 | 120 | 0.673852 | 5.312849 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/duchy/deploy/common/server/AsyncComputationControlServer.kt | 1 | 3027 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.duchy.deploy.common.server
import io.grpc.Channel
import org.wfanet.measurement.common.commandLineMain
import org.wfanet.measurement.common.crypto.SigningCerts
import org.wfanet.measurement.common.grpc.CommonServer
import org.wfanet.measurement.common.grpc.buildMutualTlsChannel
import org.wfanet.measurement.common.grpc.withDefaultDeadline
import org.wfanet.measurement.common.identity.DuchyInfo
import org.wfanet.measurement.common.identity.DuchyInfoFlags
import org.wfanet.measurement.duchy.deploy.common.CommonDuchyFlags
import org.wfanet.measurement.duchy.deploy.common.ComputationsServiceFlags
import org.wfanet.measurement.duchy.service.internal.computationcontrol.AsyncComputationControlService
import org.wfanet.measurement.internal.duchy.ComputationsGrpcKt.ComputationsCoroutineStub
import picocli.CommandLine
private const val SERVICE_NAME = "AsyncComputationControl"
private const val SERVER_NAME = "${SERVICE_NAME}Server"
class AsyncComputationControlServiceFlags {
@CommandLine.Mixin
lateinit var server: CommonServer.Flags
private set
@CommandLine.Mixin
lateinit var duchy: CommonDuchyFlags
private set
@CommandLine.Mixin
lateinit var duchyInfo: DuchyInfoFlags
private set
@CommandLine.Mixin
lateinit var computationsServiceFlags: ComputationsServiceFlags
private set
}
@CommandLine.Command(
name = SERVER_NAME,
description = ["Server daemon for $SERVICE_NAME service."],
mixinStandardHelpOptions = true,
showDefaultValues = true
)
private fun run(@CommandLine.Mixin flags: AsyncComputationControlServiceFlags) {
DuchyInfo.initializeFromFlags(flags.duchyInfo)
val clientCerts =
SigningCerts.fromPemFiles(
certificateFile = flags.server.tlsFlags.certFile,
privateKeyFile = flags.server.tlsFlags.privateKeyFile,
trustedCertCollectionFile = flags.server.tlsFlags.certCollectionFile
)
val channel: Channel =
buildMutualTlsChannel(
flags.computationsServiceFlags.target,
clientCerts,
flags.computationsServiceFlags.certHost
)
.withDefaultDeadline(flags.computationsServiceFlags.defaultDeadlineDuration)
CommonServer.fromFlags(
flags.server,
SERVER_NAME,
AsyncComputationControlService(ComputationsCoroutineStub(channel))
)
.start()
.blockUntilShutdown()
}
fun main(args: Array<String>) = commandLineMain(::run, args)
| apache-2.0 | 75f2762a13a4c7bc1ca9468c39b3c60c | 34.611765 | 102 | 0.791873 | 4.607306 | false | false | false | false |
davidwhitman/changelogs | playstoreapi/src/main/kotlin/com/thunderclouddev/playstoreapi/PlayApiClient.kt | 1 | 11042 | /*
* Copyright (c) 2017.
* Distributed under the GNU GPLv3 by David Whitman.
* https://www.gnu.org/licenses/gpl-3.0.en.html
*
* This source code is made available to help others learn. Please don't clone my app.
*/
package com.thunderclouddev.playstoreapi
import com.thunderclouddev.playstoreapi.model.ApiAppInfo
import com.thunderclouddev.playstoreapi.model.Links
import com.thunderclouddev.playstoreapi.model.Offer
import com.thunderclouddev.utils.asSingletonList
import com.thunderclouddev.utils.getOrNullIfBlank
import com.thunderclouddev.utils.isNotNullOrBlank
import fdfeProtos.UploadDeviceConfigRequest
import io.reactivex.Completable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.Headers
import okhttp3.Request
import okhttp3.RequestBody
import timber.log.Timber
import java.io.ByteArrayInputStream
import java.text.DateFormat
import java.util.*
import java.util.zip.GZIPInputStream
/**
* Executes [PlayRequest]s against the FDFE Google Play API.
*
* @author David Whitman on 27 Mar, 2017.
*/
internal class PlayApiClient(
private val rxHttpClient: RxOkHttpClient,
private val authToken: String,
private val gsfId: String,
private val deviceInfo: DeviceInfo,
private val locale: Locale,
var deviceConfigUploadRequired: Boolean = false)
: ApiClient<PlayRequest<*>> {
override fun <T> rxecute(request: com.thunderclouddev.playstoreapi.Request<PlayRequest<*>, T>): Single<T> =
uploadDeviceConfigIfRequired()
.andThen((request as PlayRequest).execute(rxHttpClient, Headers.of(getDefaultHeaders())))
private fun uploadDeviceConfigToGoogle(): Completable =
rxHttpClient.rxecute(Request.Builder()
.post(RequestBody.create(PlayApiConstants.PROTOBUF_MEDIA_TYPE, UploadDeviceConfigRequest.newBuilder()
.setDeviceConfiguration(deviceInfo.androidCheckinRequest.deviceConfiguration)
.build().toByteArray()))
.headers(Headers.of(getDefaultHeaders()
.plus(arrayListOf(
"X-DFE-Enabled-Experiments" to "cl:billing.select_add_instrument_by_default",
"X-DFE-Unsupported-Experiments" to "nocache:billing.use_charging_poller,market_emails,buyer_currency,prod_baseline,checkin.set_asset_paid_app_field,shekel_test,content_ratings,buyer_currency_in_app,nocache:encrypted_apk,recent_changes",
"X-DFE-Client-Id" to "am-android-google",
"X-DFE-SmallestScreenWidthDp" to "320",
"X-DFE-Filter-Level" to "3"
))))
.url(PlayApiConstants.UPLOADDEVICECONFIG_URL)
.build())
// .map { ResponseWrapper.parseFrom(it.body().bytes()).payload.uploadDeviceConfigResponse }
.toCompletable()
private fun uploadDeviceConfigIfRequired() =
if (deviceConfigUploadRequired) {
uploadDeviceConfigToGoogle()
.doOnComplete {
deviceConfigUploadRequired = false
}
} else {
Completable.complete()
}
/**
* Using Accept-Language you can fetch localized information such as reviews and descriptions.
* Note that changing this value has no affect on localized application list that
* server provides. It depends on only your IP location.
*/
private fun getDefaultHeaders(): Map<String, String> {
val headers = HashMap<String, String>()
if (this.authToken.isNotEmpty()) {
headers.put("Authorization", "GoogleLogin auth=" + this.authToken)
}
headers.put("User-Agent", this.deviceInfo.userAgentString)
if (this.gsfId.isNotEmpty()) {
headers.put("X-DFE-Device-Id", this.gsfId)
}
headers.put("Accept-Language", this.locale.toString().replace("_", "-"))
// This is an encoded comma separated list of ints
// Getting this list properly will be a huge task, so it is static for now
// It probably depends both on device and account settings and is retrieved when the user logs in for the first time
headers.put("X-DFE-Encoded-Targets",
"CAEScFfqlIEG6gUYogFWrAISK1WDAg+hAZoCDgIU1gYEOIACFkLMAeQBnASLATlASUuyAyqCAjY5igOMBQzfA/IClwFbApUC4ANbtgKVAS7OAX8YswHFBhgDwAOPAmGEBt4OfKkB5weSB5AFASkiN68akgMaxAMSAQEBA9kBO7UBFE1KVwIDBGs3go6BBgEBAgMECQgJAQIEAQMEAQMBBQEBBAUEFQYCBgUEAwMBDwIBAgOrARwBEwMEAg0mrwESfTEcAQEKG4EBMxghChMBDwYGASI3hAEODEwXCVh/EREZA4sBYwEdFAgIIwkQcGQRDzQ2fTC2AjfVAQIBAYoBGRg2FhYFBwEqNzACJShzFFblAo0CFxpFNBzaAd0DHjIRI4sBJZcBPdwBCQGhAUd2A7kBLBVPngEECHl0UEUMtQETigHMAgUFCc0BBUUlTywdHDgBiAJ+vgKhAU0uAcYCAWQ/5ALUAw1UwQHUBpIBCdQDhgL4AY4CBQICjARbGFBGWzA1CAEMOQH+BRAOCAZywAIDyQZ2MgM3BxsoAgUEBwcHFia3AgcGTBwHBYwBAlcBggFxSGgIrAEEBw4QEqUCASsWadsHCgUCBQMD7QICA3tXCUw7ugJZAwGyAUwpIwM5AwkDBQMJA5sBCw8BNxBVVBwVKhebARkBAwsQEAgEAhESAgQJEBCZATMdzgEBBwG8AQQYKSMUkAEDAwY/CTs4/wEaAUt1AwEDAQUBAgIEAwYEDx1dB2wGeBFgTQ")
return headers
}
}
abstract class PlayRequest<T> : com.thunderclouddev.playstoreapi.Request<PlayRequest<*>, T> {
internal val IMAGE_TYPE_ID_FULL = 4
internal val IMAGE_TYPE_ID_THUMBNAIL = 2
internal val IMAGE_TYPE_ID_SCREENSHOT = 1
abstract fun execute(apiClient: RxOkHttpClient, defaultHeaders: Headers): Single<T>
/**
* TODO: How many packages can we request at once? 10?
*/
class BulkDetailsRequest(val packageNames: List<String>) : PlayRequest<List<ApiAppInfo>>() {
override fun execute(apiClient: RxOkHttpClient, defaultHeaders: Headers): Single<List<ApiAppInfo>> =
apiClient.rxecute(Request.Builder()
.post(RequestBody.create(PlayApiConstants.PROTOBUF_MEDIA_TYPE,
fdfeProtos.BulkDetailsRequest.newBuilder()
.addAllDocid(packageNames)
.build().toByteArray()))
.headers(defaultHeaders)
.url(PlayApiConstants.BULKDETAILS_URL)
.build())
.doOnSubscribe { Timber.v("FdfeBulk fetching ${packageNames.joinToString()}") }
.map {
fdfeProtos.ResponseWrapper.parseFrom(it.body().bytes()).payload.bulkDetailsResponse.entryList
.map { entry -> entry.doc }
.map { mapDocToAppInfo(it) }
.filterIndexed { index, appInfo ->
if (appInfo.packageName.isNullOrBlank()) {
Timber.v("Ignoring app with no results: ${packageNames[index]}")
}
appInfo.packageName.isNotNullOrBlank()
}
}
}
class DetailsRequest(val packageName: String) : PlayRequest<ApiAppInfo>() {
override fun execute(apiClient: RxOkHttpClient, defaultHeaders: Headers): Single<ApiAppInfo> =
apiClient.rxecute(Request.Builder()
.get()
.headers(defaultHeaders)
.url("${PlayApiConstants.DETAILS_URL}?doc=$packageName")
.build())
.doOnSubscribe { Timber.v("FdfeDetails fetching $packageName") }
.map { fdfeProtos.ResponseWrapper.parseFrom(it.body().bytes()).payload.detailsResponse }
.map { mapDocToAppInfo(it.docV2) }
}
internal fun decompressGzippedBytes(bytes: ByteArray) = GZIPInputStream(ByteArrayInputStream(bytes)).readBytes()
internal fun mapDocToAppInfo(doc: fdfeProtos.DocV2): ApiAppInfo {
val links = mutableMapOf(Links.REL.SELF to doc.detailsUrl.asSingletonList())
if (doc.imageList.any { it.imageType == IMAGE_TYPE_ID_FULL }) {
links.put(Links.REL.ICON, doc.imageList.first { it.imageType == IMAGE_TYPE_ID_FULL }.imageUrl.asSingletonList())
}
if (doc.imageList.any { it.imageType == IMAGE_TYPE_ID_THUMBNAIL }) {
links.put(Links.REL.THUMBNAIL, doc.imageList.first { it.imageType == IMAGE_TYPE_ID_THUMBNAIL }.imageUrl.asSingletonList())
}
if (doc.imageList.any { it.imageType == IMAGE_TYPE_ID_SCREENSHOT }) {
links.put(Links.REL.SCREENSHOT, doc.imageList.filter { it.imageType == IMAGE_TYPE_ID_THUMBNAIL }.map { it.imageUrl })
}
val updateDate = try {
DateFormat.getDateInstance().parse(doc.details.appDetails.uploadDate)
} catch (exception: Exception) {
null
}
return ApiAppInfo(title = doc.title,
packageName = doc.docid,
developer = doc.creator,
rating = doc.aggregateRating.starRating,
ratingsCount = doc.aggregateRating.ratingsCount,
developerId = null,
versionName = doc.details.appDetails.versionString.getOrNullIfBlank(),
versionCode = doc.details.appDetails.versionCode,
descriptionHtml = doc.descriptionHtml.getOrNullIfBlank(),
downloadsCountString = doc.details.appDetails.numDownloads.getOrNullIfBlank(),
recentChangesHtml = doc.details.appDetails.recentChangesHtml.getOrNullIfBlank(),
category = doc.relatedLinks.categoryInfo.appCategory.getOrNullIfBlank(),
installSizeBytes = doc.details.appDetails.installationSize,
links = Links(links),
updateDate = updateDate,
bayesianMeanRating = doc.aggregateRating.bayesianMeanRating,
oneStarRatings = doc.aggregateRating.oneStarRatings,
twoStarRatings = doc.aggregateRating.twoStarRatings,
threeStarRatings = doc.aggregateRating.threeStarRatings,
fourStarRatings = doc.aggregateRating.fourStarRatings,
fiveStarRatings = doc.aggregateRating.fiveStarRatings,
contentRating = doc.relatedLinks.rated.label.getOrNullIfBlank(),
offer = Offer(
micros = doc.offerList.firstOrNull()?.micros,
currencyCode = doc.offerList.firstOrNull()?.currencyCode,
formattedAmount = doc.offerList.firstOrNull()?.formattedAmount.getOrNullIfBlank(),
offerType = doc.offerList.firstOrNull()?.offerType
),
permissions = doc.details.appDetails.permissionList
.map { it.removePrefix("android.permission.") }
)
}
}
| gpl-3.0 | 75be701fbfa7ad1a556f4b7e49886181 | 53.127451 | 781 | 0.634668 | 4.299844 | false | true | false | false |
ziggy42/Blum | app/src/main/java/com/andreapivetta/blu/data/model/Follower.kt | 1 | 351 | package com.andreapivetta.blu.data.model
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class Follower(@PrimaryKey open var userId: Long = 0) : RealmObject() {
override fun equals(other: Any?) = if (other !is Follower) false else userId == other.userId
override fun hashCode(): Int = 17 + 31 * userId.hashCode()
} | apache-2.0 | d0eb9eeba1c679c684806f6b017c9692 | 28.333333 | 96 | 0.732194 | 3.9 | false | false | false | false |
k0kubun/github-ranking | worker/src/main/kotlin/com/github/k0kubun/gitstar_ranking/GitstarRankingApp.kt | 2 | 4012 | package com.github.k0kubun.gitstar_ranking
import com.github.k0kubun.gitstar_ranking.workers.RankingWorker
import com.github.k0kubun.gitstar_ranking.workers.UserUpdateWorker
import com.github.k0kubun.gitstar_ranking.workers.UserFullScanWorker
import com.github.k0kubun.gitstar_ranking.workers.UserStarScanWorker
import com.github.k0kubun.gitstar_ranking.workers.WorkerManager
import com.google.common.util.concurrent.ThreadFactoryBuilder
import io.sentry.Sentry
import java.lang.InterruptedException
import java.lang.RuntimeException
import java.lang.Thread
import java.util.concurrent.BlockingQueue
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
import org.slf4j.LoggerFactory
private const val NUM_UPDATE_USER_WORKERS = 2
class GitstarRankingApp {
private val logger = LoggerFactory.getLogger(GitstarRankingApp::class.simpleName)
private val config = GitstarRankingConfiguration()
fun run(schedule: Boolean) {
val scheduler = buildAndRunScheduler(schedule)
val workers = buildWorkers(config)
workers.start()
Runtime.getRuntime().addShutdownHook(Thread {
shutdownAndAwaitTermination(scheduler)
workers.stop()
})
}
private fun buildAndRunScheduler(schedule: Boolean): ScheduledExecutorService {
val threadFactory = ThreadFactoryBuilder()
.setNameFormat("scheduler-%d")
.setUncaughtExceptionHandler { _: Thread?, e: Throwable ->
Sentry.captureException(e)
logger.error("Uncaught exception at scheduler: " + e.message)
}
.build()
val scheduler = Executors.newSingleThreadScheduledExecutor(threadFactory)
if (!schedule) return scheduler
// Schedule at most every 8 hours
scheduler.scheduleWithFixedDelay({ scheduleIfEmpty(config.queue.rankingQueue) }, 1, 8, TimeUnit.HOURS)
// Schedule at most every 30 minutes
scheduler.scheduleWithFixedDelay({ scheduleIfEmpty(config.queue.userStarScanQueue) }, 0, 30, TimeUnit.MINUTES)
scheduler.scheduleWithFixedDelay({ scheduleIfEmpty(config.queue.userFullScanQueue) }, 15, 30, TimeUnit.MINUTES)
return scheduler
}
private fun scheduleIfEmpty(queue: BlockingQueue<Boolean>) {
if (queue.size == 0) {
queue.put(true)
}
}
private fun buildWorkers(config: GitstarRankingConfiguration): WorkerManager {
val workers = WorkerManager()
repeat(NUM_UPDATE_USER_WORKERS) {
workers.add(UserUpdateWorker(config.database.dslContext))
}
workers.add(UserStarScanWorker(config))
workers.add(UserFullScanWorker(config))
workers.add(RankingWorker(config))
return workers
}
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html
private fun shutdownAndAwaitTermination(executor: ExecutorService) {
executor.shutdown()
try {
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
executor.shutdownNow()
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
logger.error("Failed to shutdown scheduler")
}
}
} catch (e: InterruptedException) {
Sentry.captureException(e)
logger.error("Scheduler shutdown interrupted: " + e.message)
executor.shutdownNow()
Thread.currentThread().interrupt()
}
}
}
fun main(args: Array<String>) {
System.getenv("SENTRY_DSN")?.let { dsn ->
Sentry.init { options ->
options.dsn = dsn
}
}
var schedule = true
args.forEach {
when (it) {
"--no-schedule" -> schedule = false
else -> throw RuntimeException("Unexpected argument '$it'")
}
}
GitstarRankingApp().run(schedule)
}
| mit | 556ca51d24dbdf127dd38c6673e00f8f | 36.495327 | 119 | 0.679462 | 4.63815 | false | true | false | false |
SimonVT/cathode | cathode-sync/src/main/java/net/simonvt/cathode/actions/movies/SyncRelatedMovies.kt | 1 | 3446 | /*
* Copyright (C) 2016 Simon Vig Therkildsen
*
* 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 net.simonvt.cathode.actions.movies
import android.content.ContentProviderOperation
import android.content.Context
import net.simonvt.cathode.actions.CallAction
import net.simonvt.cathode.actions.movies.SyncRelatedMovies.Params
import net.simonvt.cathode.api.entity.Movie
import net.simonvt.cathode.api.enumeration.Extended
import net.simonvt.cathode.api.service.MoviesService
import net.simonvt.cathode.common.database.forEach
import net.simonvt.cathode.common.database.getLong
import net.simonvt.cathode.provider.DatabaseContract.MovieColumns
import net.simonvt.cathode.provider.DatabaseContract.RelatedMoviesColumns
import net.simonvt.cathode.provider.DatabaseSchematic.Tables
import net.simonvt.cathode.provider.ProviderSchematic.Movies
import net.simonvt.cathode.provider.ProviderSchematic.RelatedMovies
import net.simonvt.cathode.provider.batch
import net.simonvt.cathode.provider.helper.MovieDatabaseHelper
import net.simonvt.cathode.provider.query
import retrofit2.Call
import javax.inject.Inject
class SyncRelatedMovies @Inject constructor(
private val context: Context,
private val movieHelper: MovieDatabaseHelper,
private val moviesService: MoviesService
) : CallAction<Params, List<Movie>>() {
override fun key(params: Params): String = "SyncRelatedMovies&traktId=${params.traktId}"
override fun getCall(params: Params): Call<List<Movie>> =
moviesService.getRelated(params.traktId, RELATED_COUNT, Extended.FULL)
override suspend fun handleResponse(params: Params, response: List<Movie>) {
val movieId = movieHelper.getId(params.traktId)
val ops = arrayListOf<ContentProviderOperation>()
val relatedIds = mutableListOf<Long>()
val related = context.contentResolver.query(
RelatedMovies.fromMovie(movieId),
arrayOf(Tables.MOVIE_RELATED + "." + RelatedMoviesColumns.ID)
)
related.forEach { cursor -> relatedIds.add(cursor.getLong(RelatedMoviesColumns.ID)) }
related.close()
for ((index, movie) in response.withIndex()) {
val relatedMovieId = movieHelper.partialUpdate(movie)
val op = ContentProviderOperation.newInsert(RelatedMovies.RELATED)
.withValue(RelatedMoviesColumns.MOVIE_ID, movieId)
.withValue(RelatedMoviesColumns.RELATED_MOVIE_ID, relatedMovieId)
.withValue(RelatedMoviesColumns.RELATED_INDEX, index)
.build()
ops.add(op)
}
for (id in relatedIds) {
ops.add(ContentProviderOperation.newDelete(RelatedMovies.withId(id)).build())
}
ops.add(
ContentProviderOperation.newUpdate(Movies.withId(movieId)).withValue(
MovieColumns.LAST_RELATED_SYNC,
System.currentTimeMillis()
).build()
)
context.contentResolver.batch(ops)
}
data class Params(val traktId: Long)
companion object {
private const val RELATED_COUNT = 50
}
}
| apache-2.0 | d94c0fdbbe9b3605d68c75a5f7bce3a7 | 35.659574 | 90 | 0.765815 | 4.264851 | false | false | false | false |
android/android-studio-poet | aspoet/src/main/kotlin/com/google/androidstudiopoet/generators/DependencyImageGenerator.kt | 1 | 5760 | package com.google.androidstudiopoet.generators
import com.google.androidstudiopoet.models.AbstractModuleBlueprint
import com.google.androidstudiopoet.models.AndroidModuleBlueprint
import com.google.androidstudiopoet.models.ModuleBlueprint
import com.google.androidstudiopoet.models.ProjectBlueprint
import com.google.androidstudiopoet.utils.joinPath
import com.google.androidstudiopoet.writers.ImageWriter
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
class DependencyImageGenerator(private val imageWriter: ImageWriter) {
companion object {
const val CELL_SIZE = 20
const val LINE_WIDTH = 1
const val HEADER_SIZE = CELL_SIZE + 2 * LINE_WIDTH
const val GRID_SIZE = CELL_SIZE + LINE_WIDTH
val BACKGROUND_COLOR = Color(0x000000)
val GRID_COLOR = Color(0x8F8F8F)
val APP_COLOR = Color(0x5050FF)
val ANDROID_COLOR = Color(0xA4C639)
val JAVA_COLOR = Color(0xF7DB64)
val ERROR_COLOR = Color(0xDF0000)
// Colors match https://docs.gradle.org/current/userguide/java_library_plugin.html#sec:java_library_configurations_graph
val dependencyMethodToColor = mapOf(
"api" to Color(0x00AF00),
"implementation" to Color(0x00AF00),
"runtimeOnly" to Color(0x00AF00),
"testImplementation" to Color(0x00AF00),
"testRuntimeOnly" to Color(0x00AF00),
"apiElements" to Color(0xFFA9C4),
"runtimeElements" to Color(0xFFA9C4),
"compileClassPath" to Color(0x35D9F0),
"runtimeClassPath" to Color(0x35D9F0),
"testCompileClassPath" to Color(0x35D9F0),
"testRuntimeClassPath" to Color(0x35D9F0),
"compileOnly" to Color(0xFFFFFF),
"testCompileOnly" to Color(0xFFFFFF)
)
val DEPENDENCY_MULTIPLE_METHOD_COLOR = Color(0x9F009F)
val DEPENDENCY_UNKNOWN_METHOD_COLOR = Color(0xDF0000)
}
/**
* generates an image that represents the dependency matrix of the project
*/
fun generate(blueprint: ProjectBlueprint) {
val numModules = blueprint.allModuleBlueprints.size
val imageSize = HEADER_SIZE + LINE_WIDTH + numModules * GRID_SIZE
// Create buffered image object
val img = BufferedImage(imageSize, imageSize, BufferedImage.TYPE_INT_RGB)
val graphics = img.graphics
// Background
graphics.color = BACKGROUND_COLOR
graphics.fillRect(0, 0, imageSize, imageSize)
// Generate the grid
graphics.color = GRID_COLOR
for (i in 0..numModules) {
// Horizontal
val y = HEADER_SIZE + i * GRID_SIZE
graphics.fillRect(HEADER_SIZE, y, imageSize - HEADER_SIZE, LINE_WIDTH)
// Vertical
val x = HEADER_SIZE + i * GRID_SIZE
graphics.fillRect(x, HEADER_SIZE, LINE_WIDTH, imageSize - HEADER_SIZE)
}
// Add modules headers and generate indexes to use in dependencies
val moduleNameToIndex = mutableMapOf<String, Int>()
blueprint.allModuleBlueprints.withIndex().forEach{(index, blueprint) ->
moduleNameToIndex[blueprint.name] = index
graphics.drawHeader(index, getColorForModule(blueprint))
}
// Add dependencies
blueprint.allDependencies.forEach { (moduleName, dependencies) ->
// Split dependencies by name
val seenDependencies = mutableMapOf<Int?, MutableSet<String>>()
dependencies.forEach {
seenDependencies.getOrPut(moduleNameToIndex[it.name]) { mutableSetOf() }.add(it.method)
}
// Draw dependencies
val index = moduleNameToIndex[moduleName]!!
seenDependencies.forEach { (dependencyIndex, methodSet) ->
if (dependencyIndex != null) {
graphics.drawCell(index, dependencyIndex, getColorForDependencySet(methodSet))
}
else {
graphics.drawHeader(index, ERROR_COLOR)
}
}
}
// Save to file
val imgPath = blueprint.projectRoot.joinPath("dependencies.png")
imageWriter.writeToFile(img, imgPath)
println("Dependency matrix image saved to $imgPath")
}
private fun getColorForDependencySet(dependencies: Set<String>) =
when (dependencies.size) {
0 ->
BACKGROUND_COLOR
1 ->
dependencyMethodToColor.getOrDefault(dependencies.first(), DEPENDENCY_UNKNOWN_METHOD_COLOR)
else ->
DEPENDENCY_MULTIPLE_METHOD_COLOR
}
private fun getColorForModule(blueprint: AbstractModuleBlueprint): Color =
when (blueprint) {
is AndroidModuleBlueprint ->
if (blueprint.hasLaunchActivity) {
APP_COLOR
}
else {
ANDROID_COLOR
}
is ModuleBlueprint ->
JAVA_COLOR
else ->
ERROR_COLOR
}
private fun Graphics.drawCell(r: Int, c: Int, color: Color) {
val x = HEADER_SIZE + LINE_WIDTH + c * GRID_SIZE
val y = HEADER_SIZE + LINE_WIDTH + r * GRID_SIZE
this.color = color
this.fillRect(x, y, CELL_SIZE, CELL_SIZE)
}
private fun Graphics.drawHeader(i: Int, color: Color) {
val y = HEADER_SIZE + LINE_WIDTH + GRID_SIZE * (i)
this.color = color
this.fillRect(LINE_WIDTH, y, CELL_SIZE, CELL_SIZE)
this.fillRect(y, LINE_WIDTH, CELL_SIZE, CELL_SIZE)
}
} | apache-2.0 | 1a2290040de2cb299a1f5af37d396619 | 38.731034 | 128 | 0.610764 | 4.507042 | false | false | false | false |
lfkdsk/JustDB | src/utils/parsertools/combinators/tree/Expr.kt | 1 | 2209 | package utils.parsertools.combinators.tree
import combinators.word.Operators
import combinators.word.Precedence
import utils.parsertools.ast.AstLeaf
import utils.parsertools.ast.AstNode
import utils.parsertools.combinators.Bnf
import utils.parsertools.combinators.Element
import utils.parsertools.combinators.TokenFactory
import utils.parsertools.lex.Lexer
import java.text.ParseException
/**
* Created by liufengkai on 2017/4/24.
*/
/**
* 表达式子树
*/
open class Expr(
clazz: Class<out AstNode>?,
protected var ops: Operators,
protected var factor: Bnf) : Element {
protected var factory = TokenFactory.getForAstList(clazz)
override fun parse(lexer: Lexer, nodes: MutableList<AstNode>) {
var right: AstNode = factor.parse(lexer)
var prec = nextOperator(lexer)
while (prec != null) {
right = doShift(lexer, right, prec.value)
prec = nextOperator(lexer)
}
nodes.add(right)
}
override fun match(lexer: Lexer): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
private fun doShift(lexer: Lexer, left: AstNode, prec: Int): AstNode {
val list = arrayListOf<AstNode>()
list.add(left)
// 读取一个符号
list.add(AstLeaf(lexer.nextToken()))
// 返回节点放在右子树
var right = factor.parse(lexer)
var next = nextOperator(lexer)
// 子树向右拓展
while (null != next && rightIsExpr(prec, next)) {
right = doShift(lexer, right, next.value)
next = nextOperator(lexer)
}
list.add(right)
return factory.make(list)
}
/**
* 那取下一个符号
* @param lexer 词法
* *
* @return 符号
* *
* @throws ParseException
*/
private fun nextOperator(lexer: Lexer): Precedence? {
val token = lexer[0]
if (token.isIdentifier()) {
// 从符号表里找对应的符号
return ops[token.text]
} else {
return null
}
}
/**
* 比较和右侧符号的结合性
*
* @param prec 优先级
* @param nextPrec 下一个符号的优先级
* @return tof?
*/
private fun rightIsExpr(prec: Int, nextPrec: Precedence): Boolean {
if (nextPrec.leftAssoc) return prec > nextPrec.value
else return prec >= nextPrec.value
}
}
| apache-2.0 | 531f7f7a1ae61e3ead83b4e1a3dd2e87 | 20.091837 | 101 | 0.698113 | 3.089686 | false | false | false | false |
Rorry/CoolCompiler | src/cool/parser/Parser.kt | 1 | 13092 | package cool.parser
import cool.lexer.Token
import cool.lexer.Lexer
import cool.tree.TreeNode
import cool.lexer.TokenConstants
import cool.tree.AbstractClass
import cool.tree.Clazz
import cool.tree.Features
import cool.tree.AbstractFeature
import cool.util.Name
import cool.util.NameTable
import cool.tree.AbstractExpression
import java.util.ArrayList
import cool.util.Errors
import cool.tree.ErrorFeature
import cool.tree.Formals
import cool.tree.AbstractFormal
import cool.tree.Method
import cool.tree.Attr
import cool.tree.Formal
import cool.tree.Assign
import cool.tree.Expressions
import cool.tree.Call
import cool.tree.ObjectId
import cool.tree.Dispatch
import cool.tree.BinaryExpr
import cool.tree.IfExpr
import cool.tree.WhileExpr
import cool.tree.Block
import cool.tree.New
import cool.tree.IsVoid
import cool.tree.Neg
import cool.tree.Not
import cool.tree.Comp
import cool.tree.ErrorExpr
import cool.tree.IntLiteral
import cool.tree.StringLiteral
import cool.tree.BoolLiteral
/* @deprecated */
class Parser(val lexer: Lexer) {
private var token: Token = lexer.nextToken()
private fun error(key: Int) {
Errors.printError(token.lineNumber, key)
}
private fun accept(key: Int) {
if (token.key == key) {
nextToken()
} else {
Errors.printError(token.lineNumber, key)
}
}
private fun illegal(): AbstractExpression {
Errors.printError(token.lineNumber, "No expression")
return ErrorExpr(token.lineNumber)
}
private fun skip() {
}
private fun prec(key: Int): Int {
return when (token.key) {
TokenConstants.EQ -> 1
TokenConstants.LE,
TokenConstants.LT -> 2
TokenConstants.PLUS,
TokenConstants.MINUS -> 3
TokenConstants.MULT,
TokenConstants.DIV -> 4
else -> -1
}
}
private fun nextToken() {
token = lexer.nextToken()
}
public fun parse(): TreeNode {
return clazz()
}
private fun name(key: Int): Name {
return if (token.key == key) {
val obj = token.obj
nextToken()
NameTable.addString(obj.toString())
} else
NameTable.emptyName()
}
/**
* class = CLASS TYPEID [INHERITS TYPEID] "{" features "}"
*/
private fun clazz(): AbstractClass {
if (token.key == TokenConstants.CLASS) {
nextToken()
val name: Name = name(TokenConstants.TYPEID)
var parent: Name? = null
if (token.key == TokenConstants.INHERITS) {
nextToken()
parent = name(TokenConstants.TYPEID)
}
accept(TokenConstants.LBRACE)
val features = features()
accept(TokenConstants.RBRACE)
return Clazz(token.lineNumber, name, parent, features)
} else {
error(TokenConstants.CLASS)
skip()
return Clazz(token.lineNumber, NameTable.emptyName(), NameTable.emptyName(), Features(token.lineNumber))
}
}
/**
* features = { feature }
*/
private fun features(): Features {
val elements = ArrayList<AbstractFeature>()
while (token.key != TokenConstants.RBRACE) {
if (token.key == TokenConstants.OBJECTID) {
elements.add(feature())
}
accept(TokenConstants.SEMI)
}
return Features(token.lineNumber, elements)
}
/**
* feature = OBJID feature_rest
*/
private fun feature(): AbstractFeature {
val lineNumber = token.lineNumber
if (token.key == TokenConstants.OBJECTID) {
val name = NameTable.addString(token.obj.toString())
nextToken()
return featureRest(lineNumber, name)
} else {
skip()
return ErrorFeature(lineNumber)
}
}
/**
* feature_rest = "(" formals ")" ":" TYPEID "{" expr "}"
* | ":" TYPEID ["<-" expr ";"]
*/
private fun featureRest(lineNumber: Int,
name: Name): AbstractFeature {
val feature: AbstractFeature = when (token.key) {
TokenConstants.LPAREN -> {
nextToken()
val formals = formals()
nextToken()
accept(TokenConstants.RPAREN)
accept(TokenConstants.COLON)
val typeName: Name = name(TokenConstants.TYPEID)
accept(TokenConstants.LBRACE)
val body: AbstractExpression = expr(0)
accept(TokenConstants.RBRACE)
Method(lineNumber, name, typeName, formals, body)
}
TokenConstants.COLON -> {
nextToken()
val typeName: Name = name(TokenConstants.TYPEID)
val init: AbstractExpression? = if (token.key == TokenConstants.ASSIGN) {
nextToken()
expr(0)
} else null
accept(TokenConstants.SEMI)
Attr(lineNumber, name, typeName, init)
}
else -> {
error(TokenConstants.COLON)
skip()
ErrorFeature(lineNumber)
}
}
return feature
}
/**
* formals = { formal }
*/
private fun formals(): Formals {
val lineNumber = token.lineNumber
val elements = ArrayList<AbstractFormal>()
while (token.key != TokenConstants.RPAREN) {
elements.add(formal())
if (token.key != TokenConstants.RPAREN) {
accept(TokenConstants.COMMA)
}
}
return Formals(lineNumber, elements)
}
/**
* formal = OBJID ":" TYPEID
*/
private fun formal(): AbstractFormal {
val lineNumber = token.lineNumber
val name: Name = name(TokenConstants.OBJECTID)
accept(TokenConstants.COLON)
val typeName: Name = name(TokenConstants.TYPEID)
return Formal(lineNumber, name, typeName)
}
/**
* expr_list = { expr [","] }
*/
private fun expr_list(): Expressions {
val lineNumber = token.lineNumber
val expressions = ArrayList<AbstractExpression>()
while (token.key != TokenConstants.RPAREN) {
expressions.add(expr(0))
if (token.key != TokenConstants.RPAREN) {
accept(TokenConstants.COMMA)
}
}
return Expressions(lineNumber, expressions)
}
/**
* expr = OBJID obj_rest | expr1
*/
private fun expr(minPrec: Int): AbstractExpression {
val expr1 = expr1()
return expr_rest(expr1, minPrec)
}
/**
* expr_rest = [ "@" TYPEID ] "." OBJID "(" expr_list ")"
* | { operator expr }
* operator = "||"
* | "&&"
* | "=="
* | "<" | ">" | "<=" | ">="
* | "+" | "-"
* | "*" | "/"
*/
private fun expr_rest(expr1: AbstractExpression,
minPrec: Int): AbstractExpression {
val typeName: Name? = if (token.key == TokenConstants.AT) {
nextToken()
name(TokenConstants.TYPEID)
} else null
val lineNumber = token.lineNumber
return when (token.key) {
TokenConstants.DOT -> {
nextToken()
val name: Name = name(TokenConstants.OBJECTID)
accept(TokenConstants.LPAREN)
val expr_list = expr_list()
accept(TokenConstants.RPAREN)
Dispatch(lineNumber, expr1, typeName, name, expr_list)
}
TokenConstants.PLUS,
TokenConstants.MINUS,
TokenConstants.MULT,
TokenConstants.DIV,
TokenConstants.LT,
TokenConstants.LE,
TokenConstants.EQ -> {
val lineNumber = token.lineNumber
var expr = expr1
while (minPrec <= prec(token.key)) {
val op = token.key
val q = minPrec
nextToken()
val expr2 = expr(q)
expr = BinaryExpr(lineNumber, op, expr, expr2)
}
expr
}
else -> expr1
}
}
private fun expr1(): AbstractExpression {
return if (token.key == TokenConstants.OBJECTID) {
val lineNumber = token.lineNumber
val name = NameTable.addString(token.obj.toString())
nextToken()
obj_rest(lineNumber, name)
} else {
expr2()
}
}
/**
* obj_rest = "<-" expr expr_rest | "(" expr_list ")" expr_rest | expr_rest
*/
private fun obj_rest(lineNumber: Int, name: Name): AbstractExpression {
return when (token.key) {
TokenConstants.ASSIGN -> {
nextToken()
val init = expr(0)
Assign(lineNumber, name, init)
}
TokenConstants.LPAREN -> {
nextToken()
val expr_list = expr_list()
accept(TokenConstants.RPAREN)
Call(lineNumber, name, expr_list)
}
else -> ObjectId(lineNumber, name)
}
}
/**
* expr1 = IF expr THEN expr ELSE expr FI
* | WHILE expr LOOP expr POOL
* | "{" block_exprs "}"
* | LET OBJID ":" TYPEID ["<-" expr] {"," OBJID ":" TYPEID ["<-" expr] } vars IN expr //TODO:
* | CASE expr OF OBJID ":" TYPEID => expr; { OBJID ":" TYPEID => expr; } ESAC //TODO:
* | NEW TYPEID
* | ISVOID
* | "~" expr
* | NOT expr
* | "(" expr ")"
* | literal
*/
private fun expr2(): AbstractExpression {
val lineNumber = token.lineNumber
return when (token.key) {
TokenConstants.IF -> {
nextToken()
val cond = expr(0)
accept(TokenConstants.THEN)
val thenExpr = expr(0)
accept(TokenConstants.ELSE)
val elseExpr = expr(0)
accept(TokenConstants.FI)
IfExpr(lineNumber, cond, thenExpr, elseExpr)
}
TokenConstants.WHILE -> {
nextToken()
val cond = expr(0)
accept(TokenConstants.LOOP)
val body = expr(0)
accept(TokenConstants.POOL)
WhileExpr(lineNumber, cond, body)
}
TokenConstants.LBRACE -> {
nextToken()
val expr_list = block_exprs()
accept(TokenConstants.RBRACE)
Block(lineNumber, expr_list)
}
TokenConstants.NEW -> {
nextToken()
val typeName = name(TokenConstants.TYPEID)
New(lineNumber, typeName)
}
TokenConstants.ISVOID -> {
nextToken()
val expr = expr(0)
IsVoid(lineNumber, expr)
}
TokenConstants.MINUS -> {
nextToken()
val expr = expr(0)
Neg(lineNumber, expr)
}
TokenConstants.NOT -> {
nextToken()
val expr = expr(0)
Not(lineNumber, expr)
}
TokenConstants.NEG -> {
nextToken()
val expr = expr(0)
Comp(lineNumber, expr)
}
TokenConstants.LPAREN -> {
nextToken()
val expr = expr(0)
accept(TokenConstants.RPAREN)
expr
}
TokenConstants.INT_CONST,
TokenConstants.STR_CONST,
TokenConstants.BOOL_CONST -> literal()
else -> illegal()
}
}
/**
* block_exprs = expr ";" { expr ";" }
*/
private fun block_exprs(): Expressions {
val lineNumber = token.lineNumber
val expressions = ArrayList<AbstractExpression>()
expressions.add(expr(0))
accept(TokenConstants.SEMI)
while (token.key != TokenConstants.RPAREN) {
expressions.add(expr(0))
accept(TokenConstants.SEMI)
}
return Expressions(lineNumber, expressions)
}
/**
* literal = INT | STRING | TRUE | FALSE
*/
private fun literal(): AbstractExpression {
val lineNumber = token.lineNumber
return when (token.key) {
TokenConstants.INT_CONST -> IntLiteral(lineNumber, token.obj as Int)
TokenConstants.STR_CONST -> StringLiteral(lineNumber, token.obj as String)
TokenConstants.BOOL_CONST -> BoolLiteral(lineNumber, token.obj as Boolean)
else -> illegal()
}
}
} | mit | dc00be449c37644aa3342b67cc4c92d7 | 29.952719 | 116 | 0.518637 | 4.734901 | false | false | false | false |
tomhenne/Jerusalem | src/main/java/de/esymetric/jerusalem/ownDataRepresentation/fileSystem/PartitionedQuadtreeNodeIndexFile.kt | 1 | 15194 | package de.esymetric.jerusalem.ownDataRepresentation.fileSystem
import de.esymetric.jerusalem.ownDataRepresentation.fileSystem.NodeIndexFile.NodeIndexNodeDescriptor
import de.esymetric.jerusalem.rebuilding.Rebuilder
import de.esymetric.jerusalem.utils.BufferedRandomAccessFile
import de.esymetric.jerusalem.utils.BufferedRandomAccessFileCache
import de.esymetric.jerusalem.utils.Utils
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import java.util.*
class PartitionedQuadtreeNodeIndexFile(
var dataDirectoryPath: String,
readOnly: Boolean, startNewFile: Boolean
) : NodeIndexFile {
var rafIndexCache = BufferedRandomAccessFileCache()
var rafListCache = BufferedRandomAccessFileCache()
var readOnly = false
var numberOfSentences = 0
var emptySentence = ByteArray(40)
var writeCount = 0
var writeCacheHits = 0
var readCount = 0
var readCacheHits = 0
override val writeCacheHitRatio: Float
get() {
if (writeCount == 0) return 0f
val f = 100.0f * writeCacheHits / writeCount
writeCacheHits = 0
writeCount = 0
return f
}
override val readCacheHitRatio: Float
get() {
if (readCount == 0) return 0f
val f = 100.0f * readCacheHits / readCount
readCacheHits = 0
readCount = 0
return f
}
private fun getIndexFilePath(lat: Double, lng: Double): String {
val lld = LatLonDir(lat, lng)
return (lld.getDir(dataDirectoryPath) + File.separatorChar
+ INDEX_FILENAME)
}
private fun getListFilePath(lat: Double, lng: Double): String {
val lld = LatLonDir(lat, lng)
return (lld.getDir(dataDirectoryPath) + File.separatorChar
+ LIST_FILENAME)
}
var lastIndexFilePath: String? = null
var lastIndexRaf: BufferedRandomAccessFile? = null
private fun getIndexRaf(lat: Double, lng: Double): BufferedRandomAccessFile? {
val filePath = getIndexFilePath(lat, lng)
return if (filePath == lastIndexFilePath) lastIndexRaf else try {
val raf = rafIndexCache.getRandomAccessFile(
filePath, readOnly
)
if (raf != null) {
lastIndexFilePath = filePath
lastIndexRaf = raf
numberOfSentences = raf.size / SENTENCE_LENGTH.toInt()
if (numberOfSentences == 0) insertNewSentence(raf)
}
raf
} catch (e: Exception) {
e.printStackTrace()
null
}
}
private var lastListFilePath: String? = null
private var lastListRaf: BufferedRandomAccessFile? = null
init {
this.readOnly = readOnly
if (readOnly) {
rafIndexCache.setMaxCacheSize(8)
rafListCache.setMaxCacheSize(8)
}
for (i in 0..39) emptySentence[i] = -1
}
private fun getListRaf(lat: Double, lng: Double): BufferedRandomAccessFile? {
val filePath = getListFilePath(lat, lng)
return if (filePath == lastListFilePath) lastListRaf else try {
val raf = rafListCache.getRandomAccessFile(
filePath, readOnly
)
if (raf != null) {
lastListFilePath = filePath
lastListRaf = raf
}
raf
} catch (e: Exception) {
e.printStackTrace()
null
}
}
override fun close() {
rafIndexCache.close()
rafListCache.close()
}
override fun getID(lat: Double, lng: Double): Int {
val raf = getIndexRaf(lat, lng) ?: return -1
val latInt = ((lat + LAT_OFFS) * USED_DIGITS_MULT).toInt()
val lngInt = ((lng + LNG_OFFS) * USED_DIGITS_MULT).toInt()
return try {
getID(latInt, lngInt, raf)
} catch (e: IOException) {
e.printStackTrace()
-1
}
}
private fun getID(latInt: Int, lngInt: Int): Int {
val lat = latInt / USED_DIGITS_MULT - LAT_OFFS.toInt()
val lng = lngInt / USED_DIGITS_MULT - LNG_OFFS.toInt()
val raf =
getIndexRaf(lat.toDouble(), lng.toDouble()) ?: return -1
return try {
getID(latInt, lngInt, raf)
} catch (e: IOException) {
e.printStackTrace()
-1
}
}
private fun getID(latInt: Int, lngInt: Int, raf: BufferedRandomAccessFile): Int {
if (numberOfSentences == 0) return -1
if (latInt < 0 || latInt > MAX_LAT_INT) return -1
if (lngInt < 0 || lngInt > MAX_LNG_INT) return -1
readCount++
var id = 0
val keyChain = getKeyChain(latInt, lngInt)
var i = 0
while (i < NUMBER_OF_USED_DIGITS_MULT_2) {
raf.seek(id.toLong() * SENTENCE_LENGTH + keyChain[i].toLong() * 4L)
id = raf.readInt()
if (id == -1) break
i++
}
return id // the last id is the id referring to a node
}
private fun getKeyChain(latInt: Int, lngInt: Int): IntArray {
// example: for latInt=138110 and lngInt=191480
// the keychain will be: [1, 1, 3, 9, 8, 1, 1, 4, 1, 8, 0, 0]
var latIntRemainder = latInt
var lngIntRemainder = lngInt
val keyChain = IntArray(NUMBER_OF_USED_DIGITS_MULT_2)
var i = NUMBER_OF_USED_DIGITS_MULT_2 - 2
while (i >= 0) {
keyChain[i] = latIntRemainder % 10
keyChain[i + 1] = lngIntRemainder % 10
latIntRemainder /= 10
lngIntRemainder /= 10
i -= 2
}
return keyChain
}
override fun getIDPlusSourroundingIDs(
lat: Double,
lng: Double, radius: Int
): List<NodeIndexNodeDescriptor> {
val list: MutableList<NodeIndexNodeDescriptor> = ArrayList()
val latInt = ((lat + LAT_OFFS) * USED_DIGITS_MULT).toInt()
val lngInt = ((lng + LNG_OFFS) * USED_DIGITS_MULT).toInt()
try {
val rSquare = radius * radius
for (x in latInt - radius..latInt + radius) for (y in lngInt - radius..lngInt + radius) {
val deltaX = x - latInt
val deltaY = y - lngInt
if (deltaX * deltaX + deltaY * deltaY <= rSquare) {
val idInListFile = getID(x, y)
if (idInListFile == -1) continue
val nodes = getAllNodeIDsFromQuadtreeList(
lat, lng, idInListFile
)
for (nodeID in nodes) {
val nind = NodeIndexNodeDescriptor()
nind.id = nodeID
nind.latInt = x / USED_DIGITS_MULT - LAT_OFFS.toInt() // not
// elegant
nind.lngInt = y / USED_DIGITS_MULT - LNG_OFFS.toInt()
list.add(nind)
}
}
}
} catch (e: Exception) {
e.printStackTrace()
}
return list
}
private fun getAllNodeIDsFromQuadtreeList(lat: Double, lng: Double, id: Int): List<Int> {
var currentId = id
val l: MutableList<Int> = LinkedList()
val rafList = getListRaf(lat, lng) ?: return l
try {
while (true) {
rafList.seek(currentId * NODELIST_SENTENCE_LENGTH)
val nodeID: Int = rafList.readInt()
val nextID = rafList.readInt()
l.add(nodeID)
if (nextID == -1) break
currentId = nextID
}
} catch (e: IOException) {
e.printStackTrace()
}
return l
}
override fun setID(lat: Double, lng: Double, id: Int): Int {
val raf = getIndexRaf(lat, lng)
val latInt = ((lat + LAT_OFFS) * USED_DIGITS_MULT).toInt()
val lngInt = ((lng + LNG_OFFS) * USED_DIGITS_MULT).toInt()
return try {
setID(latInt, lngInt, id, raf!!)
} catch (e: IOException) {
e.printStackTrace()
-1
}
}
private fun setID(latInt: Int, lngInt: Int, nodeID: Int, raf: BufferedRandomAccessFile): Int {
if (latInt < 0 || latInt > MAX_LAT_INT) return -1
if (lngInt < 0 || lngInt > MAX_LNG_INT) return -1
writeCount++
var id = 0
val keyChain = getKeyChain(latInt, lngInt)
var i = 0
// read as long as leafs exist
while (i < NUMBER_OF_USED_DIGITS_MULT_2 - 1) {
val pos = id.toLong() * SENTENCE_LENGTH + keyChain[i].toLong() * 4L
if (!raf.seek(pos)) break
val foundID = raf.readInt()
if (foundID == -1) break
id = foundID
i++
}
// add new leafs
while (i < NUMBER_OF_USED_DIGITS_MULT_2 - 1) {
val newID = insertNewSentence(raf)
if (newID == -1) {
println("ERROR: cannot create new sentence in QuadtreeNodeIndexFile")
return -1
}
val pos = id.toLong() * SENTENCE_LENGTH + keyChain[i].toLong() * 4L
raf.seek(pos)
raf.writeInt(newID)
id = newID
i++
}
// insert nodeID on the last leaf
val pos = id.toLong() * SENTENCE_LENGTH + keyChain[i].toLong() * 4L
raf.seek(pos)
val oldID = raf.readInt()
raf.seek(pos)
raf.writeInt(nodeID)
return oldID
}
private fun insertNewSentence(raf: BufferedRandomAccessFile?): Int {
val fileLength = numberOfSentences.toLong() * SENTENCE_LENGTH
return try {
raf!!.seek(fileLength)
raf.write(emptySentence)
val id = numberOfSentences
numberOfSentences++
id
} catch (e: IOException) {
e.printStackTrace()
-1
}
}
override val capacity: Int
get() = 10 * numberOfSentences
fun makeQuadtreeIndex(startTime: Date, nlf: PartitionedNodeListFile) {
val files = File(dataDirectoryPath).listFiles()
Arrays.sort(files)
for (f in files) if (f.isDirectory && f.name.startsWith("lat_")) {
for (g in f.listFiles()) if (g != null && g.isDirectory
&& g.name.startsWith("lng_")
) {
val list = g.listFiles()
if (list == null) {
println(
"Cannot list files in " + g.path
)
continue
}
for (h in list) if (h != null && h.isFile
&& h.name == PartitionedNodeListFile.FILE_NAME
) {
val dirLatInt: Int = f.name
.replace("lat_", "").toInt() - LatLonDir.LAT_OFFS.toInt()
val dirLngInt: Int = g.name
.replace("lng_", "").toInt() - LatLonDir.LNG_OFFS.toInt()
val quadtreeIndexFilePath = (g.path
+ File.separatorChar
+ INDEX_FILENAME)
val quadtreeListFilePath = (g.path
+ File.separatorChar
+ LIST_FILENAME)
File(quadtreeIndexFilePath).delete()
File(quadtreeListFilePath).delete()
val rafIndex = BufferedRandomAccessFile()
val rafList = BufferedRandomAccessFile()
try {
rafIndex.open(quadtreeIndexFilePath, "rw")
rafList.open(quadtreeListFilePath, "rw")
} catch (e1: FileNotFoundException) {
e1.printStackTrace()
continue
}
numberOfSentences = 0
insertNewSentence(rafIndex)
val nodes = nlf.getAllNodesInFile(h.path)
println("\n"
+ Utils.formatTimeStopWatch(
Date().time - startTime.time)
+ " building quadtree lat=" + dirLatInt
+ " lng=" + dirLngInt + " with "
+ nodes.size + " nodes"
)
var idInListFile = 0
for (n in nodes) {
try {
val latInt = ((n.lat + LAT_OFFS) * USED_DIGITS_MULT).toInt()
val lngInt = ((n.lng + LNG_OFFS) * USED_DIGITS_MULT).toInt()
// this node will be set to first in the linked list
val foundID = setID(
latInt, lngInt,
idInListFile, rafIndex
)
idInListFile++
rafList.writeInt(n.id.toInt())
rafList.writeInt(foundID) // the former first will now be second in the list
} catch (e: IOException) {
e.printStackTrace()
}
}
try {
rafIndex.close()
rafList.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
Rebuilder.cleanMem(startTime)
}
println(
Utils.formatTimeStopWatch(
Date().time
- startTime.time
)
+ " finished building quadtree"
)
}
override val maxCacheSize = 32000 // number of entries
companion object {
private const val NUMBER_OF_USED_DIGITS = 6 // if you change this, also
// change USED_DIGITS_MULT and
// MAX_SEARCH_RADIUS in
// NearestNodeFinder
const val NUMBER_OF_USED_DIGITS_MULT_2 = NUMBER_OF_USED_DIGITS * 2
const val USED_DIGITS_MULT = 1000 // 4 digits
const val LAT_OFFS = 90.0
const val LNG_OFFS = 180.0
const val SENTENCE_LENGTH = 40L // the tree has 10 leaves on each branch
// so the sentence length 10 * 4 bytes (4 bytes for each reference to the next node)
const val NODELIST_SENTENCE_LENGTH = 8L // int nodeID, int next
const val MAX_LAT_INT = 180 * USED_DIGITS_MULT
const val MAX_LNG_INT = 360 * USED_DIGITS_MULT
const val INDEX_FILENAME = "quadtreeIndex.data"
const val LIST_FILENAME = "quadtreeNodeList.data"
}
} | apache-2.0 | d0117f85263b9acb24aa80c3739ee122 | 36.085213 | 104 | 0.500724 | 4.534169 | false | false | false | false |
EricssonResearch/scott-eu | lyo-services/lib-common/src/main/kotlin/eu/scott/warehouse/lib/hazelcast/HCData.kt | 1 | 725 | package eu.scott.warehouse.lib.hazelcast
/*
@Deprecated("Phasing Hazelcast out of the SCOTT sandbox")
data class HCData(val url: String, val uuid: String, val headers: Array<String>) :
Serializable {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is HCData) return false
if (url != other.url) return false
if (uuid != other.uuid) return false
if (!Arrays.equals(headers, other.headers)) return false
return true
}
override fun hashCode(): Int {
var result = url.hashCode()
result = 31 * result + uuid.hashCode()
result = 31 * result + Arrays.hashCode(headers)
return result
}
}
*/
| apache-2.0 | f5cbe3f4b2d476f81c2471a93f709972 | 28 | 82 | 0.623448 | 4.073034 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-license/src/test/java/net/nemerosa/ontrack/extension/license/AbstractLicenseTestSupport.kt | 1 | 1127 | package net.nemerosa.ontrack.extension.license
import net.nemerosa.ontrack.extension.license.fixed.FixedLicenseService
import net.nemerosa.ontrack.it.AbstractDSLTestSupport
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.TestPropertySource
import java.time.LocalDateTime
@TestPropertySource(
properties = [
"ontrack.config.license.provider=fixed",
]
)
abstract class AbstractLicenseTestSupport : AbstractDSLTestSupport() {
@Autowired
protected lateinit var licenseService: FixedLicenseService
protected fun withLicense(
validUntil: LocalDateTime? = null,
maxProjects: Int = 0,
code: () -> Unit,
) {
val oldLicense = licenseService.license
try {
licenseService.license = License(
name = "Test license",
assignee = "CI",
validUntil = validUntil,
maxProjects = maxProjects,
active = true,
)
code()
} finally {
licenseService.license = oldLicense
}
}
} | mit | 774f1dd2d3408ae5a7e88378e1484287 | 27.923077 | 71 | 0.64685 | 4.878788 | false | true | false | false |
nemerosa/ontrack | ontrack-extension-notifications/src/main/java/net/nemerosa/ontrack/extension/notifications/subscriptions/SubscriptionsRoleContributor.kt | 1 | 2160 | package net.nemerosa.ontrack.extension.notifications.subscriptions
import net.nemerosa.ontrack.extension.notifications.recording.NotificationRecordingAccess
import net.nemerosa.ontrack.model.security.*
import org.springframework.stereotype.Component
@Component
class SubscriptionsRoleContributor : RoleContributor {
companion object {
const val GLOBAL_SUBSCRIPTIONS_MANAGER = "GLOBAL_SUBSCRIPTIONS_MANAGER"
}
override fun getGlobalRoles() = listOf(
RoleDefinition(
id = GLOBAL_SUBSCRIPTIONS_MANAGER,
name = "Global subscriptions manager",
description = "Right to manage subscriptions at global level",
)
)
override fun getGlobalFunctionContributionsForGlobalRoles(): Map<String, List<Class<out GlobalFunction>>> = mapOf(
Roles.GLOBAL_ADMINISTRATOR to listOf(
GlobalSubscriptionsManage::class.java,
NotificationRecordingAccess::class.java,
),
GLOBAL_SUBSCRIPTIONS_MANAGER to listOf(
GlobalSubscriptionsManage::class.java,
NotificationRecordingAccess::class.java,
)
)
override fun getProjectFunctionContributionsForGlobalRoles(): Map<String, List<Class<out ProjectFunction>>> =
mapOf(
Roles.GLOBAL_ADMINISTRATOR to listOf(
ProjectSubscriptionsRead::class.java,
ProjectSubscriptionsWrite::class.java,
),
Roles.GLOBAL_PARTICIPANT to listOf(
ProjectSubscriptionsRead::class.java
)
)
override fun getProjectFunctionContributionsForProjectRoles(): Map<String, List<Class<out ProjectFunction>>> =
mapOf(
Roles.PROJECT_PARTICIPANT to listOf(
ProjectSubscriptionsRead::class.java,
),
Roles.PROJECT_MANAGER to listOf(
ProjectSubscriptionsRead::class.java,
ProjectSubscriptionsWrite::class.java,
),
Roles.PROJECT_OWNER to listOf(
ProjectSubscriptionsRead::class.java,
ProjectSubscriptionsWrite::class.java,
),
)
} | mit | ef9076871e8e190267832b6f5e54e2df | 36.258621 | 118 | 0.655093 | 5.4 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-git/src/main/java/net/nemerosa/ontrack/extension/git/graphql/IssueChangeLogExportRequestGQLInputType.kt | 1 | 4577 | package net.nemerosa.ontrack.extension.git.graphql
import graphql.schema.GraphQLInputObjectType
import graphql.schema.GraphQLInputType
import graphql.schema.GraphQLType
import graphql.schema.GraphQLTypeReference
import net.nemerosa.ontrack.extension.api.model.IssueChangeLogExportRequest
import net.nemerosa.ontrack.graphql.schema.GQLInputType
import net.nemerosa.ontrack.graphql.schema.stringInputField
import org.springframework.stereotype.Component
/**
* Input type for [IssueChangeLogExportRequest].
*/
@Component
class IssueChangeLogExportRequestGQLInputType: GQLInputType<IssueChangeLogExportRequest> {
override fun createInputType(dictionary: MutableSet<GraphQLType>): GraphQLInputType =
GraphQLInputObjectType.newInputObject()
.name(IssueChangeLogExportRequest::class.java.simpleName)
.description("""Request for the export of a change log.
This request defines how to group issues by type and which format
to use for the export.
If no grouping is specified, the issues will be returned as a list, without any grouping.
The exclude field is used to exclude some issues from the export using their type.
Note that both the export format and the type of issues are specific notions linked to the issue service
(JIRA, GitHub...) that produces the issues.""".trimIndent())
.fields(
listOf(
stringInputField(IssueChangeLogExportRequest::format, nullable = true),
stringInputField(IssueChangeLogExportRequest::grouping, """
Specification for the grouping, none by default.
This specification describes how to group issues using their type. This format is independent from
the issue service and this service is responsible for the actual mapping of issue "types" into actual
issue fields. For example, for GitHub, an issue type is mapped on a label.
The format of the specification is:
----
specification := "" | ${'$'}group ( "|" ${'$'}group)*
group := ${'$'}name "=" ${'$'}type ( "," ${'$'}type)*
----
For example:
----
Bugs=bug|Features=feature,enhancement
----
Any issue that would not be mapped in a group will be assigned arbitrarily to the group defined by
altGroup property.
If the specification is empty, no grouping will be done.
""".trimIndent(), nullable = true),
stringInputField(IssueChangeLogExportRequest::exclude, nullable = true),
stringInputField(IssueChangeLogExportRequest::altGroup, """
Title of the group to use when an issue does not belong to any group. It defaults to "Other".
If left empty, any issue not belonging to a group would be excluded from the export. This field
is not used when no grouping is specified.
""".trimIndent(), nullable = true),
)
)
.build()
override fun convert(argument: Any?):IssueChangeLogExportRequest? {
return if (argument != null && argument is Map<*,*>) {
IssueChangeLogExportRequest().apply {
(argument[IssueChangeLogExportRequest::format.name] as? String)?.let {
format = it
}
(argument[IssueChangeLogExportRequest::grouping.name] as? String)?.let {
grouping = it
}
(argument[IssueChangeLogExportRequest::exclude.name] as? String)?.let {
exclude = it
}
(argument[IssueChangeLogExportRequest::altGroup.name] as? String)?.let {
altGroup = it
}
}
} else {
null
}
}
override fun getTypeRef()= GraphQLTypeReference(IssueChangeLogExportRequest::class.java.simpleName)
} | mit | d98729923e316550172f38e26387b29e | 49.307692 | 125 | 0.553856 | 6.269863 | false | false | false | false |
Kerr1Gan/ShareBox | share/src/main/java/com/ethan/and/ui/activity/SettingsActivity.kt | 1 | 11529 | package com.ethan.and.ui.activity
import android.annotation.TargetApi
import android.content.Context
import android.content.res.Configuration
import android.media.RingtoneManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.preference.*
import android.text.TextUtils
import android.text.format.Formatter
import android.view.MenuItem
import com.flybd.sharebox.PreferenceInfo
import com.flybd.sharebox.R
import com.ethan.and.ui.preference.CachePreference
import com.flybd.sharebox.util.activity.ActivityUtil
import com.flybd.sharebox.util.cache.CacheUtil
import com.flybd.sharebox.util.file.FileUtil
import java.io.File
/**
* A [PreferenceActivity] that presents a set of application settings. On
* handset devices, settings are presented as a single list. On tablets,
* settings are split by category, with category headers shown to the left of
* the list of settings.
*
*
* See [
* Android Design: Settings](http://developer.android.com/design/patterns/settings.html) for design guidelines and the [Settings
* API Guide](http://developer.android.com/guide/topics/ui/settings.html) for more information on developing a Settings UI.
*/
class SettingsActivity : AppCompatPreferenceActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupActionBar()
var pref = PreferenceManager.getDefaultSharedPreferences(this)
pref.edit().putString(getString(R.string.key_device_name), pref.getString(PreferenceInfo.PREF_DEVICE_NAME, Build.MODEL)).apply()
}
/**
* Set up the [android.app.ActionBar], if the API is available.
*/
private fun setupActionBar() {
val actionBar = supportActionBar
actionBar?.setDisplayHomeAsUpEnabled(true)
}
override fun onMenuItemSelected(featureId: Int, item: MenuItem?): Boolean {
if (item?.itemId == android.R.id.home) {
finish()
return true
}
return super.onMenuItemSelected(featureId, item)
}
/**
* {@inheritDoc}
*/
override fun onIsMultiPane(): Boolean {
return isXLargeTablet(this)
}
/**
* {@inheritDoc}
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
override fun onBuildHeaders(target: List<PreferenceActivity.Header>) {
loadHeadersFromResource(R.xml.pref_headers, target)
}
/**
* This method stops fragment injection in malicious applications.
* Make sure to deny any unknown fragments here.
*/
override fun isValidFragment(fragmentName: String): Boolean {
return PreferenceFragment::class.java.name == fragmentName
|| GeneralPreferenceFragment::class.java.name == fragmentName
|| DataSyncPreferenceFragment::class.java.name == fragmentName
|| NotificationPreferenceFragment::class.java.name == fragmentName
|| PermissionPreferenceFragment::class.java.name == fragmentName
}
/**
* This fragment shows general preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
class GeneralPreferenceFragment : PreferenceFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addPreferencesFromResource(R.xml.pref_general)
setHasOptionsMenu(true)
var cacheFile = File(activity.cacheDir.absolutePath + "/image_manager_disk_cache")
var size = 0L
if (cacheFile.exists()) {
size += getFolderSize(cacheFile)
}
cacheFile = File(CacheUtil.getCacheRootPath(activity))
if (cacheFile.exists()) {
size += getFolderSize(cacheFile)
}
PreferenceManager.getDefaultSharedPreferences(activity).edit().
putString(getString(R.string.key_clear_cache), Formatter.formatFileSize(activity, size)).apply()
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference(getString(R.string.key_device_name)))
// bindPreferenceSummaryToValue(findPreference("example_list"))
bindPreferenceSummaryToValue(findPreference(getString(R.string.key_clear_cache)))
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return super.onOptionsItemSelected(item)
}
fun getFolderSize(root: File): Long {
var list = FileUtil.getFilesByFolder(root)
var ret = 0L
for (child in list) {
ret += child.length()
}
return ret
}
}
/**
* This fragment shows notification preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
class NotificationPreferenceFragment : PreferenceFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addPreferencesFromResource(R.xml.pref_notification)
setHasOptionsMenu(true)
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference(getString(R.string.key_notification_message_ringtone)))
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return super.onOptionsItemSelected(item)
}
}
/**
* This fragment shows data and sync preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
class DataSyncPreferenceFragment : PreferenceFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addPreferencesFromResource(R.xml.pref_data_sync)
setHasOptionsMenu(true)
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("sync_frequency"))
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return super.onOptionsItemSelected(item)
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
class PermissionPreferenceFragment : PreferenceFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//jump to system and close self
var intent = ActivityUtil.getAppDetailSettingIntent(activity)
startActivity(intent)
activity.finish()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return super.onOptionsItemSelected(item)
}
}
companion object {
/**
* Helper method to determine if the device has an extra-large screen. For
* example, 10" tablets are extra-large.
*/
private fun isXLargeTablet(context: Context): Boolean {
return context.resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK >= Configuration.SCREENLAYOUT_SIZE_XLARGE
}
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private val sBindPreferenceSummaryToValueListener = Preference.OnPreferenceChangeListener { preference, value ->
val stringValue = value.toString()
if (preference is ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
val listPreference = preference
val index = listPreference.findIndexOfValue(stringValue)
// Set the summary to reflect the new value.
preference.setSummary(
if (index >= 0)
listPreference.entries[index]
else
null)
} else if (preference is RingtonePreference) {
// For ringtone preferences, look up the correct display value
// using RingtoneManager.
if (TextUtils.isEmpty(stringValue)) {
// Empty values correspond to 'silent' (no ringtone).
preference.setSummary(R.string.pref_ringtone_silent)
} else {
val ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue))
if (ringtone == null) {
// Clear the summary if there was a lookup error.
preference.setSummary(null)
} else {
// Set the summary to reflect the new ringtone display
// name.
val name = ringtone.getTitle(preference.getContext())
preference.setSummary(name)
}
}
} else if (preference is EditTextPreference && preference.key == preference.context.getString(R.string.key_device_name)) {
PreferenceManager.getDefaultSharedPreferences(preference.context).edit().
putString(PreferenceInfo.PREF_DEVICE_NAME, stringValue).apply()
preference.summary = stringValue
} else if (preference is CachePreference) {
// Cache
preference.summary = stringValue
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.summary = stringValue
}
true
}
/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
* @see .sBindPreferenceSummaryToValueListener
*/
private fun bindPreferenceSummaryToValue(preference: Preference) {
// Set the listener to watch for value changes.
preference.onPreferenceChangeListener = sBindPreferenceSummaryToValueListener
// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.context)
.getString(preference.key, ""))
}
}
}
| apache-2.0 | 809ce546e8be3962afd1d66c735b84f5 | 40.175 | 146 | 0.633793 | 5.521552 | false | false | false | false |
gameofbombs/kt-postgresql-async | postgresql-async/src/main/kotlin/com/github/mauricio/async/db/postgresql/parsers/AuthenticationStartupParser.kt | 2 | 2186 | /*
* Copyright 2013 Maurício Linhares
*
* Maurício Linhares licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.github.mauricio.async.db.postgresql.parsers
import com.github.mauricio.async.db.exceptions.UnsupportedAuthenticationMethodException
import com.github.mauricio.async.db.postgresql.messages.backend.AuthenticationChallengeMD5
import com.github.mauricio.async.db.postgresql.messages.backend.AuthenticationChallengeCleartextMessage
import com.github.mauricio.async.db.postgresql.messages.backend.AuthenticationOkMessage
import com.github.mauricio.async.db.postgresql.messages.backend.ServerMessage
import io.netty.buffer.ByteBuf
object AuthenticationStartupParser : MessageParser {
val AuthenticationOk = 0
val AuthenticationKerberosV5 = 2
val AuthenticationCleartextPassword = 3
val AuthenticationMD5Password = 5
val AuthenticationSCMCredential = 6
val AuthenticationGSS = 7
val AuthenticationGSSContinue = 8
val AuthenticationSSPI = 9
override fun parseMessage(buffer: ByteBuf): ServerMessage {
val authenticationType = buffer.readInt()
return when (authenticationType) {
AuthenticationOk -> AuthenticationOkMessage.Instance
AuthenticationCleartextPassword -> AuthenticationChallengeCleartextMessage.Instance
AuthenticationMD5Password -> {
val bytes = ByteArray(buffer.readableBytes())
buffer.readBytes(bytes)
AuthenticationChallengeMD5(bytes)
}
else -> {
throw UnsupportedAuthenticationMethodException(authenticationType)
}
}
}
} | apache-2.0 | 3367fa204ebaed94a35e29c58d9bf751 | 37.333333 | 103 | 0.744048 | 4.853333 | false | false | false | false |
kotlin-graphics/imgui | core/src/main/kotlin/imgui/internal/classes/TabBar.kt | 2 | 36290 | package imgui.internal.classes
import glm_.has
import glm_.hasnt
import glm_.max
import glm_.min
import glm_.vec2.Vec2
import glm_.vec4.Vec4
import imgui.*
import imgui.ImGui.arrowButtonEx
import imgui.ImGui.beginCombo
import imgui.ImGui.buttonBehavior
import imgui.ImGui.endCombo
import imgui.ImGui.findRenderedTextEnd
import imgui.ImGui.getIDWithSeed
import imgui.ImGui.io
import imgui.ImGui.isItemHovered
import imgui.ImGui.isMouseClicked
import imgui.ImGui.isMouseDragging
import imgui.ImGui.isMouseReleased
import imgui.ImGui.itemAdd
import imgui.ImGui.itemSize
import imgui.ImGui.keepAliveID
import imgui.ImGui.markIniSettingsDirty
import imgui.ImGui.popClipRect
import imgui.ImGui.popItemFlag
import imgui.ImGui.popStyleColor
import imgui.ImGui.pushClipRect
import imgui.ImGui.pushItemFlag
import imgui.ImGui.pushStyleColor
import imgui.ImGui.renderNavHighlight
import imgui.ImGui.selectable
import imgui.ImGui.setItemAllowOverlap
import imgui.ImGui.setTooltip
import imgui.ImGui.shrinkWidths
import imgui.ImGui.style
import imgui.ImGui.tabItemBackground
import imgui.ImGui.tabItemCalcSize
import imgui.ImGui.tabItemLabelAndCloseButton
import imgui.api.g
import imgui.internal.floor
import imgui.internal.hashStr
import imgui.internal.linearSweep
import imgui.internal.sections.ButtonFlag
import imgui.internal.sections.IMGUI_TEST_ENGINE_ITEM_INFO
import imgui.internal.sections.ItemFlag
import imgui.internal.sections.or
import kotlin.math.abs
import kotlin.reflect.KMutableProperty0
class TabBarSection {
/** Number of tabs in this section. */
var tabCount = 0
/** Sum of width of tabs in this section (after shrinking down) */
var width = 0f
/** Horizontal spacing at the end of the section. */
var spacing = 0f
}
/** Storage for a tab bar (sizeof() 152 bytes) */
class TabBar {
val tabs = ArrayList<TabItem>()
var flags: TabBarFlags = TabBarFlag.None.i
/** Zero for tab-bars used by docking */
var id: ID = 0
/** Selected tab/window */
var selectedTabId: ID = 0
var nextSelectedTabId: ID = 0
/** Can occasionally be != SelectedTabId (e.g. when previewing contents for CTRL+TAB preview) */
var visibleTabId: ID = 0
var currFrameVisible = -1
var prevFrameVisible = -1
var barRect = Rect()
var currTabsContentsHeight = 0f
/** Record the height of contents submitted below the tab bar */
var prevTabsContentsHeight = 0f
/** Actual width of all tabs (locked during layout) */
var widthAllTabs = 0f
/** Ideal width if all tabs were visible and not clipped */
var widthAllTabsIdeal = 0f
var scrollingAnim = 0f
var scrollingTarget = 0f
var scrollingTargetDistToVisibility = 0f
var scrollingSpeed = 0f
var scrollingRectMinX = 0f
var scrollingRectMaxX = 0f
var reorderRequestTabId: ID = 0
var reorderRequestDir = 0
var beginCount = 0
var wantLayout = false
var visibleTabWasSubmitted = false
/** Set to true when a new tab item or button has been added to the tab bar during last frame */
var tabsAddedNew = false
/** Number of tabs submitted this frame. */
var tabsActiveCount = 0
/** Index of last BeginTabItem() tab for use by EndTabItem() */
var lastTabItemIdx = -1
var itemSpacingY = 0f
/** style.FramePadding locked at the time of BeginTabBar() */
var framePadding = Vec2()
val backupCursorPos = Vec2()
/** For non-docking tab bar we re-append names in a contiguous buffer. */
val tabsNames = ArrayList<String>()
val TabItem.order: Int
get() = tabs.indexOf(this)
fun getTabName(tab: TabItem): String = tab.name
val TabItem.name: String
get() {
assert(nameOffset in tabsNames.indices)
return tabsNames[nameOffset]
}
// Tab Bars
/** ~ beginTabBarEx */
fun beginEx(bb: Rect, flags__: TabBarFlags): Boolean {
val window = g.currentWindow!!
if (window.skipItems) return false
var flags_ = flags__
if (flags_ hasnt TabBarFlag._DockNode) window.idStack += id
// Add to stack
g.currentTabBarStack += tabBarRef
g.currentTabBar = this
// Append with multiple BeginTabBar()/EndTabBar() pairs.
backupCursorPos put window.dc.cursorPos
if (currFrameVisible == g.frameCount) {
window.dc.cursorPos.put(barRect.min.x, barRect.max.y + itemSpacingY)
beginCount++
return true
}
// Ensure correct ordering when toggling ImGuiTabBarFlags_Reorderable flag, ensure tabs are ordered based on their submission order.
if (flags_ has TabBarFlag.Reorderable != flags has TabBarFlag.Reorderable || (tabsAddedNew && flags hasnt TabBarFlag.Reorderable))
if (tabs.size > 1)
tabs.sortBy(TabItem::beginOrder)
tabsAddedNew = false
// Flags
if (flags_ hasnt TabBarFlag.FittingPolicyMask_) flags_ = flags_ or TabBarFlag.FittingPolicyDefault_
flags = flags_
barRect = bb
wantLayout = true // Layout will be done on the first call to ItemTab()
prevFrameVisible = currFrameVisible
currFrameVisible = g.frameCount
prevTabsContentsHeight = currTabsContentsHeight
currTabsContentsHeight = 0f
itemSpacingY = g.style.itemSpacing.y
framePadding put g.style.framePadding
tabsActiveCount = 0
beginCount = 1
// Layout
// Set cursor pos in a way which only be used in the off-chance the user erroneously submits item before BeginTabItem(): items will overlap
window.dc.cursorPos.put(barRect.min.x, barRect.max.y + itemSpacingY)
// Draw separator
val col = if (flags has TabBarFlag._IsFocused) Col.TabActive else Col.TabUnfocusedActive
val y = barRect.max.y - 1f
run {
val separatorMinX = barRect.min.x - floor(window.windowPadding.x * 0.5f)
val separatorMaxX = barRect.max.x + floor(window.windowPadding.x * 0.5f)
window.drawList.addLine(Vec2(separatorMinX, y), Vec2(separatorMaxX, y), col.u32, 1f)
}
return true
}
// comfortable util
val tabBarRef: PtrOrIndex?
get() = when (this) {
in g.tabBars -> PtrOrIndex(g.tabBars.getIndex(this))
else -> PtrOrIndex(this)
}
infix fun findTabByID(tabId: ID): TabItem? = when (tabId) {
0 -> null
else -> tabs.find { it.id == tabId }
}
/** The *TabId fields be already set by the docking system _before_ the actual TabItem was created, so we clear them regardless.
* ~ tabBarRemoveTab */
infix fun removeTab(tabId: ID) {
findTabByID(tabId)?.let(tabs::remove)
if (visibleTabId == tabId) visibleTabId = 0
if (selectedTabId == tabId) selectedTabId = 0
if (nextSelectedTabId == tabId) nextSelectedTabId = 0
}
/** Called on manual closure attempt
* ~ tabBarCloseTab */
fun closeTab(tab: TabItem) {
assert(tab.flags hasnt TabItemFlag._Button)
if (tab.flags hasnt TabItemFlag.UnsavedDocument) { // This will remove a frame of lag for selecting another tab on closure.
// However we don't run it in the case where the 'Unsaved' flag is set, so user gets a chance to fully undo the closure
tab.wantClose = true
if (visibleTabId == tab.id) {
tab.lastFrameVisible = -1
nextSelectedTabId = 0
selectedTabId = 0
}
} else // Actually select before expecting closure attempt (on an UnsavedDocument tab user is expect to e.g. show a popup)
if (visibleTabId != tab.id) nextSelectedTabId = tab.id
}
/** ~TabBarQueueReorder */
fun queueReorder(tab: TabItem, dir: Int) {
assert(dir == -1 || dir == +1)
assert(reorderRequestTabId == 0)
reorderRequestTabId = tab.id
reorderRequestDir = dir
}
/** ~TabBarProcessReorder */
fun processReorder(): Boolean {
val tab1 = findTabByID(reorderRequestTabId)
if (tab1 == null || tab1.flags has TabItemFlag.NoReorder) return false
//IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_Reorderable); // <- this may happen when using debug tools
val tab2Order = tab1.order + reorderRequestDir
if (tab2Order < 0 || tab2Order >= tabs.size) return false
// Reordered TabItem must share the same position flags than target
val tab2 = tabs[tab2Order]
if (tab2.flags has TabItemFlag.NoReorder) return false
if ((tab1.flags and (TabItemFlag.Leading or TabItemFlag.Trailing)) != (tab2.flags and (TabItemFlag.Leading or TabItemFlag.Trailing))) return false
// ImGuiTabItem* tab2 = &tab_bar->Tabs[tab2_order];
// ImGuiTabItem item_tmp = *tab1;
// *tab1 = *tab2;
// *tab2 = item_tmp;
val itemTmp = tabs[reorderRequestTabId]
tabs[reorderRequestTabId] = tabs[tab2Order]
tabs[tab2Order] = itemTmp
if (flags has TabBarFlag._SaveSettings) markIniSettingsDirty()
return true
}
fun tabItemEx(label: String, pOpen_: KMutableProperty0<Boolean>?, flags_: TabItemFlags): Boolean {
var pOpen = pOpen_
var flags = flags_ // Layout whole tab bar if not already done
if (wantLayout) layout()
val window = g.currentWindow!!
if (window.skipItems) return false
val id = calcTabID(label)
// If the user called us with *p_open == false, we early out and don't render.
// We make a call to ItemAdd() so that attempts to use a contextual popup menu with an implicit ID won't use an older ID.
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window.dc.lastItemStatusFlags)
if (pOpen?.get() == false) {
pushItemFlag(ItemFlag.NoNav or ItemFlag.NoNavDefaultFocus, true)
itemAdd(Rect(), id)
popItemFlag()
return false
}
assert(pOpen == null || flags hasnt TabItemFlag._Button)
assert((flags and (TabItemFlag.Leading or TabItemFlag.Trailing)) != (TabItemFlag.Leading or TabItemFlag.Trailing)) { "Can't use both Leading and Trailing" }
// Store into ImGuiTabItemFlags_NoCloseButton, also honor ImGuiTabItemFlags_NoCloseButton passed by user (although not documented)
if (flags has TabItemFlag._NoCloseButton) pOpen = null
else if (pOpen == null) flags = flags or TabItemFlag._NoCloseButton
// Calculate tab contents size
val size = tabItemCalcSize(label, pOpen != null)
// Acquire tab data
var tabIsNew = false
val tab = findTabByID(id) ?: TabItem().also {
it.id = id
it.width = size.x
tabs += it
tabIsNew = true
tabsAddedNew = true
}
lastTabItemIdx = tabs.indexOf(tab)
tab.contentWidth = size.x
tab.beginOrder = tabsActiveCount++
val tabBarAppearing = prevFrameVisible + 1 < g.frameCount
val tabBarFocused = this.flags has TabBarFlag._IsFocused
val tabAppearing = tab.lastFrameVisible + 1 < g.frameCount
val isTabButton = flags has TabItemFlag._Button
tab.lastFrameVisible = g.frameCount
tab.flags = flags
// Append name with zero-terminator
tab.nameOffset = tabsNames.size
tabsNames += label
// Update selected tab
if (tabAppearing && this.flags has TabBarFlag.AutoSelectNewTabs && nextSelectedTabId == 0) if (!tabBarAppearing || selectedTabId == 0) if (!isTabButton) nextSelectedTabId =
id // New tabs gets activated
if (flags has TabItemFlag.SetSelected && selectedTabId != id) // SetSelected can only be passed on explicit tab bar
if (!isTabButton) nextSelectedTabId = id
// Lock visibility
// (Note: tab_contents_visible != tab_selected... because CTRL+TAB operations may preview some tabs without selecting them!)
var tabContentsVisible = visibleTabId == id
if (tabContentsVisible) visibleTabWasSubmitted = true
// On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches
if (!tabContentsVisible && selectedTabId == 0 && tabBarAppearing) if (tabs.size == 1 && this.flags hasnt TabBarFlag.AutoSelectNewTabs) tabContentsVisible =
true
// Note that tab_is_new is not necessarily the same as tab_appearing! When a tab bar stops being submitted
// and then gets submitted again, the tabs will have 'tab_appearing=true' but 'tab_is_new=false'.
if (tabAppearing && (!tabBarAppearing || tabIsNew)) {
pushItemFlag(ItemFlag.NoNav or ItemFlag.NoNavDefaultFocus, true)
itemAdd(Rect(), id)
popItemFlag()
if (isTabButton) return false
return tabContentsVisible
}
if (selectedTabId == id) tab.lastFrameSelected = g.frameCount
// Backup current layout position
val backupMainCursorPos = Vec2(window.dc.cursorPos)
// Layout
val isCentralSection = tab.flags hasnt (TabItemFlag.Leading or TabItemFlag.Trailing)
size.x = tab.width
val x = if (isCentralSection) floor(tab.offset - scrollingAnim) else tab.offset
window.dc.cursorPos = barRect.min + Vec2(x, 0f)
val pos = Vec2(window.dc.cursorPos)
val bb = Rect(pos, pos + size)
// We don't have CPU clipping primitives to clip the CloseButton (until it becomes a texture), so need to add an extra draw call (temporary in the case of vertical animation)
val wantClipRect = isCentralSection && (bb.min.x < scrollingRectMinX || bb.max.x > scrollingRectMaxX)
if (wantClipRect)
pushClipRect(Vec2(bb.min.x max scrollingRectMinX, bb.min.y - 1), Vec2(scrollingRectMaxX, bb.max.y), true)
val backupCursorMaxPos = Vec2(window.dc.cursorMaxPos)
itemSize(bb.size, style.framePadding.y)
window.dc.cursorMaxPos = backupCursorMaxPos
if (!itemAdd(bb, id)) {
if (wantClipRect) popClipRect()
window.dc.cursorPos = backupMainCursorPos
return tabContentsVisible
}
// Click to Select a tab
var buttonFlags =
(if (isTabButton) ButtonFlag.PressedOnClickRelease else ButtonFlag.PressedOnClick) or ButtonFlag.AllowItemOverlap
if (g.dragDropActive) buttonFlags = buttonFlags or ButtonFlag.PressedOnDragDropHold
val (pressed, hovered_, held) = buttonBehavior(bb, id, buttonFlags)
if (pressed && !isTabButton) nextSelectedTabId = id
val hovered = hovered_ || g.hoveredId == id
// Allow the close button to overlap unless we are dragging (in which case we don't want any overlapping tabs to be hovered)
if (g.activeId != id)
setItemAllowOverlap()
// Drag and drop: re-order tabs
if (held && !tabAppearing && isMouseDragging(MouseButton.Left)) if (!g.dragDropActive && this.flags has TabBarFlag.Reorderable) // While moving a tab it will jump on the other side of the mouse, so we also test for MouseDelta.x
if (io.mouseDelta.x < 0f && io.mousePos.x < bb.min.x) {
if (this.flags has TabBarFlag.Reorderable) queueReorder(tab, -1)
} else if (io.mouseDelta.x > 0f && io.mousePos.x > bb.max.x) if (this.flags has TabBarFlag.Reorderable) queueReorder(
tab,
+1
)
// if (false)
// if (hovered && g.hoveredIdNotActiveTimer > TOOLTIP_DELAY && bb.width < tab.widthContents) {
// // Enlarge tab display when hovering
// bb.max.x = bb.min.x + lerp (bb.width, tab.widthContents, saturate((g.hoveredIdNotActiveTimer-0.4f) * 6f)).i.f
// displayDrawList = GetOverlayDrawList(window)
// TabItemBackground(display_draw_list, bb, flags, GetColorU32(ImGuiCol_TitleBgActive))
// }
// Render tab shape
val displayDrawList = window.drawList
val tabCol = when {
held || hovered -> Col.TabHovered
else -> when {
tabContentsVisible -> when {
tabBarFocused -> Col.TabActive
else -> Col.TabUnfocusedActive
}
else -> when {
tabBarFocused -> Col.Tab
else -> Col.TabUnfocused
}
}
}
tabItemBackground(displayDrawList, bb, flags, tabCol.u32)
renderNavHighlight(bb, id)
// Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget.
val hoveredUnblocked = isItemHovered(HoveredFlag.AllowWhenBlockedByPopup)
if (hoveredUnblocked && (isMouseClicked(MouseButton.Right) || isMouseReleased(MouseButton.Right))) if (!isTabButton) nextSelectedTabId =
id
if (this.flags has TabBarFlag.NoCloseWithMiddleMouseButton) flags =
flags or TabItemFlag.NoCloseWithMiddleMouseButton
// Render tab label, process close button
val closeButtonId = if (pOpen?.get() == true) getIDWithSeed("#CLOSE", -1, id) else 0
val (justClosed, textClipped) = tabItemLabelAndCloseButton(displayDrawList, bb, flags, framePadding,
label.toByteArray(), id, closeButtonId, tabContentsVisible)
if (justClosed && pOpen != null) {
pOpen.set(false)
closeTab(tab)
}
// Restore main window position so user can draw there
if (wantClipRect) popClipRect()
window.dc.cursorPos = backupMainCursorPos
// Tooltip (FIXME: Won't work over the close button because ItemOverlap systems messes up with HoveredIdTimer)
// We test IsItemHovered() to discard e.g. when another item is active or drag and drop over the tab bar (which g.HoveredId ignores)
if (textClipped && g.hoveredId == id && !held && g.hoveredIdNotActiveTimer > g.tooltipSlowDelay && isItemHovered())
if (this.flags hasnt TabBarFlag.NoTooltip && tab.flags hasnt TabItemFlag.NoTooltip)
setTooltip(label.substring(0, findRenderedTextEnd(label)))
assert(!isTabButton || !(selectedTabId == tab.id && isTabButton)) { "TabItemButton should not be selected" }
return if (isTabButton) pressed else tabContentsVisible
}
/** This is called only once a frame before by the first call to ItemTab()
* The reason we're not calling it in BeginTabBar() is to leave a chance to the user to call the SetTabItemClosed() functions.
* ~ TabBarLayout */
fun layout() {
wantLayout = false
// Garbage collect by compacting list
// Detect if we need to sort out tab list (e.g. in rare case where a tab changed section)
var tabDstN = 0
var needSortBySection = false
val sections = Array(3) { TabBarSection() } // Layout sections: Leading, Central, Trailing
for (tabSrcN in tabs.indices) {
val tab = tabs[tabSrcN]
if (tab.lastFrameVisible < prevFrameVisible || tab.wantClose) {
// Remove tab
if (visibleTabId == tab.id) visibleTabId = 0
if (selectedTabId == tab.id) selectedTabId = 0
if (nextSelectedTabId == tab.id) nextSelectedTabId = 0
continue
}
if (tabDstN != tabSrcN)
tabs[tabDstN] = tabs[tabSrcN]
// We will need sorting if tabs have changed section (e.g. moved from one of Leading/Central/Trailing to another)
val currTabSectionN =
if (tab.flags has TabItemFlag.Leading) 0 else if (tab.flags has TabItemFlag.Trailing) 2 else 1
if (tabDstN > 0) {
val prevTab = tabs[tabDstN - 1]
val prevTabSectionN =
if (prevTab.flags has TabItemFlag.Leading) 0 else if (prevTab.flags has TabItemFlag.Trailing) 2 else 1
if (currTabSectionN == 0 && prevTabSectionN != 0)
needSortBySection = true
if (prevTabSectionN == 2 && currTabSectionN != 2)
needSortBySection = true
}
sections[currTabSectionN].tabCount++
tabDstN++
}
if (tabs.size != tabDstN)
for (i in tabDstN until tabs.size)
tabs.pop()
if (needSortBySection)
tabs.sortWith(tabItemComparerBySection)
// Calculate spacing between sections
sections[0].spacing =
if (sections[0].tabCount > 0 && sections[1].tabCount + sections[2].tabCount > 0) g.style.itemInnerSpacing.x else 0f
sections[1].spacing =
if (sections[1].tabCount > 0 && sections[2].tabCount > 0) g.style.itemInnerSpacing.x else 0f
// Setup next selected tab
var scrollTrackSelectedTabID: ID = 0
if (nextSelectedTabId != 0) {
selectedTabId = nextSelectedTabId
nextSelectedTabId = 0
scrollTrackSelectedTabID = selectedTabId
}
// Process order change request (we could probably process it when requested but it's just saner to do it in a single spot).
if (reorderRequestTabId != 0) {
if (processReorder() && reorderRequestTabId == selectedTabId)
scrollTrackSelectedTabID = reorderRequestTabId
reorderRequestTabId = 0
}
// Tab List Popup
val tabListPopupButton = flags has TabBarFlag.TabListPopupButton
if (tabListPopupButton) tabListPopupButton()?.let { tabToSelect -> // NB: Will alter BarRect.Min.x!
selectedTabId = tabToSelect.id
scrollTrackSelectedTabID = tabToSelect.id
}
// Leading/Trailing tabs will be shrink only if central one aren't visible anymore, so layout the shrink data as: leading, trailing, central
// (whereas our tabs are stored as: leading, central, trailing)
val shrinkBufferIndexes = intArrayOf(0, sections[0].tabCount + sections[2].tabCount, sections[0].tabCount)
g.shrinkWidthBuffer.clear() // [JVM] it will automatically resized in the following for loop
for (i in tabs.indices)
g.shrinkWidthBuffer += ShrinkWidthItem()
// Compute ideal tabs widths + store them into shrink buffer
var mostRecentlySelectedTab: TabItem? = null
var currSectionN = -1
var foundSelectedTabID = false
for (tabN in tabs.indices) {
val tab = tabs[tabN]
assert(tab.lastFrameVisible >= prevFrameVisible)
if ((mostRecentlySelectedTab == null || mostRecentlySelectedTab.lastFrameSelected < tab.lastFrameSelected) && tab.flags hasnt TabItemFlag._Button)
mostRecentlySelectedTab = tab
if (tab.id == selectedTabId) foundSelectedTabID = true
if (scrollTrackSelectedTabID == 0 && g.navJustMovedToId == tab.id)
scrollTrackSelectedTabID = tab.id
// Refresh tab width immediately, otherwise changes of style e.g. style.FramePadding.x would noticeably lag in the tab bar.
// Additionally, when using TabBarAddTab() to manipulate tab bar order we occasionally insert new tabs that don't have a width yet,
// and we cannot wait for the next BeginTabItem() call. We cannot compute this width within TabBarAddTab() because font size depends on the active window.
val hasCloseButton = tab.flags hasnt TabItemFlag._NoCloseButton
tab.contentWidth = tabItemCalcSize(tab.name, hasCloseButton).x
val sectionN =
if (tab.flags has TabItemFlag.Leading) 0 else if (tab.flags has TabItemFlag.Trailing) 2 else 1
val section = sections[sectionN]
section.width += tab.contentWidth + if (sectionN == currSectionN) g.style.itemInnerSpacing.x else 0f
currSectionN = sectionN
// Store data so we can build an array sorted by width if we need to shrink tabs down
g.shrinkWidthBuffer[shrinkBufferIndexes[sectionN]++].apply {
index = tabN
width = tab.contentWidth
}
assert(tab.contentWidth > 0f)
tab.width = tab.contentWidth
}
// Compute total ideal width (used for e.g. auto-resizing a window)
widthAllTabsIdeal = 0f
for (section in sections)
widthAllTabsIdeal += section.width + section.spacing
// Horizontal scrolling buttons
// (note that TabBarScrollButtons() will alter BarRect.Max.x)
if ((widthAllTabsIdeal > barRect.width && tabs.size > 1) && flags hasnt TabBarFlag.NoTabListScrollingButtons && flags has TabBarFlag.FittingPolicyScroll)
scrollingButtons()?.let { scrollTrackSelectedTab ->
scrollTrackSelectedTabID = scrollTrackSelectedTab.id
if (scrollTrackSelectedTab.flags hasnt TabItemFlag._Button)
selectedTabId = scrollTrackSelectedTabID
}
// Shrink widths if full tabs don't fit in their allocated space
val section0W = sections[0].width + sections[0].spacing
val section1W = sections[1].width + sections[1].spacing
val section2W = sections[2].width + sections[2].spacing
val centralSectionIsVisible = section0W + section2W < barRect.width
val widthExcess = when {
centralSectionIsVisible -> (section1W - (barRect.width - section0W - section2W)) max 0f // Excess used to shrink central section
else -> section0W + section2W - barRect.width // Excess used to shrink leading/trailing section
}
// With ImGuiTabBarFlags_FittingPolicyScroll policy, we will only shrink leading/trailing if the central section is not visible anymore
if (widthExcess > 0f && (flags has TabBarFlag.FittingPolicyResizeDown || !centralSectionIsVisible)) {
val shrinkDataCount =
if (centralSectionIsVisible) sections[1].tabCount else sections[0].tabCount + sections[2].tabCount
val shrinkDataOffset = if (centralSectionIsVisible) sections[0].tabCount + sections[2].tabCount else 0
shrinkWidths(g.shrinkWidthBuffer, shrinkDataOffset, shrinkDataCount, widthExcess)
// Apply shrunk values into tabs and sections
for (tabN in shrinkDataOffset until shrinkDataOffset + shrinkDataCount) {
val tab = tabs[g.shrinkWidthBuffer[tabN].index]
val shrinkedWidth = floor(g.shrinkWidthBuffer[tabN].width)
if (shrinkedWidth < 0f)
continue
val sectionN =
if (tab.flags has TabItemFlag.Leading) 0 else if (tab.flags has TabItemFlag.Trailing) 2 else 1
sections[sectionN].width -= tab.width - shrinkedWidth
tab.width = shrinkedWidth
}
}
// Layout all active tabs
var sectionTabIndex = 0
var tabOffset = 0f
widthAllTabs = 0f
for (sectionN in 0..2) {
val section = sections[sectionN]
if (sectionN == 2)
tabOffset = min(max(0f, barRect.width - section.width), tabOffset)
for (tabN in 0 until section.tabCount) {
val tab = tabs[sectionTabIndex + tabN]
tab.offset = tabOffset
tabOffset += tab.width + if (tabN < section.tabCount - 1) g.style.itemInnerSpacing.x else 0f
}
widthAllTabs += (section.width + section.spacing) max 0f
tabOffset += section.spacing
sectionTabIndex += section.tabCount
}
// If we have lost the selected tab, select the next most recently active one
if (!foundSelectedTabID) selectedTabId = 0
if (selectedTabId == 0 && nextSelectedTabId == 0)
mostRecentlySelectedTab?.let {
selectedTabId = it.id
scrollTrackSelectedTabID = selectedTabId
}
// Lock in visible tab
visibleTabId = selectedTabId
visibleTabWasSubmitted = false
// Update scrolling
if (scrollTrackSelectedTabID != 0)
findTabByID(scrollTrackSelectedTabID)?.let { scrollToTab(it, sections) }
scrollingAnim = scrollClamp(scrollingAnim)
scrollingTarget = scrollClamp(scrollingTarget)
if (scrollingAnim != scrollingTarget) { // Scrolling speed adjust itself so we can always reach our target in 1/3 seconds.
// Teleport if we are aiming far off the visible line
scrollingSpeed = scrollingSpeed max (70f * g.fontSize)
scrollingSpeed = scrollingSpeed max (abs(scrollingTarget - scrollingAnim) / 0.3f)
val teleport = prevFrameVisible + 1 < g.frameCount || scrollingTargetDistToVisibility > 10f * g.fontSize
scrollingAnim = if (teleport) scrollingTarget else linearSweep(
scrollingAnim,
scrollingTarget,
io.deltaTime * scrollingSpeed
)
} else scrollingSpeed = 0f
scrollingRectMinX = barRect.min.x + sections[0].width + sections[0].spacing
scrollingRectMaxX = barRect.max.x - sections[2].width - sections[1].spacing
// Clear name buffers
if (flags hasnt TabBarFlag._DockNode) tabsNames.clear()
// Actual layout in host window (we don't do it in BeginTabBar() so as not to waste an extra frame)
val window = g.currentWindow!!
window.dc.cursorPos put barRect.min
itemSize(Vec2(widthAllTabs, barRect.height), framePadding.y)
window.dc.idealMaxPos.x = window.dc.idealMaxPos.x max (barRect.min.x + widthAllTabsIdeal)
}
/** Dockables uses Name/ID in the global namespace. Non-dockable items use the ID stack.
* ~ TabBarCalcTabID */
infix fun calcTabID(label: String): Int {
return when {
flags has TabBarFlag._DockNode -> {
val id = hashStr(label)
keepAliveID(id)
id
}
else -> g.currentWindow!!.getID(label)
}
}
/** ~TabBarScrollClamp */
fun scrollClamp(scrolling: Float): Float = (scrolling min (widthAllTabs - barRect.width)) max 0f
/** ~TabBarScrollToTab */
fun scrollToTab(tab: TabItem, sections: Array<TabBarSection>) {
if (tab.flags has (TabItemFlag.Leading or TabItemFlag.Trailing)) return
val margin =
g.fontSize * 1f // When to scroll to make Tab N+1 visible always make a bit of N visible to suggest more scrolling area (since we don't have a scrollbar)
val order = tab.order
// Scrolling happens only in the central section (leading/trailing sections are not scrolling)
// FIXME: This is all confusing.
val scrollableWidth = barRect.width - sections[0].width - sections[2].width - sections[1].spacing
// We make all tabs positions all relative Sections[0].Width to make code simpler
val tabX1 = tab.offset - sections[0].width + if (order > sections[0].tabCount - 1) -margin else 0f
val tabX2 =
tab.offset - sections[0].width + tab.width + if (order + 1 < tabs.size - sections[2].tabCount) margin else 1f
scrollingTargetDistToVisibility = 0f
if (scrollingTarget > tabX1 || (tabX2 - tabX1 >= scrollableWidth)) {
// Scroll to the left
scrollingTargetDistToVisibility = (scrollingAnim - tabX2) max 0f
scrollingTarget = tabX1
} else if (scrollingTarget < tabX2 - scrollableWidth) {
// Scroll to the right
scrollingTargetDistToVisibility = ((tabX1 - scrollableWidth) - scrollingAnim) max 0f
scrollingTarget = tabX2 - scrollableWidth
}
}
/** ~ TabBarScrollingButtons */
fun scrollingButtons(): TabItem? {
val window = g.currentWindow!!
val arrowButtonSize = Vec2(g.fontSize - 2f, g.fontSize + g.style.framePadding.y * 2f)
val scrollingButtonsWidth = arrowButtonSize.x * 2f
val backupCursorPos = Vec2(window.dc.cursorPos)
//window->DrawList->AddRect(ImVec2(tab_bar->BarRect.Max.x - scrolling_buttons_width, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Max.x, tab_bar->BarRect.Max.y), IM_COL32(255,0,0,255));
var selectDir = 0
val arrowCol = Vec4(style.colors[Col.Text])
arrowCol.w *= 0.5f
pushStyleColor(Col.Text, arrowCol)
pushStyleColor(Col.Button, Vec4(0f))
val backupRepeatDelay = io.keyRepeatDelay
val backupRepeatRate = io.keyRepeatRate
io.keyRepeatDelay = 0.25f
io.keyRepeatRate = 0.2f
val x = barRect.min.x max (barRect.max.x - scrollingButtonsWidth)
window.dc.cursorPos.put(x, barRect.min.y)
if (arrowButtonEx("##<", Dir.Left, arrowButtonSize, ButtonFlag.PressedOnClick or ButtonFlag.Repeat)) selectDir =
-1
window.dc.cursorPos.put(x + arrowButtonSize.x, barRect.min.y)
if (arrowButtonEx(
"##>",
Dir.Right,
arrowButtonSize,
ButtonFlag.PressedOnClick or ButtonFlag.Repeat
)
) selectDir = +1
popStyleColor(2)
io.keyRepeatRate = backupRepeatRate
io.keyRepeatDelay = backupRepeatDelay
var tabToScrollTo: TabItem? = null
if (selectDir != 0) findTabByID(selectedTabId)?.let { tabItem ->
var selectedOrder = tabItem.order
var targetOrder = selectedOrder + selectDir
// Skip tab item buttons until another tab item is found or end is reached
while (tabToScrollTo == null) { // If we are at the end of the list, still scroll to make our tab visible
tabToScrollTo = tabs[if (targetOrder in tabs.indices) targetOrder else selectedOrder]
// Cross through buttons
// (even if first/last item is a button, return it so we can update the scroll)
if (tabToScrollTo!!.flags has TabItemFlag._Button) {
targetOrder += selectDir
selectedOrder += selectDir
tabToScrollTo = if (targetOrder < 0 || targetOrder >= tabs.size) tabToScrollTo else null
}
}
}
window.dc.cursorPos put backupCursorPos
barRect.max.x -= scrollingButtonsWidth + 1f
return tabToScrollTo
}
/** ~TabBarTabListPopupButton */
fun tabListPopupButton(): TabItem? {
val window = g.currentWindow!!
// We use g.Style.FramePadding.y to match the square ArrowButton size
val tabListPopupButtonWidth = g.fontSize + style.framePadding.y * 2f
val backupCursorPos = Vec2(window.dc.cursorPos)
window.dc.cursorPos.put(barRect.min.x - style.framePadding.y, barRect.min.y)
barRect.min.x += tabListPopupButtonWidth
val arrowCol = Vec4(style.colors[Col.Text])
arrowCol.w *= 0.5f
pushStyleColor(Col.Text, arrowCol)
pushStyleColor(Col.Button, Vec4())
val open = beginCombo("##v", null, ComboFlag.NoPreview or ComboFlag.HeightLargest)
popStyleColor(2)
var tabToSelect: TabItem? = null
if (open) {
for (tab in tabs) {
if (tab.flags has TabItemFlag._Button) continue
if (selectable(tab.name, selectedTabId == id)) tabToSelect = tab
}
endCombo()
}
window.dc.cursorPos = backupCursorPos
return tabToSelect
}
companion object {
fun calcMaxTabWidth() = g.fontSize * 20f
val tabItemComparerBySection = Comparator<TabItem> { a, b ->
val aSection = if (a.flags has TabItemFlag.Leading) 0 else if (a.flags has TabItemFlag.Trailing) 2 else 1
val bSection = if (b.flags has TabItemFlag.Leading) 0 else if (b.flags has TabItemFlag.Trailing) 2 else 1
if (aSection != bSection) aSection - bSection
else a.indexDuringLayout - b.indexDuringLayout
}
}
}
| mit | e7a651597820c44c3ec52bea78b0a41e | 42.987879 | 235 | 0.638303 | 4.238496 | false | false | false | false |
wbrawner/SimpleMarkdown | app/src/main/java/com/wbrawner/simplemarkdown/view/fragment/MarkdownInfoFragment.kt | 1 | 3260 | package com.wbrawner.simplemarkdown.view.fragment
import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatDelegate
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.setupWithNavController
import com.wbrawner.plausible.android.Plausible
import com.wbrawner.simplemarkdown.R
import com.wbrawner.simplemarkdown.utility.*
import kotlinx.android.synthetic.main.fragment_markdown_info.*
import kotlinx.coroutines.launch
class MarkdownInfoFragment : Fragment() {
private val errorHandler: ErrorHandler by errorHandlerImpl()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.fragment_markdown_info, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val fileName = arguments?.getString(EXTRA_FILE)
if (fileName.isNullOrBlank()) {
findNavController().navigateUp()
return
}
toolbar.setupWithNavController(findNavController())
val isNightMode = AppCompatDelegate.getDefaultNightMode() ==
AppCompatDelegate.MODE_NIGHT_YES
|| resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
val defaultCssId = if (isNightMode) {
R.string.pref_custom_css_default_dark
} else {
R.string.pref_custom_css_default
}
val css: String? = getString(defaultCssId)
lifecycleScope.launch {
try {
val html = view.context.assets?.readAssetToString(fileName)
?.toHtml()
?: throw RuntimeException("Unable to open stream to $fileName")
infoWebview.loadDataWithBaseURL(null,
String.format(FORMAT_CSS, css) + html,
"text/html",
"UTF-8", null
)
} catch (e: Exception) {
errorHandler.reportException(e)
Toast.makeText(view.context, R.string.file_load_error, Toast.LENGTH_SHORT).show()
findNavController().navigateUp()
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
findNavController().navigateUp()
return true
}
return super.onOptionsItemSelected(item)
}
override fun onStart() {
super.onStart()
arguments?.getString(EXTRA_FILE)?.let {
Plausible.pageView(it)
}
}
companion object {
const val FORMAT_CSS = "<style>" +
"%s" +
"</style>"
const val EXTRA_TITLE = "title"
const val EXTRA_FILE = "file"
}
}
| apache-2.0 | c55124b8aefa84789efa82922ace39ad | 35.629213 | 121 | 0.643558 | 4.872945 | false | false | false | false |
Ztiany/Repository | Kotlin/Kotlin-Coroutines/src/main/kotlin/core/select/01_SelectingFromChannels.kt | 2 | 1655 | package core.select
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.selects.select
/*
select 表达式可以同时等待多个挂起函数,并选择 第一个可用的。(这个有点类似于 NIO 中的 Selector)
在通道中 select,使用 receive 挂起函数,我们可以从两个通道接收 其中一个 的数据。 但是 select 表达式允许我们使用其 onReceive 子句 同时 从两者接收
*/
private fun CoroutineScope.fizz() = produce<String> {
while (true) { // sends "Fizz" every 300 ms
delay(300)
send("Fizz")
}
}
private fun CoroutineScope.buzz() = produce<String> {
while (true) { // sends "Buzz!" every 500 ms
delay(500)
send("Buzz!")
}
}
private suspend fun selectFizzBuzz(fizz: ReceiveChannel<String>, buzz: ReceiveChannel<String>) {
select<Unit> {
// <Unit> means that this select expression does not produce any result
fizz.onReceive { value ->
// this is the first select clause
println("fizz -> '$value'")
}
buzz.onReceive { value ->
// this is the second select clause
println("buzz -> '$value'")
}
}
}
fun main() = runBlocking<Unit> {
//sampleStart
val fizz = fizz()
val buzz = buzz()
repeat(7) {
selectFizzBuzz(fizz, buzz)
}
coroutineContext.cancelChildren() // cancel fizz & buzz coroutines
//sampleEnd
} | apache-2.0 | 1c7973a4cf60241a7b9ce18e4526f21d | 26.886792 | 96 | 0.664861 | 3.777494 | false | false | false | false |
Ztiany/Repository | Kotlin/Kotlin-Coroutines/src/main/kotlin/core/concurrency/02_Volatiles.kt | 2 | 918 | package core.concurrency
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlin.system.measureTimeMillis
/**
* 对于这种问题,volatile 并不能帮助我们。
*/
private suspend fun CoroutineScope.massiveRun(action: suspend () -> Unit) {
val n = 100 // number of coroutines to launch
val k = 1000 // times an action is repeated by each coroutine
val time = measureTimeMillis {
val jobs = List(n) {
launch {
repeat(k) { action() }
}
}
jobs.forEach { it.join() }
}
println("Completed ${n * k} actions in $time ms")
}
@Volatile // in Kotlin `volatile` is an annotation
private var counter = 0
fun main() = runBlocking<Unit> {
GlobalScope.massiveRun {
counter++
}
println("Counter = $counter")
} | apache-2.0 | af45c813a691fceec37e77ebac7b3fc5 | 25.147059 | 75 | 0.654279 | 4.149533 | false | false | false | false |
lare96/luna | plugins/world/player/skill/crafting/battlestaffCrafting/MakeBattlestaffAction.kt | 1 | 1200 | package world.player.skill.crafting.battlestaffCrafting
import api.predef.*
import io.luna.game.action.Action
import io.luna.game.action.InventoryAction
import io.luna.game.model.mob.Player
import world.player.skill.crafting.battlestaffCrafting.Battlestaff.Companion.BATTLESTAFF_ITEM
/**
* An [InventoryAction] implementation that makes battlestaves.
*/
class MakeBattlestaffAction(val plr: Player, val battlestaff: Battlestaff, amount: Int) :
InventoryAction(plr, true, 2, amount) {
override fun executeIf(start: Boolean): Boolean =
when {
mob.crafting.level < battlestaff.level -> {
plr.sendMessage("You need a Crafting level of ${battlestaff.level} to make this.")
false
}
else -> true
}
override fun execute() {
mob.crafting.addExperience(battlestaff.exp)
}
override fun add() = listOf(battlestaff.staffItem)
override fun remove() = listOf(battlestaff.orbItem, BATTLESTAFF_ITEM)
override fun ignoreIf(other: Action<*>?): Boolean =
when (other) {
is MakeBattlestaffAction -> battlestaff == other.battlestaff
else -> false
}
} | mit | 9022a6ba979e41931de5b9c6b837999b | 32.361111 | 98 | 0.670833 | 4.081633 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/task/twitter/message/SendMessageTask.kt | 1 | 11680 | /*
* 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.task.twitter.message
import android.content.Context
import org.mariotaku.ktextension.isNotNullOrEmpty
import de.vanita5.microblog.library.MicroBlog
import de.vanita5.microblog.library.MicroBlogException
import de.vanita5.microblog.library.twitter.TwitterUpload
import de.vanita5.microblog.library.twitter.annotation.MediaCategory
import de.vanita5.microblog.library.twitter.model.DirectMessage
import de.vanita5.microblog.library.twitter.model.NewDm
import org.mariotaku.sqliteqb.library.Expression
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.annotation.AccountType
import de.vanita5.twittnuker.extension.model.api.*
import de.vanita5.twittnuker.extension.model.isOfficial
import de.vanita5.twittnuker.extension.model.newMicroBlogInstance
import de.vanita5.twittnuker.model.AccountDetails
import de.vanita5.twittnuker.model.ParcelableMedia
import de.vanita5.twittnuker.model.ParcelableMessageConversation
import de.vanita5.twittnuker.model.ParcelableNewMessage
import de.vanita5.twittnuker.model.event.SendMessageTaskEvent
import de.vanita5.twittnuker.model.util.ParcelableMessageUtils
import de.vanita5.twittnuker.provider.TwidereDataStore.Messages.Conversations
import de.vanita5.twittnuker.task.ExceptionHandlingAbstractTask
import de.vanita5.twittnuker.task.twitter.UpdateStatusTask
import de.vanita5.twittnuker.task.twitter.message.GetMessagesTask
import de.vanita5.twittnuker.task.twitter.message.GetMessagesTask.Companion.addConversation
import de.vanita5.twittnuker.task.twitter.message.GetMessagesTask.Companion.addLocalConversations
class SendMessageTask(
context: Context
) : ExceptionHandlingAbstractTask<ParcelableNewMessage, SendMessageTask.SendMessageResult,
MicroBlogException, Unit>(context) {
private val profileImageSize = context.getString(R.string.profile_image_size)
override val exceptionClass = MicroBlogException::class.java
override fun onExecute(params: ParcelableNewMessage): SendMessageResult {
val account = params.account ?: throw MicroBlogException("No account")
val microBlog = account.newMicroBlogInstance(context, cls = MicroBlog::class.java)
val updateData = requestSendMessage(microBlog, account, params)
if (params.is_temp_conversation && params.conversation_id != null) {
val deleteTempWhere = Expression.and(Expression.equalsArgs(Conversations.ACCOUNT_KEY),
Expression.equalsArgs(Conversations.CONVERSATION_ID)).sql
val deleteTempWhereArgs = arrayOf(account.key.toString(), params.conversation_id)
context.contentResolver.delete(Conversations.CONTENT_URI, deleteTempWhere,
deleteTempWhereArgs)
}
GetMessagesTask.storeMessages(context, updateData, account)
return SendMessageResult(updateData.conversations.map { it.id })
}
override fun onException(callback: Unit?, exception: MicroBlogException) {
bus.post(SendMessageTaskEvent(params.account.key, params.conversation_id, null, false))
}
override fun onSucceed(callback: Unit?, result: SendMessageResult) {
bus.post(SendMessageTaskEvent(params.account.key, params.conversation_id,
result.conversationIds.singleOrNull(), true))
}
private fun requestSendMessage(microBlog: MicroBlog, account: AccountDetails,
message: ParcelableNewMessage): GetMessagesTask.DatabaseUpdateData {
when (account.type) {
AccountType.TWITTER -> {
if (account.isOfficial(context)) {
return sendTwitterOfficialDM(microBlog, account, message)
} else {
return sendTwitterMessageEvent(microBlog, account, message)
}
}
AccountType.FANFOU -> {
return sendFanfouDM(microBlog, account, message)
}
}
return sendDefaultDM(microBlog, account, message)
}
private fun sendTwitterOfficialDM(microBlog: MicroBlog, account: AccountDetails,
message: ParcelableNewMessage): GetMessagesTask.DatabaseUpdateData {
var deleteOnSuccess: List<UpdateStatusTask.MediaDeletionItem>? = null
var deleteAlways: List<UpdateStatusTask.MediaDeletionItem>? = null
val sendResponse = try {
val conversationId = message.conversation_id
val tempConversation = message.is_temp_conversation
val newDm = NewDm()
if (!tempConversation && conversationId != null) {
newDm.setConversationId(conversationId)
} else {
newDm.setRecipientIds(message.recipient_ids)
}
newDm.setText(message.text)
if (message.media.isNotNullOrEmpty()) {
val upload = account.newMicroBlogInstance(context, cls = TwitterUpload::class.java)
val uploadResult = UpdateStatusTask.uploadMicroBlogMediaShared(context,
upload, account, message.media, null, null, true, null)
newDm.setMediaId(uploadResult.ids[0])
deleteAlways = uploadResult.deleteAlways
deleteOnSuccess = uploadResult.deleteOnSuccess
}
microBlog.sendDm(newDm)
} catch (e: UpdateStatusTask.UploadException) {
e.deleteAlways?.forEach {
it.delete(context)
}
throw MicroBlogException(e)
} finally {
deleteAlways?.forEach { it.delete(context) }
}
deleteOnSuccess?.forEach { it.delete(context) }
val conversationId = sendResponse.entries?.firstOrNull {
it.message != null
}?.message?.conversationId
val response = microBlog.getDmConversation(conversationId, null).conversationTimeline
return GetMessagesTask.createDatabaseUpdateData(context, account, response, profileImageSize)
}
private fun sendTwitterMessageEvent(microBlog: MicroBlog, account: AccountDetails,
message: ParcelableNewMessage): GetMessagesTask.DatabaseUpdateData {
val recipientId = message.recipient_ids.singleOrNull() ?: throw MicroBlogException("No recipient")
val category = when (message.media?.firstOrNull()?.type) {
ParcelableMedia.Type.IMAGE -> MediaCategory.DM_IMAGE
ParcelableMedia.Type.VIDEO -> MediaCategory.DM_VIDEO
ParcelableMedia.Type.ANIMATED_GIF -> MediaCategory.DM_GIF
else -> null
}
val response = uploadMediaThen(account, message, category) { mediaId ->
val obj = DirectMessageEventObject {
type = "message_create"
messageCreate {
target { this.recipientId = recipientId }
messageData {
text = message.text
if (mediaId != null) {
attachment {
type = "media"
media {
id = mediaId
}
}
}
}
}
}
return@uploadMediaThen microBlog.newDirectMessageEvent(obj)
}
return createDatabaseUpdateData(account, microBlog.showDirectMessage(response.event.id))
}
private fun sendFanfouDM(microBlog: MicroBlog, account: AccountDetails, message: ParcelableNewMessage): GetMessagesTask.DatabaseUpdateData {
val recipientId = message.recipient_ids.singleOrNull() ?: throw MicroBlogException("No recipient")
val response = microBlog.sendFanfouDirectMessage(recipientId, message.text)
return createDatabaseUpdateData(account, response)
}
private fun sendDefaultDM(microBlog: MicroBlog, account: AccountDetails, message: ParcelableNewMessage): GetMessagesTask.DatabaseUpdateData {
val recipientId = message.recipient_ids.singleOrNull() ?: throw MicroBlogException("No recipient")
val response = uploadMediaThen(account, message) { mediaId ->
if (mediaId != null) {
microBlog.sendDirectMessage(recipientId, message.text, mediaId)
} else {
microBlog.sendDirectMessage(recipientId, message.text)
}
}
return createDatabaseUpdateData(account, response)
}
private fun <T> uploadMediaThen(account: AccountDetails, message: ParcelableNewMessage,
category: String? = null, action: (mediaId: String?) -> T): T {
var deleteOnSuccess: List<UpdateStatusTask.MediaDeletionItem>? = null
var deleteAlways: List<UpdateStatusTask.MediaDeletionItem>? = null
try {
var mediaId: String? = null
if (message.media.isNotNullOrEmpty()) {
val upload = account.newMicroBlogInstance(context, cls = TwitterUpload::class.java)
val uploadResult = UpdateStatusTask.uploadMicroBlogMediaShared(context,
upload, account, message.media, category, null, true, null)
mediaId = uploadResult.ids[0]
deleteAlways = uploadResult.deleteAlways
deleteOnSuccess = uploadResult.deleteOnSuccess
}
val result = action(mediaId)
deleteOnSuccess?.forEach { it.delete(context) }
return result
} catch (e: UpdateStatusTask.UploadException) {
e.deleteAlways?.forEach {
it.delete(context)
}
throw MicroBlogException(e)
} finally {
deleteAlways?.forEach { it.delete(context) }
}
}
private fun createDatabaseUpdateData(details: AccountDetails, dm: DirectMessage): GetMessagesTask.DatabaseUpdateData {
val accountKey = details.key
val conversationIds = setOf(ParcelableMessageUtils.outgoingConversationId(dm.senderId, dm.recipientId))
val conversations = hashMapOf<String, ParcelableMessageConversation>()
conversations.addLocalConversations(context, accountKey, conversationIds)
val message = ParcelableMessageUtils.fromMessage(accountKey, dm, true)
val sender = dm.sender.toParcelable(details, profileImageSize = profileImageSize)
val recipient = dm.recipient.toParcelable(details, profileImageSize = profileImageSize)
conversations.addConversation(message.conversation_id, details, message, setOf(sender, recipient), appendUsers = true)
return GetMessagesTask.DatabaseUpdateData(conversations.values, listOf(message))
}
class SendMessageResult(var conversationIds: List<String>)
companion object {
const val TEMP_CONVERSATION_ID_PREFIX = "twittnuker:temp:"
}
} | gpl-3.0 | 45ae8cf5870090c9f27c8e1ecdc6f5fe | 48.28692 | 145 | 0.682192 | 5.045356 | false | false | false | false |
stripe/stripe-android | payments-core/src/main/java/com/stripe/android/model/LuxeActionCreatorForStatus.kt | 1 | 2792 | package com.stripe.android.model
import android.net.Uri
import org.json.JSONObject
internal data class LuxeActionCreatorForStatus(
val status: StripeIntent.Status,
val actionCreator: ActionCreator
) {
internal sealed class ActionCreator {
fun create(stripeIntentJsonString: String) =
create(JSONObject(stripeIntentJsonString))
internal abstract fun create(stripeIntentJson: JSONObject): LuxeNextActionRepository.Result
internal data class RedirectActionCreator(
val redirectPagePath: String,
val returnToUrlPath: String
) : ActionCreator() {
override fun create(stripeIntentJson: JSONObject): LuxeNextActionRepository.Result {
val returnUrl = getPath(returnToUrlPath, stripeIntentJson)
val url = getPath(redirectPagePath, stripeIntentJson)
return if ((returnUrl != null) && (url != null)
) {
LuxeNextActionRepository.Result.Action(
StripeIntent.NextActionData.RedirectToUrl(
returnUrl = returnUrl,
url = Uri.parse(url)
)
)
} else {
LuxeNextActionRepository.Result.NotSupported
}
}
}
object NoActionCreator : ActionCreator() {
override fun create(stripeIntentJson: JSONObject) =
LuxeNextActionRepository.Result.NoAction
}
}
internal companion object {
/**
* This function will take a path string like: next_action\[redirect]\[url] and
* find that key path in the json object.
*/
internal fun getPath(path: String?, json: JSONObject): String? {
if (path == null) {
return null
}
val pathArray = ("[*" + "([A-Za-z_0-9]+)" + "]*").toRegex().findAll(path)
.map { it.value }
.distinct()
.filterNot { it.isEmpty() }
.toList()
var jsonObject: JSONObject? = json
var pathIndex = 0
while (pathIndex < pathArray.size &&
jsonObject != null &&
jsonObject.opt(pathArray[pathIndex]) !is String
) {
val key = pathArray[pathIndex]
if (jsonObject.has(key)) {
val tempJsonObject = jsonObject.optJSONObject(key)
if (tempJsonObject != null) {
jsonObject = tempJsonObject
}
}
pathIndex++
}
return jsonObject?.opt(pathArray[pathArray.size - 1]) as? String
}
}
}
| mit | addba60436c638fdc7ed513db9170281 | 36.226667 | 99 | 0.532593 | 5.277883 | false | false | false | false |
ianmcxa/vortaro | app/src/main/java/org/mcxa/vortaro/WordView.kt | 1 | 3327 | package org.mcxa.vortaro
import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SortedList
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.word_item.view.*
import java.util.*
// model class for a single WordModel
data class WordModel(val es : String, val en : LinkedList<EnModel>, val ety : String,
val trans: Boolean?) {
fun displayDef(): String {
// format es into esf
val esf = when(trans) {
true -> "$es (tr)"
false -> "$es (ntr)"
null -> es
}
// format en into enf
var enf = ""
en.forEach { element ->
if (enf.isNotEmpty()) enf += ", "
enf += element.toString()
}
return "$esf : $enf"
}
}
data class EnModel(val word: String, val elaboration: String?, val elbefore: Boolean?) {
override fun toString(): String {
// handle the special case where we only have an elaboration
// due to me being lazy in my parse-DB code the elaboration already has () in the case where
// we just have an elaboration and no definitions
if (word.isEmpty() && elaboration != null) return elaboration
if (elaboration.isNullOrEmpty()) return word
return when(elbefore) {
null -> word
true -> "($elaboration) $word"
false -> "$word ($elaboration)"
}
}
}
class WordAdapter: RecyclerView.Adapter<WordAdapter.ViewHolder>() {
val words = SortedList<WordModel>(WordModel::class.java, object: SortedList.Callback<WordModel>() {
override fun areContentsTheSame(oldItem: WordModel?, newItem: WordModel?): Boolean {
return oldItem == newItem
}
override fun areItemsTheSame(item1: WordModel?, item2: WordModel?): Boolean {
return item1 == item2
}
override fun compare(o1: WordModel?, o2: WordModel?): Int {
return o1!!.es.compareTo(o2!!.es)
}
override fun onChanged(position: Int, count: Int) {
notifyItemRangeChanged(position, count)
}
override fun onInserted(position: Int, count: Int) {
notifyItemRangeInserted(position, count)
}
override fun onMoved(fromPosition: Int, toPosition: Int) {
notifyItemMoved(fromPosition, toPosition)
}
override fun onRemoved(position: Int, count: Int) {
notifyItemRangeRemoved(position, count)
}
})
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val word = itemView.item_word
val etymology = itemView.item_etymology
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val wordView = inflater.inflate(R.layout.word_item, parent, false)
return ViewHolder(wordView)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val word = words.get(position)
holder.word?.text = word.displayDef()
holder.etymology?.text = word.ety
}
override fun getItemCount(): Int {
return words.size()
}
} | apache-2.0 | 50871853b2972cfc886373b4f0904ef7 | 30.695238 | 103 | 0.622182 | 4.377632 | false | false | false | false |
yuzumone/Raid | app/src/main/kotlin/net/yuzumone/raid/service/RaidMessagingService.kt | 1 | 1780 | package net.yuzumone.raid.service
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.media.RingtoneManager
import android.support.v4.app.NotificationCompat
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import net.yuzumone.raid.MainActivity
import net.yuzumone.raid.R
class RaidMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(message: RemoteMessage?) {
super.onMessageReceived(message)
if (message == null) return
if (message.notification != null) {
val title = message.notification.title ?: "Title"
val body = message.notification.body ?: "Message"
sendNotification(title, body)
}
}
private fun sendNotification(title: String, body: String) {
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this, getString(R.string.channel_id))
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0, notificationBuilder.build())
}
} | apache-2.0 | 3e73be85bc9c5eb9632264f8a38088bf | 42.439024 | 103 | 0.720787 | 5.014085 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/LiveEvent.kt | 1 | 6994 | package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.common.Entity
import com.vimeo.networking2.enums.PlaylistSortType
import com.vimeo.networking2.enums.asEnum
import java.util.Date
/**
* Live Event data.
* @param autoCCKeywords A comma-separated list of keywords for enhancing the speech detection of automated closed
* captions.
* @param autoCCLanguage The language of the Automated Closed Captions.
* @param autoCCRemaining The amount of time remaining to the user to access the Automated Closed Captions feature.
* @param contentRating The event's granular content ratings. Current values are:
* - 'unrated' - The event hasn't been rated.
* - 'safe' - The event is safe for all audiences.
* - 'advertisement' - The event contains advertisements.
* - 'drugs' - The event contains drug or alcohol use.
* - 'language' - The event contains profanity or sexually suggestive content.
* - 'nudity' - The event contains nudity.
* - 'violence' - The event contains violence.
* @param createdTime The time in ISO 8601 format when the live event was created.
* @param dashLink The upstream MPEG-DASH link. To create a live video on the event, send your live content
* to this link.
* @param embed The live event's embed data.
* @param firstVideoInPlaylist The first video to be played in the playlist.
* @param isAutoCCEnabled Whether the Automated Closed Captions feature is enabled.
* @param isChatEnabled Whether to display live chat on the event page on Vimeo.
* @param isFromShowcase Whether the live event was created from a showcase.
* @param isFromWebinar Whether the live event was created from a webinar.
* @param isLowLatencyEnabled Whether the low latency feature is enabled.
* @param isUnlimitedStreamingEnabled Whether 24/7 streaming is enabled for the event.
* @param link The URI to access the live event on Vimeo.
* @param liveClips A list of videos belonging to the live event, including their video IDs and dates streamed.
* @param metadata Metadata about the live event.
* @param nextOccurrenceTime The ISO 8601 date on which the next occurrence of the event is expected to be live.
* @param parentFolder Information about the folder that contains the event.
* @param pictures The active thumbnail image of the live event.
* @param playlistSort The order in which the videos inside the live event appear in the playlist.
* @param rtmpLink The upstream RTMP link. Send your live content to this link to create a live video on the event.
* @param rtmpsLink The upstream RTMPS link. Send your live content to this link to create a live video on the event.
* @param shouldAutomaticallyTitleStream When the value of this field is true, the title for the next video in the event
* is generated based on the time of the stream and the title field of the event.
* @param shouldIgnoreAutoCCTimeLimit Whether to ignore the time limit of the Automated Closed Captions feature.
* @param streamDescription The description of the next video streamed to the event.
* @param streamKey The stream key used in conjunction with the RTMP and RTMPS links.
* @param streamPassword Anyone with the password can access the videos generated by streaming to the event.
* @param streamPrivacy The initial privacy settings of videos generated by streaming to the event
* as well as the embed privacy of the entire collection.
* @param streamTitle The title of the next video streamed to the event.
* This field applies only when [shouldAutomaticallyTitleStream] is `false`.
* @param streamableVideo The live event's video. A recurring live event always has a video,
* which is either in a pre-live state (ready to be streamed to) or in a live state
* (which is currently being streamed to).
* @param timeZone The time zone used in resolving the timestamps included in auto-generated video titles.
* @param title The title of the live event. This field is also optionally used as the base title for videos
* created by streaming to the event.
* @param uri The live event's canonical relative URI.
* @param user The owner of the live event.
*/
@JsonClass(generateAdapter = true)
data class LiveEvent(
@Json(name = "auto_cc_keywords")
val autoCCKeywords: String? = null,
@Json(name = "auto_cc_language")
val autoCCLanguage: String? = null,
@Json(name = "auto_cc_remaining")
val autoCCRemaining: Double? = null,
@Json(name = "content_rating")
val contentRating: List<String>? = null,
@Json(name = "created_time")
val createdTime: Date? = null,
@Json(name = "dash_link")
val dashLink: String? = null,
@Json(name = "embed")
val embed: LiveEventEmbed? = null,
@Json(name = "head_clip")
val firstVideoInPlaylist: Video? = null,
@Json(name = "chat_enabled")
val isChatEnabled: Boolean? = null,
@Json(name = "from_showcase")
val isFromShowcase: Boolean? = null,
@Json(name = "from_webinar")
val isFromWebinar: Boolean? = null,
@Json(name = "low_latency")
val isLowLatencyEnabled: Boolean? = null,
@Json(name = "unlimited_duration")
val isUnlimitedStreamingEnabled: Boolean? = null,
@Json(name = "link")
val link: String? = null,
@Json(name = "live_clips")
val liveClips: List<Video>? = null,
@Json(name = "metadata")
val metadata: Metadata<LiveEventConnections, LiveEventInteractions>? = null,
@Json(name = "next_occurrence_time")
val nextOccurrenceTime: Date? = null,
@Json(name = "parent_folder")
val parentFolder: Folder? = null,
@Json(name = "pictures")
val pictures: PictureCollection? = null,
@Json(name = "playlist_sort")
val playlistSort: String? = null,
@Json(name = "rtmp_link")
val rtmpLink: String? = null,
@Json(name = "rtmps_link")
val rtmpsLink: String? = null,
@Json(name = "automatically_title_stream")
val shouldAutomaticallyTitleStream: Boolean? = null,
@Json(name = "unlimited_auto_cc")
val shouldIgnoreAutoCCTimeLimit: Boolean? = null,
@Json(name = "stream_description")
val streamDescription: String? = null,
@Json(name = "stream_key")
val streamKey: String? = null,
@Json(name = "stream_password")
val streamPassword: String? = null,
@Json(name = "stream_privacy")
val streamPrivacy: StreamPrivacy? = null,
@Json(name = "stream_title")
val streamTitle: String? = null,
@Json(name = "streamable_clip")
val streamableVideo: Video? = null,
@Json(name = "time_zone")
val timeZone: String? = null,
@Json(name = "title")
val title: String? = null,
@Json(name = "uri")
val uri: String? = null,
@Json(name = "user")
val user: User? = null
) : Entity {
override val identifier: String? = uri
}
/**
* @see LiveEvent.playlistSort
* @see PlaylistSortType
*/
val LiveEvent.playlistSortType: PlaylistSortType
get() = playlistSort.asEnum(PlaylistSortType.UNKNOWN)
| mit | b3ab13a8af0249c8346e18d65debe7c4 | 38.514124 | 120 | 0.719617 | 3.885556 | false | false | false | false |
googlearchive/android-RuntimePermissionsBasic | kotlinApp/Application/src/main/java/com/example/android/basicpermissions/camera/CameraPreviewActivity.kt | 3 | 3223 | /*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.basicpermissions.camera
import android.hardware.Camera
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.widget.FrameLayout
import com.example.android.basicpermissions.R
private const val TAG = "CameraPreviewActivity"
private const val CAMERA_ID = 0
/**
* Displays a [CameraPreview] of the first [Camera].
* An error message is displayed if the Camera is not available.
*
*
* This Activity is only used to illustrate that access to the Camera API has been granted (or
* denied) as part of the runtime permissions model. It is not relevant for the use of the
* permissions API.
*
*
* Implementation is based directly on the documentation at
* http://developer.android.com/guide/topics/media/camera.html
*/
class CameraPreviewActivity : AppCompatActivity() {
private var camera: Camera? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Open an instance of the first camera and retrieve its info.
camera = getCameraInstance(CAMERA_ID)
val cameraInfo = Camera.CameraInfo()
Camera.getCameraInfo(CAMERA_ID, cameraInfo)
if (camera == null) {
// Camera is not available, display error message.
setContentView(R.layout.activity_camera_unavailable)
} else {
setContentView(R.layout.activity_camera)
// Get the rotation of the screen to adjust the preview image accordingly.
val displayRotation = windowManager.defaultDisplay.rotation
// Create the Preview view and set it as the content of this Activity.
val cameraPreview = CameraPreview(this, null,
0, camera, cameraInfo, displayRotation)
findViewById<FrameLayout>(R.id.camera_preview).addView(cameraPreview)
}
}
public override fun onPause() {
super.onPause()
// Stop camera access
releaseCamera()
}
/**
* A safe way to get an instance of the Camera object.
*/
private fun getCameraInstance(cameraId: Int): Camera? {
var c: Camera? = null
try {
c = Camera.open(cameraId) // attempt to get a Camera instance
} catch (e: Exception) {
// Camera is not available (in use or does not exist)
Log.e(TAG, "Camera $cameraId is not available: ${e.message}")
}
return c // returns null if camera is unavailable
}
private fun releaseCamera() {
camera?.release()
camera = null
}
}
| apache-2.0 | 46ce37c8426eabaf9253a5b18b4ef9fa | 32.926316 | 94 | 0.682594 | 4.488858 | false | false | false | false |
AndroidX/androidx | fragment/fragment-lint/src/main/java/androidx/fragment/lint/FragmentTagDetector.kt | 3 | 3151 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.fragment.lint
import com.android.SdkConstants.VIEW_FRAGMENT
import com.android.resources.ResourceFolderType
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.LintFix
import com.android.tools.lint.detector.api.ResourceXmlDetector
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.XmlContext
import org.w3c.dom.Element
import java.util.Collections
/**
* Lint check for detecting use of fragment tag in layout xml files. This provides a warning that
* recommends using [FragmentContainerView] instead.
*/
class FragmentTagDetector : ResourceXmlDetector() {
companion object {
val ISSUE = Issue.create(
id = "FragmentTagUsage",
briefDescription = "Use FragmentContainerView instead of the <fragment> tag",
explanation = """FragmentContainerView replaces the <fragment> tag as the preferred \
way of adding fragments via XML. Unlike the <fragment> tag, FragmentContainerView \
uses a normal `FragmentTransaction` under the hood to add the initial fragment, \
allowing further FragmentTransaction operations on the FragmentContainerView \
and providing a consistent timing for lifecycle events.""",
category = Category.CORRECTNESS,
severity = Severity.WARNING,
implementation = Implementation(
FragmentTagDetector::class.java, Scope.RESOURCE_FILE_SCOPE
),
androidSpecific = true
).addMoreInfo(
"https://developer.android.com" +
"/reference/androidx/fragment/app/FragmentContainerView.html"
)
}
override fun appliesTo(folderType: ResourceFolderType): Boolean {
return folderType == ResourceFolderType.LAYOUT
}
override fun getApplicableElements(): Collection<String>? = Collections.singleton(VIEW_FRAGMENT)
override fun visitElement(context: XmlContext, element: Element) {
context.report(
ISSUE, context.getNameLocation(element),
"Replace the <fragment> tag with FragmentContainerView.",
LintFix.create()
.replace()
.text(VIEW_FRAGMENT)
.with("androidx.fragment.app.FragmentContainerView").build()
)
}
}
| apache-2.0 | 2ed797ce4db1a0d2fd7429a74969a978 | 41.013333 | 100 | 0.702634 | 4.724138 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/macros/proc/ProcMacroApplicationService.kt | 2 | 5005 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.macros.proc
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.util.Disposer
import org.rust.cargo.project.model.cargoProjects
import org.rust.cargo.project.settings.RustProjectSettingsService
import org.rust.cargo.project.settings.rustSettings
import org.rust.cargo.toolchain.RsToolchainBase
import org.rust.cargo.toolchain.wsl.RsWslToolchain
import org.rust.ide.experiments.RsExperiments
import org.rust.openapiext.isFeatureEnabled
import java.nio.file.Path
@Service
class ProcMacroApplicationService : Disposable {
private val servers: MutableMap<DistributionIdAndExpanderPath, ProcMacroServerPool?> = hashMapOf()
init {
val connect = ApplicationManager.getApplication().messageBus.connect(this)
connect.subscribe(RustProjectSettingsService.RUST_SETTINGS_TOPIC, object : RustProjectSettingsService.RustSettingsListener {
override fun rustSettingsChanged(e: RustProjectSettingsService.RustSettingsChangedEvent) {
if (e.oldState.toolchain?.distributionId != e.newState.toolchain?.distributionId) {
removeUnusableSevers()
}
}
})
connect.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener {
override fun projectClosed(project: Project) {
removeUnusableSevers()
}
})
}
@Synchronized
fun getServer(toolchain: RsToolchainBase, procMacroExpanderPath: Path): ProcMacroServerPool? {
if (!isAnyEnabled()) return null
val id = toolchain.distributionId
val key = DistributionIdAndExpanderPath(id, procMacroExpanderPath)
var server = servers[key]
if (server == null) {
server = ProcMacroServerPool.new(toolchain, procMacroExpanderPath, this)
servers[key] = server
}
return server
}
@Synchronized
private fun removeUnusableSevers() {
val distributionIds = mutableSetOf<String>()
val procMacroExpanderPaths = mutableSetOf<Path>()
for (project in ProjectManager.getInstance().openProjects) {
project.rustSettings.toolchain?.distributionId?.let { distributionIds.add(it) }
for (cargoProject in project.cargoProjects.allProjects) {
cargoProject.procMacroExpanderPath?.let { procMacroExpanderPaths.add(it) }
}
}
servers.keys
.filter { it.distributionId !in distributionIds || it.procMacroExpanderPath !in procMacroExpanderPaths }
.mapNotNull { servers.remove(it) }
.forEach { Disposer.dispose(it) }
}
override fun dispose() {}
private data class DistributionIdAndExpanderPath(
val distributionId: String,
val procMacroExpanderPath: Path,
)
companion object {
fun getInstance(): ProcMacroApplicationService = service()
fun isFullyEnabled(): Boolean = isFeatureEnabled(RsExperiments.EVALUATE_BUILD_SCRIPTS)
&& (
isFeatureEnabled(RsExperiments.PROC_MACROS) || isFeatureEnabled(RsExperiments.FN_LIKE_PROC_MACROS)
&& isFeatureEnabled(RsExperiments.DERIVE_PROC_MACROS)
&& isFeatureEnabled(RsExperiments.ATTR_PROC_MACROS)
)
fun isAnyEnabled(): Boolean = isFeatureEnabled(RsExperiments.EVALUATE_BUILD_SCRIPTS)
&& (
isFeatureEnabled(RsExperiments.PROC_MACROS)
|| isFeatureEnabled(RsExperiments.FN_LIKE_PROC_MACROS)
|| isFeatureEnabled(RsExperiments.DERIVE_PROC_MACROS)
|| isFeatureEnabled(RsExperiments.ATTR_PROC_MACROS)
)
fun isFunctionLikeEnabled(): Boolean = isFeatureEnabled(RsExperiments.EVALUATE_BUILD_SCRIPTS)
&& (
isFeatureEnabled(RsExperiments.PROC_MACROS)
|| isFeatureEnabled(RsExperiments.FN_LIKE_PROC_MACROS)
)
fun isDeriveEnabled(): Boolean = isFeatureEnabled(RsExperiments.EVALUATE_BUILD_SCRIPTS)
&& (
isFeatureEnabled(RsExperiments.PROC_MACROS)
|| isFeatureEnabled(RsExperiments.DERIVE_PROC_MACROS)
)
fun isAttrEnabled(): Boolean = isFeatureEnabled(RsExperiments.EVALUATE_BUILD_SCRIPTS)
&& (
isFeatureEnabled(RsExperiments.PROC_MACROS)
|| isFeatureEnabled(RsExperiments.ATTR_PROC_MACROS)
)
private val RsToolchainBase.distributionId: String
get() = if (this is RsWslToolchain) wslPath.distributionId else "Local"
}
}
| mit | d2456f8d9a0929b1aaf07bc50f3ca0e7 | 40.02459 | 132 | 0.685914 | 5.01001 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/lang/core/macros/RsMacroExpansionErrorTestBase.kt | 2 | 2183 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.macros
import org.intellij.lang.annotations.Language
import org.rust.RsTestBase
import org.rust.fileTreeFromText
import org.rust.lang.core.macros.errors.GetMacroExpansionError
import org.rust.lang.core.psi.ext.RsPossibleMacroCall
import org.rust.lang.core.psi.ext.descendantsOfType
import org.rust.lang.core.psi.ext.expansionResult
import org.rust.lang.core.psi.ext.isMacroCall
import org.rust.stdext.RsResult
abstract class RsMacroExpansionErrorTestBase : RsTestBase() {
protected inline fun <reified T : GetMacroExpansionError> checkError(
@Language("Rust") code: String
) {
checkError(code, T::class.java)
}
protected fun checkError(code: String, errorClass: Class<*>) {
InlineFile(code)
doCheck(errorClass)
}
protected inline fun <reified T : GetMacroExpansionError> checkErrorByTree(
@Language("Rust") code: String
) {
checkError(code, T::class.java)
}
protected fun checkErrorByTree(code: String, errorClass: Class<*>) {
fileTreeFromText(code).createAndOpenFileWithCaretMarker()
doCheck(errorClass)
}
private fun doCheck(errorClass: Class<*>) {
val markers = findElementsWithDataAndOffsetInEditor<RsPossibleMacroCall>()
val (macro, expectedErrorMessage) = if (markers.isEmpty()) {
myFixture.file
.descendantsOfType<RsPossibleMacroCall>()
.single { it.isMacroCall } to null
} else {
val (macro, message, _) = markers.single()
check(macro.isMacroCall)
macro to message
}
val err = when (val result = macro.expansionResult) {
is RsResult.Err -> result.err
is RsResult.Ok -> error("Expected a macro expansion error, got a successfully expanded macro")
}
check(errorClass.isInstance(err)) { "Expected error $errorClass, got $err" }
if (expectedErrorMessage != null) {
assertEquals(expectedErrorMessage, err.toUserViewableMessage())
}
}
}
| mit | 492f010490a2a0da47c72a93a619ffc4 | 33.109375 | 106 | 0.672927 | 4.314229 | false | false | false | false |
ioc1778/incubator | incubator-quant/src/main/java/com/riaektiv/quant/options/Plain1DBinomialModel.kt | 2 | 4988 | package com.riaektiv.quant.options
/**
* Coding With Passion Since 1991
* Created: 10/9/2016, 8:27 AM Eastern Time
* @author Sergey Chuykov
*/
class Plain1DBinomialModel(val exercise: Exercise) : BinomialModel {
// John C. Hull
// Options, Futures and Other Derivatives, 9th edition
// page 280-289
var nodesUp = arrayOfNulls<BinomialModelNode>(0)
var nodesDn = arrayOfNulls<BinomialModelNode>(0)
fun nodeUp(i: Int): BinomialModelNode? {
if (i >= 0) {
return nodesUp[i]
} else {
return nodesDn[-i]
}
}
fun nodeDn(i: Int): BinomialModelNode? {
if (i >= 0) {
return nodesDn[i]
} else {
return nodesUp[-i]
}
}
fun u(vol: Double, dT: Double): Double {
return Math.exp(vol * Math.sqrt(dT))
}
fun d(vol: Double, dT: Double): Double {
return Math.exp(-vol * Math.sqrt(dT))
}
fun p(u: Double, d: Double, rate: Double, dT: Double): Double {
return (Math.pow(Math.E, (rate * dT)) - d) / (u - d) // (13.3)
}
fun payoff(stockPrice: Double, putOrCall: Int, strike: Double): Double {
return Math.max(0.0, if (putOrCall == Option.CALL) stockPrice - strike else strike - stockPrice)
}
fun ov(p: Double, fu: Double, fd: Double, discount: Double): Double {
//return Math.pow(Math.E, -(rate * dT)) * (p * fu + (1 - p) * fd) // (13.2)
return discount * (p * fu + (1 - p) * fd) // (13.2)
}
fun ov(putOrCall: Int, strike: Double, stockPrice: Double, p: Double, fu: Double, fd: Double, discount: Double): Double {
val payoff = payoff(stockPrice, putOrCall, strike)
var ov = ov(p, fu, fd, discount)
if (exercise == Exercise.American) {
ov = Math.max(payoff, ov)
}
return ov
}
override fun calculate(putOrCall: Int, strike: Double, timeToExpiration: Double, stockPrice: Double, vol: Double, rate: Double, steps: Int): Double {
val t = longArrayOf(0, 0, 0, 0, 0, 0, 0, 0)
t[0] = System.currentTimeMillis()
val dT = timeToExpiration / steps
val discount = Math.pow(Math.E, -(rate * dT))
val u = u(vol, dT)
val uSqrd = u * u
val d = 1.0 / u // d(vol, dT)
val dSqrd = d * d
val p = p(u, d, rate, dT)
nodesUp = arrayOfNulls<BinomialModelNode>(steps + 1)
nodesDn = arrayOfNulls<BinomialModelNode>(steps + 1)
t[1] = System.currentTimeMillis()
val levels = steps
for (level in 0..levels) {
nodesUp[level] = BinomialModelNode(0, level, 0.0)
nodesDn[level] = BinomialModelNode(0, level, 0.0)
}
t[2] = System.currentTimeMillis()
var up = Math.pow(u, levels.toDouble())
var dn = Math.pow(d, levels.toDouble())
for (level in levels downTo 0 step 2) {
val nodeUp = nodesUp[level]
nodeUp!!.stockPrice = stockPrice * up // Math.pow(u, levelD)
nodeUp.optionValue = payoff(nodeUp.stockPrice, putOrCall, strike)
up /= uSqrd
val nodeDn = nodesDn[level]
nodeDn!!.stockPrice = stockPrice * dn // Math.pow(d, levelD)
nodeDn.optionValue = payoff(nodeDn.stockPrice, putOrCall, strike)
dn /= dSqrd
}
t[3] = System.currentTimeMillis()
var step = steps - 1
while (step > 0) {
//println("step=$step")
up = Math.pow(u, step.toDouble())
dn = Math.pow(d, step.toDouble())
for (level in step downTo 0 step 2) {
val nodeUp = nodesUp[level]!!
var fu = nodesUp[level + 1]!!.optionValue
var fd = nodeUp(level - 1)!!.optionValue
nodeUp.stockPrice = stockPrice * up // Math.pow(u, level.toDouble())
nodeUp.optionValue = ov(putOrCall, strike, nodeUp.stockPrice, p, fu, fd, discount)
up /= uSqrd
//println(String.format("level:$level %s, %s", nodeUp.stockPrice, nodeUp.optionValue))
val nodeDn = nodesDn[level]!!
fu = nodeDn(level - 1)!!.optionValue
fd = nodesDn[level + 1]!!.optionValue
nodeDn.stockPrice = stockPrice * dn // Math.pow(d, level.toDouble())
nodeDn.optionValue = ov(putOrCall, strike, nodeDn.stockPrice, p, fu, fd, discount)
dn /= dSqrd
//println(String.format("level:$level %s, %s", nodeDn.stockPrice, nodeDn.optionValue))
}
step--
}
t[4] = System.currentTimeMillis()
val fu = nodesUp[1]!!.optionValue
val fd = nodesDn[1]!!.optionValue
val optionValue = ov(p, fu, fd, discount)
t[5] = System.currentTimeMillis()
/*
for (i in 0..4) {
println(String.format("%d-%d: %d ms", i, i + 1, t[i + 1] - t[i]))
}
*/
return optionValue
}
} | bsd-3-clause | 93b8b4baf33a89b1264d9a838a7ba520 | 31.607843 | 153 | 0.546512 | 3.555239 | false | false | false | false |
kiruto/debug-bottle | components/src/main/kotlin/com/exyui/android/debugbottle/components/widgets/__FloatAnimatedDialog.kt | 1 | 3239 | package com.exyui.android.debugbottle.components.widgets
import android.app.Dialog
import android.app.DialogFragment
import android.app.FragmentManager
import android.os.Bundle
import android.view.*
import com.exyui.android.debugbottle.components.R
/**
* Created by yuriel on 9/26/16.
*/
abstract class __FloatAnimatedDialog : DialogFragment() {
protected abstract val TAG: String
protected abstract val title: Int
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return Dialog(activity).apply {
window.requestFeature(Window.FEATURE_NO_TITLE)
setContentView(createView())
}
}
override fun onStart() {
super.onStart()
dialog.window.apply {
attributes.gravity = Gravity.TOP
attributes.width = WindowManager.LayoutParams.MATCH_PARENT
attributes.height = WindowManager.LayoutParams.WRAP_CONTENT
attributes.windowAnimations = R.style.__DialogAnimation
setBackgroundDrawableResource(android.R.color.transparent)
}
/** THIS WILL ADD AN ANIMATION WITH DIALOG APPEARANCE
//Grab the window of the dialog, and change the width
val lp = WindowManager.LayoutParams()
val window = dialog.window
lp.copyFrom(window.attributes)
//This makes the dialog take up the full width
lp.width = WindowManager.LayoutParams.MATCH_PARENT
lp.height = WindowManager.LayoutParams.WRAP_CONTENT
window.attributes = lp
val attr = dialog.window.attributes
attr.gravity = Gravity.TOP
attr.flags = attr.flags and WindowManager.LayoutParams.FLAG_DIM_BEHIND.inv()
window.attributes.gravity = Gravity.TOP
val decorView = dialog.window.decorView
val scaleDown = ObjectAnimator.ofPropertyValuesHolder(decorView,
PropertyValuesHolder.ofFloat("scaleX", 0.0f, 1.0f),
PropertyValuesHolder.ofFloat("scaleY", 0.0f, 1.0f),
PropertyValuesHolder.ofFloat("alpha", 0.0f, 1.0f))
scaleDown.duration = animationDuration
scaleDown.start()
*/
}
override fun dismiss() {
/** THIS WILL ADD AN ANIMATION WITH DIALOG DISMISS
val decorView = dialog.window.decorView
val scaleDown = ObjectAnimator.ofPropertyValuesHolder(decorView,
PropertyValuesHolder.ofFloat("scaleX", 1.0f, 0.0f),
PropertyValuesHolder.ofFloat("scaleY", 1.0f, 0.0f),
PropertyValuesHolder.ofFloat("alpha", 1.0f, 0.0f))
scaleDown.addListener(object : Animator.AnimatorListener {
override fun onAnimationEnd(animation: Animator) {
super@__FloatAnimatedDialog.dismiss()
}
override fun onAnimationStart(animation: Animator) {
}
override fun onAnimationCancel(animation: Animator) {
}
override fun onAnimationRepeat(animation: Animator) {
}
})
scaleDown.duration = animationDuration
scaleDown.start()
*/
super.dismiss()
}
fun show(fm: FragmentManager) {
show(fm, TAG)
}
abstract fun createView(): View
} | apache-2.0 | e74bd825e0783fccabb606f9331aae6b | 33.105263 | 84 | 0.647731 | 4.863363 | false | false | false | false |
foreverigor/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/other/navigation/NavigationManager.kt | 1 | 5624 | package de.tum.`in`.tumcampusapp.component.other.navigation
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.support.v4.app.NavUtils
import android.support.v4.app.TaskStackBuilder
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.component.other.generic.activity.BaseActivity
import de.tum.`in`.tumcampusapp.component.tumui.calendar.CalendarActivity
import de.tum.`in`.tumcampusapp.component.tumui.grades.GradesActivity
import de.tum.`in`.tumcampusapp.component.tumui.lectures.activity.LecturesPersonalActivity
import de.tum.`in`.tumcampusapp.component.tumui.person.PersonSearchActivity
import de.tum.`in`.tumcampusapp.component.tumui.roomfinder.RoomFinderActivity
import de.tum.`in`.tumcampusapp.component.tumui.tutionfees.TuitionFeesActivity
import de.tum.`in`.tumcampusapp.component.ui.barrierfree.BarrierFreeInfoActivity
import de.tum.`in`.tumcampusapp.component.ui.cafeteria.activity.CafeteriaActivity
import de.tum.`in`.tumcampusapp.component.ui.chat.activity.ChatRoomsActivity
import de.tum.`in`.tumcampusapp.component.ui.news.NewsActivity
import de.tum.`in`.tumcampusapp.component.ui.openinghour.OpeningHoursListActivity
import de.tum.`in`.tumcampusapp.component.ui.overview.MainActivity
import de.tum.`in`.tumcampusapp.component.ui.studyroom.StudyRoomsActivity
import de.tum.`in`.tumcampusapp.component.ui.ticket.activity.EventsActivity
import de.tum.`in`.tumcampusapp.component.ui.transportation.TransportationActivity
import de.tum.`in`.tumcampusapp.component.ui.tufilm.KinoActivity
import de.tum.`in`.tumcampusapp.utils.Const
object NavigationManager {
private val topLevelActivities = setOf(
MainActivity::class.java,
CalendarActivity::class.java,
LecturesPersonalActivity::class.java,
ChatRoomsActivity::class.java,
GradesActivity::class.java,
TuitionFeesActivity::class.java,
CafeteriaActivity::class.java,
StudyRoomsActivity::class.java,
RoomFinderActivity::class.java,
TransportationActivity::class.java,
PersonSearchActivity::class.java,
NewsActivity::class.java,
EventsActivity::class.java,
BarrierFreeInfoActivity::class.java,
OpeningHoursListActivity::class.java,
KinoActivity::class.java
)
// TODO: Documentation
fun open(current: Activity, menuItem: MenuItem) {
current.startActivity(menuItem.intent)
if (menuItem.intent.getBooleanExtra(Const.SHOW_DRAWER, false)) {
current.overridePendingTransition(R.anim.fadein, R.anim.fadeout)
}
}
fun open(context: Context, destination: NavigationDestination) {
when (destination) {
is SystemActivity -> openActivity(context, destination)
is SystemIntent -> openIntent(context, destination)
}
}
private fun openActivity(context: Context, activity: SystemActivity) {
val intent = Intent(context, activity.clazz)
activity.options?.let { intent.putExtras(it) }
val isTopLevelActivity = activity.clazz in topLevelActivities
if (isTopLevelActivity) {
intent.putExtra(Const.SHOW_DRAWER, true)
}
context.startActivity(intent).also {
val currentActivity = context as? Activity
if (isTopLevelActivity) {
currentActivity?.overridePendingTransition(R.anim.fadein, R.anim.fadeout)
}
}
}
private fun openIntent(context: Context, intent: SystemIntent) {
context.startActivity(intent.intent)
}
fun closeActivity(current: AppCompatActivity) {
if (current.supportFragmentManager.backStackEntryCount > 0) {
current.supportFragmentManager.popBackStackImmediate()
return
}
val isNavigationItem = current::class.java in topLevelActivities
val showDrawer = current.intent.extras?.getBoolean(Const.SHOW_DRAWER) ?: false
if (isNavigationItem && showDrawer) {
openNavigationDrawer(current)
return
} else if (isNavigationItem) {
current.onBackPressed()
return
}
val upIntent = NavUtils.getParentActivityIntent(current) ?: return
upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
if (NavUtils.shouldUpRecreateTask(current, upIntent)) {
TaskStackBuilder.create(current)
.addNextIntentWithParentStack(upIntent)
.startActivities()
} else {
NavUtils.navigateUpTo(current, upIntent)
}
}
private fun openNavigationDrawer(activity: AppCompatActivity) {
val baseActivity = activity as? BaseActivity
baseActivity?.openDrawer()
}
fun onBackPressed(current: Activity): Boolean {
val isTopLevel = current::class.java in topLevelActivities
val showDrawer = current.intent.extras?.getBoolean(Const.SHOW_DRAWER) ?: false
val parentName = current.parentActivityIntent?.component?.className
if (isTopLevel && showDrawer && parentName == MainActivity::class.java.name) {
val intent = Intent(current, MainActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
}
current.startActivity(intent)
current.overridePendingTransition(R.anim.fadein, R.anim.fadeout)
return true
}
return false
}
}
| gpl-3.0 | 5551961da9d68822bdf94674491a9c75 | 39.171429 | 90 | 0.698613 | 4.659486 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/config/io/ConfigurationLoader.kt | 1 | 3730 | /*
Copyright 2017-2020 Charles Korn.
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 batect.config.io
import batect.config.Configuration
import batect.config.io.deserializers.PathDeserializer
import batect.logging.LogMessageBuilder
import batect.logging.Logger
import batect.os.PathResolutionResult
import batect.os.PathResolverFactory
import com.charleskorn.kaml.EmptyYamlDocumentException
import com.charleskorn.kaml.Yaml
import com.charleskorn.kaml.YamlConfiguration
import com.charleskorn.kaml.YamlException
import kotlinx.serialization.modules.serializersModuleOf
import java.nio.charset.Charset
import java.nio.file.Files
import java.nio.file.Path
class ConfigurationLoader(
private val pathResolverFactory: PathResolverFactory,
private val logger: Logger
) {
fun loadConfig(path: Path): Configuration {
val absolutePath = path.toAbsolutePath()
logger.info {
message("Loading configuration.")
data("path", absolutePath.toString())
}
if (!Files.exists(absolutePath)) {
logger.error {
message("Configuration file could not be found.")
data("path", absolutePath.toString())
}
throw ConfigurationException("The file '$absolutePath' does not exist.")
}
val configFileContent = Files.readAllBytes(absolutePath).toString(Charset.defaultCharset())
val config = loadConfig(configFileContent, absolutePath)
logger.info {
message("Configuration loaded.")
data("config", config)
}
return config
}
private fun loadConfig(configFileContent: String, filePath: Path): Configuration {
val pathResolver = pathResolverFactory.createResolver(filePath.parent)
val pathDeserializer = PathDeserializer(pathResolver)
val module = serializersModuleOf(PathResolutionResult::class, pathDeserializer)
val config = YamlConfiguration(extensionDefinitionPrefix = ".")
val parser = Yaml(configuration = config, context = module)
try {
return parser.parse(Configuration.serializer(), configFileContent)
} catch (e: Throwable) {
logger.error {
message("Exception thrown while loading configuration.")
exception(e)
}
throw mapException(e, filePath.toString())
}
}
private fun mapException(e: Throwable, fileName: String): ConfigurationException = when (e) {
is YamlException -> ConfigurationException(mapYamlExceptionMessage(e, fileName), fileName, e.line, e.column, e)
is ConfigurationException -> ConfigurationException(e.message, e.fileName ?: fileName, e.lineNumber, e.column, e)
else -> ConfigurationException("Could not load configuration file: ${e.message}", fileName, null, null, e)
}
private fun mapYamlExceptionMessage(e: YamlException, fileName: String): String = when (e) {
is EmptyYamlDocumentException -> "File '$fileName' contains no configuration."
else -> e.message
}
}
private fun LogMessageBuilder.data(key: String, value: Configuration) = this.data(key, value, Configuration.Companion)
| apache-2.0 | 29a93223d1e653d8314e1432e6a76086 | 37.453608 | 121 | 0.703217 | 4.869452 | false | true | false | false |
brianwernick/RecyclerExt | demo/src/main/kotlin/com/devbrackets/android/recyclerextdemo/ui/viewholder/SimpleTextViewHolder.kt | 1 | 1268 | package com.devbrackets.android.recyclerextdemo.ui.viewholder
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.ColorInt
import com.devbrackets.android.recyclerext.adapter.viewholder.ClickableViewHolder
import com.devbrackets.android.recyclerextdemo.R
/**
* A ViewHolder for the list_item_simple_text layout
*/
class SimpleTextViewHolder(itemView: View) : ClickableViewHolder(itemView) {
private val textView: TextView
private val spacing: View
fun setText(text: String?) {
textView.text = text
}
fun setBackgroundColor(@ColorInt color: Int) {
itemView.setBackgroundColor(color)
}
fun setSpacingVisible(visible: Boolean) {
spacing.visibility = if (visible) View.VISIBLE else View.GONE
}
companion object {
fun newInstance(inflater: LayoutInflater, parent: ViewGroup?): SimpleTextViewHolder {
val view = inflater.inflate(R.layout.list_item_simple_text, parent, false)
return SimpleTextViewHolder(view)
}
}
init {
textView = itemView.findViewById(R.id.simple_text_text_view)
spacing = itemView.findViewById(R.id.simple_text_spacing)
}
} | apache-2.0 | c22fa55affed4480729206a3d438a42e | 30.725 | 93 | 0.727129 | 4.387543 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/lang/core/resolve/scope/ExpressionScope.kt | 1 | 3210 | package org.elm.lang.core.resolve.scope
import com.intellij.psi.PsiElement
import org.elm.lang.core.psi.*
import org.elm.lang.core.psi.elements.ElmAnonymousFunctionExpr
import org.elm.lang.core.psi.elements.ElmCaseOfBranch
import org.elm.lang.core.psi.elements.ElmLetInExpr
import org.elm.lang.core.psi.elements.ElmValueDeclaration
class ExpressionScope(private val element: PsiElement) {
/** Return a lazy sequence of all names visible to the [element] */
fun getVisibleValues(): Sequence<ElmNamedElement> {
val declAncestors = mutableListOf<ElmValueDeclaration>()
return element.ancestorsStrict
.takeUntil { it is ElmFile }
.flatMap {
when (it) {
is ElmFile -> {
ModuleScope.getVisibleValues(it).all.asSequence()
}
is ElmValueDeclaration -> {
declAncestors += it
val isTopLevel = it.isTopLevel
// Don't include top-level assignees here, since they'll be included in
// ModuleScope.getVisibleValues
it.declaredNames(includeParameters = true).asSequence()
.filter { n -> !isTopLevel || n !is ElmValueAssigneeTag }
}
is ElmLetInExpr -> {
it.valueDeclarationList.asSequence()
.filter { innerDecl -> innerDecl !in declAncestors } // already visited
.flatMap { innerDecl ->
innerDecl.declaredNames(includeParameters = false).asSequence()
}
}
is ElmCaseOfBranch -> {
it.destructuredNames.asSequence()
}
is ElmAnonymousFunctionExpr -> {
it.namedParameters.asSequence()
}
else -> {
emptySequence()
}
}
}
}
}
private class TakeUntilSequence<T> (
private val sequence: Sequence<T>,
private val predicate: (T) -> Boolean
) : Sequence<T> {
override fun iterator(): Iterator<T> = object : Iterator<T> {
val iterator = sequence.iterator()
var done = false
override fun next(): T {
if (!done && iterator.hasNext()) {
val item = iterator.next()
if (predicate(item)) {
done = true
}
return item
}
throw NoSuchElementException()
}
override fun hasNext(): Boolean {
return !done && iterator.hasNext()
}
}
}
/** Return elements of this sequence up to and including the first element for which [predicate] returns true */
private fun <T> Sequence<T>.takeUntil(predicate: (T) -> Boolean): Sequence<T> {
return TakeUntilSequence(this, predicate)
}
| mit | 5a55a54fdb55c437cd14f126e3c39d96 | 39.632911 | 112 | 0.501246 | 5.524957 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/service/CommandEnum.kt | 1 | 5982 | /*
* Copyright (C) 2014 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.service
import android.os.Bundle
import org.andstatus.app.IntentExtra
import org.andstatus.app.R
import org.andstatus.app.context.MyContext
import org.andstatus.app.util.MyLog
/**
* The command to the MyService or to MyAppWidgetProvider as a enum.
* We use 'code' for persistence
*
* @author [email protected]
*/
enum class CommandEnum constructor(
/** code of the enum that is used in notes */
private val code: String?,
/** The id of the string resource with the localized name of this enum to use in UI */
private val titleResId: Int = 0,
/** less value of the priority means higher priority */
private val priority: Int = 0,
private val connectionRequired: ConnectionRequired = ConnectionRequired.ANY) {
/** The action is unknown */
UNKNOWN("unknown"),
/** There is no action */
EMPTY("empty"),
GET_TIMELINE("fetch-timeline", 0, 4, ConnectionRequired.SYNC),
GET_OLDER_TIMELINE("get-older-timeline", 0, 4, ConnectionRequired.SYNC),
/** Fetch avatar for the specified actor */
GET_AVATAR("fetch-avatar", R.string.title_command_fetch_avatar, 9, ConnectionRequired.SYNC),
GET_ATTACHMENT("fetch-attachment", R.string.title_command_fetch_attachment, 11, ConnectionRequired.DOWNLOAD_ATTACHMENT),
LIKE("create-favorite", R.string.menu_item_favorite, 0, ConnectionRequired.SYNC),
UNDO_LIKE("destroy-favorite", R.string.menu_item_destroy_favorite, 0, ConnectionRequired.SYNC),
GET_ACTOR("get-user", R.string.get_user, -5, ConnectionRequired.SYNC),
SEARCH_ACTORS("search-users", R.string.search_users, -5, ConnectionRequired.SYNC),
FOLLOW("follow-user", R.string.command_follow_user, 0, ConnectionRequired.SYNC),
UNDO_FOLLOW("stop-following-user", R.string.command_stop_following_user, 0, ConnectionRequired.SYNC),
GET_FOLLOWERS("get-followers", R.string.get_followers, -5, ConnectionRequired.SYNC),
GET_FRIENDS("get-friends", R.string.get_friends, -5, ConnectionRequired.SYNC),
GET_LISTS("get-lists", R.string.get_lists, -5, ConnectionRequired.SYNC),
GET_LIST_MEMBERS("get-list-members", R.string.get_list_members, -5, ConnectionRequired.SYNC),
/** This command is for sending both public and private notes */
UPDATE_NOTE("update-status", R.string.button_create_message, -10, ConnectionRequired.SYNC),
/** The same as #UPDATE_NOTE but is used to show that some attachment needs to be uploaded */
UPDATE_MEDIA("update-media", R.string.button_create_message, -9, ConnectionRequired.DOWNLOAD_ATTACHMENT),
DELETE_NOTE("destroy-status", R.string.menu_item_destroy_status, -3, ConnectionRequired.SYNC),
GET_NOTE("get-status", R.string.title_command_get_status, -5, ConnectionRequired.SYNC),
GET_CONVERSATION("get-conversation", R.string.get_conversation, -5, ConnectionRequired.SYNC),
/** see http://gstools.org/api/doc/ */
GET_OPEN_INSTANCES("get_open_instances", R.string.get_open_instances_title, -1, ConnectionRequired.SYNC),
ANNOUNCE("reblog", R.string.menu_item_reblog, -9, ConnectionRequired.SYNC),
UNDO_ANNOUNCE("destroy-reblog", R.string.menu_item_destroy_reblog, -3, ConnectionRequired.SYNC),
RATE_LIMIT_STATUS("rate-limit-status", 0, 0, ConnectionRequired.SYNC),
/** Stop the service after finishing all asynchronous treads (i.e. not immediately!) */
STOP_SERVICE("stop-service"),
/** Broadcast back state of [MyService] */
BROADCAST_SERVICE_STATE("broadcast-service-state");
/**
* String code for the Command to be used in notes
*/
fun save(): String? {
return code
}
/** Localized title for UI
* @param accountName
*/
fun getTitle(myContext: MyContext?, accountName: String?): CharSequence? {
if (titleResId == 0 || myContext == null || myContext.isEmpty) {
return this.code
}
var resId = titleResId
val ma = myContext.accounts.fromAccountName(accountName)
if (ma.isValid) {
resId = ma.origin.alternativeTermForResourceId(titleResId)
}
return myContext.context.getText(resId)
}
fun getPriority(): Int {
return priority
}
fun getConnectionRequired(): ConnectionRequired {
return connectionRequired
}
fun isGetTimeline(): Boolean {
return when (this) {
GET_TIMELINE, GET_OLDER_TIMELINE -> true
else -> false
}
}
companion object {
fun fromBundle(bundle: Bundle?): CommandEnum {
var command: CommandEnum = UNKNOWN
if (bundle != null) {
command = load(bundle.getString(IntentExtra.COMMAND.key))
if (command == UNKNOWN) {
MyLog.w(CommandData::class.java, "Bundle has UNKNOWN command: $bundle")
}
}
return command
}
/**
* Returns the enum for a String action code or UNKNOWN
*/
fun load(strCode: String?): CommandEnum {
if (!strCode.isNullOrEmpty()) {
for (serviceCommand in values()) {
if (serviceCommand.code == strCode) {
return serviceCommand
}
}
}
return UNKNOWN
}
}
}
| apache-2.0 | 17353e06b1ab0d5b5435de3988ba2f16 | 40.832168 | 124 | 0.658643 | 4.122674 | false | false | false | false |
CruGlobal/android-gto-support | gto-support-util/src/main/java/org/ccci/gto/android/common/util/os/BundleUtils.kt | 2 | 2009 | @file:JvmName("BundleUtils")
package org.ccci.gto.android.common.util.os
import android.os.Bundle
import java.util.Locale
import org.jetbrains.annotations.Contract
// region Enums
fun Bundle.putEnum(key: String?, value: Enum<*>?) = putString(key, value?.name)
@JvmOverloads
@Contract("_, _, _, !null -> !null")
fun <T : Enum<T>> Bundle.getEnum(type: Class<T>, key: String?, defValue: T? = null): T? {
return try {
getString(key)?.let { java.lang.Enum.valueOf<T>(type, it) } ?: defValue
} catch (e: IllegalArgumentException) {
defValue
}
}
@Contract("_, _, !null -> !null")
inline fun <reified T : Enum<T>> Bundle.getEnum(key: String?, defValue: T? = null) =
getEnum(T::class.java, key, defValue)
// endregion Enums
// region Locales
@Deprecated(
"Since v3.11.2, use BundleKt.putLocale() instead",
ReplaceWith("putLocale(key, locale)"),
DeprecationLevel.ERROR
)
@JvmName("putLocale")
@Suppress("FunctionName")
internal fun Bundle.`-putLocale`(key: String?, locale: Locale?) = putLocale(key, locale)
@Deprecated(
"Since v3.11.2, use BundleKt.getLocale() instead",
ReplaceWith("getLocale(key, defValue)"),
DeprecationLevel.ERROR
)
@JvmOverloads
@JvmName("getLocale")
@Suppress("FunctionName")
fun Bundle.`-getLocale`(key: String?, defValue: Locale? = null) = getLocale(key, defValue)
@Deprecated(
"Since v3.11.2, use BundleKt.putLocaleArray() instead",
ReplaceWith("putLocaleArray(key, locales, singleString)"),
DeprecationLevel.ERROR
)
@JvmOverloads
@JvmName("putLocaleArray")
@Suppress("FunctionName")
fun Bundle.`-putLocaleArray`(key: String?, locales: Array<Locale>?, singleString: Boolean = false) =
putLocaleArray(key, locales, singleString)
@Deprecated(
"Since v3.11.2, use BundleKt.getLocaleArray() instead",
ReplaceWith("getLocaleArray(key)"),
DeprecationLevel.ERROR
)
@JvmName("getLocaleArray")
@Suppress("FunctionName")
fun Bundle.`-getLocaleArray`(key: String?) = getLocaleArray(key)
// endregion Locales
| mit | 0151c227eaaa1b5eafe5fd46aa406f44 | 28.544118 | 100 | 0.701344 | 3.562057 | false | false | false | false |
CruGlobal/android-gto-support | gto-support-androidx-lifecycle/src/main/kotlin/org/ccci/gto/android/common/androidx/lifecycle/Transformations.kt | 1 | 12203 | @file:JvmName("Transformations2")
package org.ccci.gto.android.common.androidx.lifecycle
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.isInitialized
import androidx.lifecycle.map
import androidx.lifecycle.switchMap
// region combine
/**
* This method will combine 2 LiveData objects into a new LiveData object by running the {@param mapFunction} on the
* current values of both source LiveData objects.
*
* @see androidx.lifecycle.Transformations.map
*/
fun <IN1, IN2, OUT> combine(
source1: LiveData<IN1>,
source2: LiveData<IN2>,
mapFunction: (IN1, IN2) -> OUT
) = combineInt(source1, source2) {
@Suppress("UNCHECKED_CAST")
mapFunction(source1.value as IN1, source2.value as IN2)
}
/**
* This method will combine 2 LiveData objects into a new LiveData object by running the {@param mapFunction} on the
* current values of both source LiveData objects.
*
* @see androidx.lifecycle.Transformations.map
*/
@JvmSynthetic
fun <IN1, IN2, OUT> LiveData<IN1>.combineWith(
other: LiveData<IN2>,
mapFunction: (IN1, IN2) -> OUT
) = combineInt(this, other) {
@Suppress("UNCHECKED_CAST")
mapFunction(value as IN1, other.value as IN2)
}
/**
* This method will combine 3 LiveData objects into a new LiveData object by running the {@param mapFunction} on the
* current values of all source LiveData objects.
*
* @see androidx.lifecycle.Transformations.map
*/
fun <IN1, IN2, IN3, OUT> combine(
source1: LiveData<IN1>,
source2: LiveData<IN2>,
source3: LiveData<IN3>,
mapFunction: (IN1, IN2, IN3) -> OUT
) = combineInt(source1, source2, source3) {
@Suppress("UNCHECKED_CAST")
mapFunction(source1.value as IN1, source2.value as IN2, source3.value as IN3)
}
/**
* This method will combine 3 LiveData objects into a new LiveData object by running the {@param mapFunction} on the
* current values of all source LiveData objects.
*
* @see androidx.lifecycle.Transformations.map
*/
@JvmSynthetic
fun <IN1, IN2, IN3, OUT> LiveData<IN1>.combineWith(
other: LiveData<IN2>,
other2: LiveData<IN3>,
mapFunction: (IN1, IN2, IN3) -> OUT
) = combineInt(this, other, other2) {
@Suppress("UNCHECKED_CAST")
mapFunction(value as IN1, other.value as IN2, other2.value as IN3)
}
/**
* This method will combine 4 LiveData objects into a new LiveData object by running the {@param mapFunction} on the
* current values of all source LiveData objects.
*
* @see androidx.lifecycle.Transformations.map
*/
fun <IN1, IN2, IN3, IN4, OUT> combine(
source1: LiveData<IN1>,
source2: LiveData<IN2>,
source3: LiveData<IN3>,
source4: LiveData<IN4>,
mapFunction: (IN1, IN2, IN3, IN4) -> OUT
) = combineInt(source1, source2, source3, source4) {
@Suppress("UNCHECKED_CAST")
mapFunction(source1.value as IN1, source2.value as IN2, source3.value as IN3, source4.value as IN4)
}
/**
* This method will combine 4 LiveData objects into a new LiveData object by running the {@param mapFunction} on the
* current values of all source LiveData objects.
*
* @see androidx.lifecycle.Transformations.map
*/
@JvmSynthetic
fun <IN1, IN2, IN3, IN4, OUT> LiveData<IN1>.combineWith(
other: LiveData<IN2>,
other2: LiveData<IN3>,
other3: LiveData<IN4>,
mapFunction: (IN1, IN2, IN3, IN4) -> OUT
) = combineInt(this, other, other2, other3) {
@Suppress("UNCHECKED_CAST")
mapFunction(value as IN1, other.value as IN2, other2.value as IN3, other3.value as IN4)
}
/**
* This method will combine 5 LiveData objects into a new LiveData object by running the {@param mapFunction} on the
* current values of all source LiveData objects.
*
* @see androidx.lifecycle.Transformations.map
*/
fun <IN1, IN2, IN3, IN4, IN5, OUT> combine(
source1: LiveData<IN1>,
source2: LiveData<IN2>,
source3: LiveData<IN3>,
source4: LiveData<IN4>,
source5: LiveData<IN5>,
mapFunction: (IN1, IN2, IN3, IN4, IN5) -> OUT
) = combineInt(source1, source2, source3, source4, source5) {
@Suppress("UNCHECKED_CAST")
mapFunction(
source1.value as IN1,
source2.value as IN2,
source3.value as IN3,
source4.value as IN4,
source5.value as IN5
)
}
/**
* This method will combine 5 LiveData objects into a new LiveData object by running the {@param mapFunction} on the
* current values of all source LiveData objects.
*
* @see androidx.lifecycle.Transformations.map
*/
@JvmSynthetic
fun <IN1, IN2, IN3, IN4, IN5, OUT> LiveData<IN1>.combineWith(
other: LiveData<IN2>,
other2: LiveData<IN3>,
other3: LiveData<IN4>,
other4: LiveData<IN5>,
mapFunction: (IN1, IN2, IN3, IN4, IN5) -> OUT
) = combineInt(this, other, other2, other3, other4) {
@Suppress("UNCHECKED_CAST")
mapFunction(value as IN1, other.value as IN2, other2.value as IN3, other3.value as IN4, other4.value as IN5)
}
/**
* This method will combine 6 LiveData objects into a new LiveData object by running the {@param mapFunction} on the
* current values of all source LiveData objects.
*
* @see androidx.lifecycle.Transformations.map
*/
@JvmName("combine")
fun <IN1, IN2, IN3, IN4, IN5, IN6, OUT> LiveData<IN1>.combineWith(
other: LiveData<IN2>,
other2: LiveData<IN3>,
other3: LiveData<IN4>,
other4: LiveData<IN5>,
other5: LiveData<IN6>,
mapFunction: (IN1, IN2, IN3, IN4, IN5, IN6) -> OUT
) = combineInt(this, other, other2, other3, other4, other5) {
@Suppress("UNCHECKED_CAST")
mapFunction(
value as IN1,
other.value as IN2,
other2.value as IN3,
other3.value as IN4,
other4.value as IN5,
other5.value as IN6
)
}
/**
* This method will combine 7 LiveData objects into a new LiveData object by running the {@param mapFunction} on the
* current values of all source LiveData objects.
*
* @see androidx.lifecycle.Transformations.map
*/
@JvmName("combine")
fun <IN1, IN2, IN3, IN4, IN5, IN6, IN7, OUT> LiveData<IN1>.combineWith(
other: LiveData<IN2>,
other2: LiveData<IN3>,
other3: LiveData<IN4>,
other4: LiveData<IN5>,
other5: LiveData<IN6>,
other6: LiveData<IN7>,
mapFunction: (IN1, IN2, IN3, IN4, IN5, IN6, IN7) -> OUT
) = combineInt(this, other, other2, other3, other4, other5, other6) {
@Suppress("UNCHECKED_CAST")
mapFunction(
value as IN1,
other.value as IN2,
other2.value as IN3,
other3.value as IN4,
other4.value as IN5,
other5.value as IN6,
other6.value as IN7
)
}
private inline fun <OUT> combineInt(
vararg input: LiveData<*>,
crossinline mapFunction: () -> OUT
): LiveData<OUT> {
val result = MediatorLiveData<OUT>()
val state = object {
val inputInitialized = BooleanArray(input.size) { false }
var isInitialized = false
get() = field || inputInitialized.all { it }.also { field = it }
}
input.forEachIndexed { i, it ->
result.addSource(it) {
state.inputInitialized[i] = true
if (state.isInitialized) result.value = mapFunction()
}
}
return result
}
// endregion combine
inline fun <reified T> LiveData<*>.filterIsInstance() = map { it as? T }
fun <T : Any> LiveData<T?>.notNull(): LiveData<T> {
val result = MediatorLiveData<T>()
result.addSource(this) { it?.let { result.value = it } }
return result
}
fun <T> LiveData<out Iterable<T>>.sortedWith(comparator: Comparator<in T>) = map { it.sortedWith(comparator) }
// region switchCombineWith
/**
* This method will combine 2 LiveData objects into a new LiveData object by running the {@param mapFunction} on the
* current values of both source LiveData objects.
* Returning either of the original LiveData objects will cause an Exception.
*
* @see androidx.lifecycle.Transformations.switchMap
*/
fun <IN1, IN2, OUT> switchCombine(
source1: LiveData<IN1>,
source2: LiveData<IN2>,
mapFunction: (IN1, IN2) -> LiveData<out OUT>
) = switchCombineWithInt(source1, source2) {
@Suppress("UNCHECKED_CAST")
mapFunction(source1.value as IN1, source2.value as IN2)
}
/**
* This method will combine 2 LiveData objects into a new LiveData object by running the {@param mapFunction} on the
* current values of both source LiveData objects.
* Returning either of the original LiveData objects will cause an Exception.
*
* @see androidx.lifecycle.Transformations.switchMap
*/
fun <IN1, IN2, OUT> LiveData<IN1>.switchCombineWith(
other: LiveData<IN2>,
mapFunction: (IN1, IN2) -> LiveData<out OUT>
) = switchCombineWithInt(this, other) {
@Suppress("UNCHECKED_CAST")
mapFunction(value as IN1, other.value as IN2)
}
/**
* This method will combine 3 LiveData objects into a new LiveData object by running the {@param mapFunction} on the
* current values of the source LiveData objects.
* Returning any of the original LiveData objects will cause an Exception.
*
* @see androidx.lifecycle.Transformations.switchMap
*/
@JvmName("switchCombine")
fun <IN1, IN2, IN3, OUT> LiveData<IN1>.switchCombineWith(
other: LiveData<IN2>,
other2: LiveData<IN3>,
mapFunction: (IN1, IN2, IN3) -> LiveData<out OUT>
) = switchCombineWithInt(this, other, other2) {
@Suppress("UNCHECKED_CAST")
mapFunction(value as IN1, other.value as IN2, other2.value as IN3)
}
/**
* This method will combine 4 LiveData objects into a new LiveData object by running the {@param mapFunction} on the
* current values of the source LiveData objects.
* Returning any of the original LiveData objects will cause an Exception.
*
* @see androidx.lifecycle.Transformations.switchMap
*/
@JvmName("switchCombine")
fun <IN1, IN2, IN3, IN4, OUT> LiveData<IN1>.switchCombineWith(
other: LiveData<IN2>,
other2: LiveData<IN3>,
other3: LiveData<IN4>,
mapFunction: (IN1, IN2, IN3, IN4) -> LiveData<out OUT>
) = switchCombineWithInt(this, other, other2, other3) {
@Suppress("UNCHECKED_CAST")
mapFunction(value as IN1, other.value as IN2, other2.value as IN3, other3.value as IN4)
}
private inline fun <OUT> switchCombineWithInt(
vararg input: LiveData<*>,
crossinline mapFunction: () -> LiveData<out OUT>
): LiveData<OUT> {
val result = MediatorLiveData<OUT>()
val state = object {
val inputInitialized = BooleanArray(input.size) { false }
var isInitialized = false
get() = field || inputInitialized.all { it }.also { field = it }
var source: LiveData<out OUT>? = null
}
input.forEachIndexed { i, it ->
result.addSource(it) {
with(state) {
inputInitialized[i] = true
if (!isInitialized) return@addSource
val newSource = mapFunction()
if (source === newSource) return@addSource
source?.let { result.removeSource(it) }
source = newSource
source?.let { result.addSource(it, result::setValue) }
}
}
}
return result
}
// endregion switchCombineWith
// region Boolean operators
infix fun LiveData<Boolean>.and(other: LiveData<Boolean>) = combineWith(other) { t, o -> t && o }
infix fun LiveData<Boolean>.or(other: LiveData<Boolean>) = combineWith(other) { t, o -> t || o }
// endregion Boolean operators
inline fun <T, R> LiveData<out Iterable<T>>.switchFold(crossinline operation: (acc: LiveData<R?>, T) -> LiveData<R?>) =
switchFold(emptyLiveData(), operation)
inline fun <T, R> LiveData<out Iterable<T>>.switchFold(
acc: LiveData<R>,
crossinline operation: (acc: LiveData<R>, T) -> LiveData<R>
) = switchMap { it.fold(acc, operation) }
/**
* Transform a LiveData to return an initial value before it has had a chance to resolve it's actual value.
* This shouldn't be used with [MutableLiveData] which already has a mechanism to define an initial value.
*/
fun <T> LiveData<T>.withInitialValue(value: T) = when {
// short-circuit if the LiveData has already loaded an initial value
isInitialized -> this
else -> MediatorLiveData<T>().also {
it.value = value
it.addSource(this) { value -> it.value = value }
}
}
| mit | 85bda1d0ca10dc15888723393ef6189c | 33.471751 | 119 | 0.683193 | 3.60183 | false | false | false | false |
esofthead/mycollab | mycollab-core/src/main/java/com/mycollab/validator/constraints/DateComparisonValidator.kt | 3 | 1863 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 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:></http:>//www.gnu.org/licenses/>.
*/
package com.mycollab.validator.constraints
import org.apache.commons.beanutils.PropertyUtils
import java.time.LocalDate
import javax.validation.ConstraintValidator
import javax.validation.ConstraintValidatorContext
/**
* @author MyCollab Ltd.
* @since 1.0
*/
class DateComparisonValidator : ConstraintValidator<DateComparison, Any> {
private var firstDateField: String? = null
private var lastDateField: String? = null
override fun initialize(constraintAnnotation: DateComparison) {
this.firstDateField = constraintAnnotation.firstDateField
this.lastDateField = constraintAnnotation.lastDateField
}
override fun isValid(value: Any, context: ConstraintValidatorContext): Boolean {
return try {
val firstValue = PropertyUtils.getProperty(value, firstDateField) as? LocalDate
val lastValue = PropertyUtils.getProperty(value, lastDateField) as? LocalDate
if (firstValue != null && lastValue != null) {
return firstValue.isBefore(lastValue.plusDays(1))
}
true
} catch (ex: Exception) {
true
}
}
}
| agpl-3.0 | 6148e253f61bbbc3d5643013a78a3770 | 37 | 91 | 0.714823 | 4.643392 | false | false | false | false |
inorichi/tachiyomi-extensions | multisrc/overrides/gigaviewer/comicgardo/src/ComicGardo.kt | 1 | 1094 | package eu.kanade.tachiyomi.extension.ja.comicgardo
import eu.kanade.tachiyomi.multisrc.gigaviewer.GigaViewer
import eu.kanade.tachiyomi.source.model.SManga
import okhttp3.OkHttpClient
import org.jsoup.nodes.Element
class ComicGardo : GigaViewer(
"Comic Gardo",
"https://comic-gardo.com",
"ja",
"https://cdn-img.comic-gardo.com/public/page"
) {
override val supportsLatest: Boolean = false
override val client: OkHttpClient = super.client.newBuilder()
.addInterceptor(::imageIntercept)
.build()
override val publisher: String = "オーバーラップ"
override fun popularMangaSelector(): String = "ul.series-section-list li.series-section-item > a"
override fun popularMangaFromElement(element: Element): SManga = SManga.create().apply {
title = element.select("h5.series-title").text()
thumbnail_url = element.select("div.thumb img").attr("data-src")
setUrlWithoutDomain(element.attr("href"))
}
override fun getCollections(): List<Collection> = listOf(
Collection("連載一覧", "")
)
}
| apache-2.0 | 9c1a744eee7c20490cf707a63f383d22 | 30.529412 | 101 | 0.70056 | 3.801418 | false | false | false | false |
anlun/haskell-idea-plugin | plugin/src/org/jetbrains/grammar/dumb/Rule.kt | 1 | 2045 | package org.jetbrains.grammar.dumb
import com.intellij.psi.tree.IElementType
import java.util.ArrayList
import java.util.HashSet
class Rule(public val name : String,
public val variants : List<Variant>,
public val left : List<Variant>) {
public var done : Boolean = false;
public var canBeEmpty : Boolean = false;
public var first : Set<IElementType>? = null;
override fun toString() : String {
val n = name + ":\n"
val v = " variants: ${variants}\n"
val l = if (left.isNotEmpty()) " left: ${left}\n" else ""
return n + v + l
}
fun makeAnalysis(grammar : Map<String, Rule>) {
if (done) {
return
}
for (variant in variants) {
variant.makeAnalysis(grammar)
}
for (variant in variants) {
canBeEmpty = canBeEmpty || variant.isCanBeEmpty()
}
val result = HashSet<IElementType>()
for (variant in variants) {
if (variant is NonTerminalVariant) {
if (variant.first != null) {
result.addAll(variant.first!!)
} else {
return
}
}
}
if (canBeEmpty) {
for (lVariant in left) {
val next = (lVariant as NonTerminalVariant).next
for (variant in next) {
val term = (variant as NonTerminalVariant).term
if (term is Terminal){
result.add(term.tokenType)
} else {
variant.makeAnalysis(grammar)
result.addAll(variant.first!!)
}
}
}
}
first = HashSet(result)
}
fun makeDeepAnalysis(grammar: Map<String, Rule>) {
for (variant in variants) {
variant.makeDeepAnalysis(grammar)
}
for (variant in left) {
variant.makeDeepAnalysis(grammar)
}
}
} | apache-2.0 | 4053da06409577f4117589b851e86652 | 27.027397 | 67 | 0.500733 | 4.811765 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/cache/submission/dao/SubmissionDaoImpl.kt | 2 | 5419 | package org.stepik.android.cache.submission.dao
import android.content.ContentValues
import android.database.Cursor
import com.google.gson.GsonBuilder
import org.stepic.droid.jsonHelpers.adapters.UTCDateAdapter
import org.stepic.droid.jsonHelpers.deserializers.FeedbackDeserializer
import org.stepic.droid.jsonHelpers.deserializers.ReplyDeserializer
import org.stepic.droid.jsonHelpers.serializers.ReplySerializer
import org.stepic.droid.storage.dao.DaoBase
import org.stepic.droid.storage.operations.DatabaseOperations
import org.stepic.droid.util.getInt
import org.stepic.droid.util.getLong
import org.stepic.droid.util.getString
import org.stepic.droid.util.toObject
import org.stepik.android.cache.submission.structure.DbStructureSubmission
import org.stepik.android.model.ReplyWrapper
import org.stepik.android.model.Submission
import org.stepik.android.model.feedback.Feedback
import java.util.Date
import javax.inject.Inject
class SubmissionDaoImpl
@Inject
constructor(
databaseOperations: DatabaseOperations
) : DaoBase<Submission>(databaseOperations) {
private val utcDateAdapter = UTCDateAdapter()
private val gson = GsonBuilder()
.enableComplexMapKeySerialization()
.registerTypeAdapter(ReplyWrapper::class.java, ReplyDeserializer())
.registerTypeAdapter(ReplyWrapper::class.java, ReplySerializer())
.registerTypeAdapter(Date::class.java, utcDateAdapter)
.registerTypeAdapter(Feedback::class.java, FeedbackDeserializer())
.create()
override fun getDbName(): String =
DbStructureSubmission.TABLE_NAME
override fun getDefaultPrimaryColumn(): String =
DbStructureSubmission.Columns.ATTEMPT_ID
override fun getDefaultPrimaryValue(persistentObject: Submission): String =
persistentObject.attempt.toString()
override fun parsePersistentObject(cursor: Cursor): Submission =
Submission(
id = cursor.getLong(DbStructureSubmission.Columns.ID),
status = Submission.Status.values()[cursor.getInt(DbStructureSubmission.Columns.STATUS)],
score = cursor.getString(DbStructureSubmission.Columns.SCORE),
hint = cursor.getString(DbStructureSubmission.Columns.HINT),
time = cursor.getString(DbStructureSubmission.Columns.TIME)?.let(utcDateAdapter::stringToDate),
_reply = cursor.getString(DbStructureSubmission.Columns.REPLY)?.toObject(gson),
attempt = cursor.getLong(DbStructureSubmission.Columns.ATTEMPT_ID),
session = cursor.getString(DbStructureSubmission.Columns.SESSION)?.toLongOrNull(),
eta = cursor.getString(DbStructureSubmission.Columns.ETA),
feedback = cursor.getString(DbStructureSubmission.Columns.FEEDBACK)?.toObject(gson)
)
override fun getContentValues(persistentObject: Submission): ContentValues =
ContentValues().apply {
put(DbStructureSubmission.Columns.ID, persistentObject.id)
put(DbStructureSubmission.Columns.STATUS, persistentObject.status?.ordinal)
put(DbStructureSubmission.Columns.SCORE, persistentObject.score)
put(DbStructureSubmission.Columns.HINT, persistentObject.hint)
put(DbStructureSubmission.Columns.TIME, persistentObject.time?.let(utcDateAdapter::dateToString))
put(DbStructureSubmission.Columns.REPLY, persistentObject.reply?.let(gson::toJson))
put(DbStructureSubmission.Columns.ATTEMPT_ID, persistentObject.attempt)
put(DbStructureSubmission.Columns.SESSION, persistentObject.session?.toString())
put(DbStructureSubmission.Columns.ETA, persistentObject.eta)
put(DbStructureSubmission.Columns.FEEDBACK, persistentObject.feedback?.let(gson::toJson))
}
override fun insertOrReplace(persistentObject: Submission) {
executeSql("""
INSERT OR REPLACE INTO ${DbStructureSubmission.TABLE_NAME} (
${DbStructureSubmission.Columns.ID},
${DbStructureSubmission.Columns.STATUS},
${DbStructureSubmission.Columns.SCORE},
${DbStructureSubmission.Columns.HINT},
${DbStructureSubmission.Columns.TIME},
${DbStructureSubmission.Columns.REPLY},
${DbStructureSubmission.Columns.ATTEMPT_ID},
${DbStructureSubmission.Columns.SESSION},
${DbStructureSubmission.Columns.ETA},
${DbStructureSubmission.Columns.FEEDBACK}
)
SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
WHERE NOT EXISTS (
SELECT * FROM ${DbStructureSubmission.TABLE_NAME}
WHERE ${DbStructureSubmission.Columns.ID} > ? AND ${DbStructureSubmission.Columns.ATTEMPT_ID} = ?
)
""".trimIndent(),
arrayOf(
persistentObject.id,
persistentObject.status?.ordinal,
persistentObject.score,
persistentObject.hint,
persistentObject.time?.let(utcDateAdapter::dateToString),
persistentObject.reply?.let(gson::toJson),
persistentObject.attempt,
persistentObject.session,
persistentObject.eta,
persistentObject.feedback?.let(gson::toJson),
persistentObject.id,
persistentObject.attempt
)
)
}
} | apache-2.0 | 25de8aabcc3bae6fba1660a0c80c15de | 47.828829 | 113 | 0.69773 | 5.180688 | false | false | false | false |
pkleimann/livingdoc | livingdoc-engine/src/main/kotlin/org/livingdoc/engine/reporting/HtmlReportRenderer.kt | 3 | 1820 | package org.livingdoc.engine.reporting
import org.livingdoc.engine.execution.DocumentResult
import org.livingdoc.engine.execution.Result
import org.livingdoc.engine.execution.examples.decisiontables.model.DecisionTableResult
import org.livingdoc.engine.execution.examples.scenarios.model.ScenarioResult
class HtmlReportRenderer {
private val renderContext = HtmlRenderContext()
fun render(documentResult: DocumentResult): String {
val exampleResult = documentResult.results
val htmlResults = exampleResult.map { result ->
when (result) {
is DecisionTableResult -> handleDecisionTableResult(result)
is ScenarioResult -> handleScenarioResult(result)
else -> throw IllegalArgumentException("Unknown ExampleResult type.")
}
}
return HtmlReportTemplate().renderTemplate(htmlResults, renderContext)
}
private fun handleDecisionTableResult(decisionTableResult: DecisionTableResult): HtmlTable {
val (headers, rows, tableResult) = decisionTableResult
return table(renderContext, tableResult, headers.size) {
headers(headers)
rows(rows)
}
}
private fun handleScenarioResult(scenarioResult: ScenarioResult): HtmlList {
return list {
steps(scenarioResult.steps)
}
}
private fun table(
renderContext: HtmlRenderContext,
tableResult: Result,
columnCount: Int,
block: HtmlTable.() -> Unit
): HtmlTable {
val table = HtmlTable(renderContext, tableResult, columnCount)
table.block()
return table
}
private fun list(block: HtmlList.() -> Unit): HtmlList {
val htmlList = HtmlList()
htmlList.block()
return htmlList
}
}
| apache-2.0 | f7137e434db4593d377f919c4acee0cb | 31.5 | 96 | 0.673077 | 4.932249 | false | false | false | false |
Commit451/GitLabAndroid | app/src/main/java/com/commit451/gitlab/viewHolder/GroupViewHolder.kt | 2 | 1699 | package com.commit451.gitlab.viewHolder
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.recyclerview.widget.RecyclerView
import coil.api.load
import com.commit451.addendum.recyclerview.bindView
import com.commit451.gitlab.R
import com.commit451.gitlab.model.api.Group
import com.commit451.gitlab.model.api.VISIBILITY_PUBLIC
import com.github.ivbaranov.mli.MaterialLetterIcon
/**
* View associated with a group
*/
class GroupViewHolder(view: View) : RecyclerView.ViewHolder(view) {
companion object {
fun inflate(parent: ViewGroup): GroupViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_group, parent, false)
return GroupViewHolder(view)
}
}
val image: ImageView by bindView(R.id.image)
private val iconLetter: MaterialLetterIcon by bindView(R.id.letter)
private val textName: TextView by bindView(R.id.name)
fun bind(group: Group, @ColorInt color: Int) {
textName.text = group.name
if (group.avatarUrl.isNullOrBlank() || group.visibility != VISIBILITY_PUBLIC) {
image.visibility = View.GONE
iconLetter.visibility = View.VISIBLE
iconLetter.letter = group.name!!.substring(0, 1)
iconLetter.letterColor = Color.WHITE
iconLetter.shapeColor = color
} else {
iconLetter.visibility = View.GONE
image.visibility = View.VISIBLE
image.load(group.avatarUrl)
}
}
}
| apache-2.0 | 1e508434c3bad8861a2e28cc4de0266a | 32.313725 | 87 | 0.702766 | 4.226368 | false | false | false | false |
spkingr/50-android-kotlin-projects-in-100-days | ProjectService/app/src/main/java/me/liuqingwen/android/projectservice/APIService.kt | 1 | 3191 | package me.liuqingwen.android.projectservice
import com.google.gson.annotations.SerializedName
import io.reactivex.Observable
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
/**
* Created by Qingwen on 2018-5-14, project: ProjectService.
*
* @Author: Qingwen
* @DateTime: 2018-5-14
* @Package: me.liuqingwen.android.projectservice in project: ProjectService
*
* Notice: If you are using this class or file, check it and do some modification.
*/
private const val DOUBAN_BASE_URL = "https://api.douban.com/"
object APIService
{
private val retrofit = Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(DOUBAN_BASE_URL)
.build()
private val movieService = this.retrofit.create(IMovieService::class.java)
fun getTopObservable(start:Int = 0, count:Int = 20) = this.movieService.getTop250(start = start, count = count)
fun getOnShowObservable(city: String) = this.movieService.getOnShowByCity(city = city)
fun getComingSoonObservable(start: Int = 0, count: Int = 20) = this.movieService.getComingSoonOnes(start = start, count = count)
}
interface IMovieService
{
@GET("v2/movie/top250")
fun getTop250(@Query("start") start:Int, @Query("count") count:Int): Observable<MovieResponse>
@GET("/v2/movie/in_theaters")
fun getOnShowByCity(@Query("city") city: String = "北京"): Observable<MovieResponse>
@GET("/v2/movie/coming_soon")
fun getComingSoonOnes(@Query("start") start: Int, @Query("count") count: Int): Observable<MovieResponse>
}
data class MovieResponse(val count: Int, val start: Int, val total: Int, val title: String, val subjects: List<Movie>)
data class Movie(val id: String, val year: String, val images: SizedImage, val genres: List<String>,
@SerializedName("original_title") val originalTitle: String,
@SerializedName("title") val TranslationTitle: String,
@SerializedName("alt") val webUrl: String,
@SerializedName("casts") val movieStars: List<MovieStar>,
@SerializedName("directors") val movieDirectors: List<MovieStar>)
//aka: List<String>, ratings_count: Int, comments_count: Int, subtype: String, summary: String, current_season: Object,
// collect_count: Int, countries: List<String>, episodes_count: Object, schedule_url: String, seasons_count: Object, share_url: String, do_count: Object,
// , douban_site: String, wish_count: Int, reviews_count: Int, rating: Rating(val max:Int, val average:Int, val stars:String, val min:Int)
data class MovieStar(val id: String, val name: String,
@SerializedName("alt") val link: String,
@SerializedName("avatars") val image: SizedImage)
data class SizedImage(@SerializedName("small") val smallImage: String,
@SerializedName("medium") val mediumImage: String,
@SerializedName("large") val largeImage: String)
| mit | a05c2a3bd14fbe5434dbdbe0c40c9620 | 46.567164 | 153 | 0.702542 | 3.934568 | false | false | false | false |
raidarar/learn | src/main/kotlin/org/raidarar/learn/MemoryCache.kt | 1 | 600 | package org.raidarar.learn
import com.sun.jna.Memory
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap
object MemoryCache {
const val CACHE_BYTE_MAX = 512
private val map = ThreadLocal.withInitial { Int2ObjectArrayMap<Memory>(64) }
operator fun get(size: Int, clear: Boolean = false): Memory {
val map = map.get()
var memory = map.get(size)
if (memory == null) {
memory = Memory(size.toLong())
if (size <= CACHE_BYTE_MAX)
map.put(size, memory)
} else if (clear) memory.clear()
return memory
}
} | apache-2.0 | ac9a3bf81807f8820f52b6ba9682e161 | 24.041667 | 80 | 0.613333 | 3.821656 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.