repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
jotomo/AndroidAPS
app/src/test/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Dual_BolusTest.kt
1
1429
package info.nightscout.androidaps.danars.comm import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) class DanaRS_Packet_Bolus_Set_Dual_BolusTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { if (it is DanaRS_Packet_Bolus_Set_Dual_Bolus) { it.aapsLogger = aapsLogger } } } @Test fun runTest() { val packet = DanaRS_Packet_Bolus_Set_Dual_Bolus(packetInjector, 0.0, 0.0, 1) // test params val testparams = packet.requestParams Assert.assertEquals(0.toByte(), testparams[0]) Assert.assertEquals(1.toByte(), testparams[4]) // test message decoding packet.handleMessage(createArray(34, 0.toByte())) // DanaRPump testPump = DanaRPump.getInstance(); Assert.assertEquals(false, packet.failed) packet.handleMessage(createArray(34, 1.toByte())) // int valueRequested = (((byte) 1 & 0x000000FF) << 8) + (((byte) 1) & 0x000000FF); // assertEquals(valueRequested /100d, testPump.lastBolusAmount, 0); Assert.assertEquals(true, packet.failed) Assert.assertEquals("BOLUS__SET_DUAL_BOLUS", packet.friendlyName) } }
agpl-3.0
f922aace966d85f5cfe1f67dacaa3468
37.648649
98
0.671099
4.202941
false
true
false
false
mdaniel/intellij-community
platform/built-in-server/src/org/jetbrains/ide/RestService.kt
1
11587
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.ide import com.github.benmanes.caffeine.cache.CacheLoader import com.github.benmanes.caffeine.cache.Caffeine import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonWriter import com.google.gson.stream.MalformedJsonException import com.intellij.ide.IdeBundle import com.intellij.ide.impl.ProjectUtil.showYesNoDialog import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtilRt import com.intellij.openapi.wm.IdeFocusManager import com.intellij.ui.AppIcon import com.intellij.util.ExceptionUtil import com.intellij.util.containers.ContainerUtil import com.intellij.util.io.origin import com.intellij.util.io.referrer import com.intellij.util.net.NetUtils import com.intellij.util.text.nullize import com.intellij.xml.util.XmlStringUtil import io.netty.buffer.ByteBufInputStream import io.netty.buffer.Unpooled import io.netty.channel.Channel import io.netty.channel.ChannelHandlerContext import io.netty.handler.codec.http.* import org.jetbrains.annotations.NonNls import org.jetbrains.builtInWebServer.isSignedRequest import org.jetbrains.ide.RestService.Companion.createJsonReader import org.jetbrains.ide.RestService.Companion.createJsonWriter import org.jetbrains.io.addCommonHeaders import org.jetbrains.io.addNoCache import org.jetbrains.io.response import org.jetbrains.io.send import java.awt.Window import java.io.IOException import java.io.OutputStream import java.lang.reflect.InvocationTargetException import java.net.InetAddress import java.net.InetSocketAddress import java.net.URI import java.net.URISyntaxException import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger /** * Document your service using [apiDoc](http://apidocjs.com). * To extract a big example from source code, consider adding a *.coffee file near the sources * (or Python/Ruby, but CoffeeScript is recommended because it's plugin is lightweight). * See [AboutHttpService] for example. * * Don't create [JsonReader]/[JsonWriter] directly, use only provided [createJsonReader] and [createJsonWriter] methods * (to ensure that you handle in/out according to REST API guidelines). * * @see <a href="http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api">Best Practices for Designing a Pragmatic REST API</a>. */ abstract class RestService : HttpRequestHandler() { companion object { @JvmField val LOG = logger<RestService>() const val PREFIX = "api" @JvmStatic fun activateLastFocusedFrame() { (IdeFocusManager.getGlobalInstance().lastFocusedFrame as? Window)?.toFront() } @JvmStatic fun createJsonReader(request: FullHttpRequest): JsonReader { val reader = JsonReader(ByteBufInputStream(request.content()).reader()) reader.isLenient = true return reader } @JvmStatic fun createJsonWriter(out: OutputStream): JsonWriter { val writer = JsonWriter(out.writer()) writer.setIndent(" ") return writer } @JvmStatic fun getLastFocusedOrOpenedProject(): Project? { return IdeFocusManager.getGlobalInstance().lastFocusedFrame?.project ?: ProjectManager.getInstance().openProjects.firstOrNull() } @JvmStatic fun sendOk(request: FullHttpRequest, context: ChannelHandlerContext) { sendStatus(HttpResponseStatus.OK, HttpUtil.isKeepAlive(request), context.channel()) } @JvmStatic fun sendStatus(status: HttpResponseStatus, keepAlive: Boolean, channel: Channel) { val response = DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status) HttpUtil.setContentLength(response, 0) response.addCommonHeaders() response.addNoCache() if (keepAlive) { HttpUtil.setKeepAlive(response, true) } response.headers().set("X-Frame-Options", "Deny") response.send(channel, !keepAlive) } @JvmStatic fun send(byteOut: BufferExposingByteArrayOutputStream, request: HttpRequest, context: ChannelHandlerContext) { val response = response("application/json", Unpooled.wrappedBuffer(byteOut.internalBuffer, 0, byteOut.size())) sendResponse(request, context, response) } @JvmStatic fun sendResponse(request: HttpRequest, context: ChannelHandlerContext, response: HttpResponse) { response.addNoCache() response.headers().set("X-Frame-Options", "Deny") response.send(context.channel(), request) } @Suppress("SameParameterValue") @JvmStatic fun getStringParameter(name: String, urlDecoder: QueryStringDecoder): String? { return urlDecoder.parameters()[name]?.lastOrNull() } @JvmStatic fun getIntParameter(name: String, urlDecoder: QueryStringDecoder): Int { return StringUtilRt.parseInt(getStringParameter(name, urlDecoder).nullize(nullizeSpaces = true), -1) } @JvmOverloads @JvmStatic fun getBooleanParameter(name: String, urlDecoder: QueryStringDecoder, defaultValue: Boolean = false): Boolean { val values = urlDecoder.parameters()[name] ?: return defaultValue // if just name specified, so, true val value = values.lastOrNull() ?: return true return value.toBoolean() } fun parameterMissedErrorMessage(name: String) = "Parameter \"$name\" is not specified" } protected val gson: Gson by lazy { GsonBuilder() .setPrettyPrinting() .disableHtmlEscaping() .create() } private val abuseCounter = Caffeine.newBuilder() .expireAfterWrite(1, TimeUnit.MINUTES) .build<InetAddress, AtomicInteger>(CacheLoader { AtomicInteger() }) private val trustedOrigins = Caffeine.newBuilder() .maximumSize(1024) .expireAfterWrite(1, TimeUnit.DAYS) .build<String, Boolean>() private val hostLocks = ContainerUtil.createConcurrentWeakKeyWeakValueMap<String, Any>() private var isBlockUnknownHosts = false /** * Service url must be "/api/$serviceName", but to preserve backward compatibility, prefixless path could be also supported */ protected open val isPrefixlessAllowed: Boolean get() = false /** * Use human-readable name or UUID if it is an internal service. */ @NlsSafe protected abstract fun getServiceName(): String override fun isSupported(request: FullHttpRequest): Boolean { if (!isMethodSupported(request.method())) { return false } val uri = request.uri() if (isPrefixlessAllowed && checkPrefix(uri, getServiceName())) { return true } val serviceName = getServiceName() val minLength = 1 + PREFIX.length + 1 + serviceName.length if (uri.length >= minLength && uri[0] == '/' && uri.regionMatches(1, PREFIX, 0, PREFIX.length, ignoreCase = true) && uri.regionMatches(2 + PREFIX.length, serviceName, 0, serviceName.length, ignoreCase = true)) { if (uri.length == minLength) { return true } else { val c = uri[minLength] return c == '/' || c == '?' } } return false } protected open fun isMethodSupported(method: HttpMethod): Boolean { return method === HttpMethod.GET } override fun process(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): Boolean { try { val counter = abuseCounter.get((context.channel().remoteAddress() as InetSocketAddress).address)!! if (counter.incrementAndGet() > Registry.intValue("ide.rest.api.requests.per.minute", 30)) { HttpResponseStatus.TOO_MANY_REQUESTS.orInSafeMode(HttpResponseStatus.OK).send(context.channel(), request) return true } if (!isHostTrusted(request, urlDecoder)) { HttpResponseStatus.FORBIDDEN.orInSafeMode(HttpResponseStatus.OK).send(context.channel(), request) return true } val error = execute(urlDecoder, request, context) if (error != null) { HttpResponseStatus.BAD_REQUEST.send(context.channel(), request, error) } } catch (e: Throwable) { val status: HttpResponseStatus? // JsonReader exception if (e is MalformedJsonException || e is IllegalStateException && e.message!!.startsWith("Expected a ")) { LOG.warn(e) status = HttpResponseStatus.BAD_REQUEST } else { LOG.error(e) status = HttpResponseStatus.INTERNAL_SERVER_ERROR } status.send(context.channel(), request, XmlStringUtil.escapeString(ExceptionUtil.getThrowableText(e))) } return true } @Throws(InterruptedException::class, InvocationTargetException::class) protected open fun isHostTrusted(request: FullHttpRequest, urlDecoder: QueryStringDecoder): Boolean { @Suppress("DEPRECATION") return isHostTrusted(request) } @Deprecated("Use {@link #isHostTrusted(FullHttpRequest, QueryStringDecoder)}") @Throws(InterruptedException::class, InvocationTargetException::class) // e.g. upsource trust to configured host protected open fun isHostTrusted(request: FullHttpRequest): Boolean { if (request.isSignedRequest() || isOriginAllowed(request) == OriginCheckResult.ALLOW) { return true } val referrer = request.origin ?: request.referrer val host = try { if (referrer == null) null else URI(referrer).host.nullize() } catch (ignored: URISyntaxException) { return false } val lock = hostLocks.computeIfAbsent(host ?: "") { Object() } synchronized(lock) { if (host != null) { if (NetUtils.isLocalhost(host)) { return true } else { trustedOrigins.getIfPresent(host)?.let { return it } } } else { if (isBlockUnknownHosts) return false } var isTrusted = false ApplicationManager.getApplication().invokeAndWait( { AppIcon.getInstance().requestAttention(null, true) val message = when (host) { null -> IdeBundle.message("warning.use.rest.api.0.and.trust.host.unknown", getServiceName()) else -> IdeBundle.message("warning.use.rest.api.0.and.trust.host.1", getServiceName(), host) } isTrusted = showYesNoDialog(message, "title.use.rest.api") if (host != null) { trustedOrigins.put(host, isTrusted) } else { if (!isTrusted) { isBlockUnknownHosts = showYesNoDialog(IdeBundle.message("warning.use.rest.api.block.unknown.hosts"), "title.use.rest.api") } } }, ModalityState.any()) return isTrusted } } /** * Return error or send response using [sendOk], [send] */ @Throws(IOException::class) @NonNls abstract fun execute(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): String? } fun HttpResponseStatus.orInSafeMode(safeStatus: HttpResponseStatus): HttpResponseStatus { return if (Registry.`is`("ide.http.server.response.actual.status", true) || ApplicationManager.getApplication()?.isUnitTestMode == true) this else safeStatus }
apache-2.0
11559b0deb455a0f9a4738220513df43
35.322884
159
0.713213
4.519111
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/testData/gradle/testRunConfigurations/expectClassWithTests/src/jsTest/kotlin/sample/SampleTestsJS.kt
3
667
package sample import kotlin.test.Test import kotlin.test.assertTrue // JS actual class <lineMarker descr="Run Test" settings=" cleanJsBrowserTest jsBrowserTest --tests \"sample.SampleTests\" cleanJsNodeTest jsNodeTest --tests \"sample.SampleTests\" --continue"><lineMarker descr="Has declaration in common module">SampleTests</lineMarker></lineMarker> { @Test actual fun <lineMarker descr="Run Test" settings=" cleanJsBrowserTest jsBrowserTest --tests \"sample.SampleTests.testMe\" cleanJsNodeTest jsNodeTest --tests \"sample.SampleTests.testMe\" --continue"><lineMarker descr="Has declaration in common module">testMe</lineMarker></lineMarker>() { } }
apache-2.0
fba60efe3b9f14964a774eed8170ea28
59.727273
292
0.773613
4.631944
false
true
false
false
jwren/intellij-community
plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/compilingEvaluator/inaccessibleMembers/outerMembersNoReflection.kt
3
1276
package ceSuperAccess fun main(args: Array<String>) { A().Inner().test() } class A { public fun publicFun(): Int = 1 public val publicVal: Int = 2 protected fun protectedFun(): Int = 3 protected val protectedVal: Int = 4 @JvmField protected val protectedField: Int = 5 private fun privateFun() = 6 private val privateVal = 7 inner class Inner { fun test() { //Breakpoint! val a = publicFun() } } } fun <T> intBlock(block: () -> T): T { return block() } // REFLECTION_PATCHING: false // EXPRESSION: intBlock { publicFun() } // RESULT: 1: I // EXPRESSION: intBlock { publicVal } // RESULT: Method threw 'java.lang.IllegalAccessError' exception. // EXPRESSION: intBlock { protectedFun() } // RESULT: Method threw 'java.lang.IllegalAccessError' exception. // EXPRESSION: intBlock { protectedVal } // RESULT: Method threw 'java.lang.IllegalAccessError' exception. // EXPRESSION: intBlock { protectedField } // RESULT: Method threw 'java.lang.IllegalAccessError' exception. // EXPRESSION: intBlock { privateFun() } // RESULT: Method threw 'java.lang.VerifyError' exception. // EXPRESSION: intBlock { privateVal } // RESULT: Method threw 'java.lang.IllegalAccessError' exception.
apache-2.0
9c3f53070cf3943a7e8d32ea12490415
23.075472
65
0.666928
3.878419
false
false
false
false
JetBrains/kotlin-native
Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/StubIrElementBuilders.kt
1
34939
/* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package org.jetbrains.kotlin.native.interop.gen import org.jetbrains.kotlin.native.interop.gen.jvm.GenerationMode import org.jetbrains.kotlin.native.interop.gen.jvm.KotlinPlatform import org.jetbrains.kotlin.native.interop.indexer.* internal class MacroConstantStubBuilder( override val context: StubsBuildingContext, private val constant: ConstantDef ) : StubElementBuilder { override fun build(): List<StubIrElement> { val kotlinName = constant.name val origin = StubOrigin.Constant(constant) val declaration = when (constant) { is IntegerConstantDef -> { val literal = context.tryCreateIntegralStub(constant.type, constant.value) ?: return emptyList() val kotlinType = context.mirror(constant.type).argType.toStubIrType() when (context.platform) { KotlinPlatform.NATIVE -> PropertyStub(kotlinName, kotlinType, PropertyStub.Kind.Constant(literal), origin = origin) // No reason to make it const val with backing field on Kotlin/JVM yet: KotlinPlatform.JVM -> { val getter = PropertyAccessor.Getter.SimpleGetter(constant = literal) PropertyStub(kotlinName, kotlinType, PropertyStub.Kind.Val(getter), origin = origin) } } } is FloatingConstantDef -> { val literal = context.tryCreateDoubleStub(constant.type, constant.value) ?: return emptyList() val kind = when (context.generationMode) { GenerationMode.SOURCE_CODE -> { PropertyStub.Kind.Val(PropertyAccessor.Getter.SimpleGetter(constant = literal)) } GenerationMode.METADATA -> { PropertyStub.Kind.Constant(literal) } } val kotlinType = context.mirror(constant.type).argType.toStubIrType() PropertyStub(kotlinName, kotlinType, kind, origin = origin) } is StringConstantDef -> { val literal = StringConstantStub(constant.value) val kind = when (context.generationMode) { GenerationMode.SOURCE_CODE -> { PropertyStub.Kind.Val(PropertyAccessor.Getter.SimpleGetter(constant = literal)) } GenerationMode.METADATA -> { PropertyStub.Kind.Constant(literal) } } PropertyStub(kotlinName, KotlinTypes.string.toStubIrType(), kind, origin = origin) } else -> return emptyList() } return listOf(declaration) } } internal class StructStubBuilder( override val context: StubsBuildingContext, private val decl: StructDecl ) : StubElementBuilder { override fun build(): List<StubIrElement> { val platform = context.platform val def = decl.def ?: return generateForwardStruct(decl) val structAnnotation: AnnotationStub? = if (platform == KotlinPlatform.JVM) { if (def.kind == StructDef.Kind.STRUCT && def.fieldsHaveDefaultAlignment()) { AnnotationStub.CNaturalStruct(def.members) } else { null } } else { tryRenderStructOrUnion(def)?.let { AnnotationStub.CStruct(it) } } val classifier = context.getKotlinClassForPointed(decl) val fields: List<PropertyStub?> = def.fields.map { field -> try { assert(field.name.isNotEmpty()) assert(field.offset % 8 == 0L) val offset = field.offset / 8 val fieldRefType = context.mirror(field.type) val unwrappedFieldType = field.type.unwrapTypedefs() val origin = StubOrigin.StructMember(field) val fieldName = mangleSimple(field.name) if (unwrappedFieldType is ArrayType) { val type = (fieldRefType as TypeMirror.ByValue).valueType val annotations = if (platform == KotlinPlatform.JVM) { val length = getArrayLength(unwrappedFieldType) // TODO: @CLength should probably be used on types instead of properties. listOf(AnnotationStub.CLength(length)) } else { emptyList() } val getter = when (context.generationMode) { GenerationMode.SOURCE_CODE -> PropertyAccessor.Getter.ArrayMemberAt(offset) GenerationMode.METADATA -> PropertyAccessor.Getter.ExternalGetter(listOf(AnnotationStub.CStruct.ArrayMemberAt(offset))) } val kind = PropertyStub.Kind.Val(getter) // TODO: Should receiver be added? PropertyStub(fieldName, type.toStubIrType(), kind, annotations = annotations, origin = origin) } else { val pointedType = fieldRefType.pointedType.toStubIrType() val pointedTypeArgument = TypeArgumentStub(pointedType) if (fieldRefType is TypeMirror.ByValue) { val getter: PropertyAccessor.Getter val setter: PropertyAccessor.Setter when (context.generationMode) { GenerationMode.SOURCE_CODE -> { getter = PropertyAccessor.Getter.MemberAt(offset, typeArguments = listOf(pointedTypeArgument), hasValueAccessor = true) setter = PropertyAccessor.Setter.MemberAt(offset, typeArguments = listOf(pointedTypeArgument)) } GenerationMode.METADATA -> { getter = PropertyAccessor.Getter.ExternalGetter(listOf(AnnotationStub.CStruct.MemberAt(offset))) setter = PropertyAccessor.Setter.ExternalSetter(listOf(AnnotationStub.CStruct.MemberAt(offset))) } } val kind = PropertyStub.Kind.Var(getter, setter) PropertyStub(fieldName, fieldRefType.argType.toStubIrType(), kind, origin = origin) } else { val accessor = when (context.generationMode) { GenerationMode.SOURCE_CODE -> PropertyAccessor.Getter.MemberAt(offset, hasValueAccessor = false) GenerationMode.METADATA -> PropertyAccessor.Getter.ExternalGetter(listOf(AnnotationStub.CStruct.MemberAt(offset))) } val kind = PropertyStub.Kind.Val(accessor) PropertyStub(fieldName, pointedType, kind, origin = origin) } } } catch (e: Throwable) { null } } val bitFields: List<PropertyStub> = def.bitFields.map { field -> val typeMirror = context.mirror(field.type) val typeInfo = typeMirror.info val kotlinType = typeMirror.argType val signed = field.type.isIntegerTypeSigned() val fieldName = mangleSimple(field.name) val kind = when (context.generationMode) { GenerationMode.SOURCE_CODE -> { val readBits = PropertyAccessor.Getter.ReadBits(field.offset, field.size, signed) val writeBits = PropertyAccessor.Setter.WriteBits(field.offset, field.size) context.bridgeComponentsBuilder.getterToBridgeInfo[readBits] = BridgeGenerationInfo("", typeInfo) context.bridgeComponentsBuilder.setterToBridgeInfo[writeBits] = BridgeGenerationInfo("", typeInfo) PropertyStub.Kind.Var(readBits, writeBits) } GenerationMode.METADATA -> { val readBits = PropertyAccessor.Getter.ExternalGetter(listOf(AnnotationStub.CStruct.BitField(field.offset, field.size))) val writeBits = PropertyAccessor.Setter.ExternalSetter(listOf(AnnotationStub.CStruct.BitField(field.offset, field.size))) PropertyStub.Kind.Var(readBits, writeBits) } } PropertyStub(fieldName, kotlinType.toStubIrType(), kind, origin = StubOrigin.StructMember(field)) } val superClass = context.platform.getRuntimeType("CStructVar") require(superClass is ClassifierStubType) val rawPtrConstructorParam = FunctionParameterStub("rawPtr", context.platform.getRuntimeType("NativePtr")) val origin = StubOrigin.Struct(decl) val primaryConstructor = ConstructorStub( parameters = listOf(rawPtrConstructorParam), isPrimary = true, annotations = emptyList(), origin = origin ) val superClassInit = SuperClassInit(superClass, listOf(GetConstructorParameter(rawPtrConstructorParam))) val companionSuper = superClass.nested("Type") val typeSize = listOf(IntegralConstantStub(def.size, 4, true), IntegralConstantStub(def.align.toLong(), 4, true)) val companionSuperInit = SuperClassInit(companionSuper, typeSize) val companionClassifier = classifier.nested("Companion") val annotation = AnnotationStub.CStruct.VarType(def.size, def.align).takeIf { context.generationMode == GenerationMode.METADATA } val companion = ClassStub.Companion( companionClassifier, superClassInit = companionSuperInit, annotations = listOfNotNull(annotation, AnnotationStub.Deprecated.deprecatedCVariableCompanion) ) return listOf(ClassStub.Simple( classifier, origin = origin, properties = fields.filterNotNull() + if (platform == KotlinPlatform.NATIVE) bitFields else emptyList(), constructors = listOf(primaryConstructor), methods = emptyList(), modality = ClassStubModality.NONE, annotations = listOfNotNull(structAnnotation), superClassInit = superClassInit, companion = companion )) } private fun getArrayLength(type: ArrayType): Long { val unwrappedElementType = type.elemType.unwrapTypedefs() val elementLength = if (unwrappedElementType is ArrayType) { getArrayLength(unwrappedElementType) } else { 1L } val elementCount = when (type) { is ConstArrayType -> type.length is IncompleteArrayType -> 0L else -> TODO(type.toString()) } return elementLength * elementCount } private tailrec fun Type.isIntegerTypeSigned(): Boolean = when (this) { is IntegerType -> this.isSigned is BoolType -> false is EnumType -> this.def.baseType.isIntegerTypeSigned() is Typedef -> this.def.aliased.isIntegerTypeSigned() else -> error(this) } /** * Produces to [out] the definition of Kotlin class representing the reference to given forward (incomplete) struct. */ private fun generateForwardStruct(s: StructDecl): List<StubIrElement> = when (context.platform) { KotlinPlatform.JVM -> { val classifier = context.getKotlinClassForPointed(s) val superClass = context.platform.getRuntimeType("COpaque") val rawPtrConstructorParam = FunctionParameterStub("rawPtr", context.platform.getRuntimeType("NativePtr")) val superClassInit = SuperClassInit(superClass, listOf(GetConstructorParameter(rawPtrConstructorParam))) val origin = StubOrigin.Struct(s) val primaryConstructor = ConstructorStub(listOf(rawPtrConstructorParam), emptyList(), isPrimary = true, origin = origin) listOf(ClassStub.Simple( classifier, ClassStubModality.NONE, constructors = listOf(primaryConstructor), superClassInit = superClassInit, origin = origin)) } KotlinPlatform.NATIVE -> emptyList() } } internal class EnumStubBuilder( override val context: StubsBuildingContext, private val enumDef: EnumDef ) : StubElementBuilder { private val classifier = (context.mirror(EnumType(enumDef)) as TypeMirror.ByValue).valueType.classifier private val baseTypeMirror = context.mirror(enumDef.baseType) private val baseType = baseTypeMirror.argType.toStubIrType() override fun build(): List<StubIrElement> { if (!context.isStrictEnum(enumDef)) { return generateEnumAsConstants(enumDef) } val constructorParameter = FunctionParameterStub("value", baseType) val valueProperty = PropertyStub( name = "value", type = baseType, kind = PropertyStub.Kind.Val(PropertyAccessor.Getter.GetConstructorParameter(constructorParameter)), modality = MemberStubModality.OPEN, origin = StubOrigin.Synthetic.EnumValueField(enumDef), isOverride = true) val canonicalsByValue = enumDef.constants .groupingBy { it.value } .reduce { _, accumulator, element -> if (element.isMoreCanonicalThan(accumulator)) { element } else { accumulator } } val (canonicalConstants, aliasConstants) = enumDef.constants.partition { canonicalsByValue[it.value] == it } val canonicalEntriesWithAliases = canonicalConstants .sortedBy { it.value } // TODO: Is it stable enough? .mapIndexed { index, constant -> val literal = context.tryCreateIntegralStub(enumDef.baseType, constant.value) ?: error("Cannot create enum value ${constant.value} of type ${enumDef.baseType}") val entry = EnumEntryStub(mangleSimple(constant.name), literal, StubOrigin.EnumEntry(constant), index) val aliases = aliasConstants .filter { it.value == constant.value } .map { constructAliasProperty(it, entry) } entry to aliases } val origin = StubOrigin.Enum(enumDef) val primaryConstructor = ConstructorStub( parameters = listOf(constructorParameter), annotations = emptyList(), isPrimary = true, origin = origin, visibility = VisibilityModifier.PRIVATE ) val byValueFunction = FunctionStub( name = "byValue", returnType = ClassifierStubType(classifier), parameters = listOf(FunctionParameterStub("value", baseType)), origin = StubOrigin.Synthetic.EnumByValue(enumDef), receiver = null, modality = MemberStubModality.FINAL, annotations = listOf(AnnotationStub.Deprecated.deprecatedCEnumByValue) ) val companion = ClassStub.Companion( classifier = classifier.nested("Companion"), properties = canonicalEntriesWithAliases.flatMap { it.second }, methods = listOf(byValueFunction) ) val enumVarClass = constructEnumVarClass().takeIf { context.generationMode == GenerationMode.METADATA } val kotlinEnumType = ClassifierStubType(Classifier.topLevel("kotlin", "Enum"), listOf(TypeArgumentStub(ClassifierStubType(classifier)))) val enum = ClassStub.Enum( classifier = classifier, superClassInit = SuperClassInit(kotlinEnumType), entries = canonicalEntriesWithAliases.map { it.first }, companion = companion, constructors = listOf(primaryConstructor), properties = listOf(valueProperty), origin = origin, interfaces = listOf(context.platform.getRuntimeType("CEnum")), childrenClasses = listOfNotNull(enumVarClass) ) context.bridgeComponentsBuilder.enumToTypeMirror[enum] = baseTypeMirror return listOf(enum) } private fun constructAliasProperty(enumConstant: EnumConstant, entry: EnumEntryStub): PropertyStub { val aliasAnnotation = AnnotationStub.CEnumEntryAlias(entry.name) .takeIf { context.generationMode == GenerationMode.METADATA } return PropertyStub( enumConstant.name, ClassifierStubType(classifier), kind = PropertyStub.Kind.Val(PropertyAccessor.Getter.GetEnumEntry(entry)), origin = StubOrigin.EnumEntry(enumConstant), annotations = listOfNotNull(aliasAnnotation) ) } private fun constructEnumVarClass(): ClassStub.Simple { val enumVarClassifier = classifier.nested("Var") val rawPtrConstructorParam = FunctionParameterStub("rawPtr", context.platform.getRuntimeType("NativePtr")) val superClass = context.platform.getRuntimeType("CEnumVar") require(superClass is ClassifierStubType) val primaryConstructor = ConstructorStub( parameters = listOf(rawPtrConstructorParam), isPrimary = true, annotations = emptyList(), origin = StubOrigin.Synthetic.DefaultConstructor ) val superClassInit = SuperClassInit(superClass, listOf(GetConstructorParameter(rawPtrConstructorParam))) val baseIntegerTypeSize = when (val unwrappedType = enumDef.baseType.unwrapTypedefs()) { is IntegerType -> unwrappedType.size.toLong() CharType -> 1L else -> error("Incorrect base type for enum ${classifier.fqName}") } val typeSize = IntegralConstantStub(baseIntegerTypeSize, 4, true) val companionSuper = (context.platform.getRuntimeType("CPrimitiveVar") as ClassifierStubType).nested("Type") val varSizeAnnotation = AnnotationStub.CEnumVarTypeSize(baseIntegerTypeSize.toInt()) .takeIf { context.generationMode == GenerationMode.METADATA } val companion = ClassStub.Companion( classifier = enumVarClassifier.nested("Companion"), superClassInit = SuperClassInit(companionSuper, listOf(typeSize)), annotations = listOfNotNull(varSizeAnnotation, AnnotationStub.Deprecated.deprecatedCVariableCompanion) ) val valueProperty = PropertyStub( name = "value", type = ClassifierStubType(classifier), kind = PropertyStub.Kind.Var( PropertyAccessor.Getter.ExternalGetter(), PropertyAccessor.Setter.ExternalSetter() ), origin = StubOrigin.Synthetic.EnumVarValueField(enumDef) ) return ClassStub.Simple( classifier = enumVarClassifier, constructors = listOf(primaryConstructor), superClassInit = superClassInit, companion = companion, modality = ClassStubModality.NONE, origin = StubOrigin.VarOf(StubOrigin.Enum(enumDef)), properties = listOf(valueProperty) ) } private fun EnumConstant.isMoreCanonicalThan(other: EnumConstant): Boolean = with(other.name.toLowerCase()) { contains("min") || contains("max") || contains("first") || contains("last") || contains("begin") || contains("end") } /** * Produces to [out] the Kotlin definitions for given enum which shouldn't be represented as Kotlin enum. */ private fun generateEnumAsConstants(enumDef: EnumDef): List<StubIrElement> { // TODO: if this enum defines e.g. a type of struct field, then it should be generated inside the struct class // to prevent name clashing val entries = mutableListOf<PropertyStub>() val typealiases = mutableListOf<TypealiasStub>() val constants = enumDef.constants.filter { // Macro "overrides" the original enum constant. it.name !in context.macroConstantsByName } val kotlinType: KotlinType val baseKotlinType = context.mirror(enumDef.baseType).argType val meta = if (enumDef.isAnonymous) { kotlinType = baseKotlinType StubContainerMeta(textAtStart = if (constants.isNotEmpty()) "// ${enumDef.spelling}:" else "") } else { val typeMirror = context.mirror(EnumType(enumDef)) if (typeMirror !is TypeMirror.ByValue) { error("unexpected enum type mirror: $typeMirror") } val varTypeName = typeMirror.info.constructPointedType(typeMirror.valueType) val varTypeClassifier = typeMirror.pointedType.classifier val valueTypeClassifier = typeMirror.valueType.classifier val origin = StubOrigin.Enum(enumDef) typealiases += TypealiasStub(varTypeClassifier, varTypeName.toStubIrType(), StubOrigin.VarOf(origin)) typealiases += TypealiasStub(valueTypeClassifier, baseKotlinType.toStubIrType(), origin) kotlinType = typeMirror.valueType StubContainerMeta() } for (constant in constants) { val literal = context.tryCreateIntegralStub(enumDef.baseType, constant.value) ?: continue val kind = when (context.generationMode) { GenerationMode.SOURCE_CODE -> { val getter = PropertyAccessor.Getter.SimpleGetter(constant = literal) PropertyStub.Kind.Val(getter) } GenerationMode.METADATA -> { PropertyStub.Kind.Constant(literal) } } entries += PropertyStub( constant.name, kotlinType.toStubIrType(), kind, MemberStubModality.FINAL, null, origin = StubOrigin.EnumEntry(constant) ) } val container = SimpleStubContainer( meta, properties = entries.toList(), typealiases = typealiases.toList() ) return listOf(container) } } internal class FunctionStubBuilder( override val context: StubsBuildingContext, private val func: FunctionDecl, private val skipOverloads: Boolean = false ) : StubElementBuilder { override fun build(): List<StubIrElement> { val platform = context.platform val parameters = mutableListOf<FunctionParameterStub>() var hasStableParameterNames = true func.parameters.forEachIndexed { index, parameter -> val parameterName = parameter.name.let { if (it == null || it.isEmpty()) { hasStableParameterNames = false "arg$index" } else { it } } val representAsValuesRef = representCFunctionParameterAsValuesRef(parameter.type) parameters += when { representCFunctionParameterAsString(func, parameter.type) -> { val annotations = when (platform) { KotlinPlatform.JVM -> emptyList() KotlinPlatform.NATIVE -> listOf(AnnotationStub.CCall.CString) } val type = KotlinTypes.string.makeNullable().toStubIrType() val functionParameterStub = FunctionParameterStub(parameterName, type, annotations) context.bridgeComponentsBuilder.cStringParameters += functionParameterStub functionParameterStub } representCFunctionParameterAsWString(func, parameter.type) -> { val annotations = when (platform) { KotlinPlatform.JVM -> emptyList() KotlinPlatform.NATIVE -> listOf(AnnotationStub.CCall.WCString) } val type = KotlinTypes.string.makeNullable().toStubIrType() val functionParameterStub = FunctionParameterStub(parameterName, type, annotations) context.bridgeComponentsBuilder.wCStringParameters += functionParameterStub functionParameterStub } representAsValuesRef != null -> { FunctionParameterStub(parameterName, representAsValuesRef.toStubIrType()) } else -> { val mirror = context.mirror(parameter.type) val type = mirror.argType.toStubIrType() FunctionParameterStub(parameterName, type) } } } val returnType = if (func.returnsVoid()) { KotlinTypes.unit } else { context.mirror(func.returnType).argType }.toStubIrType() if (skipOverloads && context.isOverloading(func)) return emptyList() val annotations: List<AnnotationStub> val mustBeExternal: Boolean if (platform == KotlinPlatform.JVM) { annotations = emptyList() mustBeExternal = false } else { if (func.isVararg) { val type = KotlinTypes.any.makeNullable().toStubIrType() parameters += FunctionParameterStub("variadicArguments", type, isVararg = true) } annotations = listOf(AnnotationStub.CCall.Symbol("${context.generateNextUniqueId("knifunptr_")}_${func.name}")) mustBeExternal = true } val functionStub = FunctionStub( func.name, returnType, parameters.toList(), StubOrigin.Function(func), annotations, mustBeExternal, null, MemberStubModality.FINAL, hasStableParameterNames = hasStableParameterNames ) return listOf(functionStub) } private fun FunctionDecl.returnsVoid(): Boolean = this.returnType.unwrapTypedefs() is VoidType private fun representCFunctionParameterAsValuesRef(type: Type): KotlinType? { val pointeeType = when (type) { is PointerType -> type.pointeeType is ArrayType -> type.elemType else -> return null } val unwrappedPointeeType = pointeeType.unwrapTypedefs() if (unwrappedPointeeType is VoidType) { // Represent `void*` as `CValuesRef<*>?`: return KotlinTypes.cValuesRef.typeWith(StarProjection).makeNullable() } if (unwrappedPointeeType is FunctionType) { // Don't represent function pointer as `CValuesRef<T>?` currently: return null } if (unwrappedPointeeType is ArrayType) { return representCFunctionParameterAsValuesRef(pointeeType) } return KotlinTypes.cValuesRef.typeWith(context.mirror(pointeeType).pointedType).makeNullable() } private val platformWStringTypes = setOf("LPCWSTR") private val noStringConversion: Set<String> get() = context.configuration.noStringConversion private fun Type.isAliasOf(names: Set<String>): Boolean { var type = this while (type is Typedef) { if (names.contains(type.def.name)) return true type = type.def.aliased } return false } private fun representCFunctionParameterAsString(function: FunctionDecl, type: Type): Boolean { val unwrappedType = type.unwrapTypedefs() return unwrappedType is PointerType && unwrappedType.pointeeIsConst && unwrappedType.pointeeType.unwrapTypedefs() == CharType && !noStringConversion.contains(function.name) } // We take this approach as generic 'const short*' shall not be used as String. private fun representCFunctionParameterAsWString(function: FunctionDecl, type: Type) = type.isAliasOf(platformWStringTypes) && !noStringConversion.contains(function.name) } internal class GlobalStubBuilder( override val context: StubsBuildingContext, private val global: GlobalDecl ) : StubElementBuilder { override fun build(): List<StubIrElement> { val mirror = context.mirror(global.type) val unwrappedType = global.type.unwrapTypedefs() val origin = StubOrigin.Global(global) val kotlinType: KotlinType val kind: PropertyStub.Kind if (unwrappedType is ArrayType) { kotlinType = (mirror as TypeMirror.ByValue).valueType val getter = when (context.platform) { KotlinPlatform.JVM -> { PropertyAccessor.Getter.SimpleGetter().also { val extra = BridgeGenerationInfo(global.name, mirror.info) context.bridgeComponentsBuilder.arrayGetterBridgeInfo[it] = extra } } KotlinPlatform.NATIVE -> { val cCallAnnotation = AnnotationStub.CCall.Symbol("${context.generateNextUniqueId("knifunptr_")}_${global.name}_getter") PropertyAccessor.Getter.ExternalGetter(listOf(cCallAnnotation)).also { context.wrapperComponentsBuilder.getterToWrapperInfo[it] = WrapperGenerationInfo(global) } } } kind = PropertyStub.Kind.Val(getter) } else { when (mirror) { is TypeMirror.ByValue -> { kotlinType = mirror.argType val getter = when (context.platform) { KotlinPlatform.JVM -> { PropertyAccessor.Getter.SimpleGetter().also { val getterExtra = BridgeGenerationInfo(global.name, mirror.info) context.bridgeComponentsBuilder.getterToBridgeInfo[it] = getterExtra } } KotlinPlatform.NATIVE -> { val cCallAnnotation = AnnotationStub.CCall.Symbol("${context.generateNextUniqueId("knifunptr_")}_${global.name}_getter") PropertyAccessor.Getter.ExternalGetter(listOf(cCallAnnotation)).also { context.wrapperComponentsBuilder.getterToWrapperInfo[it] = WrapperGenerationInfo(global) } } } kind = if (global.isConst) { PropertyStub.Kind.Val(getter) } else { val setter = when (context.platform) { KotlinPlatform.JVM -> { PropertyAccessor.Setter.SimpleSetter().also { val setterExtra = BridgeGenerationInfo(global.name, mirror.info) context.bridgeComponentsBuilder.setterToBridgeInfo[it] = setterExtra } } KotlinPlatform.NATIVE -> { val cCallAnnotation = AnnotationStub.CCall.Symbol("${context.generateNextUniqueId("knifunptr_")}_${global.name}_setter") PropertyAccessor.Setter.ExternalSetter(listOf(cCallAnnotation)).also { context.wrapperComponentsBuilder.setterToWrapperInfo[it] = WrapperGenerationInfo(global) } } } PropertyStub.Kind.Var(getter, setter) } } is TypeMirror.ByRef -> { kotlinType = mirror.pointedType val getter = when (context.generationMode) { GenerationMode.SOURCE_CODE -> { PropertyAccessor.Getter.InterpretPointed(global.name, kotlinType.toStubIrType()) } GenerationMode.METADATA -> { val cCallAnnotation = AnnotationStub.CCall.Symbol("${context.generateNextUniqueId("knifunptr_")}_${global.name}_getter") PropertyAccessor.Getter.ExternalGetter(listOf(cCallAnnotation)).also { context.wrapperComponentsBuilder.getterToWrapperInfo[it] = WrapperGenerationInfo(global, passViaPointer = true) } } } kind = PropertyStub.Kind.Val(getter) } } } return listOf(PropertyStub(global.name, kotlinType.toStubIrType(), kind, origin = origin)) } } internal class TypedefStubBuilder( override val context: StubsBuildingContext, private val typedefDef: TypedefDef ) : StubElementBuilder { override fun build(): List<StubIrElement> { val mirror = context.mirror(Typedef(typedefDef)) val baseMirror = context.mirror(typedefDef.aliased) val varType = mirror.pointedType.classifier val origin = StubOrigin.TypeDef(typedefDef) return when (baseMirror) { is TypeMirror.ByValue -> { val valueType = (mirror as TypeMirror.ByValue).valueType val varTypeAliasee = mirror.info.constructPointedType(valueType) val valueTypeAliasee = baseMirror.valueType listOf( TypealiasStub(varType, varTypeAliasee.toStubIrType(), StubOrigin.VarOf(origin)), TypealiasStub(valueType.classifier, valueTypeAliasee.toStubIrType(), origin) ) } is TypeMirror.ByRef -> { val varTypeAliasee = baseMirror.pointedType listOf(TypealiasStub(varType, varTypeAliasee.toStubIrType(), origin)) } } } }
apache-2.0
c4cf27657b1dbe9405e326f180c0cc80
47.059147
152
0.587567
5.996053
false
false
false
false
jwren/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/search/KotlinSearchUsagesSupportFirImpl.kt
1
12493
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.search import com.intellij.openapi.application.runReadAction import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.SearchScope import com.intellij.psi.search.searches.DefinitionsScopedSearch import com.intellij.psi.search.searches.OverridingMethodsSearch import com.intellij.psi.util.MethodSignatureUtil import com.intellij.util.Processor import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.analyse import org.jetbrains.kotlin.analysis.api.analyseWithReadAction import org.jetbrains.kotlin.analysis.api.calls.KtDelegatedConstructorCall import org.jetbrains.kotlin.analysis.api.calls.symbol import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtPropertySymbol import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithModality import org.jetbrains.kotlin.analysis.api.tokens.HackToForceAllowRunningAnalyzeOnEDT import org.jetbrains.kotlin.analysis.api.tokens.hackyAllowRunningOnEdt import org.jetbrains.kotlin.asJava.classes.KtFakeLightMethod import org.jetbrains.kotlin.asJava.toLightMethods import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.idea.core.isInheritable import org.jetbrains.kotlin.idea.references.unwrappedTargets import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.isOverridable import org.jetbrains.kotlin.idea.search.declarationsSearch.forEachOverridingMethod import org.jetbrains.kotlin.idea.search.declarationsSearch.toPossiblyFakeLightMethods import org.jetbrains.kotlin.idea.search.usagesSearch.getDefaultImports import org.jetbrains.kotlin.idea.stubindex.KotlinTypeAliasShortNameIndex import org.jetbrains.kotlin.idea.util.ProjectRootsUtil import org.jetbrains.kotlin.idea.util.withResolvedCall import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.resolve.ImportPath import org.jetbrains.kotlin.resolve.OverridingUtil import org.jetbrains.kotlin.resolve.descriptorUtil.isTypeRefinementEnabled import org.jetbrains.kotlin.resolve.descriptorUtil.module class KotlinSearchUsagesSupportFirImpl(private val project: Project) : KotlinSearchUsagesSupport { override fun actualsForExpected(declaration: KtDeclaration, module: Module?): Set<KtDeclaration> { return emptySet() } override fun dataClassComponentMethodName(element: KtParameter): String? { return null } override fun hasType(element: KtExpression): Boolean { return false } override fun isSamInterface(psiClass: PsiClass): Boolean { return false } override fun isCallableOverride(subDeclaration: KtDeclaration, superDeclaration: PsiNamedElement): Boolean { return analyse(subDeclaration) { val subSymbol = subDeclaration.getSymbol() as? KtCallableSymbol ?: return false subSymbol.getAllOverriddenSymbols().any { it.psi == superDeclaration } } } override fun isCallableOverrideUsage(reference: PsiReference, declaration: KtNamedDeclaration): Boolean { fun KtDeclaration.isTopLevelCallable() = when (this) { is KtNamedFunction -> isTopLevel is KtProperty -> isTopLevel else -> false } if (declaration.isTopLevelCallable()) return false return reference.unwrappedTargets.any { target -> when (target) { is KtDestructuringDeclarationEntry -> false is KtCallableDeclaration -> { if (target.isTopLevelCallable()) return@any false analyse(target) { val targetSymbol = target.getSymbol() as? KtCallableSymbol ?: return@any false declaration.getSymbol() in targetSymbol.getAllOverriddenSymbols() } } is PsiMethod -> { declaration.toLightMethods().any { superMethod -> MethodSignatureUtil.isSuperMethod(superMethod, target) } } else -> false } } } override fun isUsageInContainingDeclaration(reference: PsiReference, declaration: KtNamedDeclaration): Boolean { return false } override fun isExtensionOfDeclarationClassUsage(reference: PsiReference, declaration: KtNamedDeclaration): Boolean { return false } override fun getReceiverTypeSearcherInfo(psiElement: PsiElement, isDestructionDeclarationSearch: Boolean): ReceiverTypeSearcherInfo? { return null } override fun forceResolveReferences(file: KtFile, elements: List<KtElement>) { } override fun scriptDefinitionExists(file: PsiFile): Boolean { return false } override fun getDefaultImports(file: KtFile): List<ImportPath> { return file.getDefaultImports() } override fun forEachKotlinOverride( ktClass: KtClass, members: List<KtNamedDeclaration>, scope: SearchScope, searchDeeply: Boolean, processor: (superMember: PsiElement, overridingMember: PsiElement) -> Boolean ): Boolean { return false } override fun findSuperMethodsNoWrapping(method: PsiElement): List<PsiElement> { return emptyList() } override fun forEachOverridingMethod(method: PsiMethod, scope: SearchScope, processor: (PsiMethod) -> Boolean): Boolean { if (!findNonKotlinMethodInheritors(method, scope, processor)) return false return findKotlinInheritors(method, scope, processor) } @OptIn(HackToForceAllowRunningAnalyzeOnEDT::class) private fun findKotlinInheritors( method: PsiMethod, scope: SearchScope, processor: (PsiMethod) -> Boolean ): Boolean { val ktMember = method.unwrapped as? KtNamedDeclaration ?: return true val ktClass = runReadAction { ktMember.containingClassOrObject as? KtClass } ?: return true return DefinitionsScopedSearch.search(ktClass, scope, true).forEach(Processor { psiClass -> val inheritor = psiClass.unwrapped as? KtClassOrObject ?: return@Processor true hackyAllowRunningOnEdt { analyseWithReadAction(inheritor) { findMemberInheritors(ktMember, inheritor, processor) } } }) } private fun KtAnalysisSession.findMemberInheritors( superMember: KtNamedDeclaration, targetClass: KtClassOrObject, processor: (PsiMethod) -> Boolean ): Boolean { val originalMemberSymbol = superMember.getSymbol() val inheritorSymbol = targetClass.getClassOrObjectSymbol() val inheritorMembers = inheritorSymbol.getDeclaredMemberScope() .getCallableSymbols { it == superMember.nameAsSafeName } .filter { candidate -> // todo find a cheaper way candidate.getAllOverriddenSymbols().any { it == originalMemberSymbol } } for (member in inheritorMembers) { val lightInheritorMembers = member.psi?.toPossiblyFakeLightMethods()?.distinctBy { it.unwrapped }.orEmpty() for (lightMember in lightInheritorMembers) { if (!processor(lightMember)) { return false } } } return true } private fun findNonKotlinMethodInheritors( method: PsiMethod, scope: SearchScope, processor: (PsiMethod) -> Boolean ): Boolean { if (method !is KtFakeLightMethod) { val query = OverridingMethodsSearch.search(method, scope.excludeKotlinSources(method.project), true) val continueSearching = query.forEach(Processor { processor(it) }) if (!continueSearching) { return false } } return true } override fun findDeepestSuperMethodsNoWrapping(method: PsiElement): List<PsiElement> { return when (val element = method.unwrapped) { is PsiMethod -> element.findDeepestSuperMethods().toList() is KtCallableDeclaration -> analyse(element) { val symbol = element.getSymbol() as? KtCallableSymbol ?: return emptyList() symbol.getAllOverriddenSymbols() .filter { when (it) { is KtFunctionSymbol -> it.isOverride is KtPropertySymbol -> it.isOverride else -> false } }.mapNotNull { it.psi } } else -> emptyList() } } override fun findTypeAliasByShortName(shortName: String, project: Project, scope: GlobalSearchScope): Collection<KtTypeAlias> { return KotlinTypeAliasShortNameIndex.get(shortName, project, scope) } override fun isInProjectSource(element: PsiElement, includeScriptsOutsideSourceRoots: Boolean): Boolean { return ProjectRootsUtil.isInProjectSource(element, includeScriptsOutsideSourceRoots) } override fun isOverridable(declaration: KtDeclaration): Boolean { val parent = declaration.parent if (!(parent is KtClassBody || parent is KtParameterList)) return false val klass = if (parent.parent is KtPrimaryConstructor) parent.parent.parent as? KtClass else parent.parent as? KtClass if (klass == null || (!klass.isInheritable() && !klass.isEnum())) return false if (declaration.hasModifier(KtTokens.PRIVATE_KEYWORD)) { // 'private' is incompatible with 'open' return false } return isOverridableBySymbol(declaration) } override fun isInheritable(ktClass: KtClass): Boolean = isOverridableBySymbol(ktClass) private fun isOverridableBySymbol(declaration: KtDeclaration) = analyseWithReadAction(declaration) { val symbol = declaration.getSymbol() as? KtSymbolWithModality ?: return@analyseWithReadAction false when (symbol.modality) { Modality.OPEN, Modality.SEALED, Modality.ABSTRACT -> true Modality.FINAL -> false } } override fun formatJavaOrLightMethod(method: PsiMethod): String { return "FORMAT JAVA OR LIGHT METHOD ${method.name}" } override fun formatClass(classOrObject: KtClassOrObject): String { return "FORMAT CLASS ${classOrObject.name}" } override fun expectedDeclarationIfAny(declaration: KtDeclaration): KtDeclaration? { return null } override fun isExpectDeclaration(declaration: KtDeclaration): Boolean { return false } override fun canBeResolvedWithFrontEnd(element: PsiElement): Boolean { //TODO FIR: Is the same as PsiElement.hasJavaResolutionFacade() as for FIR? return element.originalElement.containingFile != null } override fun createConstructorHandle(ktDeclaration: KtDeclaration): KotlinSearchUsagesSupport.ConstructorCallHandle { return object : KotlinSearchUsagesSupport.ConstructorCallHandle { override fun referencedTo(element: KtElement): Boolean { val callExpression = element.getNonStrictParentOfType<KtCallElement>() ?: return false return withResolvedCall(callExpression) { call -> when (call) { is KtDelegatedConstructorCall -> call.symbol == ktDeclaration.getSymbol() else -> false } } ?: false } } } override fun createConstructorHandle(psiMethod: PsiMethod): KotlinSearchUsagesSupport.ConstructorCallHandle { //TODO FIR: This is the stub. Need to implement return object : KotlinSearchUsagesSupport.ConstructorCallHandle { override fun referencedTo(element: KtElement): Boolean { return false } } } }
apache-2.0
4400582ff56921d2c4e9d85e7f1e15d8
40.643333
138
0.688866
5.508377
false
false
false
false
googlecodelabs/android-dagger-to-hilt
app/src/main/java/com/example/android/dagger/login/LoginViewModel.kt
1
1538
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.dagger.login import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.example.android.dagger.user.UserManager import javax.inject.Inject /** * LoginViewModel is the ViewModel that [LoginActivity] uses to * obtain information of what to show on the screen and handle complex logic. */ class LoginViewModel @Inject constructor(private val userManager: UserManager) { private val _loginState = MutableLiveData<LoginViewState>() val loginState: LiveData<LoginViewState> get() = _loginState fun login(username: String, password: String) { if (userManager.loginUser(username, password)) { _loginState.value = LoginSuccess } else { _loginState.value = LoginError } } fun unregister() { userManager.unregister() } fun getUsername(): String = userManager.username }
apache-2.0
f0f6388c6ea2e577dbf47d4a6a51de3c
31.723404
80
0.720416
4.523529
false
false
false
false
GunoH/intellij-community
plugins/git4idea/src/git4idea/index/GitStageCommitWorkflow.kt
2
2094
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.index import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.FileStatus import com.intellij.vcs.commit.CommitSessionInfo import com.intellij.vcs.commit.NonModalCommitWorkflow import com.intellij.vcs.commit.isCleanupCommitMessage import git4idea.GitVcs import git4idea.i18n.GitBundle.message import git4idea.repo.GitCommitTemplateTracker private val LOG = logger<GitStageCommitWorkflow>() private fun GitStageTracker.RootState.getFullyStagedPaths(): Collection<FilePath> = statuses.values .filter { it.getStagedStatus() != null && it.getStagedStatus() != FileStatus.DELETED && it.getUnStagedStatus() == null } .map { it.path(ContentVersion.STAGED) } class GitStageCommitWorkflow(project: Project) : NonModalCommitWorkflow(project) { override val isDefaultCommitEnabled: Boolean get() = true internal var trackerState: GitStageTracker.State = GitStageTracker.State.EMPTY internal lateinit var commitState: GitStageCommitState init { updateVcses(setOf(GitVcs.getInstance(project))) } override fun performCommit(sessionInfo: CommitSessionInfo) { assert(sessionInfo.isVcsCommit) { "Custom commit sessions are not supported with staging area: ${sessionInfo.executor.toString()}" } LOG.debug("Do actual commit") commitContext.isCleanupCommitMessage = project.service<GitCommitTemplateTracker>().exists() val fullyStaged = trackerState.rootStates.filter { commitState.roots.contains(it.key) }.mapValues { it.value.getFullyStagedPaths() } val committer = GitStageCommitter(project, commitState, fullyStaged, commitContext) addCommonResultHandlers(sessionInfo, committer) committer.addResultHandler(GitStageShowNotificationCommitResultHandler(committer)) committer.runCommit(message("stage.commit.process"), false) } }
apache-2.0
2f266624a71c10e28ce74db66fd15ed7
40.88
136
0.792264
4.522678
false
false
false
false
GunoH/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/actions/PkgsToDAAction.kt
2
5646
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * 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.jetbrains.packagesearch.intellij.plugin.actions import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DataKey import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.externalSystem.dependency.analyzer.DAArtifact import com.intellij.openapi.externalSystem.dependency.analyzer.DependencyAnalyzerManager import com.intellij.openapi.externalSystem.model.ProjectSystemId import com.intellij.openapi.module.Module import com.intellij.openapi.ui.popup.JBPopupFactory import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel import org.jetbrains.annotations.Nls internal class PkgsToDAAction : AnAction( /* text = */ PackageSearchBundle.message("packagesearch.quickfix.packagesearch.action.da"), /* description = */ PackageSearchBundle.message("packagesearch.quickfix.packagesearch.action.da.description"), /* icon = */ null ) { companion object { val PACKAGES_LIST_PANEL_DATA_KEY: DataKey<PackageModel.Installed?> = DataKey.create("packageSearch.packagesListPanelDataKey") } override fun isDumbAware() = true override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun update(e: AnActionEvent) { val data = e.getData(PACKAGES_LIST_PANEL_DATA_KEY) with(e.presentation) { val hasData = data != null && data.usageInfo.any { it.projectModule.buildSystemType.dependencyAnalyzerKey != null } isEnabledAndVisible = hasData if (hasData) { text = PackageSearchBundle.message( "packagesearch.quickfix.packagesearch.action.da.withIdentifier", data!!.identifier.rawValue ) description = PackageSearchBundle.message( "packagesearch.quickfix.packagesearch.action.da.description.withParam", data.identifier.rawValue ) } } } override fun actionPerformed(e: AnActionEvent) { val data = e.getData(PACKAGES_LIST_PANEL_DATA_KEY) ?: return val dependencyAnalyzerSupportedUsages = data.usageInfo.filter { it.projectModule.buildSystemType.dependencyAnalyzerKey != null } if (dependencyAnalyzerSupportedUsages.size > 1) { val defaultActionGroup = buildActionGroup { dependencyAnalyzerSupportedUsages.forEach { usage -> add(usage.projectModule.name) { navigateToDA( group = data.groupId, artifact = data.artifactId, version = usage.getDeclaredVersionOrFallback().versionName, module = usage.projectModule.nativeModule, systemId = usage.projectModule.buildSystemType.dependencyAnalyzerKey!! ) } } } @Suppress("DialogTitleCapitalization") val popup = JBPopupFactory.getInstance().createActionGroupPopup( PackageSearchBundle.message("packagesearch.quickfix.packagesearch.action.da.selectModule", data.identifier.rawValue), defaultActionGroup, e.dataContext, JBPopupFactory.ActionSelectionAid.NUMBERING, true, null, 10 ) e.project?.let { popup.showCenteredInCurrentWindow(it) } ?: popup.showInBestPositionFor(e.dataContext) } else { val usage = data.usageInfo.single() navigateToDA( group = data.groupId, artifact = data.artifactId, version = usage.getDeclaredVersionOrFallback().versionName, module = usage.projectModule.nativeModule, systemId = usage.projectModule.buildSystemType.dependencyAnalyzerKey!! ) } } @Suppress("HardCodedStringLiteral") private fun navigateToDA(group: String, artifact: String, version: String, module: Module, systemId: ProjectSystemId) = DependencyAnalyzerManager.getInstance(module.project) .getOrCreate(systemId) .setSelectedDependency( module = module, data = DAArtifact(group, artifact, version) ) } fun buildActionGroup(builder: DefaultActionGroup.() -> Unit) = DefaultActionGroup().apply(builder) private fun DefaultActionGroup.add(@Nls title: String, actionPerformed: (AnActionEvent) -> Unit) = add(object : AnAction(title) { override fun actionPerformed(e: AnActionEvent) = actionPerformed(e) })
apache-2.0
29bfba816969929fb152bbf7f8fa882d
44.902439
136
0.651258
5.382269
false
false
false
false
JetBrains/kotlin-native
shared/src/library/kotlin/org/jetbrains/kotlin/konan/library/KonanLibraryLayout.kt
4
1861
/** * Copyright 2010-2019 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.konan.library import org.jetbrains.kotlin.konan.file.File import org.jetbrains.kotlin.konan.target.KonanTarget import org.jetbrains.kotlin.library.IrKotlinLibraryLayout import org.jetbrains.kotlin.library.KotlinLibraryLayout import org.jetbrains.kotlin.library.MetadataKotlinLibraryLayout interface TargetedKotlinLibraryLayout : KotlinLibraryLayout { val target: KonanTarget? // This is a default implementation. Can't make it an assignment. get() = null val targetsDir get() = File(componentDir, "targets") val targetDir get() = File(targetsDir, target!!.visibleName) val includedDir get() = File(targetDir, "included") } interface BitcodeKotlinLibraryLayout : TargetedKotlinLibraryLayout, KotlinLibraryLayout { val kotlinDir get() = File(targetDir, "kotlin") val nativeDir get() = File(targetDir, "native") // TODO: Experiment with separate bitcode files. // Per package or per class. val mainBitcodeFile get() = File(kotlinDir, "program.kt.bc") val mainBitcodeFileName get() = mainBitcodeFile.path } interface KonanLibraryLayout : MetadataKotlinLibraryLayout, BitcodeKotlinLibraryLayout, IrKotlinLibraryLayout
apache-2.0
dc1d64a12985b3e7ed729314590471af
36.22
109
0.739925
4.337995
false
false
false
false
googlecodelabs/android-dagger-to-hilt
app/src/main/java/com/example/android/dagger/registration/enterdetails/EnterDetailsFragment.kt
1
4239
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.dagger.registration.enterdetails import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.EditText import android.widget.TextView import androidx.core.widget.doOnTextChanged import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import com.example.android.dagger.R import com.example.android.dagger.registration.RegistrationActivity import com.example.android.dagger.registration.RegistrationViewModel import javax.inject.Inject class EnterDetailsFragment : Fragment() { /** * RegistrationViewModel is used to set the username and password information (attached to * Activity's lifecycle and shared between different fragments) * EnterDetailsViewModel is used to validate the user input (attached to this * Fragment's lifecycle) * * They could get combined but for the sake of the codelab, we're separating them so we have * different ViewModels with different lifecycles. * * @Inject annotated fields will be provided by Dagger */ @Inject lateinit var registrationViewModel: RegistrationViewModel @Inject lateinit var enterDetailsViewModel: EnterDetailsViewModel private lateinit var errorTextView: TextView private lateinit var usernameEditText: EditText private lateinit var passwordEditText: EditText override fun onAttach(context: Context) { super.onAttach(context) // Grabs the registrationComponent from the Activity and injects this Fragment (activity as RegistrationActivity).registrationComponent.inject(this) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_enter_details, container, false) enterDetailsViewModel.enterDetailsState.observe(this, Observer<EnterDetailsViewState> { state -> when (state) { is EnterDetailsSuccess -> { val username = usernameEditText.text.toString() val password = passwordEditText.text.toString() registrationViewModel.updateUserData(username, password) (activity as RegistrationActivity).onDetailsEntered() } is EnterDetailsError -> { errorTextView.text = state.error errorTextView.visibility = View.VISIBLE } } }) setupViews(view) return view } private fun setupViews(view: View) { errorTextView = view.findViewById(R.id.error) usernameEditText = view.findViewById(R.id.username) usernameEditText.doOnTextChanged { _, _, _, _ -> errorTextView.visibility = View.INVISIBLE } passwordEditText = view.findViewById(R.id.password) passwordEditText.doOnTextChanged { _, _, _, _ -> errorTextView.visibility = View.INVISIBLE } view.findViewById<Button>(R.id.next).setOnClickListener { val username = usernameEditText.text.toString() val password = passwordEditText.text.toString() enterDetailsViewModel.validateInput(username, password) } } } sealed class EnterDetailsViewState object EnterDetailsSuccess : EnterDetailsViewState() data class EnterDetailsError(val error: String) : EnterDetailsViewState()
apache-2.0
d96f6873645f245c4cbe0e63d844adc2
36.513274
100
0.697806
5.088836
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinDoubleNegationInspection.kt
2
2524
// 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.codeInspection.* import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtParenthesizedExpression import org.jetbrains.kotlin.psi.KtPrefixExpression import org.jetbrains.kotlin.psi.prefixExpressionVisitor import org.jetbrains.kotlin.resolve.calls.callUtil.getType import org.jetbrains.kotlin.types.typeUtil.isBoolean class KotlinDoubleNegationInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) = prefixExpressionVisitor(fun(expression) { if (expression.operationToken != KtTokens.EXCL || expression.baseExpression?.getType(expression.analyze())?.isBoolean() != true ) { return } var parent = expression.parent while (parent is KtParenthesizedExpression) { parent = parent.parent } if (parent is KtPrefixExpression && parent.operationToken == KtTokens.EXCL) { holder.registerProblem( expression, KotlinBundle.message("redundant.double.negation"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, DoubleNegationFix() ) } }) private class DoubleNegationFix : LocalQuickFix { override fun getName() = KotlinBundle.message("double.negation.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { applyFix(descriptor.psiElement as? KtPrefixExpression ?: return) } private fun applyFix(expression: KtPrefixExpression) { var parent = expression.parent while (parent is KtParenthesizedExpression) { parent = parent.parent } if (parent is KtPrefixExpression && parent.operationToken == KtTokens.EXCL) { expression.baseExpression?.let { parent.replaced(it) } } } } }
apache-2.0
e5fb3abd78238dc4ce3d346c33d3b021
43.298246
158
0.675119
5.370213
false
false
false
false
smmribeiro/intellij-community
platform/configuration-store-impl/src/ProjectStateStorageManager.kt
9
3087
// 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.configurationStore import com.intellij.openapi.components.PathMacroSubstitutor import com.intellij.openapi.components.StateStorageOperation import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.project.Project import com.intellij.openapi.project.isExternalStorageEnabled import com.intellij.openapi.vfs.VirtualFile import com.intellij.serviceContainer.ComponentManagerImpl import org.jdom.Element import org.jetbrains.annotations.ApiStatus import java.nio.file.Path // extended in upsource open class ProjectStateStorageManager(macroSubstitutor: PathMacroSubstitutor, private val project: Project, useVirtualFileTracker: Boolean = true) : StateStorageManagerImpl(ROOT_TAG_NAME, macroSubstitutor, if (useVirtualFileTracker) project else null) { companion object { internal const val VERSION_OPTION = "version" const val ROOT_TAG_NAME = "project" } private val fileBasedStorageConfiguration = object : FileBasedStorageConfiguration { override val isUseVfsForWrite: Boolean get() = true override val isUseVfsForRead: Boolean get() = project is VirtualFileResolver override fun resolveVirtualFile(path: String, reasonOperation: StateStorageOperation): VirtualFile? { return when (project) { is VirtualFileResolver -> project.resolveVirtualFile(path, reasonOperation) else -> super.resolveVirtualFile(path, reasonOperation) } } } override fun getFileBasedStorageConfiguration(fileSpec: String): FileBasedStorageConfiguration { return when { isSpecialStorage(fileSpec) -> appFileBasedStorageConfiguration else -> fileBasedStorageConfiguration } } override fun normalizeFileSpec(fileSpec: String) = removeMacroIfStartsWith(super.normalizeFileSpec(fileSpec), PROJECT_CONFIG_DIR) override fun expandMacro(collapsedPath: String): Path { if (collapsedPath[0] == '$') { return super.expandMacro(collapsedPath) } else { // PROJECT_CONFIG_DIR is the first macro return macros.get(0).value.resolve(collapsedPath) } } override fun beforeElementSaved(elements: MutableList<Element>, rootAttributes: MutableMap<String, String>) { rootAttributes.put(VERSION_OPTION, "4") } override fun getOldStorageSpec(component: Any, componentName: String, operation: StateStorageOperation): String { if (ComponentManagerImpl.badWorkspaceComponents.contains(componentName)) { return StoragePathMacros.WORKSPACE_FILE } else { return PROJECT_FILE } } override val isExternalSystemStorageEnabled: Boolean get() = project.isExternalStorageEnabled } // for upsource @ApiStatus.Experimental interface VirtualFileResolver { @JvmDefault fun resolveVirtualFile(path: String, reasonOperation: StateStorageOperation) = doResolveVirtualFile(path, reasonOperation) }
apache-2.0
2598a8d6e3dc984698ad2f1c191b1c47
37.6
183
0.756398
5.214527
false
true
false
false
gregcockroft/AndroidMath
mathdisplaylib/src/main/java/com/agog/mathdisplay/parse/MTMathTable.kt
1
3507
package com.agog.mathdisplay.parse /** @typedef MTColumnAlignment @brief Alignment for a column of MTMathTable */ enum class MTColumnAlignment { /// Align left. KMTColumnAlignmentLeft, /// Align center. KMTColumnAlignmentCenter, /// Align right. KMTColumnAlignmentRight } class MTMathTable() : MTMathAtom(MTMathAtomType.KMTMathAtomTable, "") { private var alignments = mutableListOf<MTColumnAlignment>() // 2D variable size array of MathLists var cells: MutableList<MutableList<MTMathList>> = mutableListOf() /// The name of the environment that this table denotes. var environment: String? = null /// Spacing between each column in mu units. var interColumnSpacing: Float = 0.0f /// Additional spacing between rows in jots (one jot is 0.3 times font size). /// If the additional spacing is 0, then normal row spacing is used are used. var interRowAdditionalSpacing: Float = 0.0f constructor(env: String?) : this() { environment = env } override fun copyDeep(): MTMathTable { val atom = MTMathTable(environment) super.copyDeepContent(atom) atom.alignments = mutableListOf() atom.alignments.addAll(this.alignments.toSet()) atom.cells = mutableListOf() for (row in this.cells) { val newrow = mutableListOf<MTMathList>() for (i in 0 until row.size) { val newcol = row[i].copyDeep() newrow.add(newcol) } atom.cells.add(newrow) } atom.interColumnSpacing = this.interColumnSpacing atom.interRowAdditionalSpacing = this.interRowAdditionalSpacing return atom } override fun finalized(): MTMathTable { val newMathTable = this.copyDeep() super.finalized(newMathTable) for (row in newMathTable.cells) { for (i in 0 until row.size) { row[i] = row[i].finalized() } } return newMathTable } fun setCell(list: MTMathList, row: Int, column: Int) { if (this.cells.size <= row) { // Add more rows var i: Int = this.cells.size while (i <= row) { this.cells.add(i++, mutableListOf()) } } val rowArray: MutableList<MTMathList> = this.cells[row] if (rowArray.size <= column) { // Add more columns var i: Int = rowArray.size while (i <= column) { rowArray.add(i++, MTMathList()) } } rowArray[column] = list } fun setAlignment(alignment: MTColumnAlignment, column: Int) { if (this.alignments.size <= column) { // Add more columns var i: Int = this.alignments.size while (i <= column) { this.alignments.add(i++, MTColumnAlignment.KMTColumnAlignmentCenter) } } this.alignments[column] = alignment } fun getAlignmentForColumn(column: Int): MTColumnAlignment { if (this.alignments.size <= column) { return MTColumnAlignment.KMTColumnAlignmentCenter } else { return this.alignments[column] } } fun numColumns(): Int { var numColumns = 0 for (row in this.cells) { numColumns = maxOf(numColumns, row.size) } return numColumns } fun numRows(): Int { return this.cells.size } }
mit
45aa58296caaefbc2f7240146fbb785d
26.614173
84
0.586826
4.256068
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/editor/body/usecases/GetFileParameterDialogUseCase.kt
1
3278
package ch.rmy.android.http_shortcuts.activities.editor.body.usecases import android.view.View import android.widget.EditText import androidx.annotation.CheckResult import androidx.core.view.isVisible import ch.rmy.android.framework.extensions.doOnTextChanged import ch.rmy.android.framework.extensions.runIf import ch.rmy.android.framework.extensions.showSoftKeyboard import ch.rmy.android.framework.utils.localization.Localizable import ch.rmy.android.framework.viewmodel.viewstate.DialogState import ch.rmy.android.http_shortcuts.R import ch.rmy.android.http_shortcuts.extensions.createDialogState import ch.rmy.android.http_shortcuts.variables.VariableButton import ch.rmy.android.http_shortcuts.variables.VariableEditText import ch.rmy.android.http_shortcuts.variables.VariableViewUtils import com.afollestad.materialdialogs.WhichButton import com.afollestad.materialdialogs.actions.getActionButton import javax.inject.Inject class GetFileParameterDialogUseCase @Inject constructor( private val variableViewUtils: VariableViewUtils, ) { @CheckResult operator fun invoke( title: Localizable, showRemoveOption: Boolean = false, showFileNameOption: Boolean = false, keyName: String = "", fileName: String = "", onConfirm: (keyName: String, fileName: String) -> Unit, onRemove: () -> Unit, ): DialogState { return createDialogState(id = "get-file-parameter") { view(R.layout.dialog_file_parameter_editor) .title(title) .canceledOnTouchOutside(false) .positive(R.string.dialog_ok) { dialog -> val keyField = dialog.findViewById<VariableEditText>(R.id.key_value_key) val fileNameField = dialog.findViewById<EditText>(R.id.key_file_name) val keyText = keyField.rawString onConfirm(keyText, fileNameField.text.toString()) } .runIf(showRemoveOption) { neutral(R.string.dialog_remove) { onRemove() } } .negative(R.string.dialog_cancel) .build() .also { dialog -> val keyInput = dialog.findViewById<VariableEditText>(R.id.key_value_key) val fileNameInput = dialog.findViewById<EditText>(R.id.key_file_name) val keyVariableButton = dialog.findViewById(R.id.variable_button_key) as VariableButton variableViewUtils.bindVariableViews(keyInput, keyVariableButton) keyInput.rawString = keyName fileNameInput.setText(fileName) dialog.findViewById<View>(R.id.file_name_input_container).isVisible = showFileNameOption dialog.setOnShowListener { keyInput.showSoftKeyboard() } val okButton = dialog.getActionButton(WhichButton.POSITIVE) okButton.isEnabled = keyInput.text.isNotEmpty() keyInput.doOnTextChanged { text -> okButton.isEnabled = text.isNotEmpty() } } } } }
mit
64b825c151a39bff72e266d82f65772c
40.493671
108
0.638194
4.863501
false
false
false
false
juzraai/ted-xml-model
src/main/kotlin/hu/juzraai/ted/xml/model/tedexport/LinksSection.kt
1
1002
package hu.juzraai.ted.xml.model.tedexport import hu.juzraai.ted.xml.model.meta.Compatible import hu.juzraai.ted.xml.model.meta.TedXmlSchemaVersion.R208 import hu.juzraai.ted.xml.model.meta.TedXmlSchemaVersion.R209 import hu.juzraai.ted.xml.model.tedexport.links.Link import org.simpleframework.xml.Element import org.simpleframework.xml.Root @Root(name = "LINKS_SECTION") data class LinksSection( @field:Element(name = "XML_SCHEMA_DEFINITION_LINK") @field:Compatible(R208, R209) var xmlSchemaDefinitionLink: Link = Link(), @field:Element(name = "OFFICIAL_FORMS_LINK") @field:Compatible(R208, R209) var officialFormsLink: Link = Link(), @field:Element(name = "FORMS_LABELS_LINK") @field:Compatible(R208, R209) var formsLabelsLink: Link = Link(), @field:Element(name = "ORIGINAL_CPV_LINK") @field:Compatible(R208, R209) var originalCpvLink: Link = Link(), @field:Element(name = "ORIGINAL_NUTS_LINK") @field:Compatible(R208, R209) var originalNutsLink: Link = Link() )
apache-2.0
5db88631a57f0e8a73dd7fca751f42df
31.354839
61
0.752495
2.973294
false
false
false
false
xaethos/tracker-notifier
app/src/main/java/net/xaethos/trackernotifier/utils/ViewUtils.kt
1
3188
package net.xaethos.trackernotifier.utils import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.content.res.Resources import android.view.View import android.widget.TextView /** * Fades-in a hidden view while fading out some others * @param showView the view to show * * * @param hideViews the views to hide */ fun switchVisible(showView: View, vararg hideViews: View) { val animTime = getShortAnimTime(showView.resources) if (showView.visibility != View.VISIBLE) { showView.visibility = View.VISIBLE showView.animate() .setDuration(animTime) .alpha(1f) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { showView.visibility = View.VISIBLE } }) showView.animate().setDuration(animTime).alpha(1f).setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { showView.visibility = View.VISIBLE } }) } for (hideView in hideViews) { if (hideView.visibility == View.GONE) continue hideView.visibility = View.GONE hideView.animate() .setDuration(animTime) .alpha(0f) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { hideView.visibility = View.GONE } }) } } /** * Fades a view in or out * @param showView the view to affect * * * @param visible whether to show or hide the view */ fun View?.animateVisible(visible: Boolean) { if (this == null) return; val visibility = if (visible) View.VISIBLE else View.GONE if (this.visibility == visibility) return this.visibility = visibility this.animate() .setDuration(getShortAnimTime(this.resources)) .alpha((if (visible) 1f else 0f)) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { [email protected] = visibility } }) } /** * Set the text on the given view, and make it visible. If the text is empty or null, the * view will be hidden. * * * If the view is not a [TextView], nothing will be done. * @param textView the TextView on which to set the text * * * @param text */ fun setTextOrHide(textView: View?, text: CharSequence?) { if (textView is TextView) textView.setTextOrHide(text) } fun TextView.setTextOrHide(textRes: Int) { this.setTextOrHide(if (textRes == 0) null else context.getText(textRes)) } fun TextView.setTextOrHide(text: CharSequence?) { if (text.empty) { this.text = null this.visibility = View.GONE } else { this.text = text this.visibility = View.VISIBLE } } private fun getShortAnimTime(resources: Resources): Long { return resources.getInteger(android.R.integer.config_shortAnimTime).toLong() }
mit
e2161b6591849384b40f7dfc6c8650da
29.653846
107
0.625784
4.452514
false
false
false
false
aosp-mirror/platform_frameworks_support
buildSrc/src/main/kotlin/androidx/build/checkapi/CheckApiTask.kt
1
7888
/* * Copyright 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.build.checkapi import androidx.build.doclava.ChecksConfig import org.gradle.api.DefaultTask import org.gradle.api.GradleException import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.InputFiles import org.gradle.api.tasks.Optional import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.TaskAction import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.File import java.security.MessageDigest /** Character that resets console output color. */ private const val ANSI_RESET = "\u001B[0m" /** Character that sets console output color to red. */ private const val ANSI_RED = "\u001B[31m" /** Character that sets console output color to yellow. */ private const val ANSI_YELLOW = "\u001B[33m" private val ERROR_REGEX = Regex("^(.+):(.+): (\\w+) (\\d+): (.+)$") private fun ByteArray.encodeHex() = fold(StringBuilder(), { builder, byte -> val hexString = Integer.toHexString(byte.toInt() and 0xFF) if (hexString.length < 2) { builder.append("0") } builder.append(hexString) }).toString() private fun getShortHash(src: String): String { val str = MessageDigest.getInstance("SHA-1") .digest(src.toByteArray()).encodeHex() val len = str.length return str.substring(len - 7, len) } /** * Task used to verify changes between two API files. * <p> * This task may be configured to ignore, warn, or fail with a message for a specific set of * Doclava-defined error codes. See {@link com.google.doclava.Errors} for a complete list of * supported error codes. * <p> * Specific failures may be ignored by specifying a list of SHAs in {@link #whitelistErrors}. Each * SHA is unique to a specific API change and is logged to the error output on failure. */ open class CheckApiTask : DefaultTask() { /** API file that represents the existing API surface. */ @Optional @InputFile var oldApiFile: File? = null /** API file that represents the existing API surface's removals. */ @Optional @InputFile var oldRemovedApiFile: File? = null /** API file that represents the candidate API surface. */ @InputFile lateinit var newApiFile: File /** API file that represents the candidate API surface's removals. */ @Optional @InputFile var newRemovedApiFile: File? = null /** Optional file containing a newline-delimited list of error SHAs to ignore. */ var whitelistErrorsFile: File? = null @Optional @InputFile fun getWhiteListErrorsFileInput(): File? { // Gradle requires non-null InputFiles to exist -- even with Optional -- so work around that // by returning null for this field if the file doesn't exist. if (whitelistErrorsFile?.exists() == true) { return whitelistErrorsFile } return null } /** * Optional set of error SHAs to ignore. * <p> * Each error SHA is unique to a specific API change. */ @Optional @Input var whitelistErrors = emptySet<String>() var detectedWhitelistErrors = mutableSetOf<String>() @InputFiles var doclavaClasspath: Collection<File> = emptyList() // A dummy output file meant only to tag when this check was last ran. // Without any outputs, Gradle will run this task every time. @Optional private var mOutputFile: File? = null @OutputFile fun getOutputFile(): File { return if (mOutputFile != null) { mOutputFile!! } else { File(project.buildDir, "checkApi/$name-completed") } } @Optional fun setOutputFile(outputFile: File) { mOutputFile = outputFile } @Input lateinit var checksConfig: ChecksConfig init { group = "Verification" description = "Invoke Doclava\'s ApiCheck tool to make sure current.txt is up to date." } private fun collectAndVerifyInputs(): Set<File> { if (oldRemovedApiFile != null && newRemovedApiFile != null) { return setOf(oldApiFile!!, newApiFile, oldRemovedApiFile!!, newRemovedApiFile!!) } else { return setOf(oldApiFile!!, newApiFile) } } @TaskAction fun exec() { if (oldApiFile == null) { // Nothing to do. return } val apiFiles = collectAndVerifyInputs() val errStream = ByteArrayOutputStream() // If either of those gets tweaked, then this should be refactored to extend JavaExec. project.javaexec { spec -> spec.apply { // Put Doclava on the classpath so we can get the ApiCheck class. classpath(doclavaClasspath) main = "com.google.doclava.apicheck.ApiCheck" minHeapSize = "128m" maxHeapSize = "1024m" // add -error LEVEL for every error level we want to fail the build on. checksConfig.errors.forEach { args("-error", it) } checksConfig.warnings.forEach { args("-warning", it) } checksConfig.hidden.forEach { args("-hide", it) } spec.args(apiFiles.map { it.absolutePath }) // Redirect error output so that we can whitelist specific errors. errorOutput = errStream // We will be handling failures ourselves with a custom message. setIgnoreExitValue(true) } } // Load the whitelist file, if present. val whitelistFile = whitelistErrorsFile if (whitelistFile?.exists() == true) { whitelistErrors += whitelistFile.readLines() } // Parse the error output. val unparsedErrors = mutableSetOf<String>() val detectedErrors = mutableSetOf<List<String>>() val parsedErrors = mutableSetOf<List<String>>() ByteArrayInputStream(errStream.toByteArray()).bufferedReader().lines().forEach { val match = ERROR_REGEX.matchEntire(it) if (match == null) { unparsedErrors.add(it) } else if (match.groups[3]?.value == "error") { val hash = getShortHash(match.groups[5]?.value!!) val error = match.groupValues.subList(1, match.groupValues.size) + listOf(hash) if (hash in whitelistErrors) { detectedErrors.add(error) detectedWhitelistErrors.add(error[5]) } else { parsedErrors.add(error) } } } unparsedErrors.forEach { error -> logger.error("$ANSI_RED$error$ANSI_RESET") } parsedErrors.forEach { logger.error("$ANSI_RED${it[5]}$ANSI_RESET ${it[4]}") } detectedErrors.forEach { logger.warn("$ANSI_YELLOW${it[5]}$ANSI_RESET ${it[4]}") } if (unparsedErrors.isNotEmpty() || parsedErrors.isNotEmpty()) { throw GradleException(checksConfig.onFailMessage ?: "") } // Just create a dummy file upon completion. Without any outputs, Gradle will run this task // every time. val outputFile = getOutputFile() outputFile.parentFile.mkdirs() outputFile.createNewFile() } }
apache-2.0
60d174fc348d40389e9919fa0b0d2b78
33.449782
100
0.638185
4.441441
false
false
false
false
microg/android_packages_apps_UnifiedNlp
service/src/main/kotlin/org/microg/nlp/service/GeocodeFuser.kt
1
2586
/* * SPDX-FileCopyrightText: 2014, microG Project Team * SPDX-License-Identifier: Apache-2.0 */ package org.microg.nlp.service import android.content.Context import android.content.Intent import android.location.Address import kotlinx.coroutines.launch import org.microg.nlp.api.Constants.ACTION_GEOCODER_BACKEND import java.util.ArrayList import java.util.concurrent.CopyOnWriteArrayList class GeocodeFuser(private val context: Context, private val root: UnifiedLocationServiceRoot) { private val backendHelpers = CopyOnWriteArrayList<GeocodeBackendHelper>() suspend fun reset() { unbind() backendHelpers.clear() for (backend in Preferences(context).geocoderBackends) { val parts = backend.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() if (parts.size >= 2) { val intent = Intent(ACTION_GEOCODER_BACKEND) intent.setPackage(parts[0]) intent.setClassName(parts[0], parts[1]) backendHelpers.add(GeocodeBackendHelper(context, root.coroutineScope, intent, if (parts.size >= 3) parts[2] else null)) } } } fun bind() { for (backendHelper in backendHelpers) { backendHelper.bind() } } suspend fun unbind() { for (backendHelper in backendHelpers) { backendHelper.unbind() } } suspend fun destroy() { unbind() backendHelpers.clear() } suspend fun getFromLocation(latitude: Double, longitude: Double, maxResults: Int, locale: String): List<Address>? { if (backendHelpers.isEmpty()) return null val result = ArrayList<Address>() for (backendHelper in backendHelpers) { val backendResult = backendHelper.getFromLocation(latitude, longitude, maxResults, locale) result.addAll(backendResult) } return result } suspend fun getFromLocationName(locationName: String, maxResults: Int, lowerLeftLatitude: Double, lowerLeftLongitude: Double, upperRightLatitude: Double, upperRightLongitude: Double, locale: String): List<Address>? { if (backendHelpers.isEmpty()) return null val result = ArrayList<Address>() for (backendHelper in backendHelpers) { val backendResult = backendHelper.getFromLocationName(locationName, maxResults, lowerLeftLatitude, lowerLeftLongitude, upperRightLatitude, upperRightLongitude, locale) result.addAll(backendResult) } return result } }
apache-2.0
37e738d2baafc8b2c1f14358b164e490
35.422535
220
0.666667
4.66787
false
false
false
false
daverix/ajvm
core/src/commonMain/kotlin/net/daverix/ajvm/ApplicationObjectLoader.kt
1
1824
/* Java Virtual Machine for Android Copyright (C) 2017 David Laurell 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 */ package net.daverix.ajvm import net.daverix.ajvm.io.readClassInfo class ApplicationObjectLoader( private val fileOpener: FileOpener, private val outStream: PrintStreamObject, private val errStream: PrintStreamObject, private val staticObjects: MutableMap<String, VirtualObject> = mutableMapOf() ) { fun load(qualifiedName: String): VirtualObject = when (qualifiedName) { "java/lang/System" -> SystemObject(outStream, errStream) "java/lang/StringBuilder" -> StringBuilderObject() "java/lang/Integer" -> IntegerObject() else -> RuntimeVirtualObject( classInfo = fileOpener.openFile(qualifiedName) { readClassInfo() }, loadObject = ::load, loadStaticObject = ::loadStatic ) } private fun loadStatic(qualifiedName: String): VirtualObject { var staticObject: VirtualObject? = staticObjects[qualifiedName] if (staticObject == null) { staticObject = load(qualifiedName) staticObjects[qualifiedName] = staticObject } return staticObject } }
gpl-3.0
ac93e167a1f6d4b3446fd240c2e0b24e
37
85
0.677083
4.877005
false
false
false
false
aosp-mirror/platform_frameworks_support
room/compiler/src/main/kotlin/androidx/room/verifier/DatabaseVerifier.kt
1
4813
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.verifier import androidx.room.processor.Context import androidx.room.vo.Entity import androidx.room.vo.Warning import columnInfo import org.sqlite.JDBC import java.io.File import java.sql.Connection import java.sql.DriverManager import java.sql.SQLException import java.util.UUID import java.util.regex.Pattern import javax.lang.model.element.Element /** * Builds an in-memory version of the database and verifies the queries against it. * This class is also used to resolve the return types. */ class DatabaseVerifier private constructor( val connection: Connection, val context: Context, val entities: List<Entity>) { companion object { private const val CONNECTION_URL = "jdbc:sqlite::memory:" /** * Taken from: * https://github.com/robolectric/robolectric/blob/master/shadows/framework/ * src/main/java/org/robolectric/shadows/ShadowSQLiteConnection.java#L94 * * This is actually not accurate because it might swap anything since it does not parse * SQL. That being said, for the verification purposes, it does not matter and clearly * much easier than parsing and rebuilding the query. */ private val COLLATE_LOCALIZED_UNICODE_PATTERN = Pattern.compile( "\\s+COLLATE\\s+(LOCALIZED|UNICODE)", Pattern.CASE_INSENSITIVE) init { // see: https://github.com/xerial/sqlite-jdbc/issues/97 val tmpDir = System.getProperty("java.io.tmpdir") if (tmpDir != null) { val outDir = File(tmpDir, "room-${UUID.randomUUID()}") outDir.mkdirs() outDir.deleteOnExit() System.setProperty("org.sqlite.tmpdir", outDir.absolutePath) // dummy call to trigger JDBC initialization so that we can unregister it JDBC.isValidURL(CONNECTION_URL) unregisterDrivers() } } /** * Tries to create a verifier but returns null if it cannot find the driver. */ fun create(context: Context, element: Element, entities: List<Entity>): DatabaseVerifier? { return try { val connection = JDBC.createConnection(CONNECTION_URL, java.util.Properties()) DatabaseVerifier(connection, context, entities) } catch (ex: Exception) { context.logger.w(Warning.CANNOT_CREATE_VERIFICATION_DATABASE, element, DatabaseVerificaitonErrors.cannotCreateConnection(ex)) null } } /** * Unregisters the JDBC driver. If we don't do this, we'll leak the driver which leaks a * whole class loader. * see: https://github.com/xerial/sqlite-jdbc/issues/267 * see: https://issuetracker.google.com/issues/62473121 */ private fun unregisterDrivers() { try { DriverManager.getDriver(CONNECTION_URL)?.let { DriverManager.deregisterDriver(it) } } catch (t: Throwable) { System.err.println("Room: cannot unregister driver ${t.message}") } } } init { entities.forEach { entity -> val stmt = connection.createStatement() stmt.executeUpdate(stripLocalizeCollations(entity.createTableQuery)) } } fun analyze(sql: String): QueryResultInfo { return try { val stmt = connection.prepareStatement(stripLocalizeCollations(sql)) QueryResultInfo(stmt.columnInfo()) } catch (ex: SQLException) { QueryResultInfo(emptyList(), ex) } } private fun stripLocalizeCollations(sql: String) = COLLATE_LOCALIZED_UNICODE_PATTERN.matcher(sql).replaceAll(" COLLATE NOCASE") fun closeConnection(context: Context) { if (!connection.isClosed) { try { connection.close() } catch (t: Throwable) { //ignore. context.logger.d("failed to close the database connection ${t.message}") } } } }
apache-2.0
a1205e801f0258b3cf2dc31fa2bfa661
37.504
99
0.627467
4.650242
false
false
false
false
koma-im/koma
src/main/kotlin/koma/gui/element/control/behavior/FocusTraversalInputMap.kt
1
3965
package koma.gui.element.control.behavior import javafx.scene.Node import javafx.scene.input.KeyCode.* import javafx.scene.input.KeyEvent import koma.gui.element.control.inputmap.KInputMap import koma.gui.element.control.inputmap.KeyBinding import koma.gui.element.control.inputmap.mapping.KeyMapping import koma.gui.element.scene.traversal.Direction object FocusTraversalInputMap { val mappings: List<KeyMapping> = listOf( KeyMapping(UP, { e: KeyEvent -> traverseUp(e) }, null), KeyMapping(DOWN, { e -> traverseDown(e) }, null), KeyMapping(LEFT, { e -> traverseLeft(e) }), KeyMapping(RIGHT, { e -> traverseRight(e) }), KeyMapping(TAB, { e -> traverseNext(e) }), KeyMapping(KeyBinding(TAB).shift(), { e -> traversePrevious(e) }), KeyMapping(KeyBinding(UP).shift().alt().ctrl(), { e -> traverseUp(e) }), KeyMapping(KeyBinding(DOWN).shift().alt().ctrl(), { e -> traverseDown(e) }), KeyMapping(KeyBinding(LEFT).shift().alt().ctrl(), { e -> traverseLeft(e) }), KeyMapping(KeyBinding(RIGHT).shift().alt().ctrl(), { e -> traverseRight(e) }), KeyMapping(KeyBinding(TAB).shift().alt().ctrl(), { e -> traverseNext(e) }), KeyMapping(KeyBinding(TAB).alt().ctrl(), { e -> traversePrevious(e) }) ) fun <N : Node> createInputMap(node: N): KInputMap<N> { val inputMap = KInputMap<N>(node) inputMap.addKeyMappings(mappings) return inputMap } /*************************************************************************** * Focus Traversal methods * */ /** * Called by any of the BehaviorBase traverse methods to actually effect a * traversal of the focus. The default behavior of this method is to simply * traverse on the given node, passing the given direction. A * subclass may override this method. * * @param node The node to traverse on * @param dir The direction to traverse */ fun traverse(node: Node?, @Suppress("UNUSED_PARAMETER") _d: Direction) { if (node == null) { throw IllegalArgumentException("Attempting to traverse on a null Node. " + "Most probably a KeyEvent has been fired with a null target specified.") } //NodeHelper.traverse(node, dir); } /** * Calls the focus traversal engine and indicates that traversal should * go the next focusTraversable Node above the current one. */ fun traverseUp(e: KeyEvent) { traverse(getNode(e), Direction.UP) } /** * Calls the focus traversal engine and indicates that traversal should * go the next focusTraversable Node below the current one. */ fun traverseDown(e: KeyEvent) { traverse(getNode(e), Direction.DOWN) } /** * Calls the focus traversal engine and indicates that traversal should * go the next focusTraversable Node left of the current one. */ fun traverseLeft(e: KeyEvent) { traverse(getNode(e), Direction.LEFT) } /** * Calls the focus traversal engine and indicates that traversal should * go the next focusTraversable Node right of the current one. */ fun traverseRight(e: KeyEvent) { traverse(getNode(e), Direction.RIGHT) } /** * Calls the focus traversal engine and indicates that traversal should * go the next focusTraversable Node in the focus traversal cycle. */ fun traverseNext(e: KeyEvent) { traverse(getNode(e), Direction.NEXT) } /** * Calls the focus traversal engine and indicates that traversal should * go the previous focusTraversable Node in the focus traversal cycle. */ fun traversePrevious(e: KeyEvent) { traverse(getNode(e), Direction.PREVIOUS) } private fun getNode(e: KeyEvent): Node? { val target = e.target return target as? Node } }
gpl-3.0
c07a82423f9256fcd9e7305b748b7972
35.712963
159
0.625473
4.286486
false
false
false
false
seventhroot/elysium
bukkit/rpk-payments-bukkit/src/main/kotlin/com/rpkit/payments/bukkit/command/payment/PaymentRemoveCommand.kt
1
2944
/* * Copyright 2017 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.payments.bukkit.command.payment import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.payments.bukkit.RPKPaymentsBukkit import com.rpkit.payments.bukkit.group.RPKPaymentGroupProvider import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player class PaymentRemoveCommand(private val plugin: RPKPaymentsBukkit): CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (!sender.hasPermission("rpkit.payments.command.payment.remove")) { sender.sendMessage(plugin.messages["no-permission-payment-remove"]) return true } if (args.isEmpty()) { sender.sendMessage(plugin.messages["payment-remove-usage"]) return true } val paymentGroupProvider = plugin.core.serviceManager.getServiceProvider(RPKPaymentGroupProvider::class) val paymentGroup = paymentGroupProvider.getPaymentGroup(args.joinToString(" ")) if (paymentGroup == null) { sender.sendMessage(plugin.messages["payment-remove-invalid-payment-group"]) return true } if (sender !is Player) { sender.sendMessage(plugin.messages["not-from-console"]) return true } val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender) if (minecraftProfile == null) { sender.sendMessage(plugin.messages["no-minecraft-profile"]) return true } val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val character = characterProvider.getActiveCharacter(minecraftProfile) if (!paymentGroup.owners.contains(character)) { sender.sendMessage(plugin.messages["payment-remove-invalid-not-an-owner"]) return true } paymentGroupProvider.removePaymentGroup(paymentGroup) sender.sendMessage(plugin.messages["payment-remove-valid"]) return true } }
apache-2.0
19f4d88391527bfa490c7dd6e33ae9a6
42.955224
120
0.721128
4.923077
false
false
false
false
DR-YangLong/spring-boot-kotlin-demo
src/main/kotlin/site/yanglong/promotion/model/UserBase.kt
1
1015
package site.yanglong.promotion.model import com.baomidou.mybatisplus.activerecord.Model import com.baomidou.mybatisplus.annotations.* import com.baomidou.mybatisplus.enums.FieldFill import java.io.Serializable import java.util.* @TableName("user_base") class UserBase : Model<UserBase>(), Serializable { @TableId var userId: Long? = null var userMobile: String? = null var userName: String? = null @TableField(fill = FieldFill.INSERT) var userPwd: String? = null var appToken: String? = null @TableField//逻辑删除 @TableLogic//逻辑删除,公用可抽象到抽象父类 var userStatus: String? = null @TableField(fill = FieldFill.UPDATE)//公用可抽象到抽象父类 var modifyDate: Date? = null @Version//公用可抽象到抽象父类 var lockVersion: Long?=null companion object { private const val serialVersionUID = 7584846556783479679L } override fun pkVal(): Serializable { return this.userId!! } }
apache-2.0
65461dff47e5fb0da40469a1ab326ebb
22.45
65
0.704376
3.645914
false
false
false
false
EMResearch/EvoMaster
e2e-tests/spring-graphql/src/test/kotlin/com/foo/graphql/SpringController.kt
1
2066
package com.foo.graphql import org.evomaster.client.java.controller.EmbeddedSutController import org.evomaster.client.java.controller.api.dto.AuthenticationDto import org.evomaster.client.java.controller.api.dto.SutInfoDto import org.evomaster.client.java.controller.internal.db.DbSpecification import org.evomaster.client.java.controller.problem.GraphQlProblem import org.evomaster.client.java.controller.problem.ProblemInfo import org.springframework.boot.SpringApplication import org.springframework.context.ConfigurableApplicationContext abstract class SpringController(protected val applicationClass: Class<*>) : EmbeddedSutController() { init { super.setControllerPort(0) } protected var ctx: ConfigurableApplicationContext? = null abstract fun schemaName(): String override fun startSut(): String { ctx = SpringApplication.run(applicationClass, "--server.port=0", "--graphql.tools.schema-location-pattern=**/${schemaName()}" ) return "http://localhost:$sutPort" } val sutPort: Int get() = (ctx!!.environment .propertySources["server.ports"].source as Map<*, *>)["local.server.port"] as Int override fun isSutRunning(): Boolean { return ctx != null && ctx!!.isRunning } override fun stopSut() { ctx?.stop() ctx?.close() } override fun getPackagePrefixesToCover(): String { return "com.foo.graphql." } override fun getDbSpecifications(): MutableList<DbSpecification>? { return null } override fun getPreferredOutputFormat(): SutInfoDto.OutputFormat { return SutInfoDto.OutputFormat.KOTLIN_JUNIT_5 } override fun resetStateOfSUT() { } override fun getInfoForAuthentication(): List<AuthenticationDto> { return listOf() } override fun getProblemInfo(): ProblemInfo { return GraphQlProblem("${getBaseURL()}/graphql") } fun getBaseURL(): String { return "http://localhost:$sutPort" } }
lgpl-3.0
d66013ca628aef6e438c09562b680366
27.30137
101
0.686834
4.749425
false
false
false
false
FunServer/Core
src/main/kotlin/me/camdenorrb/core/listeners/CoreListener.kt
1
690
package me.camdenorrb.core.listeners import me.camdenorrb.core.events.PlayerMoveBlockEvent import me.camdenorrb.core.extensions.miniBus import me.camdenorrb.minibus.listener.MiniListener import org.bukkit.event.EventHandler import org.bukkit.event.EventPriority.HIGHEST import org.bukkit.event.Listener import org.bukkit.event.player.PlayerMoveEvent class CoreListener : Listener, MiniListener { @EventHandler(ignoreCancelled = true, priority = HIGHEST) fun PlayerMoveEvent.onMove() { val toBlock = to.block val fromBlock = from.block if (toBlock == fromBlock) return isCancelled = miniBus.invoke(PlayerMoveBlockEvent(player, to, from, toBlock, fromBlock)).cancelled } }
gpl-3.0
a4b0f88ea1501c60310b36040a8be01b
25.576923
100
0.804348
3.791209
false
false
false
false
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/authentication/twofactor/ui/TwoFAFragment.kt
2
5300
package chat.rocket.android.authentication.twofactor.ui import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import androidx.core.content.ContextCompat import androidx.core.view.ViewCompat import androidx.core.view.isVisible import androidx.fragment.app.Fragment import chat.rocket.android.R import chat.rocket.android.analytics.AnalyticsManager import chat.rocket.android.analytics.event.ScreenViewEvent import chat.rocket.android.authentication.twofactor.presentation.TwoFAPresenter import chat.rocket.android.authentication.twofactor.presentation.TwoFAView import chat.rocket.android.util.extension.asObservable import chat.rocket.android.util.extensions.inflate import chat.rocket.android.util.extensions.showToast import chat.rocket.android.util.extensions.textContent import chat.rocket.android.util.extensions.ui import dagger.android.support.AndroidSupportInjection import io.reactivex.disposables.Disposable import kotlinx.android.synthetic.main.fragment_authentication_two_fa.* import javax.inject.Inject fun newInstance(username: String, password: String): Fragment = TwoFAFragment().apply { arguments = Bundle(2).apply { putString(BUNDLE_USERNAME, username) putString(BUNDLE_PASSWORD, password) } } private const val BUNDLE_USERNAME = "username" private const val BUNDLE_PASSWORD = "password" class TwoFAFragment : Fragment(), TwoFAView { @Inject lateinit var presenter: TwoFAPresenter @Inject lateinit var analyticsManager: AnalyticsManager private lateinit var username: String private lateinit var password: String private lateinit var twoFaCodeDisposable: Disposable override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AndroidSupportInjection.inject(this) arguments?.run { username = getString(BUNDLE_USERNAME, "") password = getString(BUNDLE_PASSWORD, "") } ?: requireNotNull(arguments) { "no arguments supplied when the fragment was instantiated" } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = container?.inflate(R.layout.fragment_authentication_two_fa) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) activity?.apply { text_two_factor_authentication_code.requestFocus() val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.showSoftInput( text_two_factor_authentication_code, InputMethodManager.RESULT_UNCHANGED_SHOWN ) } setupOnClickListener() subscribeEditText() analyticsManager.logScreenView(ScreenViewEvent.TwoFa) } override fun onDestroyView() { super.onDestroyView() unsubscribeEditText() } override fun enableButtonConfirm() { context?.let { ViewCompat.setBackgroundTintList( button_confirm, ContextCompat.getColorStateList(it, R.color.colorAccent) ) button_confirm.isEnabled = true } } override fun disableButtonConfirm() { context?.let { ViewCompat.setBackgroundTintList( button_confirm, ContextCompat.getColorStateList(it, R.color.colorAuthenticationButtonDisabled) ) button_confirm.isEnabled = false } } override fun alertInvalidTwoFactorAuthenticationCode() = showMessage(R.string.msg_invalid_2fa_code) override fun showLoading() { ui { disableUserInput() view_loading.isVisible = true } } override fun hideLoading() { ui { view_loading.isVisible = false enableUserInput() } } override fun showMessage(resId: Int) { ui { showToast(resId) } } override fun showMessage(message: String) { ui { showToast(message) } } override fun showGenericErrorMessage() = showMessage(R.string.msg_generic_error) private fun enableUserInput() { enableButtonConfirm() text_two_factor_authentication_code.isEnabled = true } private fun disableUserInput() { disableButtonConfirm() text_two_factor_authentication_code.isEnabled = false } private fun setupOnClickListener() { button_confirm.setOnClickListener { presenter.authenticate( username, password, text_two_factor_authentication_code.textContent ) } } private fun subscribeEditText() { twoFaCodeDisposable = text_two_factor_authentication_code.asObservable() .subscribe { if (it.isNotBlank()) { enableButtonConfirm() } else { disableButtonConfirm() } } } private fun unsubscribeEditText() = twoFaCodeDisposable.dispose() }
mit
c7f6a675a620efb611423ce66778503e
30.547619
101
0.673208
5.018939
false
false
false
false
google/private-compute-libraries
java/com/google/android/libraries/pcc/chronicle/tools/ledger/JsonReaderExt.kt
1
2656
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.pcc.chronicle.tools.ledger import com.google.gson.Gson import com.google.gson.TypeAdapter import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonToken /** * This file contains extensions to [JsonReader] which help to fluently parse JSON objects in * Kotlin. */ internal fun JsonReader.readObject(fieldVisitor: JsonReader.(name: String) -> Unit) { beginObject() val seenNames = mutableSetOf<String>() while (true) { if (peek() == JsonToken.END_OBJECT) break val name = nextName() if (name in seenNames) { throw IllegalArgumentException("Invalid JSON, key \"$name\" appeared more than once at $path") } seenNames += name fieldVisitor(name) } endObject() } internal inline fun <reified T> JsonReader.readObject(gson: Gson): T { return gson.getAdapter(T::class.java).read(this) } internal fun JsonReader.readList(itemVisitor: JsonReader.() -> Unit) { beginArray() while (true) { if (peek() == JsonToken.END_ARRAY) break itemVisitor() } endArray() } internal inline fun <reified T> JsonReader.readList(gson: Gson): List<T> { val result = mutableListOf<T>() readList { result += gson.getAdapter(T::class.java).read(this) } return result } internal fun JsonReader.readStringList(): List<String> { val result = mutableListOf<String>() readList { result += nextString() } return result } internal inline fun <reified T> JsonReader.readSet(gson: Gson): Set<T> { val result = mutableSetOf<T>() beginArray() while (true) { if (peek() == JsonToken.END_ARRAY) break result += gson.getAdapter(T::class.java).read(this) } endArray() return result } internal fun <T> JsonReader.readMap(valueAdapter: TypeAdapter<T>): Map<String, T> { val result = mutableMapOf<String, T>() readObject { fieldName -> val value = valueAdapter.read(this) result[fieldName] = value } return result } internal inline fun <reified T> JsonReader.readMap(gson: Gson): Map<String, T> = readMap(gson.getAdapter(T::class.java))
apache-2.0
50d448309a099f6cc3c9d3f5b217e9bc
28.842697
100
0.709714
3.821583
false
false
false
false
google/private-compute-libraries
java/com/google/android/libraries/pcc/chronicle/storage/blobstore/BlobStoreCore.kt
1
3466
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.pcc.chronicle.storage.blobstore import android.content.Context import androidx.room.Room import com.google.android.libraries.pcc.chronicle.storage.blobstore.db.BlobDatabase import com.google.android.libraries.pcc.chronicle.storage.blobstore.inmemory.InMemoryBlobStore import com.google.android.libraries.pcc.chronicle.storage.blobstore.inmemory.InMemoryBlobStoreManagement import com.google.android.libraries.pcc.chronicle.storage.blobstore.inmemory.InMemoryStorage import com.google.android.libraries.pcc.chronicle.storage.blobstore.persisted.PersistedBlobStore import com.google.android.libraries.pcc.chronicle.storage.blobstore.persisted.PersistedBlobStoreManagement import com.google.android.libraries.pcc.chronicle.util.TimeSource /** * Entry point to BlobStore. Data stewards will use this class to create their [BlobStores] * [BlobStore]. This class also creates the [BlobStoreManager], which handles logistics around * enforcing TTL and quota limits, clearing data according to user settings, and cleaning up data * when packages are uninstalled. */ class BlobStoreCore(context: Context, private val timeSource: TimeSource) : BlobStoreProvider { private val db = Room.databaseBuilder(context, BlobDatabase::class.java, DB_NAME).build() private val dao = db.blobDao() private val inMemoryStorage = InMemoryStorage() private val manager = BlobStoreManager( timeSource = timeSource, managements = setOf(PersistedBlobStoreManagement(dao), InMemoryBlobStoreManagement(inMemoryStorage)) ) /** Provides a [BlobStore] based on the given [ManagementInfo]. */ @Suppress("UNCHECKED_CAST") override fun <T : Any> provideBlobStore(managementInfo: ManagementInfo): BlobStore<T> { if (managementInfo is PersistedManagementInfo<*>) { require(managementInfo.quotaInfo.maxRowCount > managementInfo.quotaInfo.minRowsAfterTrim) { "maxRowCount must be greater than minRowsAfterTrim." } } val checkInfo = manager.addManagementInfo(managementInfo) if ( (checkInfo != null) && ((checkInfo == managementInfo) || (checkInfo.javaClass == managementInfo.javaClass)) ) { return when (checkInfo) { is PersistedManagementInfo<*> -> PersistedBlobStore(dao, checkInfo, timeSource) as BlobStore<T> is InMemoryManagementInfo -> InMemoryBlobStore(inMemoryStorage.registerDataTypeStore(checkInfo), timeSource) } } throw IllegalArgumentException( "Persisted and in memory blob stores for the same DTD is not allowed." ) } /** * Returns the [BlobStoreManager], which provides maintenance and clean up services for * [BlobStores][BlobStore]. */ fun provideManager(): BlobStoreManager = manager companion object { private const val DB_NAME = "ChronicleBlobStore" } }
apache-2.0
eb82db051fd8791f619f28102ff2c0ff
40.261905
106
0.754183
4.247549
false
false
false
false
thomasnield/kotlin-statistics
src/main/kotlin/org/nield/kotlinstatistics/LongStatistics.kt
1
10427
package org.nield.kotlinstatistics import org.apache.commons.math3.stat.StatUtils import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics import org.nield.kotlinstatistics.range.XClosedRange val LongArray.descriptiveStatistics: Descriptives get() = DescriptiveStatistics().apply { forEach { addValue(it.toDouble()) } }.let(::ApacheDescriptives) fun LongArray.geometricMean() = StatUtils.geometricMean(asSequence().map { it.toDouble() }.toList().toDoubleArray() ) fun LongArray.median() = percentile(50.0) fun LongArray.percentile(percentile: Double) = StatUtils.percentile(asSequence().map { it.toDouble() }.toList().toDoubleArray(), percentile) fun LongArray.variance() = StatUtils.variance(asSequence().map { it.toDouble() }.toList().toDoubleArray()) fun LongArray.sumOfSquares() = StatUtils.sumSq(asSequence().map { it.toDouble() }.toList().toDoubleArray()) fun LongArray.standardDeviation() = descriptiveStatistics.standardDeviation fun LongArray.normalize() = StatUtils.normalize(asSequence().map { it.toDouble() }.toList().toDoubleArray()) val LongArray.kurtosis get() = descriptiveStatistics.kurtosis val LongArray.skewness get() = descriptiveStatistics.skewness // AGGREGATION OPERATORS inline fun <T,K> Sequence<T>.sumBy(crossinline keySelector: (T) -> K, crossinline longSelector: (T) -> Long) = groupApply(keySelector, longSelector) { it.sum() } inline fun <T,K> Iterable<T>.sumBy(crossinline keySelector: (T) -> K, crossinline longSelector: (T) -> Long) = asSequence().sumBy(keySelector, longSelector) fun <K> Sequence<Pair<K,Long>>.sumBy() = groupApply({it.first}, {it.second}) { it.sum() } fun <K> Iterable<Pair<K,Long>>.sumBy() = asSequence().sumBy() inline fun <T,K> Sequence<T>.averageBy(crossinline keySelector: (T) -> K, crossinline longSelector: (T) -> Long) = groupApply(keySelector, longSelector) { it.average() } inline fun <T,K> Iterable<T>.averageBy(crossinline keySelector: (T) -> K, crossinline valueSelector: (T) -> Long) = asSequence().averageBy(keySelector, valueSelector) fun <K> Sequence<Pair<K,Long>>.averageBy() = groupApply({it.first}, {it.second}) { it.average() } fun <K> Iterable<Pair<K,Long>>.averageBy() = asSequence().averageBy() fun Sequence<Long>.longRange() = toList().longRange() fun Iterable<Long>.longRange() = toList().let { (it.min()?:throw Exception("At least one element must be present"))..(it.max()?:throw Exception("At least one element must be present")) } inline fun <T,K> Sequence<T>.longRangeBy(crossinline keySelector: (T) -> K, crossinline longSelector: (T) -> Long) = groupApply(keySelector, longSelector) { it.range() } inline fun <T,K> Iterable<T>.longRangeBy(crossinline keySelector: (T) -> K, crossinline longSelector: (T) -> Long) = asSequence().rangeBy(keySelector, longSelector) // bin operators inline fun <T> Sequence<T>.binByLong(binSize: Long, crossinline valueSelector: (T) -> Long, rangeStart: Long? = null ) = toList().binByLong(binSize, valueSelector, rangeStart) inline fun <T, G> Sequence<T>.binByLong(binSize: Long, crossinline valueSelector: (T) -> Long, crossinline groupOp: (List<T>) -> G, rangeStart: Long? = null ) = toList().binByLong(binSize, valueSelector, groupOp, rangeStart) inline fun <T> Iterable<T>.binByLong(binSize: Long, crossinline valueSelector: (T) -> Long, rangeStart: Long? = null ): BinModel<List<T>, Long> = toList().binByLong(binSize, valueSelector, { it }, rangeStart) inline fun <T, G> Iterable<T>.binByLong(binSize: Long, crossinline valueSelector: (T) -> Long, crossinline groupOp: (List<T>) -> G, rangeStart: Long? = null ) = toList().binByLong(binSize, valueSelector, groupOp, rangeStart) inline fun <T> List<T>.binByLong(binSize: Long, crossinline valueSelector: (T) -> Long, rangeStart: Long? = null ): BinModel<List<T>, Long> = binByLong(binSize, valueSelector, { it }, rangeStart) inline fun <T, G> List<T>.binByLong(binSize: Long, crossinline valueSelector: (T) -> Long, crossinline groupOp: (List<T>) -> G, rangeStart: Long? = null ): BinModel<G, Long> { val groupedByC = asSequence().groupBy(valueSelector) val minC = rangeStart?:groupedByC.keys.min()!! val maxC = groupedByC.keys.max()!! val bins = mutableListOf<XClosedRange<Long>>().apply { var currentRangeStart = minC var currentRangeEnd = minC while (currentRangeEnd < maxC) { currentRangeEnd = currentRangeStart + binSize - 1L add(XClosedRange(currentRangeStart, currentRangeEnd)) currentRangeStart = currentRangeEnd + 1L } } return bins.asSequence() .map { it to mutableListOf<T>() } .map { binWithList -> groupedByC.entries.asSequence() .filter { it.key in binWithList.first } .forEach { binWithList.second.addAll(it.value) } binWithList }.map { Bin(it.first, groupOp(it.second)) } .toList() .let(::BinModel) } fun <T, C : Comparable<C>> BinModel<List<T>, C>.sumByLong(selector: (T) -> Long): BinModel<Long, C> = BinModel(bins.map { Bin(it.range, it.value.map(selector).sum()) }) fun <T, C : Comparable<C>> BinModel<List<T>, C>.averageByLong(selector: (T) -> Long): BinModel<Double, C> = BinModel(bins.map { Bin(it.range, it.value.map(selector).average()) }) fun <T, C : Comparable<C>> BinModel<List<T>, C>.doubleRangeBy(selector: (T) -> Long): BinModel<LongRange, C> = BinModel(bins.map { Bin(it.range, it.value.map(selector).longRange()) }) fun <T, C : Comparable<C>> BinModel<List<T>, C>.geometricMeanByLong(selector: (T) -> Long): BinModel<Double, C> = BinModel(bins.map { Bin(it.range, it.value.map(selector).geometricMean()) }) fun <T, C : Comparable<C>> BinModel<List<T>, C>.medianByLong(selector: (T) -> Long): BinModel<Double, C> = BinModel(bins.map { Bin(it.range, it.value.map(selector).median()) }) fun <T, C : Comparable<C>> BinModel<List<T>, C>.percentileByLong(selector: (T) -> Long, percentile: Double): BinModel<Double, C> = BinModel(bins.map { Bin(it.range, it.value.map(selector).percentile(percentile)) }) fun <T, C : Comparable<C>> BinModel<List<T>, C>.varianceByLong(selector: (T) -> Long): BinModel<Double, C> = BinModel(bins.map { Bin(it.range, it.value.map(selector).variance()) }) fun <T, C : Comparable<C>> BinModel<List<T>, C>.sumOfSquaresByLong(selector: (T) -> Long): BinModel<Double, C> = BinModel(bins.map { Bin(it.range, it.value.map(selector).sumOfSquares()) }) fun <T, C : Comparable<C>> BinModel<List<T>, C>.normalizeByLong(selector: (T) -> Long): BinModel<DoubleArray, C> = BinModel(bins.map { Bin(it.range, it.value.map(selector).normalize()) }) fun <T, C : Comparable<C>> BinModel<List<T>, C>.descriptiveStatisticsByLong(selector: (T) -> Long): BinModel<Descriptives, C> = BinModel(bins.map { Bin(it.range, it.value.map(selector).descriptiveStatistics) }) fun <K> Map<K, List<Long>>.sum(): Map<K, Long> = entries.map { it.key to it.value.sum() }.toMap() fun <K> Map<K, List<Long>>.average(): Map<K, Double> = entries.map { it.key to it.value.average() }.toMap() fun <K> Map<K, List<Long>>.longRange(): Map<K, Iterable<Long>> = entries.map { it.key to it.value.longRange() }.toMap() fun <K> Map<K, List<Long>>.geometricMean(): Map<K, Double> = entries.map { it.key to it.value.geometricMean() }.toMap() fun <K> Map<K, List<Long>>.median(): Map<K, Double> = entries.map { it.key to it.value.median() }.toMap() fun <K> Map<K, List<Long>>.percentile(percentile: Double): Map<K, Double> = entries.map { it.key to it.value.percentile(percentile) }.toMap() fun <K> Map<K, List<Long>>.variance(): Map<K, Double> = entries.map { it.key to it.value.variance() }.toMap() fun <K> Map<K, List<Long>>.sumOfSquares(): Map<K, Double> = entries.map { it.key to it.value.sumOfSquares() }.toMap() fun <K> Map<K, List<Long>>.normalize(): Map<K, DoubleArray> = entries.map { it.key to it.value.normalize() }.toMap() fun <K> Map<K, List<Long>>.descriptiveStatistics(): Map<K, Descriptives> = entries.map { it.key to it.value.descriptiveStatistics }.toMap() fun <K, V> Map<K, List<V>>.sumByLong(selector: (V) -> Long): Map<K, Long> = entries.map { it.key to it.value.map(selector).sum() }.toMap() fun <K, V> Map<K, List<V>>.averageByLong(selector: (V) -> Long): Map<K, Double> = entries.map { it.key to it.value.map(selector).average() }.toMap() fun <K, V> Map<K, List<V>>.LongRangeBy(selector: (V) -> Long): Map<K, Iterable<Long>> = entries.map { it.key to it.value.map(selector).longRange() }.toMap() fun <K, V> Map<K, List<V>>.geometricMeanByLong(selector: (V) -> Long): Map<K, Double> = entries.map { it.key to it.value.map(selector).geometricMean() }.toMap() fun <K, V> Map<K, List<V>>.medianByLong(selector: (V) -> Long): Map<K, Double> = entries.map { it.key to it.value.map(selector).median() }.toMap() fun <K, V> Map<K, List<V>>.percentileByLong(selector: (V) -> Long, percentile: Double): Map<K, Double> = entries.map { it.key to it.value.map(selector).percentile(percentile) }.toMap() fun <K, V> Map<K, List<V>>.varianceByLong(selector: (V) -> Long): Map<K, Double> = entries.map { it.key to it.value.map(selector).variance() }.toMap() fun <K, V> Map<K, List<V>>.sumOfSquaresByLong(selector: (V) -> Long): Map<K, Double> = entries.map { it.key to it.value.map(selector).sumOfSquares() }.toMap() fun <K, V> Map<K, List<V>>.normalizeByLong(selector: (V) -> Long): Map<K, DoubleArray> = entries.map { it.key to it.value.map(selector).normalize() }.toMap() fun <K, V> Map<K, List<V>>.descriptiveStatisticsByLong(selector: (V) -> Long): Map<K, Descriptives> = entries.map { it.key to it.value.map(selector).descriptiveStatistics }.toMap()
apache-2.0
c4c925bbd8a12b768d36b9bacf153732
50.880597
186
0.636233
3.479146
false
false
false
false
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/teams/teammember/TeamMember.kt
1
2058
package ca.josephroque.bowlingcompanion.teams.teammember import android.os.Parcel import ca.josephroque.bowlingcompanion.common.interfaces.IIdentifiable import ca.josephroque.bowlingcompanion.common.interfaces.KParcelable import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator import ca.josephroque.bowlingcompanion.leagues.League import ca.josephroque.bowlingcompanion.series.Series /** * Copyright (C) 2018 Joseph Roque * * Member of a team. */ class TeamMember( val teamId: Long, val bowlerName: String, val bowlerId: Long, val league: League? = null, val series: Series? = null ) : IIdentifiable, KParcelable { companion object { @Suppress("unused") private const val TAG = "TeamMember" @Suppress("unused") @JvmField val CREATOR = parcelableCreator(::TeamMember) private const val TEAM_ID_SHIFT = 32 private const val BOWLER_ID_TRIM = 0xFFFFFFFF } /** * ID is a concatenation of the first 32 bits of the team ID and first 32 bits * of the bowler ID. */ override val id: Long get() = teamId.shl(TEAM_ID_SHIFT).or(bowlerId.and(BOWLER_ID_TRIM)) // MARK: Constructors private constructor(p: Parcel): this( teamId = p.readLong(), bowlerName = p.readString()!!, bowlerId = p.readLong(), league = p.readParcelable<League>(League::class.java.classLoader), series = p.readParcelable<Series>(Series::class.java.classLoader) ) constructor(teamMember: TeamMember): this( teamId = teamMember.teamId, bowlerName = teamMember.bowlerName, bowlerId = teamMember.bowlerId, league = teamMember.league, series = teamMember.series ) // MARK: Parcelable override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) { writeLong(teamId) writeString(bowlerName) writeLong(bowlerId) writeParcelable(league, 0) writeParcelable(series, 0) } }
mit
85a3980e71c978c2e03607697802c1f6
29.264706
82
0.662293
4.305439
false
false
false
false
cketti/k-9
app/ui/legacy/src/main/java/com/fsck/k9/ui/ThemeExtensions.kt
1
1022
package com.fsck.k9.ui import android.content.res.Resources.Theme import android.graphics.drawable.Drawable import android.util.TypedValue fun Theme.resolveColorAttribute(attrId: Int): Int { val typedValue = TypedValue() val found = resolveAttribute(attrId, typedValue, true) if (!found) { throw IllegalStateException("Couldn't resolve attribute ($attrId)") } return typedValue.data } fun Theme.resolveDrawableAttribute(attrId: Int): Drawable { val typedValue = TypedValue() val found = resolveAttribute(attrId, typedValue, true) if (!found) { throw IllegalStateException("Couldn't resolve attribute ($attrId)") } return getDrawable(typedValue.resourceId) } fun Theme.getIntArray(attrId: Int): IntArray { val typedValue = TypedValue() val found = resolveAttribute(attrId, typedValue, true) if (!found) { throw IllegalStateException("Couldn't resolve attribute ($attrId)") } return resources.getIntArray(typedValue.resourceId) }
apache-2.0
613c7d3566ba2ca6a6f3ae8126ed6927
25.894737
75
0.719178
4.405172
false
false
false
false
perenecabuto/CatchCatch
android/app/src/main/java/io/perenecabuto/catchcatch/view/HomeActivity.kt
1
5806
package io.perenecabuto.catchcatch.view import android.content.Context import android.content.Intent import android.hardware.SensorManager import android.location.Location import android.os.Bundle import android.os.Handler import android.os.Vibrator import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import android.view.WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS import android.view.animation.AnimationUtils import android.widget.TextView import io.nlopez.smartlocation.OnLocationUpdatedListener import io.nlopez.smartlocation.SmartLocation import io.nlopez.smartlocation.location.config.LocationAccuracy import io.nlopez.smartlocation.location.config.LocationParams import io.perenecabuto.catchcatch.R import io.perenecabuto.catchcatch.drivers.GeoJsonPolygon import io.perenecabuto.catchcatch.drivers.OSMShortcuts import io.perenecabuto.catchcatch.drivers.PolygonAnimator import io.perenecabuto.catchcatch.events.GameEventHandler import io.perenecabuto.catchcatch.events.RadarEventHandler import io.perenecabuto.catchcatch.model.* import io.perenecabuto.catchcatch.sensors.CompassEventListener import org.json.JSONObject import org.osmdroid.views.MapView import java.util.* private val dialogsDelay: Long = 5000L class HomeActivity : ActivityWithLocationPermission(), ActivityWithApp, OnLocationUpdatedListener { internal var player = Player("", 0.0, 0.0) private var animator: PolygonAnimator? = null private var map: MapView? = null private var radar: RadarEventHandler? = null private var game: GameEventHandler? = null private var radarView: RadarView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) OSMShortcuts.onCreate(this) window.setFlags(FLAG_LAYOUT_NO_LIMITS, FLAG_LAYOUT_NO_LIMITS) setContentView(R.layout.activity_home) val map = OSMShortcuts.findMapById(this, R.id.activity_home_map) this.map = map map.setOnTouchListener({ _, _ -> true }) radarView = findViewById(R.id.activity_home_radar) as RadarView val sensors = getSystemService(Context.SENSOR_SERVICE) as SensorManager CompassEventListener.listenCompass(sensors) { heading -> if (animator?.running != true) { map.mapOrientation = heading } } val conf = LocationParams.Builder().setAccuracy(LocationAccuracy.HIGH).build() SmartLocation.with(this).location().continuous().config(conf).start(this) radar = RadarEventHandler(app.socket, this).apply { start() } showMessage("welcome to CatchCatch!") } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) Handler().postDelayed({ showRank(GameRank("CatchCatch", (0..10).map { PlayerRank("Player $it", Random().nextInt()) })) }, dialogsDelay) } override fun onLocationUpdated(l: Location) { sendPosition(l) val point = player.updateLocation(l).point() val map = map ?: return OSMShortcuts.showMarkerOnMap(map, "me", point) if (animator?.running != true) { OSMShortcuts.focus(map, point, 18) } } override fun onResume() { super.onResume() OSMShortcuts.onResume(this) showInfo("starting...") radar?.start() } override fun onPause() { super.onPause() game?.stop() radar?.stop() } override fun onDestroy() { super.onDestroy() val map = map ?: return map.overlays.clear() } @Suppress("UNUSED_PARAMETER") fun showSettings(view: View) { val intent = Intent(this, SettingsActivity::class.java) startActivity(intent) } fun startGame(info: GameInfo) = runOnUiThread finish@ { hideRadar() val map = map ?: return@finish animator = OSMShortcuts.animatePolygonOverlay(map, info.game) animator?.overlay?.apply { OSMShortcuts.focus(map, boundingBox) } val radar = radar ?: return@finish GameEventHandler(app.socket, info, this).let { game = it radar.switchTo(it) } } fun gameOver() = runOnUiThread finish@ { animator?.stop() game?.switchTo(radar ?: return@finish) } fun sendPosition(l: Location) { val coords = JSONObject(mapOf("lat" to l.latitude, "lon" to l.longitude)) app.socket.emit("player:update", coords.toString()) } fun showMessage(msg: String) = runOnUiThread { val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator vibrator.vibrate(100) app.tts?.speak(msg) TransparentDialog(this, msg).showWithTimeout(dialogsDelay) } fun showInfo(text: String) = runOnUiThread { val info = findViewById(R.id.activity_home_info) as TextView info.startAnimation(AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right)) info.text = text.capitalize() } fun showRank(rank: GameRank) = runOnUiThread { RankDialog(this, rank, player).showWithTimeout(dialogsDelay * 2) } fun showFeatures(games: List<Feature>) = runOnUiThread finish@ { val map = map ?: return@finish OSMShortcuts.refreshGeojsonFeaturesOnMap(map, games.map { GeoJsonPolygon(it.id, it.geojson) }) } fun showCircleAroundPlayer(meters: Double) = runOnUiThread finish@ { val map = map ?: return@finish OSMShortcuts.drawCircleOnMap(map, "player-circle", player.point(), meters, 100.0) } fun showRadar() = runOnUiThread { radarView?.visibility = VISIBLE } fun hideRadar() = runOnUiThread { radarView?.visibility = GONE } }
gpl-3.0
75c603a94059ac67ac85fb28afa4592d
32.182857
106
0.686014
4.219477
false
false
false
false
thaleslima/GuideApp
app/src/main/java/com/guideapp/ui/widget/LocalFavoriteWidgetRemoteViewsService.kt
1
4466
package com.guideapp.ui.widget import android.content.Intent import android.database.Cursor import android.graphics.Bitmap import android.os.Binder import android.util.Log import android.widget.AdapterView import android.widget.RemoteViews import android.widget.RemoteViewsService import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.request.target.Target import com.guideapp.R import com.guideapp.data.local.GuideContract import com.guideapp.ui.views.localdetail.LocalDetailActivity import java.util.concurrent.ExecutionException class LocalFavoriteWidgetRemoteViewsService : RemoteViewsService() { override fun onGetViewFactory(intent: Intent): RemoteViewsService.RemoteViewsFactory { return object : RemoteViewsService.RemoteViewsFactory { private var mData: Cursor? = null override fun onCreate() { } override fun onDataSetChanged() { mData?.close() val identityToken = Binder.clearCallingIdentity() mData = contentResolver.query(GuideContract.LocalEntry.CONTENT_URI, GuideContract.LocalEntry.COLUMNS.toTypedArray(), GuideContract.LocalEntry.getSqlSelectForFavorites(), null, null) Binder.restoreCallingIdentity(identityToken) } override fun onDestroy() { mData?.close() mData = null } override fun getCount(): Int { return mData?.count ?: 0 } override fun getViewAt(position: Int): RemoteViews? { if (position == AdapterView.INVALID_POSITION || mData == null || !mData!!.moveToPosition(position)) { return null } val views = RemoteViews(packageName, R.layout.widget_detail_list_item) views.setTextViewText(R.id.local_text, mData?.getString(GuideContract.LocalEntry.POSITION_DESCRIPTION)) views.setTextViewText(R.id.descriptions_sub_category, mData?.getString(GuideContract.LocalEntry.POSITION_DESCRIPTION_SUB_CATEGORY)) val fillInIntent = Intent() fillInIntent.putExtra(LocalDetailActivity.EXTRA_LOCAL_ID, getItemId(position)) fillInIntent.putExtra(LocalDetailActivity.EXTRA_CATEGORY_ID, mData?.getLong(GuideContract.LocalEntry.POSITION_ID_CATEGORY)) views.setOnClickFillInIntent(R.id.widget_list_item, fillInIntent) var image: Bitmap? = null val urlImage = mData?.getString(GuideContract.LocalEntry.POSITION_IMAGE_PATH) views.setImageViewResource(R.id.local_picture, R.color.placeholder) try { image = Glide.with(this@LocalFavoriteWidgetRemoteViewsService) .load(urlImage) .asBitmap() .diskCacheStrategy(DiskCacheStrategy.ALL) .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get() } catch (e: InterruptedException) { Log.e(TAG, "Error retrieving large icon from " + urlImage, e) } catch (e: ExecutionException) { Log.e(TAG, "Error retrieving large icon from " + urlImage, e) } if (image != null) { views.setImageViewBitmap(R.id.local_picture, image) } else { views.setImageViewResource(R.id.local_picture, R.color.placeholder) } return views } override fun getLoadingView(): RemoteViews { return RemoteViews(packageName, R.layout.widget_detail_list_item) } override fun getViewTypeCount(): Int { return 1 } override fun getItemId(position: Int): Long { mData?.let { data -> if (data.moveToPosition(position)) return data.getLong(GuideContract.LocalEntry.POSITION_ID) } return position.toLong() } override fun hasStableIds(): Boolean { return true } } } companion object { private val TAG = LocalFavoriteWidgetRemoteViewsService::class.java.simpleName } }
apache-2.0
02cf2ff86154553ceb31554b76e0cc1e
38.522124
147
0.601657
5.229508
false
false
false
false
Burning-Man-Earth/iBurn-Android
iBurn/src/main/java/com/gaiagps/iburn/js/Geocoder.kt
1
3934
package com.gaiagps.iburn.js import android.content.Context import com.eclipsesource.v8.V8 import com.eclipsesource.v8.V8Array import com.mapbox.mapboxsdk.geometry.LatLng import io.reactivex.Single import io.reactivex.schedulers.Schedulers import timber.log.Timber import java.util.concurrent.Executors /** * Created by dbro on 6/12/17. */ /** * Use a single threaded executor to prevent spinning up multiple instances of the JS engine, * which is very expensive */ private val jsScheduler = Schedulers.from( Executors.newSingleThreadExecutor() ) object Geocoder { val jsPath = "js/bundle.js" private var v8: V8? = null private var jsContent: String? = null fun reverseGeocode(context: Context, lat: Float, lon: Float): Single<String> { return Single.just(true) .observeOn(jsScheduler) .map { ignored -> init(context) Timber.d("Reverse geocoding...") // Call into the JavaScript object to decode a string. val playaAddress = v8?.executeStringScript("coder.reverse($lat, $lon)") Timber.d("Reverse geocode result %s", playaAddress) playaAddress ?: "?" } } fun forwardGeocode(context: Context, playaAddress: String): Single<LatLng> { return Single.just(true) .observeOn(jsScheduler) .map { ignored -> init(context) val result = LatLng() Timber.d("Forward geocoding '$playaAddress'...") if (playaAddress.length < 8) { Timber.w("Invalid playa address $playaAddress, not geocoding") } else { // Call into the JavaScript object to decode a string. val latLon = v8?.executeObjectScript("coder.forward(\"$playaAddress\")") Timber.d("Forward geocode result %s", latLon) latLon?.let { if (it.toString() == "undefined") { Timber.w("Undefined result for $playaAddress") return@let } val rawCoords = it.getObject("geometry").getObject("coordinates") if (rawCoords is V8Array) { var item: V8Array = rawCoords while (item.type != 2 /* double */) { item = item.getArray(0) } val coords = item.getDoubles(0, 2) Timber.d("Got coords! ${coords[0]}, ${coords[1]}") result.latitude = coords[1] result.longitude = coords[0] } } } result } } private fun init(context: Context) { if (jsContent == null) { Timber.d("Loading JS...") val inStream = context.assets.open(jsPath) jsContent = inStream.bufferedReader().use { it.readText() } inStream.close() Timber.d("Loaded JS") } if (v8 == null) { Timber.d("Creating V8...") v8 = V8.createV8Runtime() Timber.d("Created V8. Initializing Geocoder...") v8?.executeVoidScript("var window = this;") v8?.executeVoidScript(jsContent) v8?.executeVoidScript("var coder = window.prepare();") Timber.d("Initialized Geocoder") } } fun close() { Timber.d("Closing") jsScheduler.scheduleDirect { v8?.release() v8 = null } } }
mpl-2.0
47ed352d1886e6879b89ff75d67b6564
33.517544
96
0.491612
4.893035
false
false
false
false
signed/intellij-community
platform/projectModel-api/src/com/intellij/openapi/components/StoredProperty.kt
1
7955
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.components import com.intellij.openapi.util.ModificationTracker import com.intellij.util.SmartList import com.intellij.util.xmlb.Accessor import com.intellij.util.xmlb.SerializationFilter import com.intellij.util.xmlb.annotations.Transient import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty abstract class BaseState : SerializationFilter, ModificationTracker { // if property value differs from default private val properties: MutableList<StoredProperty> = SmartList() @Volatile internal var modificationCount: Long = 0 // reset on load state fun resetModificationCount() { modificationCount = 0 } protected fun incrementModificationCount() { modificationCount++ } override fun accepts(accessor: Accessor, bean: Any): Boolean { for (property in properties) { if (property.name == accessor.name) { return property.value != property.defaultValue } } return false } fun <T> storedProperty(defaultValue: T? = null): ReadWriteProperty<BaseState, T?> { val result = ObjectStoredProperty(defaultValue) properties.add(result) return result } /** * Empty string is always normalized to null. */ fun string(defaultValue: String? = null): ReadWriteProperty<BaseState, String?> { val result = StringStoredProperty(defaultValue) properties.add(result) return result } fun storedProperty(defaultValue: Int = 0): ReadWriteProperty<BaseState, Int> { val result = IntStoredProperty(defaultValue) properties.add(result) return result } fun storedProperty(defaultValue: Float = 0f): ReadWriteProperty<BaseState, Float> { val result = FloatStoredProperty(defaultValue) properties.add(result) return result } fun storedProperty(defaultValue: Boolean = false): ReadWriteProperty<BaseState, Boolean> { val result = ObjectStoredProperty(defaultValue) properties.add(result) return result } @Transient override fun getModificationCount(): Long { var result = modificationCount for (property in properties) { val value = property.value if (value is ModificationTracker) { result += value.modificationCount } } return result } override fun equals(other: Any?) = this === other || (other is BaseState && properties == other.properties) override fun hashCode() = properties.hashCode() override fun toString(): String { if (properties.isEmpty()) { return "" } val builder = StringBuilder() for (property in properties) { builder.append(property.value).append(" ") } builder.setLength(builder.length - 1) return builder.toString() } fun copyFrom(state: BaseState) { assert(state.properties.size == properties.size) for ((index, property) in properties.withIndex()) { val otherProperty = state.properties.get(index) if (property.name != null) { if (otherProperty.name == null) { otherProperty.name = property.name } else { assert(otherProperty.name == property.name) } } property.setValue(otherProperty) } } } internal interface StoredProperty { val defaultValue: Any? val value: Any? var name: String? fun setValue(other: StoredProperty) } private class ObjectStoredProperty<T>(override val defaultValue: T) : ReadWriteProperty<BaseState, T>, StoredProperty { override var value = defaultValue override var name: String? = null override operator fun getValue(thisRef: BaseState, property: KProperty<*>): T { name = property.name return value } @Suppress("UNCHECKED_CAST") override fun setValue(thisRef: BaseState, property: KProperty<*>, @Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE") newValue: T) { name = property.name if (value != newValue) { thisRef.modificationCount++ value = newValue } } override fun equals(other: Any?) = this === other || (other is ObjectStoredProperty<*> && value == other.value) override fun hashCode() = value?.hashCode() ?: 0 override fun toString() = if (value === defaultValue) "" else value?.toString() ?: super.toString() override fun setValue(other: StoredProperty) { @Suppress("UNCHECKED_CAST") value = (other as ObjectStoredProperty<T>).value } } private class StringStoredProperty(override val defaultValue: String?) : ReadWriteProperty<BaseState, String?>, StoredProperty { override var value = defaultValue override var name: String? = null override operator fun getValue(thisRef: BaseState, property: KProperty<*>): String? { name = property.name return value } @Suppress("UNCHECKED_CAST") override fun setValue(thisRef: BaseState, property: KProperty<*>, @Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE") _newValue: String?) { name = property.name var newValue = _newValue if (newValue != null && newValue.isEmpty()) { newValue = null } if (value != newValue) { thisRef.modificationCount++ value = newValue } } override fun equals(other: Any?) = this === other || (other is ObjectStoredProperty<*> && value == other.value) override fun hashCode() = value?.hashCode() ?: 0 override fun toString() = if (value == defaultValue) "" else value ?: super.toString() override fun setValue(other: StoredProperty) { value = (other as StringStoredProperty).value } } private class IntStoredProperty(override val defaultValue: Int) : ReadWriteProperty<BaseState, Int>, StoredProperty { override var value = defaultValue override var name: String? = null override operator fun getValue(thisRef: BaseState, property: KProperty<*>): Int { name = property.name return value } @Suppress("UNCHECKED_CAST") override fun setValue(thisRef: BaseState, property: KProperty<*>, @Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE") newValue: Int) { name = property.name if (value != newValue) { thisRef.modificationCount++ value = newValue } } override fun equals(other: Any?) = this === other || (other is IntStoredProperty && value == other.value) override fun hashCode() = value.hashCode() override fun toString() = if (value == defaultValue) "" else value.toString() override fun setValue(other: StoredProperty) { value = (other as IntStoredProperty).value } } private class FloatStoredProperty(override val defaultValue: Float) : ReadWriteProperty<BaseState, Float>, StoredProperty { override var value = defaultValue override var name: String? = null override operator fun getValue(thisRef: BaseState, property: KProperty<*>): Float { name = property.name return value } @Suppress("UNCHECKED_CAST") override fun setValue(thisRef: BaseState, property: KProperty<*>, @Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE") newValue: Float) { name = property.name if (value != newValue) { thisRef.modificationCount++ value = newValue } } override fun equals(other: Any?) = this === other || (other is FloatStoredProperty && value == other.value) override fun hashCode() = value.hashCode() override fun toString() = if (value == defaultValue) "" else value.toString() override fun setValue(other: StoredProperty) { value = (other as FloatStoredProperty).value } }
apache-2.0
091768ada447f513834bfbc4f7d8228d
28.909774
137
0.698806
4.543118
false
false
false
false
Magneticraft-Team/Magneticraft
ignore/test/block/BlockFallingBase.kt
2
3367
package block import com.cout970.magneticraft.misc.world.isServer import com.teamwizardry.librarianlib.common.base.block.BlockMod import net.minecraft.block.Block import net.minecraft.block.material.Material import net.minecraft.block.state.IBlockState import net.minecraft.entity.item.EntityFallingBlock import net.minecraft.init.Blocks import net.minecraft.util.math.BlockPos import net.minecraft.world.World import java.util.* /** * Created by Yurgen on 18/10/2016. */ open class BlockFallingBase( registryName: String, unlocalizedName: String = registryName) : BlockMod( registryName, Material.SAND, unlocalizedName) { /** * Called after the block is set in the Chunk data, but before the Tile Entity is set */ override fun onBlockAdded(worldIn: World, pos: BlockPos, state: IBlockState) { worldIn.scheduleUpdate(pos, this, this.tickRate(worldIn)) } /** * Called when a neighboring block was changed and marks that this state should perform any checks during a neighbor * change. Cases may include when redstone power is updated, cactus blocks popping off due to a neighboring solid * block, etc. */ override fun neighborChanged(state: IBlockState, worldIn: World, pos: BlockPos, blockIn: Block) { worldIn.scheduleUpdate(pos, this, this.tickRate(worldIn)) } override fun updateTick(worldIn: World, pos: BlockPos, state: IBlockState, rand: Random) { if (worldIn.isServer) { this.checkFallable(worldIn, pos) } } private fun checkFallable(worldIn: World, pos: BlockPos) { if ((worldIn.isAirBlock(pos.down()) || canFallThrough(worldIn.getBlockState(pos.down()))) && pos.y >= 0) { val i = 32 if (!fallInstantly && worldIn.isAreaLoaded(pos.add(-i, -i, -i), pos.add(i, i, i))) { if (worldIn.isServer) { val entityfallingblock = EntityFallingBlock(worldIn, pos.x.toDouble() + 0.5, pos.y.toDouble(), pos.z.toDouble() + 0.5, worldIn.getBlockState(pos)) this.onStartFalling(entityfallingblock) worldIn.spawnEntityInWorld(entityfallingblock) } } else { worldIn.setBlockToAir(pos) var blockpos: BlockPos blockpos = pos.down() while ((worldIn.isAirBlock(blockpos) || canFallThrough( worldIn.getBlockState(blockpos))) && blockpos.y > 0) { blockpos = blockpos.down() } if (blockpos.y > 0) { worldIn.setBlockState(blockpos.up(), this.defaultState) } } } } protected open fun onStartFalling(fallingEntity: EntityFallingBlock) { } /** * How many world ticks before ticking */ override fun tickRate(worldIn: World): Int { return 2 } companion object { var fallInstantly: Boolean = false fun canFallThrough(state: IBlockState): Boolean { val block = state.block val material = state.material return block === Blocks.FIRE || material === Material.AIR || material === Material.WATER || material === Material.LAVA } } }
gpl-2.0
5d5f5ab36f46960688f9fb62b27c5127
34.452632
130
0.612712
4.384115
false
false
false
false
Agusyc/DayCounter
app/src/main/java/com/agusyc/daycounter/CounterNotificator.kt
1
9935
package com.agusyc.daycounter import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.res.Resources import android.graphics.drawable.Icon import android.os.Build import android.support.v4.app.NotificationCompat import android.util.Log import org.joda.time.DateTime import org.joda.time.Days import java.util.* class CounterNotificator : BroadcastReceiver() { // This variables represent the context resources and system notification manager var res: Resources? = null private var nm: NotificationManager? = null override fun onReceive(context: Context, intent: Intent) { // We initialise the variables res = context.resources nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager // We check if the intent is right if (intent.action == ACTION_UPDATE_NOTIFICATIONS) { // We notify all the widget counter if (intent.hasExtra("widget_ids")) notify(intent.getIntArrayExtra("widget_ids"), true, context) // We notify all the list counters if (intent.hasExtra("list_ids")) notify(intent.getIntArrayExtra("list_ids"), false, context) } else if (intent.action.startsWith(ACTION_RESET_COUNTER)) { // The reset button was pressed on the notification // We do some magic trickery to get the data from the action... (Intent extras don't work here) val data = intent.action.replace(ACTION_RESET_COUNTER, "").split(" ") val isWidget = Integer.parseInt(data[1]) == 1 val prefs = if (isWidget) context.getSharedPreferences("DaysPrefs", Context.MODE_PRIVATE) else context.getSharedPreferences("ListDaysPrefs", Context.MODE_PRIVATE) val id = Integer.parseInt(data[0]) // We set the date to today's prefs.edit().putLong("${id}date", DateTime.now().withTime(0, 0, 0, 0).millis).apply() // We tell the MainActivity to update its ListView val updateListView = Intent("com.agusyc.daycounter.UPDATE_LISTVIEW") context.sendBroadcast(updateListView) notify(intArrayOf(id), isWidget, context) // We update its widget (Only if it is a widget) if (isWidget) { val updateWidget = Intent(context, WidgetUpdater::class.java) updateWidget.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE updateWidget.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, intArrayOf(id)) context.sendBroadcast(updateWidget) } } } private fun notify(ids: IntArray, areWidget: Boolean, context: Context) { // We go trough each id in the array for (id in ids) { // The current counter being processed by the for loop: val counter = Counter(context, id, areWidget) // We only notify it if it's a notification-enabled counter if (counter.notification) { // We get the current time, for calculating the difference val currentTime = System.currentTimeMillis() // We use the Joda-Time method to calculate the difference val difference = Days.daysBetween(DateTime(counter.date), DateTime(currentTime)).days val absDifference = Math.abs(difference) val contentText: String // We set the contentText depeding on the sign of the difference (Positive is since, negative is until and 0 is today) contentText = when { difference > 0 -> "${res!!.getQuantityString(R.plurals.there_has_have_been, absDifference)} $absDifference ${res!!.getQuantityString(R.plurals.days_since, absDifference, counter.label)}" difference < 0 -> "${res!!.getQuantityString(R.plurals.there_is_are, absDifference)} $absDifference ${res!!.getQuantityString(R.plurals.days_until, absDifference, counter.label)}" else -> context.getString(R.string.there_are_no_days_since, counter.label) } // Variables for starting the MainActivity when the notification is clicked val notificationIntent = Intent(context, MainActivity::class.java) val resetIntent = Intent(context, CounterNotificator::class.java) resetIntent.action = "$ACTION_RESET_COUNTER$id ${if (areWidget) 1 else 0}" val resetPIntent = PendingIntent.getBroadcast(context, 0, resetIntent, PendingIntent.FLAG_ONE_SHOT) notificationIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP val main_act_intent = PendingIntent.getActivity(context, 0, notificationIntent, 0) // We now have channels in Android Oreo, so we use it *only* if the version is O or greater if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // The id of the channel. val channel_id = "daycounterchannel" // The user-visible name of the channel. val name = "DayCounter" // The user-visible description of the channel. val description = context.getString(R.string.channel_description) val importance = NotificationManager.IMPORTANCE_MIN val mChannel = NotificationChannel(channel_id, name, importance) // Configure the notification channel. mChannel.description = description mChannel.enableLights(false) mChannel.enableVibration(false) mChannel.setShowBadge(false) nm!!.createNotificationChannel(mChannel) // We build and notify the notification val mBuilder = Notification.Builder(context, channel_id) .setSmallIcon(R.drawable.reset_counter) .setContentTitle(context.getString(R.string.app_name)) .setOngoing(true) .setColor(counter.color) .setContentIntent(main_act_intent) .setContentText(contentText) .setCategory(Notification.CATEGORY_REMINDER) .setShowWhen(false) // We add the reset button only if it's a "since" counter if (difference > 0) mBuilder.addAction(Notification.Action.Builder(Icon.createWithResource(context, R.drawable.reset_counter), context.getString(R.string.reset_counter), resetPIntent).build()) nm!!.notify(id, mBuilder.build()) } else { Log.i("DayCounter", "Using old notification system") // We build and notify the notification @Suppress("DEPRECATION") val mBuilder = NotificationCompat.Builder(context) .setSmallIcon(R.drawable.reset_counter) .setContentTitle(context.getString(R.string.app_name)) .setOngoing(true) .setColor(counter.color) .setContentIntent(main_act_intent) .setContentText(contentText) .setCategory(Notification.CATEGORY_STATUS) .setPriority(Notification.PRIORITY_MIN) .setShowWhen(false) // We add the reset button only if it's a "since" counter if (difference > 0) mBuilder.addAction(R.drawable.reset_counter, context.getString(R.string.reset_counter), resetPIntent) nm!!.notify(id, mBuilder.build()) } } } } // This method takes care of executing the previous methods to update every counter. // It parses every ID in the set and sends it to the notificator fun updateAll(context: Context) { val updaterIntent = Intent(context, CounterNotificator::class.java) updaterIntent.action = CounterNotificator.ACTION_UPDATE_NOTIFICATIONS var prefs = context.getSharedPreferences("DaysPrefs", Context.MODE_PRIVATE) var IDs_set = prefs.getStringSet("ids", HashSet<String>()) var IDs_array_str = IDs_set!!.toTypedArray<String>() var IDs_array = IntArray(IDs_array_str.size) for (i in IDs_array_str.indices) { IDs_array[i] = Integer.parseInt(IDs_array_str[i]) Log.d("UpdateReceiver", "Parsed ID: " + IDs_array[i]) } updaterIntent.putExtra("widget_ids", IDs_array) prefs = context.getSharedPreferences("ListDaysPrefs", Context.MODE_PRIVATE) IDs_set = prefs.getStringSet("ids", HashSet<String>()) IDs_array_str = IDs_set!!.toTypedArray() IDs_array = IntArray(IDs_array_str.size) for (i in IDs_array_str.indices) { IDs_array[i] = Integer.parseInt(IDs_array_str[i]) Log.d("UpdateReceiver", "Parsed ID: " + IDs_array[i]) } updaterIntent.putExtra("list_ids", IDs_array) Log.d("UpdateReceiver", "Telling the CounterNotificator to start") context.sendBroadcast(updaterIntent) } companion object { internal val ACTION_UPDATE_NOTIFICATIONS = "com.agusyc.daycounter.ACTION_UPDATE_NOTIFICATIONS" internal val ACTION_RESET_COUNTER = "com.agusyc.daycounter.ACTION_RESET_COUNTER" } }
mit
8274c4b395865ef5c6cd515dc466a2c0
52.128342
220
0.612682
4.947709
false
false
false
false
AerisG222/maw_photos_android
MaWPhotos/src/main/java/us/mikeandwan/photos/ui/screens/about/AboutFragment.kt
1
1725
package us.mikeandwan.photos.ui.screens.about import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import us.mikeandwan.photos.R import us.mikeandwan.photos.databinding.FragmentAboutBinding @AndroidEntryPoint class AboutFragment : Fragment() { companion object { fun newInstance() = AboutFragment() } private lateinit var binding: FragmentAboutBinding private val viewModel by viewModels<AboutViewModel>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentAboutBinding.inflate(inflater) binding.lifecycleOwner = viewLifecycleOwner binding.viewModel = viewModel initStateObservers() return binding.root } private fun initStateObservers() { viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { withContext(Dispatchers.IO) { val history = resources .openRawResource(R.raw.release_notes) .bufferedReader() .use { it.readText() } viewModel.setHistory(history) } } } } }
mit
736db0547c2a519e63a1aba21a2085d4
29.821429
85
0.693913
5.493631
false
false
false
false
vsch/idea-multimarkdown
src/test/java/com/vladsch/md/nav/flex/TemplateTest.kt
1
5639
/* * Copyright (c) 2015-2019 Vladimir Schneider <[email protected]>, all rights reserved. * * This code is private property of the copyright holder and cannot be used without * having obtained a license or prior written permission of the copyright holder. * * 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.vladsch.md.nav.flex import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import java.util.* @RunWith(value = Parameterized::class) class TemplateTest( val number: Int, val text: String, val expected: String ) { @Test fun replaceText() { } companion object { @Parameterized.Parameters(name = "{0}") @JvmStatic fun data(): List<Array<Any>> { val data = ArrayList<Array<Any>>() var count = 0 data.add(arrayOf<Any>(++count, """prefix someCommands;//zzzoptionszzz(REMOVE, OPT2) suffix""", """prefix suffix""")) data.add(arrayOf<Any>(++count, """prefix // zzzoptionszzz(REMOVE, OPT1) suffix""", """prefix suffix""")) data.add(arrayOf<Any>(++count, """prefix someCommands;//zzzoptionszzz(REMOVE, OPT2) suffix""", """prefix suffix""")) data.add(arrayOf<Any>(++count, """prefix someCommands1;//zzzoptionszzz(REMOVE, OPT2) someCommands2;//zzzoptionszzz(REMOVE, OPT2) someCommands3;//zzzoptionszzz(REMOVE, OPT2) someCommands4;//zzzoptionszzz(REMOVE, OPT2) suffix""", """prefix suffix""")) data.add(arrayOf<Any>(++count, """prefix someCommands;//zzzoptionszzz(OPT2) suffix""", """prefix // someCommands; suffix""")) data.add(arrayOf<Any>(++count, """prefix someCommands1;//zzzoptionszzz(OPT2) someCommands2;//zzzoptionszzz(OPT2) someCommands3;//zzzoptionszzz(OPT2) someCommands4;//zzzoptionszzz(OPT2) suffix""", """prefix // someCommands1; // someCommands2; // someCommands3; // someCommands4; suffix""")) data.add(arrayOf<Any>(++count, """prefix import com.vladsch.flexmark.internal.util.KeepType;//zzzoptionszzz(OPT2) suffix""", """prefix // import com.vladsch.flexmark.internal.util.KeepType; suffix""")) data.add(arrayOf<Any>(++count, """prefix public void extend(Parser.Builder parserBuilder) { parserBuilder.customBlockParserFactory(new ZzzzzzBlockParser.Factory());//zzzoptionszzz(REMOVE, OPT1) parserBuilder.paragraphPreProcessorFactory(ZzzzzzParagraphPreProcessor.Factory());//zzzoptionszzz(REMOVE, OPT2) parserBuilder.blockPreProcessorFactory(new ZzzzzzBlockPreProcessorFactory());//zzzoptionszzz(REMOVE, OPT3) parserBuilder.customDelimiterProcessor(new ZzzzzzDelimiterProcessor());//zzzoptionszzz(REMOVE, OPT1, OPT2) parserBuilder.linkRefProcessor(new ZzzzzzLinkRefProcessor(parserBuilder));//zzzoptionszzz(REMOVE, OPT2, OPT3) parserBuilder.postProcessor(new ZzzzzzPostProcessor());//zzzoptionszzz(REMOVE, OPT2) } suffix""", """prefix public void extend(Parser.Builder parserBuilder) { parserBuilder.customBlockParserFactory(new ZzzzzzBlockParser.Factory()); parserBuilder.blockPreProcessorFactory(new ZzzzzzBlockPreProcessorFactory()); parserBuilder.customDelimiterProcessor(new ZzzzzzDelimiterProcessor()); parserBuilder.linkRefProcessor(new ZzzzzzLinkRefProcessor(parserBuilder)); } suffix""")) data.add(arrayOf<Any>(++count, """prefix public void extend(Parser.Builder parserBuilder) { //zzzoptionszzz(REMOVE, OPT2) //zzzoptionszzz(OPT2) //zzzoptionszzz(REMOVE, OPT2) //zzzoptionszzz(REMOVE, OPT2) //zzzoptionszzz(OPT1) //zzzoptionszzz(OPT2) //zzzoptionszzz(OPT3) //zzzoptionszzz(OPT2) //zzzoptionszzz(OPT1) //zzzoptionszzz(OPT2) //zzzoptionszzz(OPT3) parserBuilder.customBlockParserFactory(new ZzzzzzBlockParser.Factory());//zzzoptionszzz(REMOVE, OPT1) parserBuilder.paragraphPreProcessorFactory(ZzzzzzParagraphPreProcessor.Factory());//zzzoptionszzz(REMOVE, OPT2) parserBuilder.blockPreProcessorFactory(new ZzzzzzBlockPreProcessorFactory());//zzzoptionszzz(REMOVE, OPT3) parserBuilder.customDelimiterProcessor(new ZzzzzzDelimiterProcessor());//zzzoptionszzz(REMOVE, OPT1, OPT2) parserBuilder.linkRefProcessor(new ZzzzzzLinkRefProcessor(parserBuilder));//zzzoptionszzz(REMOVE, OPT2, OPT3) parserBuilder.postProcessor(new ZzzzzzPostProcessor());//zzzoptionszzz(REMOVE, OPT2) } suffix""", """prefix public void extend(Parser.Builder parserBuilder) { parserBuilder.customBlockParserFactory(new ZzzzzzBlockParser.Factory()); parserBuilder.blockPreProcessorFactory(new ZzzzzzBlockPreProcessorFactory()); parserBuilder.customDelimiterProcessor(new ZzzzzzDelimiterProcessor()); parserBuilder.linkRefProcessor(new ZzzzzzLinkRefProcessor(parserBuilder)); } suffix""")) return data } } @Test fun filterLines() { val template = Template("zzzoptionszzz(", ")", "zzzzzz") template.optionSet.addAll(listOf("OPT1", "OPT3")) assertEquals(expected, template.filterLines(text)) } }
apache-2.0
3f394b89e63f6ff3bdc906df66dfec6b
37.623288
119
0.693385
4.024982
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/ide/annotator/RsSyntaxErrorsAnnotator.kt
2
9676
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.annotator import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.ProblemHighlightType import com.intellij.lang.annotation.Annotation import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.Annotator import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import org.rust.ide.inspections.fixes.SubstituteTextFix import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* class RsSyntaxErrorsAnnotator : Annotator { override fun annotate(element: PsiElement, holder: AnnotationHolder) { when (element) { is RsFunction -> checkFunction(holder, element) is RsStructItem -> checkStructItem(holder, element) is RsTypeAlias -> checkTypeAlias(holder, element) is RsConstant -> checkConstant(holder, element) is RsValueParameterList -> checkValueParameterList(holder, element) is RsValueParameter -> checkValueParameter(holder, element) is RsTypeParameterList -> checkTypeParameterList(holder, element) } } } private fun checkFunction(holder: AnnotationHolder, fn: RsFunction) { when (fn.owner) { is RsFunctionOwner.Free -> { require(fn.block, holder, "${fn.title} must have a body", fn.lastChild) deny(fn.default, holder, "${fn.title} cannot have the `default` qualifier") } is RsFunctionOwner.Trait -> { deny(fn.default, holder, "${fn.title} cannot have the `default` qualifier") deny(fn.vis, holder, "${fn.title} cannot have the `pub` qualifier") deny(fn.const, holder, "Trait functions cannot be declared const [E0379]") } is RsFunctionOwner.Impl -> { require(fn.block, holder, "${fn.title} must have a body", fn.lastChild) if (fn.default != null) { deny(fn.vis, holder, "Default ${fn.title.firstLower} cannot have the `pub` qualifier") } } is RsFunctionOwner.Foreign -> { deny(fn.default, holder, "${fn.title} cannot have the `default` qualifier") deny(fn.block, holder, "${fn.title} cannot have a body") deny(fn.const, holder, "${fn.title} cannot have the `const` qualifier") deny(fn.unsafe, holder, "${fn.title} cannot have the `unsafe` qualifier") deny(fn.externAbi, holder, "${fn.title} cannot have an extern ABI") } } } private fun checkStructItem(holder: AnnotationHolder, struct: RsStructItem) { if (struct.kind == RsStructKind.UNION && struct.tupleFields != null) { deny(struct.tupleFields, holder, "Union cannot be tuple-like") } } private fun checkTypeAlias(holder: AnnotationHolder, ta: RsTypeAlias) { val title = "Type `${ta.identifier.text}`" val owner = ta.owner when (owner) { is RsTypeAliasOwner.Free -> { deny(ta.default, holder, "$title cannot have the `default` qualifier") deny(ta.typeParamBounds, holder, "$title cannot have type parameter bounds") require(ta.typeReference, holder, "Aliased type must be provided for type `${ta.identifier.text}`", ta) } is RsTypeAliasOwner.Trait -> { deny(ta.default, holder, "$title cannot have the `default` qualifier") deny(ta.vis, holder, "$title cannot have the `pub` qualifier") deny(ta.typeParameterList, holder, "$title cannot have generic parameters") deny(ta.whereClause, holder, "$title cannot have `where` clause") } is RsTypeAliasOwner.Impl -> { if (owner.impl.`for` == null) { holder.createErrorAnnotation(ta, "Associated types are not allowed in inherent impls [E0202]") } else { deny(ta.typeParameterList, holder, "$title cannot have generic parameters") deny(ta.whereClause, holder, "$title cannot have `where` clause") deny(ta.typeParamBounds, holder, "$title cannot have type parameter bounds") require(ta.typeReference, holder, "Aliased type must be provided for type `${ta.identifier.text}`", ta) } } } } private fun checkConstant(holder: AnnotationHolder, const: RsConstant) { val title = if (const.static != null) "Static constant `${const.identifier.text}`" else "Constant `${const.identifier.text}`" when (const.owner) { is RsConstantOwner.Free -> { deny(const.default, holder, "$title cannot have the `default` qualifier") require(const.expr, holder, "$title must have a value", const) } is RsConstantOwner.Foreign -> { deny(const.default, holder, "$title cannot have the `default` qualifier") require(const.static, holder, "Only static constants are allowed in extern blocks", const.const) deny(const.expr, holder, "Static constants in extern blocks cannot have values", const.eq, const.expr) } is RsConstantOwner.Trait -> { deny(const.vis, holder, "$title cannot have the `pub` qualifier") deny(const.default, holder, "$title cannot have the `default` qualifier") deny(const.static, holder, "Static constants are not allowed in traits") } is RsConstantOwner.Impl -> { deny(const.static, holder, "Static constants are not allowed in impl blocks") require(const.expr, holder, "$title must have a value", const) } } } private fun checkValueParameterList(holder: AnnotationHolder, params: RsValueParameterList) { val fn = params.parent as? RsFunction ?: return when (fn.owner) { is RsFunctionOwner.Free -> { deny(params.selfParameter, holder, "${fn.title} cannot have `self` parameter") deny(params.dotdotdot, holder, "${fn.title} cannot be variadic") } is RsFunctionOwner.Trait, is RsFunctionOwner.Impl -> { deny(params.dotdotdot, holder, "${fn.title} cannot be variadic") } RsFunctionOwner.Foreign -> { deny(params.selfParameter, holder, "${fn.title} cannot have `self` parameter") checkDot3Parameter(holder, params.dotdotdot) } } } private fun checkDot3Parameter(holder: AnnotationHolder, dot3: PsiElement?) { if (dot3 == null) return dot3.rightVisibleLeaves .first { if (it.text != ")") { holder.createErrorAnnotation(it, "`...` must be last in argument list for variadic function") } return } } private fun checkValueParameter(holder: AnnotationHolder, param: RsValueParameter) { val fn = param.parent.parent as? RsFunction ?: return when (fn.owner) { is RsFunctionOwner.Free, is RsFunctionOwner.Impl, is RsFunctionOwner.Foreign -> { require(param.pat, holder, "${fn.title} cannot have anonymous parameters", param) } is RsFunctionOwner.Trait -> { denyType<RsPatTup>(param.pat, holder, "${fn.title} cannot have tuple parameters", param) if (param.pat == null) { val annotation = holder .createWarningAnnotation(param, "Anonymous functions parameters are deprecated (RFC 1685)") val fix = SubstituteTextFix(param.textRange, "_: ${param.text}", "Add dummy parameter name") val descriptor = InspectionManager.getInstance(param.project) .createProblemDescriptor(param, annotation.message, fix, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, true) annotation.registerFix(fix, null, null, descriptor) } } } } private fun checkTypeParameterList(holder: AnnotationHolder, element: RsTypeParameterList) { val lifetimeParams = element.lifetimeParameterList if (lifetimeParams.isEmpty()) return val startOfTypeParams = element.typeParameterList.firstOrNull()?.textOffset ?: return for (e in lifetimeParams) { if (e.textOffset > startOfTypeParams) { holder.createErrorAnnotation(e, "Lifetime parameters must be declared prior to type parameters") } } } private fun require(el: PsiElement?, holder: AnnotationHolder, message: String, vararg highlightElements: PsiElement?): Annotation? = if (el != null) null else holder.createErrorAnnotation(highlightElements.combinedRange ?: TextRange.EMPTY_RANGE, message) private fun deny(el: PsiElement?, holder: AnnotationHolder, message: String, vararg highlightElements: PsiElement?): Annotation? = if (el == null) null else holder.createErrorAnnotation(highlightElements.combinedRange ?: el.textRange, message) private inline fun <reified T : RsCompositeElement> denyType(el: PsiElement?, holder: AnnotationHolder, message: String, vararg highlightElements: PsiElement?): Annotation? = if (el !is T) null else holder.createErrorAnnotation(highlightElements.combinedRange ?: el.textRange, message) private val Array<out PsiElement?>.combinedRange: TextRange? get() = if (isEmpty()) null else filterNotNull() .map { it.textRange } .reduce(TextRange::union) private val PsiElement.rightVisibleLeaves: Sequence<PsiElement> get() = generateSequence(PsiTreeUtil.nextVisibleLeaf(this), { el -> PsiTreeUtil.nextVisibleLeaf(el) }) private val String.firstLower: String get() = if (isEmpty()) this else this[0].toLowerCase() + substring(1)
mit
f580419a9e030c6da660d753202b79ae
45.743961
174
0.657193
4.473417
false
false
false
false
jtransc/jtransc
benchmark_kotlin_mpp/wip/jzlib/Inflater.kt
1
4527
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ /* Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly([email protected]) and Mark Adler([email protected]) * and contributors of zlib. */ package com.jtransc.compression.jzlib import com.jtransc.annotation.JTranscInvisible import com.jtransc.compression.jzlib.JZlib.WrapperType @JTranscInvisible class Inflater : ZStream { constructor() : super() { init() } constructor(wrapperType: WrapperType) : this(DEF_WBITS, wrapperType) {} constructor(w: Int, wrapperType: WrapperType) : super() { val ret = init(w, wrapperType) if (ret != Z_OK) throw GZIPException("$ret: $msg") } constructor(nowrap: Boolean) : this(DEF_WBITS, nowrap) {} @JvmOverloads constructor(w: Int, nowrap: Boolean = false) : super() { val ret = init(w, nowrap) if (ret != Z_OK) throw GZIPException("$ret: $msg") } private var finished = false fun init(wrapperType: WrapperType): Int { return init(DEF_WBITS, wrapperType) } fun init(w: Int, wrapperType: WrapperType): Int { var w = w var nowrap = false if (wrapperType === JZlib.W_NONE) { nowrap = true } else if (wrapperType === JZlib.W_GZIP) { w += 16 } else if (wrapperType === JZlib.W_ANY) { w = w or Inflate.INFLATE_ANY } else if (wrapperType === JZlib.W_ZLIB) { } return init(w, nowrap) } fun init(nowrap: Boolean): Int { return init(DEF_WBITS, nowrap) } @JvmOverloads fun init(w: Int = DEF_WBITS, nowrap: Boolean = false): Int { finished = false istate = Inflate(this) return istate.inflateInit(if (nowrap) -w else w) } override fun inflate(f: Int): Int { if (istate == null) return Z_STREAM_ERROR val ret: Int = istate.inflate(f) if (ret == Z_STREAM_END) finished = true return ret } override fun end(): Int { finished = true return if (istate == null) Z_STREAM_ERROR else istate.inflateEnd() // istate = null; } fun sync(): Int { return if (istate == null) Z_STREAM_ERROR else istate.inflateSync() } fun syncPoint(): Int { return if (istate == null) Z_STREAM_ERROR else istate.inflateSyncPoint() } fun setDictionary(dictionary: ByteArray?, index: Int, dictLength: Int): Int { return if (istate == null) Z_STREAM_ERROR else istate.inflateSetDictionary(dictionary, index, dictLength) } override fun finished(): Boolean { return istate.mode === 12 /*DONE*/ } companion object { private const val MAX_WBITS = 15 // 32K LZ77 window private const val DEF_WBITS = MAX_WBITS private const val Z_NO_FLUSH = 0 private const val Z_PARTIAL_FLUSH = 1 private const val Z_SYNC_FLUSH = 2 private const val Z_FULL_FLUSH = 3 private const val Z_FINISH = 4 private const val MAX_MEM_LEVEL = 9 private const val Z_OK = 0 private const val Z_STREAM_END = 1 private const val Z_NEED_DICT = 2 private const val Z_ERRNO = -1 private const val Z_STREAM_ERROR = -2 private const val Z_DATA_ERROR = -3 private const val Z_MEM_ERROR = -4 private const val Z_BUF_ERROR = -5 private const val Z_VERSION_ERROR = -6 } }
apache-2.0
4fab7f5a0fb65865862e69e05dc53ac8
32.294118
107
0.716368
3.424357
false
false
false
false
GlimpseFramework/glimpse-framework
api/src/main/kotlin/glimpse/Vector.kt
1
3709
package glimpse import glimpse.buffers.toDirectFloatBuffer /** * A vector in three-dimensional space. * * @param x X coordinate. * @param y Y coordinate. * @param z Z coordinate. */ data class Vector(val x: Float, val y: Float, val z: Float) { /** * Constructs a [Vector] from spherical coordinates. * * @param radius Radial coordinate. * @param inclination Inclination. * @param azimuth Azimuth. */ constructor(radius: Float, inclination: Angle, azimuth: Angle) : this( radius * sin(inclination) * cos(azimuth), radius * sin(inclination) * sin(azimuth), radius * cos(inclination)) companion object { /** * Null vector. */ val NULL = Vector(0f, 0f, 0f) /** * Unit vector in the direction of the X axis. */ val X_UNIT = Vector(1f, 0f, 0f) /** * Unit vector in the direction of the Y axis. */ val Y_UNIT = Vector(0f, 1f, 0f) /** * Unit vector in the direction of the Z axis. */ val Z_UNIT = Vector(0f, 0f, 1f) } internal val _3f: Array<Float> by lazy { arrayOf(x, y, z) } internal val _4f: Array<Float> by lazy { arrayOf(x, y, z, 1f) } /** * Returns a string representation of the [Vector]. */ override fun toString() = "[%.1f, %.1f, %.1f]".format(x, y, z) /** * Magnitude of the [Vector]. */ val magnitude by lazy { Math.sqrt((x * x + y * y + z * z).toDouble()).toFloat() } /** * Inclination of the vector in spherical coordinate system. */ val inclination by lazy { atan2(Vector(x, y, 0f).magnitude, z) } /** * Azimuth of the vector in spherical coordinate system. */ val azimuth by lazy { atan2(y, x) } /** * Returns a unit vector in the direction of this [Vector]. */ val normalize by lazy { normalize(1f) } /** * Returns a vector opposit to this vector. */ operator fun unaryMinus() = Vector(-x, -y, -z) /** * Returns a sum of this vector and the [other] vector. */ operator fun plus(other: Vector) = Vector(x + other.x, y + other.y, z + other.z) /** * Returns a difference of this vector and the [other] vector. */ operator fun minus(other: Vector) = Vector(x - other.x, y - other.y, z - other.z) /** * Returns a cross product of this vector and the [other] vector. */ operator fun times(other: Vector): Vector = Vector( y * other.z - z * other.y, z * other.x - x * other.z, x * other.y - y * other.x) /** * Returns a dot product of this vector and the [other] vector. */ infix fun dot(other: Vector): Float = _3f.zip(other._3f).map { it.first * it.second }.sum() /** * Returns a product of this vector and the [number]. */ operator fun times(number: Float) = Vector(x * number, y * number, z * number) /** * Returns a quotient of this vector and the [number]. */ operator fun div(number: Float) = Vector(x / number, y / number, z / number) /** * Returns `true` if this vector is parallel to the [other] vector. */ infix fun parallelTo(other: Vector) = this * other == NULL /** * Returns a vector of the given [magnitude], in the direction of this vector. */ fun normalize(magnitude: Float): Vector { require(this.magnitude > 0f) { "Cannot normalize a null vector. Division by 0." } return this * magnitude / this.magnitude } /** * Converts the [Vector] to a [Point]. */ fun toPoint() = Point(x, y, z) } /** * Returns a direct buffer containing values of X, Y, Z coordinates of vectors from the original list. */ fun List<Vector>.toDirectBuffer() = toDirectFloatBuffer(size * 3) { it._3f } /** * Returns a direct buffer containing values of X, Y, Z, 1 coordinates of augmented vectors from the original list. */ fun List<Vector>.toDirectBufferAugmented() = toDirectFloatBuffer(size * 4) { it._4f }
apache-2.0
a1324bf556cc38ebdd8c08a2ca674f20
25.119718
115
0.638717
3.132601
false
false
false
false
wisnia/Videooo
app/src/main/kotlin/com/wisnia/videooo/login/LoginActivity.kt
2
2689
package com.wisnia.videooo.login import android.app.Activity import android.content.Intent import android.os.Bundle import android.util.Log import com.wisnia.videooo.R import com.wisnia.videooo.authentication.AuthenticationActivity import com.wisnia.videooo.authentication.presentation.LoginPresenter import com.wisnia.videooo.authentication.view.LoginView import com.wisnia.videooo.data.authentication.Token import com.wisnia.videooo.extension.text import com.wisnia.videooo.mvp.PresentationActivity import com.wisnia.videooo.mvp.Presenter import dagger.android.AndroidInjection import kotlinx.android.synthetic.main.layout_login_form.* import javax.inject.Inject private const val WEB_AUTH_REQUEST_CODE = 101 const val TOKEN_KEY = "token" class LoginActivity : PresentationActivity<LoginView>(), LoginView { @Inject lateinit var presenter: LoginPresenter override fun getPresenter(): Presenter<LoginView> = presenter override fun onCreate(savedInstanceState: Bundle?) { AndroidInjection.inject(this) super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) authSignInButton.setOnClickListener { signIn() } authSignInWebsiteButton.setOnClickListener { presenter.signInWebsite() } authRegisterButton.setOnClickListener { TODO("implement showing registration screen") } authGuestButton.setOnClickListener { presenter.signInAsGuest() } } private fun signIn() { val login = authLoginInput.text() val password = authPasswordInput.text() presenter.signIn(login, password) } override fun showError(error: Throwable) { // TODO: show response error } override fun onSignedIn() { // TODO: show movies screen } override fun onWebsiteTokenReceived(token: Token) { val intent = Intent(this, AuthenticationActivity::class.java) intent.putExtra(TOKEN_KEY, token) startActivityForResult(intent, WEB_AUTH_REQUEST_CODE) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == WEB_AUTH_REQUEST_CODE) handleWebsiteAuthenticationResult(resultCode) } private fun handleWebsiteAuthenticationResult(resultCode: Int) { when (resultCode) { Activity.RESULT_OK -> { // TODO: show movies screen Log.d("LoginActivity", "Authentication success: User permission allowed") } Activity.RESULT_CANCELED -> { // TODO: show authentication error Log.d("LoginActivity", "Authentication failed: User permission denied") } } } }
apache-2.0
0adc7ca4a68ec096adf4788cb69dd444
34.394737
95
0.713276
4.810376
false
false
false
false
Retronic/life-in-space
core/src/main/kotlin/com/retronicgames/lis/visual/characters/AbstractVisualCharacter.kt
1
1869
/** * Copyright (C) 2015 Oleg Dolya * Copyright (C) 2015 Eduardo Garcia * * This file is part of Life in Space, by Retronic Games * * Life in Space 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. * * Life in Space 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 Life in Space. If not, see <http://www.gnu.org/licenses/>. */ package com.retronicgames.lis.visual.characters import com.retronicgames.lis.manager.Assets import com.retronicgames.lis.model.characters.GameCharacter import com.retronicgames.lis.visual.DataVisual import com.retronicgames.lis.visual.VisualMapCharacter import com.retronicgames.utils.RGSpriteWrapper abstract class AbstractVisualCharacter<CharacterType : GameCharacter<*, *>, VisualModelType : DataVisual>(character: CharacterType, val visualDataModel: VisualModelType) : VisualMapCharacter(RGSpriteWrapper(Assets.sprite("characters", "${character.data.id}_${character.state.value.name.toLowerCase()}", 0))) { init { val position = character.position val offset = visualDataModel.offset val xPos = position.x.toFloat() val yPos = position.y.toFloat() val xOff = offset.x.toFloat() val yOff = offset.y.toFloat() sprite.setPosition(xPos - xOff, yPos - yOff) sprite.setOrigin(xOff, yOff) character.visible.onChange { isVisible = this } character.position.onChange { oldX, oldY, newX, newY -> sprite.setPosition(newX - xOff, newY - yOff) } } }
gpl-3.0
1f9240c0bf28cb28c8e9f6cd1465d4a1
37.163265
171
0.752809
3.845679
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/snackbar/Snackbars.kt
1
11639
/* * 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.snackbar import android.app.Activity import android.os.Build import android.view.View import android.widget.TextView import androidx.annotation.RequiresApi import androidx.annotation.StringRes import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.fragment.app.Fragment import com.google.android.material.snackbar.Snackbar import com.google.android.material.snackbar.onAttachedToWindow2 import com.ichi2.anki.BuildConfig import com.ichi2.anki.R import com.ichi2.anki.UIUtils.showThemedToast import timber.log.Timber typealias SnackbarBuilder = Snackbar.() -> Unit /** * Show a snackbar. * * You can create snackbars by calling `showSnackbar` on either an activity or a view. * As `CoordinatorLayout` is responsible for proper placement and animation of snackbars, * * * if calling on an activity, the activity **MUST** have a `CoordinatorLayout` * with id `root_layout`; * * * if calling on a view, the view **MUST** be either a `CoordinatorLayout`, * or a (possibly indirect) child of `CoordinatorLayout`. * * Any additional configuration can be done in the configuration block, e.g. * * showSnackbar(text) { * addCallback(callback) * } * * @receiver An [Activity] that has a [CoordinatorLayout] with id `root_layout`. * @param textResource String resource to show, can be formatted. * @param duration Optional. For how long to show the snackbar. Can be one of: * [Snackbar.LENGTH_SHORT], [Snackbar.LENGTH_LONG] (default), [Snackbar.LENGTH_INDEFINITE], * or exact duration in milliseconds. * @param snackbarBuilder Optional. A configuration block with the [Snackbar] as `this`. */ fun Activity.showSnackbar( @StringRes textResource: Int, duration: Int = Snackbar.LENGTH_LONG, snackbarBuilder: SnackbarBuilder? = null ) { val text = getText(textResource) showSnackbar(text, duration, snackbarBuilder) } /** * Show a snackbar. * * You can create snackbars by calling `showSnackbar` on either an activity or a view. * As `CoordinatorLayout` is responsible for proper placement and animation of snackbars, * * * if calling on an activity, the activity **MUST** have a `CoordinatorLayout` * with id `root_layout`; * * * if calling on a view, the view **MUST** be either a `CoordinatorLayout`, * or a (possibly indirect) child of `CoordinatorLayout`. * * Any additional configuration can be done in the configuration block, e.g. * * showSnackbar(text) { * addCallback(callback) * } * * @receiver An [Activity] that has a [CoordinatorLayout] with id `root_layout`. * @param text Text to show, can be formatted. * @param duration Optional. For how long to show the snackbar. Can be one of: * [Snackbar.LENGTH_SHORT], [Snackbar.LENGTH_LONG] (default), [Snackbar.LENGTH_INDEFINITE], * or exact duration in milliseconds. * @param snackbarBuilder Optional. A configuration block with the [Snackbar] as `this`. */ fun Activity.showSnackbar( text: CharSequence, duration: Int = Snackbar.LENGTH_LONG, snackbarBuilder: SnackbarBuilder? = null ) { val view: View? = findViewById(R.id.root_layout) if (view != null) { view.showSnackbar(text, duration, snackbarBuilder) } else { val errorMessage = "While trying to show a snackbar, " + "could not find a view with id root_layout in $this" if (BuildConfig.DEBUG) { throw IllegalArgumentException(errorMessage) } else { Timber.e(errorMessage) showThemedToast(this, text, false) } } } /** * Show a snackbar. * * You can create snackbars by calling `showSnackbar` on either an activity or a view. * As `CoordinatorLayout` is responsible for proper placement and animation of snackbars, * * * if calling on an activity, the activity **MUST** have a `CoordinatorLayout` * with id `root_layout`; * * * if calling on a view, the view **MUST** be either a `CoordinatorLayout`, * or a (possibly indirect) child of `CoordinatorLayout`. * * Any additional configuration can be done in the configuration block, e.g. * * showSnackbar(text) { * addCallback(callback) * } * * @receiver A [View] that is either a [CoordinatorLayout], * or a (possibly indirect) child of `CoordinatorLayout`. * @param textResource String resource to show, can be formatted. * @param duration Optional. For how long to show the snackbar. Can be one of: * [Snackbar.LENGTH_SHORT], [Snackbar.LENGTH_LONG] (default), [Snackbar.LENGTH_INDEFINITE], * or exact duration in milliseconds. * @param snackbarBuilder Optional. A configuration block with the [Snackbar] as `this`. */ fun View.showSnackbar( @StringRes textResource: Int, duration: Int = Snackbar.LENGTH_LONG, snackbarBuilder: SnackbarBuilder? = null ) { val text = resources.getText(textResource) showSnackbar(text, duration, snackbarBuilder) } /** * Show a snackbar. * * You can create snackbars by calling `showSnackbar` on either an activity or a view. * As `CoordinatorLayout` is responsible for proper placement and animation of snackbars, * * * if calling on an activity, the activity **MUST** have a `CoordinatorLayout` * with id `root_layout`; * * * if calling on a view, the view **MUST** be either a `CoordinatorLayout`, * or a (possibly indirect) child of `CoordinatorLayout`. * * Any additional configuration can be done in the configuration block, e.g. * * showSnackbar(text) { * addCallback(callback) * } * * @receiver A [View] that is either a [CoordinatorLayout], * or a (possibly indirect) child of `CoordinatorLayout`. * @param text Text to show, can be formatted. * @param duration Optional. For how long to show the snackbar. Can be one of: * [Snackbar.LENGTH_SHORT], [Snackbar.LENGTH_LONG] (default), [Snackbar.LENGTH_INDEFINITE], * or exact duration in milliseconds. * @param snackbarBuilder Optional. A configuration block with the [Snackbar] as `this`. */ fun View.showSnackbar( text: CharSequence, duration: Int = Snackbar.LENGTH_LONG, snackbarBuilder: SnackbarBuilder? = null ) { val snackbar = Snackbar.make(this, text, duration) snackbar.setMaxLines(2) snackbar.behavior = SwipeDismissBehaviorFix() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { snackbar.fixMarginsWhenInsetsChange() } if (snackbarBuilder != null) { snackbar.snackbarBuilder() } snackbar.show() } /** * Show a snackbar. * * You can create snackbars by calling `showSnackbar` on either an activity or a view. * As `CoordinatorLayout` is responsible for proper placement and animation of snackbars, * * * if calling on an activity, the activity **MUST** have a `CoordinatorLayout` * with id `root_layout`; * * * if calling on a view, the view **MUST** be either a `CoordinatorLayout`, * or a (possibly indirect) child of `CoordinatorLayout`. * * Any additional configuration can be done in the configuration block, e.g. * * showSnackbar(text) { * addCallback(callback) * } * * @receiver A [View] that is either a [CoordinatorLayout], * or a (possibly indirect) child of `CoordinatorLayout`. * @param text Text to show, can be formatted. * @param duration Optional. For how long to show the snackbar. Can be one of: * [Snackbar.LENGTH_SHORT], [Snackbar.LENGTH_LONG] (default), [Snackbar.LENGTH_INDEFINITE], * or exact duration in milliseconds. * @param snackbarBuilder Optional. A configuration block with the [Snackbar] as `this`. */ fun Fragment.showSnackbar( text: CharSequence, duration: Int = Snackbar.LENGTH_LONG, snackbarBuilder: SnackbarBuilder? = null ) { requireActivity().showSnackbar(text, duration, snackbarBuilder) } /** * Show a snackbar. * * You can create snackbars by calling `showSnackbar` on either an activity or a view. * As `CoordinatorLayout` is responsible for proper placement and animation of snackbars, * * * if calling on an activity, the activity **MUST** have a `CoordinatorLayout` * with id `root_layout`; * * * if calling on a view, the view **MUST** be either a `CoordinatorLayout`, * or a (possibly indirect) child of `CoordinatorLayout`. * * Any additional configuration can be done in the configuration block, e.g. * * showSnackbar(text) { * addCallback(callback) * } * * @receiver A [View] that is either a [CoordinatorLayout], * or a (possibly indirect) child of `CoordinatorLayout`. * @param textResource String resource to show, can be formatted. * @param duration Optional. For how long to show the snackbar. Can be one of: * [Snackbar.LENGTH_SHORT], [Snackbar.LENGTH_LONG] (default), [Snackbar.LENGTH_INDEFINITE], * or exact duration in milliseconds. * @param snackbarBuilder Optional. A configuration block with the [Snackbar] as `this`. */ fun Fragment.showSnackbar( @StringRes textResource: Int, duration: Int = Snackbar.LENGTH_LONG, snackbarBuilder: SnackbarBuilder? = null ) { val text = resources.getText(textResource) showSnackbar(text, duration, snackbarBuilder) } /* ********************************************************************************************** */ fun Snackbar.setMaxLines(maxLines: Int) { view.findViewById<TextView>(com.google.android.material.R.id.snackbar_text)?.maxLines = maxLines } /** * When bottom inset change, for instance, when keyboard is open or closed, * snackbar fails to adjust its margins and can appear too high or too low. * While snackbar does employ an `OnApplyWindowInsetsListener`, its methods don't get called. * This here is an atrocious workaround that solves the issue. It is awful and despicable. * * First of all, we use our own `OnApplyWindowInsetsListener`. Note that we *need to post it*, * as apparently something else resets it after this call. (Not sure if it's feasible * to find out what as this requires method breakpoints, which are prohibitively slow.) * Also, if we set an inset listener for a view, [View.dispatchApplyWindowInsets] will call * `onApplyWindowInsets` on our listener rather than the view, so we better call the original. * * Then, we want to call [Snackbar.updateMargins], which is private, * and the one method is not private that calls it is [Snackbar.onAttachedToWindow], * so we hack into its package namespace using a helper method. */ @RequiresApi(Build.VERSION_CODES.Q) private fun Snackbar.fixMarginsWhenInsetsChange() { view.post { view.rootView.setOnApplyWindowInsetsListener { rootView, insets -> onAttachedToWindow2() rootView.onApplyWindowInsets(insets) } } addCallback(object : Snackbar.Callback() { override fun onDismissed(snackbar: Snackbar, event: Int) { view.rootView.setOnApplyWindowInsetsListener(null) } }) }
gpl-3.0
94d1ebe4ae92f68a68bbcabec9b35b63
37.926421
100
0.702466
4.114175
false
true
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/ferry/AddFerryAccessMotorVehicle.kt
1
1404
package de.westnordost.streetcomplete.quests.ferry import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.CAR import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.RARE import de.westnordost.streetcomplete.ktx.toYesNo import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment class AddFerryAccessMotorVehicle : OsmFilterQuestType<Boolean>() { override val elementFilter = "ways, relations with route = ferry and !motor_vehicle" override val commitMessage = "Specify ferry access for motor vehicles" override val wikiLink = "Tag:route=ferry" override val icon = R.drawable.ic_quest_ferry override val hasMarkersAtEnds = true override val questTypeAchievements = listOf(RARE, CAR) override fun getTitle(tags: Map<String, String>): Int = if (tags.containsKey("name")) R.string.quest_ferry_motor_vehicle_name_title else R.string.quest_ferry_motor_vehicle_title override fun createForm() = YesNoQuestAnswerFragment() override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) { changes.add("motor_vehicle", answer.toYesNo()) } }
gpl-3.0
81727027b81a8287ca61dcff6a48091e
42.875
88
0.777778
4.543689
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/repository/PublisherRepository.kt
1
4073
package com.boardgamegeek.repository import android.content.SharedPreferences import androidx.core.content.contentValuesOf import androidx.lifecycle.MutableLiveData import com.boardgamegeek.BggApplication import com.boardgamegeek.db.CollectionDao import com.boardgamegeek.db.PublisherDao import com.boardgamegeek.entities.CompanyEntity import com.boardgamegeek.entities.PersonStatsEntity import com.boardgamegeek.extensions.* import com.boardgamegeek.io.Adapter import com.boardgamegeek.mappers.mapToEntity import com.boardgamegeek.provider.BggContract.Publishers import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class PublisherRepository(val application: BggApplication) { private val dao = PublisherDao(application) private val prefs: SharedPreferences by lazy { application.preferences() } suspend fun loadPublishers(sortBy: PublisherDao.SortType) = dao.loadPublishers(sortBy) suspend fun loadPublisher(publisherId: Int) = dao.loadPublisher(publisherId) suspend fun loadCollection(id: Int, sortBy: CollectionDao.SortType) = dao.loadCollection(id, sortBy) suspend fun delete() = dao.delete() suspend fun refreshPublisher(publisherId: Int): CompanyEntity? = withContext(Dispatchers.IO) { val response = Adapter.createForXml().company(publisherId) response.items.firstOrNull()?.mapToEntity()?.let { dao.upsert( publisherId, contentValuesOf( Publishers.Columns.PUBLISHER_NAME to it.name, Publishers.Columns.PUBLISHER_SORT_NAME to it.sortName, Publishers.Columns.PUBLISHER_DESCRIPTION to it.description, Publishers.Columns.PUBLISHER_IMAGE_URL to it.imageUrl, Publishers.Columns.PUBLISHER_THUMBNAIL_URL to it.thumbnailUrl, Publishers.Columns.UPDATED to System.currentTimeMillis(), ) ) it } } suspend fun refreshImages(publisher: CompanyEntity): CompanyEntity = withContext(Dispatchers.IO) { val response = Adapter.createGeekdoApi().image(publisher.thumbnailUrl.getImageId()) val url = response.images.medium.url dao.upsert(publisher.id, contentValuesOf(Publishers.Columns.PUBLISHER_HERO_IMAGE_URL to url)) publisher.copy(heroImageUrl = url) } suspend fun calculateWhitmoreScores(publishers: List<CompanyEntity>, progress: MutableLiveData<Pair<Int, Int>>) = withContext(Dispatchers.Default) { val sortedList = publishers.sortedBy { it.statsUpdatedTimestamp } val maxProgress = sortedList.size sortedList.forEachIndexed { i, data -> progress.postValue(i to maxProgress) val collection = dao.loadCollection(data.id) val statsEntity = PersonStatsEntity.fromLinkedCollection(collection, application) updateWhitmoreScore(data.id, statsEntity.whitmoreScore, data.whitmoreScore) } prefs[PREFERENCES_KEY_STATS_CALCULATED_TIMESTAMP_PUBLISHERS] = System.currentTimeMillis() progress.postValue(0 to 0) } suspend fun calculateStats(publisherId: Int): PersonStatsEntity = withContext(Dispatchers.Default) { val collection = dao.loadCollection(publisherId) val linkedCollection = PersonStatsEntity.fromLinkedCollection(collection, application) updateWhitmoreScore(publisherId, linkedCollection.whitmoreScore) linkedCollection } private suspend fun updateWhitmoreScore(id: Int, newScore: Int, oldScore: Int = -1) = withContext(Dispatchers.IO) { val realOldScore = if (oldScore == -1) dao.loadPublisher(id)?.whitmoreScore ?: 0 else oldScore if (newScore != realOldScore) { dao.upsert( id, contentValuesOf( Publishers.Columns.WHITMORE_SCORE to newScore, Publishers.Columns.PUBLISHER_STATS_UPDATED_TIMESTAMP to System.currentTimeMillis(), ) ) } } }
gpl-3.0
7669cf32993f4dded8e04fca8f6bf91b
46.360465
119
0.702431
4.814421
false
false
false
false
PaulWoitaschek/Voice
playback/src/main/kotlin/voice/playback/session/ChangeNotifier.kt
1
6206
package voice.playback.session import android.content.Context import android.net.Uri import android.support.v4.media.MediaDescriptionCompat import android.support.v4.media.MediaMetadataCompat import android.support.v4.media.session.MediaSessionCompat import android.support.v4.media.session.PlaybackStateCompat import android.support.v4.media.session.PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN import androidx.core.graphics.drawable.toBitmap import coil.imageLoader import coil.request.ImageRequest import voice.data.Book import voice.data.Chapter import voice.data.toUri import voice.playback.R import voice.playback.androidauto.AndroidAutoConnectedReceiver import voice.playback.di.PlaybackScope import javax.inject.Inject /** * Sets updated metadata on the media session and sends broadcasts about meta changes */ @PlaybackScope class ChangeNotifier @Inject constructor( private val bookUriConverter: BookUriConverter, private val mediaSession: MediaSessionCompat, private val context: Context, private val autoConnectedReceiver: AndroidAutoConnectedReceiver, ) { /** The last file the [.notifyChange] has used to update the metadata. **/ @Volatile private var lastFileForMetaData: Uri? = null private val playbackStateBuilder = PlaybackStateCompat.Builder() .setActions( PlaybackStateCompat.ACTION_FAST_FORWARD or PlaybackStateCompat.ACTION_PAUSE or PlaybackStateCompat.ACTION_PLAY or PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID or PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH or PlaybackStateCompat.ACTION_PLAY_PAUSE or PlaybackStateCompat.ACTION_REWIND or PlaybackStateCompat.ACTION_SEEK_TO or PlaybackStateCompat.ACTION_SKIP_TO_NEXT or PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS or PlaybackStateCompat.ACTION_SKIP_TO_QUEUE_ITEM or PlaybackStateCompat.ACTION_STOP, ) // use a different feature set for Android Auto private val playbackStateBuilderForAuto = PlaybackStateCompat.Builder() .setActions( PlaybackStateCompat.ACTION_PAUSE or PlaybackStateCompat.ACTION_PLAY or PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID or PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH or PlaybackStateCompat.ACTION_PLAY_PAUSE or PlaybackStateCompat.ACTION_SEEK_TO or PlaybackStateCompat.ACTION_SKIP_TO_QUEUE_ITEM or PlaybackStateCompat.ACTION_STOP, ) .addCustomAction( ANDROID_AUTO_ACTION_REWIND, context.getString(R.string.rewind), R.drawable.ic_fast_rewind, ) .addCustomAction( ANDROID_AUTO_ACTION_FAST_FORWARD, context.getString(R.string.fast_forward), R.drawable.ic_fast_forward, ) .addCustomAction( ANDROID_AUTO_ACTION_PREVIOUS, context.getString(R.string.previous_track), R.drawable.ic_skip_previous, ) .addCustomAction( ANDROID_AUTO_ACTION_NEXT, context.getString(R.string.next_track), R.drawable.ic_skip_next, ) fun updatePlaybackState(@PlaybackStateCompat.State state: Int, book: Book?) { val builder = if (autoConnectedReceiver.connected) { playbackStateBuilderForAuto } else { playbackStateBuilder } val playbackState = builder .apply { setState( state, book?.content?.positionInChapter ?: PLAYBACK_POSITION_UNKNOWN, book?.content?.playbackSpeed ?: 1F, ) if (book != null) { setActiveQueueItemId(book.chapters.indexOf(book.currentChapter).toLong()) } } .build() mediaSession.setPlaybackState(playbackState) } suspend fun updateMetadata(book: Book) { val content = book.content val currentChapter = book.currentChapter val bookName = content.name val chapterName = currentChapter.name val author = content.author if (lastFileForMetaData != content.currentChapter.toUri()) { appendQueue(book) val cover = context.imageLoader .execute( ImageRequest.Builder(context) .data(content.cover) .size( width = context.resources.getDimensionPixelSize(R.dimen.compat_notification_large_icon_max_width), height = context.resources.getDimensionPixelSize(R.dimen.compat_notification_large_icon_max_height), ) .fallback(R.drawable.album_art) .error(R.drawable.album_art) .allowHardware(false) .build(), ) .drawable!!.toBitmap() val mediaMetaData = MediaMetadataCompat.Builder() .putBitmap(MediaMetadataCompat.METADATA_KEY_ART, cover) .putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, cover) .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, currentChapter.duration) .putLong( MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, (content.currentChapterIndex + 1).toLong(), ) .putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, book.chapters.size.toLong()) .putString(MediaMetadataCompat.METADATA_KEY_TITLE, chapterName) .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, bookName) .putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, author) .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, author) .putString(MediaMetadataCompat.METADATA_KEY_AUTHOR, author) .putString(MediaMetadataCompat.METADATA_KEY_COMPOSER, author) .putString(MediaMetadataCompat.METADATA_KEY_GENRE, "Audiobook") .build() mediaSession.setMetadata(mediaMetaData) lastFileForMetaData = content.currentChapter.toUri() } } private fun appendQueue(book: Book) { val queue = book.chapters.mapIndexed { index, chapter -> MediaSessionCompat.QueueItem(chapter.toMediaDescription(book), index.toLong()) } if (queue.isNotEmpty()) { mediaSession.setQueue(queue) mediaSession.setQueueTitle(book.content.name) } } private fun Chapter.toMediaDescription(book: Book): MediaDescriptionCompat { return MediaDescriptionCompat.Builder() .setTitle(name) .setMediaId(bookUriConverter.chapter(book.id, id)) .build() } }
gpl-3.0
5b49e3366ec0054c6bd02171c0ba15e8
35.081395
114
0.713825
4.590237
false
false
false
false
if710/if710.github.io
2019-10-02/SystemServices/app/src/main/java/br/ufpe/cin/android/systemservices/jobscheduler/JobSchedulerActivity.kt
1
4850
package br.ufpe.cin.android.systemservices.jobscheduler import android.Manifest import android.app.Activity import android.app.AlarmManager import android.app.job.JobInfo import android.app.job.JobScheduler import android.content.* import android.content.pm.PackageManager import android.os.Bundle import android.widget.ArrayAdapter import android.widget.Toast import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.localbroadcastmanager.content.LocalBroadcastManager import br.ufpe.cin.android.systemservices.R import kotlinx.android.synthetic.main.activity_job_scheduler.* class JobSchedulerActivity : Activity() { internal var jobScheduler: JobScheduler? = null private val onDownloadCompleteEvent = object : BroadcastReceiver() { override fun onReceive(ctxt: Context, i: Intent) { toggleWidgets(true) Toast.makeText(ctxt, "Download finalizado!", Toast.LENGTH_LONG).show() startActivity(Intent(ctxt, DownloadViewActivity::class.java)) } } fun podeEscrever(): Boolean { return ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_job_scheduler) val periods = ArrayAdapter(this, android.R.layout.simple_spinner_item, resources.getStringArray(R.array.periods)) periods.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) period.adapter = periods botaoAgendar.setOnClickListener { agendarJob() toggleWidgets(false) } botaoCancelar.setOnClickListener { cancelarJobs() toggleWidgets(true) } jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler if (!podeEscrever()) { ActivityCompat.requestPermissions(this@JobSchedulerActivity, STORAGE_PERMISSIONS, WRITE_EXTERNAL_STORAGE_REQUEST) } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { when (requestCode) { WRITE_EXTERNAL_STORAGE_REQUEST -> if (!podeEscrever()) { Toast.makeText(this, "Sem permissão para escrita", Toast.LENGTH_SHORT).show() finish() } } } override fun onResume() { super.onResume() val f = IntentFilter(DownloadService.DOWNLOAD_COMPLETE) LocalBroadcastManager.getInstance(applicationContext).registerReceiver(onDownloadCompleteEvent, f) } override fun onPause() { super.onPause() LocalBroadcastManager.getInstance(applicationContext).unregisterReceiver(onDownloadCompleteEvent) } private fun toggleWidgets(enable: Boolean) { botaoAgendar.isEnabled = enable period.isEnabled = enable } private fun agendarJob() { val b = JobInfo.Builder(JOB_ID, ComponentName(this, DownloadJobService::class.java)) //criterio de rede b.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) //b.setRequiredNetworkType(JobInfo.NETWORK_TYPE_NONE); //define intervalo de periodicidade //b.setPeriodic(getPeriod()); //exige (ou nao) que esteja conectado ao carregador b.setRequiresCharging(false) //persiste (ou nao) job entre reboots //se colocar true, tem que solicitar permissao action_boot_completed //b.setPersisted(true) //exige (ou nao) que dispositivo esteja idle b.setRequiresDeviceIdle(false) //backoff criteria (linear ou exponencial) //b.setBackoffCriteria(1500, JobInfo.BACKOFF_POLICY_EXPONENTIAL); //periodo de tempo minimo pra rodar //so pode ser chamado se nao definir setPeriodic... b.setMinimumLatency(3000) //mesmo que criterios nao sejam atingidos, define um limite de tempo //so pode ser chamado se nao definir setPeriodic... b.setOverrideDeadline(6000) jobScheduler?.schedule(b.build()) } private fun cancelarJobs() { jobScheduler?.cancel(JOB_ID) // cancela todos os jobs da aplicacao // jobScheduler.cancelAll(); } private fun getPeriod(): Long { return PERIODS[period.selectedItemPosition] } companion object { private val JOB_ID = 710 private val PERIODS = longArrayOf(AlarmManager.INTERVAL_FIFTEEN_MINUTES, AlarmManager.INTERVAL_HALF_HOUR, AlarmManager.INTERVAL_HOUR) private val STORAGE_PERMISSIONS = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE) private val WRITE_EXTERNAL_STORAGE_REQUEST = 710 } }
mit
5faafa556750fe1ef3bbfc81b95e8ac9
33.884892
141
0.691277
4.493976
false
false
false
false
KasparPeterson/Globalwave
app/src/main/java/com/kasparpeterson/globalwave/recognition/SpeechRecognitionActivity.kt
1
4897
package com.kasparpeterson.globalwave.recognition import android.content.Intent import android.os.Bundle import android.os.Handler import android.speech.RecognitionListener import android.speech.RecognizerIntent import android.speech.SpeechRecognizer import android.util.Log import com.google.gson.Gson import com.kasparpeterson.globalwave.R import com.kasparpeterson.globalwave.language.LanguageProcessor import com.kasparpeterson.globalwave.spotify.SpotifyActivity import com.kasparpeterson.globalwave.spotify.search.model.Item import com.kasparpeterson.globalwave.spotify.search.SpotifySearchManager import kotlinx.android.synthetic.main.activity_speech_recognition.* import rx.Observer import rx.android.schedulers.AndroidSchedulers /** * Created by kaspar on 31/01/2017. */ class SpeechRecognitionActivity : SpotifyActivity(), RecognitionListener, Observer<Item?> { private val TAG = SpeechRecognitionActivity::class.java.simpleName private val LISTENING_DELAY = 2000L private val handler: Handler = Handler() private val languageProcessor = LanguageProcessor() var speechRecognizer: SpeechRecognizer? = null var recognizerIntent: Intent? = null var lastText = "" var spotifySearchManager: SpotifySearchManager? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_speech_recognition) spotifySearchManager = SpotifySearchManager() } override fun onSpotifyInitialised() { speechRecognizer = getRecognizer() recognizerIntent = getSpeechRecognizerIntent() startListening() } private fun getRecognizer(): SpeechRecognizer { val recognizer = SpeechRecognizer.createSpeechRecognizer(this) recognizer.setRecognitionListener(this) return recognizer } private fun getSpeechRecognizerIntent(): Intent { val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH) intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, "en") intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.packageName) intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3) intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH) return intent } override fun onRmsChanged(rmsdB: Float) { Log.d(TAG, "onRmsChanged") } override fun onEndOfSpeech() { Log.d(TAG, "onEndOfSpeech") } override fun onReadyForSpeech(params: Bundle?) { Log.d(TAG, "onReadyForSpeech") speech_recognition_result_text_view.text = getString(R.string.speech_recognition_listening) speech_recognition_last_text_text_view.text = lastText } override fun onBufferReceived(buffer: ByteArray?) { Log.d(TAG, "onBufferReceived") } override fun onPartialResults(partialResults: Bundle?) { Log.d(TAG, "onPartialResults") } override fun onEvent(eventType: Int, params: Bundle?) { Log.d(TAG, "onEvent") } override fun onBeginningOfSpeech() { Log.d(TAG, "onBeginningOfSpeech") } override fun onError(error: Int) { val errorText = getErrorText(error) speech_recognition_result_text_view.text = errorText Log.e(TAG, "onError, message: " + errorText) startListening() } override fun onResults(results: Bundle?) { if (results != null) tryToRecognise(results) startListening() } private fun tryToRecognise(results: Bundle) { val matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION) showBestMatch(matches) parseSpeech(matches[0]) printMatches(matches) lastText = matches[0] } private fun printMatches(matches: List<String>) { var text = "" for (match in matches) text += match + "\n" Log.d(TAG, "Result: " + text) } private fun showBestMatch(matches: List<String>) { speech_recognition_result_text_view.text = matches[0] } private fun startListening() { speechRecognizer?.cancel() handler.postDelayed({ speechRecognizer?.startListening(recognizerIntent) }, LISTENING_DELAY) } private fun parseSpeech(result: String) { Log.e(TAG, "parseSpeech: " + result) spotifySearchManager!!.getBestMatch(languageProcessor.process(result)) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this) } override fun onError(e: Throwable?) { Log.e(TAG, "onError", e) } override fun onNext(item: Item?) { Log.d(TAG, "onNext, item: " + Gson().toJson(item)) if (item != null && item.uri != null) play(item.uri!!) } override fun onCompleted() {} }
mit
e634960e6fed747b9dfb42eb7ddc7067
30.805195
99
0.686747
4.333628
false
false
false
false
clangen/musikcube
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/settings/activity/SettingsActivity.kt
1
19740
package io.casey.musikcube.remote.ui.settings.activity import android.app.Dialog import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.* import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import com.uacf.taskrunner.Task import com.uacf.taskrunner.Tasks import io.casey.musikcube.remote.R import io.casey.musikcube.remote.service.playback.PlayerWrapper import io.casey.musikcube.remote.service.playback.impl.streaming.StreamProxy import io.casey.musikcube.remote.ui.navigation.Transition import io.casey.musikcube.remote.ui.settings.constants.Prefs import io.casey.musikcube.remote.ui.settings.model.Connection import io.casey.musikcube.remote.ui.settings.model.ConnectionsDb import io.casey.musikcube.remote.ui.shared.activity.BaseActivity import io.casey.musikcube.remote.ui.shared.extension.* import io.casey.musikcube.remote.ui.shared.mixin.MetadataProxyMixin import io.casey.musikcube.remote.ui.shared.mixin.PlaybackMixin import java.util.* import javax.inject.Inject import io.casey.musikcube.remote.ui.settings.constants.Prefs.Default as Defaults import io.casey.musikcube.remote.ui.settings.constants.Prefs.Key as Keys class SettingsActivity : BaseActivity() { @Inject lateinit var connectionsDb: ConnectionsDb @Inject lateinit var streamProxy: StreamProxy private lateinit var addressText: EditText private lateinit var portText: EditText private lateinit var httpPortText: EditText private lateinit var passwordText: EditText private lateinit var albumArtCheckbox: CheckBox private lateinit var softwareVolume: CheckBox private lateinit var sslCheckbox: CheckBox private lateinit var certCheckbox: CheckBox private lateinit var transferCheckbox: CheckBox private lateinit var bitrateSpinner: Spinner private lateinit var formatSpinner: Spinner private lateinit var cacheSpinner: Spinner private lateinit var titleEllipsisSpinner: Spinner private lateinit var playback: PlaybackMixin private lateinit var data: MetadataProxyMixin override fun onCreate(savedInstanceState: Bundle?) { data = mixin(MetadataProxyMixin()) playback = mixin(PlaybackMixin()) component.inject(this) super.onCreate(savedInstanceState) prefs = this.getSharedPreferences(Prefs.NAME, Context.MODE_PRIVATE) setContentView(R.layout.settings_activity) setTitle(R.string.settings_title) cacheViews() bindListeners() rebindUi() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.settings_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { finish() return true } R.id.action_save -> { save() return true } } return super.onOptionsItemSelected(item) } override val transitionType: Transition get() = Transition.Vertical private fun rebindSpinner(spinner: Spinner, arrayResourceId: Int, key: String, defaultIndex: Int) { val items = ArrayAdapter.createFromResource(this, arrayResourceId, android.R.layout.simple_spinner_item) items.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinner.adapter = items spinner.setSelection(prefs.getInt(key, defaultIndex)) } private fun rebindUi() { /* connection info */ addressText.setTextAndMoveCursorToEnd(prefs.getString(Keys.ADDRESS) ?: Defaults.ADDRESS) portText.setTextAndMoveCursorToEnd(String.format( Locale.ENGLISH, "%d", prefs.getInt(Keys.MAIN_PORT, Defaults.MAIN_PORT))) httpPortText.setTextAndMoveCursorToEnd(String.format( Locale.ENGLISH, "%d", prefs.getInt(Keys.AUDIO_PORT, Defaults.AUDIO_PORT))) passwordText.setTextAndMoveCursorToEnd(prefs.getString(Keys.PASSWORD) ?: Defaults.PASSWORD) /* bitrate */ rebindSpinner( bitrateSpinner, R.array.transcode_bitrate_array, Keys.TRANSCODER_BITRATE_INDEX, Defaults.TRANSCODER_BITRATE_INDEX) /* format */ rebindSpinner( formatSpinner, R.array.transcode_format_array, Keys.TRANSCODER_FORMAT_INDEX, Defaults.TRANSCODER_FORMAT_INDEX) /* disk cache */ rebindSpinner( cacheSpinner, R.array.disk_cache_array, Keys.DISK_CACHE_SIZE_INDEX, Defaults.DISK_CACHE_SIZE_INDEX) /* title ellipsis mode */ rebindSpinner( titleEllipsisSpinner, R.array.title_ellipsis_mode_array, Keys.TITLE_ELLIPSIS_MODE_INDEX, Defaults.TITLE_ELLIPSIS_SIZE_INDEX) /* advanced */ transferCheckbox.isChecked = prefs.getBoolean( Keys.TRANSFER_TO_SERVER_ON_HEADSET_DISCONNECT, Defaults.TRANSFER_TO_SERVER_ON_HEADSET_DISCONNECT) albumArtCheckbox.isChecked = prefs.getBoolean( Keys.LASTFM_ENABLED, Defaults.LASTFM_ENABLED) softwareVolume.isChecked = prefs.getBoolean( Keys.SOFTWARE_VOLUME, Defaults.SOFTWARE_VOLUME) sslCheckbox.setCheckWithoutEvent( this.prefs.getBoolean(Keys.SSL_ENABLED,Defaults.SSL_ENABLED), sslCheckChanged) certCheckbox.setCheckWithoutEvent( this.prefs.getBoolean( Keys.CERT_VALIDATION_DISABLED, Defaults.CERT_VALIDATION_DISABLED), certValidationChanged) enableUpNavigation() } private fun onDisableSslFromDialog() { sslCheckbox.setCheckWithoutEvent(false, sslCheckChanged) } private fun onDisableCertValidationFromDialog() { certCheckbox.setCheckWithoutEvent(false, certValidationChanged) } private val sslCheckChanged = { _: CompoundButton, value:Boolean -> if (value) { if (!dialogVisible(SslAlertDialog.TAG)) { showDialog(SslAlertDialog.newInstance(), SslAlertDialog.TAG) } } } private val certValidationChanged = { _: CompoundButton, value: Boolean -> if (value) { if (!dialogVisible(DisableCertValidationAlertDialog.TAG)) { showDialog( DisableCertValidationAlertDialog.newInstance(), DisableCertValidationAlertDialog.TAG) } } } private fun cacheViews() { this.addressText = findViewById(R.id.address) this.portText = findViewById(R.id.port) this.httpPortText = findViewById(R.id.http_port) this.passwordText = findViewById(R.id.password) this.albumArtCheckbox = findViewById(R.id.album_art_checkbox) this.softwareVolume = findViewById(R.id.software_volume) this.bitrateSpinner = findViewById(R.id.transcoder_bitrate_spinner) this.formatSpinner = findViewById(R.id.transcoder_format_spinner) this.cacheSpinner = findViewById(R.id.streaming_disk_cache_spinner) this.titleEllipsisSpinner = findViewById(R.id.title_ellipsis_mode_spinner) this.sslCheckbox = findViewById(R.id.ssl_checkbox) this.certCheckbox = findViewById(R.id.cert_validation) this.transferCheckbox = findViewById(R.id.transfer_on_disconnect_checkbox) } private fun bindListeners() { findViewById<View>(R.id.button_save_as).setOnClickListener { showSaveAsDialog() } findViewById<View>(R.id.button_load).setOnClickListener { connectionsActivityLauncher.launch(ConnectionsActivity.getStartIntent(this)) } findViewById<View>(R.id.button_diagnostics).setOnClickListener { startActivity(Intent(this, DiagnosticsActivity::class.java)) } } private val connectionsActivityLauncher = launcher { activityResult -> if (activityResult.resultCode == RESULT_OK && activityResult.data != null) { activityResult.data?.let { data -> val connection = data.getParcelableExtraCompat<Connection>(ConnectionsActivity.EXTRA_SELECTED_CONNECTION) if (connection != null) { addressText.setText(connection.hostname) passwordText.setText(connection.password) portText.setText(connection.wssPort.toString()) httpPortText.setText(connection.httpPort.toString()) sslCheckbox.setCheckWithoutEvent(connection.ssl, sslCheckChanged) certCheckbox.setCheckWithoutEvent(connection.noValidate, certValidationChanged) } } } } private fun showSaveAsDialog() { if (!dialogVisible(SaveAsDialog.TAG)) { showDialog(SaveAsDialog.newInstance(), SaveAsDialog.TAG) } } private fun showInvalidConnectionDialog(messageId: Int = R.string.settings_invalid_connection_message) { if (!dialogVisible(InvalidConnectionDialog.TAG)) { showDialog(InvalidConnectionDialog.newInstance(messageId), InvalidConnectionDialog.TAG) } } private fun saveAs(name: String) { try { val connection = Connection() connection.name = name connection.hostname = addressText.text.toString() connection.wssPort = portText.text.toString().toInt() connection.httpPort = httpPortText.text.toString().toInt() connection.password = passwordText.text.toString() connection.ssl = sslCheckbox.isChecked connection.noValidate = certCheckbox.isChecked if (connection.valid) { runner.run(SaveAsTask.nameFor(connection), SaveAsTask(connectionsDb, connection)) } else { showInvalidConnectionDialog() } } catch (ex: NumberFormatException) { showInvalidConnectionDialog() } } private fun save() { val addr = addressText.text.toString() val port = portText.text.toString() val httpPort = httpPortText.text.toString() val password = passwordText.text.toString() try { prefs.edit() .putString(Keys.ADDRESS, addr) .putInt(Keys.MAIN_PORT, if (port.isNotEmpty()) port.toInt() else 0) .putInt(Keys.AUDIO_PORT, if (httpPort.isNotEmpty()) httpPort.toInt() else 0) .putString(Keys.PASSWORD, password) .putBoolean(Keys.LASTFM_ENABLED, albumArtCheckbox.isChecked) .putBoolean(Keys.SOFTWARE_VOLUME, softwareVolume.isChecked) .putBoolean(Keys.SSL_ENABLED, sslCheckbox.isChecked) .putBoolean(Keys.CERT_VALIDATION_DISABLED, certCheckbox.isChecked) .putBoolean(Keys.TRANSFER_TO_SERVER_ON_HEADSET_DISCONNECT, transferCheckbox.isChecked) .putInt(Keys.TRANSCODER_BITRATE_INDEX, bitrateSpinner.selectedItemPosition) .putInt(Keys.TRANSCODER_FORMAT_INDEX, formatSpinner.selectedItemPosition) .putInt(Keys.DISK_CACHE_SIZE_INDEX, cacheSpinner.selectedItemPosition) .putInt(Keys.TITLE_ELLIPSIS_MODE_INDEX, titleEllipsisSpinner.selectedItemPosition) .apply() if (!softwareVolume.isChecked) { PlayerWrapper.setVolume(1.0f) } streamProxy.reload() data.wss.disconnect() finish() } catch (ex: NumberFormatException) { showInvalidConnectionDialog(R.string.settings_invalid_connection_no_name_message) } } override fun onTaskCompleted(taskName: String, taskId: Long, task: Task<*, *>, result: Any) { if (SaveAsTask.match(taskName)) { if ((result as SaveAsTask.Result) == SaveAsTask.Result.Exists) { val connection = (task as SaveAsTask).connection if (!dialogVisible(ConfirmOverwriteDialog.TAG)) { showDialog( ConfirmOverwriteDialog.newInstance(connection), ConfirmOverwriteDialog.TAG) } } else { showSnackbar( findViewById(android.R.id.content), R.string.snackbar_saved_connection_preset) } } } class SslAlertDialog : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dlg = AlertDialog.Builder(requireActivity()) .setTitle(R.string.settings_ssl_dialog_title) .setMessage(R.string.settings_ssl_dialog_message) .setPositiveButton(R.string.button_enable, null) .setNegativeButton(R.string.button_disable) { _, _ -> (activity as SettingsActivity).onDisableSslFromDialog() } .setNeutralButton(R.string.button_learn_more) { _, _ -> try { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(LEARN_MORE_URL)) startActivity(intent) } catch (ex: Exception) { } } .create() dlg.setCancelable(false) return dlg } companion object { private const val LEARN_MORE_URL = "https://github.com/clangen/musikcube/wiki/ssl-server-setup" const val TAG = "ssl_alert_dialog_tag" fun newInstance(): SslAlertDialog { return SslAlertDialog() } } } class DisableCertValidationAlertDialog : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dlg = AlertDialog.Builder(requireActivity()) .setTitle(R.string.settings_disable_cert_validation_title) .setMessage(R.string.settings_disable_cert_validation_message) .setPositiveButton(R.string.button_enable, null) .setNegativeButton(R.string.button_disable) { _, _ -> (activity as SettingsActivity).onDisableCertValidationFromDialog() } .create() dlg.setCancelable(false) return dlg } companion object { const val TAG = "disable_cert_verify_dialog" fun newInstance(): DisableCertValidationAlertDialog { return DisableCertValidationAlertDialog() } } } class InvalidConnectionDialog: DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dlg = AlertDialog.Builder(requireActivity()) .setTitle(R.string.settings_invalid_connection_title) .setMessage(requireArguments().getInt(EXTRA_MESSAGE_ID)) .setNegativeButton(R.string.button_ok, null) .create() dlg.setCancelable(false) return dlg } companion object { const val TAG = "invalid_connection_dialog" private const val EXTRA_MESSAGE_ID = "extra_message_id" fun newInstance(messageId: Int = R.string.settings_invalid_connection_message): InvalidConnectionDialog { val args = Bundle() args.putInt(EXTRA_MESSAGE_ID, messageId) val result = InvalidConnectionDialog() result.arguments = args return result } } } class ConfirmOverwriteDialog : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dlg = AlertDialog.Builder(requireActivity()) .setTitle(R.string.settings_confirm_overwrite_title) .setMessage(R.string.settings_confirm_overwrite_message) .setNegativeButton(R.string.button_no, null) .setPositiveButton(R.string.button_yes) { _, _ -> arguments?.getParcelableCompat<Connection>(EXTRA_CONNECTION)?.let { connection -> val db = (activity as SettingsActivity).connectionsDb val saveAs = SaveAsTask(db, connection, true) (activity as SettingsActivity).runner.run(SaveAsTask.nameFor(connection), saveAs) } } .create() dlg.setCancelable(false) return dlg } companion object { const val TAG = "confirm_overwrite_dialog" private const val EXTRA_CONNECTION = "extra_connection" fun newInstance(connection: Connection): ConfirmOverwriteDialog { val args = Bundle() args.putParcelable(EXTRA_CONNECTION, connection) val result = ConfirmOverwriteDialog() result.arguments = args return result } } } class SaveAsDialog : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val inflater = LayoutInflater.from(context) val view = inflater.inflate(R.layout.dialog_edit, null) val edit = view.findViewById<EditText>(R.id.edit) edit.requestFocus() val dlg = AlertDialog.Builder(requireActivity()) .setTitle(R.string.settings_save_as_title) .setNegativeButton(R.string.button_cancel) { _, _ -> hideKeyboard() } .setOnCancelListener { hideKeyboard() } .setPositiveButton(R.string.button_save) { _, _ -> (activity as SettingsActivity).saveAs(edit.text.toString()) } .create() dlg.setView(view) dlg.setCancelable(false) return dlg } override fun onResume() { super.onResume() showKeyboard() } override fun onPause() { super.onPause() hideKeyboard() } companion object { const val TAG = "save_as_dialog" fun newInstance(): SaveAsDialog { return SaveAsDialog() } } } companion object { fun getStartIntent(context: Context): Intent { return Intent(context, SettingsActivity::class.java) } } } private class SaveAsTask(val db: ConnectionsDb, val connection: Connection, val overwrite: Boolean = false) : Tasks.Blocking<SaveAsTask.Result, Exception>() { enum class Result { Exists, Added } override fun exec(context: Context?): Result { val dao = db.connectionsDao() if (!overwrite) { val existing: Connection? = dao.query(connection.name) if (existing != null) { return Result.Exists } } dao.insert(connection) return Result.Added } companion object { const val NAME = "SaveAsTask" fun nameFor(connection: Connection): String { return "$NAME.${connection.name}" } fun match(name: String?): Boolean { return name != null && name.startsWith("$NAME.") } } }
bsd-3-clause
8952dbec244b1d26df8edf77edc548c3
37.255814
121
0.620415
5.086318
false
false
false
false
myTargetSDK/mytarget-android
myTargetDemo/app/src/main/java/com/my/targetDemoApp/activities/SimpleBannerActivity.kt
1
1591
package com.my.targetDemoApp.activities import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.my.target.ads.MyTargetView import com.my.targetDemoApp.databinding.ActivitySimpleBannerBinding class SimpleBannerActivity : AppCompatActivity(), MyTargetView.MyTargetViewListener { private lateinit var viewBinding: ActivitySimpleBannerBinding companion object { private const val TAG = "SimpleBannerActivity" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewBinding = ActivitySimpleBannerBinding.inflate(layoutInflater) setContentView(viewBinding.root) setSupportActionBar(viewBinding.toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true); supportActionBar?.setDisplayShowHomeEnabled(true); viewBinding.targetView.listener = this viewBinding.targetView.load() } override fun onLoad(p0: MyTargetView) { Log.d(TAG, "onLoad() called with: p0 = $p0") toast("onLoad") } override fun onClick(p0: MyTargetView) { Log.d(TAG, "onClick() called with: p0 = $p0") } override fun onNoAd(p0: String, p1: MyTargetView) { Log.d(TAG, "onNoAd() called with: p0 = $p0, p1 = $p1") toast("onLoad") } override fun onShow(p0: MyTargetView) { Log.d(TAG, "onShow() called with: p0 = $p0") } private fun toast(s: String) { Toast.makeText(this, s, Toast.LENGTH_SHORT) .show() } }
lgpl-3.0
e5ff7c4ff6a7a6b5ea14be6d42b11df1
30.84
85
0.688246
4.231383
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/caldav/CaldavViewModel.kt
1
944
package org.tasks.caldav import android.content.Intent import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.withContext import timber.log.Timber abstract class CaldavViewModel : ViewModel() { val error = MutableLiveData<Throwable?>() val inFlight = MutableLiveData(false) val finish = MutableLiveData<Intent>() protected suspend fun <T> doRequest(action: suspend () -> T): T? = withContext(NonCancellable) { if (inFlight.value == true) { return@withContext null } inFlight.value = true try { return@withContext action() } catch (e: Exception) { Timber.e(e) error.value = e return@withContext null } finally { inFlight.value = false } } }
gpl-3.0
411bd0fbde3dcf0087fdbc21a9791786
29.483871
70
0.604873
5.102703
false
false
false
false
didi/DoraemonKit
Android/dokit-test/src/main/java/com/didichuxing/doraemonkit/kit/test/event/monitor/AccessibilityEventMonitor.kt
1
6761
package com.didichuxing.doraemonkit.kit.test.event.monitor; import android.os.Build import android.view.View import android.view.accessibility.AccessibilityEvent import android.widget.* import com.didichuxing.doraemonkit.extension.tagName import com.didichuxing.doraemonkit.kit.core.DoKitFrameLayout import com.didichuxing.doraemonkit.kit.test.DoKitTestManager import com.didichuxing.doraemonkit.kit.test.event.* import com.didichuxing.doraemonkit.kit.test.utils.XposedHookUtil import com.didichuxing.doraemonkit.kit.test.utils.ViewPathUtil import com.didichuxing.doraemonkit.kit.test.utils.WindowPathUtil import com.didichuxing.doraemonkit.util.ConvertUtils import com.didichuxing.doraemonkit.util.LogHelper /** * didi Create on 2022/2/22 . * <p> * Copyright (c) 2022/2/22 by didiglobal.com. * * @author <a href="[email protected]">zhangjun</a> * @version 1.0 * @Date 2022/2/22 6:06 下午 * @Description 用一句话说明文件功能 */ object AccessibilityEventMonitor { const val TAG = "AccessibilityEventHandler" /** * 通用的ws信息处理 */ fun onAccessibilityEvent(view: View, event: AccessibilityEvent) { if (!DoKitTestManager.isHostMode()) { return } when (event.eventType) { //点击事件只响应给需要处理的控件 AccessibilityEvent.TYPE_VIEW_CLICKED -> { if (view.hasOnClickListeners() || view.parent is AdapterView<*> || view is Button) { onViewHandleEvent(view, event) } } //针对dokit悬浮窗 AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED -> { if (view is DoKitFrameLayout) { onViewHandleEvent(view, event) } } /** * view 获取焦点 */ AccessibilityEvent.TYPE_VIEW_FOCUSED, //针对 EditText 文字改变 AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED, // represents the event of scrolling a view AccessibilityEvent.TYPE_VIEW_SCROLLED, // represents the event of long clicking on a View like Button, CompoundButton AccessibilityEvent.TYPE_VIEW_LONG_CLICKED, // represents the event of changing the text selection of an EditText AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED -> { onViewHandleEvent(view, event) } AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED, AccessibilityEvent.TYPE_VIEW_SELECTED -> { LogHelper.i(TAG, "TYPE_VIEW_SELECTED or TYPE_WINDOW_STATE_CHANGED ,class=${view.javaClass},view=$view") } else -> { LogHelper.e(TAG, "type=${event.eventType},class=${view.javaClass},view=$view") } } } private fun onViewHandleEvent(view: View, accessibilityEvent: AccessibilityEvent) { val activity = ViewPathUtil.getActivity(view) val actionId = ControlEventManager.createNextEventId() val viewC12c: ViewC12c = createViewC12c(view, accessibilityEvent) val controlEvent = ControlEvent( actionId, EventType.WSE_COMMON_EVENT, mutableMapOf( "activityName" to activity.tagName ), viewC12c ) ControlEventManager.onControlEventAction(activity, view, controlEvent) } private fun createViewC12c(view: View, acc: AccessibilityEvent): ViewC12c { var viewRootImplIndex: Int = -1 var viewParents = WindowPathUtil.filterViewRoot(XposedHookUtil.ROOT_VIEWS); viewParents?.let { viewRootImplIndex = if (view.rootView.parent == null) { it.size - 1 } else { it.indexOf(view.rootView.parent) } } val actionType: ActionType = ActionType.valueOf(acc) return ViewC12c( actionType = actionType, actionName = actionType.getDesc(), accEventType = acc.eventType, windowIndex = viewRootImplIndex, viewPaths = ViewPathUtil.createViewPathOfWindow(view), accEventInfo = transformAccEventInfo(acc), text = if (view is TextView) { view.text.toString() } else { "" }, doKitViewPanelNode = createDoKitViewPanel(view), doKitViewNode = createDoKitViewInfo(view) ) } private fun createDoKitViewPanel(view: View): DoKitViewPanelNode? { if (view.rootView is DoKitFrameLayout) { val viewParents = WindowPathUtil.filterDoKitViewRoot(XposedHookUtil.ROOT_VIEWS) val windowIndex = viewParents.indexOf(view.rootView.parent) return DoKitViewPanelNode(windowIndex = windowIndex, className = (view.rootView as DoKitFrameLayout).title) } return null } /** * 创建dokitview info */ private fun createDoKitViewInfo(view: View): DoKitViewNode? { if (view !is DoKitFrameLayout) { return null } if (view.layoutParams !is FrameLayout.LayoutParams) { return null } return DoKitViewNode( (view.layoutParams as FrameLayout.LayoutParams).leftMargin, (view.layoutParams as FrameLayout.LayoutParams).topMargin ) } private fun transformAccEventInfo(acc: AccessibilityEvent): AccessibilityEventNode { return AccessibilityEventNode( acc.eventType, acc.className?.toString(), acc.packageName?.toString(), acc.eventTime, acc.beforeText?.toString(), acc.fromIndex, acc.addedCount, acc.removedCount, acc.movementGranularity, acc.toIndex, acc.action, ConvertUtils.px2dp(acc.maxScrollX.toFloat()), ConvertUtils.px2dp(acc.maxScrollY.toFloat()), if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { ConvertUtils.px2dp(acc.scrollDeltaX.toFloat()) } else { -1 }, if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { ConvertUtils.px2dp(acc.scrollDeltaY.toFloat()) } else { -1 }, ConvertUtils.px2dp(acc.scrollX.toFloat()), ConvertUtils.px2dp(acc.scrollY.toFloat()), acc.isScrollable, acc.contentChangeTypes, if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { acc.windowChanges } else { -1 } ) } }
apache-2.0
2b15d6b7486fbf10fa52a7ba8a98a02b
34.994595
119
0.601291
4.617892
false
false
false
false
tasks/tasks
app/src/main/java/com/todoroo/astrid/activity/ShareLinkActivity.kt
1
4452
package com.todoroo.astrid.activity import android.content.ContentResolver import android.content.Intent import android.net.Uri import android.os.Bundle import androidx.lifecycle.lifecycleScope import com.todoroo.astrid.data.Task import com.todoroo.astrid.service.TaskCreator import com.todoroo.astrid.utility.Constants import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch import org.tasks.analytics.Firebase import org.tasks.data.TaskAttachment import org.tasks.files.FileHelper import org.tasks.injection.InjectingAppCompatActivity import org.tasks.intents.TaskIntents import org.tasks.preferences.Preferences import timber.log.Timber import javax.inject.Inject /** * @author joshuagross * * Create a new task based on incoming links from the "share" menu */ @AndroidEntryPoint class ShareLinkActivity : InjectingAppCompatActivity() { @Inject lateinit var taskCreator: TaskCreator @Inject lateinit var preferences: Preferences @Inject lateinit var firebase: Firebase public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val intent = intent val action = intent.action when { Intent.ACTION_PROCESS_TEXT == action -> lifecycleScope.launch { val text = intent.getCharSequenceExtra(Intent.EXTRA_PROCESS_TEXT) if (text != null) { val task = taskCreator.createWithValues(text.toString()) editTask(task) firebase.addTask("clipboard") } finish() } Intent.ACTION_SEND == action -> lifecycleScope.launch { val subject = intent.getStringExtra(Intent.EXTRA_SUBJECT) val task = taskCreator.createWithValues(subject) task.notes = intent.getStringExtra(Intent.EXTRA_TEXT) if (hasAttachments(intent)) { task.putTransitory(TaskAttachment.KEY, copyAttachment(intent)) firebase.addTask("share_attachment") } else { firebase.addTask("share_text") } editTask(task) finish() } Intent.ACTION_SEND_MULTIPLE == action -> lifecycleScope.launch { val task = taskCreator.createWithValues(intent.getStringExtra(Intent.EXTRA_SUBJECT)) task.notes = intent.getStringExtra(Intent.EXTRA_TEXT) if (hasAttachments(intent)) { task.putTransitory(TaskAttachment.KEY, copyMultipleAttachments(intent)) firebase.addTask("share_multiple_attachments") } else { firebase.addTask("share_multiple_text") } editTask(task) finish() } Intent.ACTION_VIEW == action -> lifecycleScope.launch { editTask(taskCreator.createWithValues("")) firebase.addTask("action_view") finish() } else -> { Timber.e("Unhandled intent: %s", intent) finish() } } } private fun editTask(task: Task) { val intent = TaskIntents.getEditTaskIntent(this, null, task) intent.putExtra(MainActivity.FINISH_AFFINITY, true) startActivity(intent) } private fun copyAttachment(intent: Intent): ArrayList<Uri> = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM) ?.let { copyAttachments(listOf(it)) } ?: arrayListOf() private fun copyMultipleAttachments(intent: Intent): ArrayList<Uri> = intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM) ?.let { copyAttachments(it) } ?: arrayListOf() private fun copyAttachments(uris: List<Uri>) = uris .filter { it.scheme == ContentResolver.SCHEME_CONTENT && it.authority != Constants.FILE_PROVIDER_AUTHORITY } .map { FileHelper.copyToUri(this, preferences.attachmentsDirectory!!, it) } .let { ArrayList(it) } private fun hasAttachments(intent: Intent) = intent.type?.let { type -> ATTACHMENT_TYPES.any { type.startsWith(it) } } ?: false companion object { private val ATTACHMENT_TYPES = listOf("image/", "application/", "audio/") } }
gpl-3.0
5c9cbd3dd999c64484f4055e2da30497
37.721739
100
0.616577
4.913907
false
false
false
false
natanieljr/droidmate
project/pcComponents/core/src/test/kotlin/org/droidmate/device/datatypes/UnreliableDeviceGuiSnapshotProvider.kt
1
3175
// DroidMate, an automated execution generator for Android apps. // Copyright (C) 2012-2018. Saarland University // // 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/>. // // Current Maintainers: // Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland> // Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland> // // Former Maintainers: // Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de> // // web: www.droidmate.org package org.droidmate.device.datatypes import org.droidmate.deviceInterface.exploration.DeviceResponse class UnreliableDeviceGuiSnapshotProvider(private val originalGuiSnapshot: DeviceResponse) : IUnreliableDeviceGuiSnapshotProvider { override fun provide(): DeviceResponse { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun pressOkOnAppHasStopped() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getCurrentWithoutChange(): DeviceResponse { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } // TODO Fix tests /*companion object { private val logcat = LoggerFactory.getLogger(UnreliableDeviceGuiSnapshotProvider::class.java) } private val emptyGuiSnapshot = UiautomatorWindowDumpTestHelper.newEmptyWindowDump() private val appHasStoppedOKDisabledGuiSnapshot = UiautomatorWindowDumpTestHelper.newAppHasStoppedDialogOKDisabledWindowDump() private val appHasStoppedGuiSnapshot = UiautomatorWindowDumpTestHelper.newAppHasStoppedDialogWindowDump() private val guiSnapshotsSequence = arrayListOf( emptyGuiSnapshot, appHasStoppedOKDisabledGuiSnapshot, appHasStoppedGuiSnapshot ) private var currentGuiSnapshot: DeviceResponse = guiSnapshotsSequence.first() private var okOnAppHasStoppedWasPressed = false override fun pressOkOnAppHasStopped() { assert(!this.okOnAppHasStoppedWasPressed) assert(guiSnapshotsSequence.last() == currentGuiSnapshot) this.okOnAppHasStoppedWasPressed = true this.currentGuiSnapshot = originalGuiSnapshot } override fun getCurrentWithoutChange(): DeviceResponse { return this.currentGuiSnapshot } override fun provide(): DeviceResponse { logcat.trace("provide($currentGuiSnapshot)") val out = this.currentGuiSnapshot if (currentGuiSnapshot != guiSnapshotsSequence.last() && currentGuiSnapshot != originalGuiSnapshot) this.currentGuiSnapshot = this.guiSnapshotsSequence[guiSnapshotsSequence.indexOf(currentGuiSnapshot) + 1] return out }*/ }
gpl-3.0
b6e5a45046fdb7c526cb645a01045497
38.197531
131
0.785827
4.561782
false
false
false
false
lambdasoup/watchlater
app/src/main/java/com/lambdasoup/watchlater/ui/WatchLaterTheme.kt
1
4972
/* * Copyright (c) 2015 - 2022 * * Maximilian Hille <[email protected]> * Juliane Lehmann <[email protected]> * * This file is part of Watch Later. * * Watch Later 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. * * Watch Later 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 Watch Later. If not, see <http://www.gnu.org/licenses/>. */ package com.lambdasoup.watchlater.ui import androidx.annotation.StringRes import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.calculateEndPadding import androidx.compose.foundation.layout.calculateStartPadding import androidx.compose.foundation.layout.padding import androidx.compose.material.Button import androidx.compose.material.ButtonDefaults import androidx.compose.material.Colors import androidx.compose.material.MaterialTheme import androidx.compose.material.Shapes import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.material.Typography import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.material.primarySurface import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.google.accompanist.systemuicontroller.rememberSystemUiController private val Lightblue600 = Color(0xFF039BE5) private val Lightblue600Dark = Color(0xFF006DB3) private val Red600 = Color(0xFFE53935) private val Red600Dark = Color(0xFFAB000D) private val LightGrey = Color(0xFFF0F0F0) private val Green600 = Color(0xFF43A047) private val Green600Dark = Color(0xFF00701a) private val DarkColors = darkColors( secondary = Red600Dark, secondaryVariant = Red600, onSecondary = LightGrey, ) private val LightColors = lightColors( primary = Red600, primaryVariant = Red600Dark, secondary = Lightblue600, secondaryVariant = Lightblue600Dark, onSecondary = Color.White, background = LightGrey, error = Red600, ) val Colors.success: Color get() = if (isLight) Green600 else Green600Dark @Composable fun WatchLaterTheme( content: @Composable () -> Unit, ) { val isDark = isSystemInDarkTheme() val colors = if (isDark) DarkColors else LightColors val systemUiController = rememberSystemUiController() DisposableEffect(systemUiController, isDark) { systemUiController.setStatusBarColor( color = colors.primarySurface ) systemUiController.setNavigationBarColor( color = colors.background ) onDispose {} } MaterialTheme( colors = colors, typography = Typography(), shapes = Shapes(), content = content ) } @Composable fun Modifier.padWithRoomForTextButtonContent( start: Dp = 0.dp, end: Dp = 0.dp, ) = padding( start = (start - ButtonDefaults.TextButtonContentPadding.calculateStartPadding(LocalLayoutDirection.current)).coerceAtLeast(0.dp), end = (end - ButtonDefaults.TextButtonContentPadding.calculateEndPadding(LocalLayoutDirection.current)).coerceAtLeast(0.dp), ) @Composable fun Modifier.padAlignTextButtonContentStart() = padding( start = ButtonDefaults.TextButtonContentPadding.calculateStartPadding(LocalLayoutDirection.current) ) @Composable fun Modifier.padAlignTextButtonContentEnd() = padding( end = ButtonDefaults.TextButtonContentPadding.calculateEndPadding(LocalLayoutDirection.current) ) @Composable fun WatchLaterTextButton( onClick: () -> Unit, @StringRes label: Int, modifier: Modifier = Modifier, ) = TextButton( modifier = modifier, onClick = onClick, colors = ButtonDefaults.textButtonColors( contentColor = MaterialTheme.colors.secondary ), ) { Text(text = stringResource(id = label).uppercase()) } @Composable fun WatchLaterButton( onClick: () -> Unit, @StringRes label: Int, modifier: Modifier = Modifier, enabled: Boolean = true, ) = Button( modifier = modifier, enabled = enabled, onClick = onClick, colors = ButtonDefaults.buttonColors( backgroundColor = MaterialTheme.colors.secondary, contentColor = MaterialTheme.colors.onSecondary, ) ) { Text( text = stringResource(id = label).uppercase(), ) }
gpl-3.0
6bef4e9b3a9159fb06c5beed6711b254
30.66879
134
0.755229
4.361404
false
false
false
false
liceoArzignano/app_bold
app/src/main/kotlin/it/liceoarzignano/bold/news/NewsAdapter.kt
1
2851
package it.liceoarzignano.bold.news import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.zhukic.sectionedrecyclerview.SectionedRecyclerViewAdapter import it.liceoarzignano.bold.R import it.liceoarzignano.bold.ui.recyclerview.HeaderViewHolder import it.liceoarzignano.bold.utils.HelpToast import it.liceoarzignano.bold.utils.Time internal class NewsAdapter(private var mNewsList: List<News>, private val mContext: Context) : SectionedRecyclerViewAdapter<HeaderViewHolder, NewsAdapter.NewsHolder>() { override fun onCreateItemViewHolder(parent: ViewGroup, type: Int): NewsHolder = NewsHolder(LayoutInflater.from(parent.context) .inflate(R.layout.item_news, parent, false)) override fun onBindItemViewHolder(holder: NewsHolder, position: Int) = holder.setData(mNewsList[position]) override fun onCreateSubheaderViewHolder(parent: ViewGroup, type: Int): HeaderViewHolder = HeaderViewHolder(LayoutInflater.from(parent.context) .inflate(R.layout.item_subheader, parent, false)) override fun onBindSubheaderViewHolder(holder: HeaderViewHolder, position: Int) { val time = Time(mNewsList[position].date) val diff = time.diff(Time()) val title = when (diff) { -1 -> mContext.getString(R.string.events_time_yesterday) 0 -> mContext.getString(R.string.events_time_today) 1 -> mContext.getString(R.string.events_time_tomorrow) else -> time.asString(mContext) } holder.setTitle(title) } override fun getItemSize(): Int = mNewsList.size override fun onPlaceSubheaderBetweenItems(itemPosition: Int): Boolean { val a = Time(mNewsList[itemPosition].date) val b = Time(mNewsList[itemPosition + 1].date) return a.diff(b) >= 1 } fun updateList(list: List<News>) { mNewsList = list notifyDataChanged() } internal inner class NewsHolder(private val mView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(mView) { private val mTitle: TextView = mView.findViewById(R.id.row_news_title) private val mMessage: TextView = mView.findViewById(R.id.row_news_message) fun setData(news: News) { mTitle.text = news.title mMessage.text = news.description val url = news.url mView.setOnClickListener { if (!url.isEmpty()) { (mContext as NewsListActivity).showUrl(url) } HelpToast(mContext, HelpToast.KEY_NEWS_LONG_PRESS) } mView.setOnLongClickListener { (mContext as NewsListActivity).newsActions(news) } } } }
lgpl-3.0
9f47e6719d28395b061cc27bd92147fe
35.088608
124
0.676254
4.454688
false
false
false
false
d9n/intellij-rust
src/test/kotlin/org/rust/ide/annotator/RsErrorAnnotatorTest.kt
1
36082
package org.rust.ide.annotator import com.intellij.testFramework.LightProjectDescriptor class RsErrorAnnotatorTest : RsAnnotatorTestBase() { override val dataPath = "org/rust/ide/annotator/fixtures/errors" fun testInvalidModuleDeclarations() = doTest("helper.rs") fun testCreateFileQuickFix() = checkByDirectory { openFileInEditor("mod.rs") applyQuickFix("Create module file") } fun testCreateFileAndExpandModuleQuickFix() = checkByDirectory { openFileInEditor("foo.rs") applyQuickFix("Create module file") } fun testPaths() = checkErrors(""" fn main() { let ok = self::super::super::foo; let ok = super::foo::bar; let _ = <error descr="Invalid path: self and super are allowed only at the beginning">::self</error>::foo; let _ = <error>::super</error>::foo; let _ = <error>self::self</error>; let _ = <error>super::self</error>; let _ = <error>foo::self</error>::bar; let _ = <error>self::foo::super</error>::bar; } """) fun testConstFree() = checkErrors(""" const FOO: u32 = 42; pub const PUB_FOO: u32 = 41; static S_FOO: bool = true; static mut S_MUT_FOO: bool = false; pub static S_PUB_BAR: u8 = 0; pub static mut S_PUB_MUT_BAR: f16 = 1.12; <error descr="Constant `BAR` must have a value">const BAR: u8;</error> <error descr="Static constant `DEF_BAR` cannot have the `default` qualifier">default</error> static DEF_BAR: u16 = 9; """) fun testConstInTrait() = checkErrors(""" trait Foo { const FOO_1: u16 = 10; const FOO_2: f64; <error descr="Constant `PUB_BAZ` cannot have the `pub` qualifier">pub</error> const PUB_BAZ: bool; <error descr="Constant `DEF_BAR` cannot have the `default` qualifier">default</error> const DEF_BAR: u16 = 9; <error descr="Static constants are not allowed in traits">static</error> ST_FOO: u32 = 18; } """) fun testConstInImpl() = checkErrors(""" struct Foo; impl Foo { const FOO: u32 = 109; pub const PUB_FOO: u32 = 81; default const DEF_FOO: u8 = 1; <error descr="Constant `BAR` must have a value">const BAR: u8;</error> <error descr="Static constants are not allowed in impl blocks">static</error> ST_FOO: u32 = 18; } """) fun testConstInExtern() = checkErrors(""" extern "C" { static mut FOO: u32; pub static mut PUB_FOO: u8; static NON_MUT_FOO: u32; <error descr="Static constant `DEF_FOO` cannot have the `default` qualifier">default</error> static mut DEF_FOO: bool; <error descr="Only static constants are allowed in extern blocks">const</error> CONST_FOO: u32; static mut VAL_FOO: u32 <error descr="Static constants in extern blocks cannot have values">= 10</error>; } """) fun testFunction() = checkErrors(""" #[inline] pub const unsafe fn full<'a, T>(id: u32, name: &'a str, data: &T, _: &mut FnMut(Display)) -> Option<u32> where T: Sized { None } fn trailing_comma(a: u32,) {} extern "C" fn ext_fn() {} <error descr="Function `foo_default` cannot have the `default` qualifier">default</error> fn foo_default(f: u32) {} fn ref_self(<error descr="Function `ref_self` cannot have `self` parameter">&mut self</error>, f: u32) {} fn no_body()<error descr="Function `no_body` must have a body">;</error> fn anon_param(<error descr="Function `anon_param` cannot have anonymous parameters">u8</error>, a: i16) {} fn var_foo(a: bool, <error descr="Function `var_foo` cannot be variadic">...</error>) {} <error>default</error> fn two_errors(<error>u8</error>, a: i16) {} """) fun testImplAssocFunction() = checkErrors(""" struct Person<D> { data: D } impl<D> Person<D> { #[inline] pub const unsafe fn new<'a>(id: u32, name: &'a str, data: D, _: bool) -> Person<D> where D: Sized { Person { data: data } } default fn def() {} extern "C" fn ext_fn() {} default <error descr="Default associated function `def_pub` cannot have the `pub` qualifier">pub</error> fn def_pub() {} fn no_body()<error descr="Associated function `no_body` must have a body">;</error> fn anon_param(<error descr="Associated function `anon_param` cannot have anonymous parameters">u8</error>, a: i16) {} fn var_foo(a: bool, <error descr="Associated function `var_foo` cannot be variadic">...</error>) {} } """) fun testImplMethod() = checkErrors(""" struct Person<D> { data: D } impl<D> Person<D> { #[inline] pub const unsafe fn check<'a>(&self, s: &'a str) -> bool where D: Sized { false } default fn def(&self) {} extern "C" fn ext_m(&self) {} default <error descr="Default method `def_pub` cannot have the `pub` qualifier">pub</error> fn def_pub(&self) {} fn no_body(&self)<error descr="Method `no_body` must have a body">;</error> fn anon_param(&self, <error descr="Method `anon_param` cannot have anonymous parameters">u8</error>, a: i16) {} fn var_foo(&self, a: bool, <error descr="Method `var_foo` cannot be variadic">...</error>) {} } """) fun testTraitAssocFunction() = checkErrors(""" trait Animal<T> { #[inline] unsafe fn feed<'a>(food: T, d: &'a str, _: bool, f32) -> Option<f64> where T: Sized { None } fn no_body(); extern "C" fn ext_fn(); <error descr="Trait function `default_foo` cannot have the `default` qualifier">default</error> fn default_foo(); <error descr="Trait function `pub_foo` cannot have the `pub` qualifier">pub</error> fn pub_foo(); fn tup_param(<error descr="Trait function `tup_param` cannot have tuple parameters">(x, y): (u8, u8)</error>, a: bool); fn var_foo(a: bool, <error descr="Trait function `var_foo` cannot be variadic">...</error>); } """) fun testTraitMethod() = checkErrors(""" trait Animal<T> { #[inline] fn feed<'a>(&mut self, food: T, d: &'a str, _: bool, f32) -> Option<f64> where T: Sized { None } fn no_body(self); extern "C" fn ext_m(); <error descr="Trait method `default_foo` cannot have the `default` qualifier">default</error> fn default_foo(&self); <error descr="Trait method `pub_foo` cannot have the `pub` qualifier">pub</error> fn pub_foo(&mut self); fn tup_param(&self, <error descr="Trait method `tup_param` cannot have tuple parameters">(x, y): (u8, u8)</error>, a: bool); fn var_foo(&self, a: bool, <error descr="Trait method `var_foo` cannot be variadic">...</error>); } """) fun testForeignFunction() = checkErrors(""" extern { #[cold] pub fn full(len: size_t, ...) -> size_t; <error descr="Foreign function `default_foo` cannot have the `default` qualifier">default</error> fn default_foo(); <error descr="Foreign function `with_const` cannot have the `const` qualifier">const</error> fn with_const(); <error descr="Foreign function `with_unsafe` cannot have the `unsafe` qualifier">unsafe</error> fn with_unsafe(); <error descr="Foreign function `with_ext_abi` cannot have an extern ABI">extern "C"</error> fn with_ext_abi(); fn with_self(<error descr="Foreign function `with_self` cannot have `self` parameter">&self</error>, s: size_t); fn anon_param(<error descr="Foreign function `anon_param` cannot have anonymous parameters">u8</error>, a: i8); fn with_body() <error descr="Foreign function `with_body` cannot have a body">{ let _ = 1; }</error> fn var_coma(a: size_t, ...<error descr="`...` must be last in argument list for variadic function">,</error>); } """) fun testUnionTuple() = checkErrors(""" union U<error descr="Union cannot be tuple-like">(i32, f32)</error>; """) fun testTypeAliasFree() = checkErrors(""" type Int = i32; pub type UInt = u32; type Maybe<T> = Option<T>; type SizedMaybe<T> where T: Sized = Option<T>; <error descr="Type `DefBool` cannot have the `default` qualifier">default</error> type DefBool = bool; <error descr="Aliased type must be provided for type `Unknown`">type Unknown;</error> type Show<error descr="Type `Show` cannot have type parameter bounds">: Display</error> = u32; """) fun testTypeAliasInTrait() = checkErrors(""" trait Computer { type Int; type Long = i64; type Show: Display; <error descr="Type `DefSize` cannot have the `default` qualifier">default</error> type DefSize = isize; <error descr="Type `PubType` cannot have the `pub` qualifier">pub</error> type PubType; type GenType<error descr="Type `GenType` cannot have generic parameters"><T></error> = Option<T>; type WhereType <error descr="Type `WhereType` cannot have `where` clause">where T: Sized</error> = f64; } """) fun testTypeAliasInTraitImpl() = checkErrors(""" trait Vehicle { type Engine; type Control; type Lock; type Cage; type Insurance; type Driver; } struct NumericVehicle<T> { foo: T } impl<T> Vehicle for NumericVehicle<T> { type Engine = u32; default type Control = isize; type Lock<error descr="Type `Lock` cannot have generic parameters"><T></error> = Option<T>; type Cage<error descr="Type `Cage` cannot have type parameter bounds">: Sized</error> = f64; type Insurance <error descr="Type `Insurance` cannot have `where` clause">where T: Sized</error> = i8; <error descr="Aliased type must be provided for type `Driver`">type Driver;</error> } """) fun testInvalidChainComparison() = checkErrors(""" fn foo(x: i32) { <error descr="Chained comparison operator require parentheses">1 < x < 3</error>; <error descr="Chained comparison operator require parentheses">1 > x < 3</error>; <error descr="Chained comparison operator require parentheses">1 > x > 3</error>; <error descr="Chained comparison operator require parentheses">1 < x > 3</error>; <error descr="Chained comparison operator require parentheses">1 <= x < 3</error>; <error descr="Chained comparison operator require parentheses">1 < x <= 3</error>; <error descr="Chained comparison operator require parentheses">1 == x < 3</error>; <error descr="Chained comparison operator require parentheses">1 < x == 3</error>; } """) fun testValidChainComparison() = checkErrors(""" fn foo(x: i32, y: bool) { let _ = 1 < x && x < 10; let _ = 1 < x || x < 10; let _ = (1 == x) == y; let _ = y == (1 == x); } """) fun testE0046_AbsentMethodInTraitImpl() = checkErrors(""" trait TError { fn bar(); fn baz(); fn boo(); } <error descr="Not all trait items implemented, missing: `bar`, `boo` [E0046]">impl TError for ()</error> { fn baz() {} } """) fun testE0046_NotApplied() = checkErrors(""" trait T { fn foo() {} fn bar(); } impl T for() { fn bar() {} } """) fun testE0046_IgnoreMacros() = checkErrors(""" trait T { fn foo(&self); } macro_rules! impl_foo { () => { fn foo(&self) {} }; } struct S; impl T for S { impl_foo!(); } """) fun testE0050_IncorrectParamsNumberInTraitImpl() = checkErrors(""" trait T { fn ok_foo(); fn ok_bar(a: u32, b: f64); fn foo(); fn bar(a: u32); fn baz(a: u32, b: bool, c: f64); fn boo(&self, o: isize); } struct S; impl T for S { fn ok_foo() {} fn ok_bar(a: u32, b: f64) {} fn foo<error descr="Method `foo` has 1 parameter but the declaration in trait `T` has 0 [E0050]">(a: u32)</error> {} fn bar<error descr="Method `bar` has 2 parameters but the declaration in trait `T` has 1 [E0050]">(a: u32, b: bool)</error> {} fn baz<error descr="Method `baz` has 0 parameters but the declaration in trait `T` has 3 [E0050]">()</error> {} fn boo<error descr="Method `boo` has 2 parameters but the declaration in trait `T` has 1 [E0050]">(&self, o: isize, x: f16)</error> {} } """) fun testE0061_InvalidParametersNumberInFreeFunctions() = checkErrors(""" fn par_0() {} fn par_1(p: bool) {} fn par_3(p1: u32, p2: f64, p3: &'static str) {} fn main() { par_0(); par_1(true); par_3(12, 7.1, "cool"); par_0<error descr="This function takes 0 parameters but 1 parameter was supplied [E0061]">(4)</error>; par_1<error descr="This function takes 1 parameter but 0 parameters were supplied [E0061]">()</error>; par_1<error descr="This function takes 1 parameter but 2 parameters were supplied [E0061]">(true, false)</error>; par_3<error descr="This function takes 3 parameters but 2 parameters were supplied [E0061]">(5, 1.0)</error>; } """) fun testE0061_InvalidParametersNumberInAssocFunction() = checkErrors(""" struct Foo; impl Foo { fn par_0() {} fn par_2(p1: u32, p2: f64) {} } fn main() { Foo::par_0(); Foo::par_2(12, 7.1); Foo::par_0<error descr="This function takes 0 parameters but 1 parameter was supplied [E0061]">(4)</error>; Foo::par_2<error descr="This function takes 2 parameters but 3 parameters were supplied [E0061]">(5, 1.0, "three")</error>; } """) fun testE0061_InvalidParametersNumberInImplMethods() = checkErrors(""" struct Foo; impl Foo { fn par_0(&self) {} fn par_2(&self, p1: u32, p2: f64) {} } fn main() { let foo = Foo; foo.par_0(); foo.par_2(12, 7.1); foo.par_0<error descr="This function takes 0 parameters but 1 parameter was supplied [E0061]">(4)</error>; foo.par_2<error descr="This function takes 2 parameters but 3 parameters were supplied [E0061]">(5, 1.0, "three")</error>; foo.par_2<error descr="This function takes 2 parameters but 0 parameters were supplied [E0061]">()</error>; } """) fun testE0061_InvalidParametersNumberInTupleStructs() = checkErrors(""" struct Foo0(); struct Foo1(u8); fn main() { let _ = Foo0(); let _ = Foo1(1); let _ = Foo0<error descr="This function takes 0 parameters but 1 parameter was supplied [E0061]">(4)</error>; let _ = Foo1<error descr="This function takes 1 parameter but 2 parameters were supplied [E0061]">(10, false)</error>; } """) fun testE0061_InvalidParametersNumberInTupleEnumVariants() = checkErrors(""" enum Foo { VAR0(), VAR1(u8) } fn main() { let _ = Foo::VAR0(); let _ = Foo::VAR1(1); let _ = Foo::VAR0<error descr="This function takes 0 parameters but 1 parameter was supplied [E0061]">(4)</error>; let _ = Foo::VAR1<error descr="This function takes 1 parameter but 2 parameters were supplied [E0061]">(10, false)</error>; } """) fun testE0061_RespectsCfgAttribute() = checkErrors(""" struct Foo; impl Foo { #[cfg(windows)] fn bar(&self, p1: u32) {} #[cfg(not(windows))] fn bar(&self) {} } fn main() { let foo = Foo; foo.bar(10); // Ignore both calls foo.bar(); } """) // We would like to cover such cases, but the resolve engine has some flaws at the moment, // so just ignore trait implementations to remove false positives fun testE0061_IgnoresTraitImplementations() = checkErrors(""" trait Foo1 { fn foo(&self); } trait Foo2 { fn foo(&self, a: u8); } struct Bar; impl Foo1 for Bar { fn foo(&self) {} } impl<T> Foo2 for Box<T> { fn foo(&self, a: u8) {} } type BFoo1<'a> = Box<Foo1 + 'a>; fn main() { let bar: BFoo1 = Box::new(Bar); bar.foo(); // Resolves to Foo2.foo() for Box<T>, though Foo1.foo() for Bar is the correct one } """) fun `test E0069 empty return`() = checkErrors(""" fn ok1() { return; } fn ok2() -> () { return; } fn ok3() -> u32 { let _ = || return; return 10 } fn err1() -> bool { <error descr="`return;` in a function whose return type is not `()` [E0069]">return</error>; } fn err2() -> ! { <error>return</error> } """) fun `test E0121 type placeholder in signatures`() = checkErrors(""" fn ok(_: &'static str) { let four = |x: _| 4; let _ = match (8, 3) { (_, _) => four(1) }; if let Some(_) = Some(0) {} } fn foo(a: <error descr="The type placeholder `_` is not allowed within types on item signatures [E0121]">_</error>) {} fn bar() -> <error>_</error> {} fn baz(t: (u32, <error>_</error>)) -> (bool, (f64, <error>_</error>)) {} static FOO: <error>_</error> = 42; """) fun testE0124_NameDuplicationInStruct() = checkErrors(""" struct S { no_dup: bool, <error descr="Field `dup` is already declared [E0124]">dup</error>: f64, <error descr="Field `dup` is already declared [E0124]">dup</error>: f64 } enum E { VAR1 { no_dup: bool }, VAR2 { no_dup: bool, <error descr="Field `dup` is already declared [E0124]">dup</error>: f64, <error descr="Field `dup` is already declared [E0124]">dup</error>: f64 } } """) fun testE0185_SelfInImplNotInTrait() = checkErrors(""" trait T { fn ok_foo(&self, x: u32); fn ok_bar(&mut self); fn ok_baz(self); fn foo(x: u32); fn bar(); fn baz(o: bool); } struct S; impl T for S { fn ok_foo(&self, x: u32) {} fn ok_bar(&mut self) {} fn ok_baz(self) {} fn foo(<error descr="Method `foo` has a `&self` declaration in the impl, but not in the trait [E0185]">&self</error>, x: u32) {} fn bar(<error descr="Method `bar` has a `&mut self` declaration in the impl, but not in the trait [E0185]">&mut self</error>) {} fn baz(<error descr="Method `baz` has a `self` declaration in the impl, but not in the trait [E0185]">self</error>, o: bool) {} } """) fun testE0186_SelfInTraitNotInImpl() = checkErrors(""" trait T { fn ok_foo(&self, x: u32); fn ok_bar(&mut self); fn ok_baz(self); fn foo(&self, x: u32); fn bar(&mut self); fn baz(self, o: bool); } struct S; impl T for S { fn ok_foo(&self, x: u32) {} fn ok_bar(&mut self) {} fn ok_baz(self) {} fn foo<error descr="Method `foo` has a `&self` declaration in the trait, but not in the impl [E0186]">(x: u32)</error> {} fn bar<error descr="Method `bar` has a `&mut self` declaration in the trait, but not in the impl [E0186]">()</error> {} fn baz<error descr="Method `baz` has a `self` declaration in the trait, but not in the impl [E0186]">(o: bool)</error> {} } """) fun `testE0199 Only safe impls for safe traits`() = checkErrors(""" struct Foo; struct Foo2; trait Bar { } unsafe impl <error descr="Implementing the trait `Bar` is not unsafe [E0199]">Bar</error> for Foo { } impl Bar for Foo2 { } """) fun `testE0200 Only unsafe impls for unsafe traits`() = checkErrors(""" struct Foo; struct Foo2; unsafe trait Bar { } unsafe impl Bar for Foo { } impl <error descr="The trait `Bar` requires an `unsafe impl` declaration [E0200]">Bar</error> for Foo2 { } """) fun testE0201_NameDuplicationInImpl() = checkErrors(""" struct Foo; impl Foo { fn fn_unique() {} fn <error descr="Duplicate definitions with name `dup` [E0201]">dup</error>(&self, a: u32) {} fn <error descr="Duplicate definitions with name `dup` [E0201]">dup</error>(&self, a: u32) {} } trait Bar { const UNIQUE: u32; const TRAIT_DUP: u32; fn unique() {} fn trait_dup() {} } impl Bar for Foo { const UNIQUE: u32 = 14; const <error descr="Duplicate definitions with name `TRAIT_DUP` [E0201]">TRAIT_DUP</error>: u32 = 101; const <error descr="Duplicate definitions with name `TRAIT_DUP` [E0201]">TRAIT_DUP</error>: u32 = 101; fn unique() {} fn <error descr="Duplicate definitions with name `trait_dup` [E0201]">trait_dup</error>() {} fn <error descr="Duplicate definitions with name `trait_dup` [E0201]">trait_dup</error>() {} } """) fun testE0202_TypeAliasInInherentImpl() = checkErrors(""" struct Foo; impl Foo { <error descr="Associated types are not allowed in inherent impls [E0202]">type Long = i64;</error> } """) fun `test E0261 undeclared lifetimes`() = checkErrors(""" fn foo<'a, 'b>(x: &'a u32, f: &'b Fn(&'b u8) -> &'b str) -> &'a u32 { x } const FOO: for<'a> fn(&'a u32) -> &'a u32 = foo_func; struct Struct<'a> { s: &'a str } enum En<'a, 'b> { A(&'a u32), B(&'b bool) } type Str<'d> = &'d str; fn foo_err<'a>(x: &<error descr="Use of undeclared lifetime name `'b` [E0261]">'b</error> str) {} fn bar() { 'foo: loop { let _: &<error descr="Use of undeclared lifetime name `'foo` [E0261]">'foo</error> str; } } """) fun `test E0261 not applied to static lifetimes`() = checkErrors(""" const ZERO: &'static u32 = &0; fn foo(a: &'static str) {} """) fun testE0263_LifetimeNameDuplicationInGenericParams() = checkErrors(""" fn foo<'a, 'b>(x: &'a str, y: &'b str) { } struct Str<'a, 'b> { a: &'a u32, b: &'b f64 } impl<'a, 'b> Str<'a, 'b> {} enum Direction<'a, 'b> { LEFT(&'a str), RIGHT(&'b str) } trait Trait<'a, 'b> {} fn bar<<error descr="Lifetime name `'a` declared twice in the same scope [E0263]">'a</error>, 'b, <error>'a</error>>(x: &'a str, y: &'b str) { } struct St<<error>'a</error>, 'b, <error>'a</error>> { a: &'a u32, b: &'b f64 } impl<<error>'a</error>, 'b, <error>'a</error>> Str<'a, 'b> {} enum Dir<<error>'a</error>, 'b, <error>'a</error>> { LEFT(&'a str), RIGHT(&'b str) } trait Tr<<error>'a</error>, 'b, <error>'a</error>> {} """) fun testE0379_ConstTraitFunction() = checkErrors(""" trait Foo { fn foo(); <error descr="Trait functions cannot be declared const [E0379]">const</error> fn bar(); } """) fun testE0403_NameDuplicationInGenericParams() = checkErrors(""" fn sub<T, P>() {} struct Str<T, P> { t: T, p: P } impl<T, P> Str<T, P> {} enum Direction<T, P> { LEFT(T), RIGHT(P) } trait Trait<T, P> {} fn add<<error descr="The name `T` is already used for a type parameter in this type parameter list [E0403]">T</error>, <error>T</error>, P>() {} struct S< <error>T</error>, <error>T</error>, P> { t: T, p: P } impl< <error>T</error>, <error>T</error>, P> S<T, T, P> {} enum En< <error>T</error>, <error>T</error>, P> { LEFT(T), RIGHT(P) } trait Tr< <error>T</error>, <error>T</error>, P> { fn foo(t: T) -> P; } """) fun testE0407_UnknownMethodInTraitImpl() = checkErrors(""" trait T { fn foo(); } impl T for () { fn foo() {} fn <error descr="Method `quux` is not a member of trait `T` [E0407]">quux</error>() {} } """) fun testE0415_NameDuplicationInParamList() = checkErrors(""" fn foo(x: u32, X: u32) {} fn bar<T>(T: T) {} fn simple(<error descr="Identifier `a` is bound more than once in this parameter list [E0415]">a</error>: u32, b: bool, <error>a</error>: f64) {} fn tuples(<error>a</error>: u8, (b, (<error>a</error>, c)): (u16, (u32, u64))) {} """) fun `test E0426 undeclared label`() = checkErrors(""" fn ok() { 'foo: loop { break 'foo } 'bar: while true { continue 'bar } 'baz: for _ in 0..3 { break 'baz } 'outer: loop { 'inner: while true { break 'outer } } } fn err<'a>(a: &'a str) { 'foo: loop { continue <error descr="Use of undeclared label `'bar` [E0426]">'bar</error> } while true { break <error descr="Use of undeclared label `'static` [E0426]">'static</error> } for _ in 0..1 { break <error descr="Use of undeclared label `'a` [E0426]">'a</error> } } """) fun testE0428_NameDuplicationInCodeBlock() = checkErrors(""" fn abc() { const UNIQUE_CONST: i32 = 10; static UNIQUE_STATIC: f64 = 0.72; fn unique_fn() {} struct UniqueStruct; trait UniqueTrait {} enum UniqueEnum {} mod unique_mod {} const <error descr="A value named `Dup` has already been defined in this block [E0428]">Dup</error>: u32 = 20; static <error descr="A value named `Dup` has already been defined in this block [E0428]">Dup</error>: i64 = -1.3; fn <error descr="A value named `Dup` has already been defined in this block [E0428]">Dup</error>() {} struct <error descr="A type named `Dup` has already been defined in this block [E0428]">Dup</error>; trait <error descr="A type named `Dup` has already been defined in this block [E0428]">Dup</error> {} enum <error descr="A type named `Dup` has already been defined in this block [E0428]">Dup</error> {} mod <error descr="A type named `Dup` has already been defined in this block [E0428]">Dup</error> {} } """) fun testE0428_NameDuplicationInEnum() = checkErrors(""" enum Directions { NORTH, <error descr="Enum variant `SOUTH` is already declared [E0428]">SOUTH</error> { distance: f64 }, WEST, <error descr="Enum variant `SOUTH` is already declared [E0428]">SOUTH</error> { distance: f64 }, EAST } """) fun testE0428_NameDuplicationInForeignMod() = checkErrors(""" extern "C" { static mut UNIQUE: u16; fn unique(); static mut <error descr="A value named `DUP` has already been defined in this module [E0428]">DUP</error>: u32; static mut <error descr="A value named `DUP` has already been defined in this module [E0428]">DUP</error>: u32; fn <error descr="A value named `dup` has already been defined in this module [E0428]">dup</error>(); fn <error descr="A value named `dup` has already been defined in this module [E0428]">dup</error>(); } """) fun testE0428_NameDuplicationInFile() = checkErrors(""" const UNIQUE_CONST: i32 = 10; static UNIQUE_STATIC: f64 = 0.72; fn unique_fn() {} struct UniqueStruct; trait UniqueTrait {} enum UniqueEnum {} mod unique_mod {} const <error descr="A value named `Dup` has already been defined in this module [E0428]">Dup</error>: u32 = 20; static <error descr="A value named `Dup` has already been defined in this module [E0428]">Dup</error>: i64 = -1.3; fn <error descr="A value named `Dup` has already been defined in this module [E0428]">Dup</error>() {} struct <error descr="A type named `Dup` has already been defined in this module [E0428]">Dup</error>; trait <error descr="A type named `Dup` has already been defined in this module [E0428]">Dup</error> {} enum <error descr="A type named `Dup` has already been defined in this module [E0428]">Dup</error> {} mod <error descr="A type named `Dup` has already been defined in this module [E0428]">Dup</error> {} """) fun testE0428_NameDuplicationInModule() = checkErrors(""" mod foo { const UNIQUE_CONST: i32 = 10; static UNIQUE_STATIC: f64 = 0.72; fn unique_fn() {} struct UniqueStruct; trait UniqueTrait {} enum UniqueEnum {} mod unique_mod {} const <error descr="A value named `Dup` has already been defined in this module [E0428]">Dup</error>: u32 = 20; static <error descr="A value named `Dup` has already been defined in this module [E0428]">Dup</error>: i64 = -1.3; fn <error descr="A value named `Dup` has already been defined in this module [E0428]">Dup</error>() {} struct <error descr="A type named `Dup` has already been defined in this module [E0428]">Dup</error>; trait <error descr="A type named `Dup` has already been defined in this module [E0428]">Dup</error> {} enum <error descr="A type named `Dup` has already been defined in this module [E0428]">Dup</error> {} mod <error descr="A type named `Dup` has already been defined in this module [E0428]">Dup</error> {} } """) fun testE0428_NameDuplicationInTrait() = checkErrors(""" trait T { type NO_DUP_T; const NO_DUP_C: u8; fn no_dup_f(); type <error descr="A type named `DUP_T` has already been defined in this trait [E0428]">DUP_T</error>; type <error descr="A type named `DUP_T` has already been defined in this trait [E0428]">DUP_T</error>; const <error descr="A value named `DUP_C` has already been defined in this trait [E0428]">DUP_C</error>: u32; const <error descr="A value named `DUP_C` has already been defined in this trait [E0428]">DUP_C</error>: u32; fn <error descr="A value named `dup` has already been defined in this trait [E0428]">dup</error>(&self); fn <error descr="A value named `dup` has already been defined in this trait [E0428]">dup</error>(&self); } """) fun testE0428_RespectsNamespaces() = checkErrors(""" mod m { // Consts and types are in different namespaces type NO_C_DUP = bool; const NO_C_DUP: u32 = 10; // Functions and types are in different namespaces type NO_F_DUP = u8; fn NO_F_DUP() {} // Consts and functions are in the same namespace (values) fn <error descr="A value named `DUP_V` has already been defined in this module [E0428]">DUP_V</error>() {} const <error>DUP_V</error>: u8 = 1; // Enums and traits are in the same namespace (types) trait <error descr="A type named `DUP_T` has already been defined in this module [E0428]">DUP_T</error> {} enum <error>DUP_T</error> {} <error descr="Unresolved module">mod foo;</error> fn foo() {} } """) override fun getProjectDescriptor(): LightProjectDescriptor = WithStdlibAndDependencyRustProjectDescriptor fun testE0428_RespectsCrateAliases() = checkErrors(""" extern crate libc as libc_alias; mod libc {} // FIXME: ideally we want to highlight these extern crate alloc; mod alloc {} """) fun testE0463_UnknownCrate() = checkErrors(""" extern crate alloc; <error descr="Can't find crate for `litarvan` [E0463]">extern crate litarvan;</error> """) fun testE0428_IgnoresLocalBindings() = checkErrors(""" mod no_dup { fn no_dup() { let no_dup: bool = false; fn no_dup(no_dup: u23) { mod no_dup {} } } } """) fun testE0428_IgnoresInnerContainers() = checkErrors(""" mod foo { const NO_DUP: u8 = 4; fn f() { const NO_DUP: u8 = 7; { const NO_DUP: u8 = 9; } } struct S { NO_DUP: u8 } trait T { const NO_DUP: u8 = 3; } enum E { NO_DUP } mod m { const NO_DUP: u8 = 1; } } """) fun testE0428_RespectsCfgAttribute() = checkErrors(""" mod opt { #[cfg(not(windows))] mod foo {} #[cfg(windows)] mod foo {} #[cfg(windows)] fn <error descr="A value named `hello_world` has already been defined in this module [E0428]">hello_world</error>() {} fn <error descr="A value named `hello_world` has already been defined in this module [E0428]">hello_world</error>() {} } """) fun testE0449_UnnecessaryPub() = checkErrors(""" <error descr="Unnecessary visibility qualifier [E0449]">pub</error> extern "C" { } pub struct S { foo: bool, pub bar: u8, pub baz: (u32, f64) } <error>pub</error> impl S {} struct STuple (pub u32, f64); pub enum E { FOO { bar: u32, <error>pub</error> baz: u32 }, BAR(<error>pub</error> u32, f64) } pub trait Foo { type A; fn b(); const C: u32; } struct Bar; <error>pub</error> impl Foo for Bar { <error>pub</error> type A = u32; <error>pub</error> fn b() {} <error>pub</error> const C: u32 = 10; } """) fun `testE0424 self in impl`() = checkErrors(""" struct Foo; impl Foo { fn foo() { let a = <error descr="The self keyword was used in a static method [E0424]">self</error>; } } """) fun `test self expression outside function`() = checkErrors(""" const C: () = <error descr="self value is not available in this context">self</error>; """) fun `testE0424 ignore non static`() = checkErrors(""" struct Foo; impl Foo { fn foo(self) { let a = self; } } """) fun `testE0424 ignore module path`() = checkErrors(""" fn foo() { } fn bar() { self::foo() } """) }
mit
305f1c8e68f2f857a7d7510dab0f4b9a
39.862967
152
0.540547
3.825893
false
true
false
false
REBOOTERS/AndroidAnimationExercise
imitate/src/main/java/com/engineer/imitate/ui/widget/view/TestDrawable.kt
1
705
package com.engineer.imitate.ui.widget.view import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import android.graphics.drawable.ShapeDrawable /** * @author rookie * @since 12-26-2019 */ class TestDrawable:ShapeDrawable() { private lateinit var mPaint: Paint private var mStrokeWidth = 5f private var mRadius = 5f private var mColor = Color.BLUE private val maxCount = 3 private var count = 0 private lateinit var rect: RectF private var OneDp = 0f private lateinit var mContext: Context override fun draw(canvas: Canvas) { super.draw(canvas) } }
apache-2.0
20dc24b1cedc0758cc011cf12a15a5e6
23.344828
46
0.733333
4.171598
false
false
false
false
KyuBlade/kotlin-discord-bot
src/main/kotlin/com/omega/discord/bot/command/impl/music/SeekCommand.kt
1
3330
package com.omega.discord.bot.command.impl.music import com.omega.discord.bot.audio.AudioPlayerManager import com.omega.discord.bot.audio.NotSeekableException import com.omega.discord.bot.command.Command import com.omega.discord.bot.ext.StringUtils import com.omega.discord.bot.ext.seek import com.omega.discord.bot.permission.Permission import com.omega.discord.bot.util.MessageSender import sx.blah.discord.handle.obj.IChannel import sx.blah.discord.handle.obj.IMessage import sx.blah.discord.handle.obj.IUser import sx.blah.discord.util.EmbedBuilder class SeekCommand : Command { override val name: String = "seek" override val aliases: Array<String>? = null override val usage: String = "**seek <position>** - Seek to the given position in the playing track (Format: HH:mm:ss)" override val allowPrivate: Boolean = false override val permission: Permission? = Permission.COMMAND_SEEK override val ownerOnly: Boolean = false override fun execute(author: IUser, channel: IChannel, message: IMessage, args: List<String>) { val audioManager = AudioPlayerManager.getAudioManager(channel.guild) val playingTrack = audioManager.audioPlayer.playingTrack if (args.isNotEmpty()) { val durationStr = args.first() val skipTo = try { if (playingTrack == null) { MessageSender.sendMessage(channel, "No track currently playing !") null } else { Math.min( StringUtils.parseDuration(durationStr), playingTrack.duration ) } } catch (e: NumberFormatException) { MessageSender.sendMessage(channel, "The duration must be in format HH:mm:ss") null } skipTo?.let { try { val embedBuilder = EmbedBuilder() val oldPosition = playingTrack.position audioManager.audioPlayer.seek(it) val position = playingTrack.position val duration = playingTrack.duration val fromStr = StringUtils.formatDuration(oldPosition) val toStr = StringUtils.formatDuration(it) val progressStr = "($toStr/${StringUtils.formatDuration(duration)}) " + StringUtils.getTrackAsciiProgressBar(position, duration, 40) embedBuilder .withTitle("Seeking") .appendField("Track", playingTrack.info.title, false) .appendField("From", fromStr, true) .appendField("To", toStr, true) .appendField("Progress", progressStr, false) MessageSender.sendMessage(channel, embedBuilder) } catch (e: IllegalStateException) { MessageSender.sendMessage(channel, "No track currently playing !") } catch (e: NotSeekableException) { MessageSender.sendMessage(channel, "The playing track is not seekable !") } } } else missingArgs(author, message) } }
gpl-3.0
d0237d20830edc8f09945f3d668cf6db
36.852273
123
0.589489
5.211268
false
false
false
false
Ztiany/Repository
Kotlin/Kotlin-Basic/src/main/BennyHuo/chapter05/Compose.kt
2
809
package chapter05 /**函数复合*/ //f(g(x)) m(x) = f(g(x)) val add5 = {i: Int -> i + 5} // g(x) val multiplyBy2 = {i : Int -> i * 2} // f(x) fun main(args: Array<String>) { println(multiplyBy2(add5(8))) // (5 + 8) * 2 val add5AndMultiplyBy2 = add5 andThen multiplyBy2 val add5ComposeMultiplyBy2 = add5 compose multiplyBy2 println(add5AndMultiplyBy2(8)) // m(x) = f(g(x)) println(add5ComposeMultiplyBy2(8)) // m(x) = g(f(x)) } infix fun <P1, P2, R> Function1<P1, P2>.andThen(function: Function1<P2, R>): Function1<P1,R>{ return fun(p1: P1): R{ return function.invoke(this.invoke(p1)) } } infix fun <P1,P2, R> Function1<P2, R>.compose(function: Function1<P1, P2>): Function1<P1, R>{ return fun(p1: P1): R{ return this.invoke(function.invoke(p1)) } }
apache-2.0
276ffe3334dd74565867ceaa3bfd6d76
28.703704
93
0.612984
2.510972
false
false
false
false
edvin/tornadofx
src/main/java/tornadofx/ErrorHandler.kt
1
4729
package tornadofx import javafx.application.Platform.runLater import javafx.scene.control.Alert import javafx.scene.control.Alert.AlertType.ERROR import javafx.scene.control.Label import javafx.scene.control.TextArea import javafx.scene.layout.VBox import javafx.scene.paint.Color import java.io.ByteArrayOutputStream import java.io.PrintWriter import java.util.logging.Level import java.util.logging.Logger class DefaultErrorHandler : Thread.UncaughtExceptionHandler { val log = Logger.getLogger("ErrorHandler") class ErrorEvent(val thread: Thread, val error: Throwable) { internal var consumed = false fun consume() { consumed = true } } companion object { // By default, all error messages are shown. Override to decide if certain errors should be handled another way. // Call consume to avoid error dialog. var filter: (ErrorEvent) -> Unit = { } } override fun uncaughtException(t: Thread, error: Throwable) { log.log(Level.SEVERE, "Uncaught error", error) if (isCycle(error)) { log.log(Level.INFO, "Detected cycle handling error, aborting.", error) } else { val event = ErrorEvent(t, error) filter(event) if (!event.consumed) { event.consume() runLater { showErrorDialog(error) } } } } private fun isCycle(error: Throwable) = error.stackTrace.any { it.className.startsWith("${javaClass.name}\$uncaughtException$") } private fun showErrorDialog(error: Throwable) { val cause = Label(if (error.cause != null) error.cause?.message else "").apply { style = "-fx-font-weight: bold" } val textarea = TextArea().apply { prefRowCount = 20 prefColumnCount = 50 text = stringFromError(error) } Alert(ERROR).apply { title = error.message ?: "An error occured" isResizable = true headerText = if (error.stackTrace.isNullOrEmpty()) "Error" else "Error in " + error.stackTrace[0].toString() dialogPane.content = VBox().apply { add(cause) if (error is RestException) { try { title = "HTTP Request Error: $title" form { fieldset(error.message) { val response = error.response if (response != null) { field("Status") { label("${response.statusCode} ${response.reason}") } val c = response.text() if (c != null) { tabpane { background = Color.TRANSPARENT.asBackground() tab("Plain text") { textarea(c) } tab("HTML") { if (response.header("Content-Type")?.contains("html", true) == true) select() webview { engine.loadContent(c) } } tab("Stacktrace") { add(textarea) } tabs.withEach { isClosable = false } } } else { add(textarea) } } else { add(textarea) } } } } catch (e: Exception) { add(textarea) } } else { add(textarea) } } showAndWait() } } } private fun stringFromError(e: Throwable): String { val out = ByteArrayOutputStream() val writer = PrintWriter(out) e.printStackTrace(writer) writer.close() return out.toString() }
apache-2.0
7daba5393cf9786015f8a6198075c16d
34.298507
120
0.425248
6.031888
false
false
false
false
ivan-osipov/Clabo
src/test/kotlin/com/github/ivan_osipov/clabo/infrastructure/dsl/dsl.kt
1
1211
package com.github.ivan_osipov.clabo.infrastructure.dsl import com.github.ivan_osipov.clabo.api.model.Chat import com.github.ivan_osipov.clabo.api.model.Message import com.github.ivan_osipov.clabo.api.model.Update import com.github.ivan_osipov.clabo.api.model.User import java.util.concurrent.ThreadLocalRandom fun update(init: Update.() -> Unit) : Update { val update = Update() update.id = ThreadLocalRandom.current().nextLong(1_000_000).toString() update.init() return update } fun Update.message(init: Message.() -> Unit) : Message { val message = Message() message.id = ThreadLocalRandom.current().nextLong(1_000_000).toString() message.from() message.init() this.message = message return message } fun Message.from(firstName: String = "defaultUser") : User { val user = User() user.id = ThreadLocalRandom.current().nextLong(1_000_000).toString() user.firstName = firstName this.from = user val chat = Chat() chat.id = user.id this.chat = chat return user } fun user(init: User.() -> Unit): User { val user = User() user.id = ThreadLocalRandom.current().nextLong(1_000_000).toString() user.init() return user }
apache-2.0
ec7a2910014fe37f59e9b3d9c219ae20
26.545455
75
0.692816
3.636637
false
false
false
false
panpf/sketch
sketch/src/androidTest/java/com/github/panpf/sketch/test/drawable/ResizeDrawableTest.kt
1
10215
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.test.drawable import android.graphics.Bitmap import android.graphics.Bitmap.Config.RGB_565 import android.graphics.Rect import android.graphics.drawable.BitmapDrawable import android.os.Build import androidx.test.ext.junit.runners.AndroidJUnit4 import com.github.panpf.sketch.cache.CountBitmap import com.github.panpf.sketch.datasource.DataFrom.LOCAL import com.github.panpf.sketch.decode.ImageInfo import com.github.panpf.sketch.drawable.SketchAnimatableDrawable import com.github.panpf.sketch.drawable.SketchCountBitmapDrawable import com.github.panpf.sketch.drawable.internal.ResizeAnimatableDrawable import com.github.panpf.sketch.drawable.internal.ResizeDrawable import com.github.panpf.sketch.drawable.internal.tryToResizeDrawable import com.github.panpf.sketch.fetch.newAssetUri import com.github.panpf.sketch.request.DisplayRequest import com.github.panpf.sketch.resize.Precision.EXACTLY import com.github.panpf.sketch.resize.Scale.CENTER_CROP import com.github.panpf.sketch.resize.Scale.END_CROP import com.github.panpf.sketch.resize.Scale.FILL import com.github.panpf.sketch.resize.Scale.START_CROP import com.github.panpf.sketch.test.utils.TestAnimatableDrawable1 import com.github.panpf.sketch.test.utils.TestNewMutateDrawable import com.github.panpf.sketch.test.utils.getTestContext import com.github.panpf.sketch.test.utils.getTestContextAndNewSketch import com.github.panpf.sketch.test.utils.intrinsicSize import com.github.panpf.sketch.test.utils.toRequestContext import com.github.panpf.sketch.util.Size import com.github.panpf.sketch.util.getDrawableCompat import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ResizeDrawableTest { @Test fun testTryToResizeDrawable() { val context = getTestContext() val resources = context.resources val imageUri = newAssetUri("sample.jpeg") val bitmapDrawable = BitmapDrawable(resources, Bitmap.createBitmap(100, 200, RGB_565)) val request = DisplayRequest(context, imageUri) Assert.assertSame( bitmapDrawable, bitmapDrawable.tryToResizeDrawable(request, null) ) val request1 = DisplayRequest(context, imageUri) { resizeApplyToDrawable(true) } Assert.assertSame( bitmapDrawable, bitmapDrawable.tryToResizeDrawable(request1, null) ) val request2 = DisplayRequest(context, imageUri) { resizeSize(500, 300) resizePrecision(EXACTLY) } Assert.assertSame( bitmapDrawable, bitmapDrawable.tryToResizeDrawable(request2, request2.toRequestContext().resizeSize) ) val request3 = DisplayRequest(context, imageUri) { resizeApplyToDrawable(true) resizeSize(500, 300) resizePrecision(EXACTLY) } bitmapDrawable.tryToResizeDrawable(request3, request3.toRequestContext().resizeSize) .let { it as ResizeDrawable } .apply { Assert.assertNotSame(bitmapDrawable, this) Assert.assertSame(bitmapDrawable, wrappedDrawable) Assert.assertEquals(Size(500, 300), resizeSize) } val animDrawable = SketchAnimatableDrawable( animatableDrawable = TestAnimatableDrawable1(bitmapDrawable), imageUri = imageUri, requestKey = imageUri, requestCacheKey = imageUri, imageInfo = ImageInfo(100, 200, "image/jpeg", 0), dataFrom = LOCAL, transformedList = null, extras = null, ) animDrawable.tryToResizeDrawable(request3, request3.toRequestContext().resizeSize) .let { it as ResizeAnimatableDrawable } .apply { Assert.assertNotSame(animDrawable, this) Assert.assertSame(animDrawable, wrappedDrawable) Assert.assertEquals(Size(500, 300), resizeSize) } } @Test fun testIntrinsicSize() { val context = getTestContext() val resources = context.resources val bitmapDrawable = BitmapDrawable(resources, Bitmap.createBitmap(100, 200, RGB_565)) .apply { Assert.assertEquals(Size(100, 200), intrinsicSize) } ResizeDrawable(bitmapDrawable, Size(500, 300), CENTER_CROP).apply { Assert.assertEquals(Size(500, 300), intrinsicSize) Assert.assertEquals(Size(500, 300), resizeSize) Assert.assertSame(bitmapDrawable, wrappedDrawable) } } @Test fun testSetBounds() { val (context, sketch) = getTestContextAndNewSketch() val resources = context.resources val imageUri = newAssetUri("sample.jpeg") val bitmapDrawable = BitmapDrawable(resources, Bitmap.createBitmap(100, 200, RGB_565)) .apply { Assert.assertEquals(Size(100, 200), intrinsicSize) } ResizeDrawable(bitmapDrawable, Size(500, 300), START_CROP).apply { setBounds(0, 0, 500, 300) Assert.assertEquals(Rect(0, 0, 500, 300), bounds) Assert.assertEquals(Rect(0, 0, 500, 1000), bitmapDrawable.bounds) } ResizeDrawable(bitmapDrawable, Size(500, 300), CENTER_CROP).apply { setBounds(0, 0, 500, 300) Assert.assertEquals(Rect(0, 0, 500, 300), bounds) Assert.assertEquals(Rect(0, -350, 500, 650), bitmapDrawable.bounds) } ResizeDrawable(bitmapDrawable, Size(500, 300), END_CROP).apply { setBounds(0, 0, 500, 300) Assert.assertEquals(Rect(0, 0, 500, 300), bounds) Assert.assertEquals(Rect(0, -700, 500, 300), bitmapDrawable.bounds) } ResizeDrawable(bitmapDrawable, Size(500, 300), FILL).apply { setBounds(0, 0, 500, 300) Assert.assertEquals(Rect(0, 0, 500, 300), bounds) Assert.assertEquals(Rect(0, 0, 500, 300), bitmapDrawable.bounds) } ResizeDrawable( ResizeDrawable(bitmapDrawable, Size(0, 300), CENTER_CROP), Size(500, 300), CENTER_CROP ).apply { setBounds(0, 0, 500, 300) Assert.assertEquals(Rect(0, 0, 500, 300), bounds) Assert.assertEquals(Rect(-75, 0, 75, 300), bitmapDrawable.bounds) } ResizeDrawable( ResizeDrawable(bitmapDrawable, Size(300, 0), CENTER_CROP), Size(width = 500, height = 300), CENTER_CROP ).apply { setBounds(0, 0, 500, 300) Assert.assertEquals(Rect(0, 0, 500, 300), bounds) Assert.assertEquals(Rect(0, -300, 300, 300), bitmapDrawable.bounds) } ResizeDrawable( ResizeDrawable(bitmapDrawable, Size(0, 0), CENTER_CROP), Size(500, 300), CENTER_CROP ).apply { setBounds(0, 0, 500, 300) Assert.assertEquals(Rect(0, 0, 500, 300), bounds) Assert.assertEquals(Rect(0, 0, 0, 0), bitmapDrawable.bounds) } val sketchDrawable = SketchCountBitmapDrawable( resources = resources, countBitmap = CountBitmap( cacheKey = imageUri, bitmap = Bitmap.createBitmap(100, 200, RGB_565), bitmapPool = sketch.bitmapPool, disallowReuseBitmap = false, ), imageUri = imageUri, requestKey = imageUri, requestCacheKey = imageUri, imageInfo = ImageInfo(100, 200, "image/jpeg", 0), transformedList = null, extras = null, dataFrom = LOCAL, ) ResizeDrawable(sketchDrawable, Size(500, 300), CENTER_CROP).apply { setBounds(0, 0, 500, 300) Assert.assertEquals(Rect(0, 0, 500, 300), bounds) Assert.assertEquals(Rect(0, 0, 0, 0), bitmapDrawable.bounds) } } @Test fun testMutate() { val context = getTestContext() ResizeDrawable( context.getDrawableCompat(android.R.drawable.bottom_bar), Size(500, 300), CENTER_CROP ).apply { mutate() alpha = 146 context.getDrawableCompat(android.R.drawable.bottom_bar).also { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { Assert.assertEquals(255, it.alpha) } } } ResizeDrawable( TestNewMutateDrawable(context.getDrawableCompat(android.R.drawable.bottom_bar)), Size(500, 300), CENTER_CROP ).apply { mutate() alpha = 146 context.getDrawableCompat(android.R.drawable.bottom_bar).also { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { Assert.assertEquals(255, it.alpha) } } } } @Test fun testToString() { val context = getTestContext() val resources = context.resources val bitmapDrawable = BitmapDrawable(resources, Bitmap.createBitmap(100, 200, RGB_565)) .apply { Assert.assertEquals(Size(100, 200), intrinsicSize) } ResizeDrawable(bitmapDrawable, Size(500, 300), CENTER_CROP).apply { Assert.assertEquals("ResizeDrawable(wrapped=$bitmapDrawable, resizeSize=500x300, resizeScale=CENTER_CROP)", toString()) } } }
apache-2.0
ef843946aa27abdfad3fce4c5b6bf357
37.844106
131
0.633676
4.482229
false
true
false
false
panpf/sketch
sample/src/main/java/com/github/panpf/sketch/sample/ui/huge/HugeImageVerPagerFragment.kt
1
1873
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.sample.ui.huge import android.os.Bundle import androidx.viewpager2.widget.ViewPager2 import com.github.panpf.assemblyadapter.pager2.AssemblyFragmentStateAdapter import com.github.panpf.sketch.sample.AssetImages import com.github.panpf.sketch.sample.databinding.TabPagerVerFragmentBinding import com.github.panpf.sketch.sample.ui.base.BindingFragment import com.github.panpf.sketch.sample.widget.VerTabLayoutMediator class HugeImageVerPagerFragment : BindingFragment<TabPagerVerFragmentBinding>() { override fun onViewCreated(binding: TabPagerVerFragmentBinding, savedInstanceState: Bundle?) { val images = AssetImages.HUGES.toList() val titles = arrayOf("WORLD", "CARD", "QMSHT", "CWB") binding.tabPagerVerPager.apply { orientation = ViewPager2.ORIENTATION_VERTICAL adapter = AssemblyFragmentStateAdapter( this@HugeImageVerPagerFragment, listOf(HugeImageViewerFragment.ItemFactory()), images ) } VerTabLayoutMediator( binding.tabPagerVerTabLayout, binding.tabPagerVerPager ) { tab, position -> tab.text = titles[position] }.attach() } }
apache-2.0
412a1a5e9d1c8d0615ca49e683cb5a56
38.041667
98
0.720235
4.396714
false
false
false
false
stripe/stripe-android
stripecardscan/src/main/java/com/stripe/android/stripecardscan/framework/image/ImageExtensions.kt
1
1975
package com.stripe.android.stripecardscan.framework.image import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.ImageFormat import android.graphics.Rect import android.media.Image import android.renderscript.RenderScript import androidx.annotation.CheckResult import com.stripe.android.camera.framework.exception.ImageTypeNotSupportedException import com.stripe.android.camera.framework.image.NV21Image import com.stripe.android.camera.framework.image.crop /** * Determine if this application supports an image format. */ @CheckResult internal fun Image.isSupportedFormat() = isSupportedFormat(this.format) /** * Determine if this application supports an image format. */ @CheckResult internal fun isSupportedFormat(imageFormat: Int) = when (imageFormat) { ImageFormat.YUV_420_888, ImageFormat.JPEG -> true ImageFormat.NV21 -> false // this fails on devices with android API 21. else -> false } /** * Convert an image to a bitmap for processing. This will throw an [ImageTypeNotSupportedException] * if the image type is not supported (see [isSupportedFormat]). */ @CheckResult @Throws(ImageTypeNotSupportedException::class) internal fun Image.toBitmap( renderScript: RenderScript, crop: Rect = Rect( 0, 0, this.width, this.height ) ): Bitmap = when (this.format) { ImageFormat.NV21 -> NV21Image(this).crop(crop).toBitmap(renderScript) ImageFormat.YUV_420_888 -> NV21Image(this).crop(crop).toBitmap(renderScript) ImageFormat.JPEG -> jpegToBitmap().crop(crop) else -> throw ImageTypeNotSupportedException(this.format) } @CheckResult private fun Image.jpegToBitmap(): Bitmap { require(format == ImageFormat.JPEG) { "Image is not in JPEG format" } val imageBuffer = planes[0].buffer val imageBytes = ByteArray(imageBuffer.remaining()) imageBuffer.get(imageBytes) return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size) }
mit
b5603011bd495391365c346bf007f49e
32.474576
99
0.76
4.265659
false
false
false
false
kittinunf/Fuel
fuel/src/test/kotlin/com/github/kittinunf/fuel/core/interceptors/ParameterEncoderTest.kt
1
10783
package com.github.kittinunf.fuel.core.interceptors import com.github.kittinunf.fuel.core.BlobDataPart import com.github.kittinunf.fuel.core.Headers import com.github.kittinunf.fuel.core.Method import com.github.kittinunf.fuel.core.requests.DefaultRequest import com.github.kittinunf.fuel.core.requests.upload import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.CoreMatchers.not import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.core.StringContains.containsString import org.junit.Test import java.io.ByteArrayInputStream import java.net.URL class ParameterEncoderTest { @Test fun encodeRequestParametersInUrlWhenBodyDisallowed() { val methods = listOf(Method.GET, Method.DELETE, Method.HEAD, Method.OPTIONS, Method.TRACE) methods.forEach { method -> val testRequest = DefaultRequest( method, URL("https://test.fuel.com"), parameters = listOf("foo" to "bar") ) var executed = false ParameterEncoder { request -> assertThat(request.url.toExternalForm(), containsString("?")) assertThat(request.url.query, containsString("foo=bar")) assertThat("Expected parameters to be cleared", request.parameters.isEmpty(), equalTo(true)) executed = true request }(testRequest) assertThat("Expected encoder \"next\" to be called", executed, equalTo(true)) } } @Test fun encodeAppendsRequestParametersInUrl() { val methods = listOf(Method.GET, Method.DELETE, Method.HEAD, Method.OPTIONS, Method.TRACE) methods.forEach { method -> val testRequest = DefaultRequest( method, URL("https://test.fuel.com?a=b"), parameters = listOf("foo" to "bar") ) var executed = false ParameterEncoder { request -> assertThat(request.url.toExternalForm(), containsString("?")) assertThat(request.url.query, containsString("&")) assertThat(request.url.query, containsString("a=b")) assertThat(request.url.query, containsString("foo=bar")) assertThat("Expected parameters to be cleared", request.parameters.isEmpty(), equalTo(true)) executed = true request }(testRequest) assertThat("Expected encoder \"next\" to be called", executed, equalTo(true)) } } @Test fun encodeRequestParametersInBodyWhenBodyAllowed() { val methods = listOf(Method.POST, Method.PATCH, Method.PUT) methods.forEach { method -> val testRequest = DefaultRequest( method, URL("https://test.fuel.com"), parameters = listOf("foo" to "bar") ) var executed = false ParameterEncoder { request -> assertThat(request.url.toExternalForm(), not(containsString("?"))) assertThat(request.url.query, not(containsString("foo=bar"))) val contentType = request[Headers.CONTENT_TYPE].lastOrNull()?.split(';')?.first() assertThat(contentType, equalTo("application/x-www-form-urlencoded")) assertThat(request.body.asString(contentType), equalTo("foo=bar")) assertThat("Expected parameters to be cleared", request.parameters.isEmpty(), equalTo(true)) executed = true request }(testRequest) assertThat("Expected encoder \"next\" to be called", executed, equalTo(true)) } } @Test fun encodeRequestParametersInUrlWhenBodyExists() { val methods = listOf(Method.POST, Method.PATCH, Method.PUT) methods.forEach { method -> val testRequest = DefaultRequest( method, URL("https://test.fuel.com"), parameters = listOf("foo" to "bar") ).body("my current body") var executed = false ParameterEncoder { request -> assertThat(request.url.toExternalForm(), containsString("?")) assertThat(request.url.query, containsString("foo=bar")) val contentType = request[Headers.CONTENT_TYPE].lastOrNull()?.split(';')?.first() assertThat(contentType, equalTo("text/plain")) assertThat(request.body.asString(contentType), equalTo("my current body")) assertThat("Expected parameters to be cleared", request.parameters.isEmpty(), equalTo(true)) executed = true request }(testRequest) assertThat("Expected encoder \"next\" to be called", executed, equalTo(true)) } } @Test fun ignoreParameterEncodingForMultipartFormDataRequests() { val methods = listOf(Method.POST, Method.PATCH, Method.PUT) methods.forEach { method -> val testRequest = DefaultRequest( method, URL("https://test.fuel.com"), parameters = listOf("foo" to "bar") ).header(Headers.CONTENT_TYPE, "multipart/form-data") .upload() .add { BlobDataPart(ByteArrayInputStream("12345678".toByteArray()), name = "test", contentLength = 8L) } var executed = false ParameterEncoder { request -> assertThat(request.url.toExternalForm(), not(containsString("?"))) assertThat(request.url.query, not(containsString("foo=bar"))) val contentType = request[Headers.CONTENT_TYPE].lastOrNull()?.split(';')?.first() assertThat(contentType, equalTo("multipart/form-data")) val body = String(request.body.toByteArray()) assertThat(body, containsString("foo")) assertThat(body, containsString("bar")) assertThat(body, containsString("test")) assertThat(body, containsString("12345678")) assertThat("Expected parameters not to be cleared", request.parameters.isEmpty(), equalTo(false)) executed = true request }(testRequest) assertThat("Expected encoder \"next\" to be called", executed, equalTo(true)) } } @Test fun encodeMultipleParameters() { val methods = listOf(Method.GET, Method.DELETE, Method.HEAD, Method.OPTIONS, Method.TRACE) methods.forEach { method -> val testRequest = DefaultRequest( method, URL("https://test.fuel.com"), parameters = listOf("foo" to "bar", "baz" to "q") ) var executed = false ParameterEncoder { request -> assertThat(request.url.toExternalForm(), containsString("?")) assertThat(request.url.query, containsString("foo=bar")) assertThat(request.url.query, containsString("baz=q")) assertThat("Expected parameters to be cleared", request.parameters.isEmpty(), equalTo(true)) executed = true request }(testRequest) assertThat("Expected encoder \"next\" to be called", executed, equalTo(true)) } } @Test fun encodeParameterWithoutValue() { val methods = listOf(Method.GET, Method.DELETE, Method.HEAD, Method.OPTIONS, Method.TRACE) methods.forEach { method -> val testRequest = DefaultRequest( method, URL("https://test.fuel.com"), parameters = listOf("foo" to "bar", "baz" to null, "q" to "") ) var executed = false ParameterEncoder { request -> assertThat(request.url.toExternalForm(), containsString("?")) assertThat(request.url.query, containsString("foo=bar")) assertThat(request.url.query, not(containsString("baz"))) assertThat(request.url.query, containsString("q")) assertThat("Expected parameters to be cleared", request.parameters.isEmpty(), equalTo(true)) executed = true request }(testRequest) assertThat("Expected encoder \"next\" to be called", executed, equalTo(true)) } } @Test fun encodeParametersWithListValues() { val methods = listOf(Method.GET, Method.DELETE, Method.HEAD, Method.OPTIONS, Method.TRACE) methods.forEach { method -> val testRequest = DefaultRequest( method, URL("https://test.fuel.com"), parameters = listOf("foo" to "bar", "baz" to listOf("x", "y", "z")) ) var executed = false ParameterEncoder { request -> assertThat(request.url.toExternalForm(), containsString("?")) assertThat(request.url.query, containsString("foo=bar")) assertThat(request.url.query, containsString("baz[]=x")) assertThat(request.url.query, containsString("baz[]=y")) assertThat(request.url.query, containsString("baz[]=z")) assertThat("Expected parameters to be cleared", request.parameters.isEmpty(), equalTo(true)) executed = true request }(testRequest) assertThat("Expected encoder \"next\" to be called", executed, equalTo(true)) } } @Test fun encodeParametersWithArrayValues() { val methods = listOf(Method.GET, Method.DELETE, Method.HEAD, Method.OPTIONS, Method.TRACE) methods.forEach { method -> val testRequest = DefaultRequest( method, URL("https://test.fuel.com"), parameters = listOf("foo" to "bar", "baz" to arrayOf("x", "y", "z")) ) var executed = false ParameterEncoder { request -> assertThat(request.url.toExternalForm(), containsString("?")) assertThat(request.url.query, containsString("foo=bar")) assertThat(request.url.query, containsString("baz[]=x")) assertThat(request.url.query, containsString("baz[]=y")) assertThat(request.url.query, containsString("baz[]=z")) assertThat("Expected parameters to be cleared", request.parameters.isEmpty(), equalTo(true)) executed = true request }(testRequest) assertThat("Expected encoder \"next\" to be called", executed, equalTo(true)) } } }
mit
2f694460795527e917234d4785f8c9c8
39.389513
116
0.580172
5.174184
false
true
false
false
tbaxter120/Restdroid
app/src/main/java/com/ridocula/restdroid/adapters/HistoryRequestRecyclerViewAdapter.kt
1
2450
package com.ridocula.restdroid.adapters import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import com.ridocula.restdroid.R import com.ridocula.restdroid.models.HistoryRequest import com.ridocula.restdroid.models.Request /** * [RecyclerView.Adapter] that can display a [Request] and makes a call to the * specified [OnListFragmentInteractionListener]. */ class HistoryRequestRecyclerViewAdapter(values: List<HistoryRequest>, private val mListener: OnItemClickedListener?) : RecyclerView.Adapter<HistoryRequestRecyclerViewAdapter.ViewHolder>() { private var mRequests: MutableList<HistoryRequest> = ArrayList() init { mRequests.addAll(values) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_request, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.mType.text = mRequests[position].type.toString() holder.mUrl.text = mRequests[position].url holder.mView.setOnClickListener { mListener?.onItemClicked(mRequests[position]) } } fun addItem(request: HistoryRequest) { mRequests.add(request) notifyItemInserted(mRequests.size - 1) } fun setData(data: List<HistoryRequest>) { mRequests.clear() mRequests.addAll(data) notifyDataSetChanged() } fun clearItems() { mRequests.clear() notifyDataSetChanged() } override fun getItemCount(): Int { return mRequests.size } inner class ViewHolder(val mView: View) : RecyclerView.ViewHolder(mView) { val mParentView: LinearLayout val mType: TextView var mUrl: TextView init { mParentView = mView.findViewById<LinearLayout>(R.id.llRequest) as LinearLayout mType = mView.findViewById<TextView>(R.id.tvType) as TextView mUrl = mView.findViewById<TextView>(R.id.tvUrl) as TextView } override fun toString(): String { return super.toString() + " '" + mUrl.text + "'" } } interface OnItemClickedListener { fun onItemClicked(item: HistoryRequest) } }
apache-2.0
dfbd4a7c1dc0bb53133c8ea0f2eee428
29.625
189
0.686531
4.605263
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/refactoring/extractTrait/RsExtractTraitProcessor.kt
2
9100
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.refactoring.extractTrait import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.usageView.BaseUsageViewDescriptor import com.intellij.usageView.UsageInfo import com.intellij.usageView.UsageViewDescriptor import org.rust.ide.utils.GenericConstraints import org.rust.ide.utils.import.RsImportHelper import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* import org.rust.stdext.mapNotNullToSet /** * This refactoring can be applied to either inherent impl or trait. * * ## `impl Struct` * - Create `trait NewTrait` and `impl NewTrait for Struct` * - Move members from `impl Struct` to `impl NewTrait for Struct` * - Find references to moved members and add trait imports * * `impl Struct { ... }` * ⇒ * ``` * trait NewTrait { ... } * impl NewTrait for Struct { ... } * ``` * * * ## `trait Trait` * - Create `trait NewTrait`, add super `: NewTrait` * - For each `impl Trait for Struct`: * - Create `impl NewTrait for Struct` * - Move members from `impl Trait for Struct` to `impl NewTrait for Struct` * - Find references to moved members and add trait imports * * ``` * trait OldTrait { ... } * impl OldTrait for StructN { ... } * ``` * ⇒ * ``` * trait NewTrait { ... } * impl NewTrait for StructN { ... } * ``` */ class RsExtractTraitProcessor( private val traitOrImpl: RsTraitOrImpl, private val traitName: String, private val members: List<RsItemElement>, ) : BaseRefactoringProcessor(traitOrImpl.project) { private val psiFactory = RsPsiFactory(traitOrImpl.project) override fun getCommandName(): String = "Extract Trait" override fun createUsageViewDescriptor(usages: Array<out UsageInfo>): UsageViewDescriptor = BaseUsageViewDescriptor(traitOrImpl, *usages.mapNotNull { it.element }.toTypedArray()) private class MemberUsage(reference: PsiReference) : UsageInfo(reference) private class ImplUsage(val impl: RsImplItem) : UsageInfo(impl) override fun findUsages(): Array<UsageInfo> { val implUsages = run { if (traitOrImpl !is RsTraitItem) return@run emptyList() traitOrImpl.searchForImplementations().map { ImplUsage(it) } } val membersNames = members.mapNotNullToSet { it.name } val membersInImpls = implUsages.flatMap { it.impl.getMembersWithNames(membersNames) } val membersAll = members + membersInImpls val memberUsages = membersAll.flatMap { member -> val references = ReferencesSearch.search(member, member.useScope) references.map { MemberUsage(it) } } return (implUsages + memberUsages).toTypedArray() } override fun performRefactoring(usages: Array<out UsageInfo>) { val newTraitConstraints = createNewTraitConstraints() val newTrait = createNewTrait(newTraitConstraints) ?: return if (traitOrImpl is RsTraitItem) { addDerivedBound(traitOrImpl) } addTraitImports(usages, newTrait) val impls = usages.filterIsInstance<ImplUsage>().map { it.impl } + listOfNotNull(traitOrImpl as? RsImplItem) for (impl in impls) { val newImpl = createNewImpl(impl, newTraitConstraints) ?: continue if (newImpl.containingMod != newTrait.containingMod) { RsImportHelper.importElement(newImpl, newTrait) } if (impl.traitRef == null && impl.explicitMembers.isEmpty()) { impl.delete() } } } private fun createNewTraitConstraints(): GenericConstraints { val typesInsideMembers = members .filterIsInstance<RsFunction>() .flatMap { function -> listOfNotNull(function.retType, function.valueParameterList) .flatMap { it.descendantsOfType<RsTypeReference>() } } return GenericConstraints.create(traitOrImpl).filterByTypeReferences(typesInsideMembers) } private fun createNewTrait(constraints: GenericConstraints): RsTraitItem? { val typeParameters = constraints.buildTypeParameters() val whereClause = constraints.buildWhereClause() val members = when (traitOrImpl) { is RsImplItem -> members.map { it.copy().makeAbstract(psiFactory) } is RsTraitItem -> members.map { member -> member.copy().also { member.delete() } } else -> return null } val traitBody = members.joinToString(separator = "\n") { it.text } val visibility = getTraitVisibility() val trait = psiFactory.tryCreateTraitItem( "${visibility}trait $traitName $typeParameters $whereClause {\n$traitBody\n}" ) ?: return null copyAttributes(traitOrImpl, trait) return traitOrImpl.parent.addAfter(trait, traitOrImpl) as? RsTraitItem } /** [impl] - either an inherent impl or impl of existing derived trait. */ private fun createNewImpl(impl: RsImplItem, traitConstraints: GenericConstraints): RsImplItem? { val typeText = impl.typeReference?.text ?: return null val typeParametersStruct = impl.typeParameterList?.text.orEmpty() val whereClauseStruct = impl.whereClause?.text.orEmpty() val typeArgumentsTrait = traitConstraints.buildTypeArguments() val newImplBody = extractMembersFromOldImpl(impl) val newImpl = psiFactory.tryCreateImplItem( "impl $typeParametersStruct $traitName $typeArgumentsTrait for $typeText $whereClauseStruct {\n$newImplBody\n}" ) ?: return null copyAttributes(traitOrImpl, newImpl) return impl.parent.addAfter(newImpl, impl) as? RsImplItem } private fun getTraitVisibility(): String { val unitedVisibility = when (traitOrImpl) { is RsTraitItem -> traitOrImpl.visibility is RsImplItem -> members.map { it.visibility }.reduce(RsVisibility::unite) else -> error("unreachable") } return unitedVisibility.format() } private fun extractMembersFromOldImpl(impl: RsImplItem): String { val membersNames = members.mapNotNullToSet { it.name } val membersToMove = impl.getMembersWithNames(membersNames) membersToMove.forEach { (it as? RsVisibilityOwner)?.vis?.delete() (it.prevSibling as? PsiWhiteSpace)?.delete() it.delete() } return membersToMove.joinToString("\n") { it.text } } private fun copyAttributes(source: RsTraitOrImpl, target: RsTraitOrImpl) { for (attr in source.outerAttrList) { if (attr.metaItem.name == "doc") continue val inserted = target.addAfter(attr, null) target.addAfter(psiFactory.createNewline(), inserted) } val members = target.members ?: return for (attr in source.innerAttrList) { if (attr.metaItem.name == "doc") continue members.addAfter(attr, members.lbrace) members.addAfter(psiFactory.createNewline(), members.lbrace) } } private fun addDerivedBound(trait: RsTraitItem) { val typeParamBounds = trait.typeParamBounds if (typeParamBounds == null) { val anchor = trait.identifier ?: trait.typeParameterList trait.addAfter(psiFactory.createTypeParamBounds(traitName), anchor) } else { typeParamBounds.addAfter(psiFactory.createPlus(), typeParamBounds.colon) typeParamBounds.addAfter(psiFactory.createPolybound(traitName), typeParamBounds.colon) } } private fun addTraitImports(usages: Array<out UsageInfo>, trait: RsTraitItem) { val mods = usages .filterIsInstance<MemberUsage>() .mapNotNullTo(hashSetOf()) { (it.element as? RsElement)?.containingMod } for (mod in mods) { val context = mod.childOfType<RsElement>() ?: continue RsImportHelper.importElement(context, trait) } } } private fun RsImplItem.getMembersWithNames(names: Set<String>): List<RsItemElement> { val implMembers = members?.childrenOfType<RsItemElement>() ?: return emptyList() return implMembers.filter { val name = it.name ?: return@filter false name in names } } fun PsiElement.makeAbstract(psiFactory: RsPsiFactory): PsiElement { if (this is RsVisibilityOwner) vis?.delete() when (this) { is RsFunction -> { block?.delete() if (semicolon == null) add(psiFactory.createSemicolon()) } is RsConstant -> { eq?.delete() expr?.delete() } is RsTypeAlias -> { eq?.delete() typeReference?.delete() } } return this }
mit
1fc74d08ff6a2ce5630400780909a3ed
36.432099
123
0.655453
4.617259
false
false
false
false
michael71/LanbahnPanel
app/src/main/java/de/blankedv/lanbahnpanel/loco/LocoButton.kt
1
3277
package de.blankedv.lanbahnpanel.loco import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Paint import android.util.Log import de.blankedv.lanbahnpanel.model.DEBUG import de.blankedv.lanbahnpanel.model.TAG import de.blankedv.lanbahnpanel.model.controlAreaRect import de.blankedv.lanbahnpanel.util.LanbahnBitmaps.bitmaps /** * a button in the loco control area */ class LocoButton { private var xrel: Float = 0.toFloat() private var yrel: Float = 0.toFloat() // relative position in control area. private var bmON: Bitmap? = null private var bmOFF: Bitmap? = null private var w = 10 private var h = 10 // half of the bitmap width and height public var name = "?" // x and y are actual position of bitmap placing, NOT the center! var x = 0f var y = 0f /** button with two bitmaps (dependent on state) * */ constructor(x2: Float, y2: Float, on: Bitmap, off: Bitmap) { this.xrel = x2 this.yrel = y2 bmON = on bmOFF = off w = bmON!!.width / 2 h = bmON!!.height / 2 if (controlAreaRect != null) { recalcXY() } } constructor(x2: Float, y2: Float, on: Bitmap) { this.xrel = x2 this.yrel = y2 bmON = on bmOFF = on w = bmON!!.width / 2 h = bmON!!.height / 2 if (controlAreaRect != null) { recalcXY() } } /** pure text button * */ constructor(x2: Float, y2: Float) { this.xrel = x2 this.yrel = y2 bmON = null bmOFF = null if (controlAreaRect != null) { w = (controlAreaRect!!.right - controlAreaRect!!.left) / 30 h = (controlAreaRect!!.bottom - controlAreaRect!!.top) / 3 } } fun isTouched(xt: Float, yt: Float): Boolean { if (xt > x && xt < x + w.toFloat() + w.toFloat() && yt > y && yt < y + h.toFloat() + h.toFloat()) { if (DEBUG) Log.d(TAG, name + " was touched.") return true } else { if (DEBUG) Log.d(TAG, name + " was not touched.") return false } } fun recalcXY() { if (bmON == null) { w = (controlAreaRect!!.right - controlAreaRect!!.left) / 30 h = (controlAreaRect!!.bottom - controlAreaRect!!.top) / 3 } x = controlAreaRect!!.left + xrel * (controlAreaRect!!.right - controlAreaRect!!.left) - w // position where bitmap is drawn y = controlAreaRect!!.top + yrel * (controlAreaRect!!.bottom - controlAreaRect!!.top) - h if (DEBUG) Log.d(TAG, this.toString() + " LocoBtn recalc, x=" + x + " y=" + y + " w=" + w + " h=" + h) } // for 2 states fun doDraw(c: Canvas, state: Boolean) { if (state) { c.drawBitmap(bmON!!, x, y, null) } else { c.drawBitmap(bmOFF!!, x, y, null) } } fun doDraw(c: Canvas, txt : String, p: Paint) { // (x,y) drawing position for text is DIFFERENT than for bitmaps.(upper left) // (x,y) = lower left start of text. c.drawText(txt, x + w * 0.6f, y + h * 1.42f, p) } companion object { private val bg = Paint() } }
gpl-3.0
653dd8a566dd62a3981bd059015a8f44
27.745614
133
0.548978
3.546537
false
false
false
false
arcuri82/testing_security_development_enterprise_systems
advanced/rest/gui-v1/src/main/kotlin/org/tsdes/advanced/rest/guiv1/BookRest.kt
1
3793
package org.tsdes.advanced.rest.guiv1 import io.swagger.annotations.Api import io.swagger.annotations.ApiOperation import io.swagger.annotations.ApiParam import org.tsdes.advanced.rest.guiv1.dto.BookDto import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import org.tsdes.advanced.rest.guiv1.db.Book import org.tsdes.advanced.rest.guiv1.db.BookRepository import java.net.URI @Api(value = "/api/books", description = "Handling of creating and retrieving book entries") @RequestMapping(path = ["/api/books"]) @RestController class BookRest( val repository: BookRepository ) { @ApiOperation("Get all the books") @GetMapping fun getAll(): ResponseEntity<List<BookDto>> { return ResponseEntity.status(200).body( DtoConverter.transform(repository.findAll()) ) } @ApiOperation("Create a new book") @PostMapping(consumes = [MediaType.APPLICATION_JSON_UTF8_VALUE]) fun create( @ApiParam("Data for new book") @RequestBody dto: BookDto ): ResponseEntity<Void> { if (dto.id != null) { // Cannot specify an id when creating a new book return ResponseEntity.status(400).build() } val entity = Book(dto.title!!, dto.author!!, dto.year!!) repository.save(entity) return ResponseEntity.created(URI.create("/api/books/" + entity.id)).build() } @ApiOperation("Get a specific book, by id") @GetMapping(path = ["/{id}"]) fun getById( @ApiParam("The id of the book") @PathVariable("id") pathId: String ): ResponseEntity<BookDto> { val id: Long try { id = pathId.toLong() } catch (e: Exception) { return ResponseEntity.status(400).build() } val book = repository.findById(id).orElse(null) ?: return ResponseEntity.status(404).build() return ResponseEntity.status(200).body(DtoConverter.transform(book)) } @ApiOperation("Delete a specific book, by id") @DeleteMapping(path = ["/{id}"]) fun deleteById( @ApiParam("The id of the book") @PathVariable("id") pathId: String ): ResponseEntity<Void> { val id: Long try { id = pathId.toLong() } catch (e: Exception) { return ResponseEntity.status(400).build() } if (!repository.existsById(id)) { return ResponseEntity.status(404).build() } repository.deleteById(id) return return ResponseEntity.status(204).build() } @ApiOperation("Update a specific book") @PutMapping(path = ["/{id}"], consumes = [MediaType.APPLICATION_JSON_UTF8_VALUE]) fun updateById( @ApiParam("The id of the book") @PathVariable("id") pathId: String, // @ApiParam("New data for updating the book") @RequestBody dto: BookDto ): ResponseEntity<Void> { val id: Long try { id = pathId.toLong() } catch (e: Exception) { return ResponseEntity.status(400).build() } if(dto.id == null){ return ResponseEntity.status(400).build() } if(dto.id != pathId){ return ResponseEntity.status(409).build() } val entity = repository.findById(id).orElse(null) ?: return ResponseEntity.status(404).build() entity.author = dto.author!! entity.title = dto.title!! entity.year = dto.year!! repository.save(entity) return ResponseEntity.status(204).build() } }
lgpl-3.0
fcda04e580c6c2a0a65deaf10587c682
26.492754
92
0.595571
4.334857
false
false
false
false
androidx/androidx
compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/window/WindowPosition.desktop.kt
3
4561
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.window import androidx.compose.runtime.Immutable import androidx.compose.runtime.Stable import androidx.compose.ui.Alignment import androidx.compose.ui.unit.Dp /** * Constructs an [WindowPosition.Absolute] from [x] and [y] [Dp] values. */ fun WindowPosition(x: Dp, y: Dp) = WindowPosition.Absolute(x, y) /** * Constructs an [WindowPosition.Aligned] from [alignment] value. */ fun WindowPosition(alignment: Alignment) = WindowPosition.Aligned(alignment) /** * Position of the window or dialog on the screen in [Dp]. */ @Immutable sealed class WindowPosition { /** * The horizontal position of the window in [Dp]. */ @Stable abstract val x: Dp /** * The vertical position of the window in [Dp]. */ @Stable abstract val y: Dp /** * `true` if the window position has specific coordinates on the screen * * `false` if coordinates are not yet determined (position is [PlatformDefault] or [Aligned]) */ @Stable abstract val isSpecified: Boolean /** * Initial position of the window that depends on the platform. * Usually every new window will be positioned in a cascade mode. * * This value should be used only before window will be visible. * After window will be visible, it cannot change its position to the PlatformDefault */ object PlatformDefault : WindowPosition() { override val x: Dp get() = Dp.Unspecified override val y: Dp get() = Dp.Unspecified override val isSpecified: Boolean get() = false @Stable override fun toString() = "PlatformDefault" } /** * Window will be aligned when it will be shown on the screen. [alignment] defines how the * window will be aligned (in the center, or in some of the corners). Window * will be aligned in the area that is not occupied by the screen insets (taskbar, OS menubar) */ @Immutable class Aligned(val alignment: Alignment) : WindowPosition() { override val x: Dp get() = Dp.Unspecified override val y: Dp get() = Dp.Unspecified override val isSpecified: Boolean get() = false /** * Returns a copy of this [Aligned] instance optionally overriding the * [alignment]. */ fun copy(alignment: Alignment = this.alignment) = Aligned(alignment) @Stable override fun toString() = "Aligned($alignment)" override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Aligned if (alignment != other.alignment) return false return true } override fun hashCode(): Int { return alignment.hashCode() } } /** * Absolute position of the window on the current window screen */ @Immutable class Absolute(override val x: Dp, override val y: Dp) : WindowPosition() { override val isSpecified: Boolean get() = true @Stable operator fun component1(): Dp = x @Stable operator fun component2(): Dp = y /** * Returns a copy of this [Absolute] instance optionally overriding the * [x] or [y] parameter. */ fun copy(x: Dp = this.x, y: Dp = this.y) = Absolute(x, y) @Stable override fun toString() = "Absolute($x, $y)" override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Absolute if (x != other.x) return false if (y != other.y) return false return true } override fun hashCode(): Int { var result = x.hashCode() result = 31 * result + y.hashCode() return result } } }
apache-2.0
812abe6c8531125d6eee7d1866a810a3
29.211921
98
0.62574
4.502468
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/keyvalue/AccountValues.kt
1
17983
package org.thoughtcrime.securesms.keyvalue import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager import androidx.annotation.VisibleForTesting import org.signal.core.util.logging.Log import org.signal.libsignal.protocol.IdentityKey import org.signal.libsignal.protocol.IdentityKeyPair import org.signal.libsignal.protocol.ecc.Curve import org.signal.libsignal.protocol.util.Medium import org.thoughtcrime.securesms.crypto.IdentityKeyUtil import org.thoughtcrime.securesms.crypto.MasterCipher import org.thoughtcrime.securesms.crypto.ProfileKeyUtil import org.thoughtcrime.securesms.crypto.storage.PreKeyMetadataStore import org.thoughtcrime.securesms.database.SignalDatabase import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.service.KeyCachingService import org.thoughtcrime.securesms.util.Base64 import org.thoughtcrime.securesms.util.TextSecurePreferences import org.thoughtcrime.securesms.util.Util import org.whispersystems.signalservice.api.push.ACI import org.whispersystems.signalservice.api.push.PNI import org.whispersystems.signalservice.api.push.ServiceIds import org.whispersystems.signalservice.api.push.SignalServiceAddress import java.lang.IllegalStateException import java.security.SecureRandom internal class AccountValues internal constructor(store: KeyValueStore) : SignalStoreValues(store) { companion object { private val TAG = Log.tag(AccountValues::class.java) private const val KEY_SERVICE_PASSWORD = "account.service_password" private const val KEY_REGISTRATION_ID = "account.registration_id" private const val KEY_FCM_ENABLED = "account.fcm_enabled" private const val KEY_FCM_TOKEN = "account.fcm_token" private const val KEY_FCM_TOKEN_VERSION = "account.fcm_token_version" private const val KEY_FCM_TOKEN_LAST_SET_TIME = "account.fcm_token_last_set_time" private const val KEY_DEVICE_NAME = "account.device_name" private const val KEY_DEVICE_ID = "account.device_id" private const val KEY_PNI_REGISTRATION_ID = "account.pni_registration_id" private const val KEY_ACI_IDENTITY_PUBLIC_KEY = "account.aci_identity_public_key" private const val KEY_ACI_IDENTITY_PRIVATE_KEY = "account.aci_identity_private_key" private const val KEY_ACI_SIGNED_PREKEY_REGISTERED = "account.aci_signed_prekey_registered" private const val KEY_ACI_NEXT_SIGNED_PREKEY_ID = "account.aci_next_signed_prekey_id" private const val KEY_ACI_ACTIVE_SIGNED_PREKEY_ID = "account.aci_active_signed_prekey_id" private const val KEY_ACI_SIGNED_PREKEY_FAILURE_COUNT = "account.aci_signed_prekey_failure_count" private const val KEY_ACI_NEXT_ONE_TIME_PREKEY_ID = "account.aci_next_one_time_prekey_id" private const val KEY_PNI_IDENTITY_PUBLIC_KEY = "account.pni_identity_public_key" private const val KEY_PNI_IDENTITY_PRIVATE_KEY = "account.pni_identity_private_key" private const val KEY_PNI_SIGNED_PREKEY_REGISTERED = "account.pni_signed_prekey_registered" private const val KEY_PNI_NEXT_SIGNED_PREKEY_ID = "account.pni_next_signed_prekey_id" private const val KEY_PNI_ACTIVE_SIGNED_PREKEY_ID = "account.pni_active_signed_prekey_id" private const val KEY_PNI_SIGNED_PREKEY_FAILURE_COUNT = "account.pni_signed_prekey_failure_count" private const val KEY_PNI_NEXT_ONE_TIME_PREKEY_ID = "account.pni_next_one_time_prekey_id" @VisibleForTesting const val KEY_E164 = "account.e164" @VisibleForTesting const val KEY_ACI = "account.aci" @VisibleForTesting const val KEY_PNI = "account.pni" @VisibleForTesting const val KEY_IS_REGISTERED = "account.is_registered" } init { if (!store.containsKey(KEY_ACI)) { migrateFromSharedPrefsV1(ApplicationDependencies.getApplication()) } if (!store.containsKey(KEY_ACI_IDENTITY_PUBLIC_KEY)) { migrateFromSharedPrefsV2(ApplicationDependencies.getApplication()) } } public override fun onFirstEverAppLaunch() = Unit public override fun getKeysToIncludeInBackup(): List<String> { return listOf( KEY_ACI_IDENTITY_PUBLIC_KEY, KEY_ACI_IDENTITY_PRIVATE_KEY, KEY_PNI_IDENTITY_PUBLIC_KEY, KEY_PNI_IDENTITY_PRIVATE_KEY, ) } /** The local user's [ACI]. */ val aci: ACI? get() = ACI.parseOrNull(getString(KEY_ACI, null)) /** The local user's [ACI]. Will throw if not present. */ fun requireAci(): ACI { return ACI.parseOrThrow(getString(KEY_ACI, null)) } fun setAci(aci: ACI) { putString(KEY_ACI, aci.toString()) } /** The local user's [PNI]. */ val pni: PNI? get() = PNI.parseOrNull(getString(KEY_PNI, null)) /** The local user's [PNI]. Will throw if not present. */ fun requirePni(): PNI { return PNI.parseOrThrow(getString(KEY_PNI, null)) } fun setPni(pni: PNI) { putString(KEY_PNI, pni.toString()) } fun getServiceIds(): ServiceIds { return ServiceIds(requireAci(), pni) } /** The local user's E164. */ val e164: String? get() = getString(KEY_E164, null) /** The local user's e164. Will throw if not present. */ fun requireE164(): String { val e164: String? = getString(KEY_E164, null) return e164 ?: throw IllegalStateException("No e164!") } fun setE164(e164: String) { putString(KEY_E164, e164) } /** The password for communicating with the Signal service. */ val servicePassword: String? get() = getString(KEY_SERVICE_PASSWORD, null) fun setServicePassword(servicePassword: String) { putString(KEY_SERVICE_PASSWORD, servicePassword) } /** A randomly-generated value that represents this registration instance. Helps the server know if you reinstalled. */ var registrationId: Int by integerValue(KEY_REGISTRATION_ID, 0) var pniRegistrationId: Int by integerValue(KEY_PNI_REGISTRATION_ID, 0) /** The identity key pair for the ACI identity. */ val aciIdentityKey: IdentityKeyPair get() { require(store.containsKey(KEY_ACI_IDENTITY_PUBLIC_KEY)) { "Not yet set!" } return IdentityKeyPair( IdentityKey(getBlob(KEY_ACI_IDENTITY_PUBLIC_KEY, null)), Curve.decodePrivatePoint(getBlob(KEY_ACI_IDENTITY_PRIVATE_KEY, null)) ) } /** The identity key pair for the PNI identity. */ val pniIdentityKey: IdentityKeyPair get() { require(store.containsKey(KEY_PNI_IDENTITY_PUBLIC_KEY)) { "Not yet set!" } return IdentityKeyPair( IdentityKey(getBlob(KEY_PNI_IDENTITY_PUBLIC_KEY, null)), Curve.decodePrivatePoint(getBlob(KEY_PNI_IDENTITY_PRIVATE_KEY, null)) ) } fun hasAciIdentityKey(): Boolean { return store.containsKey(KEY_ACI_IDENTITY_PUBLIC_KEY) } /** Generates and saves an identity key pair for the ACI identity. Should only be done once. */ fun generateAciIdentityKeyIfNecessary() { synchronized(this) { if (store.containsKey(KEY_ACI_IDENTITY_PUBLIC_KEY)) { Log.w(TAG, "Tried to generate an ANI identity, but one was already set!", Throwable()) return } Log.i(TAG, "Generating a new ACI identity key pair.") val key: IdentityKeyPair = IdentityKeyUtil.generateIdentityKeyPair() store .beginWrite() .putBlob(KEY_ACI_IDENTITY_PUBLIC_KEY, key.publicKey.serialize()) .putBlob(KEY_ACI_IDENTITY_PRIVATE_KEY, key.privateKey.serialize()) .commit() } } fun hasPniIdentityKey(): Boolean { return store.containsKey(KEY_PNI_IDENTITY_PUBLIC_KEY) } /** Generates and saves an identity key pair for the PNI identity if one doesn't already exist. */ fun generatePniIdentityKeyIfNecessary() { synchronized(this) { if (store.containsKey(KEY_PNI_IDENTITY_PUBLIC_KEY)) { Log.w(TAG, "Tried to generate a PNI identity, but one was already set!", Throwable()) return } Log.i(TAG, "Generating a new PNI identity key pair.") val key: IdentityKeyPair = IdentityKeyUtil.generateIdentityKeyPair() store .beginWrite() .putBlob(KEY_PNI_IDENTITY_PUBLIC_KEY, key.publicKey.serialize()) .putBlob(KEY_PNI_IDENTITY_PRIVATE_KEY, key.privateKey.serialize()) .commit() } } /** When acting as a linked device, this method lets you store the identity keys sent from the primary device */ fun setAciIdentityKeysFromPrimaryDevice(aciKeys: IdentityKeyPair) { synchronized(this) { require(isLinkedDevice) { "Must be a linked device!" } store .beginWrite() .putBlob(KEY_ACI_IDENTITY_PUBLIC_KEY, aciKeys.publicKey.serialize()) .putBlob(KEY_ACI_IDENTITY_PRIVATE_KEY, aciKeys.privateKey.serialize()) .commit() } } /** Set an identity key pair for the PNI identity via change number. */ fun setPniIdentityKeyAfterChangeNumber(key: IdentityKeyPair) { synchronized(this) { Log.i(TAG, "Setting a new PNI identity key pair.") store .beginWrite() .putBlob(KEY_PNI_IDENTITY_PUBLIC_KEY, key.publicKey.serialize()) .putBlob(KEY_PNI_IDENTITY_PRIVATE_KEY, key.privateKey.serialize()) .commit() } } /** Only to be used when restoring an identity public key from an old backup */ fun restoreLegacyIdentityPublicKeyFromBackup(base64: String) { Log.w(TAG, "Restoring legacy identity public key from backup.") putBlob(KEY_ACI_IDENTITY_PUBLIC_KEY, Base64.decode(base64)) } /** Only to be used when restoring an identity private key from an old backup */ fun restoreLegacyIdentityPrivateKeyFromBackup(base64: String) { Log.w(TAG, "Restoring legacy identity private key from backup.") putBlob(KEY_ACI_IDENTITY_PRIVATE_KEY, Base64.decode(base64)) } @get:JvmName("aciPreKeys") val aciPreKeys: PreKeyMetadataStore = object : PreKeyMetadataStore { override var nextSignedPreKeyId: Int by integerValue(KEY_ACI_NEXT_SIGNED_PREKEY_ID, SecureRandom().nextInt(Medium.MAX_VALUE)) override var activeSignedPreKeyId: Int by integerValue(KEY_ACI_ACTIVE_SIGNED_PREKEY_ID, -1) override var isSignedPreKeyRegistered: Boolean by booleanValue(KEY_ACI_SIGNED_PREKEY_REGISTERED, false) override var signedPreKeyFailureCount: Int by integerValue(KEY_ACI_SIGNED_PREKEY_FAILURE_COUNT, 0) override var nextOneTimePreKeyId: Int by integerValue(KEY_ACI_NEXT_ONE_TIME_PREKEY_ID, SecureRandom().nextInt(Medium.MAX_VALUE)) } @get:JvmName("pniPreKeys") val pniPreKeys: PreKeyMetadataStore = object : PreKeyMetadataStore { override var nextSignedPreKeyId: Int by integerValue(KEY_PNI_NEXT_SIGNED_PREKEY_ID, SecureRandom().nextInt(Medium.MAX_VALUE)) override var activeSignedPreKeyId: Int by integerValue(KEY_PNI_ACTIVE_SIGNED_PREKEY_ID, -1) override var isSignedPreKeyRegistered: Boolean by booleanValue(KEY_PNI_SIGNED_PREKEY_REGISTERED, false) override var signedPreKeyFailureCount: Int by integerValue(KEY_PNI_SIGNED_PREKEY_FAILURE_COUNT, 0) override var nextOneTimePreKeyId: Int by integerValue(KEY_PNI_NEXT_ONE_TIME_PREKEY_ID, SecureRandom().nextInt(Medium.MAX_VALUE)) } /** Indicates whether the user has the ability to receive FCM messages. Largely coupled to whether they have Play Service. */ @get:JvmName("isFcmEnabled") var fcmEnabled: Boolean by booleanValue(KEY_FCM_ENABLED, false) /** The FCM token, which allows the server to send us FCM messages. */ var fcmToken: String? get() { val tokenVersion: Int = getInteger(KEY_FCM_TOKEN_VERSION, 0) return if (tokenVersion == Util.getCanonicalVersionCode()) { getString(KEY_FCM_TOKEN, null) } else { null } } set(value) { store.beginWrite() .putString(KEY_FCM_TOKEN, value) .putInteger(KEY_FCM_TOKEN_VERSION, Util.getCanonicalVersionCode()) .putLong(KEY_FCM_TOKEN_LAST_SET_TIME, System.currentTimeMillis()) .apply() } /** When we last set the [fcmToken] */ val fcmTokenLastSetTime: Long get() = getLong(KEY_FCM_TOKEN_LAST_SET_TIME, 0) /** Whether or not the user is registered with the Signal service. */ val isRegistered: Boolean get() = getBoolean(KEY_IS_REGISTERED, false) fun setRegistered(registered: Boolean) { Log.i(TAG, "Setting push registered: $registered", Throwable()) val previous = isRegistered putBoolean(KEY_IS_REGISTERED, registered) ApplicationDependencies.getIncomingMessageObserver().notifyRegistrationChanged() if (previous != registered) { Recipient.self().live().refresh() } if (previous && !registered) { clearLocalCredentials(ApplicationDependencies.getApplication()) } } val deviceName: String? get() = getString(KEY_DEVICE_NAME, null) fun setDeviceName(deviceName: String) { putString(KEY_DEVICE_NAME, deviceName) } var deviceId: Int by integerValue(KEY_DEVICE_ID, SignalServiceAddress.DEFAULT_DEVICE_ID) val isPrimaryDevice: Boolean get() = deviceId == SignalServiceAddress.DEFAULT_DEVICE_ID val isLinkedDevice: Boolean get() = !isPrimaryDevice private fun clearLocalCredentials(context: Context) { putString(KEY_SERVICE_PASSWORD, Util.getSecret(18)) val newProfileKey = ProfileKeyUtil.createNew() val self = Recipient.self() SignalDatabase.recipients.setProfileKey(self.id, newProfileKey) ApplicationDependencies.getGroupsV2Authorization().clear() } /** Do not alter. If you need to migrate more stuff, create a new method. */ private fun migrateFromSharedPrefsV1(context: Context) { Log.i(TAG, "[V1] Migrating account values from shared prefs.") putString(KEY_ACI, TextSecurePreferences.getStringPreference(context, "pref_local_uuid", null)) putString(KEY_E164, TextSecurePreferences.getStringPreference(context, "pref_local_number", null)) putString(KEY_SERVICE_PASSWORD, TextSecurePreferences.getStringPreference(context, "pref_gcm_password", null)) putBoolean(KEY_IS_REGISTERED, TextSecurePreferences.getBooleanPreference(context, "pref_gcm_registered", false)) putInteger(KEY_REGISTRATION_ID, TextSecurePreferences.getIntegerPreference(context, "pref_local_registration_id", 0)) putBoolean(KEY_FCM_ENABLED, !TextSecurePreferences.getBooleanPreference(context, "pref_gcm_disabled", false)) putString(KEY_FCM_TOKEN, TextSecurePreferences.getStringPreference(context, "pref_gcm_registration_id", null)) putInteger(KEY_FCM_TOKEN_VERSION, TextSecurePreferences.getIntegerPreference(context, "pref_gcm_registration_id_version", 0)) putLong(KEY_FCM_TOKEN_LAST_SET_TIME, TextSecurePreferences.getLongPreference(context, "pref_gcm_registration_id_last_set_time", 0)) } /** Do not alter. If you need to migrate more stuff, create a new method. */ private fun migrateFromSharedPrefsV2(context: Context) { Log.i(TAG, "[V2] Migrating account values from shared prefs.") val masterSecretPrefs: SharedPreferences = context.getSharedPreferences("SecureSMS-Preferences", 0) val defaultPrefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) val storeWriter: KeyValueStore.Writer = store.beginWrite() if (masterSecretPrefs.hasStringData("pref_identity_public_v3")) { Log.i(TAG, "Migrating modern identity key.") val identityPublic = Base64.decode(masterSecretPrefs.getString("pref_identity_public_v3", null)!!) val identityPrivate = Base64.decode(masterSecretPrefs.getString("pref_identity_private_v3", null)!!) storeWriter .putBlob(KEY_ACI_IDENTITY_PUBLIC_KEY, identityPublic) .putBlob(KEY_ACI_IDENTITY_PRIVATE_KEY, identityPrivate) } else if (masterSecretPrefs.hasStringData("pref_identity_public_curve25519")) { Log.i(TAG, "Migrating legacy identity key.") val masterCipher = MasterCipher(KeyCachingService.getMasterSecret(context)) val identityPublic = Base64.decode(masterSecretPrefs.getString("pref_identity_public_curve25519", null)!!) val identityPrivate = masterCipher.decryptKey(Base64.decode(masterSecretPrefs.getString("pref_identity_private_curve25519", null)!!)).serialize() storeWriter .putBlob(KEY_ACI_IDENTITY_PUBLIC_KEY, identityPublic) .putBlob(KEY_ACI_IDENTITY_PRIVATE_KEY, identityPrivate) } else { Log.w(TAG, "No pre-existing identity key! No migration.") } storeWriter .putInteger(KEY_ACI_NEXT_SIGNED_PREKEY_ID, defaultPrefs.getInt("pref_next_signed_pre_key_id", SecureRandom().nextInt(Medium.MAX_VALUE))) .putInteger(KEY_ACI_ACTIVE_SIGNED_PREKEY_ID, defaultPrefs.getInt("pref_active_signed_pre_key_id", -1)) .putInteger(KEY_ACI_NEXT_ONE_TIME_PREKEY_ID, defaultPrefs.getInt("pref_next_pre_key_id", SecureRandom().nextInt(Medium.MAX_VALUE))) .putInteger(KEY_ACI_SIGNED_PREKEY_FAILURE_COUNT, defaultPrefs.getInt("pref_signed_prekey_failure_count", 0)) .putBoolean(KEY_ACI_SIGNED_PREKEY_REGISTERED, defaultPrefs.getBoolean("pref_signed_prekey_registered", false)) .commit() masterSecretPrefs .edit() .remove("pref_identity_public_v3") .remove("pref_identity_private_v3") .remove("pref_identity_public_curve25519") .remove("pref_identity_private_curve25519") .commit() defaultPrefs .edit() .remove("pref_local_uuid") .remove("pref_identity_public_v3") .remove("pref_next_signed_pre_key_id") .remove("pref_active_signed_pre_key_id") .remove("pref_signed_prekey_failure_count") .remove("pref_signed_prekey_registered") .remove("pref_next_pre_key_id") .remove("pref_gcm_password") .remove("pref_gcm_registered") .remove("pref_local_registration_id") .remove("pref_gcm_disabled") .remove("pref_gcm_registration_id") .remove("pref_gcm_registration_id_version") .remove("pref_gcm_registration_id_last_set_time") .commit() } private fun SharedPreferences.hasStringData(key: String): Boolean { return this.getString(key, null) != null } }
gpl-3.0
98363dff63278708f480f158ccbaf575
41.114754
151
0.726075
3.755848
false
false
false
false
DemonWav/StatCraft
src/main/kotlin/com/demonwav/statcraft/listeners/XpGainedListener.kt
1
1211
/* * StatCraft Bukkit Plugin * * Copyright (c) 2016 Kyle Wood (DemonWav) * https://www.demonwav.com * * MIT License */ package com.demonwav.statcraft.listeners import com.demonwav.statcraft.StatCraft import com.demonwav.statcraft.querydsl.QXpGained import org.bukkit.event.EventHandler import org.bukkit.event.EventPriority import org.bukkit.event.Listener import org.bukkit.event.player.PlayerExpChangeEvent class XpGainedListener(private val plugin: StatCraft) : Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) fun onXpGain(event: PlayerExpChangeEvent) { val amount = event.amount if (amount > 0) { val uuid = event.player.uniqueId val worldName = event.player.world.name plugin.threadManager.schedule<QXpGained>( uuid, worldName, { x, clause, id, worldId -> clause.columns(x.id, x.worldId, x.amount).values(id, worldId, amount).execute() }, { x, clause, id, worldId -> clause.where(x.id.eq(id), x.worldId.eq(worldId)).set(x.amount, x.amount.add(amount)).execute() } ) } } }
mit
b6ef73c2d0ebde17c7703e7855196e7d
31.72973
114
0.641618
4.023256
false
false
false
false
jeremymailen/kotlinter-gradle
src/main/kotlin/org/jmailen/gradle/kotlinter/tasks/GitHookTasks.kt
1
4810
package org.jmailen.gradle.kotlinter.tasks import org.gradle.api.DefaultTask import org.gradle.api.provider.Property import org.gradle.api.tasks.Input import org.gradle.api.tasks.Internal import org.gradle.api.tasks.TaskAction import org.jmailen.gradle.kotlinter.support.VersionProperties import java.io.File abstract class InstallPreCommitHookTask : InstallHookTask("pre-commit") { override val hookContent = """ if ! ${'$'}GRADLEW formatKotlin ; then echo 1>&2 "\nformatKotlin had non-zero exit status, aborting commit" exit 1 fi """.trimIndent() } abstract class InstallPrePushHookTask : InstallHookTask("pre-push") { override val hookContent = """ if ! ${'$'}GRADLEW lintKotlin ; then echo 1>&2 "\nlintKotlin found problems, running formatKotlin; commit the result and re-push" ${'$'}GRADLEW formatKotlin exit 1 fi """.trimIndent() } /** * Install or update a kotlinter-gradle hook. */ abstract class InstallHookTask(@get:Internal val hookFileName: String) : DefaultTask() { @Input val gitDirPath: Property<String> = project.objects.property(default = ".git") @Input val rootProjectDir = project.objects.property(default = project.rootProject.rootDir) @get:Internal abstract val hookContent: String init { outputs.upToDateWhen { getHookFile()?.readText()?.contains(hookVersion) ?: false } } @TaskAction fun run() { val hookFile = getHookFile(true) ?: return val hookFileContent = hookFile.readText() if (hookFileContent.isEmpty()) { logger.info("creating hook file: $hookFile") hookFile.writeText(generateHook(gradleCommand, hookContent, addShebang = true)) } else { val startIndex = hookFileContent.indexOf(startHook) if (startIndex == -1) { logger.info("adding hook to file: $hookFile") hookFile.appendText(generateHook(gradleCommand, hookContent)) } else { logger.info("replacing hook in file: $hookFile") val endIndex = hookFileContent.indexOf(endHook) val newHookFileContent = hookFileContent.replaceRange( startIndex, endIndex, generateHook(gradleCommand, hookContent, includeEndHook = false), ) hookFile.writeText(newHookFileContent) } } logger.quiet("Wrote hook to $hookFile") } private fun getHookFile(warn: Boolean = false): File? { val gitDir = File(rootProjectDir.get(), gitDirPath.get()) if (!gitDir.isDirectory) { if (warn) logger.warn("skipping hook creation because $gitDir is not a directory") return null } return try { val hooksDir = File(gitDir, "hooks").apply { mkdirs() } File(hooksDir, hookFileName).apply { createNewFile().and(setExecutable(true)) } } catch (e: Exception) { if (warn) logger.warn("skipping hook creation because could not create hook under $gitDir: ${e.message}") null } } private val gradleCommand: String by lazy { val gradlewFilename = if (System.getProperty("os.name").contains("win", true)) { "gradlew.bat" } else { "gradlew" } val gradlew = File(rootProjectDir.get(), gradlewFilename) if (gradlew.exists() && gradlew.isFile && gradlew.canExecute()) { logger.info("Using gradlew wrapper at ${gradlew.invariantSeparatorsPath}") gradlew.invariantSeparatorsPath } else { "gradle" } } companion object { private val version = VersionProperties().version() internal const val startHook = "\n##### KOTLINTER HOOK START #####" internal val hookVersion = "##### KOTLINTER $version #####" internal const val endHook = "##### KOTLINTER HOOK END #####\n" internal val shebang = """ #!/bin/sh set -e """.trimIndent() /** * Generate the hook script */ internal fun generateHook( gradlew: String, hookContent: String, addShebang: Boolean = false, includeEndHook: Boolean = true, ): String = (if (addShebang) shebang else "") + """ |$startHook |$hookVersion |GRADLEW=$gradlew |$hookContent |${if (includeEndHook) endHook else ""} """.trimMargin() } }
apache-2.0
555aa76a586f0144fdf8fd57b73df2b5
32.172414
117
0.574428
4.734252
false
false
false
false
bjzhou/Coolapk
app/src/main/kotlin/bjzhou/coolapk/app/model/CardEntity.kt
1
618
package bjzhou.coolapk.app.model class CardEntity { var entityType: String? = null var title: String? = null var url: String? = null var description: String? = null var pic: String = "" var lastupdate: Long = 0 override fun toString(): String { return "CardEntity{" + "entityType='" + entityType + '\'' + ", title='" + title + '\'' + ", url='" + url + '\'' + ", description='" + description + '\'' + ", pic='" + pic + '\'' + ", lastupdate=" + lastupdate + '}' } }
gpl-2.0
edc9f22ff8b2823b814369ebb0fcec19
28.428571
56
0.451456
4.544118
false
false
false
false
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/prettyCards/dto/PrettyCardsPrettyCard.kt
1
2627
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * 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. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.prettyCards.dto import com.google.gson.annotations.SerializedName import com.vk.sdk.api.base.dto.BaseImage import com.vk.sdk.api.base.dto.BaseLinkButton import kotlin.String import kotlin.collections.List /** * @param cardId - Card ID (long int returned as string) * @param linkUrl - Link URL * @param photo - Photo ID (format "<owner_id>_<media_id>") * @param title - Title * @param button - Button key * @param buttonText - Button text in current language * @param images * @param price - Price if set (decimal number returned as string) * @param priceOld - Old price if set (decimal number returned as string) */ data class PrettyCardsPrettyCard( @SerializedName("card_id") val cardId: String, @SerializedName("link_url") val linkUrl: String, @SerializedName("photo") val photo: String, @SerializedName("title") val title: String, @SerializedName("button") val button: BaseLinkButton? = null, @SerializedName("button_text") val buttonText: String? = null, @SerializedName("images") val images: List<BaseImage>? = null, @SerializedName("price") val price: String? = null, @SerializedName("price_old") val priceOld: String? = null )
mit
63ce8d323ad3301c3f929dad1965009e
38.80303
81
0.686334
4.278502
false
false
false
false
WonderBeat/vasilich
src/main/kotlin/com/vasilich/monitoring/RequestReplyMonitoring.kt
1
1345
package com.vasilich.monitoring class RequestReplyMatcher(val request: String, val replyMatcher: (String) -> Boolean, val explanation: String) fun createRequestReplyMatchers(requestReply: Collection<RequestReplyMonitoringCfg>, matcherBuilder: (String) -> ((String) -> Boolean)) :Collection<RequestReplyMatcher> = requestReply.map { entry -> RequestReplyMatcher(entry.say, matcherBuilder(entry.reply), entry.explanation) } /** * Like in a real chat this monitoring impl. will send Vasilich a message [configurable] and get a response * Executing matchers we can check if everything is OK * If, not, we will send a message with explanations */ public trait RequestReplyMonitor<T>: CommandMonitoring { val matchers: Collection<RequestReplyMatcher> private fun lookupFailedCommands(requestReply: RequestReplyMatcher): String? { fun RequestReplyMatcher.match(reply: String) = replyMatcher(reply) val reply = command.execute(requestReply.request) return when { reply != null && requestReply.match(reply) -> requestReply.explanation else -> null } } override fun check(): Collection<String> = matchers.map { lookupFailedCommands(it) }.filterNotNull().plus(super.check()) }
gpl-2.0
e592792d2add0e47c96926b1a6e06951
42.387097
124
0.685502
4.621993
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/user/CountryStatisticsTable.kt
1
487
package de.westnordost.streetcomplete.data.user object CountryStatisticsTable { const val NAME = "country_statistics" object Columns { const val COUNTRY_CODE = "country_code" const val SUCCEEDED = "succeeded" const val RANK = "rank" } const val CREATE = """ CREATE TABLE $NAME ( ${Columns.COUNTRY_CODE} varchar(255) PRIMARY KEY, ${Columns.SUCCEEDED} int NOT NULL, ${Columns.RANK} int );""" }
gpl-3.0
2d51932020964e135280fd5a9d85b8d0
26.055556
61
0.597536
4.348214
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/data/notification/repository/NotificationRepositoryImpl.kt
1
1718
package org.stepik.android.data.notification.repository import io.reactivex.Completable import io.reactivex.Single import org.stepic.droid.model.NotificationCategory import org.stepic.droid.notifications.model.Notification import org.stepic.droid.notifications.model.NotificationStatuses import ru.nobird.android.core.model.PagedList import org.stepik.android.data.notification.source.NotificationCacheDataSource import org.stepik.android.data.notification.source.NotificationRemoteDataSource import org.stepik.android.domain.notification.repository.NotificationRepository import javax.inject.Inject class NotificationRepositoryImpl @Inject constructor( private val notificationCacheDataSource: NotificationCacheDataSource, private val notificationRemoteDataSource: NotificationRemoteDataSource ) : NotificationRepository { override fun putNotifications(vararg notificationIds: Long, isRead: Boolean): Completable = notificationRemoteDataSource.putNotifications(*notificationIds, isRead = isRead) override fun getNotificationsByCourseId(courseId: Long): Single<List<Notification>> = notificationCacheDataSource.getNotificationsByCourseId(courseId) override fun getNotifications(notificationCategory: NotificationCategory, page: Int): Single<PagedList<Notification>> = notificationRemoteDataSource.getNotifications(notificationCategory, page) override fun markNotificationAsRead(notificationCategory: NotificationCategory): Completable = notificationRemoteDataSource.markNotificationAsRead(notificationCategory) override fun getNotificationStatuses(): Single<List<NotificationStatuses>> = notificationRemoteDataSource.getNotificationStatuses() }
apache-2.0
261c7fe8a0da60fa6f70d58483a7e602
49.558824
123
0.842258
5.804054
false
false
false
false
dhleong/ideavim
src/com/maddyhome/idea/vim/action/copy/YankLineAction.kt
1
2256
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2019 The IdeaVim authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.maddyhome.idea.vim.action.copy import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Editor import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.action.VimCommandAction import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.command.CommandFlags import com.maddyhome.idea.vim.command.MappingMode import com.maddyhome.idea.vim.handler.VimActionHandler import com.maddyhome.idea.vim.helper.enumSetOf import java.util.* import javax.swing.KeyStroke class YankLineAction : VimCommandAction() { override val mappingModes: Set<MappingMode> = MappingMode.N override val keyStrokesSet: Set<List<KeyStroke>> = parseKeysSet("Y") override val type: Command.Type = Command.Type.COPY override fun makeActionHandler(): VimActionHandler = YankLineActionHandler } class YankLineMidCountAction : VimCommandAction() { override val mappingModes: Set<MappingMode> = MappingMode.N override val keyStrokesSet: Set<List<KeyStroke>> = parseKeysSet("yy") override val type: Command.Type = Command.Type.COPY override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_ALLOW_MID_COUNT) override fun makeActionHandler(): VimActionHandler = YankLineActionHandler } private object YankLineActionHandler : VimActionHandler.SingleExecution() { override fun execute(editor: Editor, context: DataContext, cmd: Command): Boolean { return VimPlugin.getYank().yankLine(editor, cmd.count) } }
gpl-2.0
37944ad148cb60e826f07b2db6bd6e4f
36.6
90
0.783245
4.232645
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/reflection/mapping/inlineReifiedFun.kt
1
449
// IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT import kotlin.reflect.* import kotlin.reflect.jvm.* import kotlin.test.assertEquals inline fun <reified T> f() = 1 fun g() {} class Foo { inline fun <reified T> h(t: T) = 1 } fun box(): String { assertEquals(::g, ::g.javaMethod!!.kotlinFunction) val h = Foo::class.members.single { it.name == "h" } as KFunction<*> assertEquals(h, h.javaMethod!!.kotlinFunction) return "OK" }
apache-2.0
20a10bce2890bad4bf16103af41f0b39
18.521739
72
0.650334
3.301471
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/splash/notification/RemindRegistrationNotificationDelegate.kt
1
2789
package org.stepik.android.view.splash.notification import android.content.Context import android.content.Intent import androidx.core.app.TaskStackBuilder import org.stepic.droid.R import org.stepic.droid.preferences.SharedPreferenceHelper import org.stepic.droid.ui.activities.SplashActivity import org.stepic.droid.util.AppConstants import org.stepic.droid.util.DateTimeHelper import org.stepik.android.view.notification.NotificationDelegate import org.stepik.android.view.notification.StepikNotificationManager import org.stepik.android.view.notification.helpers.NotificationHelper import javax.inject.Inject class RemindRegistrationNotificationDelegate @Inject constructor( private val context: Context, private val sharedPreferenceHelper: SharedPreferenceHelper, private val notificationHelper: NotificationHelper, stepikNotificationManager: StepikNotificationManager ) : NotificationDelegate("show_registration_notification", stepikNotificationManager) { companion object { private const val REGISTRATION_REMIND_NOTIFICATION_ID = 5L } override fun onNeedShowNotification() { if (sharedPreferenceHelper.isEverLogged) return val intent = Intent(context, SplashActivity::class.java) val taskBuilder = TaskStackBuilder .create(context) .addNextIntent(intent) val title = context.getString(R.string.stepik_free_courses_title) val remindMessage = context.getString(R.string.registration_remind_message) val notification = notificationHelper.makeSimpleNotificationBuilder( stepikNotification = null, justText = remindMessage, taskBuilder = taskBuilder, title = title, id = REGISTRATION_REMIND_NOTIFICATION_ID ) showNotification(REGISTRATION_REMIND_NOTIFICATION_ID, notification.build()) scheduleRemindRegistrationNotification() } fun scheduleRemindRegistrationNotification() { if (sharedPreferenceHelper.authResponseFromStore != null) { sharedPreferenceHelper.setHasEverLogged() } if (sharedPreferenceHelper.isEverLogged) return val now = DateTimeHelper.nowUtc() val oldTimestamp = sharedPreferenceHelper.registrationRemindTimestamp val scheduleMillis = if (now < oldTimestamp) { oldTimestamp } else { if (oldTimestamp == 0L) { // means that notification wasn't shown before now + AppConstants.MILLIS_IN_1HOUR } else { now + 2 * AppConstants.MILLIS_IN_1HOUR } } scheduleNotificationAt(scheduleMillis) sharedPreferenceHelper.saveRegistrationRemindTimestamp(scheduleMillis) } }
apache-2.0
7512b5bf6a3f7383bbb6e7b1266e1848
37.219178
87
0.719613
5.29222
false
false
false
false
Maccimo/intellij-community
platform/vcs-impl/src/com/intellij/util/ui/cloneDialog/RepositoryUrlCloneDialogExtension.kt
1
4782
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.util.ui.cloneDialog import com.intellij.icons.AllIcons import com.intellij.openapi.application.ModalityState import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.Disposer import com.intellij.openapi.vcs.CheckoutProvider import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.ui.VcsCloneComponent import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogExtension import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogExtensionComponent import com.intellij.ui.SimpleListCellRenderer import com.intellij.ui.components.panels.Wrapper import com.intellij.ui.layout.* import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import java.awt.BorderLayout import java.awt.event.ItemEvent import javax.swing.DefaultComboBoxModel import javax.swing.Icon import javax.swing.JComponent import javax.swing.JPanel class RepositoryUrlCloneDialogExtension : VcsCloneDialogExtension { override fun getIcon(): Icon = AllIcons.Vcs.FromVCSDialog override fun getName() = VcsBundle.message("clone.dialog.repository.url.item") override fun getTooltip(): String { return CheckoutProvider.EXTENSION_POINT_NAME.extensions .map { it.vcsName } .joinToString { it.replace("_", "") } } override fun createMainComponent(project: Project): VcsCloneDialogExtensionComponent { throw AssertionError("Shouldn't be called") // NON-NLS } override fun createMainComponent(project: Project, modalityState: ModalityState): VcsCloneDialogExtensionComponent { return RepositoryUrlMainExtensionComponent(project, modalityState) } class RepositoryUrlMainExtensionComponent(private val project: Project, private val modalityState: ModalityState) : VcsCloneDialogExtensionComponent() { override fun onComponentSelected() { dialogStateListener.onOkActionNameChanged(getCurrentVcsComponent()?.getOkButtonText() ?: VcsBundle.message("clone.dialog.clone.button")) dialogStateListener.onOkActionEnabled(true) getCurrentVcsComponent()?.onComponentSelected(dialogStateListener) } private val vcsComponents = HashMap<CheckoutProvider, VcsCloneComponent>() private val mainPanel = JPanel(BorderLayout()) private val centerPanel = Wrapper() private val comboBox: ComboBox<CheckoutProvider> = ComboBox<CheckoutProvider>().apply { renderer = SimpleListCellRenderer.create<CheckoutProvider>("") { it.vcsName.removePrefix("_") } } init { val northPanel = panel { row(VcsBundle.message("vcs.common.labels.version.control")) { comboBox() } } val insets = UIUtil.PANEL_REGULAR_INSETS northPanel.border = JBUI.Borders.empty(insets) mainPanel.add(northPanel, BorderLayout.NORTH) mainPanel.add(centerPanel, BorderLayout.CENTER) val providers = CheckoutProvider.EXTENSION_POINT_NAME.extensions val selectedByDefaultProvider: CheckoutProvider? = if (providers.isNotEmpty()) providers[0] else null providers.sortWith(CheckoutProvider.CheckoutProviderComparator()) comboBox.model = DefaultComboBoxModel(providers).apply { selectedItem = null } comboBox.addItemListener { e: ItemEvent -> if (e.stateChange == ItemEvent.SELECTED) { val provider = e.item as CheckoutProvider centerPanel.setContent(vcsComponents.getOrPut(provider, { val cloneComponent = provider.buildVcsCloneComponent(project, modalityState, dialogStateListener) Disposer.register(this, cloneComponent) cloneComponent }).getView()) centerPanel.revalidate() centerPanel.repaint() onComponentSelected() } } comboBox.selectedItem = selectedByDefaultProvider } override fun getView() = mainPanel fun openForVcs(clazz: Class<out CheckoutProvider>): RepositoryUrlMainExtensionComponent { comboBox.selectedItem = CheckoutProvider.EXTENSION_POINT_NAME.findExtension(clazz) return this } override fun doClone(checkoutListener: CheckoutProvider.Listener) { getCurrentVcsComponent()?.doClone(checkoutListener) } override fun doValidateAll(): List<ValidationInfo> { return getCurrentVcsComponent()?.doValidateAll() ?: emptyList() } override fun getPreferredFocusedComponent(): JComponent? = getCurrentVcsComponent()?.getPreferredFocusedComponent() private fun getCurrentVcsComponent() = vcsComponents[comboBox.selectedItem as CheckoutProvider] } }
apache-2.0
70e75ffe5881a67ecad5835e5dd07a83
40.224138
142
0.750105
5.108974
false
false
false
false
Maccimo/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/extensions/common/plantuml/PlantUMLCodeGeneratingProvider.kt
2
3878
// 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.intellij.plugins.markdown.extensions.common.plantuml import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.registry.Registry import org.intellij.markdown.ast.ASTNode import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.extensions.MarkdownBrowserPreviewExtension import org.intellij.plugins.markdown.extensions.MarkdownCodeFenceCacheableProvider import org.intellij.plugins.markdown.extensions.MarkdownExtensionWithDownloadableFiles import org.intellij.plugins.markdown.extensions.MarkdownExtensionWithDownloadableFiles.FileEntry import org.intellij.plugins.markdown.ui.preview.MarkdownHtmlPanel import org.intellij.plugins.markdown.ui.preview.html.MarkdownCodeFencePluginCacheCollector import org.jetbrains.annotations.ApiStatus import java.io.File import java.io.IOException @ApiStatus.Internal class PlantUMLCodeGeneratingProvider( collector: MarkdownCodeFencePluginCacheCollector? = null ): MarkdownCodeFenceCacheableProvider(collector), MarkdownExtensionWithDownloadableFiles, MarkdownBrowserPreviewExtension.Provider { override val externalFiles: Iterable<String> get() = ownFiles override val filesToDownload: Iterable<FileEntry> get() = dowloadableFiles override fun isApplicable(language: String): Boolean { return isEnabled && isAvailable && (language == "puml" || language == "plantuml") } override fun generateHtml(language: String, raw: String, node: ASTNode): String { val key = getUniqueFile(language, raw, "png").toFile() cacheDiagram(key, raw) collector?.addAliveCachedFile(this, key) return "<img src=\"${key.toURI()}\"/>" } override val displayName: String get() = MarkdownBundle.message("markdown.extensions.plantuml.display.name") override val description: String get() = MarkdownBundle.message("markdown.extensions.plantuml.description") override val id: String = "PlantUMLLanguageExtension" override fun beforeCleanup() { PlantUMLJarManager.getInstance().dropCache() } /** * PlantUML support doesn't currently require any actions/resources inside an actual browser. * This implementation is not registered in plugin.xml and is needed to make sure that * PlantUML support extension is treated the same way as other browser extensions (like Mermaid.js one). * * Such code can be found mostly in [org.intellij.plugins.markdown.settings.MarkdownSettingsConfigurable]. */ override fun createBrowserExtension(panel: MarkdownHtmlPanel): MarkdownBrowserPreviewExtension? { return null } private fun cacheDiagram(path: File, text: String) { if (!path.exists()) { generateDiagram(text, path) } } @Throws(IOException::class) private fun generateDiagram(text: CharSequence, diagramPath: File) { var innerText: String = text.toString().trim() if (!innerText.startsWith("@startuml")) { innerText = "@startuml\n$innerText" } if (!innerText.endsWith("@enduml")) { innerText += "\n@enduml" } FileUtil.createParentDirs(diagramPath) storeDiagram(innerText, diagramPath) } companion object { const val jarFilename = "plantuml.jar" private val ownFiles = listOf(jarFilename) private val dowloadableFiles = listOf(FileEntry(jarFilename) { Registry.stringValue("markdown.plantuml.download.link") }) private fun storeDiagram(source: String, file: File) { try { file.outputStream().buffered().use { PlantUMLJarManager.getInstance().generateImage(source, it) } } catch (exception: Exception) { thisLogger().warn("Cannot save diagram PlantUML diagram. ", exception) } } } }
apache-2.0
f9f6c9e4f70095ed68cc918ea1ff8ec8
39.821053
158
0.761733
4.447248
false
false
false
false
AcornUI/Acorn
acornui-core/src/test/kotlin/com/acornui/headless/ApplicationTest.kt
1
2608
/* * Copyright 2019 Poly Forest, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.acornui.headless import com.acornui.app import com.acornui.async.TimeoutException import com.acornui.component.ComponentInit import com.acornui.component.Div import com.acornui.component.UiComponent import com.acornui.component.stage import com.acornui.di.Context import com.acornui.own import com.acornui.test.* import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlin.js.Promise import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.fail import kotlin.time.seconds class ApplicationTest { @Test fun expectTimeout1() = runTest(timeout = 1.seconds) { delay(2.seconds) }.assertFailsWith<TimeoutCancellationException>() @Test fun expectTimeout2() = runTest(timeout = 1.seconds) { launch { delay(2.seconds) } }.assertFailsWith<TimeoutCancellationException>() @Test fun expectFails1() = runTest { launch { delay(1.seconds) throw ExpectedException() } }.assertFailsWith<ExpectedException>() @Test fun expectFails2() = runTest { launch { fail("Expected failure") } }.assertFails() @Test fun expectFails3() = runApplicationTest(timeout = 1.seconds) { _, _ -> own(launch { throw ExpectedException() }) }.assertFailsWith<ExpectedException>() @Test fun expectFails4(): Promise<Unit> = runAsyncTest(2.seconds) { resolve, reject -> val innerPromise = runApplicationTest(timeout = 0.3.seconds) { _, _ -> own(launch { delay(1.seconds) println("SHOULD NOT") fail("Expected failure 2") }) }.assertFailsWith<TimeoutException>() innerPromise.then { resolve() } innerPromise.catch(reject) } @Test fun addToStage() = runTest { app { stage.addElement(testComponent()) +testComponent() assertEquals(2, dom.childElementCount) } } } private class TestComponent(owner: Context) : Div(owner) private inline fun Context.testComponent(init: ComponentInit<UiComponent> = {}): UiComponent = TestComponent(this).apply(init)
apache-2.0
13cc11f66ae84355a76595ed05580193
25.353535
126
0.741181
3.790698
false
true
false
false
android/architecture-components-samples
GithubBrowserSample/app/src/main/java/com/android/example/github/vo/Contributor.kt
1
1498
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.example.github.vo import androidx.room.Entity import androidx.room.ForeignKey import com.google.gson.annotations.SerializedName @Entity( primaryKeys = ["repoName", "repoOwner", "login"], foreignKeys = [ForeignKey( entity = Repo::class, parentColumns = ["name", "owner_login"], childColumns = ["repoName", "repoOwner"], onUpdate = ForeignKey.CASCADE, deferred = true )] ) data class Contributor( @field:SerializedName("login") val login: String, @field:SerializedName("contributions") val contributions: Int, @field:SerializedName("avatar_url") val avatarUrl: String? ) { // does not show up in the response but set in post processing. lateinit var repoName: String // does not show up in the response but set in post processing. lateinit var repoOwner: String }
apache-2.0
ffdd264d2e0e85a7fb684f28c53750c8
31.565217
75
0.704272
4.317003
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/insights/usecases/ViewsAndVisitorsMapper.kt
1
10343
package org.wordpress.android.ui.stats.refresh.lists.sections.insights.usecases import org.wordpress.android.R import org.wordpress.android.R.color import org.wordpress.android.R.string import org.wordpress.android.fluxc.model.stats.time.VisitsAndViewsModel.PeriodData import org.wordpress.android.fluxc.network.utils.StatsGranularity import org.wordpress.android.fluxc.network.utils.StatsGranularity.DAYS import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ChartLegendsBlue import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ChartLegendsPurple import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Chips import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Chips.Chip import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.LineChartItem import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.LineChartItem.Line import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Text import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Text.Clickable import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ValuesItem import org.wordpress.android.ui.stats.refresh.lists.sections.insights.usecases.ViewsAndVisitorsMapper.SelectedType.Views import org.wordpress.android.ui.stats.refresh.lists.sections.insights.usecases.ViewsAndVisitorsMapper.SelectedType.Visitors import org.wordpress.android.ui.stats.refresh.utils.ContentDescriptionHelper import org.wordpress.android.ui.stats.refresh.utils.MILLION import org.wordpress.android.ui.stats.refresh.utils.StatsDateFormatter import org.wordpress.android.ui.stats.refresh.utils.StatsUtils import org.wordpress.android.ui.utils.ListItemInteraction import org.wordpress.android.util.extensions.enforceWesternArabicNumerals import org.wordpress.android.viewmodel.ResourceProvider import javax.inject.Inject @Suppress("MagicNumber") class ViewsAndVisitorsMapper @Inject constructor( private val statsDateFormatter: StatsDateFormatter, private val resourceProvider: ResourceProvider, private val statsUtils: StatsUtils, private val contentDescriptionHelper: ContentDescriptionHelper ) { private val units = listOf( string.stats_views, string.stats_visitors ) enum class SelectedType(val value: Int) { Views(0), Visitors(1); companion object { fun valueOf(value: Int): SelectedType? = values().find { it.value == value } fun getColor(selectedType: Int): Int = when (selectedType) { 0 -> color.blue_50 else -> color.purple_50 } fun getFillDrawable(selectedType: Int): Int = when (selectedType) { 0 -> R.drawable.bg_rectangle_stats_line_chart_blue_gradient else -> R.drawable.bg_rectangle_stats_line_chart_purple_gradient } } } fun buildChartLegendsBlue() = ChartLegendsBlue( string.stats_timeframe_this_week, string.stats_timeframe_previous_week ) fun buildChartLegendsPurple() = ChartLegendsPurple( string.stats_timeframe_this_week, string.stats_timeframe_previous_week ) fun buildTitle( dates: List<PeriodData>, statsGranularity: StatsGranularity = DAYS, selectedItem: PeriodData, selectedPosition: Int, startValue: Int = MILLION ): ValuesItem { val (thisWeekCount, prevWeekCount) = mapDatesToWeeks(dates, selectedPosition) return ValuesItem( selectedItem = selectedPosition, value1 = statsUtils.toFormattedString(thisWeekCount, startValue), unit1 = units[selectedPosition], contentDescription1 = resourceProvider.getString( string.stats_overview_content_description, thisWeekCount, resourceProvider.getString(units[selectedPosition]), statsDateFormatter.printGranularDate(selectedItem.period, statsGranularity), "" ), value2 = statsUtils.toFormattedString(prevWeekCount, startValue), unit2 = units[selectedPosition], contentDescription2 = resourceProvider.getString( string.stats_overview_content_description, prevWeekCount, resourceProvider.getString(units[selectedPosition]), statsDateFormatter.printGranularDate(selectedItem.period, statsGranularity), "" ) ) } private fun PeriodData.getValue(selectedPosition: Int) = when (SelectedType.valueOf(selectedPosition)) { Views -> this.views Visitors -> this.visitors else -> 0L } @Suppress("LongParameterList") fun buildChart( dates: List<PeriodData>, statsGranularity: StatsGranularity, onLineSelected: (String?) -> Unit, onLineChartDrawn: (visibleBarCount: Int) -> Unit, selectedType: Int, selectedItemPeriod: String ): List<BlockListItem> { val chartItems = dates.map { val value = it.getValue(selectedType) val date = statsDateFormatter.parseStatsDate(statsGranularity, it.period) Line( statsDateFormatter.printDayWithoutYear(date).enforceWesternArabicNumerals() as String, it.period, value.toInt() ) } val result = mutableListOf<BlockListItem>() val entryType = when (SelectedType.valueOf(selectedType)) { Visitors -> string.stats_visitors else -> string.stats_views } val contentDescriptions = statsUtils.getLineChartEntryContentDescriptions( entryType, chartItems ) result.add( LineChartItem( selectedType = selectedType, entries = chartItems, selectedItemPeriod = selectedItemPeriod, onLineSelected = onLineSelected, onLineChartDrawn = onLineChartDrawn, entryContentDescriptions = contentDescriptions ) ) return result } fun buildInformation( dates: List<PeriodData>, selectedPosition: Int, navigationAction: (() -> Unit?)? = null ): Text { val (thisWeekCount, prevWeekCount) = mapDatesToWeeks(dates, selectedPosition) if (thisWeekCount <= 0 || prevWeekCount <= 0) { return Text( text = resourceProvider.getString( string.stats_insights_views_and_visitors_visitors_empty_state, EXTERNAL_LINK_ICON_TOKEN ), links = listOf( Clickable( icon = R.drawable.ic_external_white_24dp, navigationAction = ListItemInteraction.create( action = { navigationAction?.invoke() } ) ) ) ) } val positive = thisWeekCount >= prevWeekCount val change = statsUtils.buildChange(prevWeekCount, thisWeekCount, positive, true).toString() val stringRes = when (SelectedType.valueOf(selectedPosition)) { Views -> { when { positive -> string.stats_insights_views_and_visitors_views_positive else -> string.stats_insights_views_and_visitors_views_negative } } Visitors -> { when { positive -> string.stats_insights_views_and_visitors_visitors_positive else -> string.stats_insights_views_and_visitors_visitors_negative } } else -> string.stats_insights_views_and_visitors_views_positive } return Text( text = resourceProvider.getString(stringRes, change), color = when { positive -> mapOf(color.stats_color_positive to change) else -> mapOf(color.stats_color_negative to change) } ) } fun buildChips( onChipSelected: (position: Int) -> Unit, selectedPosition: Int ): Chips { return Chips( listOf( Chip( string.stats_views, contentDescriptionHelper.buildContentDescription( string.stats_views, 0 ) ), Chip( string.stats_visitors, contentDescriptionHelper.buildContentDescription( string.stats_visitors, 1 ) ) ), selectedPosition, onChipSelected ) } private fun mapDatesToWeeks(dates: List<PeriodData>, selectedPosition: Int): Pair<Long, Long> { val values = dates.map { val value = it.getValue(selectedPosition) value.toInt() } val hasData = values.isNotEmpty() && values.size >= 7 val prevWeekData = if (hasData) values.subList(0, 7) else values.subList(0, values.size) val thisWeekData = if (hasData) values.subList(7, values.size) else emptyList() val prevWeekCount = prevWeekData.fold(0L) { acc, next -> acc + next } val thisWeekCount = thisWeekData.fold(0L) { acc, next -> acc + next } return Pair(thisWeekCount, prevWeekCount) } companion object { const val EXTERNAL_LINK_ICON_TOKEN = "ICON" } }
gpl-2.0
6eb9f3ee7f370c9154573ef592a695e4
40.538153
123
0.597602
5.143212
false
false
false
false
hermantai/samples
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-13/code-to-copy/settings/SettingsFragment.kt
2
9590
package dev.mfazio.abl.settings import android.os.Bundle import android.util.Log import android.util.TypedValue import androidx.core.content.ContextCompat import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.preference.* import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.workDataOf import dev.mfazio.abl.R import dev.mfazio.abl.api.services.getDefaultABLService import dev.mfazio.abl.teams.UITeam import kotlinx.coroutines.launch class SettingsFragment : PreferenceFragmentCompat() { private lateinit var favoriteTeamPreference: DropDownPreference private lateinit var favoriteTeamColorPreference: SwitchPreferenceCompat private lateinit var startingScreenPreference: DropDownPreference private lateinit var usernamePreference: EditTextPreference override fun onCreatePreferences( savedInstanceState: Bundle?, rootKey: String? ) { val ctx = preferenceManager.context val screen = preferenceManager.createPreferenceScreen(ctx) this.usernamePreference = EditTextPreference(ctx).apply { key = usernamePreferenceKey title = getString(R.string.user_name) summaryProvider = EditTextPreference.SimpleSummaryProvider.getInstance() onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> loadSettings(newValue?.toString()) true } } screen.addPreference(usernamePreference) this.favoriteTeamPreference = DropDownPreference(ctx).apply { key = favoriteTeamPreferenceKey title = getString(R.string.favorite_team) entries = (listOf(getString(R.string.none)) + UITeam.allTeams.map { it.teamName }).toTypedArray() entryValues = (listOf("") + UITeam.allTeams.map { it.teamId }).toTypedArray() setDefaultValue("") summaryProvider = ListPreference.SimpleSummaryProvider.getInstance() } this.favoriteTeamColorPreference = SwitchPreferenceCompat(ctx).apply { key = favoriteTeamColorsPreferenceKey title = getString(R.string.team_color_nav_bar) setDefaultValue(false) } favoriteTeamPreference.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> val teamId = newValue?.toString() if (favoriteTeamColorPreference.isChecked) { setNavBarColorForTeam(teamId) } if (teamId != null) { favoriteTeamPreference.icon = getIconForTeam(teamId) } saveSettings(favoriteTeam = teamId) true } screen.addPreference(favoriteTeamPreference) favoriteTeamColorPreference.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> val useFavoriteTeamColor = newValue as? Boolean setNavBarColorForTeam( if (useFavoriteTeamColor == true) { favoriteTeamPreference.value } else null ) saveSettings(useFavoriteTeamColor = useFavoriteTeamColor) true } screen.addPreference(favoriteTeamColorPreference) this.startingScreenPreference = DropDownPreference(ctx).apply { key = startingScreenPreferenceKey title = getString(R.string.starting_location) entries = startingScreens.keys.toTypedArray() entryValues = startingScreens.keys.toTypedArray() summaryProvider = ListPreference.SimpleSummaryProvider.getInstance() setDefaultValue(R.id.scoreboardFragment.toString()) onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> saveSettings(startingScreen = newValue?.toString()) true } } screen.addPreference(startingScreenPreference) val aboutCategory = PreferenceCategory(ctx).apply { key = aboutPreferenceCategoryKey title = getString(R.string.about) } screen.addPreference(aboutCategory) val aboutTheAppPreference = Preference(ctx).apply { key = aboutTheAppPreferenceKey title = getString(R.string.about_the_app) summary = getString(R.string.info_about_the_app) onPreferenceClickListener = Preference.OnPreferenceClickListener { [email protected]().navigate( R.id.aboutTheAppFragment ) true } } aboutCategory.addPreference(aboutTheAppPreference) val creditsPreference = Preference(ctx).apply { key = creditsPreferenceKey title = getString(R.string.credits) summary = getString(R.string.image_credits) onPreferenceClickListener = Preference.OnPreferenceClickListener { [email protected]().navigate( R.id.imageCreditsFragment ) true } } aboutCategory.addPreference(creditsPreference) val notificationsPreference = Preference(ctx).apply { key = notificationsPreferenceKey title = "Notifications" summary = "Links to display push and local notifications" onPreferenceClickListener = Preference.OnPreferenceClickListener { [email protected]().navigate( R.id.notificationsFragment ) true } } aboutCategory.addPreference(notificationsPreference) preferenceScreen = screen } override fun onBindPreferences() { favoriteTeamPreference.icon = getIconForTeam(favoriteTeamPreference.value) } private fun getIconForTeam(teamId: String) = UITeam.fromTeamId(teamId)?.let { team -> ContextCompat.getDrawable(requireContext(), team.logoId) } private fun setNavBarColorForTeam(teamId: String?) { val color = UITeam.getTeamPalette(requireContext(), teamId) ?.dominantSwatch ?.rgb ?: getDefaultColor() activity?.window?.navigationBarColor = color } private fun getDefaultColor(): Int { val colorValue = TypedValue() activity?.theme?.resolveAttribute( R.attr.colorPrimary, colorValue, true ) return colorValue.data } private fun saveSettings( userName: String? = usernamePreference.text, favoriteTeam: String? = favoriteTeamPreference.value, useFavoriteTeamColor: Boolean? = favoriteTeamColorPreference.isChecked, startingScreen: String? = startingScreenPreference.value ) { if (userName != null) { WorkManager.getInstance(requireContext()).enqueue( OneTimeWorkRequestBuilder<SaveSettingsWorker>() .setInputData( workDataOf( SaveSettingsWorker.userNameKey to userName, SaveSettingsWorker.favoriteTeamKey to favoriteTeam, SaveSettingsWorker.favoriteTeamColorCheckKey to useFavoriteTeamColor, SaveSettingsWorker.startingScreenKey to startingScreen ) ).build() ) } } private fun loadSettings(userName: String? = null) { if (userName != null) { viewLifecycleOwner.lifecycleScope.launch { try { val apiResult = getDefaultABLService().getAppSettingsForUser(userName) with(favoriteTeamPreference) { value = apiResult.favoriteTeamId icon = getIconForTeam(apiResult.favoriteTeamId) } setNavBarColorForTeam( if (apiResult.useTeamColorNavBar) { apiResult.favoriteTeamId } else null ) favoriteTeamColorPreference.isChecked = apiResult.useTeamColorNavBar startingScreenPreference.value = apiResult.startingLocation } catch (ex: Exception) { Log.i( TAG, """Settings not found. |This may just mean they haven't been initialized yet. |""".trimMargin() ) saveSettings(userName) } } } } companion object { const val TAG = "SettingsFragment" const val aboutPreferenceCategoryKey = "aboutCategory" const val aboutTheAppPreferenceKey = "aboutTheApp" const val creditsPreferenceKey = "credits" const val favoriteTeamPreferenceKey = "favoriteTeam" const val favoriteTeamColorsPreferenceKey = "useFavoriteTeamColors" const val notificationsPreferenceKey = "notifications" const val startingScreenPreferenceKey = "startingScreen" const val usernamePreferenceKey = "username" } }
apache-2.0
3461a3e49c7792e912c0fb34b22b11f7
36.464844
103
0.611887
6.334214
false
false
false
false
csumissu/WeatherForecast
app/src/main/java/csumissu/weatherforecast/MainActivity.kt
1
2680
package csumissu.weatherforecast import android.Manifest import android.arch.lifecycle.Observer import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.Toolbar import csumissu.weatherforecast.common.BasePermissionsActivity import csumissu.weatherforecast.extensions.DelegatesExt import csumissu.weatherforecast.extensions.findFragmentByTag import csumissu.weatherforecast.extensions.showFragment import csumissu.weatherforecast.ui.forecasts.ForecastsFragment import csumissu.weatherforecast.util.LocationLiveData import dagger.android.DispatchingAndroidInjector import dagger.android.support.HasSupportFragmentInjector import org.jetbrains.anko.find import org.jetbrains.anko.info import javax.inject.Inject /** * @author yxsun * @since 01/06/2017 */ class MainActivity : BasePermissionsActivity(), HasSupportFragmentInjector { private val mToolbar by lazy { find<Toolbar>(R.id.toolbar) } private var mLocalityPref by DelegatesExt.preference<String>(this, PREF_LOCALITY) private var mCountryPref by DelegatesExt.preference<String>(this, PREF_COUNTRY) @Inject lateinit var mAndroidInjector: DispatchingAndroidInjector<Fragment> @Inject lateinit var mLocationLiveData: LocationLiveData override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(mToolbar) if (savedInstanceState == null) { showFragment(ForecastsFragment(), R.id.mContentView, TAG_FORECASTS) } } override fun supportFragmentInjector() = mAndroidInjector override fun requiredPermissions() = arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION) override fun onPermissionsResult(acquired: Boolean) { if (acquired) observeLocationChanges() else finish() } private fun observeLocationChanges() { mLocationLiveData.observe(this, Observer { coordinate -> coordinate?.let { info("new data ${it.latitude} ${it.longitude}") val fragment = findFragmentByTag<ForecastsFragment>(TAG_FORECASTS) fragment?.updateCoordinate(it) } }) mLocationLiveData.getAddress().observe(this, Observer { address -> address?.let { mLocalityPref = it.locality mCountryPref = it.countryName supportActionBar?.title = "$mLocalityPref / $mCountryPref" } }) } companion object { val PREF_LOCALITY = "locality" val PREF_COUNTRY = "country" val TAG_FORECASTS = "tag_forecasts" } }
mit
d7c622299fd01af29eb15bbca396a6fc
32.924051
92
0.720522
4.908425
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/kdoc/findKDoc.kt
4
5702
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.kdoc import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithSource import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.kdoc.parser.KDocKnownTag import org.jetbrains.kotlin.kdoc.psi.api.KDoc import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getChildOfType import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType import org.jetbrains.kotlin.psi.psiUtil.isPropertyParameter import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.util.capitalizeDecapitalize.toLowerCaseAsciiOnly data class KDocContent( val contentTag: KDocTag, val sections: List<KDocSection> ) fun DeclarationDescriptor.findKDoc( descriptorToPsi: (DeclarationDescriptorWithSource) -> PsiElement? = { DescriptorToSourceUtils.descriptorToDeclaration(it) } ): KDocContent? { if (this is DeclarationDescriptorWithSource) { val psiDeclaration = descriptorToPsi(this)?.navigationElement return (psiDeclaration as? KtElement)?.findKDoc(descriptorToPsi) } return null } private typealias DescriptorToPsi = (DeclarationDescriptorWithSource) -> PsiElement? fun KtElement.findKDoc(descriptorToPsi: DescriptorToPsi): KDocContent? { return findKDoc() ?: this.lookupInheritedKDoc(descriptorToPsi) } fun KtElement.findKDoc(): KDocContent? { return this.lookupOwnedKDoc() ?: this.lookupKDocInContainer() } private fun KtElement.lookupOwnedKDoc(): KDocContent? { // KDoc for primary constructor is located inside of its class KDoc val psiDeclaration = when (this) { is KtPrimaryConstructor -> getContainingClassOrObject() else -> this } if (psiDeclaration is KtDeclaration) { val kdoc = psiDeclaration.docComment if (kdoc != null) { if (this is KtConstructor<*>) { // ConstructorDescriptor resolves to the same JetDeclaration val constructorSection = kdoc.findSectionByTag(KDocKnownTag.CONSTRUCTOR) if (constructorSection != null) { // if annotated with @constructor tag and the caret is on constructor definition, // then show @constructor description as the main content, and additional sections // that contain @param tags (if any), as the most relatable ones // practical example: val foo = Fo<caret>o("argument") -- show @constructor and @param content val paramSections = kdoc.findSectionsContainingTag(KDocKnownTag.PARAM) return KDocContent(constructorSection, paramSections) } } return KDocContent(kdoc.getDefaultSection(), kdoc.getAllSections()) } } return null } /** * Looks for sections that have a deeply nested [tag], * as opposed to [KDoc.findSectionByTag], which only looks among the top level */ private fun KDoc.findSectionsContainingTag(tag: KDocKnownTag): List<KDocSection> { return getChildrenOfType<KDocSection>() .filter { it.findTagByName(tag.name.toLowerCaseAsciiOnly()) != null } } private fun KtElement.lookupKDocInContainer(): KDocContent? { val subjectName = name val containingDeclaration = PsiTreeUtil.findFirstParent(this, true) { it is KtDeclarationWithBody && it !is KtPrimaryConstructor || it is KtClassOrObject } val containerKDoc = containingDeclaration?.getChildOfType<KDoc>() if (containerKDoc == null || subjectName == null) return null val propertySection = containerKDoc.findSectionByTag(KDocKnownTag.PROPERTY, subjectName) val paramTag = containerKDoc.findDescendantOfType<KDocTag> { it.knownTag == KDocKnownTag.PARAM && it.getSubjectName() == subjectName } val primaryContent = when { // class Foo(val <caret>s: String) this is KtParameter && this.isPropertyParameter() -> propertySection ?: paramTag // fun some(<caret>f: String) || class Some<<caret>T: Base> || Foo(<caret>s = "argument") this is KtParameter || this is KtTypeParameter -> paramTag // if this property is declared separately (outside primary constructor), but it's for some reason // annotated as @property in class's description, instead of having its own KDoc this is KtProperty && containingDeclaration is KtClassOrObject -> propertySection else -> null } return primaryContent?.let { // makes little sense to include any other sections, since we found // documentation for a very specific element, like a property/param KDocContent(it, sections = emptyList()) } } private fun KtElement.lookupInheritedKDoc(descriptorToPsi: DescriptorToPsi): KDocContent? { if (this is KtCallableDeclaration) { val descriptor = this.resolveToDescriptorIfAny() as? CallableDescriptor ?: return null for (baseDescriptor in descriptor.overriddenDescriptors) { val baseKDoc = baseDescriptor.original.findKDoc(descriptorToPsi) if (baseKDoc != null) { return baseKDoc } } } return null }
apache-2.0
c4d4daf6517bc5b6f0482adc3fcea7b7
43.209302
138
0.714311
4.84452
false
false
false
false
jkennethcarino/AnkiEditor
app/src/main/java/com/jkcarino/ankieditor/ui/editor/LicensesDialogFragment.kt
1
1769
/* * Copyright (C) 2018 Jhon Kenneth Cariño * * 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.jkcarino.ankieditor.ui.editor import android.app.Dialog import android.os.Bundle import android.webkit.WebView import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import androidx.fragment.app.FragmentManager import com.jkcarino.ankieditor.R class LicensesDialogFragment : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val webView = WebView(activity) webView.loadUrl(LICENSES_HTML) return AlertDialog.Builder(activity!!).apply { setTitle(R.string.open_source_licenses) setView(webView) setPositiveButton(android.R.string.ok) { dialog, _ -> dialog.dismiss() } }.create() } override fun show(manager: FragmentManager, tag: String) { if (manager.findFragmentByTag(tag) == null) { super.show(manager, tag) } } companion object { const val DIALOG_TAG = "licenses-dialog" private const val LICENSES_HTML = "file:///android_asset/licenses.html" } }
gpl-3.0
fd41442a18dcde994b5b4dc38f8752fd
33.666667
84
0.709276
4.280872
false
false
false
false
charroch/Kevice
src/main/kotlin/adb/LogStream.kt
1
2407
package adb import org.vertx.java.core.Handler import org.vertx.java.core.buffer.Buffer import org.vertx.java.core.streams.ReadStream import java.util.concurrent.atomic.AtomicBoolean import com.android.ddmlib.log.LogReceiver.ILogListener import com.android.ddmlib.log.LogReceiver import com.android.ddmlib.log.EventLogParser import com.android.ddmlib.log.EventContainer.EventValueType class LogStream(val device: Device) : ILogListener, ReadStream<LogStream> { override fun newEntry(entry: LogReceiver.LogEntry?) { val els = EventLogParser() els.init(device) val a = els.parse(entry) if (a?.getType() == EventValueType.STRING) { println(" " + a?.getString()) } else if (a?.getType() == EventValueType.LIST) { (0..4).forEach { print(":" + a?.getValue(it)) } println("") } if (handler != null && entry != null) { val b = Buffer(entry.data) b.appendString("\n") handler?.handle(b) } } override fun newData(data: ByteArray?, offset: Int, length: Int) { // throw UnsupportedOperationException() } val paused: AtomicBoolean = AtomicBoolean(false) var handler: Handler<Buffer>? = null var exceptionHandler: Handler<Throwable>? = null override fun exceptionHandler(handler: Handler<Throwable>?): LogStream? { exceptionHandler = handler return this } override fun dataHandler(handler: Handler<Buffer>?): LogStream? { this.handler = handler; return this } override fun pause(): LogStream? { paused.set(true) return this } override fun resume(): LogStream? { paused.set(false) return this } override fun endHandler(endHandler: Handler<Void>?): LogStream? { throw UnsupportedOperationException() } // override fun addOutput(data: ByteArray?, offset: Int, length: Int) { // if (!isCancelled() && data != null && handler != null) { // val s = String(data, offset, length, "UTF-8") // val b = Buffer(s) // handler?.handle(b) // } // } // // override fun flush() { // pause(); // } // // override fun isCancelled(): Boolean { // return paused.get() // } }
apache-2.0
068e75682a38764464fb3569103c0f85
27.317647
78
0.585791
4.230228
false
false
false
false
ftomassetti/kolasu
emf/src/test/kotlin/com/strumenta/kolasu/emf/ModelTest.kt
1
15373
package com.strumenta.kolasu.emf import com.strumenta.kolasu.model.* import com.strumenta.kolasu.model.Statement import com.strumenta.kolasu.parsing.withParseTreeNode import com.strumenta.simplelang.SimpleLangLexer import com.strumenta.simplelang.SimpleLangParser import org.antlr.v4.runtime.CharStreams import org.antlr.v4.runtime.CommonTokenStream import org.eclipse.emf.common.util.EList import org.eclipse.emf.common.util.URI import org.eclipse.emf.ecore.EClass import org.eclipse.emf.ecore.EObject import org.eclipse.emf.ecore.resource.Resource import org.eclipse.emf.ecore.resource.impl.ResourceImpl import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl import org.eclipse.emfcloud.jackson.resource.JsonResourceFactory import org.junit.Test import java.io.File import java.time.LocalDateTime import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue data class NodeFoo(val name: String) : Node() class MyRoot(val foo: Int) : Node(), Statement class MySimpleLangCu() : Node() class ModelTest { @Test fun generateSimpleModel() { val cu = CompilationUnit( listOf( VarDeclaration(Visibility.PUBLIC, "a", StringLiteral("foo")), VarDeclaration(Visibility.PRIVATE, "b", StringLiteral("bar")), VarDeclaration(Visibility.PRIVATE, "c", LocalDateTimeLiteral(LocalDateTime.now())), ) ).withPosition(Position(Point(1, 0), Point(1, 1))) val nsURI = "https://strumenta.com/simplemm" val metamodelBuilder = MetamodelBuilder(packageName(CompilationUnit::class), nsURI, "simplemm") metamodelBuilder.provideClass(CompilationUnit::class) val ePackage = metamodelBuilder.generate() val eo = cu.toEObject(ePackage) assertEquals(nsURI, eo.eClass().ePackage.nsURI) eo.saveXMI(File("simplemodel.xmi")) val jsonFile = File("simplem.json") eo.saveAsJson(jsonFile) val resourceSet = ResourceSetImpl() resourceSet.resourceFactoryRegistry.extensionToFactoryMap["json"] = JsonResourceFactory() // TODO this is to correctly resolve the metamodel, however what would happen if there were // other references to https://... resources? resourceSet.resourceFactoryRegistry.protocolToFactoryMap["https"] = JsonResourceFactory() val kolasuURI = URI.createURI(STARLASU_METAMODEL.nsURI) val kolasuRes = resourceSet.createResource(kolasuURI) kolasuRes.contents.add(STARLASU_METAMODEL) val metaURI = URI.createURI(nsURI) val metaRes = resourceSet.createResource(metaURI) metaRes.contents.add(ePackage) val uri: URI = URI.createFileURI(jsonFile.absolutePath) val resource: Resource = resourceSet.createResource(uri) assertFalse(resource.isLoaded) resource.load(null) assertEquals(1, resource.contents.size) assertTrue(resource.contents[0] is EObject) val eObject = resource.contents[0] as EObject val cuClass = ePackage.eClassifiers.find { c -> c.name.equals("CompilationUnit") } as EClass assertEquals(cuClass, eObject.eClass()) val stmts = eObject.eGet(cuClass.getEStructuralFeature("statements")) as EList<*> assertEquals(3, stmts.size) } @Test fun nullCollection() { val cu = CompilationUnit(null) val nsURI = "https://strumenta.com/simplemm" val metamodelBuilder = MetamodelBuilder(packageName(CompilationUnit::class), nsURI, "simplemm") metamodelBuilder.provideClass(CompilationUnit::class) val ePackage = metamodelBuilder.generate() val eo = cu.toEObject(ePackage) assertEquals(nsURI, eo.eClass().ePackage.nsURI) eo.saveXMI(File("simplemodel_null.xmi")) val jsonFile = File("simplem_null.json") eo.saveAsJson(jsonFile) val resourceSet = ResourceSetImpl() resourceSet.resourceFactoryRegistry.extensionToFactoryMap["json"] = JsonResourceFactory() // TODO this is to correctly resolve the metamodel, however what would happen if there were // other references to https://... resources? resourceSet.resourceFactoryRegistry.protocolToFactoryMap["https"] = JsonResourceFactory() val metaURI = URI.createURI(nsURI) val metaRes = resourceSet.createResource(metaURI) metaRes.contents.add(ePackage) val uri: URI = URI.createFileURI(jsonFile.absolutePath) val resource: Resource = resourceSet.createResource(uri) assertFalse(resource.isLoaded) resource.load(null) assertEquals(1, resource.contents.size) assertTrue(resource.contents[0] is EObject) val eObject = resource.contents[0] as EObject val cuClass = ePackage.eClassifiers.find { c -> c.name.equals("CompilationUnit") } as EClass assertEquals(cuClass, eObject.eClass()) val stmts = eObject.eGet(cuClass.getEStructuralFeature("statements")) as EList<*> assertEquals(0, stmts.size) } @Test fun originIsSerialized() { val n1 = NodeFoo("abc") val n2 = NodeFoo("def").apply { origin = n1 } val ePackage = MetamodelBuilder("com.strumenta.kolasu.emf", "http://foo.com", "foo") .apply { provideClass(NodeFoo::class) }.generate() val mapping = KolasuToEMFMapping() val eo1 = n1.toEObject(ePackage, mapping) val eo2 = n2.toEObject(ePackage, mapping) assertEquals(null, eo1.eGet("origin")) assertEquals(true, eo2.eGet("origin") is EObject) assertEquals( "abc", ((eo2.eGet("origin") as EObject).eGet("node") as EObject) .eGet("name") ) } @Test fun destinationIsSerialized() { val n1 = NodeFoo("abc").apply { destination = TextFileDestination(Position(Point(1, 8), Point(7, 4))) } val ePackage = MetamodelBuilder("com.strumenta.kolasu.emf", "http://foo.com", "foo").apply { provideClass(NodeFoo::class) }.generate() val eo1 = n1.toEObject(ePackage) val eo2Destination = eo1.eGet("destination") assertEquals(true, eo2Destination is EObject) val eo2DestinationEO = eo2Destination as EObject assertEquals("TextFileDestination", eo2DestinationEO.eClass().name) val textFileDestinationPosition = eo2DestinationEO.eGet("position") as EObject assertEquals("Position", textFileDestinationPosition.eClass().name) assertEquals(true, textFileDestinationPosition.eGet("start") is EObject) val startEO = textFileDestinationPosition.eGet("start") as EObject assertEquals(true, textFileDestinationPosition.eGet("end") is EObject) val endEO = textFileDestinationPosition.eGet("end") as EObject assertEquals(1, startEO.eGet("line")) assertEquals(8, startEO.eGet("column")) assertEquals(7, endEO.eGet("line")) assertEquals(4, endEO.eGet("column")) } @Test fun statementIsConsideredCorrectlyInMetamodel() { val mmb = MetamodelBuilder("com.strumenta.kolasu.emf", "http://foo.com", "foo") mmb.provideClass(MyRoot::class) val ePackage = mmb.generate() assertEquals(1, ePackage.eClassifiers.size) val ec = ePackage.eClassifiers[0] as EClass assertEquals("MyRoot", ec.name) assertEquals(setOf("ASTNode", "Statement"), ec.eSuperTypes.map { it.name }.toSet()) } @Test fun statementIsSerializedCorrectly() { val mmb = MetamodelBuilder("com.strumenta.kolasu.emf", "http://foo.com", "foo") mmb.provideClass(MyRoot::class) val ePackage = mmb.generate() val res = ResourceImpl() res.contents.add(ePackage) val r1 = MyRoot(124) val eo1 = r1.toEObject(res) println(eo1.eClass().eSuperTypes) assertEquals(setOf("ASTNode", "Statement"), eo1.eClass().eSuperTypes.map { it.name }.toSet()) } @Test fun cyclicReferenceByNameOnSingleReference() { val metamodelBuilder = MetamodelBuilder( "com.strumenta.kolasu.emf", "https://strumenta.com/simplemm", "simplemm" ) metamodelBuilder.provideClass(NodeWithReference::class) val ePackage = metamodelBuilder.generate() val res = ResourceImpl() res.contents.add(ePackage) val r1 = NodeWithReference("foo", ReferenceByName("foo"), mutableListOf()) r1.singlePointer.referred = r1 val eo1 = r1.toEObject(res) val reference = eo1.eGet("singlePointer") as EObject assertEquals(STARLASU_METAMODEL.getEClassifier("ReferenceByName"), reference.eClass()) assertEquals(eo1, reference.eGet("referenced")) assertEquals( """{ "eClass" : "#//NodeWithReference", "name" : "foo", "singlePointer" : { "name" : "foo", "referenced" : { "eClass" : "#//NodeWithReference", "${'$'}ref" : "/" } } }""", eo1.saveAsJson() ) } @Test fun cyclicReferenceByNameOnMultipleReference() { val metamodelBuilder = MetamodelBuilder( "com.strumenta.kolasu.emf", "https://strumenta.com/simplemm", "simplemm" ) metamodelBuilder.provideClass(NodeWithReference::class) val ePackage = metamodelBuilder.generate() val res = ResourceImpl() res.contents.add(ePackage) val r1 = NodeWithReference("foo", ReferenceByName("foo"), mutableListOf()) r1.pointers.add(ReferenceByName("a", r1)) r1.pointers.add(ReferenceByName("b", r1)) r1.pointers.add(ReferenceByName("c", r1)) val eo1 = r1.toEObject(res) val pointers = eo1.eGet("pointers") as EList<*> assertEquals(3, pointers.size) assertEquals(STARLASU_METAMODEL.getEClassifier("ReferenceByName"), (pointers[0] as EObject).eClass()) assertEquals("a", (pointers[0] as EObject).eGet("name")) assertEquals(eo1, (pointers[0] as EObject).eGet("referenced")) assertEquals(STARLASU_METAMODEL.getEClassifier("ReferenceByName"), (pointers[1] as EObject).eClass()) assertEquals("b", (pointers[1] as EObject).eGet("name")) assertEquals(eo1, (pointers[1] as EObject).eGet("referenced")) assertEquals(STARLASU_METAMODEL.getEClassifier("ReferenceByName"), (pointers[2] as EObject).eClass()) assertEquals("c", (pointers[2] as EObject).eGet("name")) assertEquals(eo1, (pointers[2] as EObject).eGet("referenced")) assertEquals( """{ "eClass" : "#//NodeWithReference", "name" : "foo", "pointers" : [ { "name" : "a", "referenced" : { "eClass" : "#//NodeWithReference", "${'$'}ref" : "/" } }, { "name" : "b", "referenced" : { "eClass" : "#//NodeWithReference", "${'$'}ref" : "/" } }, { "name" : "c", "referenced" : { "eClass" : "#//NodeWithReference", "${'$'}ref" : "/" } } ], "singlePointer" : { "name" : "foo" } }""", eo1.saveAsJson() ) } @Test fun forwardAndBackwardReferences() { val metamodelBuilder = MetamodelBuilder( "com.strumenta.kolasu.emf", "https://strumenta.com/simplemm", "simplemm" ) metamodelBuilder.provideClass(NodeWithForwardReference::class) val ePackage = metamodelBuilder.generate() val res = ResourceImpl() res.contents.add(ePackage) val a = NodeWithForwardReference("a", mutableListOf()) val b = NodeWithForwardReference("b", mutableListOf()) val c = NodeWithForwardReference("c", mutableListOf()) val d = NodeWithForwardReference("d", mutableListOf()) val e = NodeWithForwardReference("e", mutableListOf()) a.myChildren.add(b) a.myChildren.add(c) b.myChildren.add(d) d.myChildren.add(e) a.pointer = ReferenceByName("e", e) e.pointer = ReferenceByName("a", a) b.pointer = ReferenceByName("c", c) c.pointer = ReferenceByName("d", d) d.pointer = ReferenceByName("b", b) val eoA = a.toEObject(res) assertEquals( """{ "eClass" : "#//NodeWithForwardReference", "name" : "a", "myChildren" : [ { "name" : "b", "myChildren" : [ { "name" : "d", "myChildren" : [ { "name" : "e", "pointer" : { "name" : "a", "referenced" : { "eClass" : "#//NodeWithForwardReference", "${'$'}ref" : "/" } } } ], "pointer" : { "name" : "b", "referenced" : { "eClass" : "#//NodeWithForwardReference", "${'$'}ref" : "//@myChildren.0" } } } ], "pointer" : { "name" : "c", "referenced" : { "eClass" : "#//NodeWithForwardReference", "${'$'}ref" : "//@myChildren.1" } } }, { "name" : "c", "pointer" : { "name" : "d", "referenced" : { "eClass" : "#//NodeWithForwardReference", "${'$'}ref" : "//@myChildren.0/@myChildren.0" } } } ], "pointer" : { "name" : "e", "referenced" : { "eClass" : "#//NodeWithForwardReference", "${'$'}ref" : "//@myChildren.0/@myChildren.0/@myChildren.0" } } }""", eoA.saveAsJson() ) } @Test fun saveToJSONWithParseTreeOrigin() { // We verify the ParseTreeOrigin is not saved, but the position is val pt = SimpleLangParser(CommonTokenStream(SimpleLangLexer(CharStreams.fromString("input A is string")))) .compilationUnit() val ast = MySimpleLangCu().withParseTreeNode(pt) val metamodelBuilder = MetamodelBuilder( "com.strumenta.kolasu.emf", "https://strumenta.com/simplemm", "simplemm" ) metamodelBuilder.provideClass(MySimpleLangCu::class) val ePackage = metamodelBuilder.generate() val res = ResourceImpl() res.contents.add(ePackage) val eo = ast.toEObject(res) assertEquals( """{ "eClass" : "#//MySimpleLangCu", "position" : { "start" : { "line" : 1 }, "end" : { "line" : 1, "column" : 17 } } }""", eo.saveAsJson() ) } @Test fun saveToJSONNodeOrigin() { val someOtherNode = MyRoot(123) val ast = MySimpleLangCu().withOrigin(someOtherNode) val metamodelBuilder = MetamodelBuilder( "com.strumenta.kolasu.emf", "https://strumenta.com/simplemm", "simplemm" ) metamodelBuilder.provideClass(MySimpleLangCu::class) metamodelBuilder.provideClass(MyRoot::class) val ePackage = metamodelBuilder.generate() val res = ResourceImpl() res.contents.add(ePackage) val mapping = KolasuToEMFMapping() val eo1 = someOtherNode.toEObject(res, mapping) val eo2 = ast.toEObject(res, mapping) assertEquals( """{ "eClass" : "#//MySimpleLangCu", "origin" : { "eClass" : "https://strumenta.com/starlasu/v2#//NodeOrigin", "node" : { "eClass" : "#//MyRoot", "${'$'}ref" : "#//" } } }""", eo2.saveAsJson() ) } }
apache-2.0
0f8906d51a4ace601cdc2c4725ae42b8
34.834499
114
0.617511
3.807083
false
false
false
false
carrotengineer/Warren
src/main/kotlin/engineer/carrot/warren/warren/handler/TopicHandler.kt
2
1013
package engineer.carrot.warren.warren.handler import engineer.carrot.warren.kale.IKaleHandler import engineer.carrot.warren.kale.irc.message.rfc1459.TopicMessage import engineer.carrot.warren.warren.loggerFor import engineer.carrot.warren.warren.state.CaseMappingState import engineer.carrot.warren.warren.state.JoinedChannelsState class TopicHandler(val channelsState: JoinedChannelsState, val caseMappingState: CaseMappingState) : IKaleHandler<TopicMessage> { private val LOGGER = loggerFor<TopicHandler>() override val messageType = TopicMessage::class.java override fun handle(message: TopicMessage, tags: Map<String, String?>) { val channel = channelsState[message.channel] val topic = message.topic if (channel == null) { LOGGER.warn("got a topic for a channel we don't think we're in, not doing anything: $message") return } LOGGER.debug("channel topic for ${channel.name}: $topic") channel.topic = topic } }
isc
28f2d854e8a97614e7f875153ecf7751
33.931034
129
0.732478
4.423581
false
false
false
false
marius-m/wt4
app/src/main/java/lt/markmerkk/widgets/edit/LogDetailsPresenterUpdateActiveClock.kt
1
3538
package lt.markmerkk.widgets.edit import lt.markmerkk.ActiveDisplayRepository import lt.markmerkk.Const import lt.markmerkk.TicketStorage import lt.markmerkk.TimeProvider import lt.markmerkk.UserSettings import lt.markmerkk.ViewProvider import lt.markmerkk.WTEventBus import lt.markmerkk.WorklogStorage import lt.markmerkk.entities.Log import lt.markmerkk.entities.TicketCode import lt.markmerkk.entities.TimeGap import lt.markmerkk.events.EventMainOpenTickets import lt.markmerkk.interactors.ActiveLogPersistence import lt.markmerkk.mvp.LogEditService2 import lt.markmerkk.mvp.LogEditService2Impl import lt.markmerkk.utils.hourglass.HourGlass class LogDetailsPresenterUpdateActiveClock( private val viewProvider: ViewProvider<LogDetailsContract.View>, private val eventBus: WTEventBus, private val timeProvider: TimeProvider, private val hourGlass: HourGlass, private val activeLogPersistence: ActiveLogPersistence, private val ticketStorage: TicketStorage, private val activeDisplayRepository: ActiveDisplayRepository, private val userSettings: UserSettings, ) : LogDetailsContract.Presenter { private val logEditService: LogEditService2 = LogEditService2Impl( timeProvider = timeProvider, ticketStorage = ticketStorage, activeDisplayRepository = activeDisplayRepository, listener = object : LogEditService2.Listener { override fun showDateTimeChange(timeGap: TimeGap) { hourGlass.changeStart(timeGap.start) viewProvider.invoke { this.showDateTime(timeGap.start, timeGap.end) } } override fun showDuration(durationAsString: String) { viewProvider.invoke { this.showHint1(durationAsString) } } override fun showComment(comment: String) { viewProvider.invoke { this.showComment(comment) } } override fun showCode(ticketCode: TicketCode) { viewProvider.invoke { this.showTicketCode(ticketCode.code) } } override fun showSuccess(log: Log) { if (userSettings.settingsAutoStartClock) { hourGlass.startFrom(log.time.end) } else { hourGlass.stop() } activeLogPersistence.reset() viewProvider.invoke { this.closeDetails() } } } ) override fun onAttach() { val log = Log.new( timeProvider = timeProvider, start = hourGlass.start.millis, end = hourGlass.end.millis, code = activeLogPersistence.ticketCode.code, comment = activeLogPersistence.comment, systemNote = "", author = "", remoteData = null ) logEditService.initWithLog(log) viewProvider.invoke { this.initView("Active clock") } } override fun onDetach() { } override fun save() { logEditService.saveEntity() } override fun changeDateTime(timeGap: TimeGap) { logEditService.updateDateTime(timeGap) } override fun openFindTickets() { eventBus.post(EventMainOpenTickets()) } override fun changeTicketCode(ticket: String) { activeLogPersistence.changeTicketCode(ticket) logEditService.updateCode(ticket) } override fun changeComment(comment: String) { activeLogPersistence.changeComment(comment) logEditService.updateComment(comment) } }
apache-2.0
20a188a2e1e89784468e7600e57f070b
32.704762
85
0.674392
4.826739
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/TrackTypeMapping.kt
2
4276
package eu.kanade.tachiyomi.data.database.mappers import android.database.Cursor import androidx.core.content.contentValuesOf import com.pushtorefresh.storio.sqlite.SQLiteTypeMapping import com.pushtorefresh.storio.sqlite.operations.delete.DefaultDeleteResolver import com.pushtorefresh.storio.sqlite.operations.get.DefaultGetResolver import com.pushtorefresh.storio.sqlite.operations.put.DefaultPutResolver import com.pushtorefresh.storio.sqlite.queries.DeleteQuery import com.pushtorefresh.storio.sqlite.queries.InsertQuery import com.pushtorefresh.storio.sqlite.queries.UpdateQuery import eu.kanade.tachiyomi.data.database.models.Track import eu.kanade.tachiyomi.data.database.models.TrackImpl import eu.kanade.tachiyomi.data.database.tables.TrackTable.COL_FINISH_DATE import eu.kanade.tachiyomi.data.database.tables.TrackTable.COL_ID import eu.kanade.tachiyomi.data.database.tables.TrackTable.COL_LAST_CHAPTER_READ import eu.kanade.tachiyomi.data.database.tables.TrackTable.COL_LIBRARY_ID import eu.kanade.tachiyomi.data.database.tables.TrackTable.COL_MANGA_ID import eu.kanade.tachiyomi.data.database.tables.TrackTable.COL_MEDIA_ID import eu.kanade.tachiyomi.data.database.tables.TrackTable.COL_SCORE import eu.kanade.tachiyomi.data.database.tables.TrackTable.COL_START_DATE import eu.kanade.tachiyomi.data.database.tables.TrackTable.COL_STATUS import eu.kanade.tachiyomi.data.database.tables.TrackTable.COL_SYNC_ID import eu.kanade.tachiyomi.data.database.tables.TrackTable.COL_TITLE import eu.kanade.tachiyomi.data.database.tables.TrackTable.COL_TOTAL_CHAPTERS import eu.kanade.tachiyomi.data.database.tables.TrackTable.COL_TRACKING_URL import eu.kanade.tachiyomi.data.database.tables.TrackTable.TABLE class TrackTypeMapping : SQLiteTypeMapping<Track>( TrackPutResolver(), TrackGetResolver(), TrackDeleteResolver() ) class TrackPutResolver : DefaultPutResolver<Track>() { override fun mapToInsertQuery(obj: Track) = InsertQuery.builder() .table(TABLE) .build() override fun mapToUpdateQuery(obj: Track) = UpdateQuery.builder() .table(TABLE) .where("$COL_ID = ?") .whereArgs(obj.id) .build() override fun mapToContentValues(obj: Track) = contentValuesOf( COL_ID to obj.id, COL_MANGA_ID to obj.manga_id, COL_SYNC_ID to obj.sync_id, COL_MEDIA_ID to obj.media_id, COL_LIBRARY_ID to obj.library_id, COL_TITLE to obj.title, COL_LAST_CHAPTER_READ to obj.last_chapter_read, COL_TOTAL_CHAPTERS to obj.total_chapters, COL_STATUS to obj.status, COL_TRACKING_URL to obj.tracking_url, COL_SCORE to obj.score, COL_START_DATE to obj.started_reading_date, COL_FINISH_DATE to obj.finished_reading_date ) } class TrackGetResolver : DefaultGetResolver<Track>() { override fun mapFromCursor(cursor: Cursor): Track = TrackImpl().apply { id = cursor.getLong(cursor.getColumnIndexOrThrow(COL_ID)) manga_id = cursor.getLong(cursor.getColumnIndexOrThrow(COL_MANGA_ID)) sync_id = cursor.getInt(cursor.getColumnIndexOrThrow(COL_SYNC_ID)) media_id = cursor.getInt(cursor.getColumnIndexOrThrow(COL_MEDIA_ID)) library_id = cursor.getLong(cursor.getColumnIndexOrThrow(COL_LIBRARY_ID)) title = cursor.getString(cursor.getColumnIndexOrThrow(COL_TITLE)) last_chapter_read = cursor.getFloat(cursor.getColumnIndexOrThrow(COL_LAST_CHAPTER_READ)) total_chapters = cursor.getInt(cursor.getColumnIndexOrThrow(COL_TOTAL_CHAPTERS)) status = cursor.getInt(cursor.getColumnIndexOrThrow(COL_STATUS)) score = cursor.getFloat(cursor.getColumnIndexOrThrow(COL_SCORE)) tracking_url = cursor.getString(cursor.getColumnIndexOrThrow(COL_TRACKING_URL)) started_reading_date = cursor.getLong(cursor.getColumnIndexOrThrow(COL_START_DATE)) finished_reading_date = cursor.getLong(cursor.getColumnIndexOrThrow(COL_FINISH_DATE)) } } class TrackDeleteResolver : DefaultDeleteResolver<Track>() { override fun mapToDeleteQuery(obj: Track) = DeleteQuery.builder() .table(TABLE) .where("$COL_ID = ?") .whereArgs(obj.id) .build() }
apache-2.0
092dbe745e53710f766dd7b5b10d7ad3
45.989011
96
0.74579
3.973978
false
false
false
false
jovr/imgui
core/src/main/kotlin/imgui/windowsIme/imm.kt
2
5677
package imgui.windowsIme import glm_.BYTES import glm_.L import imgui.MINECRAFT_BEHAVIORS import kool.BYTES import org.lwjgl.system.* import org.lwjgl.system.MemoryUtil.memGetLong import org.lwjgl.system.MemoryUtil.memPutLong import org.lwjgl.system.windows.WindowsLibrary import uno.glfw.HWND import java.nio.ByteBuffer object imm { val lib: SharedLibrary = WindowsLibrary("Imm32") val ImmCreateContext = lib.getFunctionAddress("ImmCreateContext") val ImmGetContext = lib.getFunctionAddress("ImmGetContext") val ImmSetCompositionWindow = lib.getFunctionAddress("ImmSetCompositionWindow") val ImmReleaseContext = lib.getFunctionAddress("ImmReleaseContext") fun getContext(hwnd: HWND): Long{ return if(Platform.get() == Platform.WINDOWS && MINECRAFT_BEHAVIORS) { JNI.callP(ImmCreateContext) } else { JNI.callPP(hwnd.L, ImmGetContext) } } fun setCompositionWindow(himc: HIMC, compForm: COMPOSITIONFORM) = JNI.callPPI(himc.L, compForm.adr, ImmSetCompositionWindow) fun releaseContext(hwnd: HWND, himc: HIMC) = JNI.callPPI(hwnd.L, himc.L, ImmReleaseContext) // bit field for IMC_SETCOMPOSITIONWINDOW, IMC_SETCANDIDATEWINDOW val CFS_DEFAULT = 0x0000 val CFS_RECT = 0x0001 val CFS_POINT = 0x0002 val CFS_FORCE_POSITION = 0x0020 val CFS_CANDIDATEPOS = 0x0040 val CFS_EXCLUDE = 0x0080 } // TODO -> uno inline class HIMC(val L: Long) inline class DWORD(val L: Long) { companion object { val BYTES get() = Long.BYTES } } /** * typedef struct tagCANDIDATEFORM { * DWORD dwIndex; * DWORD dwStyle; * POINT ptCurrentPos; * RECT rcArea; * } CANDIDATEFORM, *PCANDIDATEFORM; */ class CANDIDATEFORM constructor(val adr: Long) { val buffer: ByteBuffer = MemoryUtil.memByteBuffer(adr, size) var dwIndex: DWORD get() = DWORD(memGetLong(adr + ofs.dwIndex)) set(value) = memPutLong(adr + ofs.dwIndex, value.L) var dwStyle: DWORD get() = DWORD(memGetLong(adr + ofs.dwStyle)) set(value) = memPutLong(adr + ofs.dwStyle, value.L) var ptCurrentPos: POINT get() = POINT(adr + ofs.ptCurrentPos) set(value) = value.to(adr + ofs.ptCurrentPos) var rcArea: RECT get() = RECT(adr + ofs.rcArea) set(value) = value.to(adr + ofs.rcArea) companion object { val size = 2 * Int.BYTES + POINT.size + RECT.size } object ofs { val dwIndex = 0 val dwStyle = dwIndex + DWORD.BYTES val ptCurrentPos = dwStyle + DWORD.BYTES val rcArea = ptCurrentPos + POINT.size } } /** * typedef struct tagCOMPOSITIONFORM { * DWORD dwStyle; * POINT ptCurrentPos; * RECT rcArea; * } COMPOSITIONFORM */ class COMPOSITIONFORM constructor(val adr: Long) { val buffer: ByteBuffer = MemoryUtil.memByteBuffer(adr, size) constructor() : this(MemoryUtil.nmemAlloc(size.L)) var dwStyle: DWORD get() = DWORD(memGetLong(adr + ofs.dwStyle)) set(value) = memPutLong(adr + ofs.dwStyle, value.L) var ptCurrentPos: POINT get() = POINT(adr + ofs.ptCurrentPos) set(value) = value.to(adr + ofs.ptCurrentPos) var rcArea: RECT get() = RECT(adr + ofs.rcArea) set(value) = value.to(adr + ofs.rcArea) fun free() = MemoryUtil.nmemFree(adr) companion object { val size = 2 * Int.BYTES + POINT.size + RECT.size } object ofs { val dwStyle = 0 val ptCurrentPos = dwStyle + POINT.size val rcArea = ptCurrentPos + RECT.size } } /** typedef struct tagPOINT { * LONG x; * LONG y; * } POINT, *PPOINT; */ class POINT constructor(val adr: Long) { val buffer: ByteBuffer = MemoryUtil.memByteBuffer(adr, size) var x: Long get() = MemoryUtil.memGetLong(adr + ofs.x) set(value) = MemoryUtil.memPutLong(adr + ofs.x, value) var y: Long get() = MemoryUtil.memGetLong(adr + ofs.y) set(value) = MemoryUtil.memPutLong(adr + ofs.y, value) constructor() : this(MemoryUtil.nmemAlloc(size.L)) fun to(adr: Long) { MemoryUtil.memPutLong(adr + ofs.x, x) MemoryUtil.memPutLong(adr + ofs.y, y) } companion object { val size = 2 * Long.BYTES } object ofs { val x = 0 val y = x + Long.BYTES } } /** * typedef struct _RECT { * LONG left; * LONG top; * LONG right; * LONG bottom; * } RECT, *PRECT; */ class RECT(val adr: Long) { val buffer: ByteBuffer = MemoryUtil.memByteBuffer(adr, size) var left: Long get() = MemoryUtil.memGetLong(adr + ofs.left) set(value) = MemoryUtil.memPutLong(adr + ofs.left, value) var top: Long get() = MemoryUtil.memGetLong(adr + ofs.top) set(value) = MemoryUtil.memPutLong(adr + ofs.top, value) var right: Long get() = MemoryUtil.memGetLong(adr + ofs.right) set(value) = MemoryUtil.memPutLong(adr + ofs.right, value) var bottom: Long get() = MemoryUtil.memGetLong(adr + ofs.bottom) set(value) = MemoryUtil.memPutLong(adr + ofs.bottom, value) constructor() : this(MemoryUtil.nmemAlloc(size.L)) fun to(adr: Long) { MemoryUtil.memPutLong(adr + ofs.left, left) MemoryUtil.memPutLong(adr + ofs.top, top) MemoryUtil.memPutLong(adr + ofs.right, right) MemoryUtil.memPutLong(adr + ofs.bottom, bottom) } companion object { val size = 4 * Long.BYTES } object ofs { val left = 0 val top = left + Long.BYTES val right = top + Long.BYTES val bottom = right + Long.BYTES } }
mit
b377bc1312269b73b512ea875561c82d
26.293269
128
0.633609
3.296748
false
false
false
false