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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
JetBrains/kotlin-native | runtime/src/main/kotlin/kotlin/native/internal/FloatingPointParser.kt | 2 | 13187 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.native.internal
import kotlin.comparisons.*
/**
* Takes a String and an integer exponent. The String should hold a positive
* integer value (or zero). The exponent will be used to calculate the
* floating point number by taking the positive integer the String
* represents and multiplying by 10 raised to the power of the
* exponent. Returns the closest double value to the real number.
* @param s the String that will be parsed to a floating point
* @param e an int represent the 10 to part
* @return the double closest to the real number
* @exception NumberFormatException if the String doesn't represent a positive integer value
*/
@SymbolName("Kotlin_native_FloatingPointParser_parseDoubleImpl")
private external fun parseDoubleImpl(s: String, e: Int): Double
/**
* Takes a String and an integer exponent. The String should hold a positive
* integer value (or zero). The exponent will be used to calculate the
* floating point number by taking the positive integer the String
* represents and multiplying by 10 raised to the power of the
* exponent. Returns the closest float value to the real number.
* @param s the String that will be parsed to a floating point
* @param e an int represent the 10 to part
* @return the float closest to the real number
* @exception NumberFormatException if the String doesn't represent a positive integer value
*/
@SymbolName("Kotlin_native_FloatingPointParser_parseFloatImpl")
private external fun parseFloatImpl(s: String, e: Int): Float
/**
* Used to parse a string and return either a single or double precision
* floating point number.
*/
object FloatingPointParser {
/*
* All number with exponent larger than MAX_EXP can be treated as infinity.
* All number with exponent smaller than MIN_EXP can be treated as zero.
* Exponent is 10 based.
* Eg. double's min value is 5e-324, so double "1e-325" should be parsed as 0.0
*/
private val FLOAT_MIN_EXP = -46
private val FLOAT_MAX_EXP = 38
private val DOUBLE_MIN_EXP = -324
private val DOUBLE_MAX_EXP = 308
private class StringExponentPair(var s: String, var e: Int, var negative: Boolean)
/**
* Takes a String and does some initial parsing. Should return a
* StringExponentPair containing a String with no leading or trailing white
* space and trailing zeroes eliminated. The exponent of the
* StringExponentPair will be used to calculate the floating point number by
* taking the positive integer the String represents and multiplying by 10
* raised to the power of the exponent.
* @param string the String that will be parsed to a floating point
* @return a StringExponentPair with necessary values
* @exception NumberFormatException if the String doesn't pass basic tests
*/
private fun initialParse(string: String): StringExponentPair {
var s = string
var length = s.length
var negative = false
var c: Char
var start: Int
var end: Int
val decimal: Int
var shift: Int
var e = 0
start = 0
if (length == 0)
throw NumberFormatException(s)
c = s[length - 1]
if (c == 'D' || c == 'd' || c == 'F' || c == 'f') {
length--
if (length == 0)
throw NumberFormatException(s)
}
end = maxOf(s.indexOf('E'), s.indexOf('e'))
if (end > -1) {
if (end + 1 == length)
throw NumberFormatException(s)
var exponent_offset = end + 1
if (s[exponent_offset] == '+') {
if (s[exponent_offset + 1] == '-') {
throw NumberFormatException(s)
}
exponent_offset++ // skip the plus sign
if (exponent_offset == length)
throw NumberFormatException(s)
}
val strExp = s.substring(exponent_offset, length)
try {
e = strExp.toInt()
} catch (ex: NumberFormatException) {
// strExp is not empty, so there are 2 situations the exception be thrown
// if the string is invalid we should throw exception, if the actual number
// is out of the range of Integer, we can still parse the original number to
// double or float.
var ch: Char
for (i in 0..strExp.length - 1) {
ch = strExp[i]
if (ch < '0' || ch > '9') {
if (i == 0 && ch == '-')
continue
// ex contains the exponent substring only so throw
// a new exception with the correct string.
throw NumberFormatException(s)
}
}
e = if (strExp[0] == '-') Int.MIN_VALUE else Int.MAX_VALUE
}
} else {
end = length
}
if (length == 0)
throw NumberFormatException(s)
c = s[start]
if (c == '-') {
++start
--length
negative = true
} else if (c == '+') {
++start
--length
}
if (length == 0)
throw NumberFormatException(s)
decimal = s.indexOf('.')
if (decimal > -1) {
shift = end - decimal - 1
// Prevent e overflow, shift >= 0.
if (e >= 0 || e - Int.MIN_VALUE > shift) {
e -= shift
}
s = s.substring(start, decimal) + s.substring(decimal + 1, end)
} else {
s = s.substring(start, end)
}
length = s.length
if (length == 0)
throw NumberFormatException()
end = length
while (end > 1 && s[end - 1] == '0')
--end
start = 0
while (start < end - 1 && s[start] == '0')
start++
if (end != length || start != 0) {
shift = length - end
if (e <= 0 || Int.MAX_VALUE - e > shift) {
e += shift
}
s = s.substring(start, end)
}
// Trim the length of very small numbers, natives can only handle down to E-309.
val APPROX_MIN_MAGNITUDE = -359
val MAX_DIGITS = 52
length = s.length
if (length > MAX_DIGITS && e < APPROX_MIN_MAGNITUDE) {
val d = minOf(APPROX_MIN_MAGNITUDE - e, length - 1)
s = s.substring(0, length - d)
e += d
}
return StringExponentPair(s, e, negative)
}
/*
* Assumes the string is trimmed.
*/
private fun parseDoubleName(namedDouble: String, length: Int): Double {
// Valid strings are only +Nan, NaN, -Nan, +Infinity, Infinity, -Infinity.
if (length != 3 && length != 4 && length != 8 && length != 9) {
throw NumberFormatException()
}
var negative = false
var cmpstart = 0
when (namedDouble[0]) {
'-' -> {
negative = true
cmpstart = 1
}
'+' -> cmpstart = 1
}
if (namedDouble.regionMatches(cmpstart, "Infinity", 0, 8, ignoreCase = false)) {
return if (negative)
Double.NEGATIVE_INFINITY
else
Double.POSITIVE_INFINITY
}
if (namedDouble.regionMatches(cmpstart, "NaN", 0, 3, ignoreCase = false)) {
return Double.NaN
}
throw NumberFormatException()
}
/*
* Assumes the string is trimmed.
*/
private fun parseFloatName(namedFloat: String, length: Int): Float {
// Valid strings are only +Nan, NaN, -Nan, +Infinity, Infinity, -Infinity.
if (length != 3 && length != 4 && length != 8 && length != 9) {
throw NumberFormatException()
}
var negative = false
var cmpstart = 0
when (namedFloat[0]) {
'-' -> {
negative = true
cmpstart = 1
}
'+' -> cmpstart = 1
}
if (namedFloat.regionMatches(cmpstart, "Infinity", 0, 8, ignoreCase = false)) {
return if (negative) Float.NEGATIVE_INFINITY else Float.POSITIVE_INFINITY
}
if (namedFloat.regionMatches(cmpstart, "NaN", 0, 3, ignoreCase = false)) {
return Float.NaN
}
throw NumberFormatException()
}
/*
* Answers true if the string should be parsed as a hex encoding.
* Assumes the string is trimmed.
*/
private fun parseAsHex(s: String): Boolean {
val length = s.length
if (length < 2) {
return false
}
var first = s[0]
var second = s[1]
if (first == '+' || first == '-') {
// Move along.
if (length < 3) {
return false
}
first = second
second = s[2]
}
return first == '0' && (second == 'x' || second == 'X')
}
/**
* Returns the closest double value to the real number in the string.
*
* @param string the String that will be parsed to a floating point
* @return the double closest to the real number
* @exception NumberFormatException if the String doesn't represent a double
*/
fun parseDouble(string: String): Double {
var s = string
s = s.trim { it <= ' ' }
val length = s.length
if (length == 0) {
throw NumberFormatException(s)
}
// See if this could be a named double.
val last = s[length - 1]
if (last == 'y' || last == 'N') {
return parseDoubleName(s, length)
}
// See if it could be a hexadecimal representation.
if (parseAsHex(s)) {
return HexStringParser.parseDouble(s)
}
val info = initialParse(s)
// Two kinds of situation will directly return 0.0:
// 1. info.s is 0;
// 2. actual exponent is less than Double.MIN_EXPONENT.
if ("0" == info.s || info.e + info.s.length - 1 < DOUBLE_MIN_EXP) {
return if (info.negative) -0.0 else 0.0
}
// If actual exponent is larger than Double.MAX_EXPONENT, return infinity.
// Prevent overflow, check twice.
if (info.e > DOUBLE_MAX_EXP || info.e + info.s.length - 1 > DOUBLE_MAX_EXP) {
return if (info.negative) Double.NEGATIVE_INFINITY else Double.POSITIVE_INFINITY
}
var result = parseDoubleImpl(info.s, info.e)
if (info.negative)
result = -result
return result
}
/**
* Returns the closest float value to the real number in the string.
*
* @param s the String that will be parsed to a floating point
* @return the float closest to the real number
* @exception NumberFormatException if the String doesn't represent a float
*/
fun parseFloat(string: String): Float {
var s = string
s = s.trim { it <= ' ' }
val length = s.length
if (length == 0) {
throw NumberFormatException(s)
}
// See if this could be a named float.
val last = s[length - 1]
if (last == 'y' || last == 'N') {
return parseFloatName(s, length)
}
// See if it could be a hexadecimal representation.
if (parseAsHex(s)) {
return HexStringParser.parseFloat(s)
}
val info = initialParse(s)
// Two kinds of situation will directly return 0.0f.
// 1. info.s is 0;
// 2. actual exponent is less than Float.MIN_EXPONENT.
if ("0" == info.s || info.e + info.s.length - 1 < FLOAT_MIN_EXP) {
return if (info.negative) -0.0f else 0.0f
}
// If actual exponent is larger than Float.MAX_EXPONENT, return infinity.
// Prevent overflow, check twice.
if (info.e > FLOAT_MAX_EXP || info.e + info.s.length - 1 > FLOAT_MAX_EXP) {
return if (info.negative) Float.NEGATIVE_INFINITY else Float.POSITIVE_INFINITY
}
var result = parseFloatImpl(info.s, info.e)
if (info.negative)
result = -result
return result
}
} | apache-2.0 | 329a5657823a4ba5e1827c27107bacee | 33.614173 | 92 | 0.561614 | 4.356459 | false | false | false | false |
vovagrechka/fucking-everything | attic/photlin/src/photlinc/shebang.kt | 1 | 4272 | package photlinc
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.js.backend.ast.*
import org.jetbrains.kotlin.descriptors.impl.PackageFragmentDescriptorImpl
import org.jetbrains.kotlin.js.facade.K2JSTranslator
import org.jetbrains.kotlin.js.translate.context.StaticContext
import org.jetbrains.kotlin.js.translate.context.TranslationContext
import org.jetbrains.kotlin.js.util.AstUtil
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedValueArgument
import org.jetbrains.kotlin.types.KotlinType
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
import photlin.*
import vgrechka.*
val KotlinType.typeName: String? get() {
// TODO:vgrechka More than two levels of containment
val classifierDescriptor = this.constructor.declarationDescriptor!!
val name = classifierDescriptor.name
if (name.isSpecial) return null
val fuck = name.identifier
val containingDeclaration = classifierDescriptor.containingDeclaration
val isRoot = (containingDeclaration as? PackageFragmentDescriptorImpl)?.fqName?.isRoot ?: false
return when {
isRoot -> fuck
else -> containingDeclaration.name.identifier + "." + fuck
}
}
val JsNode.kotlinTypeName: String? get() {
this.forcedKotlinTypeName?.let {return it}
this.kotlinType?.let {return it.typeName}
val valueDescriptor = this.valueDescriptor
if (valueDescriptor != null) {
return valueDescriptor.type.typeName
}
val expr = this.ktExpression
if (expr != null) {
val exprTypeInfo = StaticContext.current.bindingContext.get(BindingContext.EXPRESSION_TYPE_INFO, expr)
if (exprTypeInfo != null) {
val type = exprTypeInfo.type
if (type != null) {
return type.typeName
}
}
}
return null
}
object PhotlincDebugGlobal {
private var puid = 1L
val breakOnDebugTag: String = "1437"
// val breakOnDebugTag: String = "6607"
val breakOnPizdavalue: String = "58248"
fun nextDebugTag(): String {
return (puid++).toString()
}
fun taggedShitCreated(shit: DebugTagged) {
// @debug
if (shit.debugTag == breakOnDebugTag) {
"break on me"
}
}
}
// @extension-properties
var Any.beingDebugged by AttachedShit<Boolean?>()
var ClassDescriptor.phpClass by AttachedShit<PHPClass>()
var ClassDescriptor.phpSuperPrototypeNameRef by AttachedShit<JsNameRef?>()
var PHPClass.classDescriptor by AttachedShit<ClassDescriptor>()
var JsNode.ktExpression by AttachedShit<KtExpression?>()
var JsNode.kotlinType by AttachedShit<KotlinType?>()
var JsNode.forcedKotlinTypeName by AttachedShit<String?>()
var JsNode.declarationDescriptor by AttachedShit<DeclarationDescriptor?>()
var JsNode.callableDescriptor by AttachedShit<CallableDescriptor?>()
var JsNode.valueDescriptor by AttachedShit<ValueDescriptor?>()
var JsNode.translationContext by AttachedShit<TranslationContext?>()
var JsVars.JsVar.propertyDescriptor by AttachedShit<PropertyDescriptor?>()
var JsNameRef.additionalArgDescriptors by AttachedShit<List<DeclarationDescriptor>?>()
var JsNode.valueParameterDescriptor by AttachedShit<ValueParameterDescriptor?>()
class AttachedShit<T> : ReadWriteProperty<Any, T> {
data class Key(val obj: Any, val prop: String)
override fun getValue(thisRef: Any, property: KProperty<*>): T {
@Suppress("UNCHECKED_CAST")
return K2JSTranslator.current.shitToShit[Key(thisRef, property.name)] as T
}
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
K2JSTranslator.current.shitToShit[Key(thisRef, property.name)] = value
}
}
interface DebugTagged {
val debugTag: String?
}
fun addFieldToPHPClass(context: TranslationContext, classDescriptor: ClassDescriptor, name: String, initExpression: JsExpression?) {
val scope = context.getScopeForDescriptor(classDescriptor)
val phpClass = classDescriptor.phpClass
phpClass.statements += JsVars(JsVars.JsVar(scope.declareName(name), initExpression)-{o->
o.visibility = "private"
})
}
| apache-2.0 | 38959fcfaf767576e4e6c60bdb4d454a | 34.305785 | 132 | 0.744616 | 4.404124 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/klib/KotlinNativeLibrariesDependencySubstitutor.kt | 1 | 7767 | // 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.gradleJava.configuration.klib
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.roots.DependencyScope
import com.intellij.openapi.util.IntellijInternalApi
import com.intellij.openapi.util.Key
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
import org.jetbrains.kotlin.idea.gradleTooling.KotlinDependency
import org.jetbrains.kotlin.idea.gradleTooling.KotlinMPPGradleModel
import org.jetbrains.kotlin.idea.gradle.configuration.buildClasspathData
import org.jetbrains.kotlin.idea.gradle.configuration.klib.KlibInfo
import org.jetbrains.kotlin.idea.gradle.configuration.klib.KlibInfoProvider
import org.jetbrains.kotlin.idea.gradle.configuration.klib.KotlinNativeLibraryNameUtil
import org.jetbrains.kotlin.idea.gradle.configuration.mpp.KotlinDependenciesPreprocessor
import org.jetbrains.kotlin.idea.gradleJava.KotlinGradleFacadeImpl
import org.jetbrains.kotlin.konan.library.KONAN_STDLIB_NAME
import org.jetbrains.plugins.gradle.ExternalDependencyId
import org.jetbrains.plugins.gradle.model.*
import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext
import java.io.File
// KT-29613, KT-29783
internal class KotlinNativeLibrariesDependencySubstitutor(
private val mppModel: KotlinMPPGradleModel,
private val gradleModule: IdeaModule,
private val resolverCtx: ProjectResolverContext
) : KotlinDependenciesPreprocessor {
override fun invoke(dependencies: Iterable<KotlinDependency>): List<KotlinDependency> {
return substituteDependencies(dependencies.toList())
}
// Substitutes `ExternalDependency` entries that represent KLIBs with new dependency entries with proper type and name:
// - every `FileCollectionDependency` is checked whether it points to an existing KLIB, and substituted if it is
// - similarly for every `ExternalLibraryDependency` with `groupId == "Kotlin/Native"` (legacy KLIB provided by Gradle plugin <= 1.3.20)
private fun substituteDependencies(dependencies: Collection<ExternalDependency>): List<ExternalDependency> {
val result = ArrayList(dependencies)
for (i in 0 until result.size) {
val dependency = result[i]
val dependencySubstitute = when (dependency) {
is FileCollectionDependency -> getFileCollectionDependencySubstitute(dependency)
else -> DependencySubstitute.NoSubstitute
}
val newDependency = (dependencySubstitute as? DependencySubstitute.YesSubstitute)?.substitute ?: continue
result[i] = newDependency
}
return result
}
private val ProjectResolverContext.dependencySubstitutionCache
get() = getUserData(KLIB_DEPENDENCY_SUBSTITUTION_CACHE) ?: putUserDataIfAbsent(KLIB_DEPENDENCY_SUBSTITUTION_CACHE, HashMap())
private val klibInfoProvider: KlibInfoProvider? by lazy {
val kotlinNativeHome = mppModel.kotlinNativeHome.takeIf { it != KotlinMPPGradleModel.NO_KOTLIN_NATIVE_HOME }?.let(::File)
if (kotlinNativeHome == null) {
LOG.warn(
"""
Can't obtain Kotlin/Native home path in Kotlin Gradle plugin.
${KotlinMPPGradleModel::class.java.simpleName} is $mppModel.
${KotlinNativeLibrariesDependencySubstitutor::class.java.simpleName} will run in idle mode. No dependencies will be substituted.
""".trimIndent()
)
null
} else
KlibInfoProvider.create(kotlinNativeHome = kotlinNativeHome)
}
private val kotlinVersion: IdeKotlinVersion? by lazy {
// first, try to figure out Kotlin plugin version by classpath (the default approach)
val classpathData = buildClasspathData(gradleModule, resolverCtx)
val versionFromClasspath = KotlinGradleFacadeImpl.findKotlinPluginVersion(classpathData)
if (versionFromClasspath == null) {
// then, examine Kotlin MPP Gradle model
val versionFromModel = mppModel.targets
.asSequence()
.flatMap { it.compilations.asSequence() }
.mapNotNull { it.kotlinTaskProperties.pluginVersion?.takeIf(String::isNotBlank) }
.firstOrNull()
?.let(IdeKotlinVersion::opt) // Wasn't moved inside 'mapNotNull()' intentionally to get more stable behavior
if (versionFromModel == null) {
LOG.warn(
"""
Can't obtain Kotlin Gradle plugin version for ${gradleModule.name} module.
Build classpath is ${classpathData.classpathEntries.flatMap { it.classesFile }}.
${KotlinMPPGradleModel::class.java.simpleName} is $mppModel.
${KotlinNativeLibrariesDependencySubstitutor::class.java.simpleName} will run in idle mode. No dependencies will be substituted.
""".trimIndent()
)
null
} else
versionFromModel
} else
versionFromClasspath
}
private fun getFileCollectionDependencySubstitute(dependency: FileCollectionDependency): DependencySubstitute =
resolverCtx.dependencySubstitutionCache.getOrPut(dependency.id) {
val libraryFile = dependency.files.firstOrNull() ?: return@getOrPut DependencySubstitute.NoSubstitute
buildSubstituteIfNecessary(libraryFile)
}
private fun buildSubstituteIfNecessary(libraryFile: File): DependencySubstitute {
// need to check whether `library` points to a real KLIB,
// and if answer is yes then build a new dependency that will substitute original one
val klib = klibInfoProvider?.getKlibInfo(libraryFile) ?: return DependencySubstitute.NoSubstitute
val substitute = DefaultExternalMultiLibraryDependency().apply {
classpathOrder = if (klib.libraryName == KONAN_STDLIB_NAME) -1 else 0 // keep stdlib upper
name = klib.ideName(kotlinVersion)
packaging = DEFAULT_PACKAGING
files += klib.path
sources += klib.sourcePaths
scope = DependencyScope.PROVIDED.name
}
return DependencySubstitute.YesSubstitute(substitute)
}
companion object {
private const val DEFAULT_PACKAGING = "jar"
private val LOG = Logger.getInstance(KotlinNativeLibrariesDependencySubstitutor::class.java)
private val KLIB_DEPENDENCY_SUBSTITUTION_CACHE =
Key.create<MutableMap<ExternalDependencyId, DependencySubstitute>>("KLIB_DEPENDENCY_SUBSTITUTION_CACHE")
}
}
private sealed class DependencySubstitute {
object NoSubstitute : DependencySubstitute()
class YesSubstitute(val substitute: ExternalMultiLibraryDependency) : DependencySubstitute()
}
/**
* Library Name formatted for the IDE.
*/
@IntellijInternalApi
fun KlibInfo.ideName(kotlinVersion: IdeKotlinVersion? = null): String = buildString {
if (isFromNativeDistribution) {
append(KotlinNativeLibraryNameUtil.KOTLIN_NATIVE_LIBRARY_PREFIX)
if (kotlinVersion != null) append(" ${kotlinVersion.rawVersion} - ") else append(" ")
}
append(libraryName)
if (isStdlib) return@buildString
when (val targets = [email protected]) {
null -> Unit
is KlibInfo.NativeTargets.CommonizerIdentity -> append(" | [${targets.identityString}]")
is KlibInfo.NativeTargets.NativeTargetsList -> append(" | ${targets.nativeTargets}")
}
}
| apache-2.0 | cd440aca8f25cbcfdbbc6bc03f553eeb | 46.650307 | 158 | 0.709025 | 5.29809 | false | false | false | false |
jwren/intellij-community | tools/intellij.ide.starter/src/com/intellij/ide/starter/models/IdeInfo.kt | 1 | 2166 | package com.intellij.ide.starter.models
import com.intellij.ide.starter.system.SystemInfo
import com.intellij.ide.starter.teamcity.TeamCityCIServer
data class IdeInfo(
val productCode: String,
val platformPrefix: String,
val executableFileName: String,
val buildType: String,
val buildNumber: String? = null,
val tag: String? = null
) {
companion object {
fun new(
productCode: String,
platformPrefix: String,
executableFileName: String,
jetBrainsCIBuildType: String,
buildNumber: String? = null,
tag: String? = null
): IdeInfo {
// TODO: deal later with custom build number on CI (shouldn't affect anyone outside JB for now)
if (TeamCityCIServer.isBuildRunningOnCI && tag == null) {
val paramBuildType = TeamCityCIServer.buildParams["intellij.installer.build.type"]
val paramBuildNumber = TeamCityCIServer.buildParams["intellij.installer.build.number"]
if (paramBuildType != null && paramBuildNumber != null) {
return IdeInfo(productCode, platformPrefix, executableFileName, paramBuildType, paramBuildNumber, null)
}
}
return IdeInfo(productCode, platformPrefix, executableFileName, jetBrainsCIBuildType, buildNumber, tag)
}
}
internal val installerFilePrefix
get() = when (productCode) {
"IU" -> "ideaIU"
"IC" -> "ideaIC"
"WS" -> "WebStorm"
"PS" -> "PhpStorm"
"DB" -> "datagrip"
"GO" -> "goland"
"RM" -> "RubyMine"
"PY" -> "pycharmPY"
else -> error("Unknown product code: $productCode")
}
internal val installerProductName
get() = when (productCode) {
"IU" -> "intellij"
"IC" -> "intellij.ce"
"RM" -> "rubymine"
"PY" -> "pycharm"
else -> installerFilePrefix
}
internal val installerFileExt
get() = when {
SystemInfo.isWindows -> ".win.zip"
SystemInfo.isLinux -> ".tar.gz"
SystemInfo.isMac -> when (System.getProperty("os.arch")) {
"x86_64" -> ".dmg"
"aarch64" -> "-aarch64.dmg"
else -> error("Unknown architecture of Mac OS")
}
else -> error("Unknown OS")
}
}
| apache-2.0 | b721d63de94a56f731001c902fd8f387 | 30.391304 | 113 | 0.635272 | 4.079096 | false | false | false | false |
androidx/androidx | compose/ui/ui-lint/src/test/java/androidx/compose/ui/lint/UiStubs.kt | 3 | 12584 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.lint
import androidx.compose.lint.test.compiledStub
import com.android.tools.lint.checks.infrastructure.TestFile
object UiStubs {
val Density: TestFile = compiledStub(
filename = "Density.kt",
filepath = "androidx/compose/ui/unit",
checksum = 0x8c5922ca,
"""
package androidx.compose.ui.unit
interface Density
""",
"""
META-INF/main.kotlin_module:
H4sIAAAAAAAAAH2NSwrCMBCGR0SErCToVrC4UsghtFakG0EvEJqxBmomJBOo
tzfS7gQXw//6YABgCgCTfPNRQaDYamcCWdOrhl6eIqoHJWc0W3KqxcgpYJSr
Muj2PKQSGRumULNcVBROunmOS26Wd+1/OLEXxb83nX5TYjk7UJ/ho9j8wMkq
63xi5ck6xiDXtxQ9OmNdex2qy3evbJdtzQXs4AM20YY08QAAAA==
""",
"""
androidx/compose/ui/unit/Density.class:
H4sIAAAAAAAAAIVOTUvDQBB9s9Gmxq/UD6g38Qe4benNkyBCoCIoeMlpm6wy
Tbor3U2pt/4uD9KzP0rcqHdn4M17M/DefH69fwAY44Rwrky5sFyuZGHnr9Zp
2bBsDHt5o41j/xaDCOlMLZWslXmR99OZLnyMiNCbVNbXbOSd9qpUXl0RxHwZ
BW9qISZQFVYrbtUgsHJION2su4noi0SkgT33N+uRGFB7HBEuJv/9EzJASP7U
ZeWDeLTNotC3XGvC2UNjPM/1Ezue1vraGOuVZ2tcJ2RgC78lcPSDPRyHOQyW
26E7OaIMcYZuQOy0kGTYxV4OctjHQQ7hcOiQfgOBbqTCRAEAAA==
"""
)
val PointerEvent: TestFile = compiledStub(
filename = "PointerEvent.kt",
filepath = "androidx/compose/ui/input/pointer",
checksum = 0xbe2705da,
"""
package androidx.compose.ui.input.pointer
import androidx.compose.ui.unit.Density
interface AwaitPointerEventScope : Density
class PointerId(val value: Long)
class PointerInputChange(
val id: PointerId
)
""",
"""
META-INF/main.kotlin_module:
H4sIAAAAAAAAAH2NSwrCMBCGR0SErCToVrC4UsghtFakG0EvEJqxBmomJBOo
tzfS7gQXw//6YABgCgCTfPNRQaDYamcCWdOrhl6eIqoHJWc0W3KqxcgpYJSr
Muj2PKQSGRumULNcVBROunmOS26Wd+1/OLEXxb83nX5TYjk7UJ/ho9j8wMkq
63xi5ck6xiDXtxQ9OmNdex2qy3evbJdtzQXs4AM20YY08QAAAA==
""",
"""
androidx/compose/ui/input/pointer/AwaitPointerEventScope.class:
H4sIAAAAAAAAAJ1QTU8CMRB9syiL+AEoGrwZf4AFwsHoiURNSDAaSbxwKrvV
FJZ2Q2cRb/wuD4azP8rY1QsHTjbpm77Xzsybfn1/fALo4IRwKU08szpeiMhO
U+uUyLTQJs1YpFYbVjPRfZOaH//I7VwZHkQ2VSGIUB3LuRSJNK/iYTRWEYco
EM421cyMZnGjjNP8HmKbUOtPLCfaiHvFMpYsrwnBdF7wziiHkEATLy10zpr+
FLcI9dWyVA4aQb5LL43Vsh00Kb9rE676/x3Gtz7fmLzu2j+qrGdeTJhQHths
Fqk7nSjC6VNmWE/Vs3Z6lKiuMZYla2tc0VvEFghF5CtA/RePcOxjy+v+S1Aa
otDDTg9lj9jNYa+HfRwMQQ4VVIcIHGoOhz/oLRV0wgEAAA==
""",
"""
androidx/compose/ui/input/pointer/PointerId.class:
H4sIAAAAAAAAAJVQTW8SQRh+ZpZdlhVkQa0UP6r20mJ0aeNN06iNJhD8SGu4
cBrYSTsFZgk7S3rkt3j3YKIx8WCIR3+U8Z2FePJiMvPM+7zz5Hk/fv3+/gPA
E+wyPBQ6nicqvoxGyXSWpDLKVKT0LDPRLFHayHn0fv124iIYQ3ghFiKaCH0W
vRteyJEpwmHwnimtzBFDYa+732dw9vb7ZbgoBijAZ3AXYpJJBtYtI8CVEjjK
JDbnKmV41PuPJp4y+GfS9Nd+VKfLUOuNEzNROnojjYiFESTi04VDQzILRSo8
ptSlsqxNUXzAcLxa1gPe4AEPV8uADg9LAfedxmp5yNvsZaXuhbzJ287Pjx4P
Cye1v8wndbPgu6FnrQ4ZlUF10+GrhdTm8djQdMdJTC1We0rLt9l0KOcfxHBC
mXovGYlJX8yV5ZtkcJpk85F8rSzZPsm0UVPZV6mi3xdaJ0YYlegUB7S6gh0M
dbtJijjFLjzCu8SO4MBOGbS+odTa+YrK51yzQ2g1gI97hFuUIxWuogrkkXWj
XSKku/aKcm/AbX1B5dM/bcprwcaG436Od/CA3ud5ky6uDeB0cL2DG4TYsnCz
gwa2B2Apmrg1QDFFNcXtFEGOXoowRe0P2i862KkCAAA=
""",
"""
androidx/compose/ui/input/pointer/PointerInputChange.class:
H4sIAAAAAAAAAJVSXU8TURA9d9tul6XItogUUPwApRRxCyG+YIxKNGlSkYDh
hafb3Zty2+1dsnvb8Mhv8RdootH4YIiP/ijj7HYDgi+SbObMmcycmZ25v35/
/wFgE2sMm1z5USj9E9cL+8dhLNyBdKU6Hmj3OJRKi8jdHWEzCW4fcdURRTAG
p8uH3A2Iu+/aXeHpInIM5jOppH7O0Ki1/l/a31o5YFhshVHH7QrdjrhUscuV
CjXXMiR/J9Q7gyDYYjCkb8FiWOiFOpDK7Q77bqqieOA2lY6oVHpxETbDtHck
vF5Wu8sj3heUyLBca12dfuuvyH4i0qGZSihhwsY4bjDkagkvwLGRR5lh7Vr/
V4KFqTEYuMmQ10cyZnh6DYGL3dMGCh2hmz6DW1u51gwM5Va2tLdCc59rnuyz
P8zRa2CJKTKwHoVOZMIa5PnrDNtnpxXbqBq24Zyd2vSlvpWrnp1uGA32aqJi
Osac0cj9/GAaTn6vfM4syp7LWwXHTKQ2GLXBZDbQ66FQ+klPM8zvDZSWfdFU
QxnLdiBeXhyetrUd+oLKWlKJnUG/LaL3nHIYKq3Q48EBj2TCs+DSVa3zq18S
tffDQeSJNzKpmc1qDv7pjnW6WD7ZDirJAQkfETMJi4QGYYGYgWViLUKD0Fmt
jH3DZP0rKvXVL5j+lGbWyN5AjrJtJC9qkuwKxW6NaghngNQb9aln50gblVHF
bNbGRRIFCvXPmP54rm2mwfFUszRKyDQvT7ya2od4TPiConOUN3+IXBO3m7hD
FguJudvEPdw/BIvxAIuHKMaYibEUw4oxFcOMUY0x+wcqer7sSgQAAA==
"""
)
val PointerInputScope: TestFile = compiledStub(
filename = "SuspendingPointerInputFilter.kt",
filepath = "androidx/compose/ui/input/pointer",
checksum = 0xd7db138c,
"""
package androidx.compose.ui.input.pointer
import androidx.compose.ui.unit.Density
import androidx.compose.ui.Modifier
interface PointerInputScope : Density {
suspend fun <R> awaitPointerEventScope(
block: suspend AwaitPointerEventScope.() -> R
): R
}
fun Modifier.pointerInput(
key1: Any?,
block: suspend PointerInputScope.() -> Unit
): Modifier = Modifier
""",
"""
META-INF/main.kotlin_module:
H4sIAAAAAAAAAH2NSwrCMBCGR0SErCToVrC4UsghtFakG0EvEJqxBmomJBOo
tzfS7gQXw//6YABgCgCTfPNRQaDYamcCWdOrhl6eIqoHJWc0W3KqxcgpYJSr
Muj2PKQSGRumULNcVBROunmOS26Wd+1/OLEXxb83nX5TYjk7UJ/ho9j8wMkq
63xi5ck6xiDXtxQ9OmNdex2qy3evbJdtzQXs4AM20YY08QAAAA==
""",
"""
androidx/compose/ui/input/pointer/PointerInputScope.class:
H4sIAAAAAAAAAJ1T3U4TQRQ+s7vtLkV0WRULKGDBqDG4teoNJQSiEEqqkpZ4
w9V0uzRTtjPNzmyFu42P4oXPYLwwDd75Ir6F8Wx/AkJjjRdz5syZb84538w3
P359/QYAL+ABgeeU10PB6ieuJ1ptIX03Yi7j7Ui5bcG48kN3vz+XkmDVE23f
BELAbtIOdQPKG+67WtP3lAk6gaVR6SLOlPva55KpUxNSBGboB8rUIO92x+f9
vAQOHpWPhQoYd5udlnsUcU8xwaW7M/AKxeG+J0IRKcZ96b4SHJ2IJoDi4/Ll
vooEfq5X1q7GN8YVW18tj7+drZFUiqtjGl1fPagUN4pPRrQ1juPg6EimK2UR
Ntymr2ohZciFci4U7fN6GwUBrQU+wpb/BhMqQSJqetjIG1/ROlUUY1qro6N2
SGJMAuQYQycsWeXRqz8jEHfjXEbLav1h6ed+Muxu3HO6sXWU7cYFLU/2Nm1t
TtvVc4bVjW298NA25pYt4hiOlk87GcdKvF09bzppx8iSvJVPnX1Ka9bE7tnn
ze9fSDdOlnbm7KNmYMHZpI8CgZf/8HhXpI0McyPPXdQwgkiFQKoWCA/5O8Nr
OlcpgbX/lw7+onEqJ/gCsDBEbZ+opDHBhw0cnPbSLFYj2fZ5nfHGRaI7LED3
6bEiMFFlDU5VFOLfm69EWKHll3iHSYY62ToXBQrr8u4+DWnLx0R/wDJVEYWe
jyUw4+zgzPsr+dL4RmAgh3SiJYOACRbosIQrDSbgPs5p3M3gnMMxpeFiMoH2
rAbLPbsIKziXMXoNUjB1CHoJrpfgBlqwEzNdAgduHgKRcAtuH8KkhBkJdySY
ErISZiXMSZiXcFfCPQkLEqzfOHmKfRsFAAA=
""",
"""
androidx/compose/ui/input/pointer/SuspendingPointerInputFilterKt.class:
H4sIAAAAAAAAAK1VW08bVxD+ztrYi0OLs5QWDCW0OOGSkHWcSyMtQq1QIllx
aFqnvPB0vD5xDl6fY+0FkTfUn5JfUPUpykOE0rf+lv6GqHOWhZhAjVTF0s7O
5Zs5M3Nm1n9/ePsOwD08ZPiRq06oZefA9XV/oCPhJtKVapDE7kBLFYvQbSXR
QKiOVN1nx5qGMT+WAbFP4iIYQ3mP73M34Krr/tzeEz5pcwwTgyE8w2CledFh
T3VHvpAi9JqfBvGaPR0HUrl7+333RaL8WGoVuY8zru6tjg7I8M/nPnJj/cKA
Zxs23KaWrwfCWz8J6+tQJ7FUInK3tCIm4SbuxingNyVjb9O7eT6zzcvLXWrq
sOvuibgdcklpc6V0zI9L2NbxdhIEhKqOQhGEtwNBsMJG/FJGmzZKDAtDXUlr
UzxwGyoOyV/6URETDNP+S+H3smOe8ZD3BQEZllcu6PJHTcsE6XqrOxP4EpMl
fIEyw1g70H7PhsMwP6rmIr5iGN8iA1eUP8Po+66eIr0JfI1vxjGNGQanaiqt
np3Whcuane+JV3fI+Xx1DIuXTS7D1RPIUxHzDo856az+fo4WkxlSZGA9w1ik
P5CGqxHXoSMPjw6rpaPDkjVjpa8ykUw8fcpWZq48InPFqrE1eup22arkZ1gt
V18u5ytLNnPyjlUrOCXHTjm7VnQKToqojb1/XbDs8b/esKNDw5ZL73+38iXL
njV51BklStVnVQyXdv9/7chQ1/5jSzxzKxnk0UEsaPa0Ojn4+as0xrVRX6vb
PbrY/JbuCIbJJsXfTvptET43E29q0T4PdngojZwpx1uyq3ichMTP/ZpQMn3R
UPsykmT+6ePm0Fp9aj3dgTOwUksnoS8oIYo4m/nsnIuHO7CQh/kRDGMokFQj
6RfSm2GYWnOuvMHVW84U0T8xe4TpP8y0kCMITF9fTKJO/OIxHBXMpeGmMI9v
yW44BwvkcTf1K9IfwrGnTe/7xp7LBGpDSu0U+CClLn6gd5O01yi7xV3kGviu
ge+JYqmBKq43cAPLu2ARVrC6iysRxiLMRZiPsBbBiXAzwq0I66l4O0LhX/yB
0s2YBgAA
"""
)
val Alignment: TestFile = compiledStub(
filename = "Alignment.kt",
filepath = "androidx/compose/ui",
checksum = 0xd737b17c,
"""
package androidx.compose.ui
class Alignment {
companion object {
val TopStart = Alignment()
}
}
""",
"""
META-INF/main.kotlin_module:
H4sIAAAAAAAAAH2NSwrCMBCGR0SErCToVrC4UsghtFakG0EvEJqxBmomJBOo
tzfS7gQXw//6YABgCgCTfPNRQaDYamcCWdOrhl6eIqoHJWc0W3KqxcgpYJSr
Muj2PKQSGRumULNcVBROunmOS26Wd+1/OLEXxb83nX5TYjk7UJ/ho9j8wMkq
63xi5ck6xiDXtxQ9OmNdex2qy3evbJdtzQXs4AM20YY08QAAAA==
""",
"""
androidx/compose/ui/Alignment$Companion.class:
H4sIAAAAAAAAAJVTTW/TQBB96ziJ6waa9AP6AZTSQJNC67biVoRog5AipUVq
q1x6QBtnCZs468q7iXrMiR/CL4ATiAOKeuRHIcapaSuQKPgwO+/NvJlZj/39
x9dvAJ5ijWGFq2YUyuap54fdk1ALrye9nUC2VFcoU6wQyZUMVRaMId/mfe4F
XLW814228E0WKYbMM6mkec6QKpXrOaSRcWEjy2Cbd1IzlGv/2GObYbwlzFF4
cmh4ZBiWStdoSbFcC6OW1xamEXGptMeVCg03VE57+6HZ7wUBZd39a5ksbjLM
cN8XWhevTFD0T3LII+diAgWGzVKtE5pAKq/d73pSGREpHngvxVveC0yFOpqo
55sw2uNRR0Tb5boLK34RU0X/MvimO4oyrP9fNYbCL8GeMLzJDSfO6vZTtEsW
G+rEOkSdyhhtkNfcZNgdDqZda9Zyrfxw4FqOdQ4cyzl7n5odDrasDbabdayz
Dxkrbx0U8ql5a8Mm5LjDwbztpPOZuNIWoy5wLpezeO1qxi42y5C7CKx3SGxX
wqZgmKhJJfZ73YaIjngjIGayFvo8qPNIxjghFw56ysiuqKq+1JKoncslU+mq
UiKqBFxrQdA9DHuRL17JWDmXKOt/6LBJu7ERPyny6Kul6z0i5NFJd0V69TOc
T+RYWCGbGZE2SmRz5wkYg0tnAePEWCPxeiK2v2Dy42/a9BWtnWjLSfQGkGeU
MZUMsUanlQwxHQ/BRuJb52Qijr0Z4ujPwyohdySaQBFzeDxq/hBP6HxB/G3K
nT1Gqoq5KubJYiE2d6q4i3vHYBqLuH+MrIarsaSR0XigsawxrpH7CTHvlCUx
BAAA
""",
"""
androidx/compose/ui/Alignment.class:
H4sIAAAAAAAAAIVSXU8TQRQ9s9uWsqxSqlTKh4BUKagsEBMTISZYY9KkYCKE
hPA03Y512u0s2ZlteOS3+AtEHkgkMcRHf5TxbikQNIGXe/eeOffcc2f2958f
PwG8gscwxVUjCmXj0PPDzkGohRdLbyOQTdURygyAMeRavMu9gKum97HeEj6h
NkNmXSpp3jLY5YVdF2lkHKQwwJAyX6RmmK7dqrzGMMp9X2hdagqzEx5sGx6Z
kn/AMFteuLM3e9nh4h6cQVi4T+C6H/RNzd8qUKoQyJUM1QBGGFbKtXZoqNVr
dTueVEZEigfee/GZx4GphEqbKPZNGG3yqC2itYt9HzjI4yHD4JUYwx3Gr+eu
uSjgUeJ7zKFA1zZXC6Om1xKmHnGptMeVCg03xNXeVmi24iCgvUcunW4Kwxvc
cMKsTtem52RJICHWJuhQJtUyfTVWGErnR65jjVmOlTs/cqysNXZ+NGOvWsvs
DbPfpX99zVg5K+GuMtKBe2V4qW0YJj7FysiOqKqu1LIeiI1ra/TclbAhGIZr
UomtuFMX0Q4nDkO+Fvo82OWRTOo+6FaVElEl4FoLana2wzjyxQeZnBX7c3b/
m4IVuqMULWShmNwbeSxTlaE8QXk8+Qf+wWzK6V61QJVHmVZDevEU2eOe0GKf
nFCfU3QvCBgkKeSKGOohSfNk7wRIfcfwt+Sib/RmkbsaswS7xyycIb/HTjF6
guIZrL1TjJ9g+PhG7xDNsvGCqsR6nhwVaLmXPW/zpAS8JnySWFP7sKt4XMU0
RcwkYbaKJ5jbB9Mo4ek+UhqOxjONjEbhL7J1D8vfAwAA
"""
)
} | apache-2.0 | 99783e6c027a2e0b9dceaff279547215 | 50.995868 | 87 | 0.687808 | 2.328275 | false | false | false | false |
androidx/androidx | compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens/ElevatedButtonTokens.kt | 3 | 2146 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// VERSION: v0_103
// GENERATED CODE - DO NOT MODIFY BY HAND
package androidx.compose.material3.tokens
import androidx.compose.ui.unit.dp
internal object ElevatedButtonTokens {
val ContainerColor = ColorSchemeKeyTokens.Surface
val ContainerElevation = ElevationTokens.Level1
val ContainerHeight = 40.0.dp
val ContainerShape = ShapeKeyTokens.CornerFull
val ContainerSurfaceTintLayerColor = ColorSchemeKeyTokens.SurfaceTint
val DisabledContainerColor = ColorSchemeKeyTokens.OnSurface
val DisabledContainerElevation = ElevationTokens.Level0
const val DisabledContainerOpacity = 0.12f
val DisabledLabelTextColor = ColorSchemeKeyTokens.OnSurface
const val DisabledLabelTextOpacity = 0.38f
val FocusContainerElevation = ElevationTokens.Level1
val FocusLabelTextColor = ColorSchemeKeyTokens.Primary
val HoverContainerElevation = ElevationTokens.Level2
val HoverLabelTextColor = ColorSchemeKeyTokens.Primary
val LabelTextColor = ColorSchemeKeyTokens.Primary
val LabelTextFont = TypographyKeyTokens.LabelLarge
val PressedContainerElevation = ElevationTokens.Level1
val PressedLabelTextColor = ColorSchemeKeyTokens.Primary
val DisabledIconColor = ColorSchemeKeyTokens.OnSurface
const val DisabledIconOpacity = 0.38f
val FocusIconColor = ColorSchemeKeyTokens.Primary
val HoverIconColor = ColorSchemeKeyTokens.Primary
val IconColor = ColorSchemeKeyTokens.Primary
val IconSize = 18.0.dp
val PressedIconColor = ColorSchemeKeyTokens.Primary
} | apache-2.0 | 59bc0072b17e39983e1d164cb455075d | 42.816327 | 75 | 0.788444 | 5.085308 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/reporter/KotlinReportSubmitter.kt | 2 | 11080 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.reporter
import com.intellij.diagnostic.ReportMessages
import com.intellij.ide.DataManager
import com.intellij.ide.plugins.PluginUpdateStatus
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.IdeaLoggingEvent
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.SubmittedReportInfo
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.util.Consumer
import com.intellij.util.ThreeState
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.KotlinPluginUpdater
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinIdePlugin
import org.jetbrains.kotlin.idea.util.application.isApplicationInternalMode
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import java.awt.Component
import java.io.IOException
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeParseException
import java.time.temporal.ChronoUnit
import javax.swing.Icon
/**
* We need to wrap ITNReporter for force showing or errors from kotlin plugin even from released version of IDEA.
*/
class KotlinReportSubmitter : ITNReporterCompat() {
companion object {
private const val KOTLIN_FATAL_ERROR_NOTIFICATION_PROPERTY = "kotlin.fatal.error.notification"
private const val IDEA_FATAL_ERROR_NOTIFICATION_PROPERTY = "idea.fatal.error.notification"
private const val DISABLED_VALUE = "disabled"
private const val ENABLED_VALUE = "enabled"
private const val KOTLIN_PLUGIN_RELEASE_DATE = "kotlin.plugin.releaseDate"
private val LOG = Logger.getInstance(KotlinReportSubmitter::class.java)
@Volatile
private var isFatalErrorReportingDisabledInRelease = ThreeState.UNSURE
private val isIdeaAndKotlinRelease by lazy {
// Disabled in released version of IDEA and Android Studio
// Enabled in EAPs, Canary and Beta
val isReleaseLikeIdea = DISABLED_VALUE == System.getProperty(IDEA_FATAL_ERROR_NOTIFICATION_PROPERTY, ENABLED_VALUE)
isReleaseLikeIdea && KotlinIdePlugin.isRelease
}
private const val NUMBER_OF_REPORTING_DAYS_FROM_RELEASE = 7
fun setupReportingFromRelease() {
if (isUnitTestMode()) {
return
}
if (!isIdeaAndKotlinRelease) {
return
}
val currentPluginReleaseDate = readStoredPluginReleaseDate()
if (currentPluginReleaseDate != null) {
isFatalErrorReportingDisabledInRelease =
if (isFatalErrorReportingDisabled(currentPluginReleaseDate)) ThreeState.YES else ThreeState.NO
return
}
ApplicationManager.getApplication().executeOnPooledThread {
val releaseDate =
try {
KotlinPluginUpdater.fetchPluginReleaseDate(KotlinIdePlugin.id, KotlinIdePlugin.version, null)
} catch (e: IOException) {
LOG.warn(e)
null
} catch (e: KotlinPluginUpdater.Companion.ResponseParseException) {
// Exception won't be shown, but will be logged
LOG.error(e)
return@executeOnPooledThread
}
if (releaseDate != null) {
writePluginReleaseValue(releaseDate)
} else {
// Will try to fetch the same release date on IDE restart
}
isFatalErrorReportingDisabledInRelease = isFatalErrorReportingWithDefault(releaseDate)
}
}
private fun isFatalErrorReportingWithDefault(releaseDate: LocalDate?): ThreeState {
return if (releaseDate != null) {
if (isFatalErrorReportingDisabled(releaseDate)) ThreeState.YES else ThreeState.NO
} else {
// Disable reporting by default until we obtain a valid release date.
// We might fail reporting exceptions that happened before initialization but after successful release date fetching
// such exceptions maybe be reported after restart.
ThreeState.YES
}
}
private fun isFatalErrorReportingDisabledWithUpdate(): Boolean {
val currentPluginReleaseDate = readStoredPluginReleaseDate()
isFatalErrorReportingDisabledInRelease = isFatalErrorReportingWithDefault(currentPluginReleaseDate)
return isFatalErrorReportingDisabledInRelease == ThreeState.YES
}
private fun isFatalErrorReportingDisabled(releaseDate: LocalDate): Boolean {
return ChronoUnit.DAYS.between(releaseDate, LocalDate.now()) > NUMBER_OF_REPORTING_DAYS_FROM_RELEASE
}
private val RELEASE_DATE_FORMATTER: DateTimeFormatter by lazy {
DateTimeFormatter.ofPattern("yyyy-MM-dd")
}
private fun readStoredPluginReleaseDate(): LocalDate? {
val pluginVersionToReleaseDate = PropertiesComponent.getInstance().getValue(KOTLIN_PLUGIN_RELEASE_DATE) ?: return null
val parsedDate = fun(): LocalDate? {
val parts = pluginVersionToReleaseDate.split(":")
if (parts.size != 2) {
return null
}
val pluginVersion = parts[0]
if (pluginVersion != KotlinIdePlugin.version) {
// Stored for some other plugin version
return null
}
return try {
val dateString = parts[1]
LocalDate.parse(dateString, RELEASE_DATE_FORMATTER)
} catch (e: DateTimeParseException) {
null
}
}.invoke()
if (parsedDate == null) {
PropertiesComponent.getInstance().setValue(KOTLIN_PLUGIN_RELEASE_DATE, null)
}
return parsedDate
}
private fun writePluginReleaseValue(date: LocalDate) {
val currentKotlinVersion = KotlinIdePlugin.version
val dateStr = RELEASE_DATE_FORMATTER.format(date)
PropertiesComponent.getInstance().setValue(KOTLIN_PLUGIN_RELEASE_DATE, "$currentKotlinVersion:$dateStr")
}
}
private var hasUpdate = false
private var hasLatestVersion = false
override fun showErrorInRelease(event: IdeaLoggingEvent): Boolean {
if (isApplicationInternalMode()) {
// Reporting is always enabled for internal mode in the platform
return true
}
if (isUnitTestMode()) {
return true
}
if (hasUpdate) {
return false
}
val kotlinNotificationEnabled = DISABLED_VALUE != System.getProperty(KOTLIN_FATAL_ERROR_NOTIFICATION_PROPERTY, ENABLED_VALUE)
if (!kotlinNotificationEnabled) {
// Kotlin notifications are explicitly disabled
return false
}
if (!isIdeaAndKotlinRelease) {
return true
}
return when (isFatalErrorReportingDisabledInRelease) {
ThreeState.YES ->
false
ThreeState.NO -> {
// Reiterate the check for the case when there was no restart for long and reporting decision might expire
!isFatalErrorReportingDisabledWithUpdate()
}
ThreeState.UNSURE -> {
// There might be an exception while initialization isn't complete.
// Decide urgently based on previously stored release version if already fetched.
!isFatalErrorReportingDisabledWithUpdate()
}
}
}
override fun submitCompat(
events: Array<IdeaLoggingEvent>,
additionalInfo: String?,
parentComponent: Component?,
consumer: Consumer<in SubmittedReportInfo>
): Boolean {
if (hasUpdate) {
if (isApplicationInternalMode()) {
return super.submitCompat(events, additionalInfo, parentComponent, consumer)
}
// TODO: What happens here? User clicks report but no report is send?
return true
}
if (hasLatestVersion) {
return super.submitCompat(events, additionalInfo, parentComponent, consumer)
}
val project: Project? = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(parentComponent))
if (KotlinIdePlugin.hasPatchedVersion) {
ReportMessages.GROUP
.createNotification(KotlinBundle.message("reporter.text.can.t.report.exception.from.patched.plugin"), NotificationType.INFORMATION)
.setImportant(false)
.notify(project)
return true
}
KotlinPluginUpdater.getInstance().runUpdateCheck { status ->
if (status is PluginUpdateStatus.Update) {
hasUpdate = true
if (isApplicationInternalMode()) {
super.submitCompat(events, additionalInfo, parentComponent, consumer)
}
val rc = showDialog(
parentComponent,
KotlinBundle.message(
"reporter.message.text.you.re.running.kotlin.plugin.version",
KotlinIdePlugin.version,
status.pluginDescriptor.version
),
KotlinBundle.message("reporter.title.update.kotlin.plugin"),
arrayOf(KotlinBundle.message("reporter.button.text.update"), KotlinBundle.message("reporter.button.text.ignore")),
0, Messages.getInformationIcon()
)
if (rc == 0) {
KotlinPluginUpdater.getInstance().installPluginUpdate(status)
}
} else {
hasLatestVersion = true
super.submitCompat(events, additionalInfo, parentComponent, consumer)
}
false
}
return true
}
fun showDialog(parent: Component?, @Nls message: String, @Nls title: String, options: Array<String>, defaultOptionIndex: Int, icon: Icon?): Int {
return if (parent != null) {
Messages.showDialog(parent, message, title, options, defaultOptionIndex, icon)
} else {
Messages.showDialog(message, title, options, defaultOptionIndex, icon)
}
}
}
| apache-2.0 | 12340f48a097c047376c238c6b4602c8 | 39.586081 | 158 | 0.630957 | 5.528942 | false | false | false | false |
GunoH/intellij-community | platform/build-scripts/src/org/jetbrains/intellij/build/impl/LibraryLicensesListGenerator.kt | 5 | 6635 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment")
package org.jetbrains.intellij.build.impl
import com.fasterxml.jackson.core.JsonFactory
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.trace.Span
import org.jetbrains.intellij.build.LibraryLicense
import org.jetbrains.jps.model.JpsProject
import org.jetbrains.jps.model.java.JpsJavaClasspathKind
import org.jetbrains.jps.model.java.JpsJavaExtensionService
import org.jetbrains.jps.model.library.JpsLibrary
import org.jetbrains.jps.model.library.JpsOrderRootType
import org.jetbrains.jps.model.library.JpsRepositoryLibraryType
import java.nio.file.Files
import java.nio.file.Path
class LibraryLicensesListGenerator(private val libraryLicenses: List<LibraryLicense>) {
companion object {
fun create(project: JpsProject,
licensesList: List<LibraryLicense>,
usedModulesNames: Set<String>,
allowEmpty: Boolean = false): LibraryLicensesListGenerator {
val licences = generateLicenses(project, licensesList, usedModulesNames)
check(allowEmpty || !licences.isEmpty()) {
"Empty licenses table for ${licensesList.size} licenses and ${usedModulesNames.size} used modules names"
}
return LibraryLicensesListGenerator(licences)
}
fun getLibraryName(lib: JpsLibrary): String {
val name = lib.name
if (name.startsWith("#")) {
//unnamed module libraries in IntelliJ project may have only one root
return lib.getFiles(JpsOrderRootType.COMPILED).first().name
}
return name
}
}
fun generateHtml(file: Path) {
val out = StringBuilder()
out.append("""
<style>
table {
width: 560px;
}
th {
border:0pt;
text - align: left;
}
td {
padding - bottom: 11px;
}
.firstColumn {
width: 410px;
padding - left: 16px;
padding - right: 50px;
}
.secondColumn {
width: 150px;
padding - right: 28px;
}
.name {
color: #4a78c2;
margin - right: 5px;
}
.version {
color: #888888;
line - height: 1.5em;
white - space: nowrap;
}
.licence {
color: #779dbd;
}
</style >
""".trimIndent())
out.append("\n<table>")
out.append("\n<tr><th class=\"firstColumn\">Software</th><th class=\"secondColumn\">License</th></tr>")
for (lib in libraryLicenses) {
val libKey = ("${lib.presentableName}_${lib.version ?: ""}").replace(' ', '_')
// id here is needed because of a bug IDEA-188262
val name = if (lib.url == null) {
"<span class=\"name\">${lib.presentableName}</span>"
}
else {
"<a id=\"${libKey}_lib_url\" class=\"name\" href=\"${lib.url}\">${lib.presentableName}</a>"
}
val license = if (lib.getLibraryLicenseUrl() != null) {
"<a id=\"${libKey}_license_url\" class=\"licence\" href=\"${lib.getLibraryLicenseUrl()}\">${lib.license}</a>"
}
else {
"<span class=\"licence\">${lib.license}</span>"
}
out.append('\n')
out.append(generateHtmlLine(name = name, libVersion = lib.version ?: "", license = license))
}
out.append("\n</table>")
Files.createDirectories(file.parent)
Files.writeString(file, out)
}
fun generateJson(file: Path) {
Files.createDirectories(file.parent)
Files.newOutputStream(file).use { out ->
JsonFactory().createGenerator(out).useDefaultPrettyPrinter().use { writer ->
writer.writeStartArray()
for (entry in libraryLicenses) {
writer.writeStartObject()
writer.writeStringField("name", entry.presentableName)
writer.writeStringField("url", entry.url)
writer.writeStringField("version", entry.version)
writer.writeStringField("license", entry.license)
writer.writeStringField("licenseUrl", entry.getLibraryLicenseUrl())
writer.writeEndObject()
}
writer.writeEndArray()
}
}
}
}
private fun generateHtmlLine(name: String, libVersion: String, license: String): String {
return """
<tr valign="top">
<td class="firstColumn">$name <span class="version">$libVersion</span></td>
<td class="secondColumn">$license</td>
</tr>
""".trimIndent()
}
private fun generateLicenses(project: JpsProject, licensesList: List<LibraryLicense>, usedModulesNames: Set<String>): List<LibraryLicense> {
Span.current().setAttribute(AttributeKey.stringArrayKey("modules"), usedModulesNames.toList())
val usedModules = project.modules.filterTo(HashSet()) { usedModulesNames.contains(it.name) }
val usedLibraries = HashMap<String, String>()
for (module in usedModules) {
for (item in JpsJavaExtensionService.dependencies(module).includedIn(JpsJavaClasspathKind.PRODUCTION_RUNTIME).libraries) {
usedLibraries.put(LibraryLicensesListGenerator.getLibraryName(item), module.name)
}
}
val libraryVersions = (project.libraryCollection.libraries.asSequence() +
project.modules.asSequence().flatMap { it.libraryCollection.libraries })
.mapNotNull { it.asTyped(JpsRepositoryLibraryType.INSTANCE) }
.associate { it.name to it.properties.data.version }
val result = HashSet<LibraryLicense>()
for (item in licensesList) {
if (item.license == LibraryLicense.JETBRAINS_OWN) {
continue
}
@Suppress("NAME_SHADOWING") var item = item
if (item.libraryName != null && item.version == null && libraryVersions.containsKey(item.libraryName)) {
item = LibraryLicense(name = item.name,
url = item.url,
version = libraryVersions.get(item.libraryName)!!,
libraryName = item.libraryName,
additionalLibraryNames = item.additionalLibraryNames,
attachedTo = item.attachedTo,
transitiveDependency = item.transitiveDependency,
license = item.license,
licenseUrl = item.licenseUrl)
}
if (usedModulesNames.contains(item.attachedTo)) {
// item.attachedTo
result.add(item)
}
else {
for (name in item.getLibraryNames()) {
if (usedLibraries.containsKey(name)) {
result.add(item)
}
}
}
}
return result.sortedBy { it.presentableName }
}
| apache-2.0 | f48756b6b5e1e78a1c214d9453832e0b | 33.378238 | 140 | 0.634966 | 4.373764 | false | false | false | false |
GunoH/intellij-community | python/src/com/jetbrains/python/target/PyInterpreterVersionUtil.kt | 3 | 4167 | // 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.
@file:JvmName("PyInterpreterVersionUtil")
package com.jetbrains.python.target
import com.intellij.execution.process.CapturingProcessHandler
import com.intellij.execution.target.TargetProgressIndicatorAdapter
import com.intellij.execution.target.TargetedCommandLineBuilder
import com.intellij.execution.target.getTargetEnvironmentRequest
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.util.Ref
import com.intellij.remote.RemoteSdkException
import com.intellij.util.ui.UIUtil
import com.jetbrains.python.PyBundle
@Throws(RemoteSdkException::class)
fun PyTargetAwareAdditionalData.getInterpreterVersion(project: Project?, nullForUnparsableVersion: Boolean = true): String? {
return getInterpreterVersion(project, interpreterPath, nullForUnparsableVersion)
}
@Throws(RemoteSdkException::class)
fun PyTargetAwareAdditionalData.getInterpreterVersion(project: Project?,
interpreterPath: String,
nullForUnparsableVersion: Boolean = true): String? {
val targetEnvironmentRequest = getTargetEnvironmentRequest(project ?: ProjectManager.getInstance().defaultProject)
?: throw IllegalStateException("Unable to get target configuration from Python SDK data")
val result = Ref.create<String>()
val exception = Ref.create<RemoteSdkException>()
val task: Task.Modal = object : Task.Modal(project, PyBundle.message("python.sdk.getting.remote.interpreter.version"), true) {
override fun run(indicator: ProgressIndicator) {
val flavor = flavor
if (flavor != null) {
try {
try {
val targetedCommandLineBuilder = TargetedCommandLineBuilder(targetEnvironmentRequest)
targetedCommandLineBuilder.setExePath(interpreterPath)
targetedCommandLineBuilder.addParameter(flavor.versionOption)
val targetEnvironment = targetEnvironmentRequest.prepareEnvironment(TargetProgressIndicatorAdapter(indicator))
val targetedCommandLine = targetedCommandLineBuilder.build()
val process = targetEnvironment.createProcess(targetedCommandLine, indicator)
val commandLineString = targetedCommandLine.collectCommandsSynchronously().joinToString(separator = " ")
val capturingProcessHandler = CapturingProcessHandler(process, Charsets.UTF_8, commandLineString)
val processOutput = capturingProcessHandler.runProcess()
if (processOutput.exitCode == 0) {
val version = flavor.getVersionStringFromOutput(processOutput)
if (version != null || nullForUnparsableVersion) {
result.set(version)
return
}
else {
throw RemoteSdkException(PyBundle.message("python.sdk.empty.version.string"), processOutput.stdout, processOutput.stderr)
}
}
else {
throw RemoteSdkException(
PyBundle.message("python.sdk.non.zero.exit.code", processOutput.exitCode), processOutput.stdout, processOutput.stderr)
}
}
catch (e: Exception) {
throw RemoteSdkException.cantObtainRemoteCredentials(e)
}
}
catch (e: RemoteSdkException) {
exception.set(e)
}
}
}
}
if (!ProgressManager.getInstance().hasProgressIndicator()) {
UIUtil.invokeAndWaitIfNeeded(Runnable { ProgressManager.getInstance().run(task) })
//invokeAndWaitIfNeeded(ModalityState.defaultModalityState()) { ProgressManager.getInstance().run(task) }
}
else {
task.run(ProgressManager.getInstance().progressIndicator)
}
if (!exception.isNull) {
throw exception.get()
}
return result.get()
} | apache-2.0 | 3348d651dc2d4e6542550c671f659386 | 46.908046 | 158 | 0.708423 | 5.169975 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/run/StandaloneScriptRunConfigurationTest.kt | 4 | 8593 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.run
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiFile
import com.intellij.refactoring.RefactoringFactory
import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesProcessor
import com.intellij.testFramework.IdeaTestUtil
import com.intellij.util.ActionRunner
import org.jdom.Element
import org.jetbrains.kotlin.idea.base.util.allScope
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager
import org.jetbrains.kotlin.idea.run.script.standalone.KotlinStandaloneScriptRunConfiguration
import org.jetbrains.kotlin.idea.stubindex.KotlinScriptFqnIndex
import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR
import org.jetbrains.kotlin.idea.test.KotlinCodeInsightTestCase
import org.junit.Assert
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
import kotlin.test.assertNotEquals
@RunWith(JUnit38ClassRunner::class)
class StandaloneScriptRunConfigurationTest : KotlinCodeInsightTestCase() {
private fun assertEqualPaths(expected: String?, actual: String?) {
assertEquals(
expected?.let { FileUtilRt.toSystemIndependentName(it) },
actual?.let { FileUtilRt.toSystemIndependentName(it) }
)
}
private fun assertNotEqualPaths(illegal: String?, actual: String?, message: String? = null) {
assertNotEquals(
illegal?.let { FileUtilRt.toSystemIndependentName(it) },
actual?.let { FileUtilRt.toSystemIndependentName(it) },
message
)
}
fun testConfigurationForScript() {
configureByFile("run/simpleScript.kts")
val script = KotlinScriptFqnIndex.get("foo.SimpleScript", project, project.allScope()).single()
val runConfiguration = createConfigurationFromElement(script) as KotlinStandaloneScriptRunConfiguration
assertEqualPaths(script.containingFile.virtualFile.canonicalPath, runConfiguration.filePath)
Assert.assertEquals(
runConfiguration.filePath?.let { FileUtilRt.toSystemIndependentName(it) },
runConfiguration.systemIndependentPath
)
Assert.assertEquals("simpleScript.kts", runConfiguration.name)
Assert.assertTrue(runConfiguration.toXmlString().contains(Regex("""<option name="filePath" value="[^"]+simpleScript.kts" />""")))
val javaParameters = getJavaRunParameters(runConfiguration)
val programParametersList = javaParameters.programParametersList.list
programParametersList.checkParameter("-script") { it.contains("simpleScript.kts") }
programParametersList.checkParameter("-kotlin-home") { it == KotlinPluginLayout.kotlinc.absolutePath }
Assert.assertTrue(!programParametersList.contains("-cp"))
}
fun testOnFileRename() {
configureByFile("renameFile/simpleScript.kts")
val script = KotlinScriptFqnIndex.get("foo.SimpleScript", project, project.allScope()).single()
val runConfiguration = createConfigurationFromElement(script, save = true) as KotlinStandaloneScriptRunConfiguration
Assert.assertEquals("simpleScript.kts", runConfiguration.name)
val scriptVirtualFileBefore = script.containingFile.virtualFile
val originalPath = scriptVirtualFileBefore.canonicalPath
val originalWorkingDirectory = scriptVirtualFileBefore.parent.canonicalPath
assertEqualPaths(originalPath, runConfiguration.filePath)
assertEqualPaths(originalWorkingDirectory, runConfiguration.workingDirectory)
RefactoringFactory.getInstance(project).createRename(script.containingFile, "renamedScript.kts").run()
Assert.assertEquals("renamedScript.kts", runConfiguration.name)
val scriptVirtualFileAfter = script.containingFile.virtualFile
assertEqualPaths(scriptVirtualFileAfter.canonicalPath, runConfiguration.filePath)
assertNotEqualPaths(originalPath, runConfiguration.filePath)
assertEqualPaths(scriptVirtualFileAfter.parent.canonicalPath, runConfiguration.workingDirectory)
assertEqualPaths(originalWorkingDirectory, runConfiguration.workingDirectory)
}
fun testOnFileMoveWithDefaultWorkingDir() {
configureByFile("move/script.kts")
ScriptConfigurationManager.updateScriptDependenciesSynchronously(myFile)
val script = KotlinScriptFqnIndex.get("foo.Script", project, project.allScope()).single()
val runConfiguration = createConfigurationFromElement(script, save = true) as KotlinStandaloneScriptRunConfiguration
Assert.assertEquals("script.kts", runConfiguration.name)
val scriptVirtualFileBefore = script.containingFile.virtualFile
val originalPath = scriptVirtualFileBefore.canonicalPath
val originalWorkingDirectory = scriptVirtualFileBefore.parent.canonicalPath
assertEqualPaths(originalPath, runConfiguration.filePath)
assertEqualPaths(originalWorkingDirectory, runConfiguration.workingDirectory)
moveScriptFile(script.containingFile)
Assert.assertEquals("script.kts", runConfiguration.name)
val scriptVirtualFileAfter = script.containingFile.virtualFile
assertEqualPaths(scriptVirtualFileAfter.canonicalPath, runConfiguration.filePath)
assertNotEqualPaths(originalPath, runConfiguration.filePath)
assertEqualPaths(scriptVirtualFileAfter.parent.canonicalPath, runConfiguration.workingDirectory)
assertNotEqualPaths(originalWorkingDirectory, runConfiguration.workingDirectory)
}
fun testOnFileMoveWithNonDefaultWorkingDir() {
configureByFile("move/script.kts")
ScriptConfigurationManager.updateScriptDependenciesSynchronously(myFile)
val script = KotlinScriptFqnIndex.get("foo.Script", project, project.allScope()).single()
val runConfiguration = createConfigurationFromElement(script, save = true) as KotlinStandaloneScriptRunConfiguration
Assert.assertEquals("script.kts", runConfiguration.name)
runConfiguration.workingDirectory = runConfiguration.workingDirectory + "/customWorkingDirectory"
val scriptVirtualFileBefore = script.containingFile.virtualFile
val originalPath = scriptVirtualFileBefore.canonicalPath
val originalWorkingDirectory = scriptVirtualFileBefore.parent.canonicalPath + "/customWorkingDirectory"
assertEqualPaths(originalPath, runConfiguration.filePath)
assertEqualPaths(originalWorkingDirectory, runConfiguration.workingDirectory)
moveScriptFile(script.containingFile)
Assert.assertEquals("script.kts", runConfiguration.name)
val scriptVirtualFileAfter = script.containingFile.virtualFile
assertEqualPaths(scriptVirtualFileAfter.canonicalPath, runConfiguration.filePath)
assertNotEqualPaths(originalPath, runConfiguration.filePath)
assertNotEqualPaths(scriptVirtualFileAfter.parent.canonicalPath, runConfiguration.workingDirectory)
assertEqualPaths(originalWorkingDirectory, runConfiguration.workingDirectory)
}
private fun List<String>.checkParameter(name: String, condition: (String) -> Boolean) {
val param = find { it == name } ?: throw AssertionError("Should pass $name to compiler")
val paramValue = this[this.indexOf(param) + 1]
Assert.assertTrue("Check for $name parameter fails: actual value = $paramValue", condition(paramValue))
}
fun moveScriptFile(scriptFile: PsiFile) {
ActionRunner.runInsideWriteAction { VfsUtil.createDirectoryIfMissing(scriptFile.virtualFile.parent, "dest") }
MoveFilesOrDirectoriesProcessor(
project,
arrayOf(scriptFile),
JavaPsiFacade.getInstance(project).findPackage("dest")!!.directories[0],
false, true, null, null
).run()
}
private fun RunConfiguration.toXmlString(): String {
val element = Element("temp")
writeExternal(element)
return JDOMUtil.writeElement(element)
}
override fun getTestDataDirectory() = IDEA_TEST_DATA_DIR.resolve("run/StandaloneScript")
override fun getTestProjectJdk() = IdeaTestUtil.getMockJdk18()
}
| apache-2.0 | 2f34f83e9fb8e0ba474213662d3bd907 | 47.823864 | 158 | 0.766321 | 5.551034 | false | true | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/ide/bookmark/providers/RootTypeBookmark.kt | 8 | 1500 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.bookmark.providers
import com.intellij.ide.FileSelectInContext
import com.intellij.ide.SelectInManager
import com.intellij.ide.bookmark.Bookmark
import com.intellij.ide.scratch.RootType
import com.intellij.ide.scratch.ScratchTreeStructureProvider
import java.util.Objects
internal class RootTypeBookmark(override val provider: RootTypeBookmarkProvider, val type: RootType) : Bookmark {
val file
get() = ScratchTreeStructureProvider.getVirtualFile(type)
override val attributes: Map<String, String>
get() = mapOf("root.type.id" to type.id)
override fun createNode() = RootTypeNode(provider.project, this)
override fun canNavigate() = !provider.project.isDisposed && file?.isValid == true
override fun canNavigateToSource() = false
override fun navigate(requestFocus: Boolean) {
val context = file?.let { FileSelectInContext(provider.project, it, null) } ?: return
SelectInManager.getInstance(provider.project).targetList.find { context.selectIn(it, requestFocus) }
}
override fun hashCode() = Objects.hash(provider, type)
override fun equals(other: Any?) = other === this || other is RootTypeBookmark
&& other.provider == provider
&& other.type == type
override fun toString() = "ScratchBookmark(module=${type.id},provider=$provider)"
}
| apache-2.0 | ac1b6c0ff3ee01e467aa01f474b0bd0c | 43.117647 | 120 | 0.729333 | 4.398827 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/editor/quickDoc/OnEnumDeclaration.kt | 4 | 376 | /**
* Useless one
*/
enum class SomeEnum<caret>
//INFO: <div class='definition'><pre><font color="808080"><i>OnEnumDeclaration.kt</i></font><br>public final enum class <b>SomeEnum</b> : <a href="psi_element://kotlin.Enum">Enum</a><<a href="psi_element://SomeEnum">SomeEnum</a>></pre></div><div class='content'><p>Useless one</p></div><table class='sections'></table>
| apache-2.0 | ee3af23445cce51f436367c3b9a385ee | 61.666667 | 324 | 0.675532 | 3.133333 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/inspections/AbstractResultUnusedChecker.kt | 1 | 1984 | // 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.inspections
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
abstract class AbstractResultUnusedChecker(
private val expressionChecker: (KtExpression, AbstractResultUnusedChecker) -> Boolean,
private val callChecker: (ResolvedCall<*>, AbstractResultUnusedChecker) -> Boolean
) : AbstractKotlinInspection() {
protected fun check(expression: KtExpression): Boolean {
// Check whatever possible by PSI
if (!expressionChecker(expression, this)) return false
var current: PsiElement? = expression
var parent: PsiElement? = expression.parent
while (parent != null) {
if (parent is KtBlockExpression || parent is KtFunction || parent is KtFile) break
if (parent is KtValueArgument || parent is KtBinaryExpression || parent is KtUnaryExpression) return false
if (parent is KtQualifiedExpression && parent.receiverExpression == current) return false
// TODO: add when condition, if condition (later when it's applicable not only to Deferred)
current = parent
parent = parent.parent
}
// Then check by call
val context = expression.analyze(BodyResolveMode.PARTIAL_WITH_CFA)
if (expression.isUsedAsExpression(context)) return false
val resolvedCall = expression.getResolvedCall(context) ?: return false
return callChecker(resolvedCall, this)
}
} | apache-2.0 | 08aa5a701a971293ff75078f5145e85f | 52.648649 | 158 | 0.740423 | 5.048346 | false | false | false | false |
idea4bsd/idea4bsd | platform/platform-impl/src/org/jetbrains/ide/HttpRequestHandler.kt | 3 | 2639 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.ide
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.util.io.host
import com.intellij.util.io.isLocalOrigin
import com.intellij.util.io.parseAndCheckIsLocalHost
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.FullHttpRequest
import io.netty.handler.codec.http.HttpMethod
import io.netty.handler.codec.http.HttpRequest
import io.netty.handler.codec.http.QueryStringDecoder
import java.io.IOException
abstract class HttpRequestHandler {
companion object {
// Your handler will be instantiated on first user request
val EP_NAME = ExtensionPointName.create<HttpRequestHandler>("com.intellij.httpRequestHandler")!!
@JvmStatic
fun checkPrefix(uri: String, prefix: String): Boolean {
if (uri.length > prefix.length && uri[0] == '/' && uri.regionMatches(1, prefix, 0, prefix.length, ignoreCase = true)) {
if (uri.length - prefix.length == 1) {
return true
}
else {
val c = uri.get(prefix.length + 1)
return c == '/' || c == '?'
}
}
return false
}
}
/**
* Write request from browser without Origin will be always blocked regardless of your implementation.
*/
@SuppressWarnings("SpellCheckingInspection")
open fun isAccessible(request: HttpRequest): Boolean {
val host = request.host
// If attacker.com DNS rebound to 127.0.0.1 and user open site directly — no Origin or Referrer headers.
// So we should check Host header.
return host != null && request.isLocalOrigin() && parseAndCheckIsLocalHost("http://$host")
}
open fun isSupported(request: FullHttpRequest): Boolean {
return request.method() === HttpMethod.GET || request.method() === HttpMethod.HEAD
}
/**
* @return true if processed successfully, false to pass processing to other handlers.
*/
@Throws(IOException::class)
abstract fun process(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): Boolean
} | apache-2.0 | 83432730d850218b510904f64de62d23 | 37.231884 | 125 | 0.720516 | 4.373134 | false | false | false | false |
jwren/intellij-community | platform/platform-impl/src/com/intellij/ide/RecentProjectMetaInfo.kt | 1 | 2162 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.options.advanced.AdvancedSettings
import com.intellij.openapi.wm.impl.FrameInfo
import com.intellij.util.xmlb.annotations.Attribute
import com.intellij.util.xmlb.annotations.MapAnnotation
import com.intellij.util.xmlb.annotations.OptionTag
import com.intellij.util.xmlb.annotations.Property
import java.util.concurrent.atomic.AtomicLong
class RecentProjectMetaInfo : BaseState() {
@get:Attribute
var opened by property(false)
@get:Attribute
var displayName by string()
// to set frame title as earlier as possible
@get:Attribute
var frameTitle by string()
var build by string()
var productionCode by string()
var eap by property(false)
var binFolder by string()
var projectOpenTimestamp by property(0L)
var buildTimestamp by property(0L)
var activationTimestamp by property(0L)
var metadata by string()
@get:Attribute
var projectWorkspaceId by string()
@get:Property(surroundWithTag = false)
internal var frame: FrameInfo? by property()
}
class RecentProjectManagerState : BaseState() {
@Deprecated("")
@get:OptionTag
val recentPaths by list<String>()
@Deprecated("")
@get:OptionTag
val openPaths by list<String>()
@get:OptionTag
val groups by list<ProjectGroup>()
var pid by string()
@get:OptionTag
@get:MapAnnotation(sortBeforeSave = false)
val additionalInfo by linkedMap<String, RecentProjectMetaInfo>()
var lastProjectLocation by string()
fun validateRecentProjects(modCounter: AtomicLong) {
val limit = AdvancedSettings.getInt("ide.max.recent.projects")
if (additionalInfo.size <= limit) {
return
}
while (additionalInfo.size > limit) {
val iterator = additionalInfo.keys.iterator()
while (iterator.hasNext()) {
val path = iterator.next()
if (!additionalInfo[path]!!.opened) {
iterator.remove()
break
}
}
}
modCounter.incrementAndGet()
}
} | apache-2.0 | 410686361f2b5ac9ca38b421c6d5de6b | 27.090909 | 140 | 0.733117 | 4.281188 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/stepping/KotlinSteppingCommandProvider.kt | 1 | 15068 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.stepping
import com.intellij.debugger.PositionManager
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.MethodFilter
import com.intellij.debugger.engine.SuspendContextImpl
import com.intellij.debugger.impl.DebuggerContextImpl
import com.intellij.debugger.impl.JvmSteppingCommandProvider
import com.intellij.debugger.jdi.StackFrameProxyImpl
import com.intellij.debugger.settings.DebuggerSettings
import com.intellij.psi.PsiElement
import com.intellij.util.Range
import com.intellij.util.containers.addIfNotNull
import com.sun.jdi.*
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.caches.resolve.KotlinCacheService
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils
import org.jetbrains.kotlin.idea.core.util.getLineNumber
import org.jetbrains.kotlin.idea.debugger.*
import org.jetbrains.kotlin.idea.debugger.stepping.filter.KotlinStepOverParamDefaultImplsMethodFilter
import org.jetbrains.kotlin.idea.debugger.stepping.filter.LocationToken
import org.jetbrains.kotlin.idea.debugger.stepping.filter.StepOverCallerInfo
import org.jetbrains.kotlin.idea.refactoring.fqName.getKotlinFqName
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.inline.InlineUtil
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import kotlin.math.max
import kotlin.math.min
class KotlinSteppingCommandProvider : JvmSteppingCommandProvider() {
override fun getStepOverCommand(
suspendContext: SuspendContextImpl?,
ignoreBreakpoints: Boolean,
stepSize: Int
): DebugProcessImpl.ResumeCommand? {
if (suspendContext == null || suspendContext.isResumed) return null
val sourcePosition = suspendContext.getSourcePosition() ?: return null
if (sourcePosition.file !is KtFile) return null
return getStepOverCommand(suspendContext, ignoreBreakpoints, sourcePosition)
}
override fun getStepIntoCommand(
suspendContext: SuspendContextImpl?,
ignoreFilters: Boolean,
smartStepFilter: MethodFilter?,
stepSize: Int
): DebugProcessImpl.ResumeCommand? {
if (suspendContext == null || suspendContext.isResumed) return null
val sourcePosition = suspendContext.getSourcePosition() ?: return null
if (sourcePosition.file !is KtFile) return null
return getStepIntoCommand(suspendContext, ignoreFilters, smartStepFilter)
}
@TestOnly
fun getStepIntoCommand(
suspendContext: SuspendContextImpl,
ignoreFilters: Boolean,
smartStepFilter: MethodFilter?
): DebugProcessImpl.ResumeCommand? {
return DebuggerSteppingHelper.createStepIntoCommand(suspendContext, ignoreFilters, smartStepFilter)
}
@TestOnly
fun getStepOverCommand(
suspendContext: SuspendContextImpl,
ignoreBreakpoints: Boolean,
sourcePosition: SourcePosition
): DebugProcessImpl.ResumeCommand? {
return DebuggerSteppingHelper.createStepOverCommand(suspendContext, ignoreBreakpoints, sourcePosition)
}
@TestOnly
fun getStepOutCommand(suspendContext: SuspendContextImpl, debugContext: DebuggerContextImpl): DebugProcessImpl.ResumeCommand? {
return getStepOutCommand(suspendContext, debugContext.sourcePosition)
}
override fun getStepOutCommand(suspendContext: SuspendContextImpl?, stepSize: Int): DebugProcessImpl.ResumeCommand? {
if (suspendContext == null || suspendContext.isResumed) return null
val sourcePosition = suspendContext.debugProcess.debuggerContext.sourcePosition ?: return null
if (sourcePosition.file !is KtFile) return null
return getStepOutCommand(suspendContext, sourcePosition)
}
private fun getStepOutCommand(suspendContext: SuspendContextImpl, sourcePosition: SourcePosition): DebugProcessImpl.ResumeCommand? {
if (sourcePosition.line < 0) return null
return DebuggerSteppingHelper.createStepOutCommand(suspendContext, true)
}
}
private fun SuspendContextImpl.getSourcePosition(): SourcePosition? =
debugProcess.debuggerContext.sourcePosition
private operator fun PsiElement?.contains(element: PsiElement): Boolean {
return this?.textRange?.contains(element.textRange) ?: false
}
private fun findInlineFunctionCalls(sourcePosition: SourcePosition): List<KtCallExpression> {
fun isInlineCall(expr: KtCallExpression): Boolean {
val resolvedCall = expr.resolveToCall() ?: return false
return InlineUtil.isInline(resolvedCall.resultingDescriptor)
}
return findCallsOnPosition(sourcePosition, ::isInlineCall)
}
private fun findCallsOnPosition(sourcePosition: SourcePosition, filter: (KtCallExpression) -> Boolean): List<KtCallExpression> {
val file = sourcePosition.file as? KtFile ?: return emptyList()
val lineNumber = sourcePosition.line
val lineElement = findElementAtLine(file, lineNumber)
if (lineElement !is KtElement) {
if (lineElement != null) {
val call = findCallByEndToken(lineElement)
if (call != null && filter(call)) {
return listOf(call)
}
}
return emptyList()
}
val start = lineElement.startOffset
val end = lineElement.endOffset
val allFilteredCalls = CodeInsightUtils.findElementsOfClassInRange(file, start, end, KtExpression::class.java)
.map { KtPsiUtil.getParentCallIfPresent(it as KtExpression) }
.filterIsInstance<KtCallExpression>()
.filter { filter(it) }
.toSet()
// It is necessary to check range because of multiline assign
var linesRange = lineNumber..lineNumber
return allFilteredCalls.filter {
val shouldInclude = it.getLineNumber() in linesRange
if (shouldInclude) {
linesRange = min(linesRange.first, it.getLineNumber())..max(linesRange.last, it.getLineNumber(false))
}
shouldInclude
}
}
interface KotlinMethodFilter : MethodFilter {
fun locationMatches(context: SuspendContextImpl, location: Location): Boolean
}
fun getStepOverAction(
location: Location, sourcePosition: SourcePosition,
suspendContext: SuspendContextImpl, frameProxy: StackFrameProxyImpl
): KotlinStepAction {
val stackFrame = frameProxy.safeStackFrame() ?: return KotlinStepAction.JvmStepOver
val method = location.safeMethod() ?: return KotlinStepAction.JvmStepOver
val token = LocationToken.from(stackFrame).takeIf { it.lineNumber > 0 } ?: return KotlinStepAction.JvmStepOver
if (token.inlineVariables.isEmpty() && method.isSyntheticMethodForDefaultParameters()) {
val psiLineNumber = location.lineNumber() - 1
val lineNumbers = Range(psiLineNumber, psiLineNumber)
return KotlinStepAction.StepInto(KotlinStepOverParamDefaultImplsMethodFilter.create(location, lineNumbers))
}
val inlinedFunctionArgumentRangesToSkip = sourcePosition.collectInlineFunctionArgumentRangesToSkip()
val positionManager = suspendContext.debugProcess.positionManager
val tokensToSkip = mutableSetOf(token)
for (candidate in method.allLineLocations() ?: emptyList()) {
val candidateKotlinLineNumber =
suspendContext.getSourcePositionLine(candidate) ?:
candidate.safeKotlinPreferredLineNumber()
val candidateStackFrame = StackFrameForLocation(frameProxy.stackFrame, candidate)
val candidateToken = LocationToken.from(candidateStackFrame)
val isAcceptable = candidateToken.lineNumber >= 0
&& candidateToken.lineNumber != token.lineNumber
&& inlinedFunctionArgumentRangesToSkip.none { range -> range.contains(candidateKotlinLineNumber) }
&& candidateToken.inlineVariables.none { it !in token.inlineVariables }
&& !isInlineFunctionFromLibrary(positionManager, candidate, candidateToken)
if (!isAcceptable) {
tokensToSkip += candidateToken
}
}
return KotlinStepAction.KotlinStepOver(tokensToSkip, StepOverCallerInfo.from(location))
}
internal fun createKotlinInlineFilter(suspendContext: SuspendContextImpl): KotlinInlineFilter? {
val location = suspendContext.location ?: return null
val method = location.safeMethod() ?: return null
return KotlinInlineFilter(location, method)
}
internal class KotlinInlineFilter(location: Location, method: Method) {
private val borders = method.getInlineFunctionNamesAndBorders().values.filter { location !in it }
fun isNestedInline(context: SuspendContextImpl?): Boolean {
if (context === null) return false
val candidate = context.location ?: return false
return borders.any { range -> candidate in range }
}
}
fun Method.isSyntheticMethodForDefaultParameters(): Boolean {
return isSynthetic && name().endsWith(JvmAbi.DEFAULT_PARAMS_IMPL_SUFFIX)
}
private fun SuspendContextImpl.getSourcePositionLine(location: Location) =
debugProcess.positionManager.getSourcePosition(location)?.line
private fun isInlineFunctionFromLibrary(positionManager: PositionManager, location: Location, token: LocationToken): Boolean {
if (token.inlineVariables.isEmpty()) {
return false
}
val debuggerSettings = DebuggerSettings.getInstance()
if (!debuggerSettings.TRACING_FILTERS_ENABLED) {
return false
}
tailrec fun getDeclarationName(element: PsiElement?): FqName? {
val declaration = element?.getNonStrictParentOfType<KtDeclaration>() ?: return null
declaration.getKotlinFqName()?.let { return it }
return getDeclarationName(declaration.parent)
}
val fqn = runReadAction {
val element = positionManager.getSourcePosition(location)?.elementAt
getDeclarationName(element)?.takeIf { !it.isRoot }?.asString()
} ?: return false
for (filter in debuggerSettings.steppingFilters) {
if (filter.isEnabled && filter.matches(fqn)) {
return true
}
}
return false
}
private fun SourcePosition.collectInlineFunctionArgumentRangesToSkip() = runReadAction {
val inlineFunctionCalls = findInlineFunctionCalls(this)
if (inlineFunctionCalls.isEmpty()) {
return@runReadAction emptyList()
}
val firstCall = inlineFunctionCalls.first()
val resolutionFacade = KotlinCacheService.getInstance(firstCall.project).getResolutionFacade(inlineFunctionCalls)
val bindingContext = resolutionFacade.analyze(firstCall, BodyResolveMode.FULL)
return@runReadAction inlineFunctionCalls.collectInlineFunctionArgumentRangesToSkip(bindingContext)
}
private fun List<KtCallExpression>.collectInlineFunctionArgumentRangesToSkip(bindingContext: BindingContext): List<IntRange> {
val ranges = mutableListOf<IntRange>()
for (call in this) {
ranges.addLambdaArgumentRanges(call)
val callDescriptor = call.getResolvedCall(bindingContext)?.resultingDescriptor ?: continue
ranges.addDefaultParametersRanges(call.valueArguments.size, callDescriptor)
/*
Also add the first line of the calling expression
to handle cases like this:
inline fun foo( // Add this line
i: Int,
j: Int
) {
...
}
*/
val callElement = callDescriptor.findPsi() as? KtElement ?: continue
val line = callElement.getLineNumber(start = true)
ranges.addIfNotNull(line..line)
}
return ranges
}
private fun MutableList<IntRange>.addLambdaArgumentRanges(call: KtCallExpression) {
for (arg in call.valueArguments) {
val expression = arg.getArgumentExpression()
val functionExpression = (expression as? KtLambdaExpression)?.functionLiteral ?: expression
val function = functionExpression as? KtFunction ?: continue
addIfNotNull(function.getLineRange())
}
}
private fun MutableList<IntRange>.addDefaultParametersRanges(nonDefaultArgumentsNumber: Int, callDescriptor: CallableDescriptor) {
val allArguments = callDescriptor.valueParameters
for (i in nonDefaultArgumentsNumber until allArguments.size) {
val argument = allArguments[i].findPsi() as? KtElement ?: continue
addIfNotNull(argument.getLineRange())
}
}
private class StackFrameForLocation(private val original: StackFrame, private val location: Location) : StackFrame by original {
override fun location() = location
override fun visibleVariables(): List<LocalVariable> {
return location.method()?.variables()?.filter { it.isVisible(this) } ?: throw AbsentInformationException()
}
override fun visibleVariableByName(name: String?): LocalVariable {
return location.method()?.variablesByName(name)?.firstOrNull { it.isVisible(this) } ?: throw AbsentInformationException()
}
}
private fun KtElement.getLineRange(): IntRange? {
val startLineNumber = getLineNumber(true)
val endLineNumber = getLineNumber(false)
if (startLineNumber > endLineNumber) {
return null
}
return startLineNumber..endLineNumber
}
fun getStepOutAction(location: Location, frameProxy: StackFrameProxyImpl): KotlinStepAction {
val stackFrame = frameProxy.safeStackFrame() ?: return KotlinStepAction.StepOut
val method = location.safeMethod() ?: return KotlinStepAction.StepOut
val token = LocationToken.from(stackFrame).takeIf { it.lineNumber > 0 } ?: return KotlinStepAction.StepOut
if (token.inlineVariables.isEmpty()) {
return KotlinStepAction.StepOut
}
val tokensToSkip = mutableSetOf(token)
for (candidate in method.allLineLocations() ?: emptyList()) {
val candidateStackFrame = StackFrameForLocation(frameProxy.stackFrame, candidate)
val candidateToken = LocationToken.from(candidateStackFrame)
val isAcceptable = candidateToken.lineNumber >= 0
&& candidateToken.lineNumber != token.lineNumber
&& token.inlineVariables.any { it !in candidateToken.inlineVariables }
if (!isAcceptable) {
tokensToSkip += candidateToken
}
}
return KotlinStepAction.KotlinStepOver(tokensToSkip, StepOverCallerInfo.from(location))
}
| apache-2.0 | 9dde231c1d22cf68816b8383f40d6a63 | 41.685552 | 158 | 0.743032 | 5.190493 | false | false | false | false |
Jiansion/CustomDouYu | app/src/main/java/com/qianjia/douyu/ui/MainActivity.kt | 1 | 1815 | package com.qianjia.douyu.ui
import android.support.v4.app.Fragment
import com.qianjia.douyu.R
import com.qianjia.douyu.adapter.VPAdapter
import com.qianjia.douyu.base.BaseActivity
import com.qianjia.douyu.ui.attention.AttentionFragment
import com.qianjia.douyu.ui.find.FindFragment
import com.qianjia.douyu.ui.index.IndexFragment
import com.qianjia.douyu.ui.live.LiveFragment
import com.qianjia.douyu.ui.mine.MineFragment
import com.qianjia.douyu.util.LogUtil
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : BaseActivity() {
override fun getLayoutId(): Int {
return R.layout.activity_main
}
override fun initView() {
LogUtil.e(TAG, "initViews")
}
override fun initData() {
val list = ArrayList<Fragment>()
list.add(IndexFragment())
list.add(LiveFragment())
list.add(AttentionFragment())
list.add(FindFragment())
list.add(MineFragment())
val adapter = VPAdapter(supportFragmentManager, list)
mViewpager.adapter = adapter
mViewpager.offscreenPageLimit = 5
bottomNavigation.setOnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.tab_index//首页
-> mViewpager.setCurrentItem(0, false)
R.id.tab_live//直播
-> mViewpager.setCurrentItem(1, false)
R.id.tab_attention//关注
-> mViewpager.setCurrentItem(2, false)
R.id.tab_find//发现
-> mViewpager.setCurrentItem(3, false)
R.id.tab_mine//我的
-> mViewpager.setCurrentItem(4, false)
}
true
}
}
companion object {
private val TAG = MainActivity::class.java.simpleName
}
}
| apache-2.0 | 6bf0b03cabee239ffc30a646e5ab464d | 29.423729 | 70 | 0.637883 | 3.771008 | false | false | false | false |
smmribeiro/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/project/path/WorkingDirectoryInfo.kt | 9 | 1060 | // 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.openapi.externalSystem.service.ui.project.path
import com.intellij.openapi.externalSystem.service.ui.util.LabeledSettingsFragmentInfo
import com.intellij.openapi.roots.ui.distribution.FileChooserInfo
import org.jetbrains.annotations.Nls
interface WorkingDirectoryInfo : FileChooserInfo, LabeledSettingsFragmentInfo {
override val settingsId: String get() = "external.system.working.directory.fragment"
override val settingsGroup: String? get() = null
override val settingsPriority: Int get() = -10
override val settingsHint: String? get() = null
override val settingsActionHint: String? get() = null
override val fileChooserDescription: String? get() = null
override val fileChooserMacroFilter get() = FileChooserInfo.DIRECTORY_PATH
val emptyFieldError: @Nls(capitalization = Nls.Capitalization.Sentence) String
val externalProjects: List<ExternalProject>
} | apache-2.0 | d3006a1f2b07a07442dd62bb62c3ba7a | 49.52381 | 158 | 0.804717 | 4.568966 | false | false | false | false |
erdo/asaf-project | example-kt-02coroutine/src/main/java/foo/bar/example/forecoroutine/OG.kt | 1 | 2122 | package foo.bar.example.forecoroutine
import android.app.Application
import co.early.fore.core.WorkMode
import co.early.fore.kt.core.logging.AndroidLogger
import foo.bar.example.forecoroutine.feature.counter.Counter
import foo.bar.example.forecoroutine.feature.counter.CounterWithProgress
import java.util.HashMap
/**
*
* OG - Object Graph, pure DI implementation
*
* Copyright © 2019 early.co. All rights reserved.
*/
@Suppress("UNUSED_PARAMETER")
object OG {
private var initialized = false
private val dependencies = HashMap<Class<*>, Any>()
fun setApplication(application: Application) {
// create dependency graph
val logger = AndroidLogger("fore_")
val counter = Counter(
logger
)
val counterWithProgress = CounterWithProgress(
logger
)
// add models to the dependencies map if you will need them later
dependencies[Counter::class.java] = counter
dependencies[CounterWithProgress::class.java] = counterWithProgress
}
fun init() {
if (!initialized) {
initialized = true
// run any necessary initialization code once object graph has been created here
}
}
/**
* This is how dependencies get injected, typically an Activity/Fragment/View will call this
* during the onCreate()/onCreateView()/onFinishInflate() method respectively for each of the
* dependencies it needs.
*
* Can use a DI library for similar behaviour using annotations
*
* Will return mocks if they have been set previously in putMock()
*
*
* Call it like this:
*
* <code>
* yourModel = OG[YourModel::class.java]
* </code>
*
* If you want to more tightly scoped object, one way is to pass a factory class here and create
* an instance where you need it
*
*/
@Suppress("UNCHECKED_CAST")
operator fun <T> get(model: Class<T>): T = dependencies[model] as T
fun <T> putMock(clazz: Class<T>, instance: T) {
dependencies[clazz] = instance as Any
}
}
| apache-2.0 | 17d2b78c5371a5686d0496a6e5774d8b | 26.545455 | 100 | 0.652994 | 4.41875 | false | false | false | false |
testIT-LivingDoc/livingdoc2 | livingdoc-converters/src/main/kotlin/org/livingdoc/converters/number/BigIntegerConverter.kt | 2 | 710 | package org.livingdoc.converters.number
import java.math.BigDecimal
import java.math.BigInteger
/**
* This converter converts a BigDecimal to a BigInteger
*/
open class BigIntegerConverter : AbstractNumberConverter<BigInteger>() {
override val lowerBound: BigInteger? = null
override val upperBound: BigInteger? = null
/**
* This function returns the BigInteger representation of the given BigDecimal value.
*
* @param number the BigDecimal containing the value that should be converted
*/
override fun convertToTarget(number: BigDecimal): BigInteger = number.toBigInteger()
override fun canConvertTo(targetType: Class<*>) = BigInteger::class.java == targetType
}
| apache-2.0 | f119357db4f39f35f96f062d11d354fa | 32.809524 | 90 | 0.746479 | 5.107914 | false | false | false | false |
testIT-LivingDoc/livingdoc2 | livingdoc-format-gherkin/src/main/kotlin/org/livingdoc/repositories/format/GherkinFormat.kt | 2 | 2435 | package org.livingdoc.repositories.format
import com.beust.klaxon.Klaxon
import io.cucumber.gherkin.GherkinDocumentBuilder
import io.cucumber.gherkin.Parser
import io.cucumber.gherkin.pickles.PickleCompiler
import io.cucumber.messages.IdGenerator
import io.cucumber.messages.Messages
import org.livingdoc.repositories.Document
import org.livingdoc.repositories.DocumentFormat
import org.livingdoc.repositories.model.TestDataDescription
import org.livingdoc.repositories.model.scenario.Scenario
import org.livingdoc.repositories.model.scenario.Step
import java.io.InputStream
/**
* GherkinFormat supports parsing [Documents][Document] described using Gherkin.
*/
class GherkinFormat : DocumentFormat {
private val id = IdGenerator.Incrementing()
override fun canHandle(fileExtension: String): Boolean {
return fileExtension == "feature"
}
override fun parse(stream: InputStream): Document {
val gherkin = Parser(GherkinDocumentBuilder(id)).parse(stream.reader())
val descriptionMap = gherkin.feature.childrenList.mapNotNull {
when (it.valueCase) {
Messages.GherkinDocument.Feature.FeatureChild.ValueCase.SCENARIO ->
(it.scenario.id to it.scenario.description)
else -> null
}
}.toMap()
val pickles = PickleCompiler(id).compile(gherkin.build(), gherkin.uri)
return Document(pickles.map { pickle ->
val steps = pickle.stepsList.map { step ->
val argument = when (step.argument.messageCase) {
Messages.PickleStepArgument.MessageCase.DOC_STRING -> step.argument.docString.content
Messages.PickleStepArgument.MessageCase.DATA_TABLE -> Klaxon().toJsonString(DataTable(
rows = step.argument.dataTable.rowsList.map {
it.cellsList.map {
it.value
}
}))
else -> ""
}
Step((step.text + " " + argument).trim())
}
val id = pickle.getAstNodeIds(0)
val scenarioDescription = gherkin.feature.description + "\n\n" + descriptionMap[id]
Scenario(
steps,
TestDataDescription(pickle.name, false, scenarioDescription.trimIndent().trim())
)
})
}
}
| apache-2.0 | bc8684261a39e946f132e8f792ebd12b | 36.461538 | 106 | 0.631622 | 4.728155 | false | false | false | false |
myunusov/maxur-mserv | maxur-mserv-core/src/test/kotlin/org/maxur/mserv/frame/service/properties/PropertiesJacksonImplSpec.kt | 1 | 3578 | package org.maxur.mserv.frame.service.properties
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.junit.platform.runner.JUnitPlatform
import org.junit.runner.RunWith
import org.maxur.mserv.frame.LocatorImpl
import org.maxur.mserv.frame.TestLocatorHolder
import java.net.URI
import java.net.URL
import java.time.Duration
import java.time.temporal.ChronoUnit
import kotlin.test.assertFailsWith
@RunWith(JUnitPlatform::class)
class PropertiesJacksonImplSpec : Spek({
describe("a Properties Source as Yaml File") {
beforeEachTest {
LocatorImpl.holder = TestLocatorHolder
}
context("Load properties source by url") {
it("should return opened source with url by default") {
val sut = PropertiesSourceJacksonImpl(YAMLFactory(), "yaml")
assertThat(sut).isNotNull()
assertThat(sut.format).isEqualTo("Yaml")
assertThat(sut.uri.toString()).endsWith("application.yaml")
}
it("should return opened source with classpath url") {
val sut = PropertiesSourceJacksonImpl(
YAMLFactory(),
"yaml",
URI("classpath://application.yaml")
)
assertThat(sut).isNotNull()
assertThat(sut.format).isEqualTo("Yaml")
assertThat(sut.uri.toString()).endsWith("application.yaml")
}
it("should return opened source with url by default") {
val uri = URL(PropertiesJacksonImplSpec::class.java.getResource("/application.yaml").path).toURI()
val sut = PropertiesSourceJacksonImpl(YAMLFactory(), "yaml", uri)
assertThat(sut).isNotNull()
assertThat(sut.format).isEqualTo("Yaml")
assertThat(sut.uri.toString()).endsWith("application.yaml")
}
}
context("Load properties source from file") {
val sut = PropertiesSourceJacksonImpl(YAMLFactory(), "yaml")
it("should return value of properties by it's key") {
assertThat(sut.asString("name")).isEqualTo("μService")
assertThat(sut.read("name", String::class)).isEqualTo("μService")
assertThat(sut.asInteger("id")).isEqualTo(1)
assertThat(sut.read("id", Integer::class)).isEqualTo(1)
assertThat(sut.asLong("id")).isEqualTo(1L)
assertThat(sut.read("id", Long::class)).isEqualTo(1L)
assertThat(sut.asURI("url")).isEqualTo(URI("file:///file.txt"))
assertThat(sut.read("url", URI::class)).isEqualTo(URI("file:///file.txt"))
assertThat(sut.read("id", Double::class)).isEqualTo(1.0)
assertThat(sut.read("time", Duration::class)).isEqualTo(Duration.of(1, ChronoUnit.SECONDS))
}
it("should throw exception when properties is not found") {
assertFailsWith<IllegalStateException> {
sut.asInteger("error")
}
}
it("should throw exception when properties is not parsed") {
assertFailsWith<IllegalStateException> {
sut.read("id", PropertiesSourceHoconImpl::class)
}
}
}
}
}) | apache-2.0 | ee96854930698e07bec1115a2dbadd93 | 43.160494 | 114 | 0.606264 | 4.793566 | false | false | false | false |
MyCollab/mycollab | mycollab-web/src/main/java/com/mycollab/module/user/accountsettings/fielddef/RoleTableFieldDef.kt | 3 | 1672 | /**
* 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://www.gnu.org/licenses/>.
*/
package com.mycollab.module.user.accountsettings.fielddef
import com.mycollab.common.TableViewField
import com.mycollab.common.i18n.GenericI18Enum
import com.mycollab.module.user.accountsettings.localization.RoleI18nEnum
import com.mycollab.vaadin.web.ui.WebUIConstants
/**
* @author MyCollab Ltd
* @since 6.0.0
*/
object RoleTableFieldDef {
@JvmField
val selected = TableViewField(null, "selected", WebUIConstants.TABLE_CONTROL_WIDTH)
@JvmField
val rolename = TableViewField(GenericI18Enum.FORM_NAME, "rolename", WebUIConstants.TABLE_EX_LABEL_WIDTH)
@JvmField
val members = TableViewField(RoleI18nEnum.OPT_NUM_MEMBERS, "numMembers", WebUIConstants.TABLE_EX_LABEL_WIDTH)
@JvmField
val isDefault = TableViewField(RoleI18nEnum.FORM_IS_DEFAULT, "isdefault", WebUIConstants.TABLE_M_LABEL_WIDTH)
@JvmField
val description = TableViewField(GenericI18Enum.FORM_DESCRIPTION, "description", WebUIConstants.TABLE_EX_LABEL_WIDTH)
} | agpl-3.0 | f59281285eb6d99acf9294880eca87a4 | 37.883721 | 121 | 0.76541 | 3.904206 | false | false | false | false |
sksamuel/ktest | kotest-tests/kotest-tests-core/src/jvmTest/kotlin/com/sksamuel/kotest/listeners/spec/instancepertest/AfterSpecFunctionOverrideTest.kt | 1 | 1494 | package com.sksamuel.kotest.listeners.spec.instancepertest
import io.kotest.core.spec.IsolationMode
import io.kotest.core.spec.Spec
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import java.util.concurrent.atomic.AtomicInteger
class AfterSpecFunctionOverrideTest : FunSpec() {
companion object {
private val counter = AtomicInteger(0)
}
override fun isolationMode(): IsolationMode = IsolationMode.InstancePerTest
// should be invoked once per isolated test
override fun afterSpec(spec: Spec) {
counter.incrementAndGet()
}
init {
afterProject {
counter.get() shouldBe 5
}
test("ignored test").config(enabled = false) {}
test("a") { }
test("b") { }
test("c") { }
test("d") { }
}
}
class AfterSpecFunctionOverrideTestWithNested : FunSpec() {
companion object {
private val counter = AtomicInteger(0)
}
override fun isolationMode(): IsolationMode = IsolationMode.InstancePerTest
// should be invoked once per isolated test and per context because it's test itself too
override fun afterSpec(spec: Spec) {
counter.incrementAndGet()
}
init {
afterProject {
counter.get() shouldBe 7
}
test("ignored test").config(enabled = false) {}
context("context 1") {
test("a") { }
test("b") { }
}
context("context 2") {
test("c") { }
test("d") { }
}
}
}
| mit | 68ff3133d4ffc972d3e788e57de1984e | 20.970588 | 91 | 0.631861 | 4.330435 | false | true | false | false |
chiken88/passnotes | app/src/main/kotlin/com/ivanovsky/passnotes/domain/interactor/note_editor/NoteEditorInteractor.kt | 1 | 1598 | package com.ivanovsky.passnotes.domain.interactor.note_editor
import com.ivanovsky.passnotes.data.ObserverBus
import com.ivanovsky.passnotes.data.entity.Note
import com.ivanovsky.passnotes.data.entity.OperationResult
import com.ivanovsky.passnotes.data.entity.Template
import com.ivanovsky.passnotes.data.repository.EncryptedDatabaseRepository
import java.util.*
class NoteEditorInteractor(
private val dbRepo: EncryptedDatabaseRepository,
private val observerBus: ObserverBus
) {
fun createNewNote(note: Note): OperationResult<Unit> {
val insertResult = dbRepo.noteRepository.insert(note)
if (insertResult.isFailed) {
return insertResult.takeError()
}
observerBus.notifyNoteDataSetChanged(note.groupUid)
return insertResult.takeStatusWith(Unit)
}
fun loadNote(uid: UUID): OperationResult<Note> {
return dbRepo.noteRepository.getNoteByUid(uid)
}
fun updateNote(note: Note): OperationResult<Unit> {
val updateResult = dbRepo.noteRepository.update(note)
if (updateResult.isFailed) {
return updateResult.takeError()
}
val groupUid = note.groupUid
val oldUid = note.uid
val newUid = updateResult.obj
observerBus.notifyNoteContentChanged(groupUid, oldUid, newUid)
return updateResult.takeStatusWith(Unit)
}
fun loadTemplate(templateUid: UUID): Template? {
val templates = dbRepo.templateRepository?.templates ?: return null
return templates.firstOrNull { template -> template.uid == templateUid }
}
} | gpl-2.0 | 23629a5c861bb9582551e1c1ae12469d | 31.632653 | 80 | 0.720275 | 4.438889 | false | false | false | false |
slisson/intellij-community | plugins/settings-repository/testSrc/GitTest.kt | 13 | 13443 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository.test
import com.intellij.configurationStore.write
import com.intellij.mock.MockVirtualFileSystem
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vcs.merge.MergeSession
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.testFramework.ProjectRule
import com.intellij.testFramework.path
import com.intellij.util.PathUtilRt
import org.assertj.core.api.Assertions.assertThat
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.lib.Repository
import org.jetbrains.jgit.dirCache.deletePath
import org.jetbrains.jgit.dirCache.writePath
import org.jetbrains.settingsRepository.CannotResolveConflictInTestMode
import org.jetbrains.settingsRepository.SyncType
import org.jetbrains.settingsRepository.conflictResolver
import org.jetbrains.settingsRepository.git.GitRepositoryManager
import org.jetbrains.settingsRepository.git.commit
import org.jetbrains.settingsRepository.git.computeIndexDiff
import org.jetbrains.settingsRepository.git.resetHard
import org.junit.ClassRule
import org.junit.Test
import java.io.File
import java.nio.charset.StandardCharsets
import java.util.Arrays
import kotlin.properties.Delegates
// kotlin bug, cannot be val (.NoSuchMethodError: org.jetbrains.settingsRepository.SettingsRepositoryPackage.getMARKER_ACCEPT_MY()[B)
object AM {
val MARKER_ACCEPT_MY: ByteArray = "__accept my__".toByteArray()
val MARKER_ACCEPT_THEIRS: ByteArray = "__accept theirs__".toByteArray()
}
class GitTest : IcsTestCase() {
companion object {
@ClassRule val projectRule = ProjectRule()
}
private val repositoryManager: GitRepositoryManager
get() = icsManager.repositoryManager as GitRepositoryManager
private val repository: Repository
get() = repositoryManager.repository
var remoteRepository: Repository by Delegates.notNull()
init {
conflictResolver = { files, mergeProvider ->
val mergeSession = mergeProvider.createMergeSession(files)
for (file in files) {
val mergeData = mergeProvider.loadRevisions(file)
if (Arrays.equals(mergeData.CURRENT, AM.MARKER_ACCEPT_MY) || Arrays.equals(mergeData.LAST, AM.MARKER_ACCEPT_THEIRS)) {
mergeSession.conflictResolvedForFile(file, MergeSession.Resolution.AcceptedYours)
}
else if (Arrays.equals(mergeData.CURRENT, AM.MARKER_ACCEPT_THEIRS) || Arrays.equals(mergeData.LAST, AM.MARKER_ACCEPT_MY)) {
mergeSession.conflictResolvedForFile(file, MergeSession.Resolution.AcceptedTheirs)
}
else if (Arrays.equals(mergeData.LAST, AM.MARKER_ACCEPT_MY)) {
file.setBinaryContent(mergeData.LAST!!)
mergeProvider.conflictResolvedForFile(file)
}
else {
throw CannotResolveConflictInTestMode()
}
}
}
}
private fun addAndCommit(path: String): FileInfo {
val data = """<file path="$path" />""".toByteArray()
provider.write(path, data)
repositoryManager.commit()
return FileInfo(path, data)
}
Test fun add() {
provider.write(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT)
val diff = repository.computeIndexDiff()
assertThat(diff.diff()).isTrue()
assertThat(diff.getAdded()).containsOnly(SAMPLE_FILE_NAME)
assertThat(diff.getChanged()).isEmpty()
assertThat(diff.getRemoved()).isEmpty()
assertThat(diff.getModified()).isEmpty()
assertThat(diff.getUntracked()).isEmpty()
assertThat(diff.getUntrackedFolders()).isEmpty()
}
Test fun addSeveral() {
val addedFile = "foo.xml"
val addedFile2 = "bar.xml"
provider.write(addedFile, "foo")
provider.write(addedFile2, "bar")
val diff = repository.computeIndexDiff()
assertThat(diff.diff()).isTrue()
assertThat(diff.getAdded()).containsOnly(addedFile, addedFile2)
assertThat(diff.getChanged()).isEmpty()
assertThat(diff.getRemoved()).isEmpty()
assertThat(diff.getModified()).isEmpty()
assertThat(diff.getUntracked()).isEmpty()
assertThat(diff.getUntrackedFolders()).isEmpty()
}
Test fun delete() {
fun delete(directory: Boolean) {
val dir = "dir"
val fullFileSpec = "$dir/file.xml"
provider.write(fullFileSpec, SAMPLE_FILE_CONTENT)
provider.delete(if (directory) dir else fullFileSpec)
val diff = repository.computeIndexDiff()
assertThat(diff.diff()).isFalse()
assertThat(diff.getAdded()).isEmpty()
assertThat(diff.getChanged()).isEmpty()
assertThat(diff.getRemoved()).isEmpty()
assertThat(diff.getModified()).isEmpty()
assertThat(diff.getUntracked()).isEmpty()
assertThat(diff.getUntrackedFolders()).isEmpty()
}
delete(false)
delete(true)
}
Test fun `set upstream`() {
val url = "https://github.com/user/repo.git"
repositoryManager.setUpstream(url)
assertThat(repositoryManager.getUpstream()).isEqualTo(url)
}
Test
public fun pullToRepositoryWithoutCommits() {
doPullToRepositoryWithoutCommits(null)
}
Test fun pullToRepositoryWithoutCommitsAndCustomRemoteBranchName() {
doPullToRepositoryWithoutCommits("customRemoteBranchName")
}
private fun doPullToRepositoryWithoutCommits(remoteBranchName: String?) {
createLocalRepository(remoteBranchName)
repositoryManager.pull()
compareFiles(repository.workTree, remoteRepository.workTree)
}
Test fun pullToRepositoryWithCommits() {
doPullToRepositoryWithCommits(null)
}
Test fun pullToRepositoryWithCommitsAndCustomRemoteBranchName() {
doPullToRepositoryWithCommits("customRemoteBranchName")
}
private fun doPullToRepositoryWithCommits(remoteBranchName: String?) {
val file = createLocalRepositoryAndCommit(remoteBranchName)
repositoryManager.commit()
repositoryManager.pull()
assertThat(FileUtil.loadFile(File(repository.getWorkTree(), file.name))).isEqualTo(String(file.data, CharsetToolkit.UTF8_CHARSET))
compareFiles(repository.workTree, remoteRepository.workTree, null, PathUtilRt.getFileName(file.name))
}
private fun createLocalRepository(remoteBranchName: String? = null) {
createRemoteRepository(remoteBranchName)
repositoryManager.setUpstream(remoteRepository.getWorkTree().getAbsolutePath(), remoteBranchName)
}
private fun createLocalRepositoryAndCommit(remoteBranchName: String? = null): FileInfo {
createLocalRepository(remoteBranchName)
return addAndCommit("local.xml")
}
private fun MockVirtualFileSystem.compare() {
compareFiles(repository.workTree, remoteRepository.workTree, getRoot())
}
// never was merged. we reset using "merge with strategy "theirs", so, we must test - what's happen if it is not first merge? - see next test
Test fun resetToTheirsIfFirstMerge() {
createLocalRepositoryAndCommit(null)
sync(SyncType.OVERWRITE_LOCAL)
fs().file(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT).compare()
}
Test fun resetToTheirsISecondMergeIsNull() {
createLocalRepositoryAndCommit(null)
sync(SyncType.MERGE)
restoreRemoteAfterPush()
val fs = MockVirtualFileSystem()
fun testRemote() {
fs
.file("local.xml", """<file path="local.xml" />""")
.file(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT)
.compare()
}
testRemote()
addAndCommit("_mac/local2.xml")
sync(SyncType.OVERWRITE_LOCAL)
fs.compare()
// test: merge and push to remote after such reset
sync(SyncType.MERGE)
restoreRemoteAfterPush()
testRemote()
}
Test fun resetToMyIfFirstMerge() {
createLocalRepositoryAndCommit()
sync(SyncType.OVERWRITE_REMOTE)
restoreRemoteAfterPush()
fs().file("local.xml", """<file path="local.xml" />""").compare()
}
Test fun `reset to my, second merge is null`() {
createLocalRepositoryAndCommit()
sync(SyncType.MERGE)
restoreRemoteAfterPush()
val fs = fs().file("local.xml", """<file path="local.xml" />""").file(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT)
fs.compare()
val localToFilePath = "_mac/local2.xml"
addAndCommit(localToFilePath)
sync(SyncType.OVERWRITE_REMOTE)
restoreRemoteAfterPush()
fs.file(localToFilePath, """<file path="$localToFilePath" />""")
fs.compare()
// test: merge to remote after such reset
sync(SyncType.MERGE)
restoreRemoteAfterPush()
fs.compare()
}
Test fun `merge - resolve conflicts to my`() {
createLocalRepository()
val data = AM.MARKER_ACCEPT_MY
provider.write(SAMPLE_FILE_NAME, data)
sync(SyncType.MERGE)
restoreRemoteAfterPush()
fs().file(SAMPLE_FILE_NAME, data.toString(StandardCharsets.UTF_8)).compare()
}
Test fun `merge - theirs file deleted, my modified, accept theirs`() {
createLocalRepository()
sync(SyncType.MERGE)
val data = AM.MARKER_ACCEPT_THEIRS
provider.write(SAMPLE_FILE_NAME, data)
repositoryManager.commit()
remoteRepository.deletePath(SAMPLE_FILE_NAME)
remoteRepository.commit("delete $SAMPLE_FILE_NAME")
sync(SyncType.MERGE)
fs().compare()
}
Test fun `merge - my file deleted, theirs modified, accept my`() {
createLocalRepository()
sync(SyncType.MERGE)
provider.delete("remote.xml")
repositoryManager.commit()
remoteRepository.writePath("remote.xml", AM.MARKER_ACCEPT_THEIRS)
remoteRepository.commit("")
sync(SyncType.MERGE)
restoreRemoteAfterPush()
fs().compare()
}
Test fun `commit if unmerged`() {
createLocalRepository()
val data = "<foo />"
provider.write(SAMPLE_FILE_NAME, data)
try {
sync(SyncType.MERGE)
}
catch (e: CannotResolveConflictInTestMode) {
}
// repository in unmerged state
conflictResolver = {files, mergeProvider ->
assertThat(files).hasSize(1)
assertThat(files.first().path).isEqualTo(SAMPLE_FILE_NAME)
val mergeSession = mergeProvider.createMergeSession(files)
mergeSession.conflictResolvedForFile(files.first(), MergeSession.Resolution.AcceptedTheirs)
}
sync(SyncType.MERGE)
fs().file(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT).compare()
}
// remote is uninitialized (empty - initial commit is not done)
Test fun `merge with uninitialized upstream`() {
doSyncWithUninitializedUpstream(SyncType.MERGE)
}
Test fun `reset to my, uninitialized upstream`() {
doSyncWithUninitializedUpstream(SyncType.OVERWRITE_REMOTE)
}
Test fun `reset to theirs, uninitialized upstream`() {
doSyncWithUninitializedUpstream(SyncType.OVERWRITE_LOCAL)
}
Test fun gitignore() {
createLocalRepository()
provider.write(".gitignore", "*.html")
sync(SyncType.MERGE)
val filePaths = listOf("bar.html", "i/am/a/long/path/to/file/foo.html")
for (path in filePaths) {
provider.write(path, path)
}
val diff = repository.computeIndexDiff()
assertThat(diff.diff()).isFalse()
assertThat(diff.getAdded()).isEmpty()
assertThat(diff.getChanged()).isEmpty()
assertThat(diff.getRemoved()).isEmpty()
assertThat(diff.getModified()).isEmpty()
assertThat(diff.getUntracked()).isEmpty()
assertThat(diff.getUntrackedFolders()).isEmpty()
for (path in filePaths) {
assertThat(provider.read(path)).isNull()
}
}
private fun createRemoteRepository(branchName: String? = null, initialCommit: Boolean = true) {
val repository = tempDirManager.createRepository("upstream")
if (initialCommit) {
repository
.add(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT)
.commit("")
}
if (branchName != null) {
if (!initialCommit) {
// jgit cannot checkout&create branch if no HEAD (no commits in our empty repository), so we create initial empty commit
repository.commit("")
}
Git(repository).checkout().setCreateBranch(true).setName(branchName).call()
}
remoteRepository = repository
}
private fun doSyncWithUninitializedUpstream(syncType: SyncType) {
createRemoteRepository(initialCommit = false)
repositoryManager.setUpstream(remoteRepository.getWorkTree().getAbsolutePath())
val path = "local.xml"
val data = "<application />"
provider.write(path, data)
sync(syncType)
val fs = MockVirtualFileSystem()
if (syncType != SyncType.OVERWRITE_LOCAL) {
fs.file(path, data)
}
restoreRemoteAfterPush();
fs.compare()
}
private fun restoreRemoteAfterPush() {
/** we must not push to non-bare repository - but we do it in test (our sync merge equals to "pull&push"),
"
By default, updating the current branch in a non-bare repository
is denied, because it will make the index and work tree inconsistent
with what you pushed, and will require 'git reset --hard' to match the work tree to HEAD.
"
so, we do "git reset --hard"
*/
remoteRepository.resetHard()
}
private fun sync(syncType: SyncType) {
icsManager.sync(syncType)
}
} | apache-2.0 | 381a4772cc68bf70d2ff5c16be7ff1cd | 30.85782 | 143 | 0.718069 | 4.505027 | false | true | false | false |
wiryls/HomeworkCollectionOfMYLS | 2017.AndroidApplicationDevelopment/ODES/app/src/main/java/com/myls/odes/fragment/AffairFragment.kt | 1 | 3125 | package com.myls.odes.fragment
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_affair.*
import kotlinx.android.synthetic.main.item_affair.view.*
import com.myls.odes.R
class AffairFragment : Fragment()
{
private var listener: FragmentInteraction? = null
override fun onCreateView
(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?)
=inflater.inflate(R.layout.fragment_affair, container, false)!!
override fun onActivityCreated(savedInstanceState: Bundle?)
= super.onActivityCreated(savedInstanceState).also {
with(recycler) {
layoutManager = if (COLUMN_COUNT <= 1) LinearLayoutManager(context)
else GridLayoutManager(context, COLUMN_COUNT)
adapter = AffairRecyclerAdapter(AffairEnum.values().toList(), listener!!)
}
}
override fun onAttach(context: Context?) {
super.onAttach(context)
listener = context as? FragmentInteraction ?:
throw RuntimeException("$context must implement ${FragmentInteraction::class.java.simpleName}")
}
override fun onDetach() {
listener = null
super.onDetach()
}
private class AffairRecyclerAdapter(
private val items: List<AffairFragment.AffairEnum>,
private val listener: FragmentInteraction)
: RecyclerView.Adapter<AffairRecyclerAdapter.ViewHolder>()
, View.OnClickListener
{
override fun getItemCount() = items.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(
LayoutInflater
.from(parent.context)
.inflate(R.layout.item_affair, parent, false))
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
with(holder) { items[position].let {
desc.setText(it.DESC)
icon.setImageResource(it.ICON)
view.setOnClickListener(this@AffairRecyclerAdapter)
view.tag = it
}}
}
override fun onClick(v: View) {
val enum = (v.tag as AffairEnum).FRAGMENT
listener.onReceiveFragmentAttribute(enum)
}
class ViewHolder(val view: View) : RecyclerView.ViewHolder(view)
{
val desc = view.item_desc!!
val icon = view.item_icon!!
}
}
private enum class AffairEnum(val DESC: Int, val ICON: Int, val FRAGMENT: FragmentAttribute)
{
DORMITORY(R.string.frag_dormitory, R.drawable.ic_dormitory, FragmentAttribute.DORMITORY)
}
companion object {
private val TAG = AffairFragment::class.java.canonicalName!!
private val COLUMN_COUNT = 2
fun create() = AffairFragment()
}
}
| mit | 51b3da85651484b3088cd580821e8703 | 33.722222 | 114 | 0.66816 | 4.602356 | false | false | false | false |
Esri/arcgis-runtime-samples-android | kotlin/add-graphics-renderer/src/main/java/com/esri/arcgisruntime/sample/addgraphicsrenderer/MainActivity.kt | 1 | 11898 | /* Copyright 2020 Esri
*
* 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.esri.arcgisruntime.sample.addgraphicsrenderer
import android.graphics.Color
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.geometry.GeodesicEllipseParameters
import com.esri.arcgisruntime.geometry.GeometryEngine
import com.esri.arcgisruntime.geometry.GeometryType
import com.esri.arcgisruntime.geometry.Geometry
import com.esri.arcgisruntime.geometry.EllipticArcSegment
import com.esri.arcgisruntime.geometry.CubicBezierSegment
import com.esri.arcgisruntime.geometry.Part
import com.esri.arcgisruntime.geometry.Polygon
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.geometry.SpatialReferences
import com.esri.arcgisruntime.geometry.AngularUnit
import com.esri.arcgisruntime.geometry.AngularUnitId
import com.esri.arcgisruntime.geometry.LinearUnit
import com.esri.arcgisruntime.geometry.LinearUnitId
import com.esri.arcgisruntime.geometry.PolylineBuilder
import com.esri.arcgisruntime.geometry.PolygonBuilder
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.Graphic
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.sample.addgraphicsrenderer.databinding.ActivityMainBinding
import com.esri.arcgisruntime.symbology.SimpleFillSymbol
import com.esri.arcgisruntime.symbology.SimpleLineSymbol
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol
import com.esri.arcgisruntime.symbology.SimpleRenderer
class MainActivity : AppCompatActivity() {
private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val mapView: MapView by lazy {
activityMainBinding.mapView
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(activityMainBinding.root)
// authentication with an API key or named user is required to access basemaps and other
// location services
ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)
// create a map with a topographic basemap
val map = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC)
// set the map to be displayed in this view
mapView.map = map
mapView.setViewpoint(Viewpoint(15.169193, 16.333479, 100000000.0))
// add graphics overlays
mapView.graphicsOverlays.addAll(
arrayOf(
renderedPointGraphicsOverlay(),
renderedLineGraphicsOverlay(),
renderedPolygonGraphicsOverlay(),
renderedCurvedPolygonGraphicsOverlay(),
renderedEllipseGraphicsOverlay()
)
)
}
/**
* Create an ellipse, its graphic, a graphics overlay for it, and add it to the map view.
* */
private fun renderedEllipseGraphicsOverlay(): GraphicsOverlay {
// create and set all the parameters so that the ellipse has a major axis of 400 kilometres,
// a minor axis of 200 kilometres and is rotated at an angle of -45 degrees
val parameters = GeodesicEllipseParameters()
parameters.apply {
center = Point(40e5, 23e5, SpatialReferences.getWebMercator())
geometryType = GeometryType.POLYGON
semiAxis1Length = 200.0
semiAxis2Length = 400.0
axisDirection = -45.0
setMaxPointCount(100)
angularUnit = AngularUnit(AngularUnitId.DEGREES)
linearUnit = LinearUnit(LinearUnitId.KILOMETERS)
maxSegmentLength = 20.0
}
// define the ellipse parameters to a polygon geometry
val polygon = GeometryEngine.ellipseGeodesic(parameters)
// create an ellipse graphic overlay using the defined polygon
val ellipseGraphicOverlay = GraphicsOverlay()
val ellipseSymbol = SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, Color.MAGENTA, null)
ellipseGraphicOverlay.renderer = SimpleRenderer(ellipseSymbol)
ellipseGraphicOverlay.graphics.add(Graphic(polygon))
return ellipseGraphicOverlay
}
/**
* Create a point, its graphic, a graphics overlay for it, and add it to the map view.
* */
private fun renderedPointGraphicsOverlay(): GraphicsOverlay {
// create point
val pointGeometry = Point(40e5, 40e5, SpatialReferences.getWebMercator())
// create graphic for point
val pointGraphic = Graphic(pointGeometry)
// red diamond point symbol
val pointSymbol =
SimpleMarkerSymbol(SimpleMarkerSymbol.Style.DIAMOND, Color.RED, 10f)
// create simple renderer
val pointRenderer = SimpleRenderer(pointSymbol)
// create a new graphics overlay with these settings and add it to the map view
return GraphicsOverlay().apply {
// add graphic to overlay
graphics.add(pointGraphic)
// set the renderer on the graphics overlay to the new renderer
renderer = pointRenderer
}
}
/**
* Create a polyline, its graphic, a graphics overlay for it, and add it to the map view.
* */
private fun renderedLineGraphicsOverlay(): GraphicsOverlay {
// create line
val lineGeometry = PolylineBuilder(SpatialReferences.getWebMercator()).apply {
addPoint(-10e5, 40e5)
addPoint(20e5, 50e5)
}
// create graphic for polyline
val lineGraphic = Graphic(lineGeometry.toGeometry())
// solid blue line symbol
val lineSymbol =
SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLUE, 5f)
// create simple renderer
val lineRenderer = SimpleRenderer(lineSymbol)
// create graphic overlay for polyline and add it to the map view
return GraphicsOverlay().apply {
// add graphic to overlay
graphics.add(lineGraphic)
// set the renderer on the graphics overlay to the new renderer
renderer = lineRenderer
}
}
/**
* Create a polygon, its graphic, a graphics overlay for it, and add it to the map view.
* */
private fun renderedPolygonGraphicsOverlay(): GraphicsOverlay {
// create polygon
val polygonGeometry = PolygonBuilder(SpatialReferences.getWebMercator()).apply {
addPoint(-20e5, 20e5)
addPoint(20e5, 20e5)
addPoint(20e5, -20e5)
addPoint(-20e5, -20e5)
}
// create graphic for polygon
val polygonGraphic = Graphic(polygonGeometry.toGeometry())
// solid yellow polygon symbol
val polygonSymbol =
SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, Color.YELLOW, null)
// create simple renderer
val polygonRenderer = SimpleRenderer(polygonSymbol)
// create graphic overlay for polygon and add it to the map view
return GraphicsOverlay().apply {
// add graphic to overlay
graphics.add(polygonGraphic)
// set the renderer on the graphics overlay to the new renderer
renderer = polygonRenderer
}
}
/**
* Create a polygon, its graphic, a graphics overlay for it, and add it to the map view.
* */
private fun renderedCurvedPolygonGraphicsOverlay(): GraphicsOverlay {
// create a point for the center of the geometry
val originPoint = Point(40e5, 5e5, SpatialReferences.getWebMercator())
// create polygon
val curvedPolygonGeometry = makeHeartGeometry(originPoint, 10e5)
// create graphic for polygon
val polygonGraphic = Graphic(curvedPolygonGeometry)
// create a simple fill symbol with outline
val curvedLineSymbol = SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLACK, 1f)
val curvedFillSymbol =
SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, Color.RED, curvedLineSymbol)
// create simple renderer
val polygonRenderer = SimpleRenderer(curvedFillSymbol)
// create graphic overlay for polygon and add it to the map view
return GraphicsOverlay().apply {
// add graphic to overlay
graphics.add(polygonGraphic)
// set the renderer on the graphics overlay to the new renderer
renderer = polygonRenderer
}
}
/**
* Create a heart-shape geometry with Bezier and elliptic arc segments from a given [center]
* point and [sideLength].
*/
private fun makeHeartGeometry(center: Point, sideLength: Double): Geometry {
val spatialReference = center.spatialReference
// the x and y coordinates to simplify the calculation
val minX = center.x - 0.5 * sideLength
val minY = center.y - 0.5 * sideLength
// the radius of the arcs
val arcRadius = sideLength * 0.25
// bottom left curve
val leftCurveStart = Point(center.x, minY, spatialReference)
val leftCurveEnd = Point(minX, minY + 0.75 * sideLength, spatialReference)
val leftControlPoint1 = Point(center.x, minY + 0.25 * sideLength, spatialReference)
val leftControlPoint2 = Point(minX, center.y, spatialReference)
val leftCurve = CubicBezierSegment(
leftCurveStart,
leftControlPoint1,
leftControlPoint2,
leftCurveEnd,
spatialReference
)
// top left arc
val leftArcCenter =
Point(minX + 0.25 * sideLength, minY + 0.75 * sideLength, spatialReference)
val leftArc = EllipticArcSegment.createCircularEllipticArc(
leftArcCenter,
arcRadius,
Math.PI,
-Math.PI,
spatialReference
)
// top right arc
val rightArcCenter =
Point(minX + 0.75 * sideLength, minY + 0.75 * sideLength, spatialReference)
val rightArc = EllipticArcSegment.createCircularEllipticArc(
rightArcCenter,
arcRadius,
Math.PI,
-Math.PI,
spatialReference
)
// bottom right curve
val rightCurveStart = Point(minX + sideLength, minY + 0.75 * sideLength, spatialReference)
val rightCurveEnd = leftCurveStart
val rightControlPoint1 = Point(minX + sideLength, center.y, spatialReference)
val rightControlPoint2 = leftControlPoint1
val rightCurve = CubicBezierSegment(
rightCurveStart,
rightControlPoint1,
rightControlPoint2,
rightCurveEnd,
spatialReference
)
val heart = Part(spatialReference).apply {
add(leftCurve)
add(leftArc)
add(rightArc)
add(rightCurve)
}
return Polygon(heart, spatialReference)
}
override fun onPause() {
mapView.pause()
super.onPause()
}
override fun onResume() {
super.onResume()
mapView.resume()
}
override fun onDestroy() {
mapView.dispose()
super.onDestroy()
}
}
| apache-2.0 | a6483d10949bd14ca0ebab2ef27e8eaa | 38.528239 | 100 | 0.673811 | 4.813107 | false | false | false | false |
TonnyTao/Acornote | Acornote_Kotlin/app/src/main/java/tonnysunm/com/acornote/ui/colortag/ColorTagView.kt | 1 | 955 | package tonnysunm.com.acornote.ui.colortag
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import tonnysunm.com.acornote.R
class ColorTagView(context: Context, attrs: AttributeSet) : View(context, attrs) {
private var _colorString = context
.obtainStyledAttributes(attrs, R.styleable.ColorTagView, 0, 0)
.getString(R.styleable.ColorTagView_colorString)
private val paint = Paint().apply {
color = Color.parseColor(_colorString ?: "#000000")
}
var colorString: String?
get() = _colorString
set(value) {
_colorString = value
paint.color = Color.parseColor(value ?: "#000000")
invalidate()
}
override fun onDraw(canvas: Canvas) {
val r = width.toFloat() / 2
canvas.drawCircle(r, r, r, paint)
}
}
| apache-2.0 | fee0ef66e7de664274f92f457880cc8c | 27.939394 | 82 | 0.671204 | 4.134199 | false | false | false | false |
AntriKodSoft/ColorHub | app/src/main/java/cheetatech/com/colorhub/controller/ColorLists.kt | 1 | 3287 | package cheetatech.com.colorhub.controller
import android.content.res.Resources
import cheetatech.com.colorhub.R
import cheetatech.com.colorhub.defines.ColorData
/**
* Created by coderkan on 29.06.2017.
*/
class ColorLists (res: Resources){
var flatList: MutableList<ColorData>? = null
var socialList: MutableList<ColorData>? = null
var metroList: MutableList<ColorData>? = null
var htmlList: MutableList<ColorData>? = null
var materialLists : MutableList<MutableList<ColorData>> ? = null
private var resources: Resources = res
init {
// init flat colors
this.flatList = generateList(R.array.FlatColorCode, R.array.FlatColorName)
this.socialList = generateList(R.array.SocialColorCode, R.array.SocialColorName)
this.metroList = generateList(R.array.MetroColorCode, R.array.MetroColorName)
this.htmlList = generateList(R.array.HtmlColorCode, R.array.HtmlColorName)
//this.materialLists = generateMaterialList(R.array.MaterialColorNames)
//this.materialLists = generateList()
generateList()
println("sadfasdf")
}
fun generateList(){
this.materialLists = mutableListOf()
val arrayId = intArrayOf(R.array.MaterialColorCodeRed, R.array.MaterialColorCodePink, R.array.MaterialColorCodePurple, R.array.MaterialColorCodeDeepPurple, R.array.MaterialColorCodeIndigo, R.array.MaterialColorCodeBlue, R.array.MaterialColorCodeLightBlue, R.array.MaterialColorCodeCyan, R.array.MaterialColorCodeTeal, R.array.MaterialColorCodeGreen, R.array.MaterialColorCodeLightGreen, R.array.MaterialColorCodeLime, R.array.MaterialColorCodeYellow, R.array.MaterialColorCodeAmber, R.array.MaterialColorCodeOrange, R.array.MaterialColorCodeDeepOrange, R.array.MaterialColorCodeBrown, R.array.MaterialColorCodeGrey, R.array.MaterialColorCodeBlueGrey)
var nameList = resources.getStringArray(R.array.MaterialColorNames)?.toMutableList() // Red, Pink color names
var detailNameList = resources.getStringArray(R.array.MaterialColorCodeName)?.toMutableList() // 50 - 100 - 200 color names
for(i in 0 .. arrayId.size.minus(1)){
var arrId = arrayId[i]
var list = resources.getStringArray(arrId)?.toMutableList()
var colorDataList: MutableList<ColorData>? = mutableListOf()
for(j in 0 ..list?.size?.minus(1)!!){
if(j == 0){
var name = nameList?.get(i) ?: ""
colorDataList?.add(ColorData(name, list[j].toUpperCase()))
}else{
var name = detailNameList?.get(j) ?: ""
colorDataList?.add(ColorData(name, list[j].toUpperCase()))
}
}
if(colorDataList != null){
this.materialLists?.add(colorDataList)
}
}
}
fun generateList(arrCode: Int, arrName: Int) : MutableList<ColorData>? {
var list: MutableList<ColorData>? = mutableListOf()
var codeList = resources.getStringArray(arrCode)?.toMutableList()
var nameList = resources.getStringArray(arrName)?.toMutableList()
for (i in 0..codeList!!.size - 1)
list?.add(ColorData(nameList!![i], codeList[i].toUpperCase()))
return list
}
} | gpl-3.0 | 121bb5957dd96fda519bf0840a807b21 | 49.584615 | 658 | 0.682385 | 4.10875 | false | false | false | false |
gradle/gradle | subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/serialization/codecs/TaskNodeCodec.kt | 2 | 17371 | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.gradle.configurationcache.serialization.codecs
import org.gradle.api.Task
import org.gradle.api.file.FileCollection
import org.gradle.api.internal.GeneratedSubclasses
import org.gradle.api.internal.TaskInputsInternal
import org.gradle.api.internal.TaskInternal
import org.gradle.api.internal.TaskOutputsInternal
import org.gradle.api.internal.provider.Providers
import org.gradle.api.internal.tasks.TaskDestroyablesInternal
import org.gradle.api.internal.tasks.TaskLocalStateInternal
import org.gradle.api.internal.tasks.properties.InputParameterUtils
import org.gradle.api.specs.Spec
import org.gradle.configurationcache.extensions.uncheckedCast
import org.gradle.configurationcache.problems.PropertyKind
import org.gradle.configurationcache.problems.PropertyTrace
import org.gradle.configurationcache.serialization.Codec
import org.gradle.configurationcache.serialization.IsolateContext
import org.gradle.configurationcache.serialization.IsolateOwner
import org.gradle.configurationcache.serialization.MutableIsolateContext
import org.gradle.configurationcache.serialization.ReadContext
import org.gradle.configurationcache.serialization.WriteContext
import org.gradle.configurationcache.serialization.beans.BeanPropertyWriter
import org.gradle.configurationcache.serialization.beans.readPropertyValue
import org.gradle.configurationcache.serialization.beans.writeNextProperty
import org.gradle.configurationcache.serialization.readClassOf
import org.gradle.configurationcache.serialization.readCollection
import org.gradle.configurationcache.serialization.readCollectionInto
import org.gradle.configurationcache.serialization.readEnum
import org.gradle.configurationcache.serialization.readNonNull
import org.gradle.configurationcache.serialization.withDebugFrame
import org.gradle.configurationcache.serialization.withIsolate
import org.gradle.configurationcache.serialization.withPropertyTrace
import org.gradle.configurationcache.serialization.writeCollection
import org.gradle.configurationcache.serialization.writeEnum
import org.gradle.execution.plan.LocalTaskNode
import org.gradle.execution.plan.TaskNodeFactory
import org.gradle.internal.execution.model.InputNormalizer
import org.gradle.internal.fingerprint.DirectorySensitivity
import org.gradle.internal.fingerprint.FileNormalizer
import org.gradle.internal.fingerprint.LineEndingSensitivity
import org.gradle.internal.properties.InputBehavior
import org.gradle.internal.properties.InputFilePropertyType
import org.gradle.internal.properties.OutputFilePropertyType
import org.gradle.internal.properties.PropertyValue
import org.gradle.internal.properties.PropertyVisitor
import org.gradle.util.internal.DeferredUtil
class TaskNodeCodec(
private val userTypesCodec: Codec<Any?>,
private val taskNodeFactory: TaskNodeFactory
) : Codec<LocalTaskNode> {
override suspend fun WriteContext.encode(value: LocalTaskNode) {
val task = value.task
writeTask(task)
}
override suspend fun ReadContext.decode(): LocalTaskNode {
val task = readTask()
val node = taskNodeFactory.getOrCreateNode(task) as LocalTaskNode
node.isolated()
return node
}
private
suspend fun WriteContext.writeTask(task: TaskInternal) {
withDebugFrame({ task.path }) {
val taskType = GeneratedSubclasses.unpackType(task)
val projectPath = task.project.path
val taskName = task.name
writeClass(taskType)
writeString(projectPath)
writeString(taskName)
writeNullableString(task.reasonTaskIsIncompatibleWithConfigurationCache.orElse(null))
withDebugFrame({ taskType.name }) {
withTaskOf(taskType, task, userTypesCodec) {
writeUpToDateSpec(task)
writeCollection(task.outputs.cacheIfSpecs)
writeCollection(task.outputs.doNotCacheIfSpecs)
writeReasonNotToTrackState(task)
beanStateWriterFor(task.javaClass).run {
writeStateOf(task)
writeRegisteredPropertiesOf(
task,
this as BeanPropertyWriter
)
}
writeDestroyablesOf(task)
writeLocalStateOf(task)
writeRequiredServices(task)
}
}
}
}
private
suspend fun ReadContext.readTask(): Task {
val taskType = readClassOf<Task>()
val projectPath = readString()
val taskName = readString()
val incompatibleReason = readNullableString()
val task = createTask(projectPath, taskName, taskType, incompatibleReason)
withTaskOf(taskType, task, userTypesCodec) {
readUpToDateSpec(task)
readCollectionInto { task.outputs.cacheIfSpecs.uncheckedCast() }
readCollectionInto { task.outputs.doNotCacheIfSpecs.uncheckedCast() }
readReasonNotToTrackState(task)
beanStateReaderFor(task.javaClass).run {
readStateOf(task)
}
readRegisteredPropertiesOf(task)
readDestroyablesOf(task)
readLocalStateOf(task)
readRequiredServices(task)
}
return task
}
private
suspend fun WriteContext.writeUpToDateSpec(task: TaskInternal) {
// TODO - should just write this as a bean field of the outputs object, and also do this for the registered properties above
if (task.outputs.upToDateSpec.isEmpty) {
writeBoolean(false)
} else {
writeBoolean(true)
write(task.outputs.upToDateSpec)
}
}
private
suspend fun ReadContext.readUpToDateSpec(task: TaskInternal) {
if (readBoolean()) {
task.outputs.upToDateWhen(readNonNull<Spec<Task>>())
}
}
private
fun WriteContext.writeReasonNotToTrackState(task: TaskInternal) {
writeNullableString(task.reasonNotToTrackState.orElse(null))
}
private
fun ReadContext.readReasonNotToTrackState(task: TaskInternal) {
val reasonNotToTrackState = readNullableString()
if (reasonNotToTrackState != null) {
task.doNotTrackState(reasonNotToTrackState)
}
}
private
suspend fun WriteContext.writeRequiredServices(task: TaskInternal) {
writeCollection(task.requiredServices.elements)
}
private
suspend fun ReadContext.readRequiredServices(task: TaskInternal) {
readCollection {
task.usesService(readNonNull())
}
}
private
suspend fun WriteContext.writeDestroyablesOf(task: TaskInternal) {
val destroyables = (task.destroyables as TaskDestroyablesInternal).registeredFiles
if (destroyables.isEmpty) {
writeBoolean(false)
} else {
writeBoolean(true)
write(destroyables)
}
}
private
suspend fun ReadContext.readDestroyablesOf(task: TaskInternal) {
if (readBoolean()) {
task.destroyables.register(readNonNull<FileCollection>())
}
}
private
suspend fun WriteContext.writeLocalStateOf(task: TaskInternal) {
val localState = (task.localState as TaskLocalStateInternal).registeredFiles
if (localState.isEmpty) {
writeBoolean(false)
} else {
writeBoolean(true)
write(localState)
}
}
private
suspend fun ReadContext.readLocalStateOf(task: TaskInternal) {
if (readBoolean()) {
task.localState.register(readNonNull<FileCollection>())
}
}
}
private
suspend fun <T> T.withTaskOf(
taskType: Class<*>,
task: TaskInternal,
codec: Codec<Any?>,
action: suspend () -> Unit
) where T : IsolateContext, T : MutableIsolateContext {
withIsolate(IsolateOwner.OwnerTask(task), codec) {
withPropertyTrace(PropertyTrace.Task(taskType, task.path)) {
if (task.isCompatibleWithConfigurationCache) {
action()
} else {
forIncompatibleType(action)
}
}
}
}
private
sealed class RegisteredProperty {
data class Input(
val propertyName: String,
val propertyValue: PropertyValue,
val optional: Boolean
) : RegisteredProperty()
data class InputFile(
val propertyName: String,
val propertyValue: PropertyValue,
val optional: Boolean,
val filePropertyType: InputFilePropertyType,
val behavior: InputBehavior,
val normalizer: FileNormalizer?,
val directorySensitivity: DirectorySensitivity,
val lineEndingSensitivity: LineEndingSensitivity
) : RegisteredProperty()
data class OutputFile(
val propertyName: String,
val propertyValue: PropertyValue,
val optional: Boolean,
val filePropertyType: OutputFilePropertyType
) : RegisteredProperty()
}
private
suspend fun WriteContext.writeRegisteredPropertiesOf(
task: Task,
propertyWriter: BeanPropertyWriter
) = propertyWriter.run {
suspend fun writeProperty(propertyName: String, propertyValue: Any?, kind: PropertyKind) {
writeString(propertyName)
writeNextProperty(propertyName, propertyValue, kind)
}
suspend fun writeInputProperty(propertyName: String, propertyValue: Any?) =
writeProperty(propertyName, propertyValue, PropertyKind.InputProperty)
suspend fun writeOutputProperty(propertyName: String, propertyValue: Any?) =
writeProperty(propertyName, propertyValue, PropertyKind.OutputProperty)
val inputProperties = collectRegisteredInputsOf(task)
writeCollection(inputProperties) { property ->
property.run {
when (this) {
is RegisteredProperty.InputFile -> {
val finalValue = DeferredUtil.unpackOrNull(propertyValue)
writeInputProperty(propertyName, finalValue)
writeBoolean(optional)
writeBoolean(true)
writeEnum(filePropertyType)
writeEnum(behavior)
writeEnum(normalizer!! as InputNormalizer)
writeEnum(directorySensitivity)
writeEnum(lineEndingSensitivity)
}
is RegisteredProperty.Input -> {
val finalValue = InputParameterUtils.prepareInputParameterValue(propertyValue)
writeInputProperty(propertyName, finalValue)
writeBoolean(optional)
writeBoolean(false)
}
else -> throw IllegalStateException()
}
}
}
val outputProperties = collectRegisteredOutputsOf(task)
writeCollection(outputProperties) { property ->
property.run {
val finalValue = DeferredUtil.unpackOrNull(propertyValue)
writeOutputProperty(propertyName, finalValue)
writeBoolean(optional)
writeEnum(filePropertyType)
}
}
}
private
fun collectRegisteredOutputsOf(task: Task): List<RegisteredProperty.OutputFile> {
val properties = mutableListOf<RegisteredProperty.OutputFile>()
(task.outputs as TaskOutputsInternal).visitRegisteredProperties(object : PropertyVisitor {
override fun visitOutputFileProperty(
propertyName: String,
optional: Boolean,
value: PropertyValue,
filePropertyType: OutputFilePropertyType
) {
properties.add(
RegisteredProperty.OutputFile(
propertyName,
value,
optional,
filePropertyType
)
)
}
})
return properties
}
private
fun collectRegisteredInputsOf(task: Task): List<RegisteredProperty> {
val properties = mutableListOf<RegisteredProperty>()
(task.inputs as TaskInputsInternal).visitRegisteredProperties(object : PropertyVisitor {
override fun visitInputFileProperty(
propertyName: String,
optional: Boolean,
behavior: InputBehavior,
directorySensitivity: DirectorySensitivity,
lineEndingSensitivity: LineEndingSensitivity,
normalizer: FileNormalizer?,
propertyValue: PropertyValue,
filePropertyType: InputFilePropertyType
) {
properties.add(
RegisteredProperty.InputFile(
propertyName,
propertyValue,
optional,
filePropertyType,
behavior,
normalizer,
directorySensitivity,
lineEndingSensitivity
)
)
}
override fun visitInputProperty(
propertyName: String,
propertyValue: PropertyValue,
optional: Boolean
) {
properties.add(
RegisteredProperty.Input(
propertyName,
propertyValue,
optional
)
)
}
})
return properties
}
private
suspend fun ReadContext.readRegisteredPropertiesOf(task: Task) {
readInputPropertiesOf(task)
readOutputPropertiesOf(task)
}
private
suspend fun ReadContext.readInputPropertiesOf(task: Task) =
readCollection {
val propertyName = readString()
readPropertyValue(PropertyKind.InputProperty, propertyName) { propertyValue ->
val optional = readBoolean()
val isFileInputProperty = readBoolean()
when {
isFileInputProperty -> {
val filePropertyType = readEnum<InputFilePropertyType>()
val inputBehavior = readEnum<InputBehavior>()
val normalizer = readEnum<InputNormalizer>()
val directorySensitivity = readEnum<DirectorySensitivity>()
val lineEndingNormalization = readEnum<LineEndingSensitivity>()
(task as TaskInternal).inputs.run {
when (filePropertyType) {
InputFilePropertyType.FILE -> file(pack(propertyValue))
InputFilePropertyType.DIRECTORY -> dir(pack(propertyValue))
InputFilePropertyType.FILES -> files(pack(propertyValue))
}
}.run {
withPropertyName(propertyName)
optional(optional)
skipWhenEmpty(inputBehavior.shouldSkipWhenEmpty())
withInternalNormalizer(normalizer)
ignoreEmptyDirectories(directorySensitivity == DirectorySensitivity.IGNORE_DIRECTORIES)
normalizeLineEndings(lineEndingNormalization == LineEndingSensitivity.NORMALIZE_LINE_ENDINGS)
}
}
else -> {
task.inputs
.property(propertyName, propertyValue)
.optional(optional)
}
}
}
}
private
fun pack(value: Any?) = value ?: Providers.notDefined<Any>()
private
suspend fun ReadContext.readOutputPropertiesOf(task: Task) =
readCollection {
val propertyName = readString()
readPropertyValue(PropertyKind.OutputProperty, propertyName) { propertyValue ->
val optional = readBoolean()
val filePropertyType = readEnum<OutputFilePropertyType>()
task.outputs.run {
when (filePropertyType) {
OutputFilePropertyType.DIRECTORY -> dir(pack(propertyValue))
OutputFilePropertyType.DIRECTORIES -> dirs(pack(propertyValue))
OutputFilePropertyType.FILE -> file(pack(propertyValue))
OutputFilePropertyType.FILES -> files(pack(propertyValue))
}
}.run {
withPropertyName(propertyName)
optional(optional)
}
}
}
private
fun ReadContext.createTask(projectPath: String, taskName: String, taskClass: Class<out Task>, incompatibleReason: String?): TaskInternal {
val task = getProject(projectPath).tasks.createWithoutConstructor(taskName, taskClass) as TaskInternal
if (incompatibleReason != null) {
task.notCompatibleWithConfigurationCache(incompatibleReason)
}
return task
}
| apache-2.0 | c23a2868b30acfd5de07e99b7369307a | 34.964803 | 138 | 0.652927 | 5.411526 | false | true | false | false |
aucd29/ani | library/src/main/java/net/sarangnamu/common/ani/BkAni.kt | 1 | 5223 | package net.sarangnamu.common.ani
import android.animation.Animator
import android.animation.ArgbEvaluator
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.annotation.TargetApi
import android.content.Context
import android.os.Build
import android.support.annotation.ColorRes
import android.support.v4.content.ContextCompat
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.RelativeLayout
/**
* Created by <a href="mailto:[email protected]">Burke Choi</a> on 2017. 11. 2.. <p/>
*/
class Translation {
companion object {
fun startX(view: View, move: Float, f: ((Animator?) -> Unit)? = null) {
start(view, move, "translationX", f)
}
fun startY(view: View, move: Float, f: ((Animator?) -> Unit)? = null) {
start(view, move, "translationY", f)
}
private fun start(view: View, move: Float, type: String, f: ((Animator?) -> Unit)? = null) {
val value = move * view.context.resources.displayMetrics.density
ObjectAnimator.ofFloat(view, type, value).apply {
f?.let { addEndListener(it) }
}.start()
}
}
}
class Fade {
companion object {
fun start(hideView: View, showView: View, f: ((Animator?) -> Unit)? = null) {
ObjectAnimator.ofFloat(hideView, "alpha", 0.25f, 1f, 1f).start()
ObjectAnimator.ofFloat(showView, "alpha", 1f, 1f, 1f).apply {
f?.let { this.addEndListener(it) }
}.start()
}
}
}
class FadeColor {
companion object {
fun start(view: View, fcolor: Int, scolor: Int, f: ((Animator?) -> Unit)? = null, duration: Long = 500) {
ObjectAnimator.ofObject(view, "backgroundColor", ArgbEvaluator(), fcolor, scolor).apply {
this.duration = duration
f?.let { this.addEndListener(it) }
}.start()
}
fun startResource(view: View, @ColorRes fcolor: Int, @ColorRes scolor: Int, f: ((Animator?) -> Unit)? = null, duration: Long = 500) {
start(view, view.context.color(fcolor), view.context.color(scolor), f, duration)
}
}
}
class FadeStatusBar {
companion object {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun start(window: Window, fcolor:Int, scolor: Int, f: ((Animator?) -> Unit)? = null, duration: Long = 500) {
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
val from = window.context.color(fcolor)
val to = window.context.color(scolor)
ValueAnimator.ofArgb(from, to).apply {
this.duration = duration
this.addUpdateListener { window.statusBarColor = it.animatedValue as Int }
f?.let { this.addEndListener(it) }
}.start()
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun startResource(window: Window, @ColorRes fcolor: Int, @ColorRes scolor: Int, f: ((Animator?) -> Unit)? = null, duration: Long = 500) {
start(window, ContextCompat.getColor(window.context, fcolor), ContextCompat.getColor(window.context, scolor), f, duration)
}
}
}
class Resize {
companion object {
fun height(view: View, height: Int, f: ((Animator?) -> Unit)? = null, duration: Long = 600) {
ValueAnimator.ofInt(view.measuredHeight, height).apply {
addUpdateListener {
val value = animatedValue as Int
when (view.parent) {
is LinearLayout -> view.layoutParams.height = value // 되는 코드인지 확인해봐야 함
is RelativeLayout -> view.layoutParams.height = value
is FrameLayout -> view.layoutParams.height = value
}
}
addListener(object: Animator.AnimatorListener {
override fun onAnimationRepeat(p0: Animator?) { }
override fun onAnimationCancel(p0: Animator?) { }
override fun onAnimationStart(p0: Animator?) { }
override fun onAnimationEnd(animation: Animator?) {
removeAllUpdateListeners()
removeAllListeners()
f?.let { f(animation) }
}
})
this.duration = duration
}.start()
}
}
}
private inline fun Animator.addEndListener(crossinline f: (Animator?) -> Unit) {
addListener(object : Animator.AnimatorListener {
override fun onAnimationStart(p0: Animator?) {}
override fun onAnimationCancel(p0: Animator?) {}
override fun onAnimationRepeat(p0: Animator?) {}
override fun onAnimationEnd(animation: Animator?) {
removeListener(this)
f(animation)
}
})
}
private inline fun Context.color(@ColorRes color:Int): Int = ContextCompat.getColor(this, color)
| apache-2.0 | 17588ec3d234803e79d1353740024f9f | 38.386364 | 145 | 0.598577 | 4.372582 | false | false | false | false |
frendyxzc/KotlinNews | model/src/main/java/vip/frendy/model/entity/News.kt | 1 | 796 | package vip.frendy.model.entity
import vip.frendy.model.data.Constants
/**
* Created by iiMedia on 2017/6/2.
*/
data class RespGetNews (
val code: Int,
val msg: String,
val data: ArrayList<News>
)
data class News(
var title: String,
var summary: String,
var image: String,
var image_type: String,
var news_id: String = "1000",
var sn: String = "2D879AE7DAAB0E06210EEE2FE7D04B1CCDA4A914209DBF7203F03A7C48FA1773A6E1C60A17CD9A653CF438F9D75CCB82",
var url: String = Constants.DEFAULT_URL,
var skip_way: Int = 0,
// video
var target_url: String = ""
)
fun News.getUrl(): String {
return Constants.XW_BASE_URL + Constants.APP_INFO + "&news_id=" + news_id + "&sn=" + sn + "&equip_type=0"
} | mit | db6640cb4be836450e98739f84aee06a | 26.482759 | 124 | 0.628141 | 3.015152 | false | false | false | false |
romasch/yaml-configuration-generator | src/main/kotlin/ch/romasch/gradle/yaml/config/generation/ClassData.kt | 1 | 3580 | package ch.romasch.gradle.yaml.config.generation
class ClassData(val name: String) {
val attributes: MutableMap<String, String> = HashMap()
val attributeValues: MutableMap<String, String> = HashMap()
fun generate(packageName: String): String {
val writer = JavaCodeWriter()
writer
.write("package $packageName;")
.writeln()
.writeln("public final class $name")
.beginBlock()
.writeln()
// members
attributes.forEach { name, type ->
writer.writeln("private final $type ${lower(name)};")
}
// Default constructor
writer.writeln()
.writeln("$name()")
.beginBlock()
.writelnEach(attributes.keys.map(this::generateInitializationPart))
.endBlock()
// Override Constructor
writer.writeln()
.writeln("private $name")
.writeArgumentList(attributes.map(this::combineEntry))
.beginBlock()
.writelnEach(attributes.keys.map(this::lower).map(this::generateAssignmentPart))
.endBlock()
// Getters
attributes.forEach {name, type ->
writer.writeln()
.writeln("public $type get${name}()")
.beginBlock()
.writeln("return ${lower(name)};")
.endBlock()
}
// override()
writer.writeln()
.writeln("$name override(java.util.Map yaml)")
.beginBlock()
attributes.forEach {name, type ->
writer.writeln("$type ${lower(name)} = this.${lower(name)};")
.writeln("if (yaml.containsKey(\"$name\") && yaml.get(\"$name\") instanceof ${yamlType(type)})")
.beginBlock()
.writeln("${lower(name)} = ")
.write(generateOverridePart(name, type))
.endBlock()
}
writer.writeln("return new $name")
.writeArgumentList(attributes.keys.map(this::lower))
.write(";")
.endBlock()
// end class block
return writer
.endBlock()
.writeln()
.toString()
}
private fun generateInitializationPart(attribute: String): String {
return "this.${lower(attribute)} = ${generateInitializationValue(attribute)};"
}
private fun generateInitializationValue(attribute: String): String? {
val type = attributes[attribute]
return when (type) {
"Integer", "Boolean" -> attributeValues[attribute]
"String" -> "\"${attributeValues[attribute]}\""
else -> "new $type()"
}
}
private fun generateAssignmentPart(name: String) = "this.$name = $name;"
private fun generateOverridePart(name: String, type: String): String =
if (isScalar(type)) "($type) yaml.get(\"$name\");"
else "${lower(name)}.override((java.util.Map) yaml.get(\"$name\"));"
private fun lower(name: String) = name[0].toLowerCase() + name.substring(1)
private fun isScalar(type: String?) = yamlType(type) != "java.util.Map"
private fun yamlType(type: String?) = when (type) {
"Integer" -> "Integer"
"Boolean" -> "Boolean"
"String" -> "String"
else -> "java.util.Map"
}
private fun combineEntry(entry: Map.Entry<String, String>) = entry.value + " " + lower(entry.key)
}
| mit | 6218c0309bb32d78a698994eb13da02e | 33.095238 | 116 | 0.531285 | 4.698163 | false | false | false | false |
elect86/modern-jogl-examples | src/main/kotlin/main/tut04/orthoCube.kt | 2 | 5344 | package main.tut04
import com.jogamp.newt.event.KeyEvent
import com.jogamp.opengl.GL.*
import com.jogamp.opengl.GL2ES3.GL_COLOR
import com.jogamp.opengl.GL3
import glNext.*
import glm.size
import glm.vec._4.Vec4
import main.framework.Framework
import main.framework.Semantic
import uno.buffer.*
import uno.glsl.programOf
/**
* Created by GBarbieri on 22.02.2017.
*/
fun main(args: Array<String>) {
OrthoCube_().setup("Tutorial 04 - Ortho Cube")
}
class OrthoCube_ : Framework() {
var theProgram = 0
var offsetUniform = 0
val vertexBufferObject = intBufferBig(1)
val vao = intBufferBig(1)
override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
initializeVertexBuffer(gl)
glGenVertexArray(vao)
glBindVertexArray(vao)
glEnable(GL_CULL_FACE)
glCullFace(GL_BACK)
glFrontFace(GL_CW)
}
fun initializeProgram(gl: GL3) = with(gl) {
theProgram = programOf(gl, javaClass, "tut04", "ortho-with-offset.vert", "standard-colors.frag")
offsetUniform = glGetUniformLocation(theProgram, "offset")
}
fun initializeVertexBuffer(gl: GL3) = with(gl) {
glGenBuffer(vertexBufferObject)
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject)
glBufferData(GL_ARRAY_BUFFER, vertexData, GL_STATIC_DRAW)
glBindBuffer(GL_ARRAY_BUFFER)
}
override fun display(gl: GL3) = with(gl) {
glClearBufferf(GL_COLOR, 0)
glUseProgram(theProgram)
glUniform2f(offsetUniform, 0.5f, 0.25f)
val colorData = vertexData.size / 2
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject)
glEnableVertexAttribArray(glf.pos4_col4)
glEnableVertexAttribArray(glf.pos4_col4[1])
glVertexAttribPointer(glf.pos4_col4, 0)
glVertexAttribPointer(glf.pos4_col4[1], colorData)
glDrawArrays(36)
glDisableVertexAttribArray(glf.pos4_col4)
glDisableVertexAttribArray(glf.pos4_col4[1])
glUseProgram()
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl){
glViewport(w, h)
}
override fun end(gl: GL3) = with(gl) {
glDeleteProgram(theProgram)
glDeleteBuffer(vertexBufferObject)
glDeleteVertexArray(vao)
destroyBuffers(vao, vertexBufferObject, vertexData)
}
override fun keyPressed(keyEvent: KeyEvent) {
when (keyEvent.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
}
}
val vertexData = floatBufferOf(
+0.25f, +0.25f, +0.75f, 1.0f,
+0.25f, -0.25f, +0.75f, 1.0f,
-0.25f, +0.25f, +0.75f, 1.0f,
+0.25f, -0.25f, +0.75f, 1.0f,
-0.25f, -0.25f, +0.75f, 1.0f,
-0.25f, +0.25f, +0.75f, 1.0f,
+0.25f, +0.25f, -0.75f, 1.0f,
-0.25f, +0.25f, -0.75f, 1.0f,
+0.25f, -0.25f, -0.75f, 1.0f,
+0.25f, -0.25f, -0.75f, 1.0f,
-0.25f, +0.25f, -0.75f, 1.0f,
-0.25f, -0.25f, -0.75f, 1.0f,
-0.25f, +0.25f, +0.75f, 1.0f,
-0.25f, -0.25f, +0.75f, 1.0f,
-0.25f, -0.25f, -0.75f, 1.0f,
-0.25f, +0.25f, +0.75f, 1.0f,
-0.25f, -0.25f, -0.75f, 1.0f,
-0.25f, +0.25f, -0.75f, 1.0f,
+0.25f, +0.25f, +0.75f, 1.0f,
+0.25f, -0.25f, -0.75f, 1.0f,
+0.25f, -0.25f, +0.75f, 1.0f,
+0.25f, +0.25f, +0.75f, 1.0f,
+0.25f, +0.25f, -0.75f, 1.0f,
+0.25f, -0.25f, -0.75f, 1.0f,
+0.25f, +0.25f, -0.75f, 1.0f,
+0.25f, +0.25f, +0.75f, 1.0f,
-0.25f, +0.25f, +0.75f, 1.0f,
+0.25f, +0.25f, -0.75f, 1.0f,
-0.25f, +0.25f, +0.75f, 1.0f,
-0.25f, +0.25f, -0.75f, 1.0f,
+0.25f, -0.25f, -0.75f, 1.0f,
-0.25f, -0.25f, +0.75f, 1.0f,
+0.25f, -0.25f, +0.75f, 1.0f,
+0.25f, -0.25f, -0.75f, 1.0f,
-0.25f, -0.25f, -0.75f, 1.0f,
-0.25f, -0.25f, +0.75f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f)
} | mit | 79a9e55c4833196dfc74fdd5f6b5ddb8 | 25.859296 | 104 | 0.493451 | 2.374056 | false | false | false | false |
industrial-data-space/trusted-connector | ids-api/src/main/java/de/fhg/aisec/ids/api/Result.kt | 1 | 925 | /*-
* ========================LICENSE_START=================================
* ids-api
* %%
* Copyright (C) 2019 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.api
/** Generic result of an API call. */
open class Result(var isSuccessful: Boolean = true, var message: String = "ok")
| apache-2.0 | 0a2f40ffd812efd348607887ef811ba8 | 39.217391 | 79 | 0.625946 | 4.404762 | false | false | false | false |
Geobert/Efficio | app/src/main/kotlin/fr/geobert/efficio/EditDepartmentsActivity.kt | 1 | 5584 | package fr.geobert.efficio
import android.app.*
import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.helper.ItemTouchHelper
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import fr.geobert.efficio.data.Department
import fr.geobert.efficio.data.DepartmentManager
import fr.geobert.efficio.db.DepartmentTable
import fr.geobert.efficio.dialog.DeleteConfirmationDialog
import fr.geobert.efficio.dialog.MessageDialog
import fr.geobert.efficio.drag.DepartmentDragHelper
import fr.geobert.efficio.misc.DELETE_DEP
import fr.geobert.efficio.misc.DeleteDialogInterface
import kotlinx.android.synthetic.main.department_chooser_dialog.*
import kotlinx.android.synthetic.main.edit_dep_text.view.*
import kotlin.properties.Delegates
class EditDepartmentsActivity : BaseActivity(), DepartmentManager.DepartmentChoiceListener, DeleteDialogInterface {
private var depManager: DepartmentManager by Delegates.notNull()
private var storeId: Long by Delegates.notNull()
private var depUnderEdit: Department? = null
private val onDepRenamedListener = object : EditDepartmentNameDialog.OnDepRenameListener {
override fun onRenamingDone() {
depManager.request()
}
}
private val depTouchHelper by lazy { ItemTouchHelper(DepartmentDragHelper(this, depManager)) }
companion object {
fun callMe(frg: Fragment, storeId: Long) {
val i = Intent(frg.activity, EditDepartmentsActivity::class.java)
i.putExtra("storeId", storeId)
frg.startActivityForResult(i, 1)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.edit_departments_activity)
title = getString(R.string.edit_departments)
storeId = intent.extras.getLong("storeId")
depManager = DepartmentManager(this, findViewById(R.id.department_layout)!!,
storeId, this, true)
depManager.setEditMode(true)
depManager.request()
depTouchHelper.attachToRecyclerView(dep_list)
setIcon(R.mipmap.ic_action_arrow_left)
setIconOnClick(View.OnClickListener { onBackPressed() })
setSpinnerVisibility(View.GONE)
titleColor = ContextCompat.getColor(this, android.R.color.primary_text_dark)
}
override fun onBackPressed() {
setResult(if (depManager.hasChanged()) Activity.RESULT_OK else Activity.RESULT_CANCELED)
super.onBackPressed()
}
override fun onDepartmentChosen(d: Department) {
depUnderEdit = d
EditDepartmentNameDialog.newInstance(d.id, d.name, onDepRenamedListener).show(fragmentManager,
"RenameDepDialog")
}
override fun onDeletedConfirmed() {
val d = depUnderEdit
if (d != null && (DepartmentTable.deleteDep(this, d.id) > 0)) {
depManager.remove(d)
}
}
class EditDepartmentNameDialog : DialogFragment() {
interface OnDepRenameListener {
fun onRenamingDone()
}
private var listener: OnDepRenameListener by Delegates.notNull()
companion object {
fun newInstance(depId: Long, depName: String, listener: OnDepRenameListener): EditDepartmentNameDialog {
val d = EditDepartmentNameDialog()
d.listener = listener
val b = Bundle()
b.putLong("depId", depId)
b.putString("depName", depName)
d.arguments = b
return d
}
}
private var customView: LinearLayout by Delegates.notNull()
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog? {
val b = AlertDialog.Builder(activity)
customView = LayoutInflater.from(activity).inflate(R.layout.edit_dep_text, null) as LinearLayout
customView.edt.setText(arguments.getString("depName"))
customView.edt.selectAll()
b.setTitle(R.string.edit_dep_name).setView(customView).setCancelable(true).
setPositiveButton(android.R.string.ok, { _, _ -> onOkClicked() }).
setNeutralButton(R.string.delete, { _, _ -> onDeleteClicked() }).
setNegativeButton(android.R.string.cancel, { d, _ -> d.cancel() })
return b.create()
}
private fun onDeleteClicked() {
DeleteConfirmationDialog.newInstance(getString(R.string.confirm_delete_dep),
getString(R.string.confirm_delete_dep_title).format(arguments.getString("depName")),
DELETE_DEP).show(fragmentManager, "DeleteDepConfirm")
}
private fun onOkClicked() {
val s = customView.edt.text.trim().toString()
if (s.isNotEmpty()) {
if (DepartmentTable.updateDepartment(activity, arguments.getLong("depId"), s) > 0) {
listener.onRenamingDone()
dialog.cancel()
} else {
MessageDialog.newInstance(R.string.error_on_update_dep_name,
R.string.error_title).show(activity.fragmentManager,
"ErrDialog")
}
} else {
MessageDialog.newInstance(R.string.error_empty_dep_name,
R.string.error_title).show(activity.fragmentManager,
"ErrDialog")
}
}
}
} | gpl-2.0 | 64c04abaa45271aba2e0cfea35bc03c8 | 39.179856 | 116 | 0.649355 | 4.664996 | false | false | false | false |
Burning-Man-Earth/iBurn-Android | iBurn/src/main/java/com/gaiagps/iburn/adapters/EventStartTimeSectionIndexer.kt | 1 | 2362 | package com.gaiagps.iburn.adapters
import com.gaiagps.iburn.api.typeadapter.PlayaDateTypeAdapter
import com.gaiagps.iburn.database.PlayaItem
import com.gaiagps.iburn.database.Event
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
/**
* Created by dbro on 6/14/17.
*/
class EventStartTimeSectionIndexer(items: List<PlayaItem>? = null) : PlayaItemSectionIndxer(items) {
private val apiDateFormat = PlayaDateTypeAdapter.buildIso8601Format()
private val humanDateFormat = SimpleDateFormat("E h a", Locale.US)
private var sections: ArrayList<String>? = null
private var sectionPositions: ArrayList<Int>? = null
override fun getSections(): Array<Any> {
if (sections == null && items != null) {
val newSections = ArrayList<String>()
val newSectionPositions = ArrayList<Int>()
var lastSection = ""
items?.forEachIndexed { index, event ->
val thisSection = getSectionStringForEvent(event as Event)
if (thisSection != lastSection) {
newSections.add(thisSection)
newSectionPositions.add(index)
}
lastSection = thisSection
}
sections = newSections
sectionPositions = newSectionPositions
}
return sections?.toArray() ?: emptyArray()
}
override fun getSectionForPosition(position: Int): Int {
// Requesting the lastIndex of an empty array yields -1, which will produce ArrayIndexOutOfBoundsExceptions
if (sectionPositions?.isEmpty() ?: true) return 0
sectionPositions?.forEachIndexed { index, sectionPosition ->
if (sectionPosition > position) return index - 1
}
return sectionPositions?.lastIndex ?: 0
}
override fun getPositionForSection(section: Int): Int {
// not needed
return 0
}
private fun getSectionStringForEvent(event: Event): String {
if (event.allDay) {
return "All ${event.startTimePretty}"
} else {
try {
return humanDateFormat.format(apiDateFormat.parse(event.startTime))
} catch (e: ParseException) {
return event.startTimePretty
}
}
}
}
| mpl-2.0 | a15b8822c4ab65d987e4d28a9cadda37 | 31.356164 | 115 | 0.636325 | 4.910603 | false | false | false | false |
pardom/navigator | navigator/src/main/kotlin/navigator/route/LocalHistoryRoute.kt | 1 | 3441 | package navigator.route
import kotlinx.coroutines.experimental.Deferred
import kotlinx.coroutines.experimental.async
import navigator.Route
import navigator.Route.PopDisposition
import navigator.route.LocalHistoryRoute.Entry
/**
* A route that can handle back navigation internally by popping a list.
*
* When a [navigator.Navigator] is instructed to pop, the current route is given an opportunity to
* handle the pop internally. A LocalHistoryRoute handles the pop internally if its list of local
* history entries is non-empty. Rather than being removed as the current route, the most recent
* [Entry] is removed from the list and its [Entry.onRemove] is called.
*/
interface LocalHistoryRoute<T> : Route<T> {
val localHistory: MutableList<Entry>
override val willHandlePopInternally: Boolean
get() {
return localHistory.isNotEmpty()
}
override fun willPop(): Deferred<PopDisposition> = async {
if (willHandlePopInternally) PopDisposition.POP else super.willPop().await()
}
override fun didPop(result: Any?): Boolean {
if (localHistory.isNotEmpty()) {
val entry = localHistory.removeAt(localHistory.lastIndex)
assert(entry.owner == this)
entry.owner = null
entry.notifyRemoved()
if (localHistory.isEmpty()) {
changedInternalState()
}
return false
}
return super.didPop(result)
}
/**
* Adds a local history entry to this route.
*
* When asked to pop, if this route has any local history entries, this route will handle the
* pop internally by removing the most recently added local history entry.
*
* The given local history entry must not already be part of another local history route.
*/
fun addLocalHistoryEntry(entry: Entry) {
assert(entry.owner == null)
entry.owner = this
val wasEmpty = localHistory.isEmpty()
localHistory.add(entry)
if (wasEmpty) {
changedInternalState()
}
}
/**
* Remove a local history entry from this route.
*
* The entry's [Entry.onRemove] callback, if any, will be called synchronously.
*/
fun removeLocalHistoryEntry(entry: Entry) {
assert(entry.owner == this)
assert(localHistory.contains(entry))
localHistory.remove(entry)
entry.owner = null
entry.notifyRemoved()
if (localHistory.isEmpty()) {
changedInternalState()
}
}
/**
* Called whenever the internal state of the route has changed.
*
* This should be called whenever [willHandlePopInternally] and [didPop] might change the value
* they return. It is used by [ModalRoute], for example, to report the new information via its
* inherited widget to any children of the route.
*/
fun changedInternalState() {}
/**
* An entry in the history of a [LocalHistoryRoute].
*/
class Entry(private val onRemove: () -> Unit) {
internal var owner: LocalHistoryRoute<*>? = null
/**
* Remove this entry from the history of its associated [LocalHistoryRoute].
*/
fun remove() {
owner?.removeLocalHistoryEntry(this)
assert(owner == null)
}
internal fun notifyRemoved() {
onRemove?.invoke()
}
}
}
| apache-2.0 | dca24c51355573a79398501c7e8dccb6 | 30.861111 | 99 | 0.640221 | 4.637466 | false | false | false | false |
quarck/CalendarNotification | app/src/main/java/com/github/quarck/calnotify/app/AlarmScheduler.kt | 1 | 7088 | //
// Calendar Notifications Plus
// Copyright (C) 2016 Sergey Parshin ([email protected])
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
package com.github.quarck.calnotify.app
import android.content.Context
import com.github.quarck.calnotify.Consts
import com.github.quarck.calnotify.Settings
import com.github.quarck.calnotify.broadcastreceivers.ReminderAlarmBroadcastReceiver
import com.github.quarck.calnotify.broadcastreceivers.ReminderExactAlarmBroadcastReceiver
import com.github.quarck.calnotify.broadcastreceivers.SnoozeAlarmBroadcastReceiver
import com.github.quarck.calnotify.broadcastreceivers.SnoozeExactAlarmBroadcastReceiver
import com.github.quarck.calnotify.calendar.isNotSnoozed
import com.github.quarck.calnotify.calendar.isNotSpecial
import com.github.quarck.calnotify.calendar.isSnoozed
import com.github.quarck.calnotify.eventsstorage.EventsStorage
import com.github.quarck.calnotify.logs.DevLog
import com.github.quarck.calnotify.persistentState
import com.github.quarck.calnotify.quiethours.QuietHoursManagerInterface
import com.github.quarck.calnotify.reminders.ReminderState
import com.github.quarck.calnotify.ui.MainActivity
import com.github.quarck.calnotify.utils.alarmManager
import com.github.quarck.calnotify.utils.cancelExactAndAlarm
import com.github.quarck.calnotify.utils.setExactAndAlarm
object AlarmScheduler : AlarmSchedulerInterface {
const val LOG_TAG = "AlarmScheduler"
override fun rescheduleAlarms(context: Context, settings: Settings, quietHoursManager: QuietHoursManagerInterface) {
DevLog.debug(LOG_TAG, "rescheduleAlarms called");
EventsStorage(context).use {
db ->
val events = db.events
// Schedule event (snooze) alarm
var nextEventAlarm =
events.filter { it.isSnoozed && it.isNotSpecial }.map { it.snoozedUntil }.min()
if (nextEventAlarm != null) {
val currentTime = System.currentTimeMillis()
if (nextEventAlarm < currentTime) {
DevLog.error(LOG_TAG, "CRITICAL: rescheduleAlarms: nextAlarm=$nextEventAlarm is less than currentTime $currentTime");
nextEventAlarm = currentTime + Consts.MINUTE_IN_SECONDS * 5 * 1000L;
}
DevLog.info(LOG_TAG, "next alarm at ${nextEventAlarm} (T+${(nextEventAlarm - currentTime) / 1000L}s)");
context.alarmManager.setExactAndAlarm(
context,
settings.useSetAlarmClock,
nextEventAlarm,
SnoozeAlarmBroadcastReceiver::class.java, // ignored on KitKat and below
SnoozeExactAlarmBroadcastReceiver::class.java,
MainActivity::class.java)
context.persistentState.nextSnoozeAlarmExpectedAt = nextEventAlarm
}
else { // if (nextEventAlarm != null) {
DevLog.info(LOG_TAG, "Cancelling alarms (snooze and reminder)");
context.alarmManager.cancelExactAndAlarm(
context,
SnoozeAlarmBroadcastReceiver::class.java,
SnoozeExactAlarmBroadcastReceiver::class.java)
}
val reminderState = ReminderState(context)
// Schedule reminders alarm
var reminderAlarmNextFire: Long? = null
val quietHoursOneTimeReminderEnabled =
reminderState.quietHoursOneTimeReminderEnabled
if (settings.remindersEnabled || quietHoursOneTimeReminderEnabled) {
val activeEvents = events.filter {
it.isNotSnoozed && it.isNotSpecial && !it.isMuted && !it.isTask
}
val hasActiveNotifications = activeEvents.any()
val hasActiveAlarms = activeEvents.any { it.isAlarm }
if (hasActiveNotifications) {
reminderAlarmNextFire = System.currentTimeMillis() +
settings.reminderIntervalMillisForIndex(reminderState.currentReminderPatternIndex)
if (quietHoursOneTimeReminderEnabled) {
// a little bit of a hack to set it to fire "as soon as possible after quiet hours"
reminderAlarmNextFire = System.currentTimeMillis() + Consts.ALARM_THRESHOLD
}
if (!hasActiveAlarms) {
val quietUntil = quietHoursManager.getSilentUntil(settings, reminderAlarmNextFire)
if (quietUntil != 0L) {
DevLog.info(LOG_TAG, "Reminder alarm moved: $reminderAlarmNextFire -> ${quietUntil + Consts.ALARM_THRESHOLD}, reason: quiet hours");
// give a little extra delay, so if requests would fire precisely at the
// quietUntil, reminders would wait a bit longer
reminderAlarmNextFire = quietUntil + Consts.ALARM_THRESHOLD
}
}
DevLog.info(LOG_TAG, "Reminder Alarm next fire: $reminderAlarmNextFire")
}
else { // if (hasActiveNotifications)
DevLog.info(LOG_TAG, "no active requests")
}
}
else { // if (settings.remindersEnabled || settings.quietHoursOneTimeReminderEnabled) {
DevLog.info(LOG_TAG, "reminders are not enabled")
}
if (reminderAlarmNextFire != null) {
context.alarmManager.setExactAndAlarm(
context,
settings.useSetAlarmClock,
reminderAlarmNextFire,
ReminderAlarmBroadcastReceiver::class.java, // ignored on KitKat and below
ReminderExactAlarmBroadcastReceiver::class.java,
MainActivity::class.java)
reminderState.nextFireExpectedAt = reminderAlarmNextFire
}
else {
context.alarmManager.cancelExactAndAlarm(
context,
ReminderAlarmBroadcastReceiver::class.java,
ReminderExactAlarmBroadcastReceiver::class.java)
}
}
}
}
| gpl-3.0 | ae9c6832589a97a1c7cfe42c28d343d2 | 43.578616 | 160 | 0.630926 | 5.136232 | false | false | false | false |
j2ghz/tachiyomi-extensions | src/it/perveden/src/eu/kanade/tachiyomi/extension/it/perveden/Perveden.kt | 1 | 20586 | package eu.kanade.tachiyomi.extension.it.perveden
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.*
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.HttpUrl
import okhttp3.Request
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
class Perveden : ParsedHttpSource() {
override val name = "PervEden"
override val baseUrl = "http://www.perveden.com"
override val lang = "it"
override val supportsLatest = true
override fun latestUpdatesRequest(page: Int): Request = GET("$baseUrl/it/it-directory/?order=3&page=$page", headers)
override fun latestUpdatesSelector() = searchMangaSelector()
override fun latestUpdatesFromElement(element: Element): SManga = searchMangaFromElement(element)
override fun latestUpdatesNextPageSelector() = searchMangaNextPageSelector()
override fun popularMangaRequest(page: Int): Request = GET("$baseUrl/it/it-directory/?page=$page", headers)
override fun popularMangaSelector() = searchMangaSelector()
override fun popularMangaFromElement(element: Element): SManga = searchMangaFromElement(element)
override fun popularMangaNextPageSelector() = searchMangaNextPageSelector()
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val url = HttpUrl.parse("$baseUrl/it/it-directory/")?.newBuilder()!!.addQueryParameter("title", query)
(if (filters.isEmpty()) getFilterList() else filters).forEach { filter ->
when (filter) {
is StatusList -> filter.state
.filter { it.state }
.map { it.id.toString() }
.forEach { url.addQueryParameter("status", it) }
is Types -> filter.state
.filter { it.state }
.map { it.id.toString() }
.forEach { url.addQueryParameter("type", it) }
is TextField -> url.addQueryParameter(filter.key, filter.state)
is OrderBy -> filter.state?.let {
val sortId = it.index
url.addQueryParameter("order", if (it.ascending) "-$sortId" else "$sortId")
}
is GenreField -> filter.state.toLowerCase(Locale.ENGLISH).split(',', ';').forEach {
val id = genres[it.trim()]
if (id != null) url.addQueryParameter(filter.key, id)
}
}
}
url.addQueryParameter("page", page.toString())
return GET(url.toString(), headers)
}
override fun searchMangaSelector() = "table#mangaList > tbody > tr:has(td:gt(1))"
override fun searchMangaFromElement(element: Element) = SManga.create().apply {
element.select("td > a").first()?.let {
setUrlWithoutDomain(it.attr("href"))
title = it.text()
}
}
override fun searchMangaNextPageSelector() = "a:has(span.next)"
override fun mangaDetailsParse(document: Document) = SManga.create().apply {
val infos = document.select("div.rightbox")
author = infos.select("a[href^=/it/it-directory/?author]").first()?.text()
artist = infos.select("a[href^=/it/it-directory/?artist]").first()?.text()
genre = infos.select("a[href^=/it/it-directory/?categoriesInc]").map { it.text() }.joinToString()
description = document.select("h2#mangaDescription").text()
status = parseStatus(infos.select("h4:containsOwn(Stato)").first()?.nextSibling().toString())
val img = infos.select("div.mangaImage2 > img").first()?.attr("src")
if (!img.isNullOrBlank()) thumbnail_url = img.let { "http:$it" }
}
private fun parseStatus(status: String) = when {
status.contains("In Corso", true) -> SManga.ONGOING
status.contains("Completato", true) -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
override fun chapterListSelector() = "div#leftContent > table > tbody > tr"
override fun chapterFromElement(element: Element) = SChapter.create().apply {
val a = element.select("a[href^=/it/it-manga/]").first()
setUrlWithoutDomain(a?.attr("href").orEmpty())
name = a?.select("b")?.first()?.text().orEmpty()
date_upload = element.select("td.chapterDate").first()?.text()?.let { parseChapterDate(it.trim()) } ?: 0L
}
private fun parseChapterDate(date: String): Long =
if ("Oggi" in date) {
Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}.timeInMillis
} else if ("Ieri" in date) {
Calendar.getInstance().apply {
add(Calendar.DATE, -1)
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}.timeInMillis
} else try {
SimpleDateFormat("d MMM yyyy", Locale.ITALIAN).parse(date).time
} catch (e: ParseException) {
0L
}
override fun pageListParse(document: Document): List<Page> = mutableListOf<Page>().apply {
document.select("option[value^=/it/it-manga/]").forEach {
add(Page(size, "$baseUrl${it.attr("value")}"))
}
}
override fun imageUrlParse(document: Document): String = document.select("a#nextA.next > img").first()?.attr("src").let { "http:$it" }
private class NamedId(name: String, val id: Int) : Filter.CheckBox(name)
private class TextField(name: String, val key: String) : Filter.Text(name)
private class GenreField(name: String, val key: String) : Filter.Text(name)
private class OrderBy : Filter.Sort("Ordina per", arrayOf("Titolo manga", "Visite", "Capitoli", "Ultimo capitolo"),
Filter.Sort.Selection(1, false))
private class StatusList(statuses: List<NamedId>) : Filter.Group<NamedId>("Stato", statuses)
private class Types(types: List<NamedId>) : Filter.Group<NamedId>("Tipo", types)
override fun getFilterList() = FilterList(
TextField("Autore", "author"),
TextField("Artista", "artist"),
GenreField("Generi inclusi", "categoriesInc"),
GenreField("Generi esclusi", "categoriesExcl"),
OrderBy(),
Types(types()),
StatusList(statuses())
)
private fun types() = listOf(
NamedId("Japanese Manga", 0),
NamedId("Korean Manhwa", 1),
NamedId("Chinese Manhua", 2),
NamedId("Comic", 3),
NamedId("Doujinshi", 4)
)
private fun statuses() = listOf(
NamedId("In corso", 1),
NamedId("Completato", 2),
NamedId("Sospeso", 0)
)
private val genres = mapOf(
Pair("commedia", "4e70ea9ac092255ef70075d8"),
Pair("ecchi", "4e70ea9ac092255ef70075d9"),
Pair("age progression", "5782b043719a16947390104a"),
Pair("ahegao", "577e6f90719a168e7d256a3f"),
Pair("anal", "577e6f90719a168e7d256a3b"),
Pair("angel", "577e724a719a168ef96a74d6"),
Pair("apron", "577e720a719a166f4719a7be"),
Pair("armpit licking", "577e71db719a166f4719a3e7"),
Pair("assjob", "58474a08719a1668eeeea29b"),
Pair("aunt", "577e6f8d719a168e7d256a20"),
Pair("bbw", "5782ae42719a1675f68a6e29"),
Pair("bdsm", "577e723d719a168ef96a7416"),
Pair("bestiality", "57ad8919719a1629a0a327cf"),
Pair("big areolae", "577e7226719a166f4719a9d0"),
Pair("big ass", "577e6f8d719a168e7d256a21"),
Pair("big balls", "577e7267719a168ef96a76ee"),
Pair("big breasts", "577e6f8d719a168e7d256a1c"),
Pair("big clit", "57ef0396719a163dffb8fdff"),
Pair("big nipples", "5782ae42719a1675f68a6e2a"),
Pair("big penis", "577e7267719a168ef96a76ef"),
Pair("bike shorts", "577e7210719a166f4719a820"),
Pair("bikini", "577e6f91719a168e7d256a77"),
Pair("birth", "577e7273719a168ef96a77cf"),
Pair("blackmail", "577e6f91719a168e7d256a78"),
Pair("blindfold", "577e7208719a166f4719a78d"),
Pair("blood", "577e7295719a168ef96a79e6"),
Pair("bloomers", "5782b051719a1694739010ee"),
Pair("blowjob", "577e6f8d719a168e7d256a22"),
Pair("blowjob face", "577e71eb719a166f4719a544"),
Pair("body modification", "577e6f93719a168e7d256a8e"),
Pair("bodystocking", "5782b05c719a169473901151"),
Pair("bodysuit", "577e6f90719a168e7d256a42"),
Pair("bondage", "577e6f90719a168e7d256a45"),
Pair("breast expansion", "577e71c3719a166f4719a235"),
Pair("bukkake", "577e7210719a166f4719a821"),
Pair("bunny girl", "577e7224719a166f4719a9b9"),
Pair("business suit", "577e71e5719a166f4719a4b2"),
Pair("catgirl", "577e71d5719a166f4719a366"),
Pair("centaur", "577e7297719a168ef96a7a06"),
Pair("cervix penetration", "577e7273719a168ef96a77d0"),
Pair("cheating", "577e71b5719a166f4719a13b"),
Pair("cheerleader", "57c0a6de719a1641240e9257"),
Pair("chikan", "5782b0c6719a1679528762ac"),
Pair("chinese dress", "5782b059719a169473901131"),
Pair("chloroform", "577e6f92719a168e7d256a7f"),
Pair("christmas", "5782af2b719a169473900752"),
Pair("clit growth", "57ef0396719a163dffb8fe00"),
Pair("collar", "577e6f93719a168e7d256a8f"),
Pair("condom", "577e71d5719a166f4719a36c"),
Pair("corruption", "577e6f90719a168e7d256a41"),
Pair("cosplaying", "5782b185719a167952876944"),
Pair("cousin", "577e7283719a168ef96a78c3"),
Pair("cow", "5865d767719a162cce299571"),
Pair("cunnilingus", "577e6f8d719a168e7d256a23"),
Pair("dark skin", "577e6f90719a168e7d256a55"),
Pair("daughter", "577e7250719a168ef96a7539"),
Pair("deepthroat", "577e6f90719a168e7d256a3c"),
Pair("defloration", "577e6f92719a168e7d256a82"),
Pair("demon girl", "577e7218719a166f4719a8c8"),
Pair("dick growth", "577e6f93719a168e7d256a90"),
Pair("dickgirl on dickgirl", "5782af0e719a16947390067a"),
Pair("dog girl", "577e7218719a166f4719a8c9"),
Pair("double penetration", "577e6f90719a168e7d256a3d"),
Pair("double vaginal", "577e7226719a166f4719a9d1"),
Pair("drugs", "577e71da719a166f4719a3cb"),
Pair("drunk", "577e7199719a16697b9853ea"),
Pair("elf", "577e6f93719a168e7d256a91"),
Pair("enema", "5782aff7719a169473900d8a"),
Pair("exhibitionism", "577e72a7719a168ef96a7b26"),
Pair("eyemask", "577e7208719a166f4719a78e"),
Pair("facesitting", "577e7230719a166f4719aa8c"),
Pair("females only", "577e6f90719a168e7d256a44"),
Pair("femdom", "577e6f8c719a168e7d256a13"),
Pair("filming", "577e7242719a168ef96a7465"),
Pair("fingering", "577e6f90719a168e7d256a5d"),
Pair("fisting", "57c349e1719a1625b42603f4"),
Pair("foot licking", "5782b152719a16795287677d"),
Pair("footjob", "577e6f8d719a168e7d256a17"),
Pair("freckles", "5782ae42719a1675f68a6e2b"),
Pair("fundoshi", "577e71d9719a166f4719a3bf"),
Pair("furry", "5782ae45719a1675f68a6e49"),
Pair("futanari", "577e6f92719a168e7d256a80"),
Pair("gag", "577e6f90719a168e7d256a56"),
Pair("gaping", "577e7210719a166f4719a822"),
Pair("garter belt", "577e7201719a166f4719a704"),
Pair("glasses", "577e6f90719a168e7d256a5e"),
Pair("gothic lolita", "577e7201719a166f4719a705"),
Pair("group", "577e726e719a168ef96a7764"),
Pair("gyaru", "577e6f91719a168e7d256a79"),
Pair("hairjob", "57bcea9f719a1687ea2bc092"),
Pair("hairy", "577e7250719a168ef96a753a"),
Pair("hairy armpits", "5782b13c719a16795287669c"),
Pair("handjob", "577e71c8719a166f4719a29b"),
Pair("harem", "577e71c3719a166f4719a239"),
Pair("heterochromia", "577e7201719a166f4719a706"),
Pair("hotpants", "585b302d719a1648da4f0389"),
Pair("huge breasts", "577e71d9719a166f4719a3c0"),
Pair("huge penis", "585b302d719a1648da4f038a"),
Pair("human on furry", "577e7203719a166f4719a722"),
Pair("human pet", "577e6f90719a168e7d256a57"),
Pair("humiliation", "577e7210719a166f4719a823"),
Pair("impregnation", "577e6f90719a168e7d256a47"),
Pair("incest", "577e6f93719a168e7d256a92"),
Pair("inflation", "577e7273719a168ef96a77d1"),
Pair("insect girl", "577e71fc719a166f4719a692"),
Pair("inverted nipples", "5813993a719a165f236ddacd"),
Pair("kimono", "577e723d719a168ef96a7417"),
Pair("kissing", "5782ae4f719a1675f68a6ece"),
Pair("lactation", "577e6f93719a168e7d256a93"),
Pair("latex", "577e6f90719a168e7d256a58"),
Pair("layer cake", "577e7230719a166f4719aa8d"),
Pair("leg lock", "57b7c0c2719a169265b768bd"),
Pair("leotard", "579b141e719a16881d14ccfe"),
Pair("lingerie", "577e71fc719a166f4719a693"),
Pair("living clothes", "577e6f90719a168e7d256a49"),
Pair("lizard girl", "5782b127719a1679528765e9"),
Pair("lolicon", "5782af84719a1694739009b5"),
Pair("long tongue", "5782b158719a1679528767d5"),
Pair("machine", "57ef0396719a163dffb8fe01"),
Pair("magical girl", "577e71c3719a166f4719a236"),
Pair("maid", "5782ae3f719a1675f68a6e19"),
Pair("male on dickgirl", "577e7267719a168ef96a76f0"),
Pair("masked face", "57c349e1719a1625b42603f5"),
Pair("masturbation", "577e71b5719a166f4719a13c"),
Pair("mermaid", "578d3c5b719a164fa798c09e"),
Pair("metal armor", "5782b158719a1679528767d6"),
Pair("miko", "577e726e719a168ef96a7765"),
Pair("milf", "577e6f8d719a168e7d256a24"),
Pair("military", "577e6f8d719a168e7d256a18"),
Pair("milking", "577e6f93719a168e7d256a94"),
Pair("mind break", "577e6f90719a168e7d256a4b"),
Pair("mind control", "577e6f90719a168e7d256a4d"),
Pair("monster girl", "577e6f90719a168e7d256a4f"),
Pair("monster girl", "577e6f90719a168e7d256a46"),
Pair("moral degeneration", "577e71da719a166f4719a3cc"),
Pair("mother", "577e71c7719a166f4719a293"),
Pair("mouse girl", "5782ae45719a1675f68a6e4a"),
Pair("multiple breasts", "5782ae45719a1675f68a6e4b"),
Pair("multiple penises", "577e722a719a166f4719aa29"),
Pair("muscle", "577e7250719a168ef96a753c"),
Pair("nakadashi", "577e6f8e719a168e7d256a26"),
Pair("netorare", "577e71c7719a166f4719a294"),
Pair("niece", "5782b10a719a1679528764b5"),
Pair("nurse", "577e6f8d719a168e7d256a1d"),
Pair("oil", "5782af5e719a1694739008b1"),
Pair("onahole", "582324e5719a1674f99b3444"),
Pair("orgasm denial", "577e725d719a168ef96a762f"),
Pair("paizuri", "577e6f90719a168e7d256a3e"),
Pair("pantyhose", "577e6f8d719a168e7d256a19"),
Pair("pantyjob", "577e7276719a168ef96a77f9"),
Pair("parasite", "577e6f90719a168e7d256a50"),
Pair("pasties", "5782b029719a169473900f3b"),
Pair("piercing", "577e6f90719a168e7d256a59"),
Pair("plant girl", "577e71f4719a166f4719a5fa"),
Pair("policewoman", "57af673b719a1655a6ca8b58"),
Pair("ponygirl", "577e6f90719a168e7d256a5a"),
Pair("possession", "5782aff7719a169473900d8b"),
Pair("pregnant", "577e71da719a166f4719a3cd"),
Pair("prolapse", "5782cc79719a165f600844e0"),
Pair("prostitution", "577e7242719a168ef96a7466"),
Pair("pubic stubble", "577e71da719a166f4719a3ce"),
Pair("public use", "5782cc79719a165f600844e1"),
Pair("rape", "577e6f90719a168e7d256a51"),
Pair("rimjob", "577e725f719a168ef96a765e"),
Pair("robot", "5782b144719a1679528766f3"),
Pair("ryona", "577e723e719a168ef96a7424"),
Pair("saliva", "5884ed6f719a1678dfbb2258"),
Pair("scar", "5782b081719a167952876168"),
Pair("school swimsuit", "5782b05f719a169473901177"),
Pair("schoolgirl uniform", "577e7199719a16697b9853e6"),
Pair("selfcest", "5782b152719a16795287677e"),
Pair("sex toys", "577e6f90719a168e7d256a5b"),
Pair("sheep girl", "5782affa719a169473900da2"),
Pair("shemale", "577e7267719a168ef96a76f1"),
Pair("shibari", "577e72a6719a168ef96a7b18"),
Pair("shimapan", "5782aebd719a1694739004c5"),
Pair("sister", "577e6f8c719a168e7d256a14"),
Pair("slave", "577e71b4719a166f4719a138"),
Pair("sleeping", "577e71e5719a166f4719a4b3"),
Pair("slime", "577e6f93719a168e7d256a95"),
Pair("slime girl", "577e6f90719a168e7d256a48"),
Pair("small breasts", "577e6f90719a168e7d256a5f"),
Pair("smell", "577e7210719a166f4719a824"),
Pair("snake girl", "577e721e719a166f4719a94b"),
Pair("sole dickgirl", "582324e5719a1674f99b3445"),
Pair("sole female", "577e6f91719a168e7d256a7a"),
Pair("solo action", "5782afbf719a169473900ba2"),
Pair("spanking", "577e7199719a16697b9853e7"),
Pair("squirting", "577e7250719a168ef96a753d"),
Pair("stockings", "577e6f8d719a168e7d256a1a"),
Pair("stomach deformation", "5782aef2719a169473900606"),
Pair("strap-on", "577e71d5719a166f4719a367"),
Pair("stuck in wall", "5782aecf719a16947390055b"),
Pair("sundress", "577e7216719a166f4719a8a2"),
Pair("sweating", "577e71b5719a166f4719a13d"),
Pair("swimsuit", "577e71d3719a166f4719a342"),
Pair("swinging", "577e7203719a166f4719a723"),
Pair("syringe", "577e71da719a166f4719a3cf"),
Pair("tall girl", "577e71d9719a166f4719a3c1"),
Pair("tanlines", "577e6f91719a168e7d256a7b"),
Pair("teacher", "577e7199719a16697b9853e8"),
Pair("tentacles", "577e6f90719a168e7d256a52"),
Pair("thigh high boots", "577e6f93719a168e7d256a96"),
Pair("tiara", "5782cc74719a165f600844d3"),
Pair("tights", "5782b059719a169473901132"),
Pair("tomboy", "577e7201719a166f4719a6fb"),
Pair("torture", "577e725d719a168ef96a7630"),
Pair("tracksuit", "5782b146719a167952876708"),
Pair("transformation", "577e6f90719a168e7d256a4a"),
Pair("tribadism", "577e6f90719a168e7d256a60"),
Pair("tube", "577e7208719a166f4719a78f"),
Pair("tutor", "5782af34719a1694739007a3"),
Pair("twins", "577e726a719a168ef96a7729"),
Pair("unusual pupils", "577e6f90719a168e7d256a53"),
Pair("urethra insertion", "5877c07f719a163627a2ceb0"),
Pair("urination", "577e7210719a166f4719a825"),
Pair("vaginal sticker", "577e721c719a166f4719a930"),
Pair("vomit", "5782ae45719a1675f68a6e4c"),
Pair("vore", "577e6f8c719a168e7d256a15"),
Pair("voyeurism", "583ca1ef719a161795a60847"),
Pair("waitress", "5782ae3f719a1675f68a6e1a"),
Pair("widow", "5782b13c719a16795287669d"),
Pair("wings", "5782b158719a1679528767d7"),
Pair("witch", "577e6f93719a168e7d256a97"),
Pair("wolf girl", "577e724c719a168ef96a74fd"),
Pair("wrestling", "577e7230719a166f4719aa8e"),
Pair("x-ray", "577e6f90719a168e7d256a40"),
Pair("yandere", "577e7295719a168ef96a79e7"),
Pair("yuri", "577e6f90719a168e7d256a4c")
)
}
| apache-2.0 | 82e857abd1ddae33e769cf1cfeb399fd | 50.465 | 138 | 0.613718 | 3.05385 | false | false | false | false |
openbakery/gradle-xcodePlugin | libxcodetools/src/main/kotlin/org/openbakery/tools/Lipo.kt | 1 | 1468 | package org.openbakery.tools
import org.openbakery.CommandRunner
import org.openbakery.xcode.Xcode
import org.openbakery.xcode.Xcodebuild
import org.slf4j.LoggerFactory
import java.io.File
open class Lipo(xcodebuild: Xcodebuild) {
companion object {
val logger = LoggerFactory.getLogger("Lipo")!!
}
var xcodebuild: Xcodebuild = xcodebuild
open fun getArchs(binary: File): List<String> {
val commandList = listOf(
getLipoCommand(),
"-info",
binary.absolutePath
)
var result = xcodebuild.commandRunner.runWithResult(commandList)
if (result != null) {
var archsString = result.split(":").last().trim()
return archsString.split(" ")
}
return listOf("armv7", "arm64")
}
open fun removeArch(binary: File, arch: String) {
xcodebuild.commandRunner.run(
getLipoCommand(),
binary.absolutePath,
"-remove",
arch,
"-output",
binary.absolutePath
)
}
/**
Remove all the unsupported architecture from the app binary.
If not, then appstore connect will reject the ipa
*/
open fun removeUnsupportedArchs(binary: File, supportedArchs: List<String>) {
logger.debug("removeUnsupportedArchs at {}", binary)
logger.debug("supportedArchs are {}", supportedArchs)
val archs = getArchs(binary).toMutableList()
archs.removeAll(supportedArchs)
archs.iterator().forEach {
removeArch(binary, it)
}
}
open fun getLipoCommand() : String {
return xcodebuild.getToolchainDirectory() + "/usr/bin/lipo"
}
}
| apache-2.0 | 6a6677f7ac8f7a09e3f3c062a86e0228 | 22.677419 | 78 | 0.719346 | 3.359268 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/systems/tilemodules/ModuleInternalStorage.kt | 2 | 3927 | package com.cout970.magneticraft.systems.tilemodules
import com.cout970.magneticraft.api.energy.IElectricNode
import com.cout970.magneticraft.misc.ElectricConstants
import com.cout970.magneticraft.misc.add
import com.cout970.magneticraft.misc.energy.IMachineEnergyInterface
import com.cout970.magneticraft.misc.gui.ValueAverage
import com.cout970.magneticraft.misc.interpolate
import com.cout970.magneticraft.misc.network.FloatSyncVariable
import com.cout970.magneticraft.misc.network.IntSyncVariable
import com.cout970.magneticraft.misc.network.SyncVariable
import com.cout970.magneticraft.misc.newNbt
import com.cout970.magneticraft.misc.world.isServer
import com.cout970.magneticraft.systems.config.Config
import com.cout970.magneticraft.systems.gui.DATA_ID_CHARGE_RATE
import com.cout970.magneticraft.systems.gui.DATA_ID_STORAGE
import com.cout970.magneticraft.systems.tileentities.IModule
import com.cout970.magneticraft.systems.tileentities.IModuleContainer
import net.minecraft.nbt.NBTTagCompound
/**
* Created by cout970 on 2017/06/30.
*/
class ModuleInternalStorage(
val mainNode: IElectricNode,
val initialCapacity: Int,
val initialMaxChargeSpeed: Double = 200.0,
val initialUpperVoltageLimit: Double = ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE,
val initialLowerVoltageLimit: Double = ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE,
override val name: String = "module_electric_storage"
) : IModule, IMachineEnergyInterface {
override lateinit var container: IModuleContainer
val capacity: Int get() = (initialCapacity * Config.machineEnergyStorageMultiplier).toInt()
val maxChargeSpeed: Double get() = initialMaxChargeSpeed * Config.maxChargeSpeedMultiplier
val upperVoltageLimit: Double get() = initialUpperVoltageLimit + Config.upperVoltageLimitOffset
val lowerVoltageLimit: Double get() = initialLowerVoltageLimit + Config.lowerVoltageLimitOffset
companion object {
const val INTERVAL = 10
}
var energy: Int = 0
val chargeRate = ValueAverage(20)
override fun update() {
if (world.isServer) {
if (mainNode.voltage > upperVoltageLimit) {
val speed = interpolate(mainNode.voltage, upperVoltageLimit,
upperVoltageLimit + INTERVAL) * maxChargeSpeed
val finalSpeed = Math.min(Math.floor(speed).toInt(), capacity - energy)
if (finalSpeed != 0) {
mainNode.applyPower(-finalSpeed.toDouble(), false)
energy += finalSpeed
chargeRate += finalSpeed
}
} else if (mainNode.voltage < lowerVoltageLimit) {
val speed = (1 - interpolate(mainNode.voltage, lowerVoltageLimit,
lowerVoltageLimit + INTERVAL)) * maxChargeSpeed
val finalSpeed = Math.min(Math.floor(speed).toInt(), energy)
if (finalSpeed != 0) {
mainNode.applyPower(finalSpeed.toDouble(), false)
energy -= finalSpeed
chargeRate -= finalSpeed
}
}
chargeRate.tick()
}
}
override fun getSpeed(): Double {
return energy.toDouble() / capacity
}
override fun hasEnergy(amount: Double): Boolean = energy >= amount
override fun useEnergy(amount: Double) {
energy = Math.max(0, energy - amount.toInt())
}
override fun deserializeNBT(nbt: NBTTagCompound) {
energy = nbt.getInteger("energy")
}
override fun serializeNBT(): NBTTagCompound = newNbt {
add("energy", energy)
}
override fun getGuiSyncVariables(): List<SyncVariable> = listOf(
IntSyncVariable(DATA_ID_STORAGE, getter = { energy }, setter = { energy = it }),
FloatSyncVariable(DATA_ID_CHARGE_RATE, getter = { chargeRate.average },
setter = { chargeRate.storage = it })
)
} | gpl-2.0 | d9e886e3c6bee6ffaaae6b36e276b03a | 39.916667 | 99 | 0.691622 | 4.4625 | false | true | false | false |
anton-okolelov/intellij-rust | src/test/kotlin/org/rust/ide/intentions/FillMatchArmsIntentionTest.kt | 2 | 3529 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
class FillMatchArmsIntentionTest : RsIntentionTestBase(FillMatchArmsIntention()) {
fun `test simple enum variants`() = doAvailableTest("""
enum FooBar {
Foo,
Bar
}
fn foo(x: FooBar) {
match x/*caret*/ {}
}
""", """
enum FooBar {
Foo,
Bar
}
fn foo(x: FooBar) {
match x {
FooBar::Foo => {/*caret*/},
FooBar::Bar => {},
}
}
""")
fun `test tuple enum variants`() = doAvailableTest("""
enum FooBar {
Foo(i32),
Bar(bool, f64)
}
fn foo(x: FooBar) {
match x/*caret*/ {}
}
""", """
enum FooBar {
Foo(i32),
Bar(bool, f64)
}
fn foo(x: FooBar) {
match x {
FooBar::Foo(_) => {/*caret*/},
FooBar::Bar(_, _) => {},
}
}
""")
fun `test struct enum variants`() = doAvailableTest("""
enum FooBar {
Foo { foo: i32 },
Bar { bar1: bool, bar2: f64 }
}
fn foo(x: FooBar) {
match x/*caret*/ {}
}
""", """
enum FooBar {
Foo { foo: i32 },
Bar { bar1: bool, bar2: f64 }
}
fn foo(x: FooBar) {
match x {
FooBar::Foo { .. } => {/*caret*/},
FooBar::Bar { .. } => {},
}
}
""")
fun `test different enum variants`() = doAvailableTest("""
enum Foo {
X,
Y(i32),
Z { foo: bool }
}
fn foo(x: Foo) {
match x/*caret*/ {}
}
""", """
enum Foo {
X,
Y(i32),
Z { foo: bool }
}
fn foo(x: Foo) {
match x {
Foo::X => {/*caret*/},
Foo::Y(_) => {},
Foo::Z { .. } => {},
}
}
""")
fun `test incomplete match expr`() = doAvailableTest("""
enum FooBar {
Foo,
Bar
}
fn foo(x: FooBar) {
match x/*caret*/
}
""", """
enum FooBar {
Foo,
Bar
}
fn foo(x: FooBar) {
match x {
FooBar::Foo => {/*caret*/},
FooBar::Bar => {},
}
}
""")
fun `test don't remove comments`() = doAvailableTest("""
enum FooBar {
Foo,
Bar
}
fn foo(x: FooBar) {
match x/*caret*/ {
// test
}
}
""", """
enum FooBar {
Foo,
Bar
}
fn foo(x: FooBar) {
match x {
// test
FooBar::Foo => {/*caret*/},
FooBar::Bar => {},
}
}
""")
fun `test not empty match expr body`() = doUnavailableTest("""
enum FooBar {
Foo,
Bar
}
fn foo(x: FooBar) {
match x/*caret*/ {
FooBar::Foo => {},
}
}
""")
fun `test not enum in match expr`() = doUnavailableTest("""
fn foo(x: i32) {
match x/*caret*/ {}
}
""")
}
| mit | 598ebbc27f0bac63bb9ee0b08d19d933 | 19.517442 | 82 | 0.343723 | 4.577173 | false | true | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/lang/core/types/ty/TyTraitObject.kt | 1 | 1603 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.types.ty
import com.intellij.codeInsight.completion.CompletionUtil
import org.rust.lang.core.psi.RsTraitItem
import org.rust.lang.core.psi.ext.typeParameters
import org.rust.lang.core.types.BoundElement
import org.rust.lang.core.types.infer.TypeFolder
import org.rust.lang.core.types.infer.TypeVisitor
/**
* A "trait object" type should not be confused with a trait.
* Though you use the same path to denote both traits and trait objects,
* only the latter are ty.
*/
data class TyTraitObject(val trait: BoundElement<RsTraitItem>) : Ty(mergeFlags(trait)) {
val typeArguments: List<Ty>
get() = trait.element.typeParameters.map { typeParameterValues.get(it) ?: TyUnknown }
override val typeParameterValues: Substitution
get() = trait.subst
override fun superFoldWith(folder: TypeFolder): TyTraitObject =
TyTraitObject(trait.foldWith(folder))
override fun superVisitWith(visitor: TypeVisitor): Boolean =
trait.visitWith(visitor)
companion object {
fun valueOf(trait: RsTraitItem): TyTraitObject {
val item = CompletionUtil.getOriginalOrSelf(trait)
return TyTraitObject(BoundElement(item, defaultSubstitution(item)))
}
}
}
private fun defaultSubstitution(item: RsTraitItem): Substitution =
item.typeParameters.associate { rsTypeParameter ->
val tyTypeParameter = TyTypeParameter.named(rsTypeParameter)
tyTypeParameter to tyTypeParameter
}
| mit | e8ea581d57caf3d2ae7485beac87fdbe | 33.106383 | 93 | 0.734248 | 4.344173 | false | false | false | false |
google/horologist | network-awareness/src/main/java/com/google/android/horologist/networks/data/NetworkStatus.kt | 1 | 1510 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.networks.data
import android.net.LinkProperties
import android.net.NetworkCapabilities
import com.google.android.horologist.networks.ExperimentalHorologistNetworksApi
import java.net.Inet6Address
import java.net.InetAddress
import java.net.Socket
@ExperimentalHorologistNetworksApi
public data class NetworkStatus(
public val id: String,
public val status: Status,
public val networkInfo: NetworkInfo,
public val addresses: List<InetAddress>,
public val capabilities: NetworkCapabilities?,
public val linkProperties: LinkProperties?,
public val bindSocket: (Socket) -> Unit
) {
public val firstAddress: InetAddress?
get() = addresses.minByOrNull { it is Inet6Address }
override fun toString(): String {
return "NetworkStatus(id=$id, status=$status, type=$networkInfo, addresses=$addresses)"
}
}
| apache-2.0 | 4c802d8207df06862c6e905f9ab64430 | 34.952381 | 95 | 0.755629 | 4.507463 | false | false | false | false |
CarrotCodes/Warren | src/main/kotlin/chat/willow/warren/handler/rpl/Rpl353Handler.kt | 1 | 2265 | package chat.willow.warren.handler.rpl
import chat.willow.kale.IMetadataStore
import chat.willow.kale.KaleHandler
import chat.willow.kale.irc.message.rfc1459.rpl.Rpl353Message
import chat.willow.kale.irc.prefix.Prefix
import chat.willow.kale.irc.prefix.PrefixParser
import chat.willow.warren.helper.loggerFor
import chat.willow.warren.state.CaseMappingState
import chat.willow.warren.state.JoinedChannelsState
import chat.willow.warren.state.UserPrefixesState
import chat.willow.warren.state.generateUser
class Rpl353Handler(val channelsState: JoinedChannelsState, val userPrefixesState: UserPrefixesState, val caseMappingState: CaseMappingState) : KaleHandler<Rpl353Message.Message>(Rpl353Message.Message.Parser) {
private val LOGGER = loggerFor<Rpl353Handler>()
override fun handle(message: Rpl353Message.Message, metadata: IMetadataStore) {
val names = message.names
val channel = channelsState[message.channel]
if (channel == null) {
LOGGER.warn("got a 353 for a channel we don't think we're in - bailing: ${message.channel}")
return
}
for (name in names) {
val (prefixes, userhost) = trimPrefixes(name)
if (userhost == null || userhost.nick.isEmpty()) {
LOGGER.warn("nick was empty after trimming: $name")
continue
}
var modes = setOf<Char>()
prefixes.asSequence()
.mapNotNull { userPrefixesState.prefixesToModes[it] }
.forEach { modes += it }
channel.users += generateUser(userhost.nick, modes)
}
LOGGER.trace("channel state after 353: $channel")
}
private fun trimPrefixes(rawNick: String): Pair<Set<Char>, Prefix?> {
var nick = rawNick
var prefixes = setOf<Char>()
for (char in nick) {
if (userPrefixesState.prefixesToModes.keys.contains(char)) {
prefixes += char
nick = nick.substring(1)
} else {
val userhost = PrefixParser.parse(nick)
return Pair(prefixes, userhost)
}
}
val userhost = PrefixParser.parse(nick)
return Pair(prefixes, userhost)
}
} | isc | d94c36be2c3ba624cd6cb45ebcec34ba | 33.333333 | 210 | 0.646358 | 4.33908 | false | false | false | false |
Caellian/Math | src/main/kotlin/hr/caellian/math/matrix/MatrixF.kt | 1 | 21259 | package hr.caellian.math.matrix
import hr.caellian.math.internal.DataUtil.sumByFloat
import hr.caellian.math.internal.DataUtil.transpose
import hr.caellian.math.vector.VectorF
import hr.caellian.math.vector.VectorN
import java.nio.Buffer
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
import kotlin.math.cos
import kotlin.math.roundToInt
import kotlin.math.sin
/**
* Matrix class for float N-dimensional matrices.
*
* @author Caellian
*/
class MatrixF(override var wrapped: Array<Array<Float>> = emptyArray(), vertical: Boolean = false) : MatrixN<Float>() {
init {
require(rowCount > 1 && columnCount > 1) { "Invalid matrix size!" }
require(validate()) {
if (vertical)
"Matrix columns must be of equal length!"
else
"Matrix rows must be of equal length!"
}
if (vertical) {
wrapped = transpose().wrapped
}
}
/**
* Creates a new blank square matrix.
*
* @param size width & height of new matrix.
*/
constructor(size: Int, default: Float = 0f) : this(Array(size) { _ -> Array(size) { default } })
/**
* Creates a new matrix containing given data.
*
* @param rows number of rows matrix should store.
* @param columns number of columns matrix should store.
*/
constructor(rows: Int, columns: Int, default: Float = 0f) : this(Array(rows) { _ -> Array(columns) { default } })
/**
* Creates a new matrix using collection values.
*
* @param values values to create a new matrix from.
* @return created matrix.
*/
constructor(values: Collection<Collection<Float>>) : this(values.map { it.toTypedArray() }.toTypedArray())
/**
* Creates a new matrix using buffer values.
*
* @param buffer buffer to create a new matrix from.
* @param rowCount number of rows new matrix will have.
* @param columnCount number of columns new matrix will have.
* @return created matrix.
*/
constructor(buffer: FloatBuffer, rowCount: Int, columnCount: Int) : this(
Array(rowCount) { _ -> Array(columnCount) { buffer.get() } })
/**
* Creates a new square matrix using buffer values.
*
* This constructor depends on buffer capacity. Make sure square root of your buffer's capacity is equal to row and
* column count.
*
* @param buffer buffer to create a new matrix from.
* @return created matrix.
*/
constructor(buffer: FloatBuffer) : this(
buffer.let { _ ->
val rows = Math.sqrt(buffer.capacity().toDouble())
require(rows - rows.roundToInt() == 0.0) { "Acquired buffer can't be used to create a square matrix." }
val rowCount = rows.roundToInt()
Array(rowCount) { _ -> Array(rowCount) { buffer.get() } }
}
)
/**
* @return new matrix with negated values.
*/
override fun unaryMinus() = MatrixF(
Array(rowCount) { row -> Array(columnCount) { column -> -wrapped[row][column] } })
/**
* Performs matrix addition and returns resulting matrix.
* In order to add to matrices together, they must be of same size.
*
* @param other matrix to add to this one.
* @return resulting of matrix addition.
*/
override fun plus(other: MatrixN<Float>): MatrixF {
require(rowCount == other.rowCount && columnCount == other.columnCount) { "Invalid argument matrix size: ${other.rowCount}x${other.columnCount}!" }
return MatrixF(
Array(rowCount) { row -> Array(columnCount) { column -> wrapped[row][column] + other[row][column] } })
}
/**
* Performs matrix subtraction and returns resulting matrix.
* In order to subtract one matrix from another, matrices must be of same size.
*
* @param other matrix to subtract from this one.
* @return resulting of matrix subtraction.
*/
override fun minus(other: MatrixN<Float>): MatrixF {
require(rowCount == other.rowCount && columnCount == other.columnCount) { "Invalid argument matrix size: ${other.rowCount}x${other.columnCount}!" }
return MatrixF(
Array(rowCount) { row -> Array(columnCount) { column -> wrapped[row][column] - other[row][column] } })
}
/**
* Performs matrix multiplication on this matrix.
* Returns C from 'C = A×B' where A is this matrix and B is the other / argument matrix.
*
* @param other matrix to multiply this matrix with.
* @return result of matrix multiplication.
*/
override operator fun times(other: MatrixN<Float>): MatrixF {
require(columnCount == other.rowCount) { "Invalid multiplication (mat${rowCount}x$columnCount) * (mat${other.rowCount}x${other.columnCount})!" }
return MatrixF(Array(rowCount) { row ->
Array(other.columnCount) { column ->
(0 until columnCount).sumByFloat { wrapped[row][it] * other.wrapped[it][column] }
}
})
}
/**
* Performs matrix multiplication on this matrix.
* Returns C from 'C = A×B' where A is this matrix and B is the other / argument vector.
*
* @param other vector to multiply this matrix with.
* @return result of matrix multiplication.
*/
override fun times(other: VectorN<Float>): VectorF = (this * other.verticalMatrix as MatrixN<Float>).toVector()
/**
* Performs scalar multiplication on this matrix and returns resulting matrix.
*
* @param scalar scalar to multiply every member of this matrix with.
* @return result of scalar matrix multiplication.
*/
override operator fun times(scalar: Float): MatrixF {
return MatrixF(Array(rowCount) { row -> Array(columnCount) { column -> wrapped[row][column] * scalar } })
}
/**
* Switches two rows together.
*
* @param rowA row to be switched with rowB.
* @param rowB row to be switched with rowA.
* @return resulting matrix.
*/
override fun switchRows(rowA: Int, rowB: Int): MatrixF {
require(rowA in 0..rowCount && rowB in 0..rowCount && rowA != rowB) { "Illegal row argument(s)!" }
return MatrixF(Array(rowCount) { row ->
Array(columnCount) { column ->
when (row) {
rowA -> wrapped[rowB][column]
rowB -> wrapped[rowA][column]
else -> wrapped[row][column]
}
}
})
}
/**
* Switches two columns together.
*
* @param columnA column to be switched with columnB.
* @param columnB column to be switched with columnA.
* @return resulting matrix.
*/
override fun switchColumns(columnA: Int, columnB: Int): MatrixF {
require(columnA in 0..columnCount && columnB in 0..columnCount && columnA != columnB) { "Illegal column argument(s)!" }
return MatrixF(Array(rowCount) { row ->
Array(columnCount) { column ->
when (column) {
columnA -> wrapped[row][columnB]
columnB -> wrapped[row][columnA]
else -> wrapped[row][column]
}
}
})
}
/**
* Multiplies all entries of a row with given scalar.
*
* @param row row to multiply.
* @param multiplier scalar to multiply rows entries with.
* @return resulting matrix.
*/
override fun multiplyRow(row: Int, multiplier: Float): MatrixF {
require(row in 0..rowCount) { "Illegal row argument!" }
return MatrixF(Array(rowCount) { rowI ->
Array(columnCount) { column ->
when (rowI) {
row -> wrapped[rowI][column] * multiplier
else -> wrapped[rowI][column]
}
}
})
}
/**
* Multiplies all entries of a column with given scalar.
*
* @param column column to multiply.
* @param multiplier scalar to multiply column entries with.
* @return resulting matrix.
*/
override fun multiplyColumn(column: Int, multiplier: Float): MatrixF {
require(column in 0..columnCount) { "Illegal row argument!" }
return MatrixF(Array(rowCount) { row ->
Array(columnCount) { columnI ->
when (columnI) {
column -> wrapped[row][columnI] * multiplier
else -> wrapped[row][columnI]
}
}
})
}
/**
* Adds one row from matrix to another.
*
* @param from row to add to another row.
* @param to row to add another row to; data will be stored on this row.
* @param multiplier scalar to multiply all members of added row with on addition. It equals to 1 by default.
* @return new matrix.
*/
override fun addRows(from: Int, to: Int, multiplier: Float?): MatrixF {
require(from in 0..rowCount && to in 0..rowCount) { "Illegal row argument(s)!" }
val multiplierVal = multiplier ?: 1f
return MatrixF(Array(rowCount) { row ->
Array(columnCount) { column ->
when (row) {
to -> wrapped[to][column] + wrapped[from][column] * multiplierVal
else -> wrapped[row][column]
}
}
})
}
/**
* Adds one column from matrix to another.
*
* @param from column to add to another column.
* @param to column to add another column to; data will be stored on this column.
* @param multiplier scalar to multiply all members of added column with on addition. It equals to 1 by default.
* @return new matrix.
*/
override fun addColumns(from: Int, to: Int, multiplier: Float?): MatrixF {
require(from in 0..columnCount && to in 0..columnCount) { "Illegal column argument(s)!" }
val multiplierVal = multiplier ?: 1f
return MatrixF(Array(rowCount) { row ->
Array(columnCount) { column ->
when (column) {
to -> wrapped[row][to] + wrapped[row][from] * multiplierVal
else -> wrapped[row][column]
}
}
})
}
/**
* Inserts given row data at given index shifting rest of the matrix to the next index.
*
* @param index index at which added row data will be stored.
* @param data row data to store at given index.
* @return new matrix with extended data.
*/
override fun withRow(index: Int, data: Array<Float>): MatrixF {
require(data.size == columnCount) { "Illegal row array size! Should be $columnCount." }
return MatrixF(Array(rowCount + 1) { row ->
Array(columnCount) { column ->
when {
row == index -> data[column]
row > index -> wrapped[row + 1][column]
else -> wrapped[row][column]
}
}
})
}
/**
* Inserts given column data at given index shifting rest of the matrix to the next index.
*
* @param index index at which added column data will be stored.
* @param data column data to store at given index.
* @return new matrix with extended data.
*/
override fun withColumn(index: Int, data: Array<Float>): MatrixF {
require(data.size == rowCount) { "Illegal column array size! Should be $rowCount." }
return MatrixF(Array(rowCount) { row ->
Array(columnCount + 1) { column ->
when {
column == index -> data[row]
column > index -> wrapped[row][column + 1]
else -> wrapped[row][column]
}
}
})
}
/**
* Creates a new matrix without specified rows & columns.
*
* @param deletedRows rows to exclude from submatrix.
* @param deletedColumns columns to exclude from submatrix.
* @return defined submatrix.
*/
override fun submatrix(deletedRows: Array<Int>, deletedColumns: Array<Int>): MatrixF {
require(deletedRows.all { it in 0..rowCount } && deletedColumns.all { it in 0..columnCount }) { "Tried to delete rows which don't exist." }
val keptRows = (0..rowCount).toList().filterNot { deletedRows.contains(it) }
val keptColumns = (0..columnCount).toList().filterNot { deletedColumns.contains(it) }
return MatrixF(Array(keptRows.size) { row ->
Array(keptColumns.size) { column ->
wrapped[keptRows[row]][keptColumns[column]]
}
})
}
/**
* Constructs a new vector out of column / row vector matrix.
*
* @return vector containing matrix data.
*/
override fun toVector(): VectorF {
require(columnCount == 1 || rowCount == 1 && !(columnCount > 1 && rowCount > 1)) { "Matrix cannot be turned into a vector!" }
return if (columnCount > rowCount) {
VectorF(firstRow()[0])
} else {
VectorF(firstColumn().transpose()[0])
}
}
/**
* Constructs a new vector out of any matrix dismissing extra data.
*
* @return vector containing only first column of matrix data.
*/
override fun forceToVector(): VectorF = VectorF(firstColumn().transpose()[0])
/**
* @return a new matrix containing only the first row of this matrix.
*/
override fun firstRow() = MatrixF(
Array(1) { row -> Array(columnCount) { column -> wrapped[row][column] } })
/**
* @return a new matrix containing only the first column of this matrix.
*/
override fun firstColumn() = MatrixF(
Array(rowCount) { row -> Array(1) { column -> wrapped[row][column] } })
/**
* @return transposed matrix.
*/
override fun transpose() = MatrixF(wrapped.transpose())
/**
* @return buffer containing data of this matrix.
*/
override fun toBuffer(): Buffer {
return ByteBuffer.allocateDirect((columnCount * rowCount) shl 2).order(ByteOrder.nativeOrder()).asFloatBuffer()
.also { buffer ->
wrapped.forEach { it.forEach { inner -> buffer.put(inner) } }
buffer.flip()
}
}
/**
* Returns copy of data of this Matrix as a 2D array.
*
* @return 2D array containing data of this matrix.
*/
override fun toArray(): Array<Array<Float>> = Array(rowCount) { row ->
Array(columnCount) { column -> wrapped[row][column] }
}
/**
* @return clone of this matrix.
*/
override fun replicated() = MatrixF(toArray())
/**
* @return type supported by this class.
*/
override fun getTypeClass() = Float::class
/**
* Creates a new instance of [MatrixF] containing given data.
*
* @param data data of new wrapper.
* @return new instance of wrapper containing argument data.
*/
override fun withData(wrapped: Array<Array<Float>>) = MatrixF(wrapped)
companion object {
/**
* Initializes a new n-dimensional rotation matrix.
*
* Unless you're working with 4+ dimensional space, it's recommended you use simpler, dimensionality specific
* functions defined in specialised classes as this one is not the fastest for those simpler requirements.
*
* For details see: <a href="http://wscg.zcu.cz/wscg2004/Papers_2004_Short/N29.pdf">Aguilera - Perez Algorithm</a>
*
* @param rotationSimplex defining data. Rows of this matrix represent points defining
* simplex to perform this rotation around. Points must have their
* position in all 'n' dimensions defined and there must be 'n-1'
* points to define rotation simplex.
* @param angle degrees to rotate by objects multiplied by this rotation matrix.
* @return rotation matrix.
*/
@JvmStatic
fun initRotation(rotationSimplex: MatrixF, angle: Float): MatrixF {
val n = rotationSimplex.columnCount
require(n >= 2) { "Can't do rotation in $n-dimensional space!" }
require(rotationSimplex.rowCount == n - 1) { "Insufficient / invalid data! Can't perform rotation." }
@Suppress("LocalVariableName")
val M = arrayOfNulls<MatrixF>(n * (n - 1) / 2 + 1)
val v = arrayOfNulls<MatrixF>(n * (n - 1) / 2 + 1)
M[0] = MatrixF.initTranslationMatrix(((-rotationSimplex).firstRow().toVector()).toArray()).transpose()
v[0] = rotationSimplex
v[1] = (v[0]?.withColumn(n, Array(n - 1) { 1f })!! * M[0]!!).submatrix(emptyArray(), arrayOf(n + 1))
var result = MatrixF(M[0]!!.wrapped)
var k = 1
for (r in 2 until n) {
for (c in n downTo r) {
k += 1
M[k - 1] = MatrixF.initPlaneRotation(n + 1, c, c - 1,
Math.atan2(v[k - 1]!![r - 1][c - 1].toDouble(),
v[k - 1]!![r - 1][c - 2].toDouble()).toFloat())
v[k] = (v[k - 1]?.withColumn(n, Array(n - 1) { 1f })!! * M[k - 1]!!).submatrix(emptyArray(),
arrayOf(n + 1))
result *= M[k - 1]!!
}
}
return (result * MatrixF.initPlaneRotation(n + 1, n - 1, n, angle) * result.inverseUnsafe()).submatrix(
arrayOf(n + 1), arrayOf(n + 1))
}
/**
* Initializes a plane rotation matrix.
*
* @param size size/dimensionality of plane rotation matrix.
* @param a rotated axis index.
* @param b destination axis index.
* @param angle degrees to rotate in objects multiplied by this rotation matrix.
* @return plane rotation matrix.
*/
@JvmStatic
fun initPlaneRotation(size: Int, a: Int, b: Int, angle: Float): MatrixF {
return MatrixF(Array(size) { row ->
Array(size) { column ->
when {
row == a - 1 && column == a - 1 -> cos(Math.toRadians(angle.toDouble())).toFloat()
row == b - 1 && column == b - 1 -> cos(Math.toRadians(angle.toDouble())).toFloat()
row == a - 1 && column == b - 1 -> -sin(Math.toRadians(angle.toDouble())).toFloat()
row == b - 1 && column == a - 1 -> sin(Math.toRadians(angle.toDouble())).toFloat()
row == column -> 1f
else -> 0f
}
}
})
}
/**
* Initializes a new translation matrix using array of axial translations.
*
* @param location relative location.
* @return translation matrix.
*/
@JvmStatic
fun initTranslationMatrix(location: Array<Float>): MatrixF {
return MatrixF(Array(location.size + 1) { row ->
Array(location.size + 1) { column ->
when {
row == column -> 1f
column == location.size && row < location.size -> location[row]
else -> 0f
}
}
})
}
/**
* Initializes a new translation matrix using [VectorF].
*
* @since 3.0.0
*
* @param location relative location.
* @return translation matrix.
*/
@JvmStatic
fun initTranslationMatrix(location: VectorF): MatrixF {
return MatrixF(Array(location.size + 1) { row ->
Array(location.size + 1) { column ->
when {
row == column -> 1f
column == location.size && row < location.size -> location[row]
else -> 0f
}
}
})
}
/**
* Initializes a new scaling matrix.
*
* @param scale scale.
* @return scale matrix.
*/
@JvmStatic
fun initScalingMatrix(scale: Array<Float>): MatrixF {
return MatrixF(Array(scale.size) { row ->
Array(scale.size) { column ->
if (row == column) scale[row] else 0f
}
})
}
/**
* Initializes a new identity matrix.
*
* @param n matrix size.
* @return identity matrix.
*/
@JvmStatic
fun initIdentityMatrix(n: Int): MatrixF {
return MatrixF(Array(n) { row ->
Array(n) { column ->
if (row == column) 1f else 0f
}
})
}
}
} | mit | d31800791baee48d75d5178af9bfd6a7 | 37.371841 | 155 | 0.549184 | 4.545007 | false | false | false | false |
yshrsmz/monotweety | app/src/main/java/net/yslibrary/monotweety/appdata/user/local/resolver/UserGetResolver.kt | 1 | 1006 | package net.yslibrary.monotweety.appdata.user.local.resolver
import android.database.Cursor
import com.pushtorefresh.storio3.sqlite.StorIOSQLite
import com.pushtorefresh.storio3.sqlite.operations.get.DefaultGetResolver
import net.yslibrary.monotweety.appdata.local.getLongByName
import net.yslibrary.monotweety.appdata.local.getStringByName
import net.yslibrary.monotweety.appdata.user.User
import net.yslibrary.monotweety.appdata.user.local.UserTable
class UserGetResolver : DefaultGetResolver<User>() {
override fun mapFromCursor(storIOSQLite: StorIOSQLite, cursor: Cursor): User {
return User(
id = cursor.getLongByName(UserTable.COLUMN_ID),
name = cursor.getStringByName(UserTable.COLUMN_NAME)!!,
screenName = cursor.getStringByName(UserTable.COLUMN_SCREEN_NAME)!!,
profileImageUrl = cursor.getStringByName(UserTable.COLUMN_PROFILE_IMAGE_URL)!!,
_updatedAt = cursor.getLongByName(UserTable.COLUMN__UPDATED_AT)
)
}
}
| apache-2.0 | f87c394234085fbf88708f0a27039ee6 | 46.904762 | 91 | 0.764414 | 4.336207 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/flex/psi/FlexmarkExampleOptionsImpl.kt | 1 | 4528 | // Copyright (c) 2017-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.flex.psi
import com.intellij.lang.ASTNode
import com.intellij.openapi.project.DumbService
import com.intellij.psi.stubs.IStubElementType
import com.vladsch.md.nav.flex.psi.util.FlexmarkPsiImplUtils
import com.vladsch.md.nav.parser.MdFactoryContext
import com.vladsch.md.nav.psi.util.MdElementFactory
import com.vladsch.md.nav.psi.util.MdTypes
import java.util.*
import javax.swing.Icon
class FlexmarkExampleOptionsImpl(stub: FlexmarkExampleOptionsStub?, nodeType: IStubElementType<FlexmarkExampleOptionsStub, FlexmarkExampleOptions>?, node: ASTNode?)
: FlexmarkStubElementImpl<FlexmarkExampleOptionsStub>(stub, nodeType, node)
, FlexmarkExampleOptions {
companion object {
val EMPTY_NODES = listOf<ASTNode>()
val EMPTY_OPTIONS = listOf<FlexmarkExampleOption>()
val EMPTY_STRINGS = listOf<String>()
val OPTION_NODE_TYPES = setOf(MdTypes.FLEXMARK_EXAMPLE_OPTION)
}
constructor(stub: FlexmarkExampleOptionsStub, nodeType: IStubElementType<FlexmarkExampleOptionsStub, FlexmarkExampleOptions>) : this(stub, nodeType, null)
constructor(node: ASTNode) : this(null, null, node)
override fun getOptionNodes(): List<ASTNode> {
var child = node.firstChildNode
if (child != null) {
val list = ArrayList<ASTNode>()
while (child != null) {
if (OPTION_NODE_TYPES.contains(child.elementType)) {
list.add(child)
}
child = child.treeNext
}
if (list.isNotEmpty()) return list
}
return EMPTY_NODES
}
override fun handleContentChange(newContent: String): FlexmarkExampleOptions {
val example: FlexmarkExample = parent as FlexmarkExample
val factoryContext = MdFactoryContext(this)
val newExample = MdElementFactory.createFlexmarkExample(factoryContext, FlexmarkExampleParams(example).withOptions(newContent))
?: return this
val contentNodes = newExample.optionsList ?: return this
replace(contentNodes)
return contentNodes
}
override fun getOptionElements(): List<FlexmarkExampleOption> {
var child = firstChild
if (child != null) {
val list = ArrayList<FlexmarkExampleOption>()
while (child != null) {
if (child is FlexmarkExampleOption) {
list.add(child)
}
child = child.nextSibling
}
if (list.isNotEmpty()) return list
}
return EMPTY_OPTIONS
}
override fun getOptionsString(): String {
val stub = stub
if (stub != null) {
return stub.optionsString
}
return text
}
// REFACTOR: rename to getOptionNames()
override fun getOptions(): List<String> {
return optionsInfo.map { it.optionName }
}
override fun getOptionTexts(): List<String> {
return optionsInfo.map { it.optionText }
}
override fun getOptionsInfo(): List<FlexmarkOptionInfo> {
val stub = stub
if (stub != null) {
return stub.optionsInfo
}
if (optionNodes.isNotEmpty()) {
val nodeList = optionNodes
val list = ArrayList<FlexmarkOptionInfo>()
for (node in nodeList) {
val text = node.text
if (text.isEmpty()) continue
list.add(FlexmarkPsi.getFlexmarkOptionInfo(text))
}
return list
}
return emptyList()
}
override fun getIcon(flags: Int): Icon? {
// return MarkdownIcons.DEFINITION_ITEM
return null
}
override fun isWithIgnore(): Boolean = optionsInfo.any { it.isIgnore }
override fun isWithFail(): Boolean = optionsInfo.any { it.isFail }
override fun toString(): String {
return "FLEXMARK_EXAMPLE_OPTIONS" + super.hashCode()
}
override fun isWithErrors(): Boolean {
val options = optionsInfo
if (options.isNotEmpty() && !DumbService.isDumb(project)) {
val definitions = FlexmarkPsiImplUtils.getOptionDefinitionStrings(mdFile, true)
return !options.all { definitions.contains(it.optionName) || it.isDisabled || it.isBuiltIn }
}
return false
}
}
| apache-2.0 | 90fd256fe8c7ece6ad318ac5963c30a3 | 34.375 | 177 | 0.639576 | 4.721585 | false | false | false | false |
SimpleMobileTools/Simple-Camera | app/src/main/kotlin/com/simplemobiletools/camera/helpers/MediaActionSound.kt | 1 | 6854 | package com.simplemobiletools.camera.helpers
import android.content.Context
import android.media.AudioAttributes
import android.media.MediaPlayer
import android.media.SoundPool
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.util.Log
import java.io.File
/**
* Inspired by [android.media.MediaActionSound]
*/
class MediaActionSound(private val context: Context) {
companion object {
private const val NUM_MEDIA_SOUND_STREAMS = 1
private val SOUND_DIRS = arrayOf(
"/product/media/audio/ui/",
"/system/media/audio/ui/"
)
private val SOUND_FILES = arrayOf(
"camera_click.ogg",
"camera_focus.ogg",
"VideoRecord.ogg",
"VideoStop.ogg"
)
private const val TAG = "MediaActionSound"
const val SHUTTER_CLICK = 0
const val START_VIDEO_RECORDING = 2
const val STOP_VIDEO_RECORDING = 3
private const val STATE_NOT_LOADED = 0
private const val STATE_LOADING = 1
private const val STATE_LOADING_PLAY_REQUESTED = 2
private const val STATE_LOADED = 3
}
private class SoundState(val name: Int) {
var id = 0 // 0 is an invalid sample ID.
var state: Int = STATE_NOT_LOADED
var path: String? = null
}
private var soundPool: SoundPool? = SoundPool.Builder()
.setMaxStreams(NUM_MEDIA_SOUND_STREAMS)
.setAudioAttributes(
AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
.setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build()
).build()
private var mediaPlayer: MediaPlayer? = null
private var playCompletionRunnable: Runnable? = null
private val mSounds: Array<SoundState?> = arrayOfNulls(SOUND_FILES.size)
private val playTimeHandler = Handler(Looper.getMainLooper())
private val mLoadCompleteListener = SoundPool.OnLoadCompleteListener { _, sampleId, status ->
for (sound in mSounds) {
if (sound!!.id != sampleId) {
continue
}
var soundToBePlayed: SoundState? = null
synchronized(sound) {
if (status != 0) {
sound.state = STATE_NOT_LOADED
sound.id = 0
Log.e(TAG, "OnLoadCompleteListener() error: $status loading sound: ${sound.name}")
return@OnLoadCompleteListener
}
when (sound.state) {
STATE_LOADING -> sound.state = STATE_LOADED
STATE_LOADING_PLAY_REQUESTED -> {
soundToBePlayed = sound
sound.state = STATE_LOADED
}
else -> Log.e(TAG, "OnLoadCompleteListener() called in wrong state: ${sound.state} for sound: ${sound.name}")
}
}
if (soundToBePlayed != null) {
playSoundPool(soundToBePlayed!!)
}
break
}
}
init {
soundPool!!.setOnLoadCompleteListener(mLoadCompleteListener)
for (i in mSounds.indices) {
mSounds[i] = SoundState(i)
}
}
private fun loadSound(sound: SoundState?): Int {
val soundFileName = SOUND_FILES[sound!!.name]
for (soundDir in SOUND_DIRS) {
val soundPath = soundDir + soundFileName
sound.path = soundPath
val id = soundPool!!.load(soundPath, 1)
if (id > 0) {
sound.state = STATE_LOADING
sound.id = id
return id
}
}
return 0
}
fun load(soundName: Int) {
if (soundName < 0 || soundName >= SOUND_FILES.size) {
throw RuntimeException("Unknown sound requested: $soundName")
}
val sound = mSounds[soundName]
synchronized(sound!!) {
when (sound.state) {
STATE_NOT_LOADED -> {
loadSound(sound).let { soundId ->
if (soundId <= 0) {
Log.e(TAG, "load() error loading sound: $soundName")
}
}
}
else -> Log.e(TAG, "load() called in wrong state: $sound for sound: $soundName")
}
}
}
fun play(soundName: Int, onPlayComplete: (() -> Unit)? = null) {
if (soundName < 0 || soundName >= SOUND_FILES.size) {
throw RuntimeException("Unknown sound requested: $soundName")
}
removeHandlerCallbacks()
if (onPlayComplete != null) {
playCompletionRunnable = Runnable {
onPlayComplete.invoke()
}
}
val sound = mSounds[soundName]
synchronized(sound!!) {
when (sound.state) {
STATE_NOT_LOADED -> {
val soundId = loadSound(sound)
if (soundId <= 0) {
Log.e(TAG, "play() error loading sound: $soundName")
} else {
sound.state = STATE_LOADING_PLAY_REQUESTED
}
}
STATE_LOADING -> sound.state = STATE_LOADING_PLAY_REQUESTED
STATE_LOADED -> {
playSoundPool(sound)
}
else -> Log.e(TAG, "play() called in wrong state: ${sound.state} for sound: $soundName")
}
}
}
private fun playSoundPool(sound: SoundState) {
if (playCompletionRunnable != null) {
val duration = getSoundDuration(sound.path!!)
playTimeHandler.postDelayed(playCompletionRunnable!!, duration)
}
soundPool!!.play(sound.id, 1.0f, 1.0f, 0, 0, 1.0f)
}
fun release() {
if (soundPool != null) {
for (sound in mSounds) {
synchronized(sound!!) {
sound.state = STATE_NOT_LOADED
sound.id = 0
}
}
soundPool?.release()
soundPool = null
}
removeHandlerCallbacks()
releaseMediaPlayer()
}
private fun removeHandlerCallbacks() {
playCompletionRunnable?.let { playTimeHandler.removeCallbacks(it) }
playCompletionRunnable = null
}
private fun releaseMediaPlayer() {
mediaPlayer?.release()
mediaPlayer = null
}
private fun getSoundDuration(soundPath: String): Long {
releaseMediaPlayer()
mediaPlayer = MediaPlayer.create(context, Uri.fromFile(File(soundPath)))
return mediaPlayer!!.duration.toLong()
}
}
| gpl-3.0 | 7063a9dfcd20f7f9b93df137e4dc4313 | 33.791878 | 129 | 0.540852 | 4.717137 | false | false | false | false |
alygin/intellij-rust | src/test/kotlin/org/rust/ide/template/postfix/AssertPostfixTemplateTest.kt | 3 | 1147 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.template.postfix
class AssertPostfixTemplateTest : PostfixTemplateTest(AssertPostfixTemplate()) {
fun testNumber() = doTestNotApplicable(
"""
fn main() {
1234.assert/*caret*/
}
"""
)
fun testSimple() = doTest(
"""
fn main() {
let a = true;
a.assert/*caret*/
}
"""
,
"""
fn main() {
let a = true;
assert!(a);/*caret*/
}
"""
)
fun testNEQ() = doTest(
"""
fn foo(a: i32, b: i32) {
a != b.assert/*caret*/
}
"""
,
"""
fn foo(a: i32, b: i32) {
assert!(a != b);/*caret*/
}
"""
)
fun testSimple1() = doTest(
"""
fn foo(a: i32, b: i32) {
a == b.assert/*caret*/
}
"""
,
"""
fn foo(a: i32, b: i32) {
assert_eq!(a, b);/*caret*/
}
"""
)
}
| mit | 565b12057e40afc81a8ad69ef25f59cf | 18.116667 | 80 | 0.385353 | 3.928082 | false | true | false | false |
blackbbc/Tucao | app/src/main/kotlin/me/sweetll/tucao/widget/HorizontalDividerBuilder.kt | 1 | 1347 | package me.sweetll.tucao.widget
import android.content.Context
import android.graphics.drawable.Drawable
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat
class HorizontalDividerBuilder private constructor(private val context: Context) {
private lateinit var divider: Drawable
private var drawFirstItemTop: Boolean = false
private var leftPadding: Int = 0
private var rightPadding: Int = 0
fun setDivider(@DrawableRes dividerRes: Int): HorizontalDividerBuilder {
this.divider = ContextCompat.getDrawable(context, dividerRes)!!
return this
}
fun setDrawFirstItemTop(drawFirstItemTop: Boolean): HorizontalDividerBuilder {
this.drawFirstItemTop = drawFirstItemTop
return this
}
fun setLeftPadding(leftPadding: Int): HorizontalDividerBuilder {
this.leftPadding = leftPadding
return this
}
fun setRightPadding(rightPadding: Int): HorizontalDividerBuilder {
this.rightPadding = rightPadding
return this
}
fun build(): HorizontalDivider {
return HorizontalDivider(divider, drawFirstItemTop, leftPadding, rightPadding)
}
companion object {
fun newInstance(context: Context): HorizontalDividerBuilder {
return HorizontalDividerBuilder(context)
}
}
}
| mit | 00c5abc2b013b0032cb3991a88054a04 | 28.933333 | 86 | 0.7268 | 5.324111 | false | false | false | false |
jeffcharles/visitor-detector | app/src/main/kotlin/com/beyondtechnicallycorrect/visitordetector/fragments/SettingsFragment.kt | 1 | 4671 | package com.beyondtechnicallycorrect.visitordetector.fragments
import android.content.Context
import android.os.Bundle
import android.support.annotation.StringRes
import android.support.v7.app.AlertDialog
import android.support.v7.preference.Preference
import android.support.v7.preference.PreferenceFragmentCompat
import com.beyondtechnicallycorrect.visitordetector.R
import com.beyondtechnicallycorrect.visitordetector.VisitorDetectorApplication
import com.beyondtechnicallycorrect.visitordetector.settings.RouterSettingsKeys
import com.beyondtechnicallycorrect.visitordetector.validators.NotEmptyValidator
import com.beyondtechnicallycorrect.visitordetector.validators.RouterIpAddressValidator
import timber.log.Timber
import javax.inject.Inject
class SettingsFragment : PreferenceFragmentCompat() {
@Inject lateinit var notEmptyValidator: NotEmptyValidator
@Inject lateinit var routerIpAddressValidator: RouterIpAddressValidator
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
Timber.v("onActivityCreated")
activity.title = this.getString(R.string.settings_fragment_title)
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
Timber.v("onCreatePreferences")
(context.applicationContext as VisitorDetectorApplication)
.getApplicationComponent()
.inject(this)
this.addPreferencesFromResource(R.xml.settings)
this.findPreference(RouterSettingsKeys.homeWifiSsids).onPreferenceChangeListener =
NotEmptyPreferenceChangeListener(
context,
notEmptyValidator,
R.string.settings_home_wifi_networks_cant_be_empty
)
this.findPreference(RouterSettingsKeys.routerIpAddress).onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { preference, newValue ->
val value = newValue as String
when (routerIpAddressValidator.isValid(value)) {
RouterIpAddressValidator.Result.VALID -> true
RouterIpAddressValidator.Result.EMPTY -> {
showErrorAlert(R.string.settings_router_ip_address_cant_be_empty)
false
}
RouterIpAddressValidator.Result.NOT_AN_IP_ADDRESS -> {
showErrorAlert(R.string.settings_router_ip_address_must_be_ip_address)
false
}
RouterIpAddressValidator.Result.NOT_LOCAL_ADDRESS -> {
showErrorAlert(R.string.settings_router_ip_address_must_be_local_ip_address)
false
}
}
}
this.findPreference(RouterSettingsKeys.routerUsername).onPreferenceChangeListener =
NotEmptyPreferenceChangeListener(
context,
notEmptyValidator,
R.string.settings_router_username_cant_be_empty
)
this.findPreference(RouterSettingsKeys.routerPassword).onPreferenceChangeListener =
NotEmptyPreferenceChangeListener(
context,
notEmptyValidator,
R.string.settings_router_password_cant_be_empty
)
}
private fun showErrorAlert(@StringRes errorMessage: Int) {
val alertBuilder = AlertDialog.Builder(context)
alertBuilder.setTitle(R.string.settings_invalid_value_dialog_title)
alertBuilder.setMessage(errorMessage)
alertBuilder.setPositiveButton(android.R.string.ok, null)
alertBuilder.show()
}
private class NotEmptyPreferenceChangeListener(
val context: Context,
val notEmptyValidator: NotEmptyValidator,
@StringRes val cantBeEmptyErrorString: Int
) : Preference.OnPreferenceChangeListener {
override fun onPreferenceChange(preference: Preference?, newValue: Any?): Boolean {
val value = newValue as String
when (notEmptyValidator.isValid(value)) {
NotEmptyValidator.Result.VALID -> return true
NotEmptyValidator.Result.EMPTY -> {
val alertBuilder = AlertDialog.Builder(context)
alertBuilder.setTitle(R.string.settings_invalid_value_dialog_title)
alertBuilder.setMessage(cantBeEmptyErrorString)
alertBuilder.setPositiveButton(android.R.string.ok, null)
alertBuilder.show()
return false
}
}
}
}
}
| mit | e5e0792acfa6254102dc0160642e9c7f | 43.913462 | 100 | 0.668165 | 5.766667 | false | false | false | false |
laurencegw/jenjin | jenjin-core/src/test/kotlin/com/binarymonks/jj/core/components/ComponentLifeCycleTest.kt | 1 | 3302 | package com.binarymonks.jj.core.components
import com.binarymonks.jj.core.mockoutGDXinJJ
import com.binarymonks.jj.core.scenes.Scene
import com.binarymonks.jj.core.scenes.ScenePath
import com.binarymonks.jj.core.testScene
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito
import org.mockito.runners.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class ComponentLifeCycleTest {
lateinit var mockComponent: Component
lateinit var scene: Scene
@Before
fun setUp() {
mockoutGDXinJJ()
scene = testScene()
mockComponent = Mockito.mock(Component::class.java)
Mockito.`when`(mockComponent.type()).thenReturn(Component::class)
}
@Test
fun addToScene_whenSceneIsNotInitiallyAddedToWorld_removed_and_added_again() {
scene.addComponent(mockComponent)
Mockito.verify(mockComponent, Mockito.never()).onAddToWorld()
scene.onAddToWorld()
Mockito.verify(mockComponent, Mockito.atMost(1)).onAddToWorld()
scene.executeDestruction()
Mockito.verify(mockComponent).onRemoveFromWorld()
scene.onAddToWorld()
Mockito.verify(mockComponent, Mockito.atLeast(2)).onAddToWorld()
}
@Test
fun addToScene_whenSceneIsInitiallyAddedToWorld() {
Mockito.`when`(mockComponent.isDone()).thenReturn(true)
scene.onAddToWorld()
scene.addComponent(mockComponent)
Mockito.verify(mockComponent).onAddToWorld()
}
@Test
fun addToSceneAfterBeingRemovedFromScene() {
Mockito.`when`(mockComponent.isDone()).thenReturn(true)
scene.onAddToWorld()
scene.addComponent(mockComponent)
scene.update()
scene.update()
Mockito.verify(mockComponent, Mockito.atLeast(1)).onRemoveFromWorld()
scene.addComponent(mockComponent)
Mockito.verify(mockComponent, Mockito.atLeast(2)).onAddToWorld()
}
@Test
fun onAddToWorld_graphIsComplete_whenAddedToWorld() {
val parentScene = testScene()
parentScene.addComponent(GetMyChildSceneMock())
val childScene = testScene(name = "child")
childScene.addComponent(GetMyParentSceneMock())
childScene.addComponent(GetMyChildSceneMock())
parentScene.add(childScene)
val grandChildScene = testScene(name = "child")
grandChildScene.addComponent(GetMyParentSceneMock())
childScene.add(grandChildScene)
parentScene.onAddToWorld()
}
@Test
fun addAddToWorld_graphIsComplete_whenAddedToSceneAlreadyInWorld() {
val parentScene = testScene()
parentScene.onAddToWorld()
val childScene = testScene(name = "child")
childScene.addComponent(GetMyParentSceneMock())
childScene.addComponent(GetMyChildSceneMock())
val grandChildScene = testScene(name = "child")
grandChildScene.addComponent(GetMyParentSceneMock())
childScene.add(grandChildScene)
parentScene.add(childScene)
}
}
class GetMyParentSceneMock : Component() {
override fun onAddToWorld() {
me().getNode(ScenePath().up()).name
}
}
class GetMyChildSceneMock : Component() {
override fun onAddToWorld() {
me().getChild("child")!!.name
}
} | apache-2.0 | ac99ee280b665fa74e5be5607c62bafe | 26.525 | 82 | 0.69685 | 4.339028 | false | true | false | false |
Ingwersaft/James | src/main/kotlin/com/mkring/james/mapping/Ask.kt | 1 | 1472 | package com.mkring.james.mapping
/**
* add fallback default value
*/
infix fun <T> Ask<T>.or(fallback: T) = when (this) {
is Ask.Answer -> this
else -> Ask.Answer(fallback)
}
/**
* get answer or given default
*/
infix fun <T> Ask<T>.getOrElse(fallback: T) = when (this) {
is Ask.Answer -> value
else -> fallback
}
/**
* map answer
*/
inline infix fun <T, R> Ask<T>.map(function: (T) -> (R)): Ask<R> = when (this) {
is Ask.Timeout -> this
is Ask.Answer -> Ask.Answer(function(value))
}
/**
* validate answer
*/
inline infix fun <T> Ask<T>.any(predicate: (T) -> Boolean): Boolean = when (this) {
is Ask.Answer -> predicate(value)
is Ask.Timeout -> false
}
/**
* class encapsulating chat-conversation results
*/
sealed class Ask<out T> {
abstract fun get(): T
/**
* no answer given in time
*/
object Timeout : Ask<Nothing>() {
override fun get(): Nothing {
throw IllegalStateException("timeout or aborted")
}
override fun toString() = "[Timeout]"
}
/**
* answer object
*/
data class Answer<out T>(val value: T) : Ask<T>() {
override fun get(): T = value
override fun toString() = "[Answer: $value]"
}
companion object {
/**
* wrap a given function
*/
fun <T> of(f: () -> T): Ask<T> = try {
Answer(f())
} catch (ex: Exception) {
Timeout
}
}
}
| gpl-3.0 | 8db13ed1169686d5b0e88f6346ad2d6e | 20.028571 | 83 | 0.542799 | 3.581509 | false | false | false | false |
mingdroid/tumbviewer | app/src/main/java/com/nutrition/express/ui/login/LoginViewModel.kt | 1 | 8811 | package com.nutrition.express.ui.login
import androidx.lifecycle.*
import com.nutrition.express.BuildConfig
import com.nutrition.express.application.Constant
import com.nutrition.express.model.api.*
import com.nutrition.express.model.data.AppData
import com.nutrition.express.model.data.bean.TumblrApp
import com.nutrition.express.model.helper.OAuth1SigningHelper
import com.nutrition.express.ui.login.LoginType.NEW_ROUTE
import com.nutrition.express.ui.login.LoginType.NORMAL
import com.nutrition.express.ui.login.LoginType.ROUTE_SWITCH
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import okhttp3.Call
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import java.util.*
import kotlin.coroutines.coroutineContext
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.random.Random
class LoginViewModel : ViewModel() {
private var _tumblrApp = MutableLiveData<TumblrApp>()
private var _oauthVerifier = MutableLiveData<String>()
val requestToken = _tumblrApp.switchMap {
getRequestToken(it)
}
val accessToken = _oauthVerifier.switchMap {
getAccessToken(it)
}
private var type = NORMAL
private var oauthToken: OauthToken? = null
fun setOauthVerifier(oauthVerifier: String) {
_oauthVerifier.value = oauthVerifier
}
/*
* init api key/secret
*/
fun setType(type: Int) {
this.type = type;
var tumblrApp: TumblrApp? = null
if (type == NEW_ROUTE) {
tumblrApp = AppData.getTumblrApp()
}
if (tumblrApp == null) {
tumblrApp = selectUnusedTumblrApp(AppData.getDefaultTumplrApps())
}
if (tumblrApp == null) {
tumblrApp = TumblrApp(Constant.CONSUMER_KEY, Constant.CONSUMER_SECRET)
}
_tumblrApp.value = tumblrApp
}
/**
* get tumblr app key for positive account, just route switching.
*
* @param map
*/
private fun selectUnusedTumblrApp(map: HashMap<String, String>): TumblrApp? {
val accounts = AppData.getTumblrAccounts()
if (accounts.size < map.size) {
for (account in accounts) {
map.remove(account.apiKey)
}
} else {
val positiveAccount = AppData.getPositiveAccount()
positiveAccount?.let {
if (positiveAccount.name.isNullOrEmpty()) {
map.remove(positiveAccount.apiKey)
} else {
for (account in accounts) {
if (positiveAccount.name == account.name) {
map.remove(account.apiKey)
}
}
}
}
}
return if (map.size > 0) {
val list: List<String> = ArrayList(map.keys)
Random.nextInt()
val randomIndex = Random.nextInt(list.size)
val key = list[randomIndex]
TumblrApp(key, map[key])
} else {
null
}
}
private fun getRequestToken(tumblrApp: TumblrApp): LiveData<Resource<OauthToken>> {
return liveData {
emit(InProgress)
val auth = OAuth1SigningHelper(tumblrApp.apiKey, tumblrApp.apiSecret)
.buildRequestHeader("POST", Constant.REQUEST_TOKEN_URL)
val request = Request.Builder().run {
url(Constant.REQUEST_TOKEN_URL)
method("POST", "".toRequestBody("text/plain; charset=utf-8".toMediaType()))
header("Authorization", auth)
build()
}
withContext(viewModelScope.coroutineContext + Dispatchers.IO) {
val call = ApiClient.getOkHttpClient().newCall(request)
suspendCancellableCoroutine<Result<Response>> { continuation ->
continuation.invokeOnCancellation {
call.cancel()
}
runCatching {
call.execute()
}.onSuccess {
continuation.resume(Result.success(it))
}.onFailure {
continuation.resume(Result.failure<Response>(it))
}
}
}.onSuccess {
response ->
if (response.isSuccessful) {
val body = response.body?.string()
val hashMap = convert(body)
val oauthToken = hashMap["oauth_token"]
val oauthTokenSecret = hashMap["oauth_token_secret"]
if (oauthToken != null && oauthTokenSecret != null) {
[email protected] = OauthToken(oauthToken, oauthTokenSecret)
emit(Resource.Success([email protected]))
} else {
emit(Resource.Error(0, "unknown error"))
}
} else {
emit(Resource.Error(response.code, response.message))
}
response.close()
}.onFailure {
emit(Resource.Error(0, it.message ?: it.toString()))
}
}
}
private fun getAccessToken(oauthVerifier: String): LiveData<Resource<OauthToken>> {
val loginResult = MutableLiveData<Resource<OauthToken>>()
val tumblrApp = _tumblrApp.value ?: return loginResult
val oauth = oauthToken ?: return loginResult
loginResult.value = InProgress
val auth = OAuth1SigningHelper(tumblrApp.apiKey, tumblrApp.apiSecret)
.buildAccessHeader("POST", Constant.ACCESS_TOKEN_URL,
oauth.token, oauthVerifier, oauth.secret)
val request = Request.Builder()
.url(Constant.ACCESS_TOKEN_URL)
.method("POST", "".toRequestBody("text/plain; charset=utf-8".toMediaType()))
.header("Authorization", auth)
.build()
return liveData(viewModelScope.coroutineContext) {
emit(InProgress)
withContext(coroutineContext + Dispatchers.IO) {
val call = ApiClient.getOkHttpClient().newCall(request)
suspendCancellableCoroutine<Result<Response>> { continuation ->
continuation.invokeOnCancellation {
call.cancel()
}
runCatching {
call.execute()
}.onSuccess {
continuation.resume(Result.success(it))
}.onFailure {
continuation.resume(Result.failure<Response>(it))
}
}
}.onSuccess {
response ->
if (response.isSuccessful) {
val body = response.body?.string()
val hashMap = convert(body)
val oauthToken = hashMap["oauth_token"]
val oauthTokenSecret = hashMap["oauth_token_secret"]
if (oauthToken != null && oauthTokenSecret != null) {
val tumblrAccount = AppData.addAccount(
tumblrApp.apiKey, tumblrApp.apiSecret, oauthToken, oauthTokenSecret)
if (type == NEW_ROUTE || type == ROUTE_SWITCH) {
AppData.switchToAccount(tumblrAccount)
}
emit(Resource.Success(OauthToken(oauthToken, oauthTokenSecret)))
} else {
emit(Resource.Error(0, "unknown error"))
}
} else {
emit(Resource.Error(response.code, response.message))
}
response.close()
}.onFailure {
emit(Resource.Error(0, it.message ?: it.toString()))
}
}
}
private fun convert(body: String?): HashMap<String, String> {
val hashMap = HashMap<String, String>()
body?.let {
val strings = body.split("&").toTypedArray()
for (string in strings) {
val pair = string.split("=").toTypedArray()
if (pair.size == 2) {
hashMap[pair[0]] = pair[1]
}
}
}
return hashMap
}
data class OauthToken(val token: String, val secret: String)
} | apache-2.0 | 6c63a4471f671c25d409173be5bbcbf9 | 38.873303 | 100 | 0.555896 | 5.164713 | false | false | false | false |
tipsy/javalin | javalin-openapi/src/main/java/io/javalin/plugin/openapi/jackson/JavalinModelResolver.kt | 1 | 1616 | package io.javalin.plugin.openapi.jackson
import com.fasterxml.jackson.databind.JavaType
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import io.swagger.v3.core.converter.AnnotatedType
import io.swagger.v3.core.converter.ModelConverter
import io.swagger.v3.core.converter.ModelConverterContext
import io.swagger.v3.core.jackson.ModelResolver
import io.swagger.v3.core.util.PrimitiveType
import io.swagger.v3.oas.models.media.Schema
import java.time.Instant
class JavalinModelResolver(mapper: ObjectMapper) : ModelResolver(mapper) {
override fun resolve(annotatedType: AnnotatedType?, context: ModelConverterContext?, next: MutableIterator<ModelConverter>?): Schema<*> {
if (annotatedType == null || shouldIgnoreClass(annotatedType.type)) {
return super.resolve(annotatedType, context, next)
}
val type = extractJavaType(annotatedType)
if (type.isTypeOrSubTypeOf(Instant::class.java) && _mapper.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
&& annotatedType.ctxAnnotations?.none { it.annotationClass == io.swagger.v3.oas.annotations.media.Schema::class.java } != false
) {
return PrimitiveType.LONG.createProperty()
}
return super.resolve(annotatedType, context, next)
}
private fun extractJavaType(annotatedType: AnnotatedType): JavaType {
return if (annotatedType.type is JavaType) {
annotatedType.type as JavaType
} else {
this._mapper.constructType(annotatedType.type)
}
}
}
| apache-2.0 | b61584e321574e51ce883583e43d577c | 41.526316 | 141 | 0.737005 | 4.367568 | false | false | false | false |
vovagrechka/k2php | k2php/src/org/jetbrains/kotlin/js/translate/utils/astUtils.kt | 1 | 3409 | /*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.js.translate.utils.jsAstUtils
import k2php.*
import org.jetbrains.kotlin.js.backend.ast.*
import org.jetbrains.kotlin.js.translate.context.Namer
import photlin.*
fun JsFunction.addStatement(stmt: JsStatement) {
body.statements.add(stmt)
}
fun JsFunction.addParameter(identifier: String, index: Int? = null): JsParameter {
val name = scope.declareTemporaryName(identifier)
val parameter = JsParameter(name)
if (index == null) {
parameters.add(parameter)
} else {
parameters.add(index, parameter)
}
return parameter
}
/**
* Tests, if any node containing in receiver's AST matches, [predicate].
*/
fun JsNode.any(predicate: (JsNode) -> Boolean): Boolean {
val visitor = object : RecursiveJsVisitor() {
var matched: Boolean = false
override fun visitElement(node: JsNode) {
matched = matched || predicate(node)
if (!matched) {
super.visitElement(node)
}
}
}
visitor.accept(this)
return visitor.matched
}
fun JsExpression.toInvocationWith(
leadingExtraArgs: List<JsExpression>,
parameterCount: Int,
thisExpr: JsExpression
): JsExpression {
val qualifier: JsExpression
fun padArguments(arguments: List<JsExpression>) = arguments + (1..(parameterCount - arguments.size))
.map { Namer.getUndefinedExpression() }
when (this) {
is JsNew -> {
qualifier = Namer.getFunctionCallRef(constructorExpression)
// `new A(a, b, c)` -> `A.call($this, a, b, c)`
return JsInvocation(JsNameRef("__construct", thisExpr)-{o->
o.kind = PHPNameRefKind.FIELD
}, leadingExtraArgs + arguments)
// return JsInvocation(qualifier, listOf(thisExpr) + leadingExtraArgs + arguments)
}
is JsInvocation -> {
qualifier = getQualifier()
// `A(a, b, c)` -> `A(a, b, c, $this)`
return JsInvocation(qualifier, leadingExtraArgs + padArguments(arguments) + thisExpr)
}
else -> throw IllegalStateException("Unexpected node type: " + javaClass)
}
}
var JsWhile.test: JsExpression
get() = condition
set(value) { condition = value }
var JsArrayAccess.index: JsExpression
get() = indexExpression
set(value) { indexExpression = value }
var JsArrayAccess.array: JsExpression
get() = arrayExpression
set(value) { arrayExpression = value }
var JsConditional.test: JsExpression
get() = testExpression
set(value) { testExpression = value }
var JsConditional.then: JsExpression
get() = thenExpression
set(value) { thenExpression = value }
var JsConditional.otherwise: JsExpression
get() = elseExpression
set(value) { elseExpression = value }
| apache-2.0 | 2602a743d6fbeb6d6fc51d46b397ba8c | 29.990909 | 104 | 0.666178 | 4.203453 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/multimediacard/fields/ImageField.kt | 1 | 4169 | /****************************************************************************************
* Copyright (c) 2013 Bibek Shrestha <[email protected]> *
* Copyright (c) 2013 Zaur Molotnikov <[email protected]> *
* Copyright (c) 2013 Nicolas Raoul <[email protected]> *
* Copyright (c) 2013 Flavio Lerda <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki.multimediacard.fields
import androidx.annotation.CheckResult
import androidx.annotation.VisibleForTesting
import com.ichi2.libanki.Collection
import com.ichi2.utils.KotlinCleanup
import org.jsoup.Jsoup
import timber.log.Timber
import java.io.File
/**
* Field with an image.
*/
@KotlinCleanup("convert properties to single-line overrides")
class ImageField : FieldBase(), IField {
@get:JvmName("getImagePath_unused")
var extraImagePathRef: String? = null
private var mName: String? = null
override val type: EFieldType = EFieldType.IMAGE
override val isModified: Boolean
get() = thisModified
override var imagePath: String?
get() = extraImagePathRef
set(value) {
extraImagePathRef = value
setThisModified()
}
override var audioPath: String? = null
override var text: String? = null
override var hasTemporaryMedia: Boolean = false
override var name: String?
get() = mName
set(value) {
mName = value
}
override val formattedValue: String
get() {
val file = File(imagePath!!)
return formatImageFileName(file)
}
override fun setFormattedString(col: Collection, value: String) {
extraImagePathRef = getImageFullPath(col, value)
}
companion object {
private const val serialVersionUID = 4431611060655809687L
@VisibleForTesting
fun formatImageFileName(file: File): String {
return if (file.exists()) {
"""<img src="${file.name}">"""
} else {
""
}
}
@VisibleForTesting
@KotlinCleanup("remove ? from value")
fun getImageFullPath(col: Collection, value: String?): String {
val path = parseImageSrcFromHtml(value)
if ("" == path) {
return ""
}
val mediaDir = col.media.dir() + "/"
return mediaDir + path
}
@VisibleForTesting
@CheckResult
@KotlinCleanup("remove ? from html")
fun parseImageSrcFromHtml(html: String?): String {
return if (html == null) {
""
} else try {
val doc = Jsoup.parseBodyFragment(html)
val image = doc.selectFirst("img[src]") ?: return ""
image.attr("src")
} catch (e: Exception) {
Timber.w(e)
""
}
}
}
}
| gpl-3.0 | c208ffffb64253b511386880dd4b634f | 36.558559 | 90 | 0.509235 | 5.127921 | false | false | false | false |
rock3r/detekt | detekt-cli/src/main/kotlin/io/gitlab/arturbosch/detekt/cli/ReportPath.kt | 1 | 1733 | package io.gitlab.arturbosch.detekt.cli
import io.gitlab.arturbosch.detekt.cli.out.HtmlOutputReport
import io.gitlab.arturbosch.detekt.cli.out.TxtOutputReport
import io.gitlab.arturbosch.detekt.cli.out.XmlOutputReport
import java.nio.file.Path
import java.nio.file.Paths
data class ReportPath(val kind: String, val path: Path) {
companion object {
private const val NUM_OF_PARTS_UNIX = 2
private const val NUM_OF_PARTS_WINDOWS = 3
private const val REPORT_PATH_SEPARATOR = ":"
fun from(input: String): ReportPath {
val parts = input.split(REPORT_PATH_SEPARATOR)
val path = when (val partsSize = parts.size) {
NUM_OF_PARTS_UNIX -> parts[1]
NUM_OF_PARTS_WINDOWS -> parts.slice(1 until partsSize).joinToString(REPORT_PATH_SEPARATOR)
else -> error(
"Input '$input' must consist of two parts for Unix OSs or three for Windows (report-id:path)."
)
}
val kind = parts[0]
assertNotEmpty(kind, path)
return ReportPath(defaultMapping(kind), Paths.get(path))
}
private fun assertNotEmpty(kind: String, path: String) {
require(kind.isNotEmpty()) { "The kind of report must not be empty (path - $path)" }
require(path.isNotEmpty()) { "The path of the report must not be empty (kind - $kind)" }
}
private fun defaultMapping(reportId: String) = when (reportId) {
"txt" -> TxtOutputReport::class.java.simpleName
"xml" -> XmlOutputReport::class.java.simpleName
"html" -> HtmlOutputReport::class.java.simpleName
else -> reportId
}
}
}
| apache-2.0 | d43c4916e7e1461e6e67fffcdefb25bd | 38.386364 | 114 | 0.619735 | 4.106635 | false | false | false | false |
tipsy/javalin | javalin/src/test/java/io/javalin/TestLifecycleEvents.kt | 1 | 2099 | /*
* Javalin - https://javalin.io
* Copyright 2017 David Åse
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*
*/
package io.javalin
import io.javalin.testing.TestUtil
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class TestLifecycleEvents {
@Test
fun `lifecycle events work`() = TestUtil.runLogLess {
var log = ""
Javalin.create().events { event ->
event.serverStarting { log += "Starting" }
event.serverStarted { log += "Started" }
event.serverStopping { log += "Stopping" }
event.serverStopping { log += "Stopping" }
event.serverStopping { log += "Stopping" }
event.serverStopped { log += "Stopped" }
}.start(0).stop()
assertThat(log).isEqualTo("StartingStartedStoppingStoppingStoppingStopped")
}
@Test
fun `server started event works`() = TestUtil.runLogLess {
var log = ""
val existingApp = Javalin.create().start(20000)
runCatching {
Javalin.create().events { event ->
event.serverStartFailed { log += "Failed to start" }
}.start(20000).stop() // port conflict
}
assertThat(log).isEqualTo("Failed to start")
existingApp.stop()
}
@Test
fun `handlerAdded event works`() = TestUtil.test { app, _ ->
var log = ""
app.events { it.handlerAdded { handlerMetaInfo -> log += handlerMetaInfo.path } }
app.events { it.handlerAdded { handlerMetaInfo -> log += handlerMetaInfo.path } }
app.get("/test-path") {}
assertThat(log).isEqualTo("/test-path/test-path")
}
@Test
fun `wsHandlerAdded event works`() = TestUtil.test { app, _ ->
var log = ""
app.events { it.wsHandlerAdded { handlerMetaInfo -> log += handlerMetaInfo.path } }
app.events { it.wsHandlerAdded { handlerMetaInfo -> log += handlerMetaInfo.path } }
app.ws("/test-path-ws") {}
assertThat(log).isEqualTo("/test-path-ws/test-path-ws")
}
}
| apache-2.0 | 6fa1f4af2367b9a1bb08e7427bd7cef4 | 33.393443 | 91 | 0.605338 | 4.089669 | false | true | false | false |
shkschneider/android_Skeleton | core/src/main/kotlin/me/shkschneider/skeleton/javax/Version.kt | 1 | 1617 | package me.shkschneider.skeleton.javax
open class Version(version: String) : Comparable<Version> {
private var version: List<String> = version.split(".")
// <https://semver.org>
fun semVer(): Boolean {
val parts = version.toString().takeWhile { it.isDigit() || it == '.' }.split(".")
if (parts.size == 3) {
parts.forEach {
it.toIntOrNull() ?: return false
}
return true
}
return false
}
override fun compareTo(other: Version): Int {
val version2 = other.toList()
val size = Math.max(version.size, version2.size)
0.rangeTo(size).forEach { i ->
try {
// Process as number
val i1: Int = if (i < version.size) Integer.valueOf(version[i]) else 0
val i2: Int = if (i < version2.size) Integer.valueOf(version2[i]) else 0
if (i1 < i2) return -1
if (i1 > i2) return 1
} catch (e: NumberFormatException) {
// Process as string
return version[i].compareTo(version2[i])
}
}
return 0
}
private fun toList(): List<String> {
return version
}
override fun toString(): String {
return version.joinToString(".")
}
class Comparator : java.util.Comparator<Version> {
override fun compare(v1: Version?, v2: Version?): Int {
v1 ?: return -1
v2 ?: return 1
return v1.compareTo(v2)
}
}
}
| apache-2.0 | eeacafa04d31818318b86153f7d42f68 | 27.4 | 89 | 0.500928 | 4.405995 | false | false | false | false |
adityaDave2017/my-vocab | app/src/main/java/com/android/vocab/activity/WordEditorActivity.kt | 1 | 4778 | package com.android.vocab.activity
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import com.android.vocab.R
import com.android.vocab.adapter.TypeListAdapter
import com.android.vocab.databinding.ActivityWordEditorBinding
import com.android.vocab.provider.bean.Word
import com.android.vocab.provider.bean.WordAndType
import com.android.vocab.provider.bean.WordType
import com.android.vocab.provider.deleteWord
import com.android.vocab.provider.getWordTypes
import com.android.vocab.provider.insertNewWord
import com.android.vocab.provider.updateWord
import com.android.vocab.utils.hideSoftKeyboard
import kotlinx.android.synthetic.main.content_word_editor.*
@Suppress("unused")
class WordEditorActivity : AppCompatActivity() {
val LOG_TAG: String = WordEditorActivity::class.java.simpleName
companion object {
val ADD_REQUEST:Int = 1
val EDIT_REQUEST:Int = 2
val NO_CHANGE_RESULT: Int = 3
val CHANGE_OCCURRED_RESULT: Int = 4
val WORD_TO_EDIT: String = "WORD_TO_EDIT"
val PARENT_ACTIVITY_CLASS: String = "PARENT_ACTIVITY"
}
private var isEdit: Boolean = false
private lateinit var binding: ActivityWordEditorBinding
private lateinit var prevWord: WordAndType
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (intent.getStringExtra(PARENT_ACTIVITY_CLASS) == null) {
throw Exception("Parent Activity must be specified")
}
binding = DataBindingUtil.setContentView(this, R.layout.activity_word_editor)
binding.word = if (intent.getParcelableExtra<Word>(WORD_TO_EDIT) != null) {
isEdit = true
prevWord = intent.getParcelableExtra(WORD_TO_EDIT)
prevWord.makeClone()
} else {
WordAndType()
}
setSupportActionBar(findViewById(R.id.appBarEditWord) as Toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val typeList: ArrayList<WordType> = ArrayList()
typeList.add(WordType(typeName = getString(R.string.select_type)))
typeList.addAll(getWordTypes(baseContext))
spinnerWordType.adapter =
TypeListAdapter(baseContext, R.layout.support_simple_spinner_dropdown_item, typeList)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_editor, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.miDelete -> {
hideSoftKeyboard(this)
deleteWord(baseContext, binding.word)
setResult(CHANGE_OCCURRED_RESULT)
finish()
return true
}
R.id.miDone -> {
hideSoftKeyboard(this)
// Update when old item
if (isEdit) {
if (!isValidInput()) {
return true
}
if (binding.word != prevWord) {
updateWord(baseContext, binding.word)
setResult(CHANGE_OCCURRED_RESULT)
} else {
Toast.makeText(baseContext, getString(R.string.no_change), Toast.LENGTH_SHORT).show()
}
finish()
// Add when new item
} else {
if (!isValidInput()) {
return true
}
insertNewWord(baseContext, binding.word)
setResult(CHANGE_OCCURRED_RESULT)
finish()
}
return true
}
else -> return false
}
}
private fun isValidInput(): Boolean {
var valid: Boolean = true
if (binding.word.word.isEmpty()) {
valid = false
tilWord.editText?.error = getString(R.string.error_word_enter)
}
if (binding.word.meaning.isEmpty()) {
valid = false
tilMeaning.editText?.error = getString(R.string.error_meaning_enter)
}
if (spinnerWordType.selectedItemPosition == 0) {
valid = false
Toast.makeText(baseContext, getString(R.string.select_type), Toast.LENGTH_SHORT).show()
}
return valid
}
override fun onSupportNavigateUp(): Boolean {
finish()
return true
}
}
| mit | c76b06c04be4b1145d852dc6095f262c | 32.412587 | 109 | 0.614274 | 4.698132 | false | false | false | false |
i7c/cfm | server/mbservice/src/main/kotlin/org/rliz/mbs/release/data/ReleaseGroupRepo.kt | 1 | 1972 | package org.rliz.mbs.release.data
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.jdbc.core.JdbcOperations
import org.springframework.stereotype.Service
import java.util.UUID
@Service
class ReleaseGroupRepo {
@Autowired
lateinit var jdbc: JdbcOperations
fun getReleaseGroups(ids: List<UUID>): List<ReleaseGroupWithArtists> =
jdbc.query(
"""
select
rg.gid rg_gid,
rg.name as rg_name,
acn.name as acn_name,
acn.join_phrase as acn_jp
from musicbrainz.release_group rg
join musicbrainz.artist_credit ac on (rg.artist_credit = ac.id)
join musicbrainz.artist_credit_name acn on (acn.artist_credit = ac.id)
where rg.gid in (?${", ?".repeat(ids.size - 1)})
order by
acn.position asc
""".trimIndent(),
{ rs, _ ->
ReleaseGroupWithArtist(
UUID.fromString(rs.getString("rg_gid")),
rs.getString("rg_name"),
rs.getString("acn_jp"),
rs.getString("acn_name")
)
},
ids.toTypedArray()
).groupBy(ReleaseGroupWithArtist::id).map { accumulate(it.value) }
fun getReleaseGroup(id: UUID): ReleaseGroupWithArtists? =
getReleaseGroups(listOf(id))
.let {
if (it.isEmpty()) return null
it[0]
}
private fun accumulate(flatLines: List<ReleaseGroupWithArtist>): ReleaseGroupWithArtists =
ReleaseGroupWithArtists(
flatLines[0].id,
flatLines[0].name,
flatLines.map(ReleaseGroupWithArtist::artist),
flatLines.fold("", { acc, next -> "$acc${next.artist}${next.joinPhrase}" })
)
}
| gpl-3.0 | ff7d52ccc1888833035ffbd2f26baebf | 35.518519 | 94 | 0.537018 | 4.543779 | false | false | false | false |
PaulWoitaschek/Voice | bookOverview/src/main/kotlin/voice/bookOverview/views/Header.kt | 1 | 548 | package voice.bookOverview.views
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import voice.bookOverview.overview.BookOverviewCategory
@Composable
internal fun Header(
category: BookOverviewCategory,
modifier: Modifier = Modifier,
) {
Text(
modifier = modifier,
text = stringResource(id = category.nameRes),
style = MaterialTheme.typography.headlineSmall,
)
}
| gpl-3.0 | d0fcfba2f02b19630ed761f01a924ca0 | 26.4 | 55 | 0.804745 | 4.419355 | false | false | false | false |
danrien/projectBlueWater | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/browsing/remote/MediaItemServiceFileLookup.kt | 1 | 2864 | package com.lasthopesoftware.bluewater.client.browsing.remote
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.MediaMetadataCompat
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.FilePropertyHelpers
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.KnownFileProperties
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.ProvideScopedFileProperties
import com.lasthopesoftware.bluewater.client.browsing.items.media.image.ProvideImages
import com.namehillsoftware.handoff.promises.Promise
class MediaItemServiceFileLookup(
private val filePropertiesProvider: ProvideScopedFileProperties,
private val imageProvider: ProvideImages
) : GetMediaItemsFromServiceFiles {
override fun promiseMediaItem(serviceFile: ServiceFile): Promise<MediaBrowserCompat.MediaItem> {
return promiseMediaMetadataWithFileProperties(serviceFile)
.then { mediaMetadataBuilder ->
MediaBrowserCompat.MediaItem(
mediaMetadataBuilder.build().description,
MediaBrowserCompat.MediaItem.FLAG_PLAYABLE
)
}
}
override fun promiseMediaItemWithImage(serviceFile: ServiceFile): Promise<MediaBrowserCompat.MediaItem> {
val promisedImage = imageProvider.promiseFileBitmap(serviceFile)
return promiseMediaMetadataWithFileProperties(serviceFile)
.eventually { mediaMetadataBuilder ->
promisedImage.then { image ->
mediaMetadataBuilder.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, image)
MediaBrowserCompat.MediaItem(
mediaMetadataBuilder.build().description,
MediaBrowserCompat.MediaItem.FLAG_PLAYABLE
)
}
}
}
private fun promiseMediaMetadataWithFileProperties(serviceFile: ServiceFile) =
filePropertiesProvider.promiseFileProperties(serviceFile)
.then { p ->
MediaMetadataCompat.Builder().apply {
val artist = p[KnownFileProperties.ARTIST]
val name = p[KnownFileProperties.NAME]
val album = p[KnownFileProperties.ALBUM]
val duration = FilePropertyHelpers.parseDurationIntoMilliseconds(p).toLong()
putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, RemoteBrowserService.serviceFileMediaIdPrefix + RemoteBrowserService.mediaIdDelimiter + p[KnownFileProperties.KEY])
putString(MediaMetadataCompat.METADATA_KEY_ARTIST, artist)
putString(MediaMetadataCompat.METADATA_KEY_ALBUM, album)
putString(MediaMetadataCompat.METADATA_KEY_TITLE, name)
putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration)
val trackNumberString = p[KnownFileProperties.TRACK]
val trackNumber = trackNumberString?.toLongOrNull()
if (trackNumber != null) {
putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, trackNumber)
}
}
}
}
| lgpl-3.0 | 4bc1886fa4701af023cc4ab0d4af8de5 | 43.75 | 173 | 0.80831 | 4.672104 | false | false | false | false |
tasks/tasks | app/src/test/java/org/tasks/makers/GtaskListMaker.kt | 1 | 1521 | package org.tasks.makers
import com.natpryce.makeiteasy.Instantiator
import com.natpryce.makeiteasy.Property
import com.natpryce.makeiteasy.Property.newProperty
import com.natpryce.makeiteasy.PropertyLookup
import com.natpryce.makeiteasy.PropertyValue
import com.todoroo.astrid.api.FilterListItem.NO_ORDER
import org.tasks.data.GoogleTaskList
import org.tasks.makers.Maker.make
object GtaskListMaker {
val ID: Property<GoogleTaskList, Long> = newProperty()
val ACCOUNT: Property<GoogleTaskList, String> = newProperty()
val REMOTE_ID: Property<GoogleTaskList, String> = newProperty()
val LAST_SYNC: Property<GoogleTaskList, Long> = newProperty()
val NAME: Property<GoogleTaskList, String> = newProperty()
private val ORDER: Property<GoogleTaskList, Int> = newProperty()
private val COLOR: Property<GoogleTaskList, Int> = newProperty()
private val instantiator = Instantiator { lookup: PropertyLookup<GoogleTaskList> ->
val list = GoogleTaskList()
list.id = lookup.valueOf(ID, 0L)
list.account = lookup.valueOf(ACCOUNT, "account")
list.remoteId = lookup.valueOf(REMOTE_ID, "1")
list.title = lookup.valueOf(NAME, "Default")
list.order = lookup.valueOf(ORDER, NO_ORDER)
list.lastSync = lookup.valueOf(LAST_SYNC, 0L)
list.setColor(lookup.valueOf(COLOR, 0))
list
}
fun newGtaskList(vararg properties: PropertyValue<in GoogleTaskList?, *>): GoogleTaskList {
return make(instantiator, *properties)
}
} | gpl-3.0 | 28be0a14bf0cac2c4b144928a6fefdd8 | 41.277778 | 95 | 0.731755 | 4.02381 | false | false | false | false |
AoEiuV020/PaNovel | baseJar/src/main/java/cc/aoeiuv020/base/jar/jsoup.kt | 1 | 8252 | @file:Suppress("unused")
package cc.aoeiuv020.base.jar
import cc.aoeiuv020.anull.notNull
import cc.aoeiuv020.okhttp.OkHttpUtils
import cc.aoeiuv020.okhttp.charset
import cc.aoeiuv020.okhttp.url
import cc.aoeiuv020.regex.compileRegex
import okhttp3.Call
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.jsoup.nodes.Node
import org.jsoup.nodes.TextNode
import org.jsoup.select.Elements
import org.jsoup.select.NodeTraversor
import org.jsoup.select.NodeVisitor
import java.net.URL
import java.util.*
/**
* Created by AoEiuV020 on 2018.06.10-15:56:52.
*/
fun jsoupParse(call: Call): Document {
val response = call.execute()
return response.body().notNull().use {
it.byteStream().use { input ->
Jsoup.parse(input, response.charset(), response.url())
}
}
}
fun jsoupConnect(url: String): Document = jsoupParse(OkHttpUtils.get(url))
fun Element.findAll(predicate: (Element) -> Boolean): List<Element> {
val list = LinkedList<Element>()
// 过时方法懒得改,
@Suppress("DEPRECATION")
NodeTraversor(object : NodeVisitor {
override fun tail(node: Node?, depth: Int) {
}
override fun head(node: Node?, depth: Int) {
if (node is Element && predicate(node)) {
list.add(node)
}
}
}).traverse(this)
// 转成RandomAccess的ArrayList,
return list.toList()
}
/**
* 匹配空白符和空格符,
* 和kotlin的trim效果一致,
* javaWhitespace能匹配全角空格,
* javaSpaceChar能匹配utf-8扩充的半角空格,
*/
private val whitespaceRegex = compileRegex("[\\p{javaWhitespace}\\p{javaSpaceChar}]+")
private val newLineRegex = compileRegex("[\n\r]+")
/**
* 得到列表中每个元素的文字,包括子元素,
* 所有文字部分按空白字符分割,这是最常有的情况,
*/
fun Elements.textListSplitWhitespace(): List<String> = flatMap { it.textListSplitWhitespace() }
/**
* 同时添加了图片,markdown格式,
*/
fun Element.textList(): List<String> {
// 用LinkedList方便频繁添加,
val list = LinkedList<String>()
val line = StringBuilder()
// 过时方法懒得改,
@Suppress("DEPRECATION")
NodeTraversor(object : NodeVisitor {
override fun head(node: Node?, depth: Int) {
if (node is TextNode) {
if (preserveWhitespace(node.parentNode())) {
// 如果是需要保持空格的标签中的文本,按换行符拆成多行,
node.ownTextList().toCollection(list)
} else {
// 如果是普通的标签中的文本,缓存起来,不算一行,
line.append(node.text())
}
} else if (node is Element) {
// 添加图片,按自己的格式,
if (node.isImage()) {
imgText(node)?.let { list.add(it) }
}
// 如果需要换行,把存起来的line处理掉,
if (line.isNotBlank() && (node.isBr() || node.isBlock)) {
list.add(line.toString().trim())
line.delete(0, line.length)
}
}
}
override fun tail(node: Node?, depth: Int) {
}
}).traverse(this)
if (line.isNotBlank()) {
list.add(line.toString().trim())
line.delete(0, line.length)
}
// 转成RandomAccess的ArrayList,
return list.toList()
}
private fun preserveWhitespace(node: Node?): Boolean {
// looks only at this element and one level up, to prevent recursion & needless stack searches
if (node != null && node is Element) {
return node.tag().preserveWhitespace() || node.parent() != null && node.parent().tag().preserveWhitespace()
}
return false
}
/**
* 用所有空格或空白符分割元素里的文字,
* 支持全角空格,
* 同时添加了图片,markdown格式,
*/
fun Element.textListSplitWhitespace(): List<String> {
// 用LinkedList方便频繁添加,
val list = LinkedList<String>()
@Suppress("DEPRECATION")
NodeTraversor(object : NodeVisitor {
private val line = StringBuilder()
override fun head(node: Node?, depth: Int) {
if (node is TextNode) {
// 完全分割所有空白,不需要被分割的span之类也会被分割,
node.ownTextListSplitWhitespace().toCollection(list)
} else if (node is Element && node.isImage()) {
imgText(node)?.let { list.add(it) }
}
}
override fun tail(node: Node?, depth: Int) {
}
}).traverse(this)
// 转成RandomAccess的ArrayList,
return list.toList()
}
// svg中有image标签,
fun Element.isImage() = tagName() == "img" || tagName() == "image"
fun Element.isBr() = tagName() == "br"
// 按markdown格式添加图片字符串,
fun imgText(img: Element): String? {
// 延迟加载可能把地址放在data-original,
return (img.absDataOriginal().takeIf(String::isNotBlank)
?: img.absSrc().takeIf(String::isNotBlank)
// svg中的image标签有这个属性,
?: img.absXlinkHref().takeIf(String::isNotBlank)
)?.let {
// 只记录完整路径,
ImageUtil.getImageFromUrl(it)
}
}
/**
* 并不获取子元素里的文字,
* 支持全角空格,
*/
fun Element.ownTextListSplitWhitespace(): List<String> =
this.textNodes().flatMap { it.ownTextListSplitWhitespace() }
/**
* 并不获取子元素里的文字,
* 支持全角空格,
* 同时添加了图片,markdown格式,
*/
fun Element.ownTextListWithImage(): List<String> =
this.childNodes().flatMap {
if (it is TextNode) {
it.ownTextListSplitWhitespace()
} else if (it is Element && it.tagName() == "img") {
imgText(it)?.let { listOf(it) }
?: listOf()
} else {
listOf()
}
}
/**
* 切开所有换行符,
*/
fun TextNode.ownTextList(): List<String> =
// 用wholeText才能拿到换行符,
wholeText.trim().takeIf(String::isNotEmpty)?.splitNewLine()?.filter(String::isNotBlank)
?: listOf()
/**
* 切开所有空白符,
*/
fun TextNode.ownTextListSplitWhitespace(): List<String> =
// trim里的判断和这个whitespaceRegex是一样的,
// trim后可能得到空字符串,判断一下,
this.wholeText.trim().takeIf(String::isNotEmpty)?.splitWhitespace() ?: listOf()
fun String.splitWhitespace(): List<String> = this.split(whitespaceRegex)
fun String.splitNewLine(): List<String> = this.split(newLineRegex)
fun Element.src(): String = attr("src")
fun Element.absSrc(): String = absUrl(baseUri(), src())
fun Element.dataOriginal(): String = attr("data-original")
fun Element.absDataOriginal(): String = absUrl(baseUri(), dataOriginal())
fun Element.href(): String = attr("href")
fun Element.absHref(): String = absUrl(baseUri(), href())
fun Element.xlinkHref(): String = attr("xlink:href")
fun Element.absXlinkHref(): String = absUrl(baseUri(), xlinkHref())
// Jsoup的absUrl处理jar协议会出问题,错误在jar:后添加一个斜杆,
private fun absUrl(base: String, attr: String): String =
if (attr.isBlank()) ""
else URL(URL(base), attr).toString()
/**
* 地址仅路径,斜杆/开头,
*/
fun Element.path(): String = path(absHref())
fun Element.title(): String = attr("title")
fun Element.ownerPath(): String = URL(ownerDocument().location()).path
// kotlin的trim有包括utf8的特殊的空格,和java的trim不重复,
fun TextNode.textNotBlank(): String? = this.text().trim().takeIf(String::isNotBlank)
fun Element.ownTextList(): List<String> = this.textNodes().flatMap { it.ownTextList() }
fun Element.ownLinesString(): String = ownTextListSplitWhitespace().joinToString("\n")
fun Element.linesString(): String = textListSplitWhitespace().joinToString("\n")
fun TextNode.ownLinesString(): String = ownTextListSplitWhitespace().joinToString("\n")
fun Node.text(): String = (this as TextNode).text()
| gpl-3.0 | 5758ccdeaadc341e757e438f41bf07fb | 29.533333 | 115 | 0.623908 | 3.430712 | false | false | false | false |
SpectraLogic/ds3_autogen | ds3-autogen-go/src/main/kotlin/com/spectralogic/ds3autogen/go/generators/client/ClientGeneratorUtil.kt | 2 | 5480 | /*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.spectralogic.ds3autogen.go.generators.client
import com.spectralogic.ds3autogen.api.models.apispec.Ds3Request
import com.spectralogic.ds3autogen.api.models.enums.Classification
import com.spectralogic.ds3autogen.api.models.enums.Requirement
import com.spectralogic.ds3autogen.go.utils.getGoArgFromResource
import com.spectralogic.ds3autogen.go.utils.isGoResourceAnArg
import com.spectralogic.ds3autogen.utils.Ds3RequestClassificationUtil
import com.spectralogic.ds3autogen.utils.Ds3RequestUtils
import com.spectralogic.ds3autogen.utils.RequestConverterUtil
import com.spectralogic.ds3autogen.utils.models.NotificationType
private const val PATH_REQUEST_REFERENCE = "request"
/**
* Creates the Go request path code for a Ds3 request
*/
fun Ds3Request.toRequestPath(): String {
if (classification == Classification.amazons3) {
return getAmazonS3RequestPath()
}
if (classification == Classification.spectrads3) {
return getSpectraDs3RequestPath()
}
throw IllegalArgumentException("Unsupported classification: " + classification.toString())
}
/**
* Creates the Go request path code for an AmazonS3 request
*/
fun Ds3Request.getAmazonS3RequestPath(): String {
if (classification != Classification.amazons3) {
return ""
}
val builder = StringBuilder("\"/\"")
if (bucketRequirement == Requirement.REQUIRED) {
builder.append(" + ").append(PATH_REQUEST_REFERENCE).append(".BucketName")
}
if (objectRequirement == Requirement.REQUIRED) {
builder.append(" + \"/\" + ").append(PATH_REQUEST_REFERENCE).append(".ObjectName")
}
return builder.toString()
}
/**
* Creates the Go request path code for a SpectraS3 request
*/
fun Ds3Request.getSpectraDs3RequestPath(): String {
if (classification != Classification.spectrads3) {
return ""
}
if (resource == null) {
return "\"/_rest_/\""
}
val builder = StringBuilder("\"/_rest_/")
.append(resource!!.toString().toLowerCase())
if (Ds3RequestClassificationUtil.isNotificationRequest(this)
&& includeInPath
&& (RequestConverterUtil.getNotificationType(this) == NotificationType.DELETE
|| RequestConverterUtil.getNotificationType(this) == NotificationType.GET)) {
builder.append("/\"").append(" + ").append(PATH_REQUEST_REFERENCE).append(".NotificationId")
} else if (Ds3RequestUtils.hasBucketNameInPath(this)) {
builder.append("/\"").append(" + ").append(PATH_REQUEST_REFERENCE).append(".BucketName")
} else if (this.isGoResourceAnArg()) {
val resourceArg = this.getGoArgFromResource()
builder.append("/\"").append(" + ").append(PATH_REQUEST_REFERENCE)
.append(".").append(resourceArg.name.capitalize())
} else {
builder.append("\"")
}
return builder.toString()
}
/**
* Creates the Go code for transforming a variable to string based on its Go type.
* Requires that the specified Go type is a non-pointer variable or an interface.
* This is used to convert required parameters into query parameters within the
* Go client code.
*/
fun goQueryParamToString(name: String, goType: String): String {
return when (goType) {
"*int", "*int64", "*bool", "*float64", "*string" ->
throw IllegalArgumentException("Expected Go variable to be a non-pointer or an interface, but was '$goType'")
"" -> "\"\"" // Denotes void parameter in contract
"bool" -> "strconv.FormatBool(request.$name)"
"int" -> "strconv.Itoa(request.$name)"
"int64" -> "strconv.FormatInt(request.$name, 10)"
"float64" -> "strconv.FormatFloat(request.$name, 'f', -1, 64)"
"string" -> "request.$name"
else -> "request.$name.String()"
}
}
/**
* Creates the Go code for transforming a variable pointer to a string pointer based on its Go type.
* Go code does not assume that it is safe to access pointer values. This is used to convert
* optional request parameters into query parameters within the Go client code.
*/
fun goPtrQueryParamToStringPtr(name: String, goType: String): String {
return when (goType) {
"", "int", "bool", "int64", "float64", "string" ->
throw IllegalArgumentException("Expected Go variable to be a pointer or an interface, but was '$goType'")
"*int" -> "networking.IntPtrToStrPtr(request.$name)"
"*int64" -> "networking.Int64PtrToStrPtr(request.$name)"
"*bool" -> "networking.BoolPtrToStrPtr(request.$name)"
"*float64" -> "networking.Float64PtrToStrPtr(request.$name)"
"*string" -> "request.$name"
else -> "networking.InterfaceToStrPtr(request.$name)"
}
} | apache-2.0 | 1c9d2554119e9ef97cdbae3708f615bf | 41.820313 | 121 | 0.668248 | 4.23493 | false | false | false | false |
06needhamt/Neuroph-Intellij-Plugin | neuroph-plugin/src/com/thomas/needham/neurophidea/actions/InitialisationAction.kt | 1 | 2023 | /* The MIT License (MIT)
Copyright (c) 2016 Tom Needham
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.thomas.needham.neurophidea.actions
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
/**
* Created by Thomas Needham on 24/05/2016.
*
* Initial action that is performed when the plugin is loaded on IDE startup
* or enabled manually by the user.
*/
class InitialisationAction : AnAction {
companion object ProjectInfo {
var project: Project? = null
var projectDirectory: String? = ""
var isOpen: Boolean? = false
}
constructor() {
}
constructor(text: String?) : super(text) {
}
/**
* Function called when the plugin has been successfully initialised
* @param p0 The action event that fired the action
*/
override fun actionPerformed(p0: AnActionEvent) {
// Setup the Plugin and load the project
project = p0.project
projectDirectory = project?.basePath
isOpen = project?.isOpen
}
} | mit | 03238750e7bbccc8fb8945d74c88fee6 | 32.180328 | 78 | 0.770143 | 4.350538 | false | false | false | false |
yh-kim/gachi-android | Gachi/app/src/main/kotlin/com/pickth/gachi/view/signup/fragment/AgeAddFragment.kt | 1 | 3778 | /*
* Copyright 2017 Yonghoon Kim
*
* 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.pickth.gachi.view.signup.fragment
import android.os.Bundle
import android.text.InputType
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.pickth.gachi.R
import com.pickth.gachi.base.BaseAddInfoFragment
import com.pickth.gachi.net.service.UserService
import com.pickth.gachi.util.UserInfoManager
import kotlinx.android.synthetic.main.fragment_signup_add_text.view.*
import okhttp3.ResponseBody
import org.jetbrains.anko.toast
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class AgeAddFragment : BaseAddInfoFragment() {
companion object {
val PAGE_INDEX = 1
private val mInstance = AgeAddFragment()
fun getInstance(): AgeAddFragment = mInstance
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val rootView = inflater!!.inflate(R.layout.fragment_signup_add_text, container, false)
rootView.tv_add_info_title.text = resources.getStringArray(R.array.add_info_title)[PAGE_INDEX]
rootView.et_add_info_input.run {
hint = "22"
inputType = (InputType.TYPE_CLASS_NUMBER)
}
rootView.tv_add_info_explanation.text = "연령대로 표시됩니다"
return rootView
}
override fun clickNextButton(isSkip: Boolean) {
Log.d(TAG, "click next button, isSkip: $isSkip")
if(isSkip) {
mListener?.onChange()
return
}
val textAge = view!!.et_add_info_input.text.toString()
if(textAge.length == 0) {
activity.toast("올바른 값을 입력해주세요")
return
}
val input = textAge.toInt()
if(input*1 == 0) {
activity.toast("올바른 값을 입력해주세요")
return
}
initialUserInfo(input)
}
fun initialUserInfo(input: Int) {
Log.d(TAG, "initialUserInfo, age input: $input")
var map = HashMap<String, String>()
map.set("age", input.toString())
UserService()
.initialUserInfo(UserInfoManager.firebaseUserToken, UserInfoManager.getUser(context)?.uid!!, NicknameAddFragment.PAGE_INDEX + 1, map)
.enqueue(object : Callback<ResponseBody> {
override fun onResponse(call: Call<ResponseBody>?, response: Response<ResponseBody>) {
Log.d(TAG, "initialUserInfo onResponse, code: ${response.code()}")
if (response.code() == 200) {
UserInfoManager.getUser(context)?.age = input
UserInfoManager.notifyDataSetChanged(context)
Log.d(TAG, "user info: ${UserInfoManager.getUser(context).toString()}")
mListener?.onChange()
}
}
override fun onFailure(call: Call<ResponseBody>?, t: Throwable?) {
Log.d(TAG, "initialUserInfo on Failure ${t?.printStackTrace()}")
}
})
}
} | apache-2.0 | 68aef97fa9294707394b0a37bae04054 | 33.100917 | 149 | 0.630786 | 4.331002 | false | false | false | false |
yh-kim/gachi-android | Gachi/app/src/main/kotlin/com/pickth/gachi/view/gachi/GachiDetailActivity.kt | 1 | 5254 | /*
* Copyright 2017 Yonghoon Kim
*
* 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.pickth.gachi.view.gachi
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.MenuItem
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.pickth.gachi.R
import com.pickth.gachi.base.BaseActivity
import com.pickth.gachi.net.service.GachiService
import com.pickth.gachi.util.MyDividerItemDecoration
import com.pickth.gachi.view.chat.Participant
import kotlinx.android.synthetic.main.activity_gachi_detail.*
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class GachiDetailActivity: BaseActivity() {
private lateinit var mParticipantAdapter: GachiDetailParticipantAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_gachi_detail)
// actionbar
setSupportActionBar(gachi_toolbar)
supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_back)
supportActionBar?.setDisplayShowTitleEnabled(false)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
mParticipantAdapter = GachiDetailParticipantAdapter()
rv_gachi_participant_list.run {
layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
adapter = mParticipantAdapter
addItemDecoration(MyDividerItemDecoration(context, LinearLayoutManager.HORIZONTAL, 10, false))
}
getGachiInfo()
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when(item?.itemId) {
android.R.id.home -> {
finish()
}
}
return super.onOptionsItemSelected(item)
}
fun getLid(): String = intent.getStringExtra("lid")
fun getGachiInfo() {
GachiService()
.getGachiInfo(getLid())
.enqueue(object: Callback<ResponseBody> {
override fun onResponse(call: Call<ResponseBody>?, response: Response<ResponseBody>) {
Log.d(TAG, "getGachiInfo onResponse, code: ${response.code()}")
if(response.code() != 200) return
val json = JSONObject(response.body()?.string())
Log.d(TAG, "getGachiInfo onResponse, json: ${json}")
// get info
var title = json.getString("detail")
var maxNum = json.getInt("max_follower")
// get member
var members = json.getJSONArray("member")
for(i in 0..members.length() - 1) {
var member = members.getJSONObject(i)
var memberUid = member.getString("uid")
var memberNickname = member.getString("nickname")
var memberProfile = member.getString("profile_image")
// bind
mParticipantAdapter.addItem(Participant(memberUid, memberNickname, memberProfile))
}
// get leader
val leader = json.getJSONObject("leader")
var uid = leader.getString("uid")
var nickname = leader.getString("nickname")
var profile = leader.getString("profile_image")
// bind
if(title == "null") title = "no title"
tv_gachi_title.text = title
tv_gachi_maxNum.text = "${maxNum}명 모집 중"
if(profile == "") {
Glide.with(applicationContext)
.load(R.drawable.test)
.apply(RequestOptions().circleCrop())
.into(iv_gachi_leader_profile)
} else {
Glide.with(applicationContext)
.load(profile)
.apply(RequestOptions().circleCrop())
.into(iv_gachi_leader_profile)
}
tv_gachi_leader_nickname.text = nickname
tv_gachi_leader_info.text = "지역 없음\n20대 중반"
}
override fun onFailure(call: Call<ResponseBody>?, t: Throwable?) {
}
})
}
} | apache-2.0 | 41f69d8afe65116ecedd998d11c447ce | 39.253846 | 110 | 0.57091 | 5.226773 | false | false | false | false |
stoman/competitive-programming | problems/2021adventofcode18a/submissions/accepted/Stefan.kt | 2 | 5328 | import java.util.*
abstract class SnailfishNumber(var parent: SnailfishPair?) {
abstract fun encodingLength(): Int
abstract fun magnitude(): Long
abstract fun copy(): SnailfishNumber
abstract fun addToLeftmostValue(summand: Long)
abstract fun addToRightmostValue(summand: Long)
abstract fun explode(depth: Int = 0): Boolean
abstract fun split(): Boolean
fun reduce() {
do {
var didSomething = explode()
if (!didSomething) {
didSomething = split()
}
} while (didSomething)
}
operator fun plus(other: SnailfishNumber): SnailfishNumber {
require(parent == null && other.parent == null)
val sum = SnailfishPair(null, copy(), other.copy())
sum.left.parent = sum
sum.right.parent = sum
sum.reduce()
return sum
}
companion object {
fun read(input: String): SnailfishNumber {
if (input[0] != '[') {
return SnailfishLiteral(null, input[0].digitToInt().toLong())
}
val left = read(input.drop(1))
require(input[1 + left.encodingLength()] == ',')
val right = read(input.drop(2 + left.encodingLength()))
require(input[2 + left.encodingLength() + right.encodingLength()] == ']')
val pair = SnailfishPair(null, left, right)
left.parent = pair
right.parent = pair
return pair
}
}
}
class SnailfishPair(parent: SnailfishPair?, var left: SnailfishNumber, var right: SnailfishNumber) :
SnailfishNumber(parent) {
override fun encodingLength(): Int = 3 + left.encodingLength() + right.encodingLength()
override fun magnitude(): Long = 3 * left.magnitude() + 2 * right.magnitude()
override fun copy(): SnailfishNumber {
val c = SnailfishPair(parent, left.copy(), right.copy())
c.left.parent = c
c.right.parent = c
return c
}
override fun addToLeftmostValue(summand: Long) {
left.addToLeftmostValue(summand)
}
override fun addToRightmostValue(summand: Long) {
right.addToRightmostValue(summand)
}
private fun addToUpwardsThenLeftmostValue(summand: Long) {
val parentNonNull = parent ?: return
if (parentNonNull.right == this) {
parentNonNull.addToUpwardsThenLeftmostValue(summand)
} else
parentNonNull.right.addToLeftmostValue(summand)
}
private fun addToUpwardsThenRightmostValue(summand: Long) {
val parentNonNull = parent ?: return
if (parentNonNull.left == this) {
parentNonNull.addToUpwardsThenRightmostValue(summand)
} else
parentNonNull.left.addToRightmostValue(summand)
}
override fun toString(): String = "[$left,$right]"
override fun explode(depth: Int): Boolean {
if (depth >= 3) {
if (left is SnailfishPair) {
val leftAsSnailfishPair = left as SnailfishPair
require(leftAsSnailfishPair.left is SnailfishLiteral && leftAsSnailfishPair.right is SnailfishLiteral)
addToUpwardsThenRightmostValue((leftAsSnailfishPair.left as SnailfishLiteral).value)
right.addToLeftmostValue((leftAsSnailfishPair.right as SnailfishLiteral).value)
left = SnailfishLiteral(this, 0)
return true
}
if (right is SnailfishPair) {
val rightAsSnailfishPair = right as SnailfishPair
require(rightAsSnailfishPair.left is SnailfishLiteral && rightAsSnailfishPair.right is SnailfishLiteral)
left.addToRightmostValue((rightAsSnailfishPair.left as SnailfishLiteral).value)
addToUpwardsThenLeftmostValue((rightAsSnailfishPair.right as SnailfishLiteral).value)
right = SnailfishLiteral(this, 0)
return true
}
}
if (left.explode(depth + 1)) {
return true
}
return right.explode(depth + 1)
}
override fun split(): Boolean {
if (left is SnailfishLiteral) {
val leftAsSnailfishLiteral = left as SnailfishLiteral
if (leftAsSnailfishLiteral.value >= 10) {
left = fromValue(this, leftAsSnailfishLiteral.value)
return true
}
}
if (left.split()) {
return true
}
if (right is SnailfishLiteral) {
val rightAsSnailfishLiteral = right as SnailfishLiteral
if (rightAsSnailfishLiteral.value >= 10) {
right = fromValue(this, rightAsSnailfishLiteral.value)
return true
}
}
return right.split()
}
companion object {
fun fromValue(parent: SnailfishPair, value: Long): SnailfishPair {
val ret = SnailfishPair(parent, SnailfishLiteral(null, value / 2), SnailfishLiteral(null, (value + 1) / 2))
ret.left.parent = ret
ret.right.parent = ret
return ret
}
}
}
class SnailfishLiteral(parent: SnailfishPair?, var value: Long) : SnailfishNumber(parent) {
override fun encodingLength(): Int = 1
override fun magnitude(): Long = value
override fun copy(): SnailfishNumber = SnailfishLiteral(parent, value)
override fun addToLeftmostValue(summand: Long) {
value += summand
}
override fun addToRightmostValue(summand: Long) {
value += summand
}
override fun toString(): String = value.toString()
override fun explode(depth: Int): Boolean = false
override fun split(): Boolean = false
}
@ExperimentalStdlibApi
fun main() {
val s = Scanner(System.`in`)
println(buildList {
while (s.hasNext()) {
add(SnailfishNumber.read(s.next()))
}
}.reduce(SnailfishNumber::plus).magnitude())
}
| mit | e7e94438206d81ccf179ffe4a3a6e963 | 28.932584 | 113 | 0.678491 | 3.794872 | false | false | false | false |
samtstern/quickstart-android | database/app/src/main/java/com/google/firebase/quickstart/database/kotlin/SignInActivity.kt | 1 | 4815 | package com.google.firebase.quickstart.database.kotlin
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.ktx.auth
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import com.google.firebase.quickstart.database.R
import com.google.firebase.quickstart.database.databinding.ActivitySignInBinding
import com.google.firebase.quickstart.database.kotlin.models.User
class SignInActivity : BaseActivity(), View.OnClickListener {
private lateinit var database: DatabaseReference
private lateinit var auth: FirebaseAuth
private lateinit var binding: ActivitySignInBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySignInBinding.inflate(layoutInflater)
setContentView(binding.root)
database = Firebase.database.reference
auth = Firebase.auth
setProgressBar(R.id.progressBar)
// Click listeners
with(binding) {
buttonSignIn.setOnClickListener(this@SignInActivity)
buttonSignUp.setOnClickListener(this@SignInActivity)
}
}
public override fun onStart() {
super.onStart()
// Check auth on Activity start
auth.currentUser?.let {
onAuthSuccess(it)
}
}
private fun signIn() {
Log.d(TAG, "signIn")
if (!validateForm()) {
return
}
showProgressBar()
val email = binding.fieldEmail.text.toString()
val password = binding.fieldPassword.text.toString()
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
Log.d(TAG, "signIn:onComplete:" + task.isSuccessful)
hideProgressBar()
if (task.isSuccessful) {
onAuthSuccess(task.result?.user!!)
} else {
Toast.makeText(baseContext, "Sign In Failed",
Toast.LENGTH_SHORT).show()
}
}
}
private fun signUp() {
Log.d(TAG, "signUp")
if (!validateForm()) {
return
}
showProgressBar()
val email = binding.fieldEmail.text.toString()
val password = binding.fieldPassword.text.toString()
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
Log.d(TAG, "createUser:onComplete:" + task.isSuccessful)
hideProgressBar()
if (task.isSuccessful) {
onAuthSuccess(task.result?.user!!)
} else {
Toast.makeText(baseContext, "Sign Up Failed",
Toast.LENGTH_SHORT).show()
}
}
}
private fun onAuthSuccess(user: FirebaseUser) {
val username = usernameFromEmail(user.email!!)
// Write new user
writeNewUser(user.uid, username, user.email)
// Go to MainActivity
startActivity(Intent(this@SignInActivity, MainActivity::class.java))
finish()
}
private fun usernameFromEmail(email: String): String {
return if (email.contains("@")) {
email.split("@".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0]
} else {
email
}
}
private fun validateForm(): Boolean {
var result = true
if (TextUtils.isEmpty(binding.fieldEmail.text.toString())) {
binding.fieldEmail.error = "Required"
result = false
} else {
binding.fieldEmail.error = null
}
if (TextUtils.isEmpty(binding.fieldPassword.text.toString())) {
binding.fieldPassword.error = "Required"
result = false
} else {
binding.fieldPassword.error = null
}
return result
}
// [START basic_write]
private fun writeNewUser(userId: String, name: String, email: String?) {
val user = User(name, email)
database.child("users").child(userId).setValue(user)
}
// [END basic_write]
override fun onClick(v: View) {
val i = v.id
if (i == R.id.buttonSignIn) {
signIn()
} else if (i == R.id.buttonSignUp) {
signUp()
}
}
companion object {
private const val TAG = "SignInActivity"
}
}
| apache-2.0 | 85eeadf43d2747b815a033222f1a6ba1 | 29.66879 | 87 | 0.595223 | 4.853831 | false | false | false | false |
Ztiany/Repository | Kotlin/Kotlin-Coroutines/src/main/kotlin/core/concurrency/03_ThreadSafeDataStructures.kt | 2 | 1548 | package core.concurrency
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.util.concurrent.atomic.AtomicInteger
import kotlin.system.measureTimeMillis
/*
一种对线程、协程都有效的常规解决方法,就是使用线程安全(也称为同步的、 可线性化、原子)的数据结构,它为需要在共享状态上执行的相应操作提供所有必需的同步处理。
在简单的计数器场景中,我们可以使用具有 incrementAndGet 原子操作的 AtomicInteger 类:
这是针对此类特定问题的最快解决方案。它适用于普通计数器、集合、队列和其他标准数据结构以及它们的基本操作。
然而,它并不容易被扩展来应对复杂状态、或一些没有现成的线程安全实现的复杂操作。
*/
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")
}
private var counter = AtomicInteger()
fun main() = runBlocking<Unit> {
//sampleStart
GlobalScope.massiveRun {
counter.incrementAndGet()
}
println("Counter = ${counter.get()}")
//sampleEnd
} | apache-2.0 | c1efe988f421b3ed636b2c12d1a658d7 | 27.975 | 79 | 0.708981 | 3.234637 | false | false | false | false |
vondear/RxTools | RxUI/src/main/java/com/tamsiree/rxui/view/TBlurView.kt | 1 | 2920 | package com.tamsiree.rxui.view
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.AttributeSet
import android.widget.ImageView
import androidx.annotation.IntRange
import androidx.appcompat.widget.AppCompatImageView
import com.tamsiree.rxkit.RxAnimationTool.startSwitchBackgroundAnim
import com.tamsiree.rxkit.TBlurTool
import com.tamsiree.rxkit.TBlurTool.getBlurBitmap
import com.tamsiree.rxui.R
/**
* @ClassName TBlurImageView
* @Description TODO
* @Author tamsiree
* @Date 20-3-26 下午2:32
* @Version 1.0
*/
class TBlurView : AppCompatImageView {
private lateinit var mImageView: ImageView
private var mBlurRunnable: Runnable? = null
/**
* 模糊度 (0...25f)
*/
@SuppressLint("SupportAnnotationUsage")
@IntRange(from = 0, to = 25)
var blurRadius = 15f
//模糊View引用的资源ID
var blurSrc = 0
/**
* 单位是 ms 毫秒
*/
var delayTime: Long = 200
private lateinit var mContext: Context
constructor(context: Context) : super(context) {
initView(context, null)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
initView(context, attrs)
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
initView(context, attrs)
}
private fun initView(context: Context, attrs: AttributeSet?) {
mContext = context
mImageView = this
mImageView.scaleType = ScaleType.CENTER_CROP
//获得这个控件对应的属性。
val a = context.obtainStyledAttributes(attrs, R.styleable.TBlurView)
try {
//模糊View
blurSrc = a.getResourceId(R.styleable.TBlurView_blurSrc, R.drawable.icon_placeholder)
blurRadius = a.getInteger(R.styleable.TBlurView_blurRadius, 15).toFloat()
delayTime = a.getInteger(R.styleable.TBlurView_blurDelayTime, 200).toLong()
} finally {
//回收这个对象
a.recycle()
}
if (isInEditMode) {
val bitmap = BitmapFactory.decodeResource(mContext.resources, blurSrc)
mImageView.setImageBitmap(TBlurTool.stackBlur(bitmap, blurRadius.toInt(), true))
} else {
notifyChange(blurSrc)
}
}
fun notifyChange(resId: Int) {
blurSrc = resId
removeCallbacks(mBlurRunnable)
mBlurRunnable = Runnable { setBlurImage() }
postDelayed(mBlurRunnable, delayTime)
}
private fun generateBlurImage(): Bitmap {
val bitmap = BitmapFactory.decodeResource(mContext.resources, blurSrc)
return getBlurBitmap(mContext, bitmap, blurRadius)
}
private fun setBlurImage() {
startSwitchBackgroundAnim(mImageView, generateBlurImage())
}
} | apache-2.0 | 1241af4b2887d1942de89c1797399b7c | 28.968421 | 114 | 0.677793 | 4.286145 | false | false | false | false |
AndroidX/androidx | wear/watchface/watchface-complications-rendering/src/main/java/androidx/wear/watchface/complications/rendering/ComplicationStyle.kt | 3 | 13047 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.watchface.complications.rendering
import android.graphics.Color
import android.graphics.ColorFilter
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import androidx.annotation.ColorInt
import androidx.annotation.IntDef
import androidx.annotation.Px
import androidx.annotation.RestrictTo
import androidx.wear.watchface.complications.data.SmallImageType
/**
* Defines attributes to customize appearance of rendered [ ].
*/
public class ComplicationStyle {
/**
* Constants used to define border styles for complicationSlots.
*
* @hide
*/
@Retention(AnnotationRetention.SOURCE)
@IntDef(BORDER_STYLE_NONE, BORDER_STYLE_SOLID, BORDER_STYLE_DASHED)
@RestrictTo(
RestrictTo.Scope.LIBRARY_GROUP
)
public annotation class BorderStyle
/** The background color to be used. */
@ColorInt
public var backgroundColor: Int = BACKGROUND_COLOR_DEFAULT
@ColorInt get() = field
set(@ColorInt backgroundColor: Int) { field = backgroundColor }
/** The background drawable to be used, or null if there's no background drawable. */
public var backgroundDrawable: Drawable? = null
/**
* The color to render the text with. Text color is used for rendering short text and long
* text fields.
*/
@ColorInt
public var textColor: Int = PRIMARY_COLOR_DEFAULT
@ColorInt get() = field
set(@ColorInt textColor: Int) { field = textColor }
/**
* The color to render the title with. Title color is used for rendering short title and long
* title fields.
*/
@ColorInt
public var titleColor: Int = SECONDARY_COLOR_DEFAULT
@ColorInt get() = field
set(@ColorInt titleColor: Int) { field = titleColor }
/** The typeface to be used for short and long text. */
public var textTypeface: Typeface = TYPEFACE_DEFAULT
private set
/** The typeface to be used for short and long title. */
public var titleTypeface: Typeface = TYPEFACE_DEFAULT
private set
@Px
private var mTextSize = TEXT_SIZE_DEFAULT
@Px
private var mTitleSize = TEXT_SIZE_DEFAULT
private var mImageColorFilter: ColorFilter? = null
@ColorInt
private var mIconColor = PRIMARY_COLOR_DEFAULT
@ColorInt
private var mBorderColor = BORDER_COLOR_DEFAULT
@BorderStyle
private var mBorderStyle = BORDER_STYLE_SOLID
@Px
private var mBorderDashWidth = DASH_WIDTH_DEFAULT
@Px
private var mBorderDashGap = DASH_GAP_DEFAULT
@Px
private var mBorderRadius = BORDER_RADIUS_DEFAULT
@Px
private var mBorderWidth = BORDER_WIDTH_DEFAULT
@Px
private var mRangedValueRingWidth = RING_WIDTH_DEFAULT
@ColorInt
private var mRangedValuePrimaryColor = PRIMARY_COLOR_DEFAULT
@ColorInt
private var mRangedValueSecondaryColor = SECONDARY_COLOR_DEFAULT
@ColorInt
private var mHighlightColor = HIGHLIGHT_COLOR_DEFAULT
@get:JvmName(name = "isDirty")
internal var isDirty: Boolean = true
private set
public constructor()
public constructor(style: ComplicationStyle) {
backgroundColor = style.backgroundColor
backgroundDrawable = style.backgroundDrawable
textColor = style.textColor
titleColor = style.titleColor
textTypeface = style.textTypeface
titleTypeface = style.titleTypeface
mTextSize = style.textSize
mTitleSize = style.titleSize
mImageColorFilter = style.imageColorFilter
mIconColor = style.iconColor
mBorderColor = style.borderColor
mBorderStyle = style.borderStyle
mBorderDashWidth = style.borderDashWidth
mBorderDashGap = style.borderDashGap
mBorderRadius = style.borderRadius
mBorderWidth = style.borderWidth
mRangedValueRingWidth = style.rangedValueRingWidth
mRangedValuePrimaryColor = style.rangedValuePrimaryColor
mRangedValueSecondaryColor = style.rangedValueSecondaryColor
mHighlightColor = style.highlightColor
}
@JvmName(name = "clearDirtyFlag")
internal fun clearDirtyFlag() {
isDirty = false
}
/**
* The color filter used in active mode when rendering large images and small images
* with style [SmallImageType.PHOTO].
*/
public var imageColorFilter: ColorFilter?
get() = mImageColorFilter
set(colorFilter) {
mImageColorFilter = colorFilter
isDirty = true
}
/** The color for tinting icons. */
public var iconColor: Int
@ColorInt get() = mIconColor
set(@ColorInt iconColor) {
mIconColor = iconColor
isDirty = true
}
/** Returns the text size to be used for short and long text fields. */
public var textSize: Int
@Px get() = mTextSize
set(@Px textSize) {
mTextSize = textSize
isDirty = true
}
/** The text size to be used for short and long title fields. */
public var titleSize: Int
@Px get() = mTitleSize
set(@Px titleSize) {
mTitleSize = titleSize
isDirty = true
}
/**
* The color to render the complication border with.
*/
public var borderColor: Int
@ColorInt get() = mBorderColor
set(@ColorInt borderColor) {
mBorderColor = borderColor
isDirty = true
}
/**
* The style to render the complication border with.
*/
public var borderStyle: Int
@BorderStyle get() = mBorderStyle
set(@BorderStyle borderStyle) {
mBorderStyle = when (borderStyle) {
BORDER_STYLE_SOLID -> BORDER_STYLE_SOLID
BORDER_STYLE_DASHED -> BORDER_STYLE_DASHED
else -> BORDER_STYLE_NONE
}
isDirty = true
}
/** The dash width to be used when drawing borders of type [.BORDER_STYLE_DASHED]. */
public var borderDashWidth: Int
@Px get() = mBorderDashWidth
set(@Px borderDashWidth) {
mBorderDashWidth = borderDashWidth
isDirty = true
}
/**
* The dash gap to be used when drawing borders of type [.BORDER_STYLE_DASHED].
*/
public var borderDashGap: Int
@Px get() = mBorderDashGap
set(@Px borderDashGap) {
mBorderDashGap = borderDashGap
isDirty = true
}
/**
* The border radius to be applied to the corners of the bounds of the complication in
* active mode. Border radius will be limited to the half of width or height, depending
* on which one is smaller. If [ComplicationStyle.BORDER_RADIUS_DEFAULT] is returned, border
* radius should be reduced to half of the minimum of width or height during the rendering.
*/
public var borderRadius: Int
@Px get() = mBorderRadius
set(@Px borderRadius) {
mBorderRadius = borderRadius
isDirty = true
}
/**
* The width to render the complication border with.
*/
public var borderWidth: Int
@Px get() = mBorderWidth
set(@Px borderWidth) {
mBorderWidth = borderWidth
isDirty = true
}
/** The ring width to be used when rendering ranged value indicator. */
public var rangedValueRingWidth: Int
@Px get() = mRangedValueRingWidth
set(@Px rangedValueRingWidth) {
mRangedValueRingWidth = rangedValueRingWidth
isDirty = true
}
/** The color to be used when rendering first part of ranged value indicator. */
public var rangedValuePrimaryColor: Int
@ColorInt get() = mRangedValuePrimaryColor
set(@ColorInt rangedValuePrimaryColor) {
mRangedValuePrimaryColor = rangedValuePrimaryColor
isDirty = true
}
/** The color to be used when rendering second part of ranged value indicator. */
public var rangedValueSecondaryColor: Int
@ColorInt get() = mRangedValueSecondaryColor
set(@ColorInt rangedValueSecondaryColor) {
mRangedValueSecondaryColor = rangedValueSecondaryColor
isDirty = true
}
/** The highlight color to be used when the complication is highlighted. */
public var highlightColor: Int
@ColorInt get() = mHighlightColor
set(@ColorInt highlightColor) {
mHighlightColor = highlightColor
isDirty = true
}
/**
* Sets [Typeface] to use when rendering short text and long text fields.
*
* @param textTypeface The [Typeface] to render the text with
*/
public fun setTextTypeface(textTypeface: Typeface) {
this.textTypeface = textTypeface
isDirty = true
}
/**
* Sets the [Typeface] to render the title for short and long text with.
*
* @param titleTypeface The [Typeface] to render the title with
*/
public fun setTitleTypeface(titleTypeface: Typeface) {
this.titleTypeface = titleTypeface
isDirty = true
}
/**
* Returns a copy of the ComplicationStyle [tint]ed by [tintColor].
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
fun asTinted(tintColor: Int): ComplicationStyle = ComplicationStyle(this).apply {
backgroundColor = tint(backgroundColor, tintColor)
borderColor = tint(borderColor, tintColor)
highlightColor = tint(highlightColor, tintColor)
iconColor = tint(iconColor, tintColor)
rangedValuePrimaryColor = tint(rangedValuePrimaryColor, tintColor)
rangedValueSecondaryColor = tint(rangedValueSecondaryColor, tintColor)
textColor = tint(textColor, tintColor)
titleColor = tint(titleColor, tintColor)
}
public companion object {
/** Style where the borders are not drawn. */
public const val BORDER_STYLE_NONE: Int = 0
/** Style where the borders are drawn without any gap. */
public const val BORDER_STYLE_SOLID: Int = 1
/**
* Style where the borders are drawn as dashed lines. If this is set as current border
* style, dash width and dash gap should also be set via [.setBorderDashWidth],
* [.setBorderDashGap] or XML attributes, or default values will be used.
*/
public const val BORDER_STYLE_DASHED: Int = 2
/** Default primary color. */
private const val PRIMARY_COLOR_DEFAULT = Color.WHITE
/** Default secondary color. */
private const val SECONDARY_COLOR_DEFAULT = Color.LTGRAY
/** Default background color. */
private const val BACKGROUND_COLOR_DEFAULT = Color.BLACK
/** Default background color. */
private const val HIGHLIGHT_COLOR_DEFAULT = Color.LTGRAY
/** Default border color. */
private const val BORDER_COLOR_DEFAULT = Color.WHITE
/** Default text size. */
@Px
private const val TEXT_SIZE_DEFAULT = Int.MAX_VALUE
/** Default typeface. */
private val TYPEFACE_DEFAULT =
Typeface.create("sans-serif-condensed", Typeface.NORMAL)
/** Default dash width. */
@Px
private const val DASH_WIDTH_DEFAULT = 3
/** Default dash gap. */
@Px
private const val DASH_GAP_DEFAULT = 3
/** Default border width. */
@Px
private const val BORDER_WIDTH_DEFAULT = 1
/** Default ring width. */
@Px
private const val RING_WIDTH_DEFAULT = 2
/** Default border radius. */
@Px
public const val BORDER_RADIUS_DEFAULT: Int = Int.MAX_VALUE
/** Computes the luminance of [color] and applies that to [tint]. */
internal fun tint(color: Int, tint: Int): Int {
// See https://en.wikipedia.org/wiki/Relative_luminance
val luminance = (Color.red(color).toFloat() * (0.2126f / 255.0f)) +
(Color.green(color).toFloat() * (0.7152f / 255.0f)) +
(Color.blue(color).toFloat() * (0.0722f / 255.0f))
return Color.argb(
Color.alpha(color).toFloat() / 255.0f,
Color.red(tint) * luminance / 255.0f,
Color.green(tint) * luminance / 255.0f,
Color.blue(tint) * luminance / 255.0f
)
}
}
} | apache-2.0 | d4190778e205dd15f5193291363207e1 | 32.285714 | 97 | 0.639994 | 4.711809 | false | false | false | false |
Xenoage/Zong | utils-kotlin/src/com/xenoage/utils/document/io/FileFormat.kt | 1 | 1619 | package com.xenoage.utils.document.io
import com.xenoage.utils.document.Document
/**
* General information on a file format for a document.
*
*/
data class FileFormat<T : Document>(
/** The unique ID of the format, like "MP3" */
val id: String,
/** The name of the format, like "MPEG Audio Layer III" */
val name: String,
/* Gets the default extension, like ".mp3" or ".xml" */
val defaultExtension: String,
/** Nore supported extensions, like ".mid" or ".xml" */
val otherExtensions: List<String> = emptyList(),
/** The reader for this file format, or null if unsupported */
val input: FileInput<T>? = null,
/** The writer for this file format, or null if unsupported */
val output: FileOutput<T>? = null) {
/** All supported extensions, like ".mid" or ".xml". */
val allExtensions: List<String>
get() = listOf(defaultExtension).plus(otherExtensions)
/** All supported extensions with a leading asterisk, like "*.mid" or "*.xml". */
val allExtensionsWithAsterisk: List<String>
get() = allExtensions.map { "*.$it" }
/**
* The file filter description of the format. By default, this
* is the name of the format with the default extensions and
* other extensions in parentheses, like "MPEG Audio Layer III (.mp3, .mpeg)".
*/
val filterDescription: String
get() = "$name (${allExtensions.map { ".$it" }.joinToString()})"
/** Returns a copy of this [FileFormat] with the given input and output class. */
fun withIO(input: FileInput<T>, output: FileOutput<T>): FileFormat<T> {
return FileFormat(id, name, defaultExtension, otherExtensions, input, output)
}
}
| agpl-3.0 | 09615d1ee3f764728636fcfc7f6a9d7a | 31.38 | 82 | 0.683138 | 3.597778 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/medialibrary/albums/CreateAlbum.kt | 2 | 2592 | package abi44_0_0.expo.modules.medialibrary.albums
import android.content.Context
import android.os.AsyncTask
import android.media.MediaScannerConnection
import android.net.Uri
import android.provider.MediaStore
import abi44_0_0.expo.modules.core.Promise
import abi44_0_0.expo.modules.core.utilities.ifNull
import abi44_0_0.expo.modules.medialibrary.ERROR_NO_ALBUM
import abi44_0_0.expo.modules.medialibrary.ERROR_UNABLE_TO_LOAD
import abi44_0_0.expo.modules.medialibrary.ERROR_UNABLE_TO_LOAD_PERMISSION
import abi44_0_0.expo.modules.medialibrary.ERROR_UNABLE_TO_SAVE
import abi44_0_0.expo.modules.medialibrary.MediaLibraryUtils
import java.io.File
import java.io.IOException
internal class CreateAlbum(
private val context: Context,
private val albumName: String,
private val assetId: String,
copyAsset: Boolean,
private val promise: Promise
) : AsyncTask<Void?, Void?, Void?>() {
private val mStrategy = if (copyAsset) AssetFileStrategy.copyStrategy else AssetFileStrategy.moveStrategy
private fun createAlbum(mimeType: String): File? {
val albumDir = MediaLibraryUtils.getEnvDirectoryForAssetType(mimeType, false)
.ifNull {
promise.reject(ERROR_NO_ALBUM, "Could not guess asset type.")
return null
}
val album = File(albumDir.path, albumName)
.takeIf { it.exists() || it.mkdirs() }
.ifNull {
promise.reject(ERROR_NO_ALBUM, "Could not create album directory.")
return null
}
return album
}
public override fun doInBackground(vararg params: Void?): Void? {
try {
val files = MediaLibraryUtils.getAssetsById(context, promise, assetId) ?: return null
val albumCreator = files[0]
val album = createAlbum(albumCreator.mimeType) ?: return null
val newFile = mStrategy.apply(albumCreator, album, context)
MediaScannerConnection.scanFile(
context,
arrayOf(newFile.path),
null
) { path: String, uri: Uri? ->
if (uri == null) {
promise.reject(ERROR_UNABLE_TO_SAVE, "Could not add image to album.")
return@scanFile
}
val selection = "${MediaStore.Images.Media.DATA}=?"
val args = arrayOf(path)
queryAlbum(context, selection, args, promise)
}
} catch (e: SecurityException) {
promise.reject(
ERROR_UNABLE_TO_LOAD_PERMISSION,
"Could not create album: need WRITE_EXTERNAL_STORAGE permission.", e
)
} catch (e: IOException) {
promise.reject(ERROR_UNABLE_TO_LOAD, "Could not read file or parse EXIF tags", e)
}
return null
}
}
| bsd-3-clause | 5b8198703624a5fd9c7b4d54bd94177d | 35 | 107 | 0.700231 | 3.874439 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/glitter/src/test/kotlin/com/teamwizardry/librarianlib/glitter/test/systems/PerfectBouncySystem.kt | 1 | 2632 | package com.teamwizardry.librarianlib.glitter.test.systems
import com.teamwizardry.librarianlib.glitter.bindings.ConstantBinding
import com.teamwizardry.librarianlib.glitter.modules.BasicPhysicsUpdateModule
import com.teamwizardry.librarianlib.glitter.modules.SpriteRenderModule
import com.teamwizardry.librarianlib.glitter.test.modules.VelocityRenderModule
import net.minecraft.entity.Entity
import net.minecraft.util.Identifier
object PerfectBouncySystem : TestSystem(Identifier("liblib-glitter-test:perfect_bouncy")) {
override fun configure() {
val position = bind(3)
val previousPosition = bind(3)
val velocity = bind(3)
val color = bind(4)
updateModules.add(
BasicPhysicsUpdateModule(
position = position,
previousPosition = previousPosition,
velocity = velocity,
enableCollision = true,
gravity = ConstantBinding(0.02),
bounciness = ConstantBinding(1.0),
friction = ConstantBinding(0.00),
damping = ConstantBinding(0.0)
)
)
renderModules.add(
SpriteRenderModule.build(
Identifier("minecraft", "textures/item/clay_ball.png"),
position,
)
.previousPosition(previousPosition)
.color(color)
.size(0.15)
.build()
)
renderModules.add(
VelocityRenderModule(
blend = true,
previousPosition = position,
position = position,
velocity = velocity,
color = color,
size = 1f,
alpha = null
)
)
}
override fun spawn(player: Entity) {
val eyePos = player.getCameraPosVec(1f)
val look = player.rotationVector
val spawnDistance = 2
val spawnVelocity = 0.2
this.addParticle(
200,
// position
eyePos.x + look.x * spawnDistance,
eyePos.y + look.y * spawnDistance,
eyePos.z + look.z * spawnDistance,
// previous position
eyePos.x + look.x * spawnDistance,
eyePos.y + look.y * spawnDistance,
eyePos.z + look.z * spawnDistance,
// velocity
look.x * spawnVelocity,
look.y * spawnVelocity,
look.z * spawnVelocity,
// color
Math.random(),
Math.random(),
Math.random(),
1.0
)
}
} | lgpl-3.0 | b71117c0bcb8a00aa5790c090cd4ec6f | 31.506173 | 91 | 0.552812 | 5.100775 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/annotator/fixes/ReplaceWithStdMemDropFixTest.kt | 3 | 7127 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator.fixes
import org.rust.ide.annotator.RsAnnotatorTestBase
import org.rust.ide.annotator.RsErrorAnnotator
class ReplaceWithStdMemDropFixTest : RsAnnotatorTestBase(RsErrorAnnotator::class) {
fun `test correct self type call expr`() = checkFixByText("Replace with `std::mem::drop`", """
struct X;
#[lang = "drop"]
pub trait Drop {
fn drop(&mut self);
}
impl Drop for X {
fn drop(&mut self) {}
}
fn main() {
let mut x = X {};
<error descr="Explicit calls to `drop` are forbidden. Use `std::mem::drop` instead [E0040]">X::drop/*caret*/</error>(&mut x);
}
""", """
struct X;
#[lang = "drop"]
pub trait Drop {
fn drop(&mut self);
}
impl Drop for X {
fn drop(&mut self) {}
}
fn main() {
let mut x = X {};
std::mem::drop(x);
}
""")
fun `test incorrect self type call expr`() = checkFixByText("Replace with `std::mem::drop`", """
struct X;
#[lang = "drop"]
pub trait Drop {
fn drop(&mut self);
}
impl Drop for X {
fn drop(&mut self) {}
}
fn main() {
let mut x = X {};
<error descr="Explicit calls to `drop` are forbidden. Use `std::mem::drop` instead [E0040]">X::drop/*caret*/</error>(&mut x, 123, "foo");
}
""", """
struct X;
#[lang = "drop"]
pub trait Drop {
fn drop(&mut self);
}
impl Drop for X {
fn drop(&mut self) {}
}
fn main() {
let mut x = X {};
std::mem::drop(&mut x, 123, "foo");
}
""")
fun `test correct Drop type call expr`() = checkFixByText("Replace with `std::mem::drop`", """
struct X;
#[lang = "drop"]
pub trait Drop {
fn drop(&mut self);
}
impl Drop for X {
fn drop(&mut self) {}
}
fn main() {
let mut x = X {};
<error descr="Explicit calls to `drop` are forbidden. Use `std::mem::drop` instead [E0040]">Drop::drop/*caret*/</error>(&mut x);
}
""", """
struct X;
#[lang = "drop"]
pub trait Drop {
fn drop(&mut self);
}
impl Drop for X {
fn drop(&mut self) {}
}
fn main() {
let mut x = X {};
std::mem::drop(x);
}
""")
fun `test incorrect Drop type call expr`() = checkFixByText("Replace with `std::mem::drop`", """
struct X;
#[lang = "drop"]
pub trait Drop {
fn drop(&mut self);
}
impl Drop for X {
fn drop(&mut self) {}
}
fn main() {
let mut x = X {};
<error descr="Explicit calls to `drop` are forbidden. Use `std::mem::drop` instead [E0040]">Drop::drop/*caret*/</error>(&mut x, 123, "foo");
}
""", """
struct X;
#[lang = "drop"]
pub trait Drop {
fn drop(&mut self);
}
impl Drop for X {
fn drop(&mut self) {}
}
fn main() {
let mut x = X {};
std::mem::drop(&mut x, 123, "foo");
}
""")
fun `test correct method call`() = checkFixByText("Replace with `std::mem::drop`", """
struct X;
#[lang = "drop"]
pub trait Drop {
fn drop(&mut self);
}
impl Drop for X {
fn drop(&mut self) {}
}
fn main() {
let mut x = X {};
x.<error descr="Explicit calls to `drop` are forbidden. Use `std::mem::drop` instead [E0040]">drop/*caret*/</error>();
}
""", """
struct X;
#[lang = "drop"]
pub trait Drop {
fn drop(&mut self);
}
impl Drop for X {
fn drop(&mut self) {}
}
fn main() {
let mut x = X {};
std::mem::drop(x);
}
""")
fun `test incorrect method call`() = checkFixByText("Replace with `std::mem::drop`", """
struct X;
#[lang = "drop"]
pub trait Drop {
fn drop(&mut self);
}
impl Drop for X {
fn drop(&mut self) {}
}
fn main() {
let mut x = X {};
x.<error descr="Explicit calls to `drop` are forbidden. Use `std::mem::drop` instead [E0040]">drop/*caret*/</error>(123, "foo");
}
""", """
struct X;
#[lang = "drop"]
pub trait Drop {
fn drop(&mut self);
}
impl Drop for X {
fn drop(&mut self) {}
}
fn main() {
let mut x = X {};
std::mem::drop(x, 123, "foo");
}
""")
fun `test correct chain method call`() = checkFixByText("Replace with `std::mem::drop`", """
struct X;
#[lang = "drop"]
pub trait Drop {
fn drop(&mut self);
}
impl Drop for X {
fn drop(&mut self) {}
}
struct XFactory;
impl XFactory {
fn create_x(&self, foo: u32) -> X {
X {}
}
}
fn main() {
XFactory {}.create_x(123).<error descr="Explicit calls to `drop` are forbidden. Use `std::mem::drop` instead [E0040]">drop/*caret*/</error>();
}
""", """
struct X;
#[lang = "drop"]
pub trait Drop {
fn drop(&mut self);
}
impl Drop for X {
fn drop(&mut self) {}
}
struct XFactory;
impl XFactory {
fn create_x(&self, foo: u32) -> X {
X {}
}
}
fn main() {
std::mem::drop(XFactory {}.create_x(123));
}
""")
fun `test incorrect chain method call`() = checkFixByText("Replace with `std::mem::drop`", """
struct X;
#[lang = "drop"]
pub trait Drop {
fn drop(&mut self);
}
impl Drop for X {
fn drop(&mut self) {}
}
struct XFactory;
impl XFactory {
fn create_x(&self, foo: u32) -> X {
X {}
}
}
fn main() {
XFactory {}.create_x(123).<error descr="Explicit calls to `drop` are forbidden. Use `std::mem::drop` instead [E0040]">drop/*caret*/</error>(123, "foo");
}
""", """
struct X;
#[lang = "drop"]
pub trait Drop {
fn drop(&mut self);
}
impl Drop for X {
fn drop(&mut self) {}
}
struct XFactory;
impl XFactory {
fn create_x(&self, foo: u32) -> X {
X {}
}
}
fn main() {
std::mem::drop(XFactory {}.create_x(123), 123, "foo");
}
""")
}
| mit | d6b3331b35d60b4c5023b14221ef86f7 | 25.106227 | 164 | 0.431738 | 4.122036 | false | false | false | false |
androidx/androidx | benchmark/benchmark-darwin-gradle-plugin/src/main/kotlin/androidx/benchmark/darwin/gradle/RunDarwinBenchmarksTask.kt | 3 | 2996 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.benchmark.darwin.gradle
import javax.inject.Inject
import org.gradle.api.DefaultTask
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputDirectory
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import org.gradle.process.ExecOperations
@CacheableTask
abstract class RunDarwinBenchmarksTask @Inject constructor(
private val execOperations: ExecOperations
) : DefaultTask() {
@get:InputDirectory
@get:PathSensitive(PathSensitivity.RELATIVE)
abstract val xcodeProjectPath: DirectoryProperty
@get:Input
abstract val destination: Property<String>
@get:Input
abstract val scheme: Property<String>
@get:OutputDirectory
abstract val xcResultPath: DirectoryProperty
@TaskAction
fun runBenchmarks() {
requireXcodeBuild()
// Consider moving this into the shared instance of XCodeBuildService
// given that is a much cleaner way of sharing a single instance of a running simulator.
val simCtrl = XCodeSimCtrl(execOperations, destination.get())
val xcodeProject = xcodeProjectPath.get().asFile
val xcResultFile = xcResultPath.get().asFile
if (xcResultFile.exists()) {
xcResultFile.deleteRecursively()
}
simCtrl.start { destinationDesc ->
val args = listOf(
"xcodebuild",
"test",
"-project", xcodeProject.absolutePath.toString(),
"-scheme", scheme.get(),
"-destination", destinationDesc,
"-resultBundlePath", xcResultFile.absolutePath,
)
logger.info("Command : ${args.joinToString(" ")}")
execOperations.executeQuietly(args)
}
}
private fun requireXcodeBuild() {
val result = execOperations.exec { spec ->
spec.commandLine = listOf("which", "xcodebuild")
// Ignore exit value here to return a better exception message
spec.isIgnoreExitValue = true
}
require(result.exitValue == 0) {
"xcodebuild is missing on this machine."
}
}
}
| apache-2.0 | fbce890fbfea33a4280819a21c76eb5f | 34.666667 | 96 | 0.688585 | 4.666667 | false | false | false | false |
chiragbharadwaj/crypto | src/set1/xor/DetectXor.kt | 2 | 1176 | package set1.xor
import java.io.File
import set1.xor.SingleXor.score
/* Set 1, Challenge 4: A file containing hundreds of hex strings is provided. Exactly one of them has been ciphered
* using the single-character XOR cipher from Set 1, Challenge 3. Find the plain text of that ciphered string. */
object DetectXor {
/* detect(filename) detects which string is most likely to be the ciphered one by scoring each one and picking the
* one with the highest score overall in the file.
* Requires: [filename] is the fully-qualified name of a valid file which contains strings separated by newlines. Each
* string in the file consists of only hexadecimal characters, i.e. only [0-9] and [a-f] as constituents.
*/
fun detect(filename: String): String {
val bufferedReader = File(filename).bufferedReader()
val text = bufferedReader.use { it.readLines() } // Try-with-resources, Kotlin-style.
var max = 0
var result = ""
for (line in text) {
val (_, plain) = SingleXor.decrypt(line)
var score = plain.score()
if (score > max) {
max = score
result = plain
}
}
return result
}
} | gpl-2.0 | 1731048099899744b277d213d63d0ad2 | 34.666667 | 120 | 0.678571 | 3.959596 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/ide/intentions/MakeEncoderIntention.kt | 1 | 7374 | package org.elm.ide.intentions
import org.elm.lang.core.lookup.ElmLookup
import org.elm.lang.core.psi.ElmFile
import org.elm.lang.core.psi.elements.ElmTypeDeclaration
import org.elm.lang.core.types.*
class MakeEncoderIntention : AnnotationBasedGeneratorIntention() {
override fun getText() = "Generate Encoder"
override fun getRootIfApplicable(annotationTy: Ty): Ty? {
if (annotationTy !is TyFunction) return null
val param = annotationTy.parameters.singleOrNull() ?: return null
val ret = annotationTy.ret as? TyUnion ?: return null
if (ret.module != "Json.Encode" || ret.name != "Value") return null
return param
}
override fun generator(context: Context): TyFunctionGenerator {
return EncoderGenerator(context.file, context.ty, context.name)
}
}
private class EncoderGenerator(
file: ElmFile,
root: Ty,
private val functionName: String
) : TyFunctionGenerator(file, root) {
/** Counter used to prevent name collision of generated functions */
private var i = 1
override fun generateCode(): String {
// run gen on the root to kick off generation
val genBody = gen(root)
val rootFunc = funcsByTy[root]
funcsByTy.remove(root)
val param = rootFunc?.paramName ?: root.renderParam()
val body = rootFunc?.body ?: " $genBody $param"
return buildString {
append("\n$functionName $param =\n")
append(body)
for (f in funcsByTy.values) {
append("\n\n\n")
append("-- TODO: double-check generated code\n")
append("${f.name} : ${f.qualifier}${f.paramTy.renderedText()} -> ${qual("Value")}\n")
append("${f.name} ${f.paramName} =\n")
append(f.body)
}
}
}
/** Return a unary callable expression that will encode [ty] */
private fun gen(ty: Ty): String = when (ty) {
is TyRecord -> generateRecord(ty)
is TyUnion -> generateUnion(ty)
is TyVar -> "(\\_ -> Debug.todo \"Can't generate encoders for type variables\")"
is TyTuple -> generateTuple(ty)
is TyUnit -> "(\\_ -> ${qual("null")})"
is TyFunction, TyInProgressBinding, is MutableTyRecord, is TyUnknown -> {
"(\\_ -> Debug.todo \"Can't generate encoder for type ${ty.renderedText()}\")"
}
}
private fun generateUnion(ty: TyUnion): String = when {
ty.isTyInt -> qual("int")
ty.isTyFloat -> qual("float")
ty.isTyBool -> qual("bool")
ty.isTyString -> qual("string")
ty.isTyChar -> "(${qual("String", "fromChar")} >> ${qual("string")})"
ty.isTyList -> existing(ty) ?: "${qual("list")} ${gen(ty.parameters[0])}"
ty.module == "Set" && ty.name == "Set" -> existing(ty) ?: "${qual("set")} ${gen(ty.parameters[0])}"
ty.module == "Array" && ty.name == "Array" -> existing(ty)
?: "${qual("array")} ${gen(ty.parameters[0])}"
ty.module == "Maybe" && ty.name == "Maybe" -> generateMaybe(ty)
ty.module == "Dict" && ty.name == "Dict" -> generateDict(ty)
else -> generateUnionFunc(ty)
}
private fun generateUnionFunc(ty: TyUnion): String {
val cached = existing(ty) ?: funcsByTy[ty]?.name
if (cached != null) return cached
val renderedTy = ty.renderParam()
val decl: ElmTypeDeclaration? = ElmLookup.findFirstByNameAndModule(ty.name, ty.module, file)
val (param, body) = if (decl == null) {
renderedTy to "Debug.todo \"Can't generate encoder for ${ty.name}\""
} else {
unionsToExpose += ty.toRef()
val variants = decl.variantInference().value
val patternsAndExprs = variants.map { (variant, params) ->
val pattern = (listOf(variant) + params.map { it.renderParam() }).joinToString(" ")
val expr = when (params.size) {
0 -> "${qual("string")} \"$variant\""
1 -> "${gen(params[0])} ${params[0].renderParam()}"
else -> "Debug.todo \"Cannot generate encoder for variant with multiple parameters\""
}
pattern to expr
}
if (variants.size == 1) {
// For a single variant, we can pattern match it in the function parameter
"(${patternsAndExprs[0].first})" to " ${patternsAndExprs[0].second}"
} else {
// Otherwise we have to use a case expression
renderedTy to patternsAndExprs.joinToString("\n\n", prefix = " case $renderedTy of\n") { (pattern, expr) ->
"""
| $pattern ->
| $expr
""".trimMargin()
}
}
}
val name = "encode${ty.alias?.let { funcNames[it.toRef()] } ?: ty.name}"
val func = GeneratedFunction(name = name, paramTy = ty, paramName = param, body = body, qualifier = qualifierFor(ty.toRef()))
funcsByTy[ty] = func
return name
}
private fun generateRecord(ty: TyRecord): String {
val cached = ty.alias?.let { existing(ty) } ?: funcsByTy[ty]?.name
if (cached != null) return cached
val name = "encode${ty.alias?.let { funcNames[it.toRef()] } ?: "Record${i++}"}"
val param = ty.renderParam()
val qualifier = ty.alias?.let { qualifierFor(it.toRef()) } ?: ""
val body = buildString {
append(" ${qual("object")} <|\n [ ")
ty.fields.entries.joinTo(this, separator = "\n , ") { (k, v) ->
"( \"$k\", ${gen(v)} $param.$k )"
}
append("\n ]")
}
val func = GeneratedFunction(name = name, paramTy = ty, paramName = param, body = body, qualifier = qualifier)
funcsByTy[ty] = func
return name
}
private fun generateDict(ty: TyUnion): String {
val k = ty.parameters[0]
return if (k !is TyUnion || !k.isTyString) {
"(\\_ -> Debug.todo \"Can't generate encoder for Dict with non-String keys\")"
} else {
"(${qual("Dict", "toList")} >> ${qual("List", "map")} (\\( k, v ) -> ( k, ${gen(ty.parameters[1])} v )) >> ${qual("object")})"
}
}
private fun generateTuple(ty: TyTuple): String {
return if (ty.types.size == 2) {
"(\\( a, b ) -> ${qual("list")} identity [ ${gen(ty.types[0])} a, ${gen(ty.types[1])} b ])"
} else {
"(\\( a, b, c ) -> ${qual("list")} identity [ ${gen(ty.types[0])} a, ${gen(ty.types[1])} b, ${gen(ty.types[2])} c ])"
}
}
private fun generateMaybe(ty: TyUnion): String {
return existing(ty) ?: run {
"(${qual("Maybe", "map")} ${gen(ty.parameters[0])} >> ${qual("Maybe", "withDefault")} ${qual("null")})"
}
}
override fun isExistingFunction(needle: Ty, function: Ty): Boolean {
return function.run {
this is TyFunction &&
parameters == listOf(needle) &&
ret is TyUnion &&
ret.module == "Json.Encode" &&
ret.name == "Value"
}
}
private fun qual(name: String) = qual("Json.Encode", name)
}
| mit | 5b1a0ac5418037a40ed563d70840a7b4 | 41.137143 | 138 | 0.536344 | 4.040548 | false | false | false | false |
paulalewis/agl | src/main/kotlin/com/castlefrog/agl/domains/yahtzee/YahtzeeAction.kt | 1 | 1810 | package com.castlefrog.agl.domains.yahtzee
import com.castlefrog.agl.Action
sealed class YahtzeeAction : Action<YahtzeeAction>
/**
* The roll action controls which dice get rolled and which are kept for next
* state.
* Indicated quantity of each die number to not roll again.
*/
data class YahtzeeRollAction(val selected: ByteArray = ByteArray(YahtzeeState.N_VALUES)) : YahtzeeAction() {
override fun copy(): YahtzeeRollAction = copy(selected = selected)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
return selected.contentEquals((other as YahtzeeRollAction).selected)
}
override fun hashCode(): Int = selected.contentHashCode()
override fun toString(): String {
val output = StringBuilder()
output.append("[ ")
for (value in selected) {
output.append(value).append(" ")
}
output.append("]")
return output.toString()
}
}
data class YahtzeeSelectAction(val scoreCategory: YahtzeeScoreCategory) : YahtzeeAction() {
override fun toString(): String {
return scoreCategory.toString()
}
override fun copy(): YahtzeeSelectAction = this
companion object {
/** list of all possible select actions. */
private val selectActions = generateSelectActions()
fun valueOf(scoreCategory: Int): YahtzeeAction {
return selectActions[scoreCategory]
}
fun valueOf(scoreCategory: YahtzeeScoreCategory): YahtzeeAction {
return valueOf(scoreCategory.ordinal)
}
private fun generateSelectActions(): List<YahtzeeSelectAction> {
return YahtzeeScoreCategory.values().map { YahtzeeSelectAction(it) }
}
}
}
| mit | 22a9113e796ef6fbaca570864a93f92d | 29.677966 | 108 | 0.668508 | 3.995585 | false | false | false | false |
midhunhk/random-contact | app/src/androidTest/java/com/ae/apps/randomcontact/ContactGroupDaoTest.kt | 1 | 1989 | package com.ae.apps.randomcontact
import android.content.Context
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.ae.apps.randomcontact.room.AppDatabase
import com.ae.apps.randomcontact.room.dao.ContactGroupDao
import com.ae.apps.randomcontact.room.entities.ContactGroup
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.io.IOException
@RunWith(AndroidJUnit4::class)
class ContactGroupDaoTest {
private lateinit var contactGroupDao: ContactGroupDao
private lateinit var database: AppDatabase
@Before
fun createDatabase(){
val context: Context = ApplicationProvider.getApplicationContext()
database = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
.allowMainThreadQueries()
.build()
contactGroupDao = database.contactGroupDao()
}
@After
@Throws(IOException::class)
fun closeDatabase(){
database.close()
}
@Test
@Throws(IOException::class)
fun insertAndGetContactGroup() = runBlocking {
val contactGroup = ContactGroup(name = "Test Group", selectedContacts = "3,4,6")
contactGroupDao.insert(contactGroup)
val allGroups = contactGroupDao.getAll().value
// TODO assertion for LiveData
// Assert.assertEquals(allGroups?.get(0)?.name, contactGroup.name)
}
@Test
fun getAllGroups() = runBlocking {
var contactGroup = ContactGroup(name = "Test Group", selectedContacts = "3,4,6")
contactGroupDao.insert(contactGroup)
contactGroup = ContactGroup(name = "Test Group2", selectedContacts = "6")
contactGroupDao.insert(contactGroup)
val all = contactGroupDao.getAll().value
if (all != null) {
Assert.assertEquals(2, all.size)
}
}
} | apache-2.0 | c904f356d2ada9981277767d4a891b2e | 30.587302 | 88 | 0.712418 | 4.323913 | false | true | false | false |
adrielcafe/MoovAndroidApp | app/src/main/java/cafe/adriel/moov/view/activity/MovieDetailActivity.kt | 1 | 2353 | package cafe.adriel.moov.view.activity
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.MenuItem
import cafe.adriel.moov.*
import cafe.adriel.moov.contract.MovieContract
import cafe.adriel.moov.model.entity.Movie
import com.bumptech.glide.Glide
import com.tinsuke.icekick.extension.parcelLateState
import kotlinx.android.synthetic.main.activity_movie_detail.*
class MovieDetailActivity: BaseActivity(), MovieContract.IMovieView {
private var movie: Movie by parcelLateState()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_movie_detail)
movie = intent.getParcelableExtra(Constant.EXTRA_MOVIE)
supportActionBar?.run {
setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
setDisplayHomeAsUpEnabled(true)
title = null
}
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
showMovie()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
supportFinishAfterTransition()
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun showMovie() {
movie?.run {
vName.text = name
vOverview.text = overview
genres?.let {
if (it.isNotEmpty()) {
vGenre.text = "{md-local-offer} ${Util.getGenres(genres)}"
}
}
releaseDate?.toDate()?.let {
vReleaseDate.text = "{md-access-time} ${it.toFormattedString()}"
}
posterImagePath?.let {
Glide.with(this@MovieDetailActivity)
.load(Util.getPosterImageUrl(it))
.dontAnimate()
.into(vPoster)
}
backdropImagePath?.let {
Glide.with(this@MovieDetailActivity)
.load(Util.getBackdropImageUrl(it))
.into(vBackdrop)
}
}
}
override fun showError(error: String) {
showToast(error)
}
} | mit | c388e94dd19a061718c71853f4e08536 | 29.973684 | 80 | 0.59881 | 4.97463 | false | false | false | false |
MrSugarCaney/DirtyArrows | src/main/kotlin/nl/sugcube/dirtyarrows/bow/ability/LaserBow.kt | 1 | 4698 | package nl.sugcube.dirtyarrows.bow.ability
import nl.sugcube.dirtyarrows.DirtyArrows
import nl.sugcube.dirtyarrows.bow.BowAbility
import nl.sugcube.dirtyarrows.bow.DefaultBow
import nl.sugcube.dirtyarrows.util.*
import org.bukkit.Location
import org.bukkit.Material
import org.bukkit.Sound
import org.bukkit.enchantments.Enchantment
import org.bukkit.entity.Arrow
import org.bukkit.entity.LivingEntity
import org.bukkit.entity.Player
import org.bukkit.event.entity.ProjectileLaunchEvent
import org.bukkit.inventory.ItemStack
import org.bukkit.util.Vector
/**
* Shoots straight at the target. Slightly less damage than a regular bow.
* Instant damage. Laser beams can travel through transparent blocks.
*
* @author SugarCaney
*/
open class LaserBow(plugin: DirtyArrows) : BowAbility(
plugin = plugin,
type = DefaultBow.LASER,
canShootInProtectedRegions = true,
removeArrow = false,
description = "Shoot fast laser beams.",
costRequirements = listOf(ItemStack(Material.REDSTONE, 1))
) {
/**
* The chance that a laser beam crits. Number between 0 and 1.
*/
val criticalHitChance = config.getDouble("$node.critical-hit-chance")
/**
* With what number to multiply the damage dealt compared to the vanilla damage calculation.
*/
val damageMultiplier = config.getDouble("$node.damage-multiplier")
/**
* The maximum amount of blocks a laser beam can travel.
*/
val maximumRange = config.getDouble("$node.maximum-range")
/**
* In what increment the laser travels (in blocks).
*/
val step = config.getDouble("$node.step")
init {
check(criticalHitChance in 0.0..1.0) { "$node.critical-hit-chance must be between 0 and 1, got <$criticalHitChance>" }
check(step > 0) { "$node.step must be greater than 0, got <$step>" }
}
override fun launch(player: Player, arrow: Arrow, event: ProjectileLaunchEvent) {
val launchLocation = player.location
val direction = player.location.direction.normalize()
player.playSound(player.location, Sound.ENTITY_VEX_HURT, 30f, 1f)
// Continue checking the line from the player's direction until the maximum distance is exceeded.
// Stop prematurely when a solid block is hit, or when an entity is hit.
val checkLocation = arrow.location
while (checkLocation.distance(launchLocation) <= maximumRange) {
checkLocation.add(direction.copyOf().multiply(step))
// Beam can only go through transparent blocks.
if (checkLocation.block.type.isOccluding) break
// Check if it hit an entity.
val target = checkLocation.findEntity(player)
if (target != null) {
target.damage(arrow, player)
player.playSound(player.location, Sound.ENTITY_ARROW_HIT_PLAYER, 10f, 1f)
break
}
checkLocation.showBeamPart(direction)
}
// Only launch the laser beam.
unregisterArrow(arrow)
arrow.remove()
}
/**
* Damages this entity.
*
* @param arrow
* The arrow that was shot.
* @param player
* The player that shot the laser.
*/
private fun LivingEntity.damage(arrow: Arrow, player: Player) {
val damageAmount = arrow.damage(player.bowItem())
damage(damageAmount, player)
}
/**
* Get the first living entity near this location.
*/
private fun Location.findEntity(shooter: LivingEntity): LivingEntity? {
return copyOf(y = y - 0.7).nearbyLivingEntities(0.5).asSequence()
.filter { it != shooter }
.firstOrNull()
}
/**
* Shows the laser beam part at this location in the direction of the given vector.
*/
private fun Location.showBeamPart(direction: Vector) {
copyOf().add(direction.copyOf().multiply(step * 0.67))
.fuzz(0.05)
.showColoredDust(org.bukkit.Color.RED, 1)
fuzz(0.05).showColoredDust(org.bukkit.Color.RED, 1)
copyOf().add(direction.copyOf().multiply(step * 1.33))
.fuzz(0.05)
.showColoredDust(org.bukkit.Color.RED, 1)
}
/**
* Calculates how much damage to deal with the laser beam.
*
* @param bow
* The bow that the shooter holds.
*/
private fun Arrow.damage(bow: ItemStack?): Double {
val powerLevel = bow?.getEnchantmentLevel(Enchantment.ARROW_DAMAGE) ?: 0
val velocity = velocity.length()
return arrowDamage(velocity, criticalHitChance, powerLevel) * damageMultiplier
}
} | gpl-3.0 | b7dc3c419c5084b8ee908ccb09743e22 | 33.29927 | 126 | 0.647297 | 4.205909 | false | false | false | false |
apollostack/apollo-android | composite/samples/kotlin-sample/src/main/java/com/apollographql/apollo3/kotlinsample/data/ApolloCoroutinesService.kt | 1 | 2867 | package com.apollographql.apollo3.kotlinsample.data
import com.apollographql.apollo3.ApolloClient
import com.apollographql.apollo3.coroutines.await
import com.apollographql.apollo3.kotlinsample.GithubRepositoriesQuery
import com.apollographql.apollo3.kotlinsample.GithubRepositoryCommitsQuery
import com.apollographql.apollo3.kotlinsample.GithubRepositoryDetailQuery
import com.apollographql.apollo3.kotlinsample.type.OrderDirection
import com.apollographql.apollo3.kotlinsample.type.PullRequestState
import com.apollographql.apollo3.kotlinsample.type.RepositoryOrderField
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
/**
* An implementation of a [GitHubDataSource] that shows how we can use coroutines to make our apollo requests.
*/
class ApolloCoroutinesService(
apolloClient: ApolloClient,
private val processContext: CoroutineContext = Dispatchers.IO,
private val resultContext: CoroutineContext = Dispatchers.Main
) : GitHubDataSource(apolloClient) {
private var job: Job? = null
override fun fetchRepositories() {
val repositoriesQuery = GithubRepositoriesQuery(
repositoriesCount = 50,
orderBy = RepositoryOrderField.UPDATED_AT,
orderDirection = OrderDirection.DESC
)
job = CoroutineScope(processContext).launch {
try {
val response = apolloClient.query(repositoriesQuery).await()
withContext(resultContext) {
repositoriesSubject.onNext(mapRepositoriesResponseToRepositories(response))
}
} catch (e: Exception) {
exceptionSubject.onNext(e)
}
}
}
override fun fetchRepositoryDetail(repositoryName: String) {
val repositoryDetailQuery = GithubRepositoryDetailQuery(
name = repositoryName,
pullRequestStates = listOf(PullRequestState.OPEN)
)
job = CoroutineScope(processContext).launch {
try {
val response = apolloClient.query(repositoryDetailQuery).await()
withContext(resultContext) {
repositoryDetailSubject.onNext(response)
}
} catch (e: Exception) {
exceptionSubject.onNext(e)
}
}
}
override fun fetchCommits(repositoryName: String) {
val commitsQuery = GithubRepositoryCommitsQuery(
name = repositoryName
)
job = CoroutineScope(processContext).launch {
try {
val response = apolloClient.query(commitsQuery).await()
val headCommit = response.data?.viewer?.repository?.ref?.target as? GithubRepositoryCommitsQuery.Data.Viewer.Repository.Ref.CommitTarget
val commits = headCommit?.history?.edges?.filterNotNull().orEmpty()
withContext(resultContext) {
commitsSubject.onNext(commits)
}
} catch (e: Exception) {
exceptionSubject.onNext(e)
}
}
}
override fun cancelFetching() {
job?.cancel()
}
}
| mit | 433d997fdb402dcf76b19a655d94d5a1 | 32.337209 | 144 | 0.728636 | 4.859322 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/track/shikimori/ShikimoriInterceptor.kt | 1 | 1496 | package eu.kanade.tachiyomi.data.track.shikimori
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import okhttp3.Interceptor
import okhttp3.Response
import uy.kohesive.injekt.injectLazy
class ShikimoriInterceptor(val shikimori: Shikimori) : Interceptor {
private val json: Json by injectLazy()
/**
* OAuth object used for authenticated requests.
*/
private var oauth: OAuth? = shikimori.restoreToken()
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
val currAuth = oauth ?: throw Exception("Not authenticated with Shikimori")
val refreshToken = currAuth.refresh_token!!
// Refresh access token if expired.
if (currAuth.isExpired()) {
val response = chain.proceed(ShikimoriApi.refreshTokenRequest(refreshToken))
if (response.isSuccessful) {
newAuth(json.decodeFromString<OAuth>(response.body.string()))
} else {
response.close()
}
}
// Add the authorization header to the original request.
val authRequest = originalRequest.newBuilder()
.addHeader("Authorization", "Bearer ${oauth!!.access_token}")
.header("User-Agent", "Tachiyomi")
.build()
return chain.proceed(authRequest)
}
fun newAuth(oauth: OAuth?) {
this.oauth = oauth
shikimori.saveToken(oauth)
}
}
| apache-2.0 | f35929f7e21555d04548ab6aa081ff51 | 30.829787 | 88 | 0.654412 | 4.857143 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/more/settings/screen/AboutScreen.kt | 1 | 10322 | package eu.kanade.presentation.more.settings.screen
import android.content.Context
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Public
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.navigator.LocalNavigator
import cafe.adriel.voyager.navigator.currentOrThrow
import com.bluelinelabs.conductor.Router
import eu.kanade.domain.ui.UiPreferences
import eu.kanade.presentation.components.AppBar
import eu.kanade.presentation.components.LinkIcon
import eu.kanade.presentation.components.Scaffold
import eu.kanade.presentation.components.ScrollbarLazyColumn
import eu.kanade.presentation.more.LogoHeader
import eu.kanade.presentation.more.about.LicensesScreen
import eu.kanade.presentation.more.settings.widget.TextPreferenceWidget
import eu.kanade.presentation.util.LocalBackPress
import eu.kanade.presentation.util.LocalRouter
import eu.kanade.tachiyomi.BuildConfig
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.updater.AppUpdateChecker
import eu.kanade.tachiyomi.data.updater.AppUpdateResult
import eu.kanade.tachiyomi.data.updater.RELEASE_URL
import eu.kanade.tachiyomi.ui.more.NewUpdateDialogController
import eu.kanade.tachiyomi.util.CrashLogUtil
import eu.kanade.tachiyomi.util.lang.toDateTimestampString
import eu.kanade.tachiyomi.util.lang.withIOContext
import eu.kanade.tachiyomi.util.lang.withUIContext
import eu.kanade.tachiyomi.util.system.copyToClipboard
import eu.kanade.tachiyomi.util.system.logcat
import eu.kanade.tachiyomi.util.system.toast
import kotlinx.coroutines.launch
import logcat.LogPriority
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.TimeZone
class AboutScreen : Screen {
@Composable
override fun Content() {
val scope = rememberCoroutineScope()
val context = LocalContext.current
val uriHandler = LocalUriHandler.current
val handleBack = LocalBackPress.current
val navigator = LocalNavigator.currentOrThrow
val router = LocalRouter.currentOrThrow
Scaffold(
topBar = { scrollBehavior ->
AppBar(
title = stringResource(R.string.pref_category_about),
navigateUp = if (handleBack != null) handleBack::invoke else null,
scrollBehavior = scrollBehavior,
)
},
) { contentPadding ->
ScrollbarLazyColumn(
contentPadding = contentPadding,
) {
item {
LogoHeader()
}
item {
TextPreferenceWidget(
title = stringResource(R.string.version),
subtitle = getVersionName(withBuildDate = true),
onPreferenceClick = {
val deviceInfo = CrashLogUtil(context).getDebugInfo()
context.copyToClipboard("Debug information", deviceInfo)
},
)
}
if (BuildConfig.INCLUDE_UPDATER) {
item {
TextPreferenceWidget(
title = stringResource(R.string.check_for_updates),
onPreferenceClick = {
scope.launch {
checkVersion(context, router)
}
},
)
}
}
if (!BuildConfig.DEBUG) {
item {
TextPreferenceWidget(
title = stringResource(R.string.whats_new),
onPreferenceClick = { uriHandler.openUri(RELEASE_URL) },
)
}
}
item {
TextPreferenceWidget(
title = stringResource(R.string.help_translate),
onPreferenceClick = { uriHandler.openUri("https://tachiyomi.org/help/contribution/#translation") },
)
}
item {
TextPreferenceWidget(
title = stringResource(R.string.licenses),
onPreferenceClick = { navigator.push(LicensesScreen()) },
)
}
item {
TextPreferenceWidget(
title = stringResource(R.string.privacy_policy),
onPreferenceClick = { uriHandler.openUri("https://tachiyomi.org/privacy") },
)
}
item {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp),
horizontalArrangement = Arrangement.Center,
) {
LinkIcon(
label = stringResource(R.string.website),
painter = rememberVectorPainter(Icons.Outlined.Public),
url = "https://tachiyomi.org",
)
LinkIcon(
label = "Discord",
painter = painterResource(R.drawable.ic_discord_24dp),
url = "https://discord.gg/tachiyomi",
)
LinkIcon(
label = "Twitter",
painter = painterResource(R.drawable.ic_twitter_24dp),
url = "https://twitter.com/tachiyomiorg",
)
LinkIcon(
label = "Facebook",
painter = painterResource(R.drawable.ic_facebook_24dp),
url = "https://facebook.com/tachiyomiorg",
)
LinkIcon(
label = "Reddit",
painter = painterResource(R.drawable.ic_reddit_24dp),
url = "https://www.reddit.com/r/Tachiyomi",
)
LinkIcon(
label = "GitHub",
painter = painterResource(R.drawable.ic_github_24dp),
url = "https://github.com/tachiyomiorg",
)
}
}
}
}
}
/**
* Checks version and shows a user prompt if an update is available.
*/
private suspend fun checkVersion(context: Context, router: Router) {
val updateChecker = AppUpdateChecker()
withUIContext {
context.toast(R.string.update_check_look_for_updates)
try {
when (val result = withIOContext { updateChecker.checkForUpdate(context, isUserPrompt = true) }) {
is AppUpdateResult.NewUpdate -> {
NewUpdateDialogController(result).showDialog(router)
}
is AppUpdateResult.NoNewUpdate -> {
context.toast(R.string.update_check_no_new_updates)
}
else -> {}
}
} catch (e: Exception) {
context.toast(e.message)
logcat(LogPriority.ERROR, e)
}
}
}
companion object {
fun getVersionName(withBuildDate: Boolean): String {
return when {
BuildConfig.DEBUG -> {
"Debug ${BuildConfig.COMMIT_SHA}".let {
if (withBuildDate) {
"$it (${getFormattedBuildTime()})"
} else {
it
}
}
}
BuildConfig.PREVIEW -> {
"Preview r${BuildConfig.COMMIT_COUNT}".let {
if (withBuildDate) {
"$it (${BuildConfig.COMMIT_SHA}, ${getFormattedBuildTime()})"
} else {
"$it (${BuildConfig.COMMIT_SHA})"
}
}
}
else -> {
"Stable ${BuildConfig.VERSION_NAME}".let {
if (withBuildDate) {
"$it (${getFormattedBuildTime()})"
} else {
it
}
}
}
}
}
private fun getFormattedBuildTime(): String {
return try {
val inputDf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'", Locale.US)
inputDf.timeZone = TimeZone.getTimeZone("UTC")
val buildTime = inputDf.parse(BuildConfig.BUILD_TIME)
val outputDf = DateFormat.getDateTimeInstance(
DateFormat.MEDIUM,
DateFormat.SHORT,
Locale.getDefault(),
)
outputDf.timeZone = TimeZone.getDefault()
buildTime!!.toDateTimestampString(UiPreferences.dateFormat(Injekt.get<UiPreferences>().dateFormat().get()))
} catch (e: Exception) {
BuildConfig.BUILD_TIME
}
}
}
}
| apache-2.0 | e6aa6986f90efb97429c091c0d2d4b54 | 39.637795 | 123 | 0.518601 | 5.640437 | false | false | false | false |
javaslang/javaslang-circuitbreaker | resilience4j-kotlin/src/main/kotlin/io/github/resilience4j/kotlin/retry/RetryRegistry.kt | 2 | 6982 | /*
*
* Copyright 2020
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*
*/
@file:Suppress("FunctionName")
package io.github.resilience4j.kotlin.retry
import io.github.resilience4j.retry.RetryConfig
import io.github.resilience4j.retry.RetryRegistry
import io.vavr.Tuple2 as VavrTuple2
import io.vavr.collection.HashMap as VavrHashMap
/**
* Creates new custom [RetryRegistry].
*
* ```kotlin
* val retryRegistry = RetryRegistry {
* withRetryConfig(defaultConfig)
* withTags(commonTags)
* }
* ```
*
* @param config methods of [RetryRegistry.Builder] that customize resulting `RetryRegistry`
*/
inline fun RetryRegistry(
config: RetryRegistry.Builder.() -> Unit
): RetryRegistry {
return RetryRegistry.custom().apply(config).build()
}
/**
* Configures a [RetryRegistry] with a custom default Retry configuration.
*
* ```kotlin
* val retryRegistry = RetryRegistry {
* withRetryConfig<String> {
* waitDuration(Duration.ofMillis(10))
* retryOnResult { result -> result == "ERROR" }
* }
* }
* ```
*
* @param config methods of [RetryConfig.Builder] that customize default `RetryConfig`
*/
inline fun <T> RetryRegistry.Builder.withRetryConfig(
config: RetryConfig.Builder<T>.() -> Unit
) {
withRetryConfig(RetryConfig(config))
}
/**
* Configures a [RetryRegistry] with a custom default Retry configuration.
*
* ```kotlin
* val retryRegistry = RetryRegistry {
* withRetryConfig {
* waitDuration(Duration.ofMillis(10))
* retryOnResult { result -> result == "ERROR" }
* }
* }
* ```
*
* @param config methods of [RetryConfig.Builder] that customize default `RetryConfig`
*/
@JvmName("withUntypedRetryConfig")
inline fun RetryRegistry.Builder.withRetryConfig(
config: RetryConfig.Builder<Any?>.() -> Unit
) {
withRetryConfig(RetryConfig(config))
}
/**
* Configures a [RetryRegistry] with a custom default Retry configuration.
*
* ```kotlin
* val retryRegistry = RetryRegistry {
* withRetryConfig<String>(baseRetryConfig) {
* waitDuration(Duration.ofMillis(10))
* retryOnResult { result -> result == "ERROR" }
* }
* }
* ```
*
* @param baseConfig base `RetryConfig`
* @param config methods of [RetryConfig.Builder] that customize default `RetryConfig`
*/
inline fun <T> RetryRegistry.Builder.withRetryConfig(
baseConfig: RetryConfig,
config: RetryConfig.Builder<T>.() -> Unit
) {
withRetryConfig(RetryConfig(baseConfig, config))
}
/**
* Configures a [RetryRegistry] with a custom default Retry configuration.
*
* ```kotlin
* val retryRegistry = RetryRegistry {
* withRetryConfig(baseRetryConfig) {
* waitDuration(Duration.ofMillis(10))
* }
* }
* ```
*
* @param baseConfig base `RetryConfig`
* @param config methods of [RetryConfig.Builder] that customize default `RetryConfig`
*/
@JvmName("withUntypedRetryConfig")
inline fun RetryRegistry.Builder.withRetryConfig(
baseConfig: RetryConfig,
config: RetryConfig.Builder<Any?>.() -> Unit
) {
withRetryConfig(RetryConfig(baseConfig, config))
}
/**
* Configures a [RetryRegistry] with a custom Retry configuration.
*
* ```kotlin
* val retryRegistry = RetryRegistry {
* addRetryConfig<String>("sharedConfig1") {
* waitDuration(Duration.ofMillis(10))
* retryOnResult { result -> result == "ERROR" }
* }
* }
* ```
*
* @param configName configName for a custom shared Retry configuration
* @param config methods of [RetryConfig.Builder] that customize resulting `RetryConfig`
*/
inline fun <T> RetryRegistry.Builder.addRetryConfig(
configName: String,
config: RetryConfig.Builder<T>.() -> Unit
) {
addRetryConfig(configName, RetryConfig(config))
}
/**
* Configures a [RetryRegistry] with a custom Retry configuration.
*
* ```kotlin
* val retryRegistry = RetryRegistry {
* addRetryConfig("sharedConfig1") {
* waitDuration(Duration.ofMillis(10))
* }
* }
* ```
*
* @param configName configName for a custom shared Retry configuration
* @param config methods of [RetryConfig.Builder] that customize resulting `RetryConfig`
*/
@JvmName("addUntypedRetryConfig")
inline fun RetryRegistry.Builder.addRetryConfig(
configName: String,
config: RetryConfig.Builder<Any?>.() -> Unit
) {
addRetryConfig(configName, RetryConfig(config))
}
/**
* Configures a [RetryRegistry] with a custom Retry configuration.
*
* ```kotlin
* val retryRegistry = RetryRegistry {
* addRetryConfig<String>("sharedConfig1", baseRetryConfig) {
* waitDuration(Duration.ofMillis(10))
* retryOnResult { result -> result == "ERROR" }
* }
* }
* ```
*
* @param configName configName for a custom shared Retry configuration
* @param baseConfig base `RetryConfig`
* @param config methods of [RetryConfig.Builder] that customize resulting `RetryConfig`
*/
inline fun <T> RetryRegistry.Builder.addRetryConfig(
configName: String,
baseConfig: RetryConfig,
config: RetryConfig.Builder<T>.() -> Unit
) {
addRetryConfig(configName, RetryConfig(baseConfig, config))
}
/**
* Configures a [RetryRegistry] with a custom Retry configuration.
*
* ```kotlin
* val retryRegistry = RetryRegistry {
* addRetryConfig("sharedConfig1", baseRetryConfig) {
* waitDuration(Duration.ofMillis(10))
* }
* }
* ```
*
* @param configName configName for a custom shared Retry configuration
* @param baseConfig base `RetryConfig`
* @param config methods of [RetryConfig.Builder] that customize resulting `RetryConfig`
*/
@JvmName("addUntypedRetryConfig")
inline fun RetryRegistry.Builder.addRetryConfig(
configName: String,
baseConfig: RetryConfig,
config: RetryConfig.Builder<Any?>.() -> Unit
) {
addRetryConfig(configName, RetryConfig(baseConfig, config))
}
/**
* Configures a [RetryRegistry] with Tags.
*
* Tags added to the registry will be added to every instance created by this registry.
*
* @param tags default tags to add to the registry.
*/
fun RetryRegistry.Builder.withTags(tags: Map<String, String>) {
withTags(VavrHashMap.ofAll(tags))
}
/**
* Configures a [RetryRegistry] with Tags.
*
* Tags added to the registry will be added to every instance created by this registry.
*
* @param tags default tags to add to the registry.
*/
fun RetryRegistry.Builder.withTags(vararg tags: Pair<String, String>) {
withTags(VavrHashMap.ofEntries(tags.map { VavrTuple2(it.first, it.second) }))
}
| apache-2.0 | 2faf78f3f2a0f722cc868556e05d68cb | 27.970954 | 100 | 0.700229 | 3.848953 | false | true | false | false |
k9mail/k-9 | app/ui/base/src/main/java/com/fsck/k9/ui/base/extensions/ConfigurationExtensions.kt | 2 | 1072 | package com.fsck.k9.ui.base.extensions
import android.content.res.Configuration
import android.os.Build
import android.os.LocaleList
import androidx.annotation.RequiresApi
import java.util.Locale
@Suppress("DEPRECATION")
var Configuration.currentLocale: Locale
get() {
return if (Build.VERSION.SDK_INT >= 24) {
locales[0]
} else {
locale
}
}
set(value) {
if (Build.VERSION.SDK_INT >= 24) {
setLocales(createLocaleList(value, locales))
} else {
setLocale(value)
}
}
@RequiresApi(24)
private fun createLocaleList(topLocale: Locale, otherLocales: LocaleList): LocaleList {
if (!otherLocales.isEmpty && otherLocales[0] == topLocale) {
return otherLocales
}
val locales = mutableListOf(topLocale)
for (index in 0 until otherLocales.size()) {
val currentLocale = otherLocales[index]
if (currentLocale != topLocale) {
locales.add(currentLocale)
}
}
return LocaleList(*locales.toTypedArray())
}
| apache-2.0 | bccc7eeaf6f506b57b81a9ed4527626b | 25.146341 | 87 | 0.637127 | 4.171206 | false | false | false | false |
k9mail/k-9 | app/storage/src/main/java/com/fsck/k9/preferences/migrations/StorageMigrationTo18.kt | 2 | 1579 | package com.fsck.k9.preferences.migrations
import android.database.sqlite.SQLiteDatabase
/**
* Rewrite the per-network type IMAP compression settings to a single setting.
*/
class StorageMigrationTo18(
private val db: SQLiteDatabase,
private val migrationsHelper: StorageMigrationsHelper
) {
fun rewriteImapCompressionSettings() {
val accountUuidsListValue = migrationsHelper.readValue(db, "accountUuids")
if (accountUuidsListValue == null || accountUuidsListValue.isEmpty()) {
return
}
val accountUuids = accountUuidsListValue.split(",")
for (accountUuid in accountUuids) {
rewriteImapCompressionSetting(accountUuid)
}
}
private fun rewriteImapCompressionSetting(accountUuid: String) {
val useCompressionWifi = migrationsHelper.readValue(db, "$accountUuid.useCompression.WIFI").toBoolean()
val useCompressionMobile = migrationsHelper.readValue(db, "$accountUuid.useCompression.MOBILE").toBoolean()
val useCompressionOther = migrationsHelper.readValue(db, "$accountUuid.useCompression.OTHER").toBoolean()
val useCompression = useCompressionWifi && useCompressionMobile && useCompressionOther
migrationsHelper.writeValue(db, "$accountUuid.useCompression", useCompression.toString())
migrationsHelper.writeValue(db, "$accountUuid.useCompression.WIFI", null)
migrationsHelper.writeValue(db, "$accountUuid.useCompression.MOBILE", null)
migrationsHelper.writeValue(db, "$accountUuid.useCompression.OTHER", null)
}
}
| apache-2.0 | 38c0cf6e6af60d6c8eaac173bce252ce | 42.861111 | 115 | 0.735909 | 5.444828 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/test/java/org/wordpress/android/ui/bloggingprompts/onboarding/BloggingPromptsOnboardingUiStateMapperTest.kt | 1 | 3903 | package org.wordpress.android.ui.bloggingprompts.onboarding
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.wordpress.android.R
import org.wordpress.android.R.string
import org.wordpress.android.ui.avatars.TrainOfAvatarsItem.AvatarItem
import org.wordpress.android.ui.avatars.TrainOfAvatarsItem.TrailingLabelTextItem
import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingDialogFragment.DialogType.INFORMATION
import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingDialogFragment.DialogType.ONBOARDING
import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingUiState.Ready
import org.wordpress.android.ui.utils.UiString.UiStringPluralRes
class BloggingPromptsOnboardingUiStateMapperTest {
private val classToTest = BloggingPromptsOnboardingUiStateMapper()
private val expectedRespondents = listOf(
AvatarItem(""),
AvatarItem(""),
AvatarItem(""),
TrailingLabelTextItem(
UiStringPluralRes(
0,
R.string.my_site_blogging_prompt_card_number_of_answers_one,
R.string.my_site_blogging_prompt_card_number_of_answers_other,
3
),
R.attr.colorOnSurface
)
)
private val primaryButtonListener: () -> Unit = {}
private val secondaryButtonListener: () -> Unit = {}
private val expectedOnboardingDialogReadyState = Ready(
promptRes = string.blogging_prompts_onboarding_card_prompt,
respondents = expectedRespondents,
contentTopRes = string.blogging_prompts_onboarding_content_top,
contentBottomRes = string.blogging_prompts_onboarding_content_bottom,
contentNoteTitle = string.blogging_prompts_onboarding_content_note_title,
contentNoteContent = string.blogging_prompts_onboarding_content_note_content,
primaryButtonLabel = string.blogging_prompts_onboarding_try_it_now,
isPrimaryButtonVisible = true,
onPrimaryButtonClick = primaryButtonListener,
secondaryButtonLabel = string.blogging_prompts_onboarding_remind_me,
isSecondaryButtonVisible = true,
onSecondaryButtonClick = secondaryButtonListener
)
private val expectedInformationDialogReadyState = Ready(
promptRes = string.blogging_prompts_onboarding_card_prompt,
respondents = expectedRespondents,
contentTopRes = string.blogging_prompts_onboarding_content_top,
contentBottomRes = string.blogging_prompts_onboarding_content_bottom,
contentNoteTitle = string.blogging_prompts_onboarding_content_note_title,
contentNoteContent = string.blogging_prompts_onboarding_content_note_content,
primaryButtonLabel = string.blogging_prompts_onboarding_got_it,
isPrimaryButtonVisible = true,
onPrimaryButtonClick = primaryButtonListener,
secondaryButtonLabel = string.blogging_prompts_onboarding_remind_me,
isSecondaryButtonVisible = false,
onSecondaryButtonClick = secondaryButtonListener
)
@Test
fun `Should return correct Ready state for ONBOARDING type dialog`() {
val actual = classToTest.mapReady(ONBOARDING, primaryButtonListener, secondaryButtonListener)
val expected = expectedOnboardingDialogReadyState
assertThat(actual).isEqualTo(expected)
}
@Test
fun `Should return correct Ready state for INFORMATION type dialog`() {
val actual = classToTest.mapReady(INFORMATION, primaryButtonListener, secondaryButtonListener)
val expected = expectedInformationDialogReadyState
assertThat(actual).isEqualTo(expected)
}
}
| gpl-2.0 | e4715c5868f1dfd4d8c2ad42ad54ce91 | 49.038462 | 121 | 0.711248 | 5.217914 | false | true | false | false |
markusressel/TutorialTooltip | library/src/main/java/de/markusressel/android/library/tutorialtooltip/builder/TutorialTooltipChainBuilder.kt | 1 | 2889 | /*
* Copyright (c) 2016 Markus Ressel
*
* 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 de.markusressel.android.library.tutorialtooltip.builder
import android.util.Log
import de.markusressel.android.library.tutorialtooltip.TutorialTooltip
import java.util.*
/**
* Class to easily build a chain of TutorialTooltips
*
*
* Add items to the chain using `addItem(TutorialTooltipBuilder)`.
* Start the chain using `execute()`.
*
*
* To proceed from one item in the chain to the next you have to close (remove) its ancestor TutorialTooltip.
* The next item will then show up automatically.
*
*
* Created by Markus on 23.12.2016.
*/
class TutorialTooltipChainBuilder : Builder<TutorialTooltipChainBuilder>() {
private val tooltips: MutableList<TutorialTooltipBuilder>
/**
* Constructor for the Builder
* Chain methods and call ".build()" as your last step to make this object immutable.
*/
init {
tooltips = ArrayList()
}
/**
* Add a TutorialTooltip to the chain
* @param tutorialTooltipBuilder TutorialTooltipBuilder
* *
* @return TutorialTooltipChainBuilder
*/
fun addItem(tutorialTooltipBuilder: TutorialTooltipBuilder): TutorialTooltipChainBuilder {
throwIfCompleted()
tooltips.add(tutorialTooltipBuilder)
return this
}
/**
* Execute the chain and show TutorialItems one after another
*/
fun execute() {
if (tooltips.isEmpty()) {
Log.w(TAG, "Empty chain. Nothing to do.")
return
}
if (!isCompleted) {
build()
}
for (currentIndex in tooltips.indices) {
val tooltipBuilder = tooltips[currentIndex]
val userListener = tooltipBuilder.onPostRemove
tooltipBuilder.onPostRemove = { id, view ->
// call user defined listener
userListener?.invoke(id, view)
// open the next TutorialTooltip in the chain (if one exists)
if (currentIndex >= 0 && currentIndex < tooltips.size - 1) {
TutorialTooltip.show(tooltips[currentIndex + 1])
}
}
}
// show the first TutorialTooltip
TutorialTooltip.show(tooltips[0])
}
companion object {
private const val TAG = "ChainBuilder"
}
}
| apache-2.0 | 5ee743e071b44f8790211efbce8f57ef | 28.479592 | 109 | 0.652475 | 4.674757 | false | false | false | false |
ChristopherGittner/OSMBugs | app/src/main/java/org/gittner/osmbugs/ui/SettingsFragment.kt | 1 | 3135 | package org.gittner.osmbugs.ui
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.preference.EditTextPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import org.gittner.osmbugs.R
import org.gittner.osmbugs.keepright.KeeprightSelectErrorsDialog
import org.gittner.osmbugs.mapdust.MapdustSelectErrorsDialog
import org.gittner.osmbugs.osmnotes.OsmNotesLoginActivity
import org.gittner.osmbugs.osmose.OsmoseSelectErrorsDialog
import org.koin.android.ext.android.inject
import org.osmdroid.config.Configuration
import org.osmdroid.tileprovider.modules.SqlTileWriter
class SettingsFragment : PreferenceFragmentCompat() {
private val mViewModel: ErrorViewModel by inject()
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.preferences)
findPreference<Preference>(getString(R.string.pref_keepright_enabled_types))?.onPreferenceClickListener = Preference.OnPreferenceClickListener {
activity?.supportFragmentManager?.let { KeeprightSelectErrorsDialog().show(it, "Select Errors") }
true
}
findPreference<Preference>(getString(R.string.pref_mapdust_enabled_types))?.onPreferenceClickListener = Preference.OnPreferenceClickListener {
activity?.supportFragmentManager?.let { MapdustSelectErrorsDialog().show(it, "Select Errors") }
true
}
findPreference<Preference>(getString(R.string.pref_osmose_enabled_types))?.onPreferenceClickListener = Preference.OnPreferenceClickListener {
activity?.supportFragmentManager?.let { OsmoseSelectErrorsDialog().show(it, "Select Errors") }
true
}
findPreference<Preference>(getString(R.string.pref_openstreetmap_notes_log_in))?.onPreferenceClickListener = Preference.OnPreferenceClickListener {
startActivity(Intent(context, OsmNotesLoginActivity::class.java))
true
}
findPreference<Preference>(getString(R.string.pref_clear_tile_cache))?.onPreferenceClickListener = Preference.OnPreferenceClickListener {
if (clearTileCache()) {
Toast.makeText(requireContext(), R.string.tile_cache_cleared, Toast.LENGTH_LONG).show()
} else {
Toast.makeText(requireContext(), R.string.tile_cache_cleared_failed, Toast.LENGTH_LONG).show()
}
true
}
findPreference<EditTextPreference>(getString(R.string.pref_tile_cache_ttl_override))?.setOnPreferenceChangeListener { _, newValue ->
Configuration.getInstance().expirationOverrideDuration = newValue.toString().toLong() * 1000
clearTileCache()
true
}
}
private fun clearTileCache(): Boolean {
val sqlTileWriter = SqlTileWriter()
if (!sqlTileWriter.purgeCache()) {
return false
}
SqlTileWriter() // Recreates the Database. Required because purgeCache Deletes the whole database but does not recreate
return true
}
} | mit | 974d00d73a0829ff29957f44ebda4051 | 41.378378 | 155 | 0.724721 | 5.130933 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/gradle/CompilerArgumentsCachingTest.kt | 1 | 26566 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.gradle
import org.jetbrains.kotlin.cli.common.arguments.*
import org.jetbrains.kotlin.idea.gradle.configuration.CachedArgumentsRestoring
import org.jetbrains.kotlin.idea.gradleTooling.arguments.*
import org.jetbrains.kotlin.idea.test.testFramework.KtUsefulTestCase
import org.jetbrains.kotlin.utils.addToStdlib.cast
import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty
import org.junit.Assert
import org.junit.Test
import java.io.File
import java.util.*
import kotlin.random.Random
import kotlin.random.nextInt
import kotlin.reflect.KProperty1
import kotlin.reflect.full.memberProperties
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class CompilerArgumentsCachingTest {
@Test
fun `extract CommonCompilerArguments, modify and check bucket`() {
extractAndCheck(CommonCompilerArguments.DummyImpl::class.java) {
configureCommon()
}
}
@Test
fun `extract CommonCompilerArguments, modify, cache and check`() {
extractAndCheck(CommonCompilerArguments.DummyImpl::class.java) {
configureCommon()
}.cacheAndCheckConsistency()
}
@Test
fun `cache CommonCompilerArguments, restore and compare`() {
createCacheRestoreCompare(CommonCompilerArguments.DummyImpl::class.java) {
configureCommon()
}
}
@Test
fun `extract K2MetadataCompilerArguments, modify and check bucket`() {
extractAndCheck(K2MetadataCompilerArguments::class.java) {
configureMetadata()
}
}
@Test
fun `extract K2MetadataCompilerArguments, modify, cache and check`() {
extractAndCheck(K2MetadataCompilerArguments::class.java) {
configureMetadata()
}.cacheAndCheckConsistency()
}
@Test
fun `cache K2MetadataCompilerArguments, restore and compare`() {
createCacheRestoreCompare(K2MetadataCompilerArguments::class.java) {
configureMetadata()
}
}
@Test
fun `extract K2JVMCompilerArguments and modify and check bucket`() {
extractAndCheck(K2JVMCompilerArguments::class.java) {
configureJvm()
}
}
@Test
fun `extract K2JVMCompilerArguments and modify, cache and check`() {
extractAndCheck(K2JVMCompilerArguments::class.java) {
configureJvm()
}.cacheAndCheckConsistency()
}
@Test
fun `cache K2JVMCompilerArguments, restore and compare`() {
createCacheRestoreCompare(K2JVMCompilerArguments::class.java) {
configureJvm()
}
}
@Test
fun `extract K2JSCompilerArguments and modify and check bucket`() {
extractAndCheck(K2JSCompilerArguments::class.java) {
configureJs()
}
}
@Test
fun `extract K2JSCompilerArguments and modify, cache and check`() {
extractAndCheck(K2JSCompilerArguments::class.java) {
configureJs()
}.cacheAndCheckConsistency()
}
@Test
fun `cache K2JSCompilerArguments, restore and compare`() {
createCacheRestoreCompare(K2JSCompilerArguments::class.java) {
configureJs()
}
}
private fun ExtractedCompilerArgumentsBucket.cacheAndCheckConsistency() {
val mapper = CompilerArgumentsCacheMapperImpl()
val cachedBucket = CompilerArgumentsCachingManager.cacheCompilerArguments(this, mapper)
singleArguments.entries.forEach { (key, value) ->
assertTrue(mapper.checkCached(key))
val rawValue = value ?: return@forEach
assertTrue(mapper.checkCached(rawValue))
val keyCacheId = mapper.cacheArgument(key)
val matchingCachedEntry = cachedBucket.singleArguments.entries.singleOrNull { (cachedKey, _) ->
cachedKey.data == keyCacheId
}
assertTrue(matchingCachedEntry != null)
val valueCacheId = mapper.cacheArgument(rawValue)
assertEquals(
(matchingCachedEntry.value as KotlinCachedRegularCompilerArgument).data,
valueCacheId
)
}
Assert.assertArrayEquals(
classpathParts,
cachedBucket.classpathParts.data.map { mapper.getCached((it as KotlinCachedRegularCompilerArgument).data) }.toTypedArray()
)
flagArguments.entries.forEach { (key, value) ->
assertTrue(mapper.checkCached(key))
val keyCacheId = mapper.cacheArgument(key)
val matchingCachedEntry = cachedBucket.flagArguments.entries.singleOrNull { (cachedKey, _) ->
cachedKey.data == keyCacheId
}
assertTrue(matchingCachedEntry != null)
}
multipleArguments.entries.forEach { (key, value) ->
assertTrue(mapper.checkCached(key))
val rawValues = value ?: return@forEach
rawValues.forEach {
assertTrue(mapper.checkCached(it))
}
val keyCacheId = mapper.cacheArgument(key)
val matchingCachedEntry = cachedBucket.multipleArguments.entries.singleOrNull { (cachedKey, _) ->
true && cachedKey.data == keyCacheId
}
assertTrue(matchingCachedEntry != null)
val valueCacheIds = rawValues.map { mapper.cacheArgument(it) }
Assert.assertArrayEquals(
(matchingCachedEntry.value as KotlinCachedMultipleCompilerArgument).data
.map { (it as KotlinCachedRegularCompilerArgument).data }.toTypedArray(),
valueCacheIds.toTypedArray()
)
}
assertContentEquals(
freeArgs,
cachedBucket.freeArgs.map { mapper.getCached((it as KotlinCachedRegularCompilerArgument).data) }
)
assertContentEquals(
internalArguments,
cachedBucket.internalArguments.map { mapper.getCached((it as KotlinCachedRegularCompilerArgument).data) }
)
}
private fun CommonCompilerArguments.configureCommon() {
help = Random.nextBoolean()
extraHelp = Random.nextBoolean()
version = Random.nextBoolean()
verbose = Random.nextBoolean()
suppressWarnings = Random.nextBoolean()
allWarningsAsErrors = Random.nextBoolean()
progressiveMode = Random.nextBoolean()
script = Random.nextBoolean()
noInline = Random.nextBoolean()
skipMetadataVersionCheck = Random.nextBoolean()
skipPrereleaseCheck = Random.nextBoolean()
allowKotlinPackage = Random.nextBoolean()
reportOutputFiles = Random.nextBoolean()
multiPlatform = Random.nextBoolean()
noCheckActual = Random.nextBoolean()
inlineClasses = Random.nextBoolean()
legacySmartCastAfterTry = Random.nextBoolean()
effectSystem = Random.nextBoolean()
readDeserializedContracts = Random.nextBoolean()
allowResultReturnType = Random.nextBoolean()
properIeee754Comparisons = Random.nextBoolean()
reportPerf = Random.nextBoolean()
listPhases = Random.nextBoolean()
profilePhases = Random.nextBoolean()
checkPhaseConditions = Random.nextBoolean()
checkStickyPhaseConditions = Random.nextBoolean()
useK2 = Random.nextBoolean()
useFirExtendedCheckers = Random.nextBoolean()
disableUltraLightClasses = Random.nextBoolean()
useMixedNamedArguments = Random.nextBoolean()
expectActualLinker = Random.nextBoolean()
disableDefaultScriptingPlugin = Random.nextBoolean()
inferenceCompatibility = Random.nextBoolean()
extendedCompilerChecks = Random.nextBoolean()
suppressVersionWarnings = Random.nextBoolean()
// Invalid values doesn't matter
languageVersion = generateRandomString(20)
apiVersion = generateRandomString(20)
kotlinHome = generateRandomString(20)
intellijPluginRoot = generateRandomString(20)
dumpPerf = generateRandomString(20)
metadataVersion = generateRandomString(20)
dumpDirectory = generateRandomString(20)
dumpOnlyFqName = generateRandomString(20)
explicitApi = generateRandomString(20)
pluginOptions = generateRandomStringArray(20)
pluginClasspaths = generateRandomStringArray(20)
optIn = generateRandomStringArray(20)
commonSources = generateRandomStringArray(20)
disablePhases = generateRandomStringArray(20)
verbosePhases = generateRandomStringArray(20)
phasesToDumpBefore = generateRandomStringArray(20)
phasesToDumpAfter = generateRandomStringArray(20)
phasesToDump = generateRandomStringArray(20)
namesExcludedFromDumping = generateRandomStringArray(20)
phasesToValidateBefore = generateRandomStringArray(20)
phasesToValidateAfter = generateRandomStringArray(20)
phasesToValidate = generateRandomStringArray(20)
}
private fun K2MetadataCompilerArguments.configureMetadata() {
configureCommon()
enabledInJps = Random.nextBoolean()
destination = generateRandomString(20)
moduleName = generateRandomString(20)
classpath = generateRandomStringArray(20).joinToString(File.pathSeparator)
friendPaths = generateRandomStringArray(20)
refinesPaths = generateRandomStringArray(20)
}
private fun K2JVMCompilerArguments.configureJvm() {
configureCommon()
includeRuntime = Random.nextBoolean()
noJdk = Random.nextBoolean()
noStdlib = Random.nextBoolean()
noReflect = Random.nextBoolean()
javaParameters = Random.nextBoolean()
useIR = Random.nextBoolean()
useOldBackend = Random.nextBoolean()
allowUnstableDependencies = Random.nextBoolean()
doNotClearBindingContext = Random.nextBoolean()
noCallAssertions = Random.nextBoolean()
noReceiverAssertions = Random.nextBoolean()
noParamAssertions = Random.nextBoolean()
noOptimize = Random.nextBoolean()
inheritMultifileParts = Random.nextBoolean()
useTypeTable = Random.nextBoolean()
useOldClassFilesReading = Random.nextBoolean()
suppressMissingBuiltinsError = Random.nextBoolean()
useJavac = Random.nextBoolean()
compileJava = Random.nextBoolean()
disableStandardScript = Random.nextBoolean()
strictMetadataVersionSemantics = Random.nextBoolean()
sanitizeParentheses = Random.nextBoolean()
allowNoSourceFiles = Random.nextBoolean()
emitJvmTypeAnnotations = Random.nextBoolean()
noOptimizedCallableReferences = Random.nextBoolean()
noKotlinNothingValueException = Random.nextBoolean()
noResetJarTimestamps = Random.nextBoolean()
noUnifiedNullChecks = Random.nextBoolean()
useOldInlineClassesManglingScheme = Random.nextBoolean()
enableJvmPreview = Random.nextBoolean()
suppressDeprecatedJvmTargetWarning = Random.nextBoolean()
typeEnhancementImprovementsInStrictMode = Random.nextBoolean()
destination = generateRandomString(20)
jdkHome = generateRandomString(20)
expression = generateRandomString(20)
moduleName = generateRandomString(20)
jvmTarget = generateRandomString(20)
abiStability = generateRandomString(20)
javaModulePath = generateRandomString(20)
assertionsMode = generateRandomString(20)
buildFile = generateRandomString(20)
declarationsOutputPath = generateRandomString(20)
javaPackagePrefix = generateRandomString(20)
supportCompatqualCheckerFrameworkAnnotations = generateRandomString(20)
jspecifyAnnotations = generateRandomString(20)
jvmDefault = generateRandomString(20)
defaultScriptExtension = generateRandomString(20)
stringConcat = generateRandomString(20)
klibLibraries = generateRandomString(20)
profileCompilerCommand = generateRandomString(20)
repeatCompileModules = generateRandomString(20)
samConversions = generateRandomString(20)
lambdas = generateRandomString(20)
classpath = generateRandomStringArray(20).joinToString(File.pathSeparator)
scriptTemplates = generateRandomStringArray(10)
additionalJavaModules = generateRandomStringArray(10)
scriptResolverEnvironment = generateRandomStringArray(10)
javacArguments = generateRandomStringArray(10)
javaSourceRoots = generateRandomStringArray(10)
jsr305 = generateRandomStringArray(10)
friendPaths = generateRandomStringArray(10)
}
private fun K2JSCompilerArguments.configureJs() {
configureCommon()
noStdlib = Random.nextBoolean()
sourceMap = Random.nextBoolean()
metaInfo = Random.nextBoolean()
irProduceKlibDir = Random.nextBoolean()
irProduceKlibFile = Random.nextBoolean()
irProduceJs = Random.nextBoolean()
irDce = Random.nextBoolean()
irDcePrintReachabilityInfo = Random.nextBoolean()
irPropertyLazyInitialization = Random.nextBoolean()
irOnly = Random.nextBoolean()
irPerModule = Random.nextBoolean()
generateDts = Random.nextBoolean()
typedArrays = Random.nextBoolean()
friendModulesDisabled = Random.nextBoolean()
metadataOnly = Random.nextBoolean()
enableJsScripting = Random.nextBoolean()
fakeOverrideValidator = Random.nextBoolean()
wasm = Random.nextBoolean()
outputFile = generateRandomString(20)
libraries = generateRandomString(20)
sourceMapPrefix = generateRandomString(20)
sourceMapBaseDirs = generateRandomString(20)
sourceMapEmbedSources = generateRandomString(20)
target = generateRandomString(20)
moduleKind = generateRandomString(20)
main = generateRandomString(20)
outputPrefix = generateRandomString(20)
outputPostfix = generateRandomString(20)
irModuleName = generateRandomString(20)
includes = generateRandomString(20)
friendModules = generateRandomString(20)
errorTolerancePolicy = generateRandomString(20)
}
private fun <T : CommonCompilerArguments> extractAndCheck(
argumentsClass: Class<out T>,
modify: T.() -> Unit = {}
): ExtractedCompilerArgumentsBucket {
val compilerArguments = argumentsClass.getDeclaredConstructor().newInstance()
compilerArguments.modify()
val bucket = CompilerArgumentsExtractor.prepareCompilerArgumentsBucket(compilerArguments)
val propertiesByName = argumentsClass.kotlin.memberProperties.associateBy { it.name }
KtUsefulTestCase.assertContainsElements(
singleCompilerArgumentsMap[argumentsClass.simpleName]!!.sorted(),
bucket.singleArguments.keys.toList().sorted(),
)
bucket.singleArguments.entries.forEach {
assertEquals(
propertiesByName[it.key]!!.cast<KProperty1<T, String>>().get(compilerArguments),
it.value
)
}
assertEquals(
propertiesByName["classpath"]?.cast<KProperty1<T, String>>()?.get(compilerArguments),
bucket.classpathParts.ifNotEmpty { joinToString(File.pathSeparator) }
)
KtUsefulTestCase.assertContainsElements(
multipleCompilerArgumentsMap[argumentsClass.simpleName]!!.sorted(),
bucket.multipleArguments.keys.toList().sorted(),
)
bucket.multipleArguments.entries.forEach {
Assert.assertArrayEquals(propertiesByName[it.key]!!.cast<KProperty1<T, Array<String>>>().get(compilerArguments), it.value)
}
KtUsefulTestCase.assertContainsElements(
flagCompilerArgumentsMap[argumentsClass.simpleName]!!.sorted(),
bucket.flagArguments.keys.toList().sorted(),
)
bucket.flagArguments.entries.forEach {
assertEquals(propertiesByName[it.key]!!.cast<KProperty1<T, Boolean>>().get(compilerArguments), it.value)
}
KtUsefulTestCase.assertOrderedEquals(
propertiesByName["freeArgs"]!!.cast<KProperty1<T, List<String>>>().get(compilerArguments),
bucket.freeArgs.toList()
)
KtUsefulTestCase.assertOrderedEquals(
propertiesByName["internalArguments"]!!.cast<KProperty1<T, List<InternalArgument>>>().get(compilerArguments)
.map { it.stringRepresentation },
bucket.internalArguments.toList()
)
return bucket
}
private fun <T : CommonCompilerArguments> createCacheRestoreCompare(klass: Class<out T>, modify: T.() -> Unit = {}) {
val compilerArguments = klass.getDeclaredConstructor().newInstance()
compilerArguments.modify()
val extractedBucket = CompilerArgumentsExtractor.prepareCompilerArgumentsBucket(compilerArguments)
val mapper = CompilerArgumentsCacheMapperImpl()
val cachedArgsBucket = CompilerArgumentsCachingManager.cacheCompilerArguments(extractedBucket, mapper)
val restoreCompilerArguments = CachedArgumentsRestoring::class.java.declaredMethods
.find { it.name == "restoreCachedCompilerArguments" }!!.apply { isAccessible = true }
val restoredCompilerArguments = restoreCompilerArguments.invoke(
CachedArgumentsRestoring::class.java.kotlin.objectInstance,
cachedArgsBucket,
mapper
) as CommonCompilerArguments
assertTrue(checkEquals(compilerArguments, restoredCompilerArguments))
}
@Suppress("UNCHECKED_CAST")
private inline fun <reified T : CommonCompilerArguments> checkEquals(first: T, second: T): Boolean {
val annotatedProperties = T::class.java.kotlin.memberProperties.filter { it.annotations.any { anno -> anno is Argument } }
return annotatedProperties.all { prop ->
when (prop.returnType.classifier) {
Array<String>::class -> Arrays.equals(prop.get(first) as? Array<String>, prop.get(second) as? Array<String>)
else -> prop.get(first) == prop.get(second)
}
} && first.freeArgs == second.freeArgs && first.internalArguments == second.internalArguments
}
companion object {
private val alphabet = ('a'..'z').joinToString(separator = "") + ('A'..'Z').joinToString(separator = "")
private fun generateRandomString(length: Int): String =
generateSequence { Random.nextInt(alphabet.indices) }.take(length).map { alphabet[it] }.joinToString("")
private fun generateRandomStringArray(size: Int): Array<String> =
generateSequence { generateRandomString(10) }.take(size).toList().toTypedArray()
private val commonFlagCompilerArgumentNames = listOf(
"help",
"extraHelp",
"version",
"verbose",
"suppressWarnings",
"allWarningsAsErrors",
"progressiveMode",
"script",
"noInline",
"skipMetadataVersionCheck",
"skipPrereleaseCheck",
"allowKotlinPackage",
"reportOutputFiles",
"multiPlatform",
"noCheckActual",
"inlineClasses",
"polymorphicSignature",
"legacySmartCastAfterTry",
"effectSystem",
"readDeserializedContracts",
"allowResultReturnType",
"properIeee754Comparisons",
"reportPerf",
"listPhases",
"profilePhases",
"checkPhaseConditions",
"checkStickyPhaseConditions",
"useK2",
"useFirExtendedCheckers",
"disableUltraLightClasses",
"useMixedNamedArguments",
"expectActualLinker",
"disableDefaultScriptingPlugin",
"inferenceCompatibility",
"extendedCompilerChecks",
"suppressVersionWarnings"
)
private val commonSingleCompilerArgumentNames = listOf(
"languageVersion",
"apiVersion",
"kotlinHome",
"intellijPluginRoot",
"dumpPerf",
"metadataVersion",
"dumpDirectory",
"dumpOnlyFqName",
"explicitApi",
)
private val commonMultipleCompilerArgumentNames = listOf(
"pluginOptions",
"pluginClasspaths",
"experimental",
"useExperimental",
"optIn",
"commonSources",
"disablePhases",
"verbosePhases",
"phasesToDumpBefore",
"phasesToDumpAfter",
"phasesToDump",
"namesExcludedFromDumping",
"phasesToValidateBefore",
"phasesToValidateAfter",
"phasesToValidate"
)
private val k2MetadataFlagCompilerArgumentNames = commonFlagCompilerArgumentNames + listOf(
"enabledInJps",
)
private val k2MetadataSingleCompilerArgumentNames = commonSingleCompilerArgumentNames + listOf(
"destination",
"moduleName"
)
private val k2MetadataMultipleCompilerArgumentNames = commonMultipleCompilerArgumentNames + listOf(
"friendPaths",
"refinesPaths"
)
private val k2JvmFlagCompilerArgumentNames = commonFlagCompilerArgumentNames + listOf(
"includeRuntime",
"noJdk",
"noStdlib",
"noReflect",
"javaParameters",
"useIR",
"useOldBackend",
"allowUnstableDependencies",
"doNotClearBindingContext",
"noCallAssertions",
"noReceiverAssertions",
"noParamAssertions",
"strictJavaNullabilityAssertions",
"noOptimize",
"inheritMultifileParts",
"useTypeTable",
"skipRuntimeVersionCheck",
"useOldClassFilesReading",
"suppressMissingBuiltinsError",
"useJavac",
"compileJava",
"noExceptionOnExplicitEqualsForBoxedNull",
"disableStandardScript",
"strictMetadataVersionSemantics",
"sanitizeParentheses",
"allowNoSourceFiles",
"emitJvmTypeAnnotations",
"noOptimizedCallableReferences",
"noKotlinNothingValueException",
"noResetJarTimestamps",
"noUnifiedNullChecks",
"useOldSpilledVarTypeAnalysis",
"useOldInlineClassesManglingScheme",
"enableJvmPreview",
"suppressDeprecatedJvmTargetWarning",
"typeEnhancementImprovementsInStrictMode"
)
private val k2JvmSingleCompilerArgumentNames = commonSingleCompilerArgumentNames + listOf(
"destination",
"jdkHome",
"expression",
"moduleName",
"jvmTarget",
"abiStability",
"javaModulePath",
"constructorCallNormalizationMode",
"assertionsMode",
"buildFile",
"declarationsOutputPath",
"javaPackagePrefix",
"supportCompatqualCheckerFrameworkAnnotations",
"jspecifyAnnotations",
"jvmDefault",
"defaultScriptExtension",
"stringConcat",
"klibLibraries",
"profileCompilerCommand",
"repeatCompileModules",
"lambdas",
"samConversions",
)
private val k2JvmMultipleCompilerArgumentNames = commonMultipleCompilerArgumentNames + listOf(
"scriptTemplates",
"additionalJavaModules",
"scriptResolverEnvironment",
"javacArguments",
"javaSourceRoots",
"jsr305",
"friendPaths",
)
private val k2JsFlagCompilerArgumentNames = commonFlagCompilerArgumentNames + listOf(
"noStdlib",
"sourceMap",
"metaInfo",
"irProduceKlibDir",
"irProduceKlibFile",
"irProduceJs",
"irDce",
"irDceDriven",
"irDcePrintReachabilityInfo",
"irPropertyLazyInitialization",
"irOnly",
"irPerModule",
"generateDts",
"typedArrays",
"friendModulesDisabled",
"metadataOnly",
"enableJsScripting",
"fakeOverrideValidator",
"wasm"
)
private val k2JsSingleCompilerArgumentNames = commonSingleCompilerArgumentNames + listOf(
"outputFile",
"libraries",
"sourceMapPrefix",
"sourceMapBaseDirs",
"sourceMapEmbedSources",
"target",
"moduleKind",
"main",
"outputPrefix",
"outputPostfix",
"irModuleName",
"includes",
"friendModules",
"errorTolerancePolicy",
"irDceRuntimeDiagnostic",
"repositries"
)
private val k2JsMultipleCompilerArgumentNames = commonMultipleCompilerArgumentNames
private val flagCompilerArgumentsMap = mapOf(
"DummyImpl" to commonFlagCompilerArgumentNames,
"K2MetadataCompilerArguments" to k2MetadataFlagCompilerArgumentNames,
"K2JVMCompilerArguments" to k2JvmFlagCompilerArgumentNames,
"K2JSCompilerArguments" to k2JsFlagCompilerArgumentNames
)
private val singleCompilerArgumentsMap = mapOf(
"DummyImpl" to commonSingleCompilerArgumentNames,
"K2MetadataCompilerArguments" to k2MetadataSingleCompilerArgumentNames,
"K2JVMCompilerArguments" to k2JvmSingleCompilerArgumentNames,
"K2JSCompilerArguments" to k2JsSingleCompilerArgumentNames
)
private val multipleCompilerArgumentsMap = mapOf(
"DummyImpl" to commonMultipleCompilerArgumentNames,
"K2MetadataCompilerArguments" to k2MetadataMultipleCompilerArgumentNames,
"K2JVMCompilerArguments" to k2JvmMultipleCompilerArgumentNames,
"K2JSCompilerArguments" to k2JsMultipleCompilerArgumentNames
)
}
}
| apache-2.0 | 23b53019ffb990233e907984c4803cfe | 39.745399 | 158 | 0.652789 | 5.469631 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database/src/main/kotlin/com/onyx/lang/map/OptimisticLockingMap.kt | 1 | 2618 | package com.onyx.lang.map
import com.onyx.lang.concurrent.impl.DefaultClosureReadWriteLock
/**
* Created by Tim Osborn on 3/24/17.
*
* This map only locks on write access. It is non blocking for read access.
*/
open class OptimisticLockingMap<K, V>(@Suppress("MemberVisibilityCanPrivate") val m: MutableMap<K, V>) : MutableMap<K, V> {
val lock = DefaultClosureReadWriteLock()
// region Properties
override val entries: MutableSet<MutableMap.MutableEntry<K, V>>
get() = lock.optimisticReadLock { m.entries }
override val keys: MutableSet<K>
get() = lock.optimisticReadLock { m.keys }
override val values: MutableCollection<V>
get() = lock.optimisticReadLock { m.values }
override val size: Int
get() = lock.optimisticReadLock { m.size }
// endregion
// region Overload Read Methods
override fun isEmpty(): Boolean = lock.optimisticReadLock { m.isEmpty() }
override fun containsKey(key: K): Boolean = lock.optimisticReadLock { m.containsKey(key) }
override fun containsValue(value: V): Boolean = lock.optimisticReadLock { m.containsValue(value) }
override operator fun get(key: K): V? = lock.optimisticReadLock { m[key] }
// endregion
// region Overload Write Synchronized Methods
override fun put(key: K, value: V): V? = lock.writeLock { m.put(key, value) }
override fun remove(key: K): V? = lock.writeLock { m.remove(key) }
override fun putAll(from: Map<out K, V>) = lock.writeLock { m.putAll(from) }
override fun clear() = lock.writeLock { m.clear() }
// endregion
/**
* Get or put overridden so that it first uses optimistic locking. If it failed to return a value, check again
* in order to account for a race condition. Lastly put a new value by calling the unit.
*
* I found the Kotlin extension method was not in fact thread safe as the documentation claims with the ConcurrentHashMap
* so this is here to account for that
*
* This does call the get method an extra time. Using this map implies it is heavy on the read access and therefore
* need a non blocking read whereas it is acceptable to have slower write times since it is not write heavy.
*
* @since 2.0.0
*/
inline fun getOrPut(key: K, crossinline body: () -> V): V {
val value: V? = get(key)
return value ?: lock.writeLock {
var newValue = m[key]
if (newValue == null) {
newValue = body.invoke()
m[key] = newValue
}
return@writeLock newValue
}!!
}
}
| agpl-3.0 | e548f1f3d0855c3277efd321d2136245 | 36.942029 | 125 | 0.653934 | 4.155556 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.