content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package ftl.client.google import com.google.testing.model.IosDeviceCatalog import com.google.testing.model.IosModel import com.google.testing.model.Orientation import ftl.config.Device import ftl.environment.getLocaleDescription import ftl.environment.ios.getDescription import ftl.environment.ios.iosVersionsToCliTable import ftl.http.executeWithRetry /** * Validates iOS device model and version * * note: 500 Internal Server Error is returned on invalid model id/version **/ object IosCatalog { private val catalogMap: MutableMap<String, IosDeviceCatalog> = mutableMapOf() private val xcodeMap: MutableMap<String, List<String>> = mutableMapOf() fun getModels(projectId: String): List<IosModel> = iosDeviceCatalog(projectId).models.orEmpty() fun softwareVersionsAsTable(projectId: String) = getVersionsList(projectId).iosVersionsToCliTable() fun describeSoftwareVersion(projectId: String, versionId: String) = getVersionsList(projectId).getDescription(versionId) private fun getVersionsList(projectId: String) = iosDeviceCatalog(projectId).versions private fun getLocaleDescription(projectId: String, locale: String) = getLocales(projectId).getLocaleDescription(locale) internal fun getLocales(projectId: String) = iosDeviceCatalog(projectId).runtimeConfiguration.locales fun supportedOrientations(projectId: String): List<Orientation> = iosDeviceCatalog(projectId).runtimeConfiguration.orientations fun supportedXcode(version: String, projectId: String) = xcodeVersions(projectId).contains(version) private fun xcodeVersions(projectId: String) = xcodeMap.getOrPut(projectId) { iosDeviceCatalog(projectId).xcodeVersions.map { it.version } } fun Device.getSupportedVersionId(projectId: String): List<String> = iosDeviceCatalog(projectId).models.find { it.id == model }?.supportedVersionIds ?: emptyList() // Device catalogMap is different depending on the project id private fun iosDeviceCatalog( projectId: String ) = try { catalogMap.getOrPut(projectId) { GcTesting.get.testEnvironmentCatalog() .get("ios") .setProjectId(projectId) .executeWithRetry() .iosDeviceCatalog .filterDevicesWithoutSupportedVersions() } } catch (e: java.lang.Exception) { throw java.lang.RuntimeException(e) } private fun IosDeviceCatalog.filterDevicesWithoutSupportedVersions() = setModels(models.filterNotNull().filter { it.supportedVersionIds?.isNotEmpty() ?: false }) }
test_runner/src/main/kotlin/ftl/client/google/IosCatalog.kt
281751961
package com.kickstarter.viewmodels import android.content.Intent import com.kickstarter.KSRobolectricTestCase import com.kickstarter.mock.factories.ProjectFactory import com.kickstarter.models.Project import com.kickstarter.ui.IntentKey import org.junit.Test import rx.observers.TestSubscriber class ProjectSocialViewModelTest : KSRobolectricTestCase() { private val project = TestSubscriber<Project>() @Test fun testProjectInit() { val project = ProjectFactory.project() val intent = Intent().apply { putExtra(IntentKey.PROJECT, project) } val vm = ProjectSocialViewModel.ViewModel(environment()) .also { it.intent(intent) } vm.outputs.project().subscribe(this.project) this.project.assertValue(project) } }
app/src/test/java/com/kickstarter/viewmodels/ProjectSocialViewModelTest.kt
2347965058
// 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.warmup import com.intellij.ide.startup.ServiceNotReadyException import com.intellij.openapi.progress.impl.CoreProgressManager import com.intellij.util.indexing.FileBasedIndex import com.intellij.util.indexing.FileBasedIndexEx import com.intellij.warmup.util.ConsoleLog import com.intellij.warmup.util.runTaskAndLogTime import kotlinx.coroutines.time.delay import java.time.Duration import kotlin.system.exitProcess suspend fun waitIndexInitialization() { val deferred = (FileBasedIndex.getInstance() as FileBasedIndexEx).untilIndicesAreInitialized() ?: throw ServiceNotReadyException() deferred.join() } suspend fun waitUntilProgressTasksAreFinishedOrFail() { try { waitUntilProgressTasksAreFinished() } catch (e: IllegalStateException) { ConsoleLog.info(e.message ?: e.toString()) exitProcess(2) } } private suspend fun waitUntilProgressTasksAreFinished() { runTaskAndLogTime("Awaiting for progress tasks") { val timeout = System.getProperty("ide.progress.tasks.awaiting.timeout.min", "60").toLongOrNull() ?: 60 val startTime = System.currentTimeMillis() while (CoreProgressManager.getCurrentIndicators().isNotEmpty()) { if (System.currentTimeMillis() - startTime > Duration.ofMinutes(timeout).toMillis()) { val timeoutMessage = StringBuilder("Progress tasks awaiting timeout.\n") timeoutMessage.appendLine("Not finished tasks:") for (indicator in CoreProgressManager.getCurrentIndicators()) { timeoutMessage.appendLine(" - ${indicator.text}") } error(timeoutMessage) } delay(Duration.ofMillis(1000)) } } }
platform/warmup/src/com/intellij/warmup/warmupUtils.kt
3310655991
fun main(args: Array<String>) { qualifier somethingElse() }
plugins/kotlin/j2k/new/tests/testData/copyPaste/OnlyQualifier.expected.kt
1560854060
fun a() { (fun(i: Int) { })(<caret>) } // SET_TRUE: ALIGN_MULTILINE_METHOD_BRACKETS // IGNORE_FORMATTER
plugins/kotlin/idea/tests/testData/indentationOnNewline/emptyParameters/EmptyArgumentInCallByDeclaration2.kt
256938106
package com.replaymod.replay.gui.overlay import com.replaymod.core.ReplayMod import com.replaymod.core.gui.common.UITexture import gg.essential.elementa.components.UIContainer import gg.essential.elementa.constraints.CenterConstraint import gg.essential.elementa.constraints.SiblingConstraint import gg.essential.elementa.dsl.childOf import gg.essential.elementa.dsl.constrain import gg.essential.elementa.dsl.pixels import gg.essential.elementa.dsl.provideDelegate class UIStatusIndicator(u: Int, v: Int) : UIContainer() { val icon by UITexture(ReplayMod.TEXTURE, UITexture.TextureData.ofSize(16, 16).offset(u, v)).constrain { x = CenterConstraint() y = CenterConstraint() width = 16.pixels height = 16.pixels } childOf this init { constrain { x = SiblingConstraint(4f) y = 0.pixels(alignOpposite = true) width = 20.pixels height = 20.pixels } } }
src/main/kotlin/com/replaymod/replay/gui/overlay/UIStatusIndicator.kt
3186233648
// 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.scratch.compile import com.intellij.execution.configurations.JavaCommandLineState import com.intellij.execution.process.CapturingProcessHandler import com.intellij.execution.target.TargetEnvironmentRequest import com.intellij.execution.target.TargetProgressIndicatorAdapter import com.intellij.execution.target.TargetedCommandLine import com.intellij.execution.target.local.LocalTargetEnvironmentRequest import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.util.Computable import com.intellij.openapi.util.io.FileUtil import org.jetbrains.kotlin.idea.KotlinJvmBundle import org.jetbrains.kotlin.idea.core.KotlinCompilerIde import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager import org.jetbrains.kotlin.idea.scratch.LOG import org.jetbrains.kotlin.idea.scratch.ScratchExpression import org.jetbrains.kotlin.idea.scratch.ScratchFile import org.jetbrains.kotlin.idea.scratch.compile.KtScratchSourceFileProcessor.Result import org.jetbrains.kotlin.idea.scratch.printDebugMessage import org.jetbrains.kotlin.idea.util.JavaParametersBuilder import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import java.io.File class KtScratchExecutionSession( private val file: ScratchFile, private val executor: KtCompilingExecutor ) { companion object { private const val TIMEOUT_MS = 30000 } @Volatile private var backgroundProcessIndicator: ProgressIndicator? = null fun execute(callback: () -> Unit) { val psiFile = file.ktScratchFile ?: return executor.errorOccurs( KotlinJvmBundle.message("couldn.t.find.ktfile.for.current.editor"), isFatal = true ) val expressions = file.getExpressions() if (!executor.checkForErrors(psiFile, expressions)) return when (val result = runReadAction { KtScratchSourceFileProcessor().process(expressions) }) { is Result.Error -> return executor.errorOccurs(result.message, isFatal = true) is Result.OK -> { LOG.printDebugMessage("After processing by KtScratchSourceFileProcessor:\n ${result.code}") executeInBackground(KotlinJvmBundle.message("running.kotlin.scratch")) { indicator -> backgroundProcessIndicator = indicator val modifiedScratchSourceFile = createFileWithLightClassSupport(result, psiFile) tryRunCommandLine(modifiedScratchSourceFile, psiFile, result, callback) } } } } private fun executeInBackground(title: String, block: (indicator: ProgressIndicator) -> Unit) { object : Task.Backgroundable(file.project, title, true) { override fun run(indicator: ProgressIndicator) = block.invoke(indicator) }.queue() } private fun createFileWithLightClassSupport(result: Result.OK, psiFile: KtFile): KtFile = runReadAction { KtPsiFactory(file.project).createFileWithLightClassSupport("tmp.kt", result.code, psiFile) } private fun tryRunCommandLine(modifiedScratchSourceFile: KtFile, psiFile: KtFile, result: Result.OK, callback: () -> Unit) { assert(backgroundProcessIndicator != null) try { runCommandLine( file.project, modifiedScratchSourceFile, file.getExpressions(), psiFile, result, backgroundProcessIndicator!!, callback ) } catch (e: Throwable) { if (e is ControlFlowException) throw e reportError(result, e, psiFile) } } fun reportError(result: Result.OK, e: Throwable, psiFile: KtFile) { LOG.printDebugMessage(result.code) executor.errorOccurs(e.message ?: KotlinJvmBundle.message("couldn.t.compile.0", psiFile.name), e, isFatal = true) } private fun runCommandLine( project: Project, modifiedScratchSourceFile: KtFile, expressions: List<ScratchExpression>, psiFile: KtFile, result: Result.OK, indicator: ProgressIndicator, callback: () -> Unit ) { val tempDir = DumbService.getInstance(project).runReadActionInSmartMode(Computable { compileFileToTempDir(modifiedScratchSourceFile, expressions) }) ?: return try { val (environmentRequest, commandLine) = createCommandLine(psiFile, file.module, result.mainClassName, tempDir.path) val environment = environmentRequest.prepareEnvironment(TargetProgressIndicatorAdapter(indicator)) val commandLinePresentation = commandLine.getCommandPresentation(environment) LOG.printDebugMessage(commandLinePresentation) val processHandler = CapturingProcessHandler(environment.createProcess(commandLine, indicator), null, commandLinePresentation) val executionResult = processHandler.runProcessWithProgressIndicator(indicator, TIMEOUT_MS) when { executionResult.isTimeout -> { executor.errorOccurs( KotlinJvmBundle.message( "couldn.t.get.scratch.execution.result.stopped.by.timeout.0.ms", TIMEOUT_MS ) ) } executionResult.isCancelled -> { // ignore } else -> { executor.parseOutput(executionResult, expressions) } } } finally { tempDir.delete() callback() } } fun stop() { backgroundProcessIndicator?.cancel() } private fun compileFileToTempDir(psiFile: KtFile, expressions: List<ScratchExpression>): File? { if (!executor.checkForErrors(psiFile, expressions)) return null val tmpDir = FileUtil.createTempDirectory("compile", "scratch") LOG.printDebugMessage("Temp output dir: ${tmpDir.path}") KotlinCompilerIde(psiFile).compileToDirectory(tmpDir) return tmpDir } private fun createCommandLine(originalFile: KtFile, module: Module?, mainClassName: String, tempOutDir: String): Pair<TargetEnvironmentRequest, TargetedCommandLine> { val javaParameters = JavaParametersBuilder(originalFile.project) .withSdkFrom(module, true) .withMainClassName(mainClassName) .build() javaParameters.classPath.add(tempOutDir) if (module != null) { javaParameters.classPath.addAll(JavaParametersBuilder.getModuleDependencies(module)) } ScriptConfigurationManager.getInstance(originalFile.project) .getConfiguration(originalFile)?.let { javaParameters.classPath.addAll(it.dependenciesClassPath.map { f -> f.absolutePath }) } val wslConfiguration = JavaCommandLineState.checkCreateWslConfiguration(javaParameters.jdk) val request = wslConfiguration?.createEnvironmentRequest(originalFile.project) ?: LocalTargetEnvironmentRequest() return request to javaParameters.toCommandLine(request).build() } }
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/compile/KtScratchExecutionSession.kt
2941814973
// 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.configuration import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.project.ProjectData import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider import com.intellij.openapi.externalSystem.service.project.manage.AbstractProjectDataService import com.intellij.openapi.project.Project /** * This service appeared as a solution of the problem when [KotlinOutputPathsData] couldn't be deserialized after having been stored on disk * as a part of [DataNode] graph. Though we don't need the service itself, for now its the only way to make things work. * * Deserialization takes place at [serialization.kt#createDataClassResolver] (located in [platform-api.jar]). * * Graph contains nodes belonging to both IDEA and its plugins. To deserialize a node IDEA tries to load its class using a chain of * class-loaders: its own and those provided by actual set of plugins. The nuance is how to get plugins' ones. The approach is the * following. There is an association between a node's payload and a service which is supposed to consume it, see [getTargetDataKey] and * [DataNode.key]. Plugin services are guaranteed to be loaded by plugin class loader. No service - no plugin, node is just skipped. * */ class KotlinOutputPathsDataService : AbstractProjectDataService<KotlinOutputPathsData, Void>() { override fun getTargetDataKey() = KotlinOutputPathsData.KEY override fun importData( toImport: MutableCollection<out DataNode<KotlinOutputPathsData>>, projectData: ProjectData?, project: Project, modelsProvider: IdeModifiableModelsProvider ) { } }
plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/configuration/KotlinOutputPathsDataService.kt
866630382
// WITH_RUNTIME // IS_APPLICABLE: false class T<U> { fun <U> T<U>.iterator(): Iterator<U> = listOf<U>().iterator() } fun test() { T<Int>()<caret> }
plugins/kotlin/idea/tests/testData/intentions/iterateExpression/nonOperatorIterator.kt
191352775
fun some() { do println() while (true) println() while (true) <caret> }
plugins/kotlin/idea/tests/testData/indentationOnNewline/controlFlowConstructions/DoWhile7.after.kt
3499090466
package io.github.feelfreelinux.wykopmobilny.api.mywykop import io.github.feelfreelinux.wykopmobilny.APP_KEY import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.common.WykopApiResponse import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.EntryLinkResponse import io.reactivex.Single import retrofit2.http.GET import retrofit2.http.Path interface MyWykopRetrofitApi { @GET("/mywykop/index/page/{page}/appkey/$APP_KEY") fun getIndex(@Path("page") page: Int): Single<WykopApiResponse<List<EntryLinkResponse>>> @GET("/mywykop/users/page/{page}/appkey/$APP_KEY") fun byUsers(@Path("page") page: Int): Single<WykopApiResponse<List<EntryLinkResponse>>> @GET("/mywykop/tags/page/{page}/appkey/$APP_KEY") fun byTags(@Path("page") page: Int): Single<WykopApiResponse<List<EntryLinkResponse>>> }
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/api/mywykop/MyWykopRetrofitApi.kt
2231296546
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.coroutine.proxy.mirror import com.sun.jdi.* import org.jetbrains.kotlin.idea.debugger.coroutine.util.isSubTypeOrSame import org.jetbrains.kotlin.idea.debugger.coroutine.util.logger import org.jetbrains.kotlin.idea.debugger.evaluate.DefaultExecutionContext class DebugProbesImpl private constructor(context: DefaultExecutionContext) : BaseMirror<ObjectReference, MirrorOfDebugProbesImpl>("kotlinx.coroutines.debug.internal.DebugProbesImpl", context) { private val instanceField by FieldDelegate<ObjectReference>("INSTANCE") private val instance = instanceField.staticValue() private val javaLangListMirror = JavaUtilAbstractCollection(context) private val stackTraceElement = StackTraceElement(context) private val coroutineInfo = CoroutineInfo.instance(this, context) ?: throw IllegalStateException("CoroutineInfo implementation not found.") private val debugProbesCoroutineOwner = DebugProbesImplCoroutineOwner(coroutineInfo, context) private val isInstalledInCoreMethod by MethodDelegate<BooleanValue>("isInstalled\$kotlinx_coroutines_debug", "()Z") private val isInstalledInDebugMethod by MethodDelegate<BooleanValue>("isInstalled\$kotlinx_coroutines_core", "()Z") private val enhanceStackTraceWithThreadDumpMethod by MethodMirrorDelegate("enhanceStackTraceWithThreadDump", javaLangListMirror) private val dumpMethod by MethodMirrorDelegate("dumpCoroutinesInfo", javaLangListMirror, "()Ljava/util/List;") val isInstalled: Boolean by lazy { isInstalled(context) } override fun fetchMirror(value: ObjectReference, context: DefaultExecutionContext) = MirrorOfDebugProbesImpl(value, instance, isInstalled) fun isInstalled(context: DefaultExecutionContext): Boolean = isInstalledInDebugMethod.value(instance, context)?.booleanValue() ?: isInstalledInCoreMethod.value(instance, context)?.booleanValue() ?: throw IllegalStateException("isInstalledMethod not found") fun enhanceStackTraceWithThreadDump( context: DefaultExecutionContext, coroutineInfo: ObjectReference, lastObservedStackTrace: ObjectReference ): List<MirrorOfStackTraceElement>? { instance ?: return emptyList() val list = enhanceStackTraceWithThreadDumpMethod.mirror(instance, context, coroutineInfo, lastObservedStackTrace) ?: return emptyList() return list.values.mapNotNull { stackTraceElement.mirror(it, context) } } fun dumpCoroutinesInfo(context: DefaultExecutionContext): List<MirrorOfCoroutineInfo> { instance ?: return emptyList() val referenceList = dumpMethod.mirror(instance, context) ?: return emptyList() return referenceList.values.mapNotNull { coroutineInfo.mirror(it, context) } } fun getCoroutineInfo(value: ObjectReference?, context: DefaultExecutionContext): MirrorOfCoroutineInfo? { val coroutineOwner = debugProbesCoroutineOwner.mirror(value, context) return coroutineOwner?.coroutineInfo } companion object { val log by logger fun instance(context: DefaultExecutionContext) = try { DebugProbesImpl(context) } catch (e: IllegalStateException) { log.debug("Attempt to access DebugProbesImpl but none found.", e) null } } } class DebugProbesImplCoroutineOwner(private val coroutineInfo: CoroutineInfo, context: DefaultExecutionContext) : BaseMirror<ObjectReference, MirrorOfCoroutineOwner>(COROUTINE_OWNER_CLASS_NAME, context) { private val infoField by FieldMirrorDelegate("info", DebugCoroutineInfoImpl(context)) override fun fetchMirror(value: ObjectReference, context: DefaultExecutionContext): MirrorOfCoroutineOwner? { val info = infoField.value(value) ?: return null if (infoField.isCompatible(info)) return MirrorOfCoroutineOwner(value, infoField.mirrorOnly(info, context)) else return MirrorOfCoroutineOwner(value, coroutineInfo.mirror(info, context)) } companion object { const val COROUTINE_OWNER_CLASS_NAME = "kotlinx.coroutines.debug.internal.DebugProbesImpl\$CoroutineOwner" fun instanceOf(value: ObjectReference?) = value?.referenceType()?.isSubTypeOrSame(COROUTINE_OWNER_CLASS_NAME) ?: false } } class DebugCoroutineInfoImpl constructor(context: DefaultExecutionContext) : BaseMirror<ObjectReference, MirrorOfCoroutineInfo>("kotlinx.coroutines.debug.internal.DebugCoroutineInfoImpl", context) { private val stackTraceElement = StackTraceElement(context) val lastObservedThread by FieldDelegate<ThreadReference>("lastObservedThread") val state by FieldMirrorDelegate<ObjectReference, String>("_state", JavaLangObjectToString(context)) val lastObservedFrame by FieldMirrorDelegate("_lastObservedFrame", WeakReference(context)) val creationStackBottom by FieldMirrorDelegate("creationStackBottom", CoroutineStackFrame(context)) val sequenceNumber by FieldDelegate<LongValue>("sequenceNumber") val _context by MethodMirrorDelegate("getContext", CoroutineContext(context)) val getCreationStackTrace by MethodMirrorDelegate("getCreationStackTrace", JavaUtilAbstractCollection(context)) override fun fetchMirror(value: ObjectReference, context: DefaultExecutionContext): MirrorOfCoroutineInfo? { val state = state.mirror(value, context) val coroutineContext = _context.mirror(value, context) val creationStackBottom = creationStackBottom.mirror(value, context) val creationStackTraceMirror = getCreationStackTrace.mirror(value, context) val creationStackTrace = creationStackTraceMirror?.values?.mapNotNull { stackTraceElement.mirror(it, context) } val lastObservedFrame = lastObservedFrame.mirror(value, context) return MirrorOfCoroutineInfo( value, coroutineContext, creationStackBottom, sequenceNumber.value(value)?.longValue(), null, creationStackTrace, state, lastObservedThread.value(value), lastObservedFrame?.reference ) } } class CoroutineInfo private constructor( private val debugProbesImplMirror: DebugProbesImpl, context: DefaultExecutionContext, val className: String = AGENT_134_CLASS_NAME ) : BaseMirror<ObjectReference, MirrorOfCoroutineInfo>(className, context) { //private val javaLangListMirror = //private val coroutineContextMirror = private val stackTraceElement = StackTraceElement(context) private val contextFieldRef by FieldMirrorDelegate("context", CoroutineContext(context)) private val creationStackBottom by FieldMirrorDelegate("creationStackBottom", CoroutineStackFrame(context)) private val sequenceNumberField by FieldDelegate<LongValue>("sequenceNumber") private val creationStackTraceMethod by MethodMirrorDelegate("getCreationStackTrace", JavaUtilAbstractCollection(context)) private val stateMethod by MethodMirrorDelegate<ObjectReference, String>("getState", JavaLangObjectToString(context)) private val lastObservedStackTraceMethod by MethodDelegate<ObjectReference>("lastObservedStackTrace") private val lastObservedFrameField by FieldDelegate<ObjectReference>("lastObservedFrame") private val lastObservedThreadField by FieldDelegate<ThreadReference>("lastObservedThread") companion object { val log by logger private const val AGENT_134_CLASS_NAME = "kotlinx.coroutines.debug.CoroutineInfo" private const val AGENT_135_AND_UP_CLASS_NAME = "kotlinx.coroutines.debug.internal.DebugCoroutineInfo" fun instance(debugProbesImplMirror: DebugProbesImpl, context: DefaultExecutionContext): CoroutineInfo? { val classType = context.findClassSafe(AGENT_135_AND_UP_CLASS_NAME) ?: context.findClassSafe(AGENT_134_CLASS_NAME) ?: return null return try { CoroutineInfo(debugProbesImplMirror, context, classType.name()) } catch (e: IllegalStateException) { log.warn("coroutine-debugger: $classType not found", e) null } } } override fun fetchMirror(value: ObjectReference, context: DefaultExecutionContext): MirrorOfCoroutineInfo { val state = stateMethod.mirror(value, context) val coroutineContext = contextFieldRef.mirror(value, context) val creationStackBottom = creationStackBottom.mirror(value, context) val sequenceNumber = sequenceNumberField.value(value)?.longValue() val creationStackTraceMirror = creationStackTraceMethod.mirror(value, context) val creationStackTrace = creationStackTraceMirror?.values?.mapNotNull { stackTraceElement.mirror(it, context) } val lastObservedStackTrace = lastObservedStackTraceMethod.value(value, context) val enhancedList = if (lastObservedStackTrace != null) debugProbesImplMirror.enhanceStackTraceWithThreadDump(context, value, lastObservedStackTrace) else emptyList() val lastObservedThread = lastObservedThreadField.value(value) val lastObservedFrame = lastObservedFrameField.value(value) return MirrorOfCoroutineInfo( value, coroutineContext, creationStackBottom, sequenceNumber, enhancedList, creationStackTrace, state, lastObservedThread, lastObservedFrame ) } }
plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/proxy/mirror/coroutinesDebugMirror.kt
2442876864
// WITH_RUNTIME val foo: String <caret>get() = throw UnsupportedOperationException()
plugins/kotlin/idea/tests/testData/intentions/convertToBlockBody/getterWithThrow.kt
3779638825
/** * Copyright 2010 - 2022 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.exodus.entitystore import jetbrains.exodus.entitystore.util.EntityIdSetFactory import jetbrains.exodus.entitystore.util.ImmutableSingleTypeEntityIdBitSet import org.junit.Assert import java.util.* import kotlin.math.max class EntityIdSetTest : EntityStoreTestBase() { fun testEntityIdSet() { var set = EntityIdSetFactory.newSet() for (i in 0..9) { for (j in 0L..999L) { set = set.add(i, j) } for (j in 0L..999L) { Assert.assertTrue(set.contains(i, j)) } for (j in 0L..999L) { Assert.assertFalse(set.contains(i + 1, j)) } } Assert.assertEquals(-1, set.count().toLong()) Assert.assertFalse(set.contains(null)) set = set.add(null) Assert.assertTrue(set.contains(null)) } fun testEntityIdSetIterator() { var set = EntityIdSetFactory.newSet() for (i in 0..9) { for (j in 0L..999L) { set = set.add(i, j) } } var sample = EntityIdSetFactory.newSet() for (entityId in set) { Assert.assertTrue(set.contains(entityId)) Assert.assertFalse(sample.contains(entityId)) sample = sample.add(entityId) } Assert.assertFalse(sample.contains(null)) set = set.add(null) sample = EntityIdSetFactory.newSet() for (entityId in set) { Assert.assertTrue(set.contains(entityId)) Assert.assertFalse(sample.contains(entityId)) sample = sample.add(entityId) } Assert.assertTrue(sample.contains(null)) } fun testEntityIdSetCount() { var set = EntityIdSetFactory.newSet() for (i in 0..99) { set = set.add(7, i.toLong()) } Assert.assertEquals(100, set.count().toLong()) } fun testBitSet() { checkSet(0, 2, 7, 11, 55, 78) checkSet(4, 6, 7, 11, 55, 260) checkSet(4147483647L, 4147483648L, 4147483649L) } private fun checkSet(vararg data: Long) { Arrays.sort(data) val typeId = 7 val set = ImmutableSingleTypeEntityIdBitSet(typeId, data[0], data[data.size - 1], data, data.size) assertEquals(data.size, set.count()) var prevValue = data[0] - 20 for (i in data.indices) { val value = data[i] for (k in max(0, prevValue + 1) until value) { assertFalse(set.contains(typeId, k)) assertEquals(-1, set.indexOf(PersistentEntityId(typeId, k))) } prevValue = value assertTrue(set.contains(typeId, value)) assertFalse(set.contains(3, value)) assertEquals(i, set.indexOf(PersistentEntityId(typeId, value))) } val actualData = LongArray(data.size) var i = 0 for (id in set) { assertEquals(typeId, id.typeId) actualData[i++] = id.localId } Assert.assertArrayEquals(data, actualData) val reverseIterator = set.reverseIterator() while (reverseIterator.hasNext()) { val next = reverseIterator.next() Assert.assertEquals(data[--i], next.localId) } Assert.assertEquals(data[0], set.first.localId) Assert.assertEquals(data[data.size - 1], set.last.localId) } }
entity-store/src/test/kotlin/jetbrains/exodus/entitystore/EntityIdSetTest.kt
121528655
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.intelliLang import com.intellij.lang.Language import com.intellij.openapi.command.undo.UndoManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider import com.intellij.openapi.ui.TestDialog import com.intellij.openapi.ui.TestDialogManager import com.intellij.psi.PsiMethodCallExpression import com.intellij.psi.injection.Injectable import com.intellij.psi.util.parentOfType import com.intellij.util.ui.UIUtil import junit.framework.TestCase import org.intellij.plugins.intelliLang.inject.InjectLanguageAction import org.intellij.plugins.intelliLang.inject.InjectorUtils import org.intellij.plugins.intelliLang.inject.UnInjectLanguageAction import org.intellij.plugins.intelliLang.inject.config.BaseInjection import org.intellij.plugins.intelliLang.inject.config.InjectionPlace import org.intellij.plugins.intelliLang.inject.java.JavaLanguageInjectionSupport class JavaLanguageInjectionSupportTest : AbstractLanguageInjectionTestCase() { fun testAnnotationInjection() { myFixture.configureByText("Foo.java", """ class Foo { void bar() { baz("{\"a\": <caret> 1 }"); } void baz(String json){} } """) StoringFixPresenter().apply { InjectLanguageAction.invokeImpl(project, myFixture.editor, myFixture.file, Injectable.fromLanguage(Language.findLanguageByID("JSON")), this ) }.process() assertInjectedLangAtCaret("JSON") myFixture.checkResult(""" |import org.intellij.lang.annotations.Language; | |class Foo { | void bar() { | baz("{\"a\": 1 }"); | } | | void baz(@Language("JSON") String json){} | } | """.trimMargin()) assertNotNull(myFixture.getAvailableIntention("Uninject language or reference")) UnInjectLanguageAction.invokeImpl(project, topLevelEditor, topLevelFile) assertInjectedLangAtCaret(null) } fun testTemplateLanguageInjection() { myFixture.configureByText("Foo.java", """ class Foo { void bar() { baz("Text with **Mark<caret>down**"); } void baz(String str){} } """) assertNotNull(myFixture.getAvailableIntention("Inject language or reference")) InjectLanguageAction.invokeImpl(project, myFixture.editor, myFixture.file, Injectable.fromLanguage(Language.findLanguageByID("Markdown")) ) assertInjectedLangAtCaret("XML") assertNotNull(myFixture.getAvailableIntention("Uninject language or reference")) UnInjectLanguageAction.invokeImpl(project, topLevelEditor, topLevelFile) assertInjectedLangAtCaret(null) } fun testConfigInjection() { fun currentPrintlnInjection(): BaseInjection? { val psiMethod = topLevelFile.findElementAt(topLevelCaretPosition)!!.parentOfType<PsiMethodCallExpression>()!!.resolveMethod()!! val injection = JavaLanguageInjectionSupport.makeParameterInjection(psiMethod, 0, "JSON"); return InjectorUtils.getEditableInstance(project).findExistingInjection(injection) } myFixture.configureByText("Foo.java", """ class Foo { void bar() { System.out.println("{\"a\": <caret> 1 }"); } } """) TestCase.assertNull(currentPrintlnInjection()) InjectLanguageAction.invokeImpl(project, myFixture.editor, myFixture.file, Injectable.fromLanguage(Language.findLanguageByID("JSON"))) assertInjectedLangAtCaret("JSON") TestCase.assertNotNull(currentPrintlnInjection()) myFixture.configureByText("Another.java", """ class Another { void bar() { System.out.println("{\"a\": <caret> 1 }"); } } """) assertInjectedLangAtCaret("JSON") UnInjectLanguageAction.invokeImpl(project, topLevelEditor, topLevelFile) TestCase.assertNull(currentPrintlnInjection()) assertInjectedLangAtCaret(null) } fun testConfigUnInjectionAndUndo() { Configuration.getInstance().withInjections(listOf(jsonToPrintlnInjection())) { myFixture.configureByText("Foo.java", """ class Foo { void bar() { System.out.println("{\"a\": <caret> 1 }"); } } """) assertInjectedLangAtCaret("JSON") UnInjectLanguageAction.invokeImpl(project, topLevelEditor, topLevelFile) assertInjectedLangAtCaret(null) InjectLanguageAction.invokeImpl(project, topLevelEditor, topLevelFile, Injectable.fromLanguage(Language.findLanguageByID("JSON"))) assertInjectedLangAtCaret("JSON") undo(topLevelEditor) assertInjectedLangAtCaret(null) } } fun testPartialJson() { Configuration.getInstance().withInjections(listOf(jsonToPrintlnInjection())) { myFixture.configureByText("Foo.java", """ class Foo { void bar() { System.out.println( "{'id': '0'," + "'uri': 'http://localhost/'}" .replaceAll("'", "\"")); System.out.println("{ bad_json: 123 }".replaceAll("'", "\"")); } } """) injectionTestFixture.assertInjectedContent("'", "{'id': '0',missingValue") } } fun testRegexJson() { Configuration.getInstance().withInjections(listOf(jsonToPrintlnInjection().apply { setValuePattern("""\((.*?)\)""") isSingleFile = true })) { myFixture.configureByText("Foo.java", """ class Foo { void bar() { System.out.println("({'id':1,) bbb ('boo': 3})"); } } """) injectionTestFixture.assertInjectedContent("{'id':1,'boo': 3}") } } fun testRegexJsonNotSingle() { Configuration.getInstance().withInjections(listOf(jsonToPrintlnInjection().apply { setValuePattern("""\((.*?)\)""") isSingleFile = false })) { myFixture.configureByText("Foo.java", """ class Foo { void bar() { System.out.println("({'id':1}) bbb ({'boo': 3})"); } } """) injectionTestFixture.assertInjectedContent("{'id':1}", "{'boo': 3}") } } private fun jsonToPrintlnInjection(): BaseInjection = BaseInjection("java").apply { injectedLanguageId = "JSON" setInjectionPlaces( InjectionPlace(compiler.createElementPattern( """psiParameter().ofMethod(0, psiMethod().withName("println").withParameters("java.lang.String").definedInClass("java.io.PrintStream"))""", "println JSOM"), true ), InjectionPlace(compiler.createElementPattern( """psiParameter().ofMethod(0, psiMethod().withName("print").withParameters("java.lang.String").definedInClass("java.io.PrintStream"))""", "print JSON"), true ) ) } private fun undo(editor: Editor) { UIUtil.invokeAndWaitIfNeeded(Runnable { val oldTestDialog = TestDialogManager.setTestDialog(TestDialog.OK) try { val undoManager = UndoManager.getInstance(project) val textEditor = TextEditorProvider.getInstance().getTextEditor(editor) undoManager.undo(textEditor) } finally { TestDialogManager.setTestDialog(oldTestDialog) } }) } }
plugins/IntelliLang/IntelliLang-tests/test/org/intellij/plugins/intelliLang/JavaLanguageInjectionSupportTest.kt
2778940088
// 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.gradleTooling import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.artifacts.Dependency import org.gradle.api.artifacts.ProjectDependency import org.gradle.api.provider.Property import org.gradle.tooling.BuildController import org.gradle.tooling.model.Model import org.gradle.tooling.model.build.BuildEnvironment import org.gradle.tooling.model.gradle.GradleBuild import org.gradle.util.GradleVersion import org.jetbrains.kotlin.idea.gradleTooling.arguments.CachedExtractedArgsInfo import org.jetbrains.kotlin.idea.gradleTooling.arguments.CompilerArgumentsCacheMapperImpl import org.jetbrains.kotlin.idea.gradleTooling.arguments.CompilerArgumentsCachingChain import org.jetbrains.kotlin.idea.gradleTooling.arguments.CompilerArgumentsCachingManager.cacheCompilerArgument import org.jetbrains.kotlin.idea.projectModel.CompilerArgumentsCacheAware import org.jetbrains.kotlin.idea.projectModel.KotlinTaskProperties import org.jetbrains.plugins.gradle.model.ProjectImportModelProvider import org.jetbrains.plugins.gradle.tooling.ErrorMessageBuilder import org.jetbrains.plugins.gradle.tooling.ModelBuilderContext import org.jetbrains.plugins.gradle.tooling.ModelBuilderService import java.io.File import java.io.Serializable import java.lang.reflect.InvocationTargetException import java.util.* @Deprecated("Use org.jetbrains.kotlin.idea.projectModel.CachedArgsInfo instead") interface ArgsInfo : Serializable { val currentArguments: List<String> val defaultArguments: List<String> val dependencyClasspath: List<String> } @Suppress("DEPRECATION") @Deprecated("Use org.jetbrains.kotlin.idea.gradleTooling.CachedCompilerArgumentsBySourceSet instead") typealias CompilerArgumentsBySourceSet = Map<String, ArgsInfo> typealias CachedCompilerArgumentsBySourceSet = Map<String, CachedExtractedArgsInfo> typealias AdditionalVisibleSourceSetsBySourceSet = Map</* Source Set Name */ String, /* Visible Source Set Names */ Set<String>> interface KotlinGradleModel : Serializable { val hasKotlinPlugin: Boolean @Suppress("DEPRECATION", "TYPEALIAS_EXPANSION_DEPRECATION") @Deprecated( "Use 'cachedCompilerArgumentsBySourceSet' instead", ReplaceWith("cachedCompilerArgumentsBySourceSet"), DeprecationLevel.ERROR ) val compilerArgumentsBySourceSet: CompilerArgumentsBySourceSet val additionalVisibleSourceSets: AdditionalVisibleSourceSetsBySourceSet val cachedCompilerArgumentsBySourceSet: CachedCompilerArgumentsBySourceSet val coroutines: String? val platformPluginId: String? val implements: List<String> val kotlinTarget: String? val kotlinTaskProperties: KotlinTaskPropertiesBySourceSet val gradleUserHome: String val cacheAware: CompilerArgumentsCacheAware @Deprecated(level = DeprecationLevel.ERROR, message = "Use KotlinGradleModel#cacheAware instead") val partialCacheAware: CompilerArgumentsCacheAware } data class KotlinGradleModelImpl( override val hasKotlinPlugin: Boolean, @Suppress("OverridingDeprecatedMember", "DEPRECATION", "TYPEALIAS_EXPANSION_DEPRECATION") override val compilerArgumentsBySourceSet: CompilerArgumentsBySourceSet, override val cachedCompilerArgumentsBySourceSet: CachedCompilerArgumentsBySourceSet, override val additionalVisibleSourceSets: AdditionalVisibleSourceSetsBySourceSet, override val coroutines: String?, override val platformPluginId: String?, override val implements: List<String>, override val kotlinTarget: String? = null, override val kotlinTaskProperties: KotlinTaskPropertiesBySourceSet, override val gradleUserHome: String, override val cacheAware: CompilerArgumentsCacheAware ) : KotlinGradleModel { @Deprecated( "Use KotlinGradleModel#cacheAware instead", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith("KotlinGradleModel#cacheAware") ) @Suppress("OverridingDeprecatedMember") override val partialCacheAware: CompilerArgumentsCacheAware get() = throw UnsupportedOperationException("Not yet implemented") } abstract class AbstractKotlinGradleModelBuilder : ModelBuilderService { companion object { val kotlinCompileJvmTaskClasses = listOf( "org.jetbrains.kotlin.gradle.tasks.KotlinCompile_Decorated", "org.jetbrains.kotlin.gradle.tasks.KotlinCompileWithWorkers_Decorated" ) val kotlinCompileTaskClasses = kotlinCompileJvmTaskClasses + listOf( "org.jetbrains.kotlin.gradle.tasks.Kotlin2JsCompile_Decorated", "org.jetbrains.kotlin.gradle.tasks.KotlinCompileCommon_Decorated", "org.jetbrains.kotlin.gradle.tasks.Kotlin2JsCompileWithWorkers_Decorated", "org.jetbrains.kotlin.gradle.tasks.KotlinCompileCommonWithWorkers_Decorated" ) val platformPluginIds = listOf("kotlin-platform-jvm", "kotlin-platform-js", "kotlin-platform-common") val pluginToPlatform = linkedMapOf( "kotlin" to "kotlin-platform-jvm", "kotlin2js" to "kotlin-platform-js" ) val kotlinPluginIds = listOf("kotlin", "kotlin2js", "kotlin-android") const val ABSTRACT_KOTLIN_COMPILE_CLASS = "org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile" const val kotlinProjectExtensionClass = "org.jetbrains.kotlin.gradle.dsl.KotlinProjectExtension" const val kotlinSourceSetClass = "org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet" const val kotlinPluginWrapper = "org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapperKt" private val propertyClassPresent = GradleVersion.current() >= GradleVersion.version("4.3") fun Task.getSourceSetName(): String = try { val method = javaClass.methods.firstOrNull { it.name.startsWith("getSourceSetName") && it.parameterTypes.isEmpty() } val sourceSetName = method?.invoke(this) when { sourceSetName is String -> sourceSetName propertyClassPresent && sourceSetName is Property<*> -> sourceSetName.get() as? String else -> null } } catch (e: InvocationTargetException) { null // can be thrown if property is not initialized yet } ?: "main" } } private const val REQUEST_FOR_NON_ANDROID_MODULES_ONLY = "*" class AndroidAwareGradleModelProvider<TModel>( private val modelClass: Class<TModel>, private val androidPluginIsRequestingVariantSpecificModels: Boolean ) : ProjectImportModelProvider { override fun populateBuildModels( controller: BuildController, buildModel: GradleBuild, consumer: ProjectImportModelProvider.BuildModelConsumer ) = Unit override fun populateProjectModels( controller: BuildController, projectModel: Model, modelConsumer: ProjectImportModelProvider.ProjectModelConsumer ) { val supportsParametrizedModels: Boolean = controller.findModel(BuildEnvironment::class.java)?.gradle?.gradleVersion?.let { // Parametrized build models were introduced in 4.4. Make sure that gradle import does not fail on pre-4.4 GradleVersion.version(it) >= GradleVersion.version("4.4") } ?: false val model = if (androidPluginIsRequestingVariantSpecificModels && supportsParametrizedModels) { controller.findModel(projectModel, modelClass, ModelBuilderService.Parameter::class.java) { it.value = REQUEST_FOR_NON_ANDROID_MODULES_ONLY } } else { controller.findModel(projectModel, modelClass) } if (model != null) { modelConsumer.consume(model, modelClass) } } class Result( private val hasProjectAndroidBasePlugin: Boolean, private val requestedVariantNames: Set<String>? ) { fun shouldSkipBuildAllCall(): Boolean = hasProjectAndroidBasePlugin && requestedVariantNames?.singleOrNull() == REQUEST_FOR_NON_ANDROID_MODULES_ONLY fun shouldSkipSourceSet(sourceSetName: String): Boolean = requestedVariantNames != null && !requestedVariantNames.contains(sourceSetName.lowercase(Locale.getDefault())) } companion object { fun parseParameter(project: Project, parameterValue: String?): Result { return Result( hasProjectAndroidBasePlugin = project.plugins.findPlugin("com.android.base") != null, requestedVariantNames = parameterValue?.splitToSequence(',')?.map { it.lowercase(Locale.getDefault()) }?.toSet() ) } } } class KotlinGradleModelBuilder : AbstractKotlinGradleModelBuilder(), ModelBuilderService.Ex { override fun getErrorMessageBuilder(project: Project, e: Exception): ErrorMessageBuilder { return ErrorMessageBuilder.create(project, e, "Gradle import errors") .withDescription("Unable to build Kotlin project configuration") } override fun canBuild(modelName: String?): Boolean = modelName == KotlinGradleModel::class.java.name private fun getImplementedProjects(project: Project): List<Project> { return listOf("expectedBy", "implement") .flatMap { project.configurations.findByName(it)?.dependencies ?: emptySet<Dependency>() } .filterIsInstance<ProjectDependency>() .mapNotNull { it.dependencyProject } } // see GradleProjectResolverUtil.getModuleId() in IDEA codebase private fun Project.pathOrName() = if (path == ":") name else path private fun Task.getDependencyClasspath(): List<String> { try { val abstractKotlinCompileClass = javaClass.classLoader.loadClass(ABSTRACT_KOTLIN_COMPILE_CLASS) val getCompileClasspath = abstractKotlinCompileClass.getDeclaredMethod("getCompileClasspath").apply { isAccessible = true } @Suppress("UNCHECKED_CAST") return (getCompileClasspath.invoke(this) as Collection<File>).map { it.path } } catch (e: ClassNotFoundException) { // Leave arguments unchanged } catch (e: NoSuchMethodException) { // Leave arguments unchanged } catch (e: InvocationTargetException) { // We can safely ignore this exception here as getCompileClasspath() gets called again at a later time // Leave arguments unchanged } return emptyList() } private fun getCoroutines(project: Project): String? { val kotlinExtension = project.extensions.findByName("kotlin") ?: return null val experimentalExtension = try { kotlinExtension::class.java.getMethod("getExperimental").invoke(kotlinExtension) } catch (e: NoSuchMethodException) { return null } return try { experimentalExtension::class.java.getMethod("getCoroutines").invoke(experimentalExtension)?.toString() } catch (e: NoSuchMethodException) { null } } override fun buildAll(modelName: String, project: Project): KotlinGradleModelImpl? { return buildAll(project, null) } override fun buildAll(modelName: String, project: Project, builderContext: ModelBuilderContext): KotlinGradleModelImpl? { return buildAll(project, builderContext) } private fun buildAll(project: Project, builderContext: ModelBuilderContext?): KotlinGradleModelImpl? { // When running in Android Studio, Android Studio would request specific source sets only to avoid syncing // currently not active build variants. We convert names to the lower case to avoid ambiguity with build variants // accidentally named starting with upper case. val androidVariantRequest = AndroidAwareGradleModelProvider.parseParameter(project, builderContext?.parameter) if (androidVariantRequest.shouldSkipBuildAllCall()) return null val kotlinPluginId = kotlinPluginIds.singleOrNull { project.plugins.findPlugin(it) != null } val platformPluginId = platformPluginIds.singleOrNull { project.plugins.findPlugin(it) != null } val target = project.getTarget() if (kotlinPluginId == null && platformPluginId == null && target == null) { return null } val cachedCompilerArgumentsBySourceSet = LinkedHashMap<String, CachedExtractedArgsInfo>() val additionalVisibleSourceSets = LinkedHashMap<String, Set<String>>() val extraProperties = HashMap<String, KotlinTaskProperties>() val argsMapper = CompilerArgumentsCacheMapperImpl() val kotlinCompileTasks = target?.let { it.compilations ?: emptyList() } ?.mapNotNull { compilation -> compilation.getCompileKotlinTaskName(project) } ?: (project.getAllTasks(false)[project]?.filter { it.javaClass.name in kotlinCompileTaskClasses } ?: emptyList()) kotlinCompileTasks.forEach { compileTask -> if (compileTask.javaClass.name !in kotlinCompileTaskClasses) return@forEach val sourceSetName = compileTask.getSourceSetName() if (androidVariantRequest.shouldSkipSourceSet(sourceSetName)) return@forEach val currentArguments = CompilerArgumentsCachingChain.extractAndCacheTask(compileTask, argsMapper, defaultsOnly = false) val defaultArguments = CompilerArgumentsCachingChain.extractAndCacheTask(compileTask, argsMapper, defaultsOnly = true) val dependencyClasspath = compileTask.getDependencyClasspath().map { cacheCompilerArgument(it, argsMapper) } cachedCompilerArgumentsBySourceSet[sourceSetName] = CachedExtractedArgsInfo(argsMapper.cacheOriginIdentifier, currentArguments, defaultArguments, dependencyClasspath) additionalVisibleSourceSets[sourceSetName] = getAdditionalVisibleSourceSets(project, sourceSetName) extraProperties.acknowledgeTask(compileTask, null) } val platform = platformPluginId ?: pluginToPlatform.entries.singleOrNull { project.plugins.findPlugin(it.key) != null }?.value val implementedProjects = getImplementedProjects(project) return KotlinGradleModelImpl( hasKotlinPlugin = kotlinPluginId != null || platformPluginId != null, compilerArgumentsBySourceSet = emptyMap(), cachedCompilerArgumentsBySourceSet = cachedCompilerArgumentsBySourceSet, additionalVisibleSourceSets = additionalVisibleSourceSets, coroutines = getCoroutines(project), platformPluginId = platform, implements = implementedProjects.map { it.pathOrName() }, kotlinTarget = platform ?: kotlinPluginId, kotlinTaskProperties = extraProperties, gradleUserHome = project.gradle.gradleUserHomeDir.absolutePath, cacheAware = argsMapper ) } }
plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/KotlinGradleModelBuilder.kt
2744715885
// 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.script import com.intellij.openapi.module.JavaModuleType import com.intellij.openapi.module.Module import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ModuleRootModificationUtil import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.IdeaTestUtil import com.intellij.testFramework.PlatformTestCase import com.intellij.testFramework.PsiTestUtil import com.intellij.util.ThrowableRunnable import com.intellij.util.ui.UIUtil import org.jdom.Element import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts import org.jetbrains.kotlin.idea.completion.test.KotlinCompletionTestCase import org.jetbrains.kotlin.idea.core.script.IdeScriptReportSink import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager.Companion.updateScriptDependenciesSynchronously import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionContributor import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionsManager import org.jetbrains.kotlin.idea.core.script.settings.KotlinScriptingSettings import org.jetbrains.kotlin.idea.highlighter.KotlinHighlightingUtil import org.jetbrains.kotlin.idea.script.AbstractScriptConfigurationTest.Companion.useDefaultTemplate import org.jetbrains.kotlin.idea.test.* import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.idea.util.projectStructure.getModuleDir import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.scripting.definitions.findScriptDefinition import org.jetbrains.kotlin.test.TestJdkKind import org.jetbrains.kotlin.test.util.addDependency import org.jetbrains.kotlin.test.util.projectLibrary import java.io.File import java.nio.file.Paths import kotlin.script.dependencies.Environment import kotlin.script.experimental.api.ScriptDiagnostic // some bugs can only be reproduced when some module and script have intersecting library dependencies private const val configureConflictingModule = "// CONFLICTING_MODULE" private fun String.splitOrEmpty(delimeters: String) = split(delimeters).takeIf { it.size > 1 } ?: emptyList() internal val switches = listOf( useDefaultTemplate, configureConflictingModule ) abstract class AbstractScriptConfigurationTest : KotlinCompletionTestCase() { companion object { private const val SCRIPT_NAME = "script.kts" val validKeys = setOf("javaHome", "sources", "classpath", "imports", "template-classes-names") const val useDefaultTemplate = "// DEPENDENCIES:" const val templatesSettings = "// TEMPLATES: " } protected fun testPath(fileName: String = fileName()): String = testDataFile(fileName).toString() protected fun testPath(): String = testPath(fileName()) override fun setUpModule() { // do not create default module } private fun findMainScript(testDir: File): File { testDir.walkTopDown().find { it.name == SCRIPT_NAME }?.let { return it } return testDir.walkTopDown().singleOrNull { it.name.contains("script") } ?: error("Couldn't find $SCRIPT_NAME file in $testDir") } private val sdk by lazy { runWriteAction { val sdk = PluginTestCaseBase.addJdk(testRootDisposable) { IdeaTestUtil.getMockJdk18() } ProjectRootManager.getInstance(project).projectSdk = sdk sdk } } protected fun configureScriptFile(path: File): VirtualFile { val mainScriptFile = findMainScript(path) return configureScriptFile(path, mainScriptFile) } protected fun configureScriptFile(path: File, mainScriptFile: File): VirtualFile { val environment = createScriptEnvironment(mainScriptFile) registerScriptTemplateProvider(environment) File(path, "mainModule").takeIf { it.exists() }?.let { myModule = createTestModuleFromDir(it) } path.listFiles { file -> file.name.startsWith("module") } ?.filter { it.exists() } ?.forEach { val newModule = createTestModuleFromDir(it) assert(myModule != null) { "Main module should exists" } ModuleRootModificationUtil.addDependency(myModule, newModule) } path.listFiles { file -> file.name.startsWith("script") && file.name != SCRIPT_NAME }?.forEach { createFileAndSyncDependencies(it) } // If script is inside module if (module != null && mainScriptFile.parentFile.name.toLowerCase().contains("module")) { module.addDependency( projectLibrary( "script-runtime", classesRoot = VfsUtil.findFileByIoFile(KotlinArtifacts.instance.kotlinScriptRuntime, true) ) ) if (environment["template-classes"] != null) { module.addDependency( projectLibrary( "script-template-library", classesRoot = environment.toVirtualFile("template-classes") ) ) } } if (configureConflictingModule in environment) { val sharedLib = environment.toVirtualFile("lib-classes") val sharedLibSources = environment.toVirtualFile("lib-source") if (module == null) { // Force create module if it doesn't exist myModule = createTestModuleByName("mainModule") } module.addDependency(projectLibrary("sharedLib", classesRoot = sharedLib, sourcesRoot = sharedLibSources)) } module?.let { ModuleRootModificationUtil.updateModel(it) { model -> model.sdk = sdk } } return createFileAndSyncDependencies(mainScriptFile) } private fun Environment.toVirtualFile(name: String): VirtualFile { val value = this[name] as? File ?: error("no file value for '$name'") return VfsUtil.findFileByIoFile(value, true) ?: error("unable to look up a virtual file for $name: $value") } private val oldScripClasspath: String? = System.getProperty("kotlin.script.classpath") private var settings: Element? = null override fun setUp() { super.setUp() settings = KotlinScriptingSettings.getInstance(project).state ScriptDefinitionsManager.getInstance(project).getAllDefinitions().forEach { KotlinScriptingSettings.getInstance(project).setEnabled(it, false) } setUpTestProject() } open fun setUpTestProject() { } override fun tearDown() { runAll( ThrowableRunnable { System.setProperty("kotlin.script.classpath", oldScripClasspath ?: "") }, ThrowableRunnable { settings?.let { KotlinScriptingSettings.getInstance(project).loadState(it) } }, ThrowableRunnable { super.tearDown() } ) } override fun getTestProjectJdk(): Sdk { return IdeaTestUtil.getMockJdk18() } protected fun createTestModuleByName(name: String): Module { val path = File(project.basePath, name).path val newModuleDir = runWriteAction { VfsUtil.createDirectoryIfMissing(path) ?: error("unable to create $path") } val newModule = createModuleAt(name, project, JavaModuleType.getModuleType(), Paths.get(newModuleDir.path)) PsiTestUtil.addSourceContentToRoots(newModule, newModuleDir) return newModule } private fun createTestModuleFromDir(dir: File): Module { return createTestModuleByName(dir.name).apply { val findFileByIoFile = LocalFileSystem.getInstance().findFileByIoFile(dir) ?: error("unable to locate $dir") PlatformTestCase.copyDirContentsTo(findFileByIoFile, contentRoot()) } } private fun Module.contentRoot() = ModuleRootManager.getInstance(this).contentRoots.first() private fun createScriptEnvironment(scriptFile: File): Environment { val defaultEnvironment = defaultEnvironment(scriptFile.parent) val env = mutableMapOf<String, Any?>() scriptFile.forEachLine { line -> fun iterateKeysInLine(prefix: String) { if (line.contains(prefix)) { line.trim().substringAfter(prefix).split(";").forEach { entry -> val (key, values) = entry.splitOrEmpty(":").map { it.trim() } assert(key in validKeys) { "Unexpected key: $key" } env[key] = values.split(",").map { val str = it.trim() defaultEnvironment[str] ?: str } } } } iterateKeysInLine(useDefaultTemplate) iterateKeysInLine(templatesSettings) switches.forEach { if (it in line) { env[it] = true } } } if (env[useDefaultTemplate] != true && env["template-classes-names"] == null) { env["template-classes-names"] = listOf("custom.scriptDefinition.Template") } val jdkKind = when ((env["javaHome"] as? List<String>)?.singleOrNull()) { "9" -> TestJdkKind.FULL_JDK_11 // TODO is that correct? else -> TestJdkKind.MOCK_JDK } runWriteAction { val jdk = PluginTestCaseBase.addJdk(testRootDisposable) { PluginTestCaseBase.jdk(jdkKind) } env["javaHome"] = File(jdk.homePath!!) } env.putAll(defaultEnvironment) return env } private fun defaultEnvironment(path: String): Map<String, File?> { val templateOutDir = File(path, "template").takeIf { it.isDirectory }?.let { compileLibToDir(it, getScriptingClasspath()) } ?: testDataFile("../defaultTemplate").takeIf { it.isDirectory }?.let { compileLibToDir(it, getScriptingClasspath()) } if (templateOutDir != null) { System.setProperty("kotlin.script.classpath", templateOutDir.path) } else { LOG.warn("templateOutDir is not found") } val libSrcDir = File(path, "lib").takeIf { it.isDirectory } val libClasses = libSrcDir?.let { compileLibToDir(it, emptyList()) } var moduleSrcDir = File(path, "depModule").takeIf { it.isDirectory } val moduleClasses = moduleSrcDir?.let { compileLibToDir(it, emptyList()) } if (moduleSrcDir != null) { val depModule = createTestModuleFromDir(moduleSrcDir) moduleSrcDir = File(depModule.getModuleDir()) } return mapOf( "runtime-classes" to KotlinArtifacts.instance.kotlinStdlib, "runtime-source" to KotlinArtifacts.instance.kotlinStdlibSources, "lib-classes" to libClasses, "lib-source" to libSrcDir, "module-classes" to moduleClasses, "module-source" to moduleSrcDir, "template-classes" to templateOutDir ) } protected fun getScriptingClasspath(): List<File> { return listOf( KotlinArtifacts.instance.kotlinScriptRuntime, KotlinArtifacts.instance.kotlinScriptingCommon, KotlinArtifacts.instance.kotlinScriptingJvm ) } protected fun createFileAndSyncDependencies(scriptFile: File): VirtualFile { var script: VirtualFile? = null if (module != null) { val contentRoot = module.contentRoot() script = contentRoot.findChild(scriptFile.name) } if (script == null) { val target = File(project.basePath, scriptFile.name) scriptFile.copyTo(target) script = VfsUtil.findFileByIoFile(target, true) } script ?: error("Test file with script couldn't be found in test project") configureByExistingFile(script) loadScriptConfigurationSynchronously(script) return script } protected open fun loadScriptConfigurationSynchronously(script: VirtualFile) { updateScriptDependenciesSynchronously(myFile) // This is needed because updateScriptDependencies invalidates psiFile that was stored in myFile field VfsUtil.markDirtyAndRefresh(false, true, true, project.baseDir) myFile = psiManager.findFile(script) checkHighlighting() } protected fun checkHighlighting(file: KtFile = myFile as KtFile) { val reports = IdeScriptReportSink.getReports(file) val isFatalErrorPresent = reports.any { it.severity == ScriptDiagnostic.Severity.FATAL } assert(isFatalErrorPresent || KotlinHighlightingUtil.shouldHighlight(file)) { "Highlighting is switched off for ${file.virtualFile.path}\n" + "reports=$reports\n" + "scriptDefinition=${file.findScriptDefinition()}" } } private fun compileLibToDir(srcDir: File, classpath: List<File>): File { val outDir = KotlinTestUtils.tmpDirForReusableFolder("${getTestName(false)}${srcDir.name}Out") KotlinCompilerStandalone( listOf(srcDir), target = outDir, classpath = classpath + listOf(outDir), compileKotlinSourcesBeforeJava = false ).compile() return outDir } private fun registerScriptTemplateProvider(environment: Environment) { val provider = if (environment[useDefaultTemplate] == true) { FromTextTemplateProvider(environment) } else { CustomScriptTemplateProvider(environment) } addExtensionPointInTest( ScriptDefinitionContributor.EP_NAME, project, provider, testRootDisposable ) ScriptDefinitionsManager.getInstance(project).reloadScriptDefinitions() UIUtil.dispatchAllInvocationEvents() } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/script/AbstractScriptConfigurationTest.kt
3638976170
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.runToolbar import com.intellij.execution.* import com.intellij.execution.actions.RunConfigurationsComboBoxAction import com.intellij.execution.impl.EditConfigurationsDialog import com.intellij.execution.runToolbar.components.ComboBoxArrowComponent import com.intellij.execution.runToolbar.components.MouseListenerHelper import com.intellij.execution.runToolbar.components.TrimmedMiddleLabel import com.intellij.ide.DataManager import com.intellij.ide.HelpTooltip import com.intellij.idea.ActionsBundle import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl.DO_NOT_ADD_CUSTOMIZATION_HANDLER import com.intellij.openapi.actionSystem.impl.segmentedActionBar.SegmentedCustomPanel import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopup import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.wm.IdeFocusManager import com.intellij.ui.Gray import com.intellij.ui.JBColor import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import net.miginfocom.swing.MigLayout import java.awt.Color import java.awt.Dimension import java.awt.Font import java.beans.PropertyChangeEvent import javax.swing.JComponent import javax.swing.SwingUtilities open class RunToolbarRunConfigurationsAction : RunConfigurationsComboBoxAction(), RTRunConfiguration { companion object { fun doRightClick(dataContext: DataContext) { ActionManager.getInstance().getAction("RunToolbarSlotContextMenuGroup")?.let { if(it is ActionGroup) { SwingUtilities.invokeLater { val popup = JBPopupFactory.getInstance().createActionGroupPopup( null, it, dataContext, false, false, false, null, 5, null) popup.showInBestPositionFor(dataContext) } } } } } open fun trace(e: AnActionEvent, add: String? = null) { } override fun getEditRunConfigurationAction(): AnAction? { return ActionManager.getInstance().getAction(RunToolbarEditConfigurationAction.ACTION_ID) } override fun createFinalAction(configuration: RunnerAndConfigurationSettings, project: Project): AnAction { return RunToolbarSelectConfigAction(configuration, project) } override fun getSelectedConfiguration(e: AnActionEvent): RunnerAndConfigurationSettings? { return e.configuration() ?: e.project?.let { val value = RunManager.getInstance(it).selectedConfiguration e.setConfiguration(value) value } } override fun checkMainSlotVisibility(state: RunToolbarMainSlotState): Boolean { return false } override fun update(e: AnActionEvent) { super.update(e) if(!e.presentation.isVisible) return e.presentation.isVisible = !e.isActiveProcess() if (!RunToolbarProcess.isExperimentalUpdatingEnabled) { e.mainState()?.let { e.presentation.isVisible = e.presentation.isVisible && checkMainSlotVisibility(it) } } e.presentation.description = e.runToolbarData()?.let { RunToolbarData.prepareDescription(e.presentation.text, ActionsBundle.message("action.RunToolbarShowHidePopupAction.click.to.open.combo.text")) } } override fun createCustomComponent(presentation: Presentation, place: String): JComponent { return object : SegmentedCustomPanel(presentation) { private val setting = object : TrimmedMiddleLabel() { override fun getFont(): Font { return UIUtil.getToolbarFont() } override fun getForeground(): Color { return UIUtil.getLabelForeground() } } private val arrow = ComboBoxArrowComponent().getView() init { MouseListenerHelper.addListener(this, { doClick() }, { doShiftClick() }, { doRightClick() }) fill() putClientProperty(DO_NOT_ADD_CUSTOMIZATION_HANDLER, true) background = JBColor.namedColor("ComboBoxButton.background", Gray.xDF) } override fun presentationChanged(event: PropertyChangeEvent) { setting.icon = presentation.icon setting.text = presentation.text setting.putClientProperty(DO_NOT_ADD_CUSTOMIZATION_HANDLER, true) isEnabled = presentation.isEnabled setting.isEnabled = isEnabled arrow.isVisible = isEnabled toolTipText = presentation.description setting.toolTipText = presentation.description arrow.toolTipText = presentation.description } private fun fill() { layout = MigLayout("ins 0 0 0 3, novisualpadding, gap 0, fill, hidemode 3", "4[][min!]") add(setting, "ay center, growx, wmin 10") add(arrow) setting.border = JBUI.Borders.empty() } private fun doRightClick() { RunToolbarRunConfigurationsAction.doRightClick(ActionToolbar.getDataContextFor(this)) } private fun doClick() { IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown { showPopup() } } fun showPopup() { val popup: JBPopup = createPopup() {} if (Registry.`is`("ide.helptooltip.enabled")) { HelpTooltip.setMasterPopup(this, popup) } popup.showUnderneathOf(this) } private fun createPopup(onDispose: Runnable): JBPopup { return createActionPopup(ActionToolbar.getDataContextFor(this), this, onDispose) } private fun doShiftClick() { val context = DataManager.getInstance().getDataContext(this) val project = CommonDataKeys.PROJECT.getData(context) if (project != null && !ActionUtil.isDumbMode(project)) { EditConfigurationsDialog(project).show() return } } override fun getPreferredSize(): Dimension { val d = super.getPreferredSize() d.width = FixWidthSegmentedActionToolbarComponent.RUN_CONFIG_WIDTH return d } } } private class RunToolbarSelectConfigAction(val configuration: RunnerAndConfigurationSettings, val project: Project) : DumbAwareAction() { init { var name = Executor.shortenNameIfNeeded(configuration.name) if (name.isEmpty()) { name = " " } val presentation = templatePresentation presentation.setText(name, false) presentation.description = ExecutionBundle.message("select.0.1", configuration.type.configurationTypeDescription, name) updateIcon(presentation) } private fun updateIcon(presentation: Presentation) { setConfigurationIcon(presentation, configuration, project) } override fun actionPerformed(e: AnActionEvent) { e.project?.let { e.runToolbarData()?.clear() e.setConfiguration(configuration) e.id()?.let {id -> RunToolbarSlotManager.getInstance(it).configurationChanged(id, configuration) } updatePresentation(ExecutionTargetManager.getActiveTarget(project), configuration, project, e.presentation, e.place) } } override fun update(e: AnActionEvent) { super.update(e) updateIcon(e.presentation) } } }
platform/execution-impl/src/com/intellij/execution/runToolbar/RunToolbarRunConfigurationsAction.kt
3772039734
// 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.nj2k.externalCodeProcessing import com.intellij.psi.PsiField import com.intellij.psi.PsiMember import com.intellij.psi.PsiMethod import com.intellij.psi.SmartPsiElementPointer import org.jetbrains.kotlin.idea.base.utils.fqname.getKotlinFqName import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.psiUtil.isPrivate interface JKMemberData<K : KtDeclaration> { var kotlinElementPointer: SmartPsiElementPointer<K>? var isStatic: Boolean val fqName: FqName? var name: String val kotlinElement get() = kotlinElementPointer?.element val searchInJavaFiles: Boolean get() = true val searchInKotlinFiles: Boolean get() = true val searchingNeeded get() = kotlinElement?.isPrivate() != true && (searchInJavaFiles || searchInKotlinFiles) } interface JKMemberDataCameFromJava<J : PsiMember, K : KtDeclaration> : JKMemberData<K> { val javaElement: J override val fqName get() = javaElement.getKotlinFqName() } interface JKFieldData : JKMemberData<KtProperty> data class JKFakeFieldData( override var isStatic: Boolean, override var kotlinElementPointer: SmartPsiElementPointer<KtProperty>? = null, override val fqName: FqName?, override var name: String ) : JKFieldData { override val searchInJavaFiles: Boolean get() = false override val searchInKotlinFiles: Boolean get() = false } data class JKFieldDataFromJava( override val javaElement: PsiField, override var isStatic: Boolean = false, override var kotlinElementPointer: SmartPsiElementPointer<KtProperty>? = null, override var name: String = javaElement.name ) : JKMemberDataCameFromJava<PsiField, KtProperty>, JKFieldData { override val searchInKotlinFiles: Boolean get() = wasRenamed val wasRenamed: Boolean get() = javaElement.name != name } data class JKMethodData( override val javaElement: PsiMethod, override var isStatic: Boolean = false, override var kotlinElementPointer: SmartPsiElementPointer<KtNamedFunction>? = null, var usedAsAccessorOfProperty: JKFieldData? = null ) : JKMemberDataCameFromJava<PsiMethod, KtNamedFunction> { override var name: String = javaElement.name }
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/externalCodeProcessing/JKMemberData.kt
427962379
package com.mysdk public object ResponseConverter { public fun fromParcelable(parcelable: ParcelableResponse): Response { val annotatedValue = Response( response = parcelable.response, mySecondInterface = (parcelable.mySecondInterface as MySecondInterfaceStubDelegate).delegate) return annotatedValue } public fun toParcelable(annotatedValue: Response): ParcelableResponse { val parcelable = ParcelableResponse() parcelable.response = annotatedValue.response parcelable.mySecondInterface = MySecondInterfaceStubDelegate(annotatedValue.mySecondInterface) return parcelable } }
privacysandbox/tools/tools-apicompiler/src/test/test-data/fullfeaturedsdk/output/com/mysdk/ResponseConverter.kt
16875332
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material3 import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.VectorConverter import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.interaction.DragInteraction import androidx.compose.foundation.interaction.FocusInteraction import androidx.compose.foundation.interaction.HoverInteraction import androidx.compose.foundation.interaction.Interaction import androidx.compose.foundation.interaction.InteractionSource import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.material3.tokens.ElevatedCardTokens import androidx.compose.material3.tokens.FilledCardTokens import androidx.compose.material3.tokens.OutlinedCardTokens import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.compositeOver import androidx.compose.ui.unit.Dp /** * <a href="https://m3.material.io/components/cards/overview" class="external" target="_blank">Material Design filled card</a>. * * Cards contain contain content and actions that relate information about a subject. Filled cards * provide subtle separation from the background. This has less emphasis than elevated or outlined * cards. * * This Card does not handle input events - see the other Card overloads if you want a clickable or * selectable Card. * * ![Filled card image](https://developer.android.com/images/reference/androidx/compose/material3/filled-card.png) * * Card sample: * @sample androidx.compose.material3.samples.CardSample * * @param modifier the [Modifier] to be applied to this card * @param shape defines the shape of this card's container, border (when [border] is not null), and * shadow (when using [elevation]) * @param colors [CardColors] that will be used to resolve the colors used for this card in * different states. See [CardDefaults.cardColors]. * @param elevation [CardElevation] used to resolve the elevation for this card in different states. * This controls the size of the shadow below the card. Additionally, when the container color is * [ColorScheme.surface], this controls the amount of primary color applied as an overlay. See also: * [Surface]. * @param border the border to draw around the container of this card */ @Composable fun Card( modifier: Modifier = Modifier, shape: Shape = CardDefaults.shape, colors: CardColors = CardDefaults.cardColors(), elevation: CardElevation = CardDefaults.cardElevation(), border: BorderStroke? = null, content: @Composable ColumnScope.() -> Unit ) { Surface( modifier = modifier, shape = shape, color = colors.containerColor(enabled = true).value, contentColor = colors.contentColor(enabled = true).value, tonalElevation = elevation.tonalElevation(enabled = true, interactionSource = null).value, shadowElevation = elevation.shadowElevation(enabled = true, interactionSource = null).value, border = border, ) { Column(content = content) } } /** * <a href="https://m3.material.io/components/cards/overview" class="external" target="_blank">Material Design filled card</a>. * * Cards contain contain content and actions that relate information about a subject. Filled cards * provide subtle separation from the background. This has less emphasis than elevated or outlined * cards. * * This Card handles click events, calling its [onClick] lambda. * * ![Filled card image](https://developer.android.com/images/reference/androidx/compose/material3/filled-card.png) * * Clickable card sample: * @sample androidx.compose.material3.samples.ClickableCardSample * * @param onClick called when this card is clicked * @param modifier the [Modifier] to be applied to this card * @param enabled controls the enabled state of this card. When `false`, this component will not * respond to user input, and it will appear visually disabled and disabled to accessibility * services. * @param shape defines the shape of this card's container, border (when [border] is not null), and * shadow (when using [elevation]) * @param colors [CardColors] that will be used to resolve the color(s) used for this card in * different states. See [CardDefaults.cardColors]. * @param elevation [CardElevation] used to resolve the elevation for this card in different states. * This controls the size of the shadow below the card. Additionally, when the container color is * [ColorScheme.surface], this controls the amount of primary color applied as an overlay. See also: * [Surface]. * @param border the border to draw around the container of this card * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this card. You can create and pass in your own `remember`ed instance to observe * [Interaction]s and customize the appearance / behavior of this card in different states. * */ @ExperimentalMaterial3Api @Composable fun Card( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, shape: Shape = CardDefaults.shape, colors: CardColors = CardDefaults.cardColors(), elevation: CardElevation = CardDefaults.cardElevation(), border: BorderStroke? = null, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable ColumnScope.() -> Unit ) { Surface( onClick = onClick, modifier = modifier, enabled = enabled, shape = shape, color = colors.containerColor(enabled).value, contentColor = colors.contentColor(enabled).value, tonalElevation = elevation.tonalElevation(enabled, interactionSource).value, shadowElevation = elevation.shadowElevation(enabled, interactionSource).value, border = border, interactionSource = interactionSource, ) { Column(content = content) } } /** * <a href="https://m3.material.io/components/cards/overview" class="external" target="_blank">Material Design elevated card</a>. * * Elevated cards contain content and actions that relate information about a subject. They have a * drop shadow, providing more separation from the background than filled cards, but less than * outlined cards. * * This ElevatedCard does not handle input events - see the other ElevatedCard overloads if you * want a clickable or selectable ElevatedCard. * * ![Elevated card image](https://developer.android.com/images/reference/androidx/compose/material3/elevated-card.png) * * Elevated card sample: * @sample androidx.compose.material3.samples.ElevatedCardSample * * @param modifier the [Modifier] to be applied to this card * @param shape defines the shape of this card's container and shadow (when using [elevation]) * @param colors [CardColors] that will be used to resolve the color(s) used for this card in * different states. See [CardDefaults.elevatedCardElevation]. * @param elevation [CardElevation] used to resolve the elevation for this card in different states. * This controls the size of the shadow below the card. Additionally, when the container color is * [ColorScheme.surface], this controls the amount of primary color applied as an overlay. See also: * [Surface]. */ @Composable fun ElevatedCard( modifier: Modifier = Modifier, shape: Shape = CardDefaults.elevatedShape, colors: CardColors = CardDefaults.elevatedCardColors(), elevation: CardElevation = CardDefaults.elevatedCardElevation(), content: @Composable ColumnScope.() -> Unit ) = Card( modifier = modifier, shape = shape, border = null, elevation = elevation, colors = colors, content = content ) /** * <a href="https://m3.material.io/components/cards/overview" class="external" target="_blank">Material Design elevated card</a>. * * Elevated cards contain content and actions that relate information about a subject. They have a * drop shadow, providing more separation from the background than filled cards, but less than * outlined cards. * * This ElevatedCard handles click events, calling its [onClick] lambda. * * ![Elevated card image](https://developer.android.com/images/reference/androidx/compose/material3/elevated-card.png) * * Clickable elevated card sample: * @sample androidx.compose.material3.samples.ClickableElevatedCardSample * * @param onClick called when this card is clicked * @param modifier the [Modifier] to be applied to this card * @param enabled controls the enabled state of this card. When `false`, this component will not * respond to user input, and it will appear visually disabled and disabled to accessibility * services. * @param shape defines the shape of this card's container and shadow (when using [elevation]) * @param colors [CardColors] that will be used to resolve the color(s) used for this card in * different states. See [CardDefaults.elevatedCardElevation]. * @param elevation [CardElevation] used to resolve the elevation for this card in different states. * This controls the size of the shadow below the card. Additionally, when the container color is * [ColorScheme.surface], this controls the amount of primary color applied as an overlay. See also: * [Surface]. * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this card. You can create and pass in your own `remember`ed instance to observe * [Interaction]s and customize the appearance / behavior of this card in different states. */ @ExperimentalMaterial3Api @Composable fun ElevatedCard( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, shape: Shape = CardDefaults.elevatedShape, colors: CardColors = CardDefaults.elevatedCardColors(), elevation: CardElevation = CardDefaults.elevatedCardElevation(), interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable ColumnScope.() -> Unit ) = Card( onClick = onClick, modifier = modifier, enabled = enabled, shape = shape, colors = colors, elevation = elevation, border = null, interactionSource = interactionSource, content = content ) /** * <a href="https://m3.material.io/components/cards/overview" class="external" target="_blank">Material Design outlined card</a>. * * Outlined cards contain content and actions that relate information about a subject. They have a * visual boundary around the container. This can provide greater emphasis than the other types. * * This OutlinedCard does not handle input events - see the other OutlinedCard overloads if you want * a clickable or selectable OutlinedCard. * * ![Outlined card image](https://developer.android.com/images/reference/androidx/compose/material3/outlined-card.png) * * Outlined card sample: * @sample androidx.compose.material3.samples.OutlinedCardSample * * @param modifier the [Modifier] to be applied to this card * @param shape defines the shape of this card's container, border (when [border] is not null), and * shadow (when using [elevation]) * @param colors [CardColors] that will be used to resolve the color(s) used for this card in * different states. See [CardDefaults.outlinedCardColors]. * @param elevation [CardElevation] used to resolve the elevation for this card in different states. * This controls the size of the shadow below the card. Additionally, when the container color is * [ColorScheme.surface], this controls the amount of primary color applied as an overlay. See also: * [Surface]. * @param border the border to draw around the container of this card */ @Composable fun OutlinedCard( modifier: Modifier = Modifier, shape: Shape = CardDefaults.outlinedShape, colors: CardColors = CardDefaults.outlinedCardColors(), elevation: CardElevation = CardDefaults.outlinedCardElevation(), border: BorderStroke = CardDefaults.outlinedCardBorder(), content: @Composable ColumnScope.() -> Unit ) = Card( modifier = modifier, shape = shape, colors = colors, elevation = elevation, border = border, content = content ) /** * <a href="https://m3.material.io/components/cards/overview" class="external" target="_blank">Material Design outlined card</a>. * * Outlined cards contain content and actions that relate information about a subject. They have a * visual boundary around the container. This can provide greater emphasis than the other types. * * This OutlinedCard handles click events, calling its [onClick] lambda. * * ![Outlined card image](https://developer.android.com/images/reference/androidx/compose/material3/outlined-card.png) * * Clickable outlined card sample: * @sample androidx.compose.material3.samples.ClickableOutlinedCardSample * * @param onClick called when this card is clicked * @param modifier the [Modifier] to be applied to this card * @param enabled controls the enabled state of this card. When `false`, this component will not * respond to user input, and it will appear visually disabled and disabled to accessibility * services. * @param shape defines the shape of this card's container, border (when [border] is not null), and * shadow (when using [elevation]) * @param colors [CardColors] that will be used to resolve the color(s) used for this card in * different states. See [CardDefaults.outlinedCardColors]. * @param elevation [CardElevation] used to resolve the elevation for this card in different states. * This controls the size of the shadow below the card. Additionally, when the container color is * [ColorScheme.surface], this controls the amount of primary color applied as an overlay. See also: * [Surface]. * @param border the border to draw around the container of this card * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this card. You can create and pass in your own `remember`ed instance to observe * [Interaction]s and customize the appearance / behavior of this card in different states. */ @ExperimentalMaterial3Api @Composable fun OutlinedCard( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, shape: Shape = CardDefaults.outlinedShape, colors: CardColors = CardDefaults.outlinedCardColors(), elevation: CardElevation = CardDefaults.outlinedCardElevation(), border: BorderStroke = CardDefaults.outlinedCardBorder(enabled), interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable ColumnScope.() -> Unit ) = Card( onClick = onClick, modifier = modifier, enabled = enabled, shape = shape, colors = colors, elevation = elevation, border = border, interactionSource = interactionSource, content = content ) /** * Contains the default values used by all card types. */ object CardDefaults { // shape Defaults /** Default shape for a card. */ val shape: Shape @Composable get() = FilledCardTokens.ContainerShape.toShape() /** Default shape for an elevated card. */ val elevatedShape: Shape @Composable get() = ElevatedCardTokens.ContainerShape.toShape() /** Default shape for an outlined card. */ val outlinedShape: Shape @Composable get() = OutlinedCardTokens.ContainerShape.toShape() /** * Creates a [CardElevation] that will animate between the provided values according to the * Material specification for a [Card]. * * @param defaultElevation the elevation used when the [Card] is has no other [Interaction]s. * @param pressedElevation the elevation used when the [Card] is pressed. * @param focusedElevation the elevation used when the [Card] is focused. * @param hoveredElevation the elevation used when the [Card] is hovered. * @param draggedElevation the elevation used when the [Card] is dragged. */ @Composable fun cardElevation( defaultElevation: Dp = FilledCardTokens.ContainerElevation, pressedElevation: Dp = FilledCardTokens.PressedContainerElevation, focusedElevation: Dp = FilledCardTokens.FocusContainerElevation, hoveredElevation: Dp = FilledCardTokens.HoverContainerElevation, draggedElevation: Dp = FilledCardTokens.DraggedContainerElevation, disabledElevation: Dp = FilledCardTokens.DisabledContainerElevation ): CardElevation = CardElevation( defaultElevation = defaultElevation, pressedElevation = pressedElevation, focusedElevation = focusedElevation, hoveredElevation = hoveredElevation, draggedElevation = draggedElevation, disabledElevation = disabledElevation ) /** * Creates a [CardElevation] that will animate between the provided values according to the * Material specification for an [ElevatedCard]. * * @param defaultElevation the elevation used when the [ElevatedCard] is has no other * [Interaction]s. * @param pressedElevation the elevation used when the [ElevatedCard] is pressed. * @param focusedElevation the elevation used when the [ElevatedCard] is focused. * @param hoveredElevation the elevation used when the [ElevatedCard] is hovered. * @param draggedElevation the elevation used when the [ElevatedCard] is dragged. */ @Composable fun elevatedCardElevation( defaultElevation: Dp = ElevatedCardTokens.ContainerElevation, pressedElevation: Dp = ElevatedCardTokens.PressedContainerElevation, focusedElevation: Dp = ElevatedCardTokens.FocusContainerElevation, hoveredElevation: Dp = ElevatedCardTokens.HoverContainerElevation, draggedElevation: Dp = ElevatedCardTokens.DraggedContainerElevation, disabledElevation: Dp = ElevatedCardTokens.DisabledContainerElevation ): CardElevation = CardElevation( defaultElevation = defaultElevation, pressedElevation = pressedElevation, focusedElevation = focusedElevation, hoveredElevation = hoveredElevation, draggedElevation = draggedElevation, disabledElevation = disabledElevation ) /** * Creates a [CardElevation] that will animate between the provided values according to the * Material specification for an [OutlinedCard]. * * @param defaultElevation the elevation used when the [OutlinedCard] is has no other * [Interaction]s. * @param pressedElevation the elevation used when the [OutlinedCard] is pressed. * @param focusedElevation the elevation used when the [OutlinedCard] is focused. * @param hoveredElevation the elevation used when the [OutlinedCard] is hovered. * @param draggedElevation the elevation used when the [OutlinedCard] is dragged. */ @Composable fun outlinedCardElevation( defaultElevation: Dp = OutlinedCardTokens.ContainerElevation, pressedElevation: Dp = defaultElevation, focusedElevation: Dp = defaultElevation, hoveredElevation: Dp = defaultElevation, draggedElevation: Dp = OutlinedCardTokens.DraggedContainerElevation, disabledElevation: Dp = OutlinedCardTokens.DisabledContainerElevation ): CardElevation = CardElevation( defaultElevation = defaultElevation, pressedElevation = pressedElevation, focusedElevation = focusedElevation, hoveredElevation = hoveredElevation, draggedElevation = draggedElevation, disabledElevation = disabledElevation ) /** * Creates a [CardColors] that represents the default container and content colors used in a * [Card]. * * @param containerColor the container color of this [Card] when enabled. * @param contentColor the content color of this [Card] when enabled. * @param disabledContainerColor the container color of this [Card] when not enabled. * @param disabledContentColor the content color of this [Card] when not enabled. */ @Composable fun cardColors( containerColor: Color = FilledCardTokens.ContainerColor.toColor(), contentColor: Color = contentColorFor(containerColor), disabledContainerColor: Color = FilledCardTokens.DisabledContainerColor.toColor() .copy(alpha = FilledCardTokens.DisabledContainerOpacity) .compositeOver( MaterialTheme.colorScheme.surfaceColorAtElevation( FilledCardTokens.DisabledContainerElevation ) ), disabledContentColor: Color = contentColorFor(containerColor).copy(DisabledAlpha), ): CardColors = CardColors( containerColor = containerColor, contentColor = contentColor, disabledContainerColor = disabledContainerColor, disabledContentColor = disabledContentColor ) /** * Creates a [CardColors] that represents the default container and content colors used in an * [ElevatedCard]. * * @param containerColor the container color of this [ElevatedCard] when enabled. * @param contentColor the content color of this [ElevatedCard] when enabled. * @param disabledContainerColor the container color of this [ElevatedCard] when not enabled. * @param disabledContentColor the content color of this [ElevatedCard] when not enabled. */ @Composable fun elevatedCardColors( containerColor: Color = ElevatedCardTokens.ContainerColor.toColor(), contentColor: Color = contentColorFor(containerColor), disabledContainerColor: Color = ElevatedCardTokens.DisabledContainerColor.toColor() .copy(alpha = ElevatedCardTokens.DisabledContainerOpacity) .compositeOver( MaterialTheme.colorScheme.surfaceColorAtElevation( ElevatedCardTokens.DisabledContainerElevation ) ), disabledContentColor: Color = contentColor.copy(DisabledAlpha), ): CardColors = CardColors( containerColor = containerColor, contentColor = contentColor, disabledContainerColor = disabledContainerColor, disabledContentColor = disabledContentColor ) /** * Creates a [CardColors] that represents the default container and content colors used in an * [OutlinedCard]. * * @param containerColor the container color of this [OutlinedCard] when enabled. * @param contentColor the content color of this [OutlinedCard] when enabled. * @param disabledContainerColor the container color of this [OutlinedCard] when not enabled. * @param disabledContentColor the content color of this [OutlinedCard] when not enabled. */ @Composable fun outlinedCardColors( containerColor: Color = OutlinedCardTokens.ContainerColor.toColor(), contentColor: Color = contentColorFor(containerColor), disabledContainerColor: Color = containerColor, disabledContentColor: Color = contentColor.copy(DisabledAlpha), ): CardColors = CardColors( containerColor = containerColor, contentColor = contentColor, disabledContainerColor = disabledContainerColor, disabledContentColor = disabledContentColor ) /** * Creates a [BorderStroke] that represents the default border used in [OutlinedCard]. * * @param enabled whether the card is enabled */ @Composable fun outlinedCardBorder(enabled: Boolean = true): BorderStroke { val color = if (enabled) { OutlinedCardTokens.OutlineColor.toColor() } else { OutlinedCardTokens.DisabledOutlineColor.toColor() .copy(alpha = OutlinedCardTokens.DisabledOutlineOpacity) .compositeOver( MaterialTheme.colorScheme.surfaceColorAtElevation( OutlinedCardTokens.DisabledContainerElevation ) ) } return remember(color) { BorderStroke(OutlinedCardTokens.OutlineWidth, color) } } } /** * Represents the elevation for a card in different states. * * - See [CardDefaults.cardElevation] for the default elevation used in a [Card]. * - See [CardDefaults.elevatedCardElevation] for the default elevation used in an [ElevatedCard]. * - See [CardDefaults.outlinedCardElevation] for the default elevation used in an [OutlinedCard]. */ @Immutable class CardElevation internal constructor( private val defaultElevation: Dp, private val pressedElevation: Dp, private val focusedElevation: Dp, private val hoveredElevation: Dp, private val draggedElevation: Dp, private val disabledElevation: Dp ) { /** * Represents the tonal elevation used in a card, depending on its [enabled] state and * [interactionSource]. This should typically be the same value as the [shadowElevation]. * * Tonal elevation is used to apply a color shift to the surface to give the it higher emphasis. * When surface's color is [ColorScheme.surface], a higher elevation will result in a darker * color in light theme and lighter color in dark theme. * * See [shadowElevation] which controls the elevation of the shadow drawn around the card. * * @param enabled whether the card is enabled * @param interactionSource the [InteractionSource] for this card */ @Composable internal fun tonalElevation( enabled: Boolean, interactionSource: InteractionSource? ): State<Dp> { if (interactionSource == null) { return remember { mutableStateOf(defaultElevation) } } return animateElevation(enabled = enabled, interactionSource = interactionSource) } /** * Represents the shadow elevation used in a card, depending on its [enabled] state and * [interactionSource]. This should typically be the same value as the [tonalElevation]. * * Shadow elevation is used to apply a shadow around the card to give it higher emphasis. * * See [tonalElevation] which controls the elevation with a color shift to the surface. * * @param enabled whether the card is enabled * @param interactionSource the [InteractionSource] for this card */ @Composable internal fun shadowElevation( enabled: Boolean, interactionSource: InteractionSource? ): State<Dp> { if (interactionSource == null) { return remember { mutableStateOf(defaultElevation) } } return animateElevation(enabled = enabled, interactionSource = interactionSource) } @Composable private fun animateElevation( enabled: Boolean, interactionSource: InteractionSource ): State<Dp> { val interactions = remember { mutableStateListOf<Interaction>() } LaunchedEffect(interactionSource) { interactionSource.interactions.collect { interaction -> when (interaction) { is HoverInteraction.Enter -> { interactions.add(interaction) } is HoverInteraction.Exit -> { interactions.remove(interaction.enter) } is FocusInteraction.Focus -> { interactions.add(interaction) } is FocusInteraction.Unfocus -> { interactions.remove(interaction.focus) } is PressInteraction.Press -> { interactions.add(interaction) } is PressInteraction.Release -> { interactions.remove(interaction.press) } is PressInteraction.Cancel -> { interactions.remove(interaction.press) } is DragInteraction.Start -> { interactions.add(interaction) } is DragInteraction.Stop -> { interactions.remove(interaction.start) } is DragInteraction.Cancel -> { interactions.remove(interaction.start) } } } } val interaction = interactions.lastOrNull() val target = if (!enabled) { disabledElevation } else { when (interaction) { is PressInteraction.Press -> pressedElevation is HoverInteraction.Enter -> hoveredElevation is FocusInteraction.Focus -> focusedElevation is DragInteraction.Start -> draggedElevation else -> defaultElevation } } val animatable = remember { Animatable(target, Dp.VectorConverter) } LaunchedEffect(target) { if (enabled) { val lastInteraction = when (animatable.targetValue) { pressedElevation -> PressInteraction.Press(Offset.Zero) hoveredElevation -> HoverInteraction.Enter() focusedElevation -> FocusInteraction.Focus() draggedElevation -> DragInteraction.Start() else -> null } animatable.animateElevation( from = lastInteraction, to = interaction, target = target ) } else { // No transition when moving to a disabled state. animatable.snapTo(target) } } return animatable.asState() } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || other !is CardElevation) return false if (defaultElevation != other.defaultElevation) return false if (pressedElevation != other.pressedElevation) return false if (focusedElevation != other.focusedElevation) return false if (hoveredElevation != other.hoveredElevation) return false if (disabledElevation != other.disabledElevation) return false return true } override fun hashCode(): Int { var result = defaultElevation.hashCode() result = 31 * result + pressedElevation.hashCode() result = 31 * result + focusedElevation.hashCode() result = 31 * result + hoveredElevation.hashCode() result = 31 * result + disabledElevation.hashCode() return result } } /** * Represents the container and content colors used in a card in different states. * * - See [CardDefaults.cardColors] for the default colors used in a [Card]. * - See [CardDefaults.elevatedCardColors] for the default colors used in a [ElevatedCard]. * - See [CardDefaults.outlinedCardColors] for the default colors used in a [OutlinedCard]. */ @Immutable class CardColors internal constructor( private val containerColor: Color, private val contentColor: Color, private val disabledContainerColor: Color, private val disabledContentColor: Color, ) { /** * Represents the container color for this card, depending on [enabled]. * * @param enabled whether the card is enabled */ @Composable internal fun containerColor(enabled: Boolean): State<Color> { return rememberUpdatedState(if (enabled) containerColor else disabledContainerColor) } /** * Represents the content color for this card, depending on [enabled]. * * @param enabled whether the card is enabled */ @Composable internal fun contentColor(enabled: Boolean): State<Color> { return rememberUpdatedState(if (enabled) contentColor else disabledContentColor) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || other !is CardColors) return false if (containerColor != other.containerColor) return false if (contentColor != other.contentColor) return false if (disabledContainerColor != other.disabledContainerColor) return false if (disabledContentColor != other.disabledContentColor) return false return true } override fun hashCode(): Int { var result = containerColor.hashCode() result = 31 * result + contentColor.hashCode() result = 31 * result + disabledContainerColor.hashCode() result = 31 * result + disabledContentColor.hashCode() return result } }
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/Card.kt
1506083232
package domain.recommendation data class DomainRecommendationCompany(val name: String)
domain/src/main/kotlin/domain/recommendation/DomainRecommendationCompany.kt
2480287837
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.ift.lesson.refactorings import com.intellij.codeInsight.template.impl.TemplateManagerImpl import com.intellij.java.ift.JavaLessonsBundle import com.intellij.java.refactoring.JavaRefactoringBundle import com.intellij.ui.UIBundle import training.dsl.* import training.dsl.LessonUtil.rawEnter import training.dsl.LessonUtil.restoreIfModifiedOrMoved import training.learn.LessonsBundle import training.learn.course.KLesson import javax.swing.JDialog class JavaExtractMethodCocktailSortLesson : KLesson("Refactorings.ExtractMethod", LessonsBundle.message("extract.method.lesson.name")) { override val lessonContent: LessonContext.() -> Unit get() = { prepareSample(javaSortSample) showWarningIfInplaceRefactoringsDisabled() actionTask("ExtractMethod") { restoreIfModifiedOrMoved(javaSortSample) LessonsBundle.message("extract.method.invoke.action", action(it)) } task { transparentRestore = true stateCheck { TemplateManagerImpl.getTemplateState(editor) != null } } val processDuplicatesTitle = JavaRefactoringBundle.message("process.duplicates.title") task { text(JavaLessonsBundle.message("java.extract.method.edit.method.name", rawEnter())) triggerUI().component { dialog: JDialog -> dialog.title == processDuplicatesTitle } restoreState(delayMillis = defaultRestoreDelay) { TemplateManagerImpl.getTemplateState(editor) == null } test(waitEditorToBeReady = false) { invokeActionViaShortcut("ENTER") } } val replaceButtonText = UIBundle.message("replace.prompt.replace.button").dropMnemonic() task { text(LessonsBundle.message("extract.method.confirm.several.replaces", strong(replaceButtonText))) stateCheck { previous.ui?.isShowing?.not() ?: true } test(waitEditorToBeReady = false) { dialog(processDuplicatesTitle) { button(replaceButtonText).click() } } } restoreRefactoringOptionsInformer() } override val helpLinks: Map<String, String> get() = mapOf( Pair(LessonsBundle.message("extract.method.help.link"), LessonUtil.getHelpLink("extract-method.html")), ) } private val javaSortSample = parseLessonSample(""" class Demo { public static void cocktailSort(int[] a) { boolean swapped = true; int start = 0; int end = a.length; while (swapped) { swapped = false; for (int i = start; i < end - 1; ++i) { <select> if (a[i] > a[i + 1]) { int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; swapped = true; } </select> } if (!swapped) break; swapped = false; end = end - 1; for (int i = end - 1; i >= start; i--) { if (a[i] > a[i + 1]) { int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; swapped = true; } } start = start + 1; } } } """.trimIndent())
java/java-features-trainer/src/com/intellij/java/ift/lesson/refactorings/JavaExtractMethodCocktailSortLesson.kt
663053456
fun stop(): Boolean { return false } fun foo() { while (true) { if (!stop()) break } }
plugins/kotlin/j2k/new/tests/testData/newJ2k/for/infiniteFor.kt
263952259
// 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.debugger.stepping.smartStepInto import com.intellij.debugger.SourcePosition import com.intellij.debugger.actions.JvmSmartStepIntoHandler import com.intellij.debugger.actions.SmartStepTarget import com.intellij.debugger.engine.DebugProcessImpl import com.intellij.debugger.engine.DebuggerManagerThreadImpl import com.intellij.debugger.engine.MethodFilter import com.intellij.debugger.engine.events.DebuggerCommandImpl import com.intellij.debugger.impl.DebuggerSession import com.intellij.debugger.impl.PrioritizedTask import com.intellij.debugger.jdi.MethodBytecodeUtil import com.intellij.openapi.application.ReadAction import com.intellij.openapi.progress.ProgressManager import com.intellij.psi.PsiDocumentManager import com.intellij.util.Range import com.intellij.util.containers.OrderedSet import com.sun.jdi.Location import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.compute import org.jetbrains.kotlin.idea.base.psi.getTopmostElementAtOffset import org.jetbrains.kotlin.idea.debugger.base.util.DexDebugFacility import org.jetbrains.kotlin.idea.debugger.KotlinDebuggerSettings import org.jetbrains.kotlin.idea.debugger.base.util.safeLocation import org.jetbrains.kotlin.idea.debugger.base.util.safeMethod import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile class KotlinSmartStepIntoHandler : JvmSmartStepIntoHandler() { override fun isAvailable(position: SourcePosition?) = position?.file is KtFile override fun findStepIntoTargets(position: SourcePosition, session: DebuggerSession) = if (KotlinDebuggerSettings.getInstance().alwaysDoSmartStepInto) { findSmartStepTargetsAsync(position, session) } else { super.findStepIntoTargets(position, session) } override fun findSmartStepTargetsAsync(position: SourcePosition, session: DebuggerSession): Promise<List<SmartStepTarget>> { val result = AsyncPromise<List<SmartStepTarget>>() val command = object : DebuggerCommandImpl(PrioritizedTask.Priority.NORMAL) { override fun action() = result.compute { findSmartStepTargetsInReadAction(position, session) } override fun commandCancelled() { result.setError("Cancelled") } } val managerThread = session.process.managerThread if (DebuggerManagerThreadImpl.isManagerThread()) { managerThread.invoke(command) } else { managerThread.schedule(command) } return result } override fun findSmartStepTargets(position: SourcePosition): List<SmartStepTarget> = findSmartStepTargetsInReadAction(position, null) override fun createMethodFilter(stepTarget: SmartStepTarget?): MethodFilter? = when (stepTarget) { is KotlinSmartStepTarget -> stepTarget.createMethodFilter() else -> super.createMethodFilter(stepTarget) } private fun findSmartStepTargetsInReadAction(position: SourcePosition, session: DebuggerSession?) = ReadAction.nonBlocking<List<SmartStepTarget>> { findSmartStepTargets(position, session) }.executeSynchronously() private fun findSmartStepTargets(position: SourcePosition, session: DebuggerSession?): List<SmartStepTarget> { val topmostElement = position.getTopmostElement() ?: return emptyList() val lines = topmostElement.getLines() ?: return emptyList() var targets = findSmartStepTargets(topmostElement, lines) if (session != null) { targets = calculateSmartStepTargetsToShow(targets, session.process, lines.toClosedRange()) } return reorderWithSteppingFilters(targets) } } private fun findSmartStepTargets(topmostElement: KtElement, lines: Range<Int>): List<SmartStepTarget> { val targets = OrderedSet<SmartStepTarget>() val visitor = SmartStepTargetVisitor(topmostElement, lines, targets) topmostElement.accept(visitor, null) return targets } private fun calculateSmartStepTargetsToShow(targets: List<SmartStepTarget>, debugProcess: DebugProcessImpl, lines: ClosedRange<Int>): List<SmartStepTarget> { val lambdaTargets = mutableListOf<SmartStepTarget>() val methodTargets = mutableListOf<KotlinMethodSmartStepTarget>() for (target in targets) { if (target is KotlinMethodSmartStepTarget) { methodTargets.add(target) } else { lambdaTargets.add(target) } } return lambdaTargets + methodTargets.filterAlreadyExecuted(debugProcess, lines) } private fun List<KotlinMethodSmartStepTarget>.filterAlreadyExecuted( debugProcess: DebugProcessImpl, lines: ClosedRange<Int> ): List<KotlinMethodSmartStepTarget> { DebuggerManagerThreadImpl.assertIsManagerThread() if (DexDebugFacility.isDex(debugProcess) || size <= 1) return this val frameProxy = debugProcess.suspendManager.pausedContext?.frameProxy val location = frameProxy?.safeLocation() ?: return this return filterSmartStepTargets(location, lines, this, debugProcess) } private fun SourcePosition.getTopmostElement(): KtElement? { val element = elementAt ?: return null return getTopmostElementAtOffset(element, element.textRange.startOffset) as? KtElement } private fun KtElement.getLines(): Range<Int>? { val file = containingKtFile val document = PsiDocumentManager.getInstance(file.project).getDocument(file) ?: return null val textRange = textRange return Range(document.getLineNumber(textRange.startOffset), document.getLineNumber(textRange.endOffset)) } private fun filterSmartStepTargets( location: Location, lines: ClosedRange<Int>, targets: List<KotlinMethodSmartStepTarget>, debugProcess: DebugProcessImpl ): List<KotlinMethodSmartStepTarget> { val method = location.safeMethod() ?: return targets val targetFilterer = KotlinSmartStepTargetFilterer(targets, debugProcess) val targetFiltererAdapter = KotlinSmartStepTargetFiltererAdapter( lines, location, debugProcess.positionManager, targetFilterer ) val visitedOpcodes = mutableListOf<Int>() // During the first pass we traverse the whole method to collect its opcodes (the result is different // from method.bytecodes() because of the method visiting policy), and to check // that all smart step targets are filtered out. MethodBytecodeUtil.visit(method, Long.MAX_VALUE, object : OpcodeReportingMethodVisitor(targetFiltererAdapter) { override fun reportOpcode(opcode: Int) { ProgressManager.checkCanceled() visitedOpcodes.add(opcode) targetFiltererAdapter.reportOpcode(opcode) } override fun visitMethodInsn(opcode: Int, owner: String, name: String, descriptor: String, isInterface: Boolean) { targetFiltererAdapter.visitMethodInsn(opcode, owner, name, descriptor, isInterface) } }, true) // We failed to filter out all smart step targets during the traversal of the whole method, so // we can't guarantee the correctness of filtering. if (targetFilterer.getUnvisitedTargets().isNotEmpty()) { return targets } targetFilterer.reset() // During the second pass we traverse a part of the method (until location.codeIndex()), the rest opcodes // will be replaced with mock ones, so we stop when current opcode doesn't match the previously visited one. MethodBytecodeUtil.visit(method, location.codeIndex(), object : OpcodeReportingMethodVisitor(targetFiltererAdapter) { private var visitedOpcodeCnt = 0 private var stopVisiting = false override fun reportOpcode(opcode: Int) { ProgressManager.checkCanceled() if (stopVisiting || opcode != visitedOpcodes[visitedOpcodeCnt++]) { stopVisiting = true return } targetFiltererAdapter.reportOpcode(opcode) } override fun visitMethodInsn(opcode: Int, owner: String, name: String, descriptor: String, isInterface: Boolean) { if (stopVisiting) return targetFiltererAdapter.visitMethodInsn(opcode, owner, name, descriptor, isInterface) } }, true) return targetFilterer.getUnvisitedTargets() } private fun Range<Int>.toClosedRange() = from..to
plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/KotlinSmartStepIntoHandler.kt
2359278765
// "Import extension function 'H.unaryMinus'" "true" // ERROR: Unresolved reference: - package h import util.unaryMinus interface H fun f(h: H?) { -h } /* IGNORE_FIR */
plugins/kotlin/idea/tests/testData/quickfix/autoImports/unaryMinusOperator.after.kt
2075227933
// 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.observable import com.intellij.openapi.observable.dispatcher.SingleEventDispatcher import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.use import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import java.util.concurrent.atomic.AtomicInteger class SingleEventDispatcherTest { @Test fun `test event dispatching`() { val dispatcher = SingleEventDispatcher.create() val eventCounter = AtomicInteger() Disposer.newDisposable().use { disposable -> dispatcher.whenEventHappened(disposable) { eventCounter.incrementAndGet() } assertEquals(0, eventCounter.get()) dispatcher.fireEvent() assertEquals(1, eventCounter.get()) dispatcher.fireEvent() assertEquals(2, eventCounter.get()) dispatcher.fireEvent() assertEquals(3, eventCounter.get()) } dispatcher.fireEvent() assertEquals(3, eventCounter.get()) eventCounter.set(0) dispatcher.whenEventHappened { eventCounter.incrementAndGet() } assertEquals(0, eventCounter.get()) dispatcher.fireEvent() assertEquals(1, eventCounter.get()) dispatcher.fireEvent() assertEquals(2, eventCounter.get()) dispatcher.fireEvent() assertEquals(3, eventCounter.get()) } @Test fun `test event dispatching with ttl=1`() { val dispatcher = SingleEventDispatcher.create() val eventCounter = AtomicInteger() dispatcher.onceWhenEventHappened { eventCounter.incrementAndGet() } assertEquals(0, eventCounter.get()) dispatcher.fireEvent() assertEquals(1, eventCounter.get()) dispatcher.fireEvent() assertEquals(1, eventCounter.get()) eventCounter.set(0) Disposer.newDisposable().use { disposable -> dispatcher.onceWhenEventHappened(disposable) { eventCounter.incrementAndGet() } assertEquals(0, eventCounter.get()) } dispatcher.fireEvent() assertEquals(0, eventCounter.get()) } @Test fun `test event dispatching with ttl=N`() { val dispatcher = SingleEventDispatcher.create() val eventCounter = AtomicInteger() dispatcher.whenEventHappened(10) { eventCounter.incrementAndGet() } repeat(10) { assertEquals(it, eventCounter.get()) dispatcher.fireEvent() assertEquals(it + 1, eventCounter.get()) } dispatcher.fireEvent() assertEquals(10, eventCounter.get()) dispatcher.fireEvent() assertEquals(10, eventCounter.get()) eventCounter.set(0) Disposer.newDisposable().use { disposable -> dispatcher.whenEventHappened(10, disposable) { eventCounter.incrementAndGet() } repeat(5) { assertEquals(it, eventCounter.get()) dispatcher.fireEvent() assertEquals(it + 1, eventCounter.get()) } } dispatcher.fireEvent() assertEquals(5, eventCounter.get()) dispatcher.fireEvent() assertEquals(5, eventCounter.get()) } }
platform/platform-tests/testSrc/com/intellij/observable/SingleEventDispatcherTest.kt
239161670
public fun f { class C { fun f() { } val c: Int } }
plugins/kotlin/idea/tests/testData/stubs/MembersInLocalClass.kt
2489261163
// 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.ui.charts import com.intellij.ui.ColorUtil import com.intellij.ui.JBColor import com.intellij.util.ui.GraphicsUtil import com.intellij.util.ui.JBUI import org.intellij.lang.annotations.MagicConstant import java.awt.* import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.util.function.Consumer import javax.swing.JComponent import javax.swing.SwingConstants import kotlin.math.absoluteValue import kotlin.math.roundToInt import kotlin.math.sign interface ChartComponent { fun paintComponent(g: Graphics2D) } /** * Holds instance of ChartWrapper in which has been added. */ abstract class Overlay<T: ChartWrapper>: ChartComponent { var wrapper: ChartWrapper? = null set(value) { field = value afterChartInitialized() } var mouseLocation: Point? = null /** * Typed value for {@code wrapper}. * * Normally wrapper is already initialized when added to ChartWrapper. */ val chart: T @Suppress("UNCHECKED_CAST") get() = wrapper as T open fun afterChartInitialized() { } fun Point.toChartSpace(): Point? = wrapper?.let { if (it.margins.left < x && x < it.width - it.margins.right && it.margins.top < y && y < it.height - it.margins.bottom) { Point(x - it.margins.left, y - it.margins.top) } else null } } interface XYChartComponent<X: Number, Y: Number> { val ranges: MinMax<X, Y> } abstract class GridChartWrapper<X: Number, Y: Number>: ChartWrapper(), XYChartComponent<X, Y> { abstract override val ranges: Grid<X, Y> val grid: Grid<X, Y> get() = ranges val gridWidth: Int get() = width - (margins.left + margins.right) val gridHeight: Int get() = height - (margins.top + margins.bottom) var gridColor: Color = JBColor(Color(0xF0F0F0), Color(0x313335)) var gridLabelColor: Color = ColorUtil.withAlpha(JBColor.foreground(), 0.6) protected fun paintGrid(grid: Graphics2D, chart: Graphics2D, xy: MinMax<X, Y>) { val gc = Color(gridColor.rgb) val gcd = gc.darker() val bounds = grid.clipBounds val xOrigin: Int = if (ranges.xOriginInitialized) findX(xy, ranges.xOrigin).toInt() else 0 val yOrigin: Int = if (ranges.yOriginInitialized) findY(xy, ranges.yOrigin).toInt() else height var tmp: Int // — helps to filter line drawing, when lines are met too often // draws vertical grid lines tmp = -1 ranges.xLines.apply { min = xy.xMin max = xy.xMax }.forEach { val gl = GridLine(it, xy, SwingConstants.VERTICAL).apply(ranges.xPainter::accept) val px = findGridLineX(gl, it).roundToInt() if (gl.paintLine) { if ((tmp - px).absoluteValue < 1) { return@forEach } else { tmp = px } grid.color = if (gl.majorLine) gcd else gc grid.drawLine(px, bounds.y, px, bounds.y + bounds.height) } gl.label?.let { label -> chart.color = gridLabelColor val (x, y) = findGridLabelOffset(gl, chart) chart.drawString(label, px + margins.left - x.toInt(), yOrigin - margins.bottom + y.toInt()) } } // draws horizontal grid lines tmp = -1 ranges.yLines.apply { min = xy.yMin max = xy.yMax }.forEach { val gl = GridLine(it, xy).apply(ranges.yPainter::accept) val py = findGridLineY(gl, it).roundToInt() if (gl.paintLine) { if ((tmp - py).absoluteValue < 1) { return@forEach } else { tmp = py } grid.color = if (gl.majorLine) gcd else gc grid.drawLine(bounds.x, py, bounds.x + bounds.width, py) } gl.label?.let { label -> chart.color = gridLabelColor val (x, y) = findGridLabelOffset(gl, chart) chart.drawString(label, xOrigin + margins.left - x.toInt(), py + margins.top + y.toInt() ) } } } protected open fun findGridLineX(gl: GridLine<X, Y, *>, x: X) = findX(gl.xy, x) protected open fun findGridLineY(gl: GridLine<X, Y, *>, y: Y) = findY(gl.xy, y) abstract fun findMinMax(): MinMax<X, Y> protected open fun findX(xy: MinMax<X, Y>, x: X): Double { val width = width - (margins.left + margins.right) return width * (x.toDouble() - xy.xMin.toDouble()) / (xy.xMax.toDouble() - xy.xMin.toDouble()) } protected open fun findY(xy: MinMax<X, Y>, y: Y): Double { val height = height - (margins.top + margins.bottom) return height - height * (y.toDouble() - xy.yMin.toDouble()) / (xy.yMax.toDouble() - xy.yMin.toDouble()) } protected open fun findGridLabelOffset(line: GridLine<*, *, *>, g: Graphics2D): Coordinates<Double, Double> { val s = JBUI.scale(4).toDouble() val b = g.fontMetrics.getStringBounds(line.label, null) val x = when (line.horizontalAlignment) { SwingConstants.RIGHT -> -s SwingConstants.CENTER -> b.width / 2 SwingConstants.LEFT -> b.width + s else -> -s } val y = b.height - when (line.verticalAlignment) { SwingConstants.TOP -> b.height + s SwingConstants.CENTER -> b.height / 2 + s / 2 // compensate SwingConstants.BOTTOM -> 0.0 else -> 0.0 } return x to y } } abstract class ChartWrapper : ChartComponent { var width: Int = 0 private set var height: Int = 0 private set var background: Color = JBColor.background() var overlays: List<ChartComponent> = mutableListOf() set(value) { field.forEach { if (it is Overlay<*>) it.wrapper = null } (field as MutableList<ChartComponent>).addAll(value) field.forEach { if (it is Overlay<*>) it.wrapper = this } } var margins = Insets(0, 0, 0, 0) open fun paintOverlay(g: Graphics2D) { overlays.forEach { it.paintComponent(g) } } open val component: JComponent by lazy { createCentralPanel().apply { with(MouseAware()) { addMouseMotionListener(this) addMouseListener(this) } } } fun update() = component.repaint() protected open fun createCentralPanel(): JComponent = CentralPanel() protected var mouseLocation: Point? = null private set(value) { field = value overlays.forEach { if (it is Overlay<*>) it.mouseLocation = value } } private inner class MouseAware : MouseAdapter() { override fun mouseMoved(e: MouseEvent) { mouseLocation = e.point component.repaint() } override fun mouseEntered(e: MouseEvent) { mouseLocation = e.point component.repaint() } override fun mouseExited(e: MouseEvent) { mouseLocation = null component.repaint() } override fun mouseDragged(e: MouseEvent) { mouseLocation = e.point component.repaint() } } private inner class CentralPanel : JComponent() { override fun paintComponent(g: Graphics) { g.clip = Rectangle(0, 0, width, height) g.color = [email protected] (g as Graphics2D).fill(g.clip) [email protected] = height [email protected] = width val gridGraphics = (g.create(0, 0, [email protected], [email protected]) as Graphics2D).apply { setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED) setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE) GraphicsUtil.setupAntialiasing(this) } try { [email protected](gridGraphics) } finally { gridGraphics.dispose() } val overlayGraphics = (g.create() as Graphics2D).apply { setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED) setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE) GraphicsUtil.setupAntialiasing(this) } try { [email protected](overlayGraphics) } finally { overlayGraphics.dispose() } } } } open class Dataset<T> { var label: String? = null var lineColor: Paint? = JBColor.foreground() var fillColor: Paint? = null open var data: Iterable<T> = mutableListOf() fun add(vararg values: T) { addAll(values.toList()) } fun addAll(values: Collection<T>) { (data as? MutableList<T>)?.addAll(values) ?: throw UnsupportedOperationException() } fun Color.transparent(alpha: Double) = ColorUtil.withAlpha(this, alpha) } data class Coordinates<X: Number, Y: Number>(val x: X, val y: Y) { companion object { @JvmStatic fun <X: Number, Y: Number> of(x: X, y: Y) : Coordinates<X, Y> = Coordinates(x, y) } } infix fun <X: Number, Y: Number> X.to(y: Y): Coordinates<X, Y> = Coordinates(this, y) open class MinMax<X: Number, Y: Number> { lateinit var xMin: X private val xMinInitialized get() = this::xMin.isInitialized lateinit var xMax: X val xMaxInitialized get() = this::xMax.isInitialized lateinit var yMin: Y private val yMinInitialized get() = this::yMin.isInitialized lateinit var yMax: Y val yMaxInitialized get() = this::yMax.isInitialized fun process(point: Coordinates<X, Y>) { val (x, y) = point process(x, y) } fun process(x: X, y: Y) { processX(x) processY(y) } private fun processX(x: X) { xMin = if (!xMinInitialized || xMin.toDouble() > x.toDouble()) x else xMin xMax = if (!xMaxInitialized || xMax.toDouble() < x.toDouble()) x else xMax } private fun processY(y: Y) { yMin = if (!yMinInitialized || yMin.toDouble() > y.toDouble()) y else yMin yMax = if (!yMaxInitialized || yMax.toDouble() < y.toDouble()) y else yMax } operator fun times(other: MinMax<X, Y>): MinMax<X, Y> { val my = MinMax<X, Y>() if (this.xMinInitialized) my.xMin = this.xMin else if (other.xMinInitialized) my.xMin = other.xMin if (this.xMaxInitialized) my.xMax = this.xMax else if (other.xMaxInitialized) my.xMax = other.xMax if (this.yMinInitialized) my.yMin = this.yMin else if (other.yMinInitialized) my.yMin = other.yMin if (this.yMaxInitialized) my.yMax = this.yMax else if (other.yMaxInitialized) my.yMax = other.yMax return my } operator fun plus(other: MinMax<X, Y>) : MinMax<X, Y> { val my = MinMax<X, Y>() help(this.xMinInitialized, this::xMin, other.xMinInitialized, other::xMin, -1, my::xMin.setter) help(this.xMaxInitialized, this::xMax, other.xMaxInitialized, other::xMax, 1, my::xMax.setter) help(this.yMinInitialized, this::yMin, other.yMinInitialized, other::yMin, -1, my::yMin.setter) help(this.yMaxInitialized, this::yMax, other.yMaxInitialized, other::yMax, 1, my::yMax.setter) return my } private fun <T: Number> help(thisInitialized: Boolean, thisGetter: () -> T, otherInitialized: Boolean, otherGetter: () -> T, sign: Int, calc: (T) -> Unit) { when { thisInitialized && otherInitialized -> { val thisValue = thisGetter().toDouble() val thatValue = otherGetter().toDouble() calc(if (thisValue.compareTo(thatValue).sign == sign) thisGetter() else otherGetter()) } thisInitialized && !otherInitialized -> calc((thisGetter())) !thisInitialized && otherInitialized -> calc(otherGetter()) } } operator fun component1(): X = xMin operator fun component2(): X = xMax operator fun component3(): Y = yMin operator fun component4(): Y = yMax val isInitialized get() = xMinInitialized && xMaxInitialized && yMinInitialized && yMaxInitialized } class Grid<X: Number, Y: Number>: MinMax<X, Y>() { lateinit var xOrigin: X val xOriginInitialized get() = this::xOrigin.isInitialized var xLines: ValueIterable<X> = ValueIterable.createStub() var xPainter: (Consumer<GridLine<X, Y, X>>) = Consumer { } lateinit var yOrigin: Y val yOriginInitialized get() = this::yOrigin.isInitialized var yLines: ValueIterable<Y> = ValueIterable.createStub() var yPainter: (Consumer<GridLine<X, Y, Y>>) = Consumer { } } class GridLine<X: Number, Y: Number, T: Number>(val value: T, @get:JvmName("getXY") val xy: MinMax<X, Y>, @MagicConstant val orientation: Int = SwingConstants.HORIZONTAL) { var paintLine = true var majorLine = false var label: String? = null @MagicConstant var horizontalAlignment = SwingConstants.CENTER @MagicConstant var verticalAlignment = SwingConstants.BOTTOM } abstract class ValueIterable<X: Number> : Iterable<X> { lateinit var min: X lateinit var max: X open fun prepare(min: X, max: X): ValueIterable<X> { this.min = min this.max = max return this } companion object { fun <T: Number> createStub(): ValueIterable<T> { return object: ValueIterable<T>() { val iter = object: Iterator<T> { override fun hasNext() = false override fun next(): T { error("not implemented") } } override fun iterator(): Iterator<T> = iter } } } }
platform/platform-impl/src/com/intellij/ui/charts/ChartWrapper.kt
803818469
fun foo(p: Any?, c: Collection<String>) { for (e in c) { print(p!!) } <caret>xxx }
plugins/kotlin/idea/tests/testData/resolve/partialBodyResolve/For1.kt
642435644
package com.kingz.functiontest import androidx.test.ext.junit.runners.AndroidJUnit4 import com.kingz.database.DatabaseApplication import com.kingz.database.dao.SongDao_Impl import com.zeke.kangaroo.utils.ZLog import com.zeke.test.BaseInstrumentedTest import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith /** * author:ZekeWang * date:2021/1/15 * description: */ @RunWith(AndroidJUnit4::class) class ApplicationTest : BaseInstrumentedTest(){ @Test fun testFindMethod(){ val app = DatabaseApplication.getInstance() val declaredMethod = DatabaseApplication::class.java.getDeclaredMethod("getSongDao") declaredMethod.isAccessible = true val songDao = declaredMethod.invoke(app) if(songDao is SongDao_Impl){ ZLog.d("Get sondao") } assertTrue(songDao is SongDao_Impl) } }
app/src/androidTest/java/com/kingz/functiontest/ApplicationTest.kt
1481639840
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package training.actions import com.intellij.lang.Language import com.intellij.lang.LanguageExtensionPoint import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.ex.ComboBoxAction import com.intellij.openapi.util.NlsSafe import training.lang.LangManager import training.lang.LangSupport import training.learn.LearnBundle import training.ui.LearnToolWindow import training.util.resetPrimaryLanguage import javax.swing.JComponent internal class ChooseProgrammingLanguageForLearningAction(private val learnToolWindow: LearnToolWindow) : ComboBoxAction() { override fun createPopupActionGroup(button: JComponent?): DefaultActionGroup { val allActionsGroup = DefaultActionGroup() val supportedLanguagesExtensions = LangManager.getInstance().supportedLanguagesExtensions.sortedBy { it.language } for (langSupportExt: LanguageExtensionPoint<LangSupport> in supportedLanguagesExtensions) { val languageId = langSupportExt.language val displayName = Language.findLanguageByID(languageId)?.displayName ?: continue allActionsGroup.add(SelectLanguageAction(languageId, displayName)) } return allActionsGroup } override fun update(e: AnActionEvent) { val langSupport = LangManager.getInstance().getLangSupport() if (langSupport != null) { e.presentation.text = getDisplayName(langSupport) } e.presentation.description = LearnBundle.message("learn.choose.language.description.combo.box") } private inner class SelectLanguageAction(private val languageId: String, @NlsSafe displayName: String) : AnAction(displayName) { override fun actionPerformed(e: AnActionEvent) { val ep = LangManager.getInstance().supportedLanguagesExtensions.singleOrNull { it.language == languageId } ?: return resetPrimaryLanguage(ep.instance) learnToolWindow.setModulesPanel() } } } @NlsSafe private fun getDisplayName(language: LangSupport) = Language.findLanguageByID(language.primaryLanguage)?.displayName ?: LearnBundle.message("unknown.language.name")
plugins/ide-features-trainer/src/training/actions/ChooseProgrammingLanguageForLearningAction.kt
4006426149
// WITH_RUNTIME fun test(list: List<Int>) { list.filter { it > 1 }.filter { it > 2 }.let<caret> { println(it) } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/complexRedundantLet/callChain.kt
2503900740
// FIR_IDENTICAL public StringMethod() : String { } open class StringMy() { } public class Test : String<caret> { } // EXIST: StringMy // EXIST: String // ABSENT: StringMethod // FIR_COMPARISON
plugins/kotlin/completion/tests/testData/basic/common/InTypeAnnotation.kt
1777376353
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.ring import org.jetbrains.benchmarksLauncher.Random var globalAddendum = 0 open class LambdaBenchmark { private inline fun <T> runLambda(x: () -> T): T = x() private fun <T> runLambdaNoInline(x: () -> T): T = x() init { globalAddendum = Random.nextInt(20) } //Benchmark fun noncapturingLambda(): Int { var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { x += runLambda { globalAddendum } } return x } //Benchmark fun noncapturingLambdaNoInline(): Int { var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { x += runLambdaNoInline { globalAddendum } } return x } //Benchmark fun capturingLambda(): Int { val addendum = globalAddendum + 1 var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { x += runLambda { addendum } } return x } //Benchmark fun capturingLambdaNoInline(): Int { val addendum = globalAddendum + 1 var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { x += runLambdaNoInline { addendum } } return x } //Benchmark fun mutatingLambda(): Int { var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { runLambda { x += globalAddendum } } return x } //Benchmark fun mutatingLambdaNoInline(): Int { var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { runLambdaNoInline { x += globalAddendum } } return x } //Benchmark fun methodReference(): Int { var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { x += runLambda(::referenced) } return x } //Benchmark fun methodReferenceNoInline(): Int { var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { x += runLambdaNoInline(::referenced) } return x } } private fun referenced(): Int { return globalAddendum }
performance/ring/src/main/kotlin/org/jetbrains/ring/LambdaBenchmark.kt
2905608971
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.js.resolve.diagnostics import com.intellij.psi.PsiElement import org.jetbrains.kotlin.builtins.ReflectionTypes import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.diagnostics.Errors.UNSUPPORTED import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.checkers.AbstractReflectionApiCallChecker import org.jetbrains.kotlin.resolve.calls.checkers.CallCheckerContext import org.jetbrains.kotlin.storage.StorageManager import org.jetbrains.kotlin.storage.getValue private val ALLOWED_KCLASS_MEMBERS = setOf("simpleName", "isInstance") class JsReflectionAPICallChecker(private val module: ModuleDescriptor, storageManager: StorageManager) : AbstractReflectionApiCallChecker(module, storageManager) { override val isWholeReflectionApiAvailable: Boolean get() = false override fun report(element: PsiElement, context: CallCheckerContext) { context.trace.report(UNSUPPORTED.on(element, "This reflection API is not supported yet in JavaScript")) } private val kClass by storageManager.createLazyValue { ReflectionTypes(module).kClass } override fun isAllowedReflectionApi(descriptor: CallableDescriptor, containingClass: ClassDescriptor): Boolean = super.isAllowedReflectionApi(descriptor, containingClass) || DescriptorUtils.isSubclass(containingClass, kClass) && descriptor.name.asString() in ALLOWED_KCLASS_MEMBERS }
phizdets/phizdetsc/src/org/jetbrains/kotlin/js/resolve/diagnostics/JsReflectionAPICallChecker.kt
1299790999
package com.simplemobiletools.calendar.pro.fragments import android.content.Intent import android.os.Bundle import android.os.Handler import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.RelativeLayout import androidx.fragment.app.Fragment import com.simplemobiletools.calendar.pro.R import com.simplemobiletools.calendar.pro.activities.MainActivity import com.simplemobiletools.calendar.pro.activities.SimpleActivity import com.simplemobiletools.calendar.pro.adapters.DayEventsAdapter import com.simplemobiletools.calendar.pro.extensions.config import com.simplemobiletools.calendar.pro.extensions.eventsHelper import com.simplemobiletools.calendar.pro.extensions.getViewBitmap import com.simplemobiletools.calendar.pro.extensions.printBitmap import com.simplemobiletools.calendar.pro.helpers.* import com.simplemobiletools.calendar.pro.interfaces.NavigationListener import com.simplemobiletools.calendar.pro.models.Event import com.simplemobiletools.commons.extensions.* import kotlinx.android.synthetic.main.fragment_day.view.* import kotlinx.android.synthetic.main.top_navigation.view.* class DayFragment : Fragment() { var mListener: NavigationListener? = null private var mTextColor = 0 private var mDayCode = "" private var lastHash = 0 private lateinit var mHolder: RelativeLayout override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_day, container, false) mHolder = view.day_holder mDayCode = requireArguments().getString(DAY_CODE)!! setupButtons() return view } override fun onResume() { super.onResume() updateCalendar() } private fun setupButtons() { mTextColor = requireContext().getProperTextColor() mHolder.top_left_arrow.apply { applyColorFilter(mTextColor) background = null setOnClickListener { mListener?.goLeft() } val pointerLeft = requireContext().getDrawable(R.drawable.ic_chevron_left_vector) pointerLeft?.isAutoMirrored = true setImageDrawable(pointerLeft) } mHolder.top_right_arrow.apply { applyColorFilter(mTextColor) background = null setOnClickListener { mListener?.goRight() } val pointerRight = requireContext().getDrawable(R.drawable.ic_chevron_right_vector) pointerRight?.isAutoMirrored = true setImageDrawable(pointerRight) } val day = Formatter.getDayTitle(requireContext(), mDayCode) mHolder.top_value.apply { text = day contentDescription = text setOnClickListener { (activity as MainActivity).showGoToDateDialog() } setTextColor(context.getProperTextColor()) } } fun updateCalendar() { val startTS = Formatter.getDayStartTS(mDayCode) val endTS = Formatter.getDayEndTS(mDayCode) context?.eventsHelper?.getEvents(startTS, endTS) { receivedEvents(it) } } private fun receivedEvents(events: List<Event>) { val newHash = events.hashCode() if (newHash == lastHash || !isAdded) { return } lastHash = newHash val replaceDescription = requireContext().config.replaceDescription val sorted = ArrayList(events.sortedWith(compareBy({ !it.getIsAllDay() }, { it.startTS }, { it.endTS }, { it.title }, { if (replaceDescription) it.location else it.description }))) activity?.runOnUiThread { updateEvents(sorted) } } private fun updateEvents(events: ArrayList<Event>) { if (activity == null) return DayEventsAdapter(activity as SimpleActivity, events, mHolder.day_events, mDayCode) { editEvent(it as Event) }.apply { mHolder.day_events.adapter = this } if (requireContext().areSystemAnimationsEnabled) { mHolder.day_events.scheduleLayoutAnimation() } } private fun editEvent(event: Event) { Intent(context, getActivityToOpen(event.isTask())).apply { putExtra(EVENT_ID, event.id) putExtra(EVENT_OCCURRENCE_TS, event.startTS) putExtra(IS_TASK_COMPLETED, event.isTaskCompleted()) startActivity(this) } } fun printCurrentView() { mHolder.apply { top_left_arrow.beGone() top_right_arrow.beGone() top_value.setTextColor(resources.getColor(R.color.theme_light_text_color)) (day_events.adapter as? DayEventsAdapter)?.togglePrintMode() Handler().postDelayed({ requireContext().printBitmap(day_holder.getViewBitmap()) Handler().postDelayed({ top_left_arrow.beVisible() top_right_arrow.beVisible() top_value.setTextColor(requireContext().getProperTextColor()) (day_events.adapter as? DayEventsAdapter)?.togglePrintMode() }, 1000) }, 1000) } } }
app/src/main/kotlin/com/simplemobiletools/calendar/pro/fragments/DayFragment.kt
2215177259
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package kotlin.sequences import kotlin.comparisons.* import kotlin.native.internal.FixmeConcurrency @FixmeConcurrency internal actual class ConstrainedOnceSequence<T> actual constructor(sequence: Sequence<T>) : Sequence<T> { // TODO: not MT friendly. private var sequenceRef : Sequence<T>? = sequence override actual fun iterator(): Iterator<T> { val sequence = sequenceRef if (sequence == null) throw IllegalStateException("This sequence can be consumed only once.") sequenceRef = null return sequence.iterator() } }
runtime/src/main/kotlin/kotlin/sequences/Sequences.kt
3401970452
package usage import javapackage.one.JavaClassOne import javapackage.one.JavaClassOne.MAGIC_CONST import javapackage.one.JavaClassOne.build class KotlinClassOne { fun update(javaClassOne: JavaClassOne) { } } class KotlinClassTwo fun usage() { val javaClass = JavaClassOne() // expect "val two = KotlinClassTwo()" after kotlinClassOne, KT-40867 val kotlinClassOne = KotlinClassOne() val kotlinOther = KotlinClassOne() kotlinClassOne.update(javaClass) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(KotlinClassTwo()) println(kotlinClassOne) System.err.println(result) build(result.convertToInt() + javaClass.hashCode() + javaClass.convertToInt() + MAGIC_CONST + build(javaClass.field).field) } val kotlinOne = KotlinClassOne() val kotlinTwo = KotlinClassTwo() fun a() { val javaClassOne = JavaClassOne() val kotlinOther = KotlinClassOne() kotlinOne.update(javaClassOne) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build( result.convertToInt() + javaClassOne.hashCode() + javaClassOne.convertToInt() + MAGIC_CONST + build( javaClassOne.field ).field ) val d = JavaClassOne() val kotlinOther = KotlinClassOne() kotlinOne.update(d) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + d.hashCode() + d.convertToInt() + MAGIC_CONST + build(d.field).field) d.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } d.also { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } with(d) { val kotlinOther = KotlinClassOne() kotlinOne.update(this) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + hashCode() + convertToInt() + MAGIC_CONST + build(field).field) } with(d) out@{ with(4) { val kotlinOther = KotlinClassOne() kotlinOne.update(this@out) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + [email protected]() + [email protected]() + MAGIC_CONST + build([email protected]).field) } } } fun a2() { val d: JavaClassOne? = null if (d != null) { val kotlinOther = KotlinClassOne() kotlinOne.update(d) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + d.hashCode() + d.convertToInt() + MAGIC_CONST + build(d.field).field) } d?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } d?.also { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } with(d) { this?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } } with(d) out@{ with(4) { this@out?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } } } } fun a3() { val d: JavaClassOne? = null val a1 = d?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } val a2 = d?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } val a3 = d?.also { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } val a4 = with(d) { this?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } } val a5 = with(d) out@{ with(4) { this@out?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } } } } fun a4() { val d: JavaClassOne? = null d?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) }?.convertToInt()?.dec() val a2 = d?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } a2?.convertToInt()?.toLong() val also = d?.also { it.apply(kotlinOne, kotlinTwo) } if (also != null) { val kotlinOther = KotlinClassOne() kotlinOne.update(also) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + also.hashCode() + also.convertToInt() + MAGIC_CONST + build(also.field).field) } val a4 = with(d) { this?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } }?.convertToInt() val a5 = with(d) out@{ with(4) { this@out?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } } }?.convertToInt() val a6 = a4?.let { out -> a5?.let { out + it } } } fun JavaClassOne.b(): Int? { val kotlinOther = KotlinClassOne() kotlinOne.update(this) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) return build(result.convertToInt() + hashCode() + convertToInt() + MAGIC_CONST + build(field).field).convertToInt() } fun JavaClassOne.c(): Int { val kotlinOther = KotlinClassOne() kotlinOne.update(this) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) return build(result.convertToInt() + this.hashCode() + this.convertToInt() + MAGIC_CONST + build(this.field).field).convertToInt() } fun d(d: JavaClassOne): Int { val kotlinOther = KotlinClassOne() kotlinOne.update(d) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) return build(result.convertToInt() + d.hashCode() + d.convertToInt() + MAGIC_CONST + build(d.field).field).convertToInt() }
plugins/kotlin/idea/tests/testData/refactoring/inlineMultiFile/fromJavaToKotlin/complexJavaToKotlin2/after/usage/main.kt
1160621547
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.gradleJava.testing.native import com.intellij.openapi.module.Module import org.jetbrains.kotlin.ide.konan.KotlinNativeRunConfigurationProvider import org.jetbrains.kotlin.idea.gradleJava.run.AbstractKotlinMultiplatformTestClassGradleConfigurationProducer import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.konan.isNative class KotlinMultiplatformNativeTestClassGradleConfigurationProducer : AbstractKotlinMultiplatformTestClassGradleConfigurationProducer(), KotlinNativeRunConfigurationProvider { override val isForTests: Boolean get() = true override fun isApplicable(module: Module, platform: TargetPlatform) = platform.isNative() }
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/testing/native/KotlinMultiplatformNativeTestClassGradleConfigurationProducer.kt
1738827951
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.log.ui.table.column.util import com.github.benmanes.caffeine.cache.Caffeine import com.intellij.openapi.util.Disposer import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.vcs.log.CommitId import com.intellij.vcs.log.data.util.VcsCommitsDataLoader class CachingVcsCommitsDataLoader<T>( private val loader: VcsCommitsDataLoader<T>, cacheSize: Long = 150 ) : VcsCommitsDataLoader<T> { private val cache = Caffeine.newBuilder().maximumSize(cacheSize).build<CommitId, T>() init { Disposer.register(this, loader) } override fun loadData(commits: List<CommitId>, onChange: (Map<CommitId, T>) -> Unit) { loader.loadData(commits) { cache.putAll(it) onChange(it) } } @RequiresEdt fun getData(commit: CommitId): T? = cache.getIfPresent(commit) override fun dispose() { cache.invalidateAll() } }
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/table/column/util/CachingVcsCommitsDataLoader.kt
745722685
internal abstract val noofGears: Int
plugins/kotlin/j2k/old/tests/testData/fileOrElement/function/abstractMethod.kt
1229918773
// FIR_COMPARISON fun foo(p: Iterable<D>) { p.filter { it.<caret> } } interface D { fun bar() } // EXIST: bar
plugins/kotlin/completion/tests/testData/basic/common/InLambda.kt
194815499
class C { constructor() <selection> <caret>init { } </selection> fun foo() { } // comment val bar = 1 }
plugins/kotlin/idea/tests/testData/wordSelection/ClassMember2/2.kt
3901060968
// "Replace with 's.newFun(this)'" "true" open class Base { @Deprecated("", ReplaceWith("s.newFun(this)")) fun oldFun(s: String){} open inner class Inner } class Derived : Base() { inner class InnerDerived : Base.Inner() { fun foo() { <caret>oldFun("a") } } } fun String.newFun(x: Base){}
plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/changeThisToOuterThis.kt
820791557
class Bla : ImplementMe { override fun someF(l: MutableList<Int>?, integer: Int) { } }
plugins/kotlin/idea/tests/testData/refactoring/changeSignature/MutableFlexibleType5After.1.kt
1848765870
package com.jetbrains.packagesearch.intellij.plugin.maven import com.intellij.openapi.project.Project import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleType import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleTypeTerm import com.jetbrains.packagesearch.intellij.plugin.maven.configuration.PackageSearchMavenConfiguration import icons.OpenapiIcons import javax.swing.Icon internal object MavenProjectModuleType : ProjectModuleType { override val icon: Icon get() = OpenapiIcons.RepositoryLibraryLogo override val packageIcon: Icon get() = icon override fun terminologyFor(term: ProjectModuleTypeTerm): String = PackageSearchBundle.message("packagesearch.terminology.dependency.scope") override fun defaultScope(project: Project): String = PackageSearchMavenConfiguration.getInstance(project).determineDefaultMavenScope() override fun userDefinedScopes(project: Project): List<String> = PackageSearchMavenConfiguration.getInstance(project).getMavenScopes() }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/maven/MavenProjectModuleType.kt
1866235109
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.decompiler.classFile import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.builtins.DefaultBuiltIns import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.contracts.ContractDeserializerImpl import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.NotFoundClasses import org.jetbrains.kotlin.idea.caches.IDEKotlinBinaryClassCache import org.jetbrains.kotlin.idea.decompiler.textBuilder.DeserializerForDecompilerBase import org.jetbrains.kotlin.idea.decompiler.textBuilder.LoggingErrorReporter import org.jetbrains.kotlin.idea.decompiler.textBuilder.ResolveEverythingToKotlinAnyLocalClassifierResolver import org.jetbrains.kotlin.incremental.components.LookupTracker import org.jetbrains.kotlin.load.java.structure.JavaClass import org.jetbrains.kotlin.load.java.structure.classId import org.jetbrains.kotlin.load.kotlin.* import org.jetbrains.kotlin.load.kotlin.KotlinClassFinder.Result.KotlinClass import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmProtoBufUtil import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.resolve.sam.SamConversionResolverImpl import org.jetbrains.kotlin.serialization.deserialization.ClassData import org.jetbrains.kotlin.serialization.deserialization.ClassDataFinder import org.jetbrains.kotlin.serialization.deserialization.DeserializationComponents import org.jetbrains.kotlin.serialization.deserialization.DeserializationConfiguration import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedPackageMemberScope import java.io.InputStream fun DeserializerForClassfileDecompiler(classFile: VirtualFile): DeserializerForClassfileDecompiler { val kotlinClassHeaderInfo = IDEKotlinBinaryClassCache.getInstance().getKotlinBinaryClassHeaderData(classFile) ?: error("Decompiled data factory shouldn't be called on an unsupported file: $classFile") val packageFqName = kotlinClassHeaderInfo.classId.packageFqName return DeserializerForClassfileDecompiler(classFile.parent!!, packageFqName) } class DeserializerForClassfileDecompiler( packageDirectory: VirtualFile, directoryPackageFqName: FqName ) : DeserializerForDecompilerBase(directoryPackageFqName) { override val builtIns: KotlinBuiltIns get() = DefaultBuiltIns.Instance private val classFinder = DirectoryBasedClassFinder(packageDirectory, directoryPackageFqName) override val deserializationComponents: DeserializationComponents init { val classDataFinder = DirectoryBasedDataFinder(classFinder, LOG) val notFoundClasses = NotFoundClasses(storageManager, moduleDescriptor) val annotationAndConstantLoader = BinaryClassAnnotationAndConstantLoaderImpl(moduleDescriptor, notFoundClasses, storageManager, classFinder) val configuration = object : DeserializationConfiguration { override val readDeserializedContracts: Boolean = true override val preserveDeclarationsOrdering: Boolean = true } deserializationComponents = DeserializationComponents( storageManager, moduleDescriptor, configuration, classDataFinder, annotationAndConstantLoader, packageFragmentProvider, ResolveEverythingToKotlinAnyLocalClassifierResolver(builtIns), LoggingErrorReporter(LOG), LookupTracker.DO_NOTHING, JavaFlexibleTypeDeserializer, emptyList(), notFoundClasses, ContractDeserializerImpl(configuration, storageManager), extensionRegistryLite = JvmProtoBufUtil.EXTENSION_REGISTRY, samConversionResolver = SamConversionResolverImpl(storageManager, samWithReceiverResolvers = emptyList()) ) } override fun resolveDeclarationsInFacade(facadeFqName: FqName): List<DeclarationDescriptor> { val packageFqName = facadeFqName.parent() assert(packageFqName == directoryPackageFqName) { "Was called for $facadeFqName; only members of $directoryPackageFqName package are expected." } val binaryClassForPackageClass = classFinder.findKotlinClass(ClassId.topLevel(facadeFqName)) val header = binaryClassForPackageClass?.classHeader val annotationData = header?.data val strings = header?.strings if (annotationData == null || strings == null) { LOG.error("Could not read annotation data for $facadeFqName from ${binaryClassForPackageClass?.classId}") return emptyList() } val (nameResolver, packageProto) = JvmProtoBufUtil.readPackageDataFrom(annotationData, strings) val membersScope = DeserializedPackageMemberScope( createDummyPackageFragment(header.packageName?.let(::FqName) ?: facadeFqName.parent()), packageProto, nameResolver, header.metadataVersion, JvmPackagePartSource(binaryClassForPackageClass, packageProto, nameResolver), deserializationComponents ) { emptyList() } return membersScope.getContributedDescriptors().toList() } companion object { private val LOG = Logger.getInstance(DeserializerForClassfileDecompiler::class.java) } } class DirectoryBasedClassFinder( val packageDirectory: VirtualFile, val directoryPackageFqName: FqName ) : KotlinClassFinder { override fun findKotlinClassOrContent(javaClass: JavaClass) = findKotlinClassOrContent(javaClass.classId!!) override fun findKotlinClassOrContent(classId: ClassId): KotlinClassFinder.Result? { if (classId.packageFqName != directoryPackageFqName) { return null } val targetName = classId.relativeClassName.pathSegments().joinToString("$", postfix = ".class") val virtualFile = packageDirectory.findChild(targetName) if (virtualFile != null && isKotlinWithCompatibleAbiVersion(virtualFile)) { return IDEKotlinBinaryClassCache.getInstance().getKotlinBinaryClass(virtualFile)?.let(::KotlinClass) } return null } // TODO override fun findMetadata(classId: ClassId): InputStream? = null // TODO override fun hasMetadataPackage(fqName: FqName): Boolean = false // TODO: load built-ins from packageDirectory? override fun findBuiltInsData(packageFqName: FqName): InputStream? = null } class DirectoryBasedDataFinder( val classFinder: DirectoryBasedClassFinder, val log: Logger ) : ClassDataFinder { override fun findClassData(classId: ClassId): ClassData? { val binaryClass = classFinder.findKotlinClass(classId) ?: return null val classHeader = binaryClass.classHeader val data = classHeader.data if (data == null) { log.error("Annotation data missing for ${binaryClass.classId}") return null } val strings = classHeader.strings if (strings == null) { log.error("String table not found in class ${binaryClass.classId}") return null } val (nameResolver, classProto) = JvmProtoBufUtil.readClassDataFrom(data, strings) return ClassData(nameResolver, classProto, classHeader.metadataVersion, KotlinJvmBinarySourceElement(binaryClass)) } }
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/decompiler/classFile/DeserializerForClassfileDecompiler.kt
2061837429
package foo fun a() { val <caret>x = 1 }
plugins/kotlin/idea/tests/testData/refactoring/copy/copyLocalVariable/before/foo/test.kt
1509645829
package p2 operator fun Runnable.plusAssign(p: Int): Unit = TODO() val v1 = 1 val v2 = 1 val v3 = 1
plugins/kotlin/idea/tests/testData/editor/optimizeImports/jvm/PlusAndPlusAssign.dependency2.kt
3676849157
// WITH_STDLIB class MyClass { fun foo() { val c = 2 c.div(2)<caret> c.div(c + 2 + c) + c.div(c) } }
plugins/kotlin/idea/tests/testData/intentions/convertToScope/convertToWith/withDifficultRenaming.kt
1965881319
val some = 12 class Some(someParam : Int) { init { fun internalFun(someInternal : Int) : Int { return some<caret> } } } // EXIST: some, someInternal, someParam
plugins/kotlin/completion/tests/testData/basic/common/InFunInClassInitializer.kt
2530391790
package lib.threejs @native("THREE.Geometry") open class Geometry { //Properties @native var id: Int = noImpl @native var name: String = noImpl @native var vertices: Array<Vector3> = noImpl @native var colors: Array<Color> = noImpl //@native var faces: Array<Triangle> = noImpl //@native var faceVertexUvs: Array<UV> = noImpl //@native var morphTargets: Vector3 = noImpl //@native var morphColors: Vector3 = noImpl //@native var morphNormals: Vector3 = noImpl @native var skinWeights: Vector3 = noImpl @native var skinIndices: Vector3 = noImpl //@native var boundingBox: Vector3 = noImpl @native var boundingSphere: Double = noImpl @native var hasTangents: Boolean = noImpl @native var dynamic: Boolean = noImpl @native var verticesNeedUpdate: Boolean = noImpl @native var elementsNeedUpdate: Boolean = noImpl @native var uvsNeedUpdate: Boolean = noImpl @native var normalsNeedUpdate: Boolean = noImpl @native var tangentsNeedUpdate: Boolean = noImpl @native var colorsNeedUpdate: Boolean = noImpl @native var lineDistancesNeedUpdate: Boolean = noImpl @native var buffersNeedUpdate: Boolean = noImpl @native var lineDistances: Array<Double> = noImpl //Functions fun applyMatrix(m: Matrix4): Unit = noImpl fun computeFaceNormals(): Unit = noImpl fun computeVertexNormals(): Unit = noImpl fun computeMorphNormals(): Unit = noImpl fun computeTangents(): Unit = noImpl fun computeBoundingBox(): Unit = noImpl fun computeBoundingSphere(): Unit = noImpl fun merge(geometry: Geometry, m: Matrix4, materialIndexOffset: Int): Unit = noImpl fun mergeVertices(): Unit = noImpl fun makeGroups(m: Matrix4): Unit = noImpl fun clone(m: Matrix4): Unit = noImpl fun dispose(m: Matrix4): Unit = noImpl fun computeLineDistances(m: Matrix4): Unit = noImpl } @native("THREE.PlaneGeometry") open class PlaneGeometry(width: Double, height: Double) : Geometry() { } @native("THREE.Object3D") open class Object3D( @native var parent: Object3D = noImpl, @native var children: Array<Object3D> = noImpl, @native var position: Vector3 = noImpl, @native var rotation: Euler = noImpl, @native var scale: Vector3 = noImpl ) { @native var castShadow: Boolean = noImpl @native var receiveShadow: Boolean = noImpl @native var shadow: dynamic = noImpl @native var int: Int = noImpl @native var uuid: String = noImpl @native var name: String = noImpl @native var matrix: Matrix4 = noImpl @native var matrixWorld: Matrix4 = noImpl @native var quaternion: Quaternion = noImpl @native var matrixAutoUpdate: Boolean = noImpl @native var matrixWorldNeedsUpdate: Boolean = noImpl @native var material: Material = noImpl @native var visible: Boolean //Functions fun add(obj: Object3D): Unit = noImpl fun remove(obj: Object3D): Unit = noImpl @native fun rotateX(radians: Double): Unit = noImpl @native fun rotateY(radians: Double): Unit = noImpl @native fun rotateZ(radians: Double): Unit = noImpl @native fun updateMatrix(): Unit = noImpl @native fun updateMatrixWorld(): Unit = noImpl @native fun translateOnAxis(axis: Vector3, distance: Number): Object3D = noImpl @native fun applyMatrix(matrix: Matrix4): Unit = noImpl @native fun getWorldPosition(optionalTarget: Vector3): Vector3 = noImpl @native fun getWorldQuaternion(optionalTarget: Quaternion): Quaternion = noImpl @native fun getWorldRotation(optionalTarget: Quaternion): Quaternion = noImpl @native open fun clone(recursive: Boolean): Object3D = noImpl } @native("THREE.Group") open class Group() : Object3D() { }
client/src/lib/threejs/Core.kt
882393768
package com.amar.NoteDirector.asynctasks import android.content.Context import android.os.AsyncTask import com.simplemobiletools.commons.extensions.getFilenameFromPath import com.simplemobiletools.commons.extensions.hasWriteStoragePermission import com.simplemobiletools.commons.extensions.internalStoragePath import com.simplemobiletools.commons.extensions.sdCardPath import com.amar.NoteDirector.extensions.config import com.amar.NoteDirector.extensions.containsNoMedia import com.amar.NoteDirector.extensions.getFilesFrom import com.amar.NoteDirector.models.Directory import com.amar.NoteDirector.models.Medium import java.io.File import java.util.* class GetDirectoriesAsynctask(val context: Context, val isPickVideo: Boolean, val isPickImage: Boolean, val callback: (dirs: ArrayList<Directory>) -> Unit) : AsyncTask<Void, Void, ArrayList<Directory>>() { var config = context.config var shouldStop = false val showHidden = config.shouldShowHidden override fun doInBackground(vararg params: Void): ArrayList<Directory> { if (!context.hasWriteStoragePermission()) return ArrayList() val media = context.getFilesFrom("default", isPickImage, isPickVideo) val excludedPaths = config.excludedFolders val includedPaths = config.includedFolders val directories = groupDirectories(media) val dirs = ArrayList(directories.values .filter { File(it.path).exists() }) .filter { shouldFolderBeVisible(it.path, excludedPaths, includedPaths) } as ArrayList<Directory> Directory.sorting = config.directorySorting dirs.sort() return movePinnedToFront(dirs) } private fun groupDirectories(media: ArrayList<Medium>): Map<String, Directory> { val albumCovers = config.parseAlbumCovers() val hidden = context.resources.getString(com.amar.NoteDirector.R.string.hidden) val directories = LinkedHashMap<String, Directory>() for ((name, path, isVideo, dateModified, dateTaken, size) in media) { if (shouldStop) cancel(true) val parentDir = File(path).parent ?: continue if (directories.containsKey(parentDir.toLowerCase())) { val directory = directories[parentDir.toLowerCase()]!! val newImageCnt = directory.mediaCnt + 1 directory.mediaCnt = newImageCnt directory.addSize(size) } else { var dirName = parentDir.getFilenameFromPath() if (parentDir == context.internalStoragePath) { dirName = context.getString(com.amar.NoteDirector.R.string.internal) } else if (parentDir == context.sdCardPath) { dirName = context.getString(com.amar.NoteDirector.R.string.sd_card) } if (File(parentDir).containsNoMedia()) { dirName += " $hidden" if (!showHidden) continue } var thumbnail = path albumCovers.forEach { if (it.path == parentDir && File(it.tmb).exists()) { thumbnail = it.tmb } } val directory = Directory(parentDir, thumbnail, dirName, 1, dateModified, dateTaken, size) directories.put(parentDir.toLowerCase(), directory) } } return directories } private fun shouldFolderBeVisible(path: String, excludedPaths: MutableSet<String>, includedPaths: MutableSet<String>): Boolean { val file = File(path) return if (includedPaths.contains(path)) { true } else if (isThisOrParentExcluded(path, excludedPaths, includedPaths)) { false } else if (!config.shouldShowHidden && file.isDirectory && file.canonicalFile == file.absoluteFile) { var containsNoMediaOrDot = file.containsNoMedia() || path.contains("/.") if (!containsNoMediaOrDot) { containsNoMediaOrDot = checkParentHasNoMedia(file.parentFile) } !containsNoMediaOrDot } else { true } } private fun checkParentHasNoMedia(file: File): Boolean { var curFile = file while (true) { if (curFile.containsNoMedia()) { return true } curFile = curFile.parentFile if (curFile.absolutePath == "/") break } return false } private fun isThisOrParentExcluded(path: String, excludedPaths: MutableSet<String>, includedPaths: MutableSet<String>) = includedPaths.none { path.startsWith(it) } && excludedPaths.any { path.startsWith(it) } private fun movePinnedToFront(dirs: ArrayList<Directory>): ArrayList<Directory> { val foundFolders = ArrayList<Directory>() val pinnedFolders = config.pinnedFolders dirs.forEach { if (pinnedFolders.contains(it.path)) foundFolders.add(it) } dirs.removeAll(foundFolders) dirs.addAll(0, foundFolders) return dirs } override fun onPostExecute(dirs: ArrayList<Directory>) { super.onPostExecute(dirs) callback(dirs) } }
app/src/main/kotlin/com/amar/notesapp/asynctasks/GetDirectoriesAsynctask.kt
1556846680
package pt.joaomneto.titancompanion.adventure import android.app.AlertDialog import android.content.DialogInterface import android.widget.Button import android.widget.EditText import android.widget.ListView import org.junit.Assert.assertTrue import org.junit.Test import org.robolectric.Shadows import org.robolectric.shadows.ShadowDialog import pt.joaomneto.titancompanion.R import pt.joaomneto.titancompanion.adventure.impl.fragments.AdventureNotesFragment import java.util.Properties import kotlin.reflect.KClass abstract class AdventureNotesTest<T : Adventure, U : AdventureNotesFragment>( adventureClass: KClass<T>, fragmentClass: KClass<U>, savegame: Properties ) : TCAdventureBaseTest<T, U>( adventureClass, fragmentClass, savegame ) { @Test fun `when clicking the add note button it adds an note to the list via a dialog`() { loadActivity() fragment.findComponent<Button>(R.id.buttonAddNote).performClick() val dialog = ShadowDialog.getLatestDialog() as AlertDialog val inputField = dialog.findViewById<EditText>(R.id.alert_editText_field) inputField.setText("n1") dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick() val listView = fragment.findComponent<ListView>(R.id.noteList) val shadowListView = Shadows.shadowOf(listView) assertTrue(shadowListView.findIndexOfItemContainingText("n1") >= 0) } @Test fun `when long pressing an note item it removes an item from the list via a confirmation dialog`() { loadActivity("notes" to "n1#n2") val listView = fragment.findComponent<ListView>(R.id.noteList) val shadowListView = Shadows.shadowOf(listView) listView.onItemLongClickListener.onItemLongClick( null, null, shadowListView.findIndexOfItemContainingText("n1"), -1 ) val dialog = ShadowDialog.getLatestDialog() as AlertDialog dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick() assertTrue(shadowListView.findIndexOfItemContainingText("n1") < 0) } }
src/test/java/pt/joaomneto/titancompanion/adventure/AdventureNotesTest.kt
1558452595
package pt.joaomneto.titancompanion import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import org.junit.runner.RunWith import pt.joaomneto.titancompanion.consts.FightingFantasyGamebook.ARMIES_OF_DEATH @LargeTest @RunWith(AndroidJUnit4::class) class TestAOD : TestST() { override val gamebook = ARMIES_OF_DEATH }
src/androidTest/java/pt/joaomneto/titancompanion/TestAOD.kt
2621273668
package net.amigochi.amigochi import android.app.Application class KAmigochiApp: Application(){ override fun onCreate() { super.onCreate() } }
app/src/main/kotlin/net/amigochi/amigochi/KAmigochiApp.kt
81617776
package com.mycollab.module.project.service import com.mycollab.module.project.ProjectTypeConstants import com.mycollab.test.DataSet import com.mycollab.test.rule.DbUnitInitializerRule import com.mycollab.test.spring.IntegrationServiceTest import org.assertj.core.api.Assertions.assertThat import org.assertj.core.groups.Tuple.tuple import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.junit.jupiter.SpringExtension @ExtendWith(SpringExtension::class, DbUnitInitializerRule::class) class TicketRelationServiceTest : IntegrationServiceTest() { @Autowired private lateinit var ticketRelationService: TicketRelationService @DataSet @Test fun testFindRelatedTickets() { val ticketRelations = ticketRelationService.findRelatedTickets(1, ProjectTypeConstants.BUG) assertThat(ticketRelations.size).isEqualTo(3) assertThat(ticketRelations).extracting("ticketKey", "ticketid", "ticketName", "ticketStatus", "tickettype", "typeKey", "typeid", "typeName", "typeStatus", "type", "rel", "ltr") .contains(tuple(2, 1, "Bug 1", "ReOpen","Project-Bug", 1, 1, "Task 1", "Open","Project-Task", "Duplicated", true), tuple(4, 2, "Task 2", "Closed","Project-Task", 2, 1, "Bug 1", "ReOpen", "Project-Bug", "Block", false), tuple(2, 1, "Bug 1", "ReOpen", "Project-Bug", 3, 2, "Bug 2", "Open", "Project-Bug", "Block", true)) } }
mycollab-services-community/src/test/java/com/mycollab/module/project/service/TicketRelationServiceTest.kt
593151409
// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.stardroid.ephemeris import android.content.SharedPreferences import android.content.res.Resources import android.graphics.Color import com.google.android.stardroid.base.Lists import com.google.android.stardroid.control.AstronomerModel import com.google.android.stardroid.math.Vector3 import com.google.android.stardroid.math.heliocentricCoordinatesFromOrbitalElements import com.google.android.stardroid.math.updateFromRaDec import com.google.android.stardroid.renderables.* import com.google.android.stardroid.renderer.RendererObjectManager.UpdateType import com.google.android.stardroid.space.SolarSystemObject import com.google.android.stardroid.space.Universe import java.util.* /** * Implementation of the * [AstronomicalRenderable] for planets. * * @author Brent Bryan */ class SolarSystemRenderable( private val solarSystemBody: SolarSystemBody, resources: Resources, model: AstronomerModel, prefs: SharedPreferences ) : AbstractAstronomicalRenderable() { private val pointPrimitives = ArrayList<PointPrimitive>() private val imagePrimitives = ArrayList<ImagePrimitive>() private val labelPrimitives = ArrayList<TextPrimitive>() private val resources: Resources private val model: AstronomerModel private val name: String private val preferences: SharedPreferences private val currentCoords = Vector3(0f, 0f, 0f) private val solarSystemObject: SolarSystemObject private var earthCoords: Vector3 private var imageId = -1 private var lastUpdateTimeMs = 0L private val universe = Universe() override val names: List<String> get() = Lists.asList(name) override val searchLocation: Vector3 get() = currentCoords private fun updateCoords(time: Date) { lastUpdateTimeMs = time.time // TODO(johntaylor): figure out why we do this - presumably to make sure the images // are orientated correctly taking into account the Earth's orbital plane. // I'm not sure we're doing this right though. earthCoords = heliocentricCoordinatesFromOrbitalElements(SolarSystemBody.Earth.getOrbitalElements(time)) currentCoords.updateFromRaDec(universe.getRaDec(solarSystemBody, time)) for (imagePrimitives in imagePrimitives) { imagePrimitives.setUpVector(earthCoords) } } override fun initialize(): Renderable { val time = model.time updateCoords(time) imageId = solarSystemObject.getImageResourceId(time) if (solarSystemBody === SolarSystemBody.Moon) { imagePrimitives.add( ImagePrimitive( currentCoords, resources, imageId, earthCoords, solarSystemObject.getPlanetaryImageSize() ) ) } else { val usePlanetaryImages = preferences.getBoolean(SHOW_PLANETARY_IMAGES, true) if (usePlanetaryImages || solarSystemBody === SolarSystemBody.Sun) { imagePrimitives.add( ImagePrimitive( currentCoords, resources, imageId, UP, solarSystemObject.getPlanetaryImageSize() ) ) } else { pointPrimitives.add(PointPrimitive(currentCoords, PLANET_COLOR, PLANET_SIZE)) } } labelPrimitives.add(TextPrimitive(currentCoords, name, PLANET_LABEL_COLOR)) return this } override fun update(): EnumSet<UpdateType> { val updates = EnumSet.noneOf(UpdateType::class.java) val modelTime = model.time if (Math.abs(modelTime.time - lastUpdateTimeMs) > solarSystemObject.getUpdateFrequencyMs()) { updates.add(UpdateType.UpdatePositions) // update location updateCoords(modelTime) // For moon only: if (solarSystemBody === SolarSystemBody.Moon && !imagePrimitives.isEmpty()) { // Update up vector. imagePrimitives[0].setUpVector(earthCoords) // update image: val newImageId = solarSystemObject.getImageResourceId(modelTime) if (newImageId != imageId) { imageId = newImageId imagePrimitives[0].setImageId(imageId) updates.add(UpdateType.UpdateImages) } } } return updates } override val images: List<ImagePrimitive> get() = imagePrimitives override val labels: List<TextPrimitive> get() = labelPrimitives override val points: List<PointPrimitive> get() = pointPrimitives companion object { private const val PLANET_SIZE = 3 private val PLANET_COLOR = Color.argb(20, 129, 126, 246) private const val PLANET_LABEL_COLOR = 0xf67e81 private const val SHOW_PLANETARY_IMAGES = "show_planetary_images" private val UP = Vector3(0.0f, 1.0f, 0.0f) } init { solarSystemObject = universe.solarSystemObjectFor(solarSystemBody) this.resources = resources this.model = model name = resources.getString(solarSystemObject.getNameResourceId()) preferences = prefs earthCoords = heliocentricCoordinatesFromOrbitalElements( SolarSystemBody.Earth.getOrbitalElements(model.time)) } }
app/src/main/java/com/google/android/stardroid/ephemeris/SolarSystemRenderable.kt
3251178621
/* * Copyright 2018 New Vector Ltd * * 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 im.vector.util import android.graphics.Bitmap import android.graphics.Canvas import org.matrix.androidsdk.core.Log private const val LOG_TAG = "BitmapUtil" /** * Create a centered square bitmap from another one. * * if height == width * +-------+ * |XXXXXXX| * |XXXXXXX| * |XXXXXXX| * +-------+ * * if width > height * +------+-------+------+ * | |XXXXXXX| | * | |XXXXXXX| | * | |XXXXXXX| | * +------+-------+------+ * * if height > width * +-------+ * | | * | | * +-------+ * |XXXXXXX| * |XXXXXXX| * |XXXXXXX| * +-------+ * | | * | | * +-------+ * * @param bitmap the bitmap to "square" * @return the squared bitmap */ fun Bitmap.createSquareBitmap(): Bitmap = when { width == height -> this width > height -> try { // larger than high Bitmap.createBitmap(this, (width - height) / 2, 0, height, height) } catch (e: Exception) { Log.e(LOG_TAG, "## createSquareBitmap " + e.message, e) this } else -> try { // higher than large Bitmap.createBitmap(this, 0, (height - width) / 2, width, width) } catch (e: Exception) { Log.e(LOG_TAG, "## createSquareBitmap " + e.message, e) this } } /** * Add a background color to the Bitmap */ fun Bitmap.addBackgroundColor(backgroundColor: Int): Bitmap { // Create new bitmap based on the size and config of the old val newBitmap = Bitmap.createBitmap(width, height, config ?: Bitmap.Config.ARGB_8888) // Reported by the Play Store if (newBitmap == null) { Log.e(LOG_TAG, "## unable to add background color") return this } Canvas(newBitmap).let { // Paint background it.drawColor(backgroundColor) // Draw the old bitmap on top of the new background it.drawBitmap(this, 0f, 0f, null) } return newBitmap }
vector/src/main/java/im/vector/util/BitmapUtil.kt
2427171722
package cz.filipproch.reactor.util import cz.filipproch.reactor.base.translator.SimpleTranslatorFactory import cz.filipproch.reactor.base.translator.TranslatorFactory import cz.filipproch.reactor.base.view.ReactorUiAction import cz.filipproch.reactor.base.view.ReactorUiEvent import cz.filipproch.reactor.base.view.ReactorUiModel import cz.filipproch.reactor.base.view.ReactorView import io.reactivex.Observable import io.reactivex.functions.Consumer /** * TODO * * @author Filip Prochazka (@filipproch) */ class FakeReactorView : ReactorView<TestTranslator> { var onEmittersInitCalled = false var onConnectModelChannelCalled = false var onConnectModelStreamCalled = false var onConnectActionChannelCalled = false var onConnectActionStreamCalled = false var registerEmitterExecutions = 0 var dispatchExecutions = 0 var consumeOnUiExecutions = 0 private var onEmittersInitCallback: (() -> Unit)? = null override val translatorFactory: TranslatorFactory<TestTranslator> get() = SimpleTranslatorFactory(TestTranslator::class.java) override fun onEmittersInit() { onEmittersInitCalled = true onEmittersInitCallback?.invoke() } override fun onConnectModelStream(modelStream: Observable<out ReactorUiModel>) { onConnectModelStreamCalled = true } override fun onConnectActionStream(actionStream: Observable<out ReactorUiAction>) { onConnectActionStreamCalled = true } override fun registerEmitter(emitter: Observable<out ReactorUiEvent>) { registerEmitterExecutions++ } override fun dispatch(event: ReactorUiEvent) { dispatchExecutions++ } override fun <T> Observable<T>.consumeOnUi(receiverAction: Consumer<T>) { consumeOnUiExecutions++ } fun setOnEmittersInitCallback(callback: () -> Unit) { onEmittersInitCallback = callback } }
library/src/test/java/cz/filipproch/reactor/util/FakeReactorView.kt
1023369051
package com.hannesdorfmann.mosby3.conductor.sample.create import android.net.Uri import com.hannesdorfmann.mosby3.conductor.sample.model.tasks.TaskBuilder import com.hannesdorfmann.mosby3.conductor.sample.model.tasks.TaskDao import com.hannesdorfmann.mosby3.mvp.MvpBasePresenter import rx.Subscription import javax.inject.Inject /** * Presenter to create a new Task * * @author Hannes Dorfmann */ class CreateTaskPresenter @Inject constructor(private val dao: TaskDao, private val taskBuilder: TaskBuilder) : MvpBasePresenter<CreateTaskView>() { private lateinit var taskBuilderSubscription: Subscription override fun attachView(view: CreateTaskView) { super.attachView(view) taskBuilderSubscription = taskBuilder.observable.subscribe({ getView()?.setTaskSnapshot(it) }) } override fun detachView(retainInstance: Boolean) { super.detachView(retainInstance) taskBuilderSubscription.unsubscribe() } fun setTaskTitle(title: String) { taskBuilder.setTitle(title) } fun setTaskDescription(description: String) { taskBuilder.setDescription(description) } fun addImage(uri: Uri) { taskBuilder.addImage(uri) } fun saveTask() { } }
app/src/main/java/com/hannesdorfmann/mosby3/conductor/sample/create/CreateTaskPresenter.kt
204156291
package link.continuum.desktop.gui.icon.avatar import javafx.scene.layout.Region import javafx.scene.paint.Color import koma.Server import koma.network.media.MHUrl import kotlinx.coroutines.MainScope import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import link.continuum.desktop.gui.StackPane import link.continuum.desktop.gui.StyleBuilder import link.continuum.desktop.gui.add import link.continuum.desktop.gui.component.FitImageRegion import link.continuum.desktop.gui.em import link.continuum.desktop.util.debugAssertUiThread import mu.KotlinLogging private val logger = KotlinLogging.logger {} abstract class UrlAvatar( ) { private val scope = MainScope() val root: Region = object :StackPane() { // roughly aligned with text vertically override fun getBaselineOffset(): Double = height * 0.75 } val initialIcon = InitialIcon() val imageView = FitImageRegion() init { imageView.imageProperty.onEach { val noImage = it == null initialIcon.root.apply { isVisible = noImage isManaged = noImage } }.launchIn(scope) root as StackPane root.add(initialIcon.root) root.add(imageView) } @Deprecated("") fun updateName(name: String, color: Color) { debugAssertUiThread() this.initialIcon.updateItem(name, color) } /** * null url clears the image */ fun updateUrl(url: MHUrl?, server: Server) { imageView.setMxc(url, server) } fun cancelScope() { scope.cancel() } companion object { } } /** * width and height are about two lines */ class Avatar2L: UrlAvatar() { init { root as StackPane root.style = rootStyle } companion object { private val rootStyle = StyleBuilder { fixHeight(2.2.em) fixWidth(2.2.em) }.toStyle() private val clipStyle = StyleBuilder { } } } /** * width and height are about two lines */ class AvatarInline: UrlAvatar() { init { root as StackPane root.style = rootStyle } companion object { private val rootStyle = StyleBuilder { fixHeight(1.em) fixWidth(1.em) }.toStyle() } }
src/main/kotlin/link/continuum/desktop/gui/icon/avatar/url.kt
1215513026
/* * Copyright 2019 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.uamp.media.library import android.content.Context import android.support.v4.media.MediaBrowserCompat import android.support.v4.media.MediaBrowserCompat.MediaItem import android.support.v4.media.MediaMetadataCompat import com.example.android.uamp.media.MusicService import com.example.android.uamp.media.R import com.example.android.uamp.media.extensions.album import com.example.android.uamp.media.extensions.albumArt import com.example.android.uamp.media.extensions.albumArtUri import com.example.android.uamp.media.extensions.artist import com.example.android.uamp.media.extensions.flag import com.example.android.uamp.media.extensions.id import com.example.android.uamp.media.extensions.title import com.example.android.uamp.media.extensions.trackNumber import com.example.android.uamp.media.extensions.urlEncoded /** * Represents a tree of media that's used by [MusicService.onLoadChildren]. * * [BrowseTree] maps a media id (see: [MediaMetadataCompat.METADATA_KEY_MEDIA_ID]) to one (or * more) [MediaMetadataCompat] objects, which are children of that media id. * * For example, given the following conceptual tree: * root * +-- Albums * | +-- Album_A * | | +-- Song_1 * | | +-- Song_2 * ... * +-- Artists * ... * * Requesting `browseTree["root"]` would return a list that included "Albums", "Artists", and * any other direct children. Taking the media ID of "Albums" ("Albums" in this example), * `browseTree["Albums"]` would return a single item list "Album_A", and, finally, * `browseTree["Album_A"]` would return "Song_1" and "Song_2". Since those are leaf nodes, * requesting `browseTree["Song_1"]` would return null (there aren't any children of it). */ class BrowseTree( val context: Context, musicSource: MusicSource, val recentMediaId: String? = null ) { private val mediaIdToChildren = mutableMapOf<String, MutableList<MediaMetadataCompat>>() /** * Whether to allow clients which are unknown (not on the allowed list) to use search on this * [BrowseTree]. */ val searchableByUnknownCaller = true /** * In this example, there's a single root node (identified by the constant * [UAMP_BROWSABLE_ROOT]). The root's children are each album included in the * [MusicSource], and the children of each album are the songs on that album. * (See [BrowseTree.buildAlbumRoot] for more details.) * * TODO: Expand to allow more browsing types. */ init { val rootList = mediaIdToChildren[UAMP_BROWSABLE_ROOT] ?: mutableListOf() val recommendedMetadata = MediaMetadataCompat.Builder().apply { id = UAMP_RECOMMENDED_ROOT title = context.getString(R.string.recommended_title) albumArtUri = RESOURCE_ROOT_URI + context.resources.getResourceEntryName(R.drawable.ic_recommended) flag = MediaBrowserCompat.MediaItem.FLAG_BROWSABLE }.build() val albumsMetadata = MediaMetadataCompat.Builder().apply { id = UAMP_ALBUMS_ROOT title = context.getString(R.string.albums_title) albumArtUri = RESOURCE_ROOT_URI + context.resources.getResourceEntryName(R.drawable.ic_album) flag = MediaBrowserCompat.MediaItem.FLAG_BROWSABLE }.build() rootList += recommendedMetadata rootList += albumsMetadata mediaIdToChildren[UAMP_BROWSABLE_ROOT] = rootList musicSource.forEach { mediaItem -> val albumMediaId = mediaItem.album.urlEncoded val albumChildren = mediaIdToChildren[albumMediaId] ?: buildAlbumRoot(mediaItem) albumChildren += mediaItem // Add the first track of each album to the 'Recommended' category if (mediaItem.trackNumber == 1L) { val recommendedChildren = mediaIdToChildren[UAMP_RECOMMENDED_ROOT] ?: mutableListOf() recommendedChildren += mediaItem mediaIdToChildren[UAMP_RECOMMENDED_ROOT] = recommendedChildren } // If this was recently played, add it to the recent root. if (mediaItem.id == recentMediaId) { mediaIdToChildren[UAMP_RECENT_ROOT] = mutableListOf(mediaItem) } } } /** * Provide access to the list of children with the `get` operator. * i.e.: `browseTree\[UAMP_BROWSABLE_ROOT\]` */ operator fun get(mediaId: String) = mediaIdToChildren[mediaId] /** * Builds a node, under the root, that represents an album, given * a [MediaMetadataCompat] object that's one of the songs on that album, * marking the item as [MediaItem.FLAG_BROWSABLE], since it will have child * node(s) AKA at least 1 song. */ private fun buildAlbumRoot(mediaItem: MediaMetadataCompat): MutableList<MediaMetadataCompat> { val albumMetadata = MediaMetadataCompat.Builder().apply { id = mediaItem.album.urlEncoded title = mediaItem.album artist = mediaItem.artist albumArt = mediaItem.albumArt albumArtUri = mediaItem.albumArtUri.toString() flag = MediaItem.FLAG_BROWSABLE }.build() // Adds this album to the 'Albums' category. val rootList = mediaIdToChildren[UAMP_ALBUMS_ROOT] ?: mutableListOf() rootList += albumMetadata mediaIdToChildren[UAMP_ALBUMS_ROOT] = rootList // Insert the album's root with an empty list for its children, and return the list. return mutableListOf<MediaMetadataCompat>().also { mediaIdToChildren[albumMetadata.id!!] = it } } } const val UAMP_BROWSABLE_ROOT = "/" const val UAMP_EMPTY_ROOT = "@empty@" const val UAMP_RECOMMENDED_ROOT = "__RECOMMENDED__" const val UAMP_ALBUMS_ROOT = "__ALBUMS__" const val UAMP_RECENT_ROOT = "__RECENT__" const val MEDIA_SEARCH_SUPPORTED = "android.media.browse.SEARCH_SUPPORTED" const val RESOURCE_ROOT_URI = "android.resource://com.example.android.uamp.next/drawable/"
common/src/main/java/com/example/android/uamp/media/library/BrowseTree.kt
1885300005
package net.niiranen.lov.suite import net.niiranen.lov.LovInstrumentationTest import org.junit.runner.RunWith import org.junit.runners.Suite @RunWith(Suite::class) @Suite.SuiteClasses(LovInstrumentationTest::class) class InstrumentationTestSuite
lov/src/androidTest/kotlin/net/niiranen/lov/suite/InstrumentationTestSuite.kt
1879674845
package com.rpkit.essentials.bukkit.kit import com.rpkit.essentials.bukkit.RPKEssentialsBukkit import com.rpkit.kit.bukkit.kit.RPKKit import com.rpkit.kit.bukkit.kit.RPKKitProvider class RPKKitProviderImpl(private val plugin: RPKEssentialsBukkit): RPKKitProvider { override val kits: MutableList<RPKKit> = plugin.config.getList("kits") as MutableList<RPKKit> override fun getKit(id: Int): RPKKit? { return kits.firstOrNull { it.id == id } } override fun getKit(name: String): RPKKit? { return kits.firstOrNull { it.name == name } } override fun addKit(kit: RPKKit) { kits.add(kit) plugin.config.set("kits", kits) plugin.saveConfig() } override fun updateKit(kit: RPKKit) { removeKit(kit) addKit(kit) } override fun removeKit(kit: RPKKit) { kits.remove(getKit(kit.id)) plugin.config.set("kits", kits) plugin.saveConfig() } }
bukkit/rpk-essentials-bukkit/src/main/kotlin/com/rpkit/essentials/bukkit/kit/RPKKitProviderImpl.kt
4212160790
/* * Copyright 2016 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.chat.bukkit.chatchannel.directed import com.rpkit.chat.bukkit.RPKChatBukkit import com.rpkit.chat.bukkit.chatchannel.pipeline.DirectedChatChannelPipelineComponent import com.rpkit.chat.bukkit.context.DirectedChatChannelMessageContext import com.rpkit.chat.bukkit.snooper.RPKSnooperProvider import org.bukkit.Bukkit import org.bukkit.configuration.serialization.ConfigurationSerializable import org.bukkit.configuration.serialization.SerializableAs /** * Snoop component. * Sends message to snoopers if the message would not be sent to them otherwise. */ @SerializableAs("SnoopComponent") class SnoopComponent(private val plugin: RPKChatBukkit): DirectedChatChannelPipelineComponent, ConfigurationSerializable { override fun process(context: DirectedChatChannelMessageContext): DirectedChatChannelMessageContext { if (!context.isCancelled) return context val snooperProvider = plugin.core.serviceManager.getServiceProvider(RPKSnooperProvider::class) if (snooperProvider.snooperMinecraftProfiles.contains(context.receiverMinecraftProfile)) { context.receiverMinecraftProfile.sendMessage(context.message) } return context } override fun serialize(): MutableMap<String, Any> { return mutableMapOf() } companion object { @JvmStatic fun deserialize(serialized: MutableMap<String, Any>): SnoopComponent { return SnoopComponent(Bukkit.getPluginManager().getPlugin("rpk-chat-bukkit") as RPKChatBukkit) } } }
bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/chatchannel/directed/SnoopComponent.kt
2572866707
/* * Copyright (C) 2016/2022 Litote * * 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.litote.kmongo.reactor import kotlinx.serialization.Serializable import org.bson.Document import org.junit.Test import org.litote.kmongo.model.Friend import org.litote.kmongo.oldestMongoTestVersion import kotlin.test.assertEquals import kotlin.test.assertTrue /** * */ class CommandTest : KMongoReactorBaseTest<Friend>(oldestMongoTestVersion) { @Serializable class LocationResult(val results: List<Location>) @Serializable class Location(var dis: Double = 0.toDouble(), var obj: NestedLocation? = null) { val name: String get() = obj?.name ?: "" } @Serializable class NestedLocation(var name: String? = null) @Test fun canRunACommand() { val document = database.runCommand<Document>("{ ping: 1 }").block() ?: throw AssertionError("Document must not null!") assertEquals(1.0, document["ok"]) } @Test fun canRunACommandWithParameter() { col.insertOne("{test:1}").block() val friends = "friend" val document = database.runCommand<Document>("{ count: '$friends' }").block() ?: throw AssertionError("Document must not null!") assertEquals(1, document["n"]) } @Test fun canRunAGeoNearCommand() { col.createIndex("{loc:'2d'}").block() col.insertOne("{loc:{lat:48.690833,lng:9.140556}, name:'Paris'}").block() val document = database.runCommand<LocationResult>( "{ geoNear : 'friend', near : [48.690,9.140], spherical: true}" ).block() ?: throw AssertionError("Document must not null!") val locations = document.results assertEquals(1, locations.size) assertEquals(1.732642945641585E-5, locations.first().dis) assertEquals("Paris", locations.first().name) } @Test fun canRunAnEmptyResultCommand() { col.createIndex("{loc:'2d'}").block() val document = database.runCommand<LocationResult>( "{ geoNear : 'friend', near : [48.690,9.140], spherical: true}" ).block() ?: throw AssertionError("Document must not null!") assertTrue(document.results.isEmpty()) } }
kmongo-reactor-core-tests/src/main/kotlin/org/litote/kmongo/reactor/CommandTest.kt
1560514451
package org.evomaster.core.problem.httpws.service import com.fasterxml.jackson.databind.ObjectMapper import org.evomaster.client.java.controller.api.dto.* import org.evomaster.core.StaticCounter import org.evomaster.core.database.DbAction import org.evomaster.core.database.DbActionTransformer import org.evomaster.core.logging.LoggingUtil import org.evomaster.core.output.CookieWriter import org.evomaster.core.output.TokenWriter import org.evomaster.core.problem.api.service.ApiWsFitness import org.evomaster.core.problem.api.service.ApiWsIndividual import org.evomaster.core.problem.rest.* import org.evomaster.core.problem.rest.param.HeaderParam import org.evomaster.core.remote.SutProblemException import org.evomaster.core.search.Action import org.evomaster.core.search.Individual import org.glassfish.jersey.client.ClientConfig import org.glassfish.jersey.client.ClientProperties import org.glassfish.jersey.client.HttpUrlConnectorProvider import org.slf4j.Logger import org.slf4j.LoggerFactory import java.net.MalformedURLException import java.net.URL import javax.annotation.PostConstruct import javax.ws.rs.client.Client import javax.ws.rs.client.ClientBuilder import javax.ws.rs.client.Entity import javax.ws.rs.client.Invocation import javax.ws.rs.core.MediaType import javax.ws.rs.core.NewCookie import javax.ws.rs.core.Response abstract class HttpWsFitness<T>: ApiWsFitness<T>() where T : Individual { companion object { private val log: Logger = LoggerFactory.getLogger(HttpWsFitness::class.java) init{ System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); } } protected lateinit var client : Client @PostConstruct protected fun initialize() { log.debug("Initializing {}", HttpWsFitness::class.simpleName) val clientConfiguration = ClientConfig() .property(ClientProperties.CONNECT_TIMEOUT, 10_000) .property(ClientProperties.READ_TIMEOUT, config.tcpTimeoutMs) //workaround bug in Jersey client .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true) .property(ClientProperties.FOLLOW_REDIRECTS, false) client = ClientBuilder.newClient(clientConfiguration) if (!config.blackBox || config.bbExperiments) { rc.checkConnection() val started = rc.startSUT() if (!started) { throw SutProblemException("Failed to start the system under test") } infoDto = rc.getSutInfo() ?: throw SutProblemException("Failed to retrieve the info about the system under test") } log.debug("Done initializing {}", HttpWsFitness::class.simpleName) } override fun reinitialize(): Boolean { try { if (!config.blackBox) { rc.stopSUT() } initialize() } catch (e: Exception) { log.warn("Failed to re-initialize the SUT: $e") return false } return true } open fun getlocation5xx(status: Int, additionalInfoList: List<AdditionalInfoDto>, indexOfAction: Int, result: HttpWsCallResult, name: String) : String?{ var location5xx : String? = null if (status == 500){ val statement = additionalInfoList[indexOfAction].lastExecutedStatement location5xx = statement ?: DEFAULT_FAULT_CODE result.setLastStatementWhen500(location5xx) } return location5xx } protected fun getBaseUrl(): String { var baseUrl = if (!config.blackBox || config.bbExperiments) { infoDto.baseUrlOfSUT } else { BlackBoxUtils.targetUrl(config, sampler) } try{ /* Note: this in theory should already been checked: either in EMConfig for Black-box testing, or already in the driver for White-Box testing */ URL(baseUrl) } catch (e: MalformedURLException){ val base = "Invalid 'baseUrl'." val wb = "In the EvoMaster driver, in the startSut() method, you must make sure to return a valid URL." val err = " ERROR: $e" val msg = if(config.blackBox) "$base $err" else "$base $wb $err" throw SutProblemException(msg) } if (baseUrl.endsWith("/")) { baseUrl = baseUrl.substring(0, baseUrl.length - 1) } return baseUrl } /** * If any action needs auth based on tokens via JSON, do a "login" before * running the actions, and store the tokens */ protected fun getTokens(ind: T): Map<String, String>{ val tokensLogin = TokenWriter.getTokenLoginAuth(ind) //from userId to Token val map = mutableMapOf<String, String>() val baseUrl = getBaseUrl() for(tl in tokensLogin){ val response = try { client.target(baseUrl + tl.endpoint) .request() .buildPost(Entity.entity(tl.jsonPayload, MediaType.APPLICATION_JSON_TYPE)) .invoke() } catch (e: Exception) { log.warn("Failed to login for ${tl.userId}: $e") continue } if (response.statusInfo.family != Response.Status.Family.SUCCESSFUL) { log.warn("Login request failed with status ${response.status}") continue } if(! response.hasEntity()){ log.warn("Login request failed, with no body response from which to extract the auth token") continue } val body = response.readEntity(String::class.java) val jackson = ObjectMapper() val tree = jackson.readTree(body) var token = tree.at(tl.extractTokenField).asText() if(token == null || token.isEmpty()){ log.warn("Failed login. Cannot extract token '${tl.extractTokenField}' from response: $body") continue } if(tl.headerPrefix.isNotEmpty()){ token = tl.headerPrefix + token } map[tl.userId] = token } return map } /** * If any action needs auth based on cookies, do a "login" before * running the actions, and collect the cookies from the server. * * @return a map from username to auth cookie for those users */ protected fun getCookies(ind: T): Map<String, List<NewCookie>> { val cookieLogins = CookieWriter.getCookieLoginAuth(ind) val map: MutableMap<String, List<NewCookie>> = mutableMapOf() val baseUrl = getBaseUrl() for (cl in cookieLogins) { val mediaType = when (cl.contentType) { ContentType.X_WWW_FORM_URLENCODED -> MediaType.APPLICATION_FORM_URLENCODED_TYPE ContentType.JSON -> MediaType.APPLICATION_JSON_TYPE } val response = try { client.target(cl.getUrl(baseUrl)) .request() //TODO could consider other cases besides POST .buildPost(Entity.entity(cl.payload(), mediaType)) .invoke() } catch (e: Exception) { log.warn("Failed to login for ${cl.username}/${cl.password}: $e") continue } if (response.statusInfo.family != Response.Status.Family.SUCCESSFUL) { /* if it is a 3xx, we need to look at Location header to determine if a success or failure. TODO: could explicitly ask for this info in the auth DTO. However, as 3xx makes little sense in a REST API, maybe not so important right now, although had this issue with some APIs using default settings in Spring Security */ if (response.statusInfo.family == Response.Status.Family.REDIRECTION) { val location = response.getHeaderString("location") if (location != null && (location.contains("error", true) || location.contains("login", true))) { log.warn("Login request failed with ${response.status} redirection toward $location") continue } } else { log.warn("Login request failed with status ${response.status}") continue } } if (response.cookies.isEmpty()) { log.warn("Cookie-based login request did not give back any new cookie") continue } map[cl.username] = response.cookies.values.toList() } return map } protected fun registerNewAction(action: Action, index: Int){ rc.registerNewAction(getActionDto(action, index)) } @Deprecated("replaced by doDbCalls()") open fun doInitializingActions(ind: ApiWsIndividual) { if (log.isTraceEnabled){ log.trace("do {} InitializingActions: {}", ind.seeInitializingActions().size, ind.seeInitializingActions().filterIsInstance<DbAction>().joinToString(","){ it.getResolvedName() }) } if (ind.seeInitializingActions().filterIsInstance<DbAction>().none { !it.representExistingData }) { /* We are going to do an initialization of database only if there is data to add. Note that current data structure also keeps info on already existing data (which of course should not be re-inserted...) */ return } val dto = DbActionTransformer.transform(ind.seeInitializingActions().filterIsInstance<DbAction>()) dto.idCounter = StaticCounter.getAndIncrease() val ok = rc.executeDatabaseCommand(dto) if (!ok) { //this can happen if we do not handle all constraints LoggingUtil.uniqueWarn(log, "Failed in executing database command") } } protected fun handleHeaders(a: HttpWsAction, builder: Invocation.Builder, cookies: Map<String, List<NewCookie>>, tokens: Map<String, String>) { a.auth.headers.forEach { builder.header(it.name, it.value) } val prechosenAuthHeaders = a.auth.headers.map { it.name } /* TODO: optimization, avoid mutating header gene if anyway using pre-chosen one */ a.parameters.filterIsInstance<HeaderParam>() //TODO those should be skipped directly in the search, ie, right now they are useless genes .filter { !prechosenAuthHeaders.contains(it.name) } .filter { !(a.auth.jsonTokenPostLogin != null && it.name.equals("Authorization", true)) } .filter{ it.isInUse()} .forEach { builder.header(it.name, it.gene.getValueAsRawString()) } if (a.auth.cookieLogin != null) { val list = cookies[a.auth.cookieLogin!!.username] if (list == null || list.isEmpty()) { log.warn("No cookies for ${a.auth.cookieLogin!!.username}") } else { list.forEach { builder.cookie(it.toCookie()) } } } if (a.auth.jsonTokenPostLogin != null) { val token = tokens[a.auth.jsonTokenPostLogin!!.userId] if (token == null || token.isEmpty()) { log.warn("No auth token for ${a.auth.jsonTokenPostLogin!!.userId}") } else { builder.header("Authorization", token) } } } }
core/src/main/kotlin/org/evomaster/core/problem/httpws/service/HttpWsFitness.kt
2873316160
package com.gmail.blueboxware.libgdxplugin.ui import com.gmail.blueboxware.libgdxplugin.filetypes.atlas2.psi.Atlas2Region import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinResource import com.intellij.psi.ElementDescriptionLocation import com.intellij.psi.ElementDescriptionProvider import com.intellij.psi.PsiElement /* * Copyright 2017 Blue Box Ware * * 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. */ class LibGDXElementDescriptionProvider : ElementDescriptionProvider { override fun getElementDescription(element: PsiElement, location: ElementDescriptionLocation): String? = when (element) { is SkinResource -> element.name is Atlas2Region -> element.name else -> null } }
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/ui/LibGDXElementDescriptionProvider.kt
3861689149
// Licensed under the MIT license. See LICENSE file in the project root // for full license information. @file:JvmName("ReflectionExtensions") package net.dummydigit.qbranch import net.dummydigit.qbranch.annotations.QBranchGeneratedCode import java.lang.reflect.Field import java.lang.reflect.ParameterizedType import java.lang.reflect.Type import kotlin.reflect.KClass /** A function to check if given class is a generated bond class. * @return True if cls is Bond generated, or false if not. */ fun Class<*>.isQBranchGeneratedStruct() : Boolean { val isBondGenerated = this.getAnnotation(QBranchGeneratedCode::class.java) != null return isBondGenerated && !this.isEnum } /** * A function to check if given class is a generic type. * @return True if class is generic type, or false if not. */ fun Class<*>.isGenericClass() : Boolean { return this.typeParameters.size > 0 } /** * A function to check if given Kotlin class is a generic type. * @return True if class is generic type, or false if not. */ fun KClass<*>.isGenericClass() : Boolean { return this.java.isGenericClass() } fun Class<*>.isQBranchBuiltinType() : Boolean = when (this) { String::class.java -> true Byte::class.java -> true Short::class.java -> true Int::class.java -> true Long::class.java -> true UnsignedByte::class.java -> true UnsignedShort::class.java -> true UnsignedInt::class.java -> true UnsignedLong::class.java -> true ByteString::class.java -> true // TODO: Add container types later. else -> false } fun KClass<*>.isQBranchBuiltinType() : Boolean { return this.java.isQBranchBuiltinType() } /** * Tell whether a given field has a generic type. */ fun Field.isGenericType() : Boolean { val declaredType = this.genericType val realType = this.type return (declaredType !is ParameterizedType) && declaredType != (realType) } /** * A helper class to retrieve type arguments of given type. */ abstract class TypeReference<T> : Comparable<TypeReference<T>> { val type: Type = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] override fun compareTo(other: TypeReference<T>) = 0 } /** * Extract type arguments of generic types. Callable from Kotlin code only. * @return An array of type, which represents the list of type arguments. */ inline fun <reified T: Any> extractGenericTypeArguments() : Array<Type> { // Make use of generic type token to allow we val type = object : TypeReference<T>() {}.type if (type is ParameterizedType) { return type.actualTypeArguments } else { throw UnsupportedOperationException("NonParameterizedType:type=$type") } }
core/src/main/kotlin/net/dummydigit/qbranch/ReflectionExtensions.kt
853001218
package com.gmail.blueboxware.libgdxplugin.filetypes.bitmapFont.highlighting import com.gmail.blueboxware.libgdxplugin.filetypes.bitmapFont.BitmapFontElementTypes import com.gmail.blueboxware.libgdxplugin.filetypes.bitmapFont.psi.BitmapFontKey import com.gmail.blueboxware.libgdxplugin.filetypes.bitmapFont.psi.BitmapFontProperty import com.gmail.blueboxware.libgdxplugin.filetypes.bitmapFont.psi.BitmapFontValue import com.gmail.blueboxware.libgdxplugin.utils.isLeaf import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.Annotator import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import org.jetbrains.kotlin.psi.psiUtil.startOffset /* * Copyright 2017 Blue Box Ware * * 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. */ class BitmapFontHighlighter : Annotator { companion object { val KEYWORDS = listOf("info", "common", "page", "chars", "char", "kernings", "kerning") } override fun annotate(element: PsiElement, holder: AnnotationHolder) { if (element is BitmapFontProperty) { holder .newSilentAnnotation(HighlightSeverity.INFORMATION) .range(element.keyElement) .textAttributes(BitmapFontColorSettingsPage.KEY) .create() element.valueElement?.let { holder .newSilentAnnotation(HighlightSeverity.INFORMATION) .range(it) .textAttributes(BitmapFontColorSettingsPage.VALUE) .create() } element.node.getChildren(null).forEach { node -> if (node.text == "=") { holder .newSilentAnnotation(HighlightSeverity.INFORMATION) .range(node) .textAttributes(BitmapFontColorSettingsPage.EQUALS_SIGN) .create() } } element.valueElement?.let { valueElement -> val valueText = valueElement.text val start = valueElement.startOffset for (i in valueText.indices) { if (valueText[i] == ',') { holder .newSilentAnnotation(HighlightSeverity.INFORMATION) .range(TextRange(start + i, start + i + 1)) .textAttributes(BitmapFontColorSettingsPage.COMMA) .create() } } } } else if (element.isLeaf(BitmapFontElementTypes.UNQUOTED_STRING)) { if (KEYWORDS.contains(element.text) && element.parent !is BitmapFontKey && element.parent !is BitmapFontValue) { holder .newSilentAnnotation(HighlightSeverity.INFORMATION) .range(element) .textAttributes(BitmapFontColorSettingsPage.KEYWORD) .create() } } } }
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/bitmapFont/highlighting/BitmapFontHighlighter.kt
2117682224
package com.gmail.blueboxware.libgdxplugin.filetypes.json.inspections import com.gmail.blueboxware.libgdxplugin.filetypes.json.psi.GdxJsonElement import com.gmail.blueboxware.libgdxplugin.filetypes.json.utils.isSuppressed import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.SuppressQuickFix import com.intellij.psi.PsiElement /* * Copyright 2019 Blue Box Ware * * 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. */ abstract class GdxJsonBaseInspection : LocalInspectionTool() { protected fun getShortID() = id.removePrefix("LibGDXJson") override fun getGroupPath() = arrayOf("libGDX", "JSON") @Suppress("DialogTitleCapitalization") override fun getGroupDisplayName() = "libGDX" override fun isEnabledByDefault() = true override fun isSuppressedFor(element: PsiElement): Boolean = (element as? GdxJsonElement)?.isSuppressed(getShortID()) ?: false abstract override fun getBatchSuppressActions(element: PsiElement?): Array<SuppressQuickFix> }
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/json/inspections/GdxJsonBaseInspection.kt
1497644487
package cc.ayakurayuki.csa.starter.core.entity import io.vertx.core.json.Json import java.util.* /** * * @author ayakurayuki * @date 2019/05/09-10:30 */ data class JsonResponse(val status: Int, val message: String, val data: Any?) { constructor() : this(JsonResponse()) constructor(data: Any?) : this(0, "", data) constructor(status: Int, data: Any?) : this(status, "", data) private val result: LinkedHashMap<String, Any?> get() { val map = LinkedHashMap<String, Any?>() map["status"] = this.status map["message"] = this.message map["data"] = this.data return map } override fun toString(): String { return Json.encode(this) } }
csa-core/src/main/java/cc/ayakurayuki/csa/starter/core/entity/JsonResponse.kt
2853173932
@file:Suppress("unused") package org.eurofurence.connavigator.util.v2 import android.content.Context import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonToken import com.google.gson.stream.JsonWriter import io.reactivex.Flowable import io.swagger.client.JsonUtil.getGson import io.swagger.client.JsonUtil.getListTypeForDeserialization import org.eurofurence.connavigator.util.extensions.* import java.io.File import java.io.ObjectInputStream import java.io.ObjectOutputStream import java.util.* import kotlin.reflect.KClass import kotlin.reflect.KProperty /** * Container of stored values. */ abstract class Stored(val context: Context) { /** * A stored value. */ inner class StoredValue<T : Any>( private val elementClass: KClass<T>, private val swaggerStored: Boolean) { operator fun getValue(any: Any, kProperty: KProperty<*>): T? { val file = File(context.filesDir, "${kProperty.name}.val") if (!file.exists()) return null else if (swaggerStored) JsonReader(file.safeReader()).use { return getGson().fromJson<T>(it, elementClass.java) } else ObjectInputStream(file.safeInStream()).use { @Suppress("unchecked_cast") return it.readObject() as T } } operator fun setValue(any: Any, kProperty: KProperty<*>, t: T?) { val file = File(context.filesDir, "${kProperty.name}.val") if (t == null) file.delete() else if (swaggerStored) JsonWriter(file.safeWriter()).use { getGson().toJson(t, elementClass.java, it) } else file.substitute { sub -> ObjectOutputStream(sub.safeOutStream()).use { it.writeObject(t) } } } } /** * A stored list of values. */ inner class StoredValues<T : Any>( private val elementClass: KClass<T>, private val swaggerStored: Boolean) { operator fun getValue(any: Any, kProperty: KProperty<*>): List<T> { val file = File(context.filesDir, "${kProperty.name}.val") if (!file.exists()) return emptyList() else if (swaggerStored) JsonReader(file.safeReader()).use { return getGson().fromJson<List<T>>(it, getListTypeForDeserialization(elementClass.java)) } else ObjectInputStream(file.safeInStream()).use { @Suppress("unchecked_cast") return it.readObject() as List<T> } } operator fun setValue(any: Any, kProperty: KProperty<*>, t: List<T>) { val file = File(context.filesDir, "${kProperty.name}.val") when { t.isEmpty() -> file.delete() swaggerStored -> JsonWriter(file.safeWriter()).use { getGson().toJson(t, getListTypeForDeserialization(elementClass.java), it) } else -> file.substitute { sub -> ObjectOutputStream(sub.safeOutStream()).use { it.writeObject(t) } } } } } /** * A stored source that caches elements and creates an index via the [id] function. */ inner class StoredSource<T : Any>( private val elementClass: KClass<T>, val id: (T) -> UUID) : Source<T, UUID> { /** * Storage file, generated from the type name. */ private val file = File(context.filesDir, "${elementClass.qualifiedName}.db") /** * Last time of read or write-through. */ private var readTime: Long? = null /** * Last value of read or write-through. */ private val readValue = hashMapOf<UUID, T>() /** * Streams the elements as an observable. */ fun stream(): Flowable<T> = Flowable.fromIterable(items) /** * The entries of the database, writing serializes with GSON. */ var entries: Map<UUID, T> get() { synchronized(file) { // File does not exist, therefore not content if (!file.exists()) return emptyMap() // File modified since last read, load changes if (file.lastModified() != readTime) JsonReader(file.safeReader()).use { // Carry file time attribute and reset the values. readTime = file.lastModified() readValue.clear() // Get the GSON object and keep it, as it is used multiple times. val gson = getGson() // Assert that the file contains an array. if (it.peek() == JsonToken.BEGIN_ARRAY) { // Consume the start. it.beginArray() // Until stopped on the end of the array, produce items. while (it.peek() != JsonToken.END_ARRAY) { // Get the current item from the reader at it's position. val current = gson.fromJson<T>(it, elementClass.java) // Add it to the map. readValue[id(current)] = current } // After the array, consume end for sanity. it.endArray() } } // Return the cached value return readValue } } set(values) { synchronized(file) { // Write values file.substitute { sub -> JsonWriter(sub.safeWriter()).use { getGson().toJson(values.values, getListTypeForDeserialization(elementClass.java), it) } } // Cache values and store the write time readTime = file.lastModified() readValue.clear() readValue.putAll(values) } } var items: Collection<T> get() = entries.values set(values) { entries = values.associateBy(id) } val fileTime get() = if (file.exists()) file.lastModified() else null override fun get(i: UUID?) = if (i != null) entries[i] else null /** * Applies the delta to the store. */ fun apply(abstractDelta: AbstractDelta<T>) { // Make new entries from original or new empty map val newEntries = if (abstractDelta.clearBeforeInsert) hashMapOf() else entries.toMutableMap() // Remove removed entities for (d in abstractDelta.deleted) newEntries.remove(d) // Replace changed entities for (c in abstractDelta.changed) newEntries[id(c)] = c // Transfer value if new. if (entries != newEntries) entries = newEntries } /** * Deletes the content and resets the values. */ fun delete() { synchronized(file) { file.delete() readTime = null readValue.clear() } } fun <U : Comparable<U>> asc(by: (T) -> U) = items.sortedBy(by) fun <U : Comparable<U>> desc(by: (T) -> U) = items.sortedByDescending(by) val size get() = items.size val isPresent get() = file.exists() } /** * Creates a stored value. */ protected inline fun <reified T : Any> storedValue(swaggerStored: Boolean = false) = StoredValue(T::class, swaggerStored) /** * Creates a stored list of values. */ protected inline fun <reified T : Any> storedValues(swaggerStored: Boolean = false) = StoredValues(T::class, swaggerStored) /** * Creates a stored source with the given identity function */ protected inline fun <reified T : Any> storedSource(noinline id: (T) -> UUID) = StoredSource(T::class, id) }
app/src/main/kotlin/org/eurofurence/connavigator/util/v2/Stored.kt
3920769665
package com.two_two.checkreaction.ui.finishscreen import android.app.Activity import android.content.Intent import android.os.Bundle import android.os.Parcelable import android.view.View import com.two_two.checkreaction.R import com.two_two.checkreaction.domain.firebase.FirebaseSender import com.two_two.checkreaction.models.App import com.two_two.checkreaction.models.firebase.FirebaseScienceResult import com.two_two.checkreaction.models.science.ScienceTestResult import com.two_two.checkreaction.ui.gamescore.science.ScienceScoreActivity import kotlinx.android.synthetic.main.activity_science_finish.* import java.io.Serializable class ScienceFinishActivity : Activity() { var testResult: ScienceTestResult? = null var firebaseResult : FirebaseScienceResult? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_science_finish) testResult = intent.getSerializableExtra(ScienceTestResult.TAG) as ScienceTestResult? if (testResult == null) { accuracy_result_text.setText(R.string.error_cannot_find_result) average_result_text.visibility = View.INVISIBLE } else { calcFirebaseTestResult() fillTextForResult() updateScienceTestResult() } rating_button.setOnClickListener { openResultsScreen() } } private fun calcFirebaseTestResult() { val username = App.getInstance().getLocalData().getUsername() firebaseResult = FirebaseScienceResult(testResult!!.currectHits, testResult!!.average, username) } private fun ScienceFinishActivity.fillTextForResult() { val accuracySb = StringBuilder() accuracySb.append(getString(R.string.accuracy)) accuracySb.append(testResult?.currectHits) accuracySb.append(getString(R.string.of)) accuracySb.append(testResult?.testType?.maxAttempts) accuracySb.append(getString(R.string.tapped_ok)) accuracy_result_text.text = accuracySb.toString() val averageSB = StringBuilder() averageSB.append(getString(R.string.speed)) averageSB.append(testResult?.average) averageSB.append(getString(R.string.milliseconds_descroption)) average_result_text.text = averageSB.toString() } private fun openResultsScreen() { intent = Intent(this, ScienceScoreActivity::class.java) intent.putExtra(FirebaseScienceResult.TAG, firebaseResult as Serializable) startActivity(intent) } private fun updateScienceTestResult() { val fireResult = firebaseResult ?: return FirebaseSender.getInstance().updateScienceTestResult(fireResult) } }
app/src/main/java/com/two_two/checkreaction/ui/finishscreen/ScienceFinishActivity.kt
3850604221
package com.voipgrid.vialer.api import android.content.Context import com.voipgrid.vialer.User import com.voipgrid.vialer.api.models.SystemUser import com.voipgrid.vialer.logging.Logger import com.voipgrid.vialer.middleware.MiddlewareHelper import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * The responsibility of this is to make sure our local user information matches the information stored * in the api. * */ class UserSynchronizer(private val voipgridApi: VoipgridApi, private val context: Context, private val secureCalling: SecureCalling) { private val logger = Logger(this) /** * Sync our local user information with that on voipgrid. * */ suspend fun sync() { syncVoipgridUser() val voipgridUser = User.voipgridUser ?: return syncUserDestinations() if (!voipgridUser.hasVoipAccount()) { handleMissingVoipAccount() return } syncVoipAccount(voipgridUser) if (User.hasVoipAccount) { secureCalling.updateApiBasedOnCurrentPreferenceSetting() MiddlewareHelper.registerAtMiddleware(context) } } /** * Temporary method for java interop, to be removed after SettingsActivity has been * reverted to Kotlin. * */ fun syncWithCallback(callback: () -> Unit) = GlobalScope.launch(Dispatchers.IO) { sync() callback.invoke() } /** * If there is no voip account we want to make sure that our local version * reflects that. * */ private fun handleMissingVoipAccount() { logger.i("User does not have a VoIP account, disabling sip") User.voipAccount = null User.voip.hasEnabledSip = false } /** * Fetch the voipgrid user from the api and update our stored version. * */ private suspend fun syncVoipgridUser() = withContext(Dispatchers.IO) { val response = voipgridApi.systemUser().execute() if (!response.isSuccessful) { logger.e("Unable to retrieve a system user") return@withContext } User.voipgridUser = response.body() User.voip.isAccountSetupForSip = true } /** * Sync the voip account with the remote version. * */ private suspend fun syncVoipAccount(voipgridUser: SystemUser) = withContext(Dispatchers.IO) { val response = voipgridApi.phoneAccount(voipgridUser.voipAccountId).execute() if (!response.isSuccessful) { logger.e("Unable to retrieve voip account from api") return@withContext } val voipAccount = response.body() ?: return@withContext if (voipAccount.accountId == null) { handleMissingVoipAccount() return@withContext } User.voipAccount = response.body() } private suspend fun syncUserDestinations() = withContext(Dispatchers.IO) { val response = voipgridApi.fetchDestinations().execute() if (!response.isSuccessful) { logger.e("Unable to retrieve sync user destinations: " + response.code()) return@withContext } val destinations = response.body()?.objects ?: return@withContext User.internal.destinations = destinations } }
app/src/main/java/com/voipgrid/vialer/api/UserSynchronizer.kt
2465089919
package fr.free.nrw.commons.modifications import android.content.ContentProviderClient import android.content.ContentValues import android.database.MatrixCursor import android.database.sqlite.SQLiteDatabase import android.net.Uri import android.os.RemoteException import com.nhaarman.mockito_kotlin.* import fr.free.nrw.commons.BuildConfig import fr.free.nrw.commons.TestCommonsApplication import fr.free.nrw.commons.modifications.ModificationsContentProvider.BASE_URI import fr.free.nrw.commons.modifications.ModifierSequenceDao.Table.* import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(constants = BuildConfig::class, sdk = [21], application = TestCommonsApplication::class) class ModifierSequenceDaoTest { private val mediaUrl = "http://example.com/" private val columns = arrayOf(COLUMN_ID, COLUMN_MEDIA_URI, COLUMN_DATA) private val client: ContentProviderClient = mock() private val database: SQLiteDatabase = mock() private val contentValuesCaptor = argumentCaptor<ContentValues>() private lateinit var testObject: ModifierSequenceDao @Before fun setUp() { testObject = ModifierSequenceDao { client } } @Test fun createFromCursorWithEmptyModifiers() { testObject.fromCursor(createCursor("")).let { assertEquals(mediaUrl, it.mediaUri.toString()) assertEquals(BASE_URI.buildUpon().appendPath("1").toString(), it.contentUri.toString()) assertTrue(it.modifiers.isEmpty()) } } @Test fun createFromCursorWtihCategoryModifier() { val cursor = createCursor("{\"name\": \"CategoriesModifier\", \"data\": {}}") val seq = testObject.fromCursor(cursor) assertEquals(1, seq.modifiers.size) assertTrue(seq.modifiers[0] is CategoryModifier) } @Test fun createFromCursorWithRemoveModifier() { val cursor = createCursor("{\"name\": \"TemplateRemoverModifier\", \"data\": {}}") val seq = testObject.fromCursor(cursor) assertEquals(1, seq.modifiers.size) assertTrue(seq.modifiers[0] is TemplateRemoveModifier) } @Test fun deleteSequence() { whenever(client.delete(isA(), isNull(), isNull())).thenReturn(1) val seq = testObject.fromCursor(createCursor("")) testObject.delete(seq) verify(client).delete(eq(seq.contentUri), isNull(), isNull()) } @Test(expected = RuntimeException::class) fun deleteTranslatesRemoteExceptions() { whenever(client.delete(isA(), isNull(), isNull())).thenThrow(RemoteException("")) val seq = testObject.fromCursor(createCursor("")) testObject.delete(seq) } @Test fun saveExistingSequence() { val modifierJson = "{\"name\":\"CategoriesModifier\",\"data\":{}}" val expectedData = "{\"modifiers\":[$modifierJson]}" val cursor = createCursor(modifierJson) val seq = testObject.fromCursor(cursor) testObject.save(seq) verify(client).update(eq(seq.contentUri), contentValuesCaptor.capture(), isNull(), isNull()) contentValuesCaptor.firstValue.let { assertEquals(2, it.size()) assertEquals(mediaUrl, it.get(COLUMN_MEDIA_URI)) assertEquals(expectedData, it.get(COLUMN_DATA)) } } @Test fun saveNewSequence() { val expectedContentUri = BASE_URI.buildUpon().appendPath("1").build() whenever(client.insert(isA(), isA())).thenReturn(expectedContentUri) val seq = ModifierSequence(Uri.parse(mediaUrl)) testObject.save(seq) assertEquals(expectedContentUri.toString(), seq.contentUri.toString()) verify(client).insert(eq(ModificationsContentProvider.BASE_URI), contentValuesCaptor.capture()) contentValuesCaptor.firstValue.let { assertEquals(2, it.size()) assertEquals(mediaUrl, it.get(COLUMN_MEDIA_URI)) assertEquals("{\"modifiers\":[]}", it.get(COLUMN_DATA)) } } @Test(expected = RuntimeException::class) fun saveTranslatesRemoteExceptions() { whenever(client.insert(isA(), isA())).thenThrow(RemoteException("")) testObject.save(ModifierSequence(Uri.parse(mediaUrl))) } @Test fun createTable() { onCreate(database) verify(database).execSQL(CREATE_TABLE_STATEMENT) } @Test fun updateTable() { onUpdate(database, 1, 2) inOrder(database) { verify<SQLiteDatabase>(database).execSQL(DROP_TABLE_STATEMENT) verify<SQLiteDatabase>(database).execSQL(CREATE_TABLE_STATEMENT) } } @Test fun deleteTable() { onDelete(database) inOrder(database) { verify<SQLiteDatabase>(database).execSQL(DROP_TABLE_STATEMENT) verify<SQLiteDatabase>(database).execSQL(CREATE_TABLE_STATEMENT) } } private fun createCursor(modifierJson: String) = MatrixCursor(columns, 1).apply { addRow(listOf("1", mediaUrl, "{\"modifiers\": [$modifierJson]}")) moveToFirst() } }
app/src/test/kotlin/fr/free/nrw/commons/modifications/ModifierSequenceDaoTest.kt
1242312802
/* * You can change the height of the bmi calculator down below. * First enter your weight in kg, then * the bmi calculator will give you your bmi and tell you if you are underweight, normal, or overweight */ import java.util.Scanner fun main(args: Array<String>) { // Height val height = 1.84 /*Change ^ for your height(m)*/ // Weight val w = Scanner(System.`in`) println("How heavy are you in kg?") val weight = w.nextDouble() println(weight.toString() + "kg") print("How tall are you?") println(" " + height + "m") val bmi = weight / (height * height) println("BMI: " + bmi) if (bmi < 16) { println("You are severely underweight!") } else if (bmi < 17) { println("You are moderately underweight!") } else if (bmi <= 18.5) { println("You are a little bit underweight!") } else if (bmi <= 25) { println("Your bmi is normal") } else if (bmi <= 30) { println("You are overweight!") } else if (bmi <= 35) { println("You are obese!") } else if (bmi >= 35) { println("You are morbidly obese!") } }
utilities/bmi.kt
336562162
package com.nao20010128nao.DroidComplex import android.support.v4.app.* import java.util.* class UsefulPagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) { internal var pages: MutableList<BaseFragment> = ArrayList() fun addTab(page: BaseFragment) { pages.add(page) notifyDataSetChanged() } override fun getCount(): Int = pages.size override fun getItem(p1: Int): Fragment = pages[p1] override fun getPageTitle(position: Int): CharSequence = pages[position].name }
app/src/main/java/com/nao20010128nao/DroidComplex/UsefulPagerAdapter.kt
3559837739
/* * 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.annotation import com.google.android.libraries.pcc.chronicle.api.StorageMedia /** * This annotation can be used to describe a [ManagementStrategy] for Chronicle data. When the * [DataCacheStoreAnnotationProcessor] plugin is present, it will operate on all types with this * annotation. When processed, this annotation will generate a [ManagementStrategy] object for the * data. The parameter `storageMedia` can be one of the [StorageMedia] enumerated types, or the * default is `StorageMedia.MEMORY`. */ @Retention(AnnotationRetention.SOURCE) @Target(AnnotationTarget.CLASS) annotation class DataCacheStore( val ttl: String, val maxItems: Int, val storageMedia: StorageMedia = StorageMedia.MEMORY )
java/com/google/android/libraries/pcc/chronicle/annotation/DataCacheStore.kt
2003996573
package org.buffer.android.boilerplate.data.source import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.whenever import org.buffer.android.boilerplate.data.repository.BufferooCache import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class BufferooDataStoreFactoryTest { private lateinit var bufferooDataStoreFactory: BufferooDataStoreFactory private lateinit var bufferooCache: BufferooCache private lateinit var bufferooCacheDataStore: BufferooCacheDataStore private lateinit var bufferooRemoteDataStore: BufferooRemoteDataStore @Before fun setUp() { bufferooCache = mock() bufferooCacheDataStore = mock() bufferooRemoteDataStore = mock() bufferooDataStoreFactory = BufferooDataStoreFactory(bufferooCache, bufferooCacheDataStore, bufferooRemoteDataStore) } //<editor-fold desc="Retrieve Data Store"> @Test fun retrieveDataStoreWhenNotCachedReturnsRemoteDataStore() { stubBufferooCacheIsCached(false) val bufferooDataStore = bufferooDataStoreFactory.retrieveDataStore() assert(bufferooDataStore is BufferooRemoteDataStore) } @Test fun retrieveDataStoreWhenCacheExpiredReturnsRemoteDataStore() { stubBufferooCacheIsCached(true) stubBufferooCacheIsExpired(true) val bufferooDataStore = bufferooDataStoreFactory.retrieveDataStore() assert(bufferooDataStore is BufferooRemoteDataStore) } @Test fun retrieveDataStoreReturnsCacheDataStore() { stubBufferooCacheIsCached(true) stubBufferooCacheIsExpired(false) val bufferooDataStore = bufferooDataStoreFactory.retrieveDataStore() assert(bufferooDataStore is BufferooCacheDataStore) } //</editor-fold> //<editor-fold desc="Retrieve Remote Data Store"> @Test fun retrieveRemoteDataStoreReturnsRemoteDataStore() { val bufferooDataStore = bufferooDataStoreFactory.retrieveRemoteDataStore() assert(bufferooDataStore is BufferooRemoteDataStore) } //</editor-fold> //<editor-fold desc="Retrieve Cache Data Store"> @Test fun retrieveCacheDataStoreReturnsCacheDataStore() { val bufferooDataStore = bufferooDataStoreFactory.retrieveCacheDataStore() assert(bufferooDataStore is BufferooCacheDataStore) } //</editor-fold> //<editor-fold desc="Stub helper methods"> private fun stubBufferooCacheIsCached(isCached: Boolean) { whenever(bufferooCache.isCached()) .thenReturn(isCached) } private fun stubBufferooCacheIsExpired(isExpired: Boolean) { whenever(bufferooCache.isExpired()) .thenReturn(isExpired) } //</editor-fold> }
data/src/test/java/org/buffer/android/boilerplate/data/source/BufferooDataStoreFactoryTest.kt
3833908565
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ @file:Suppress("JAVA_MODULE_DOES_NOT_DEPEND_ON_MODULE") package com.almasb.fxgl.core.math import javafx.geometry.Point2D import org.hamcrest.CoreMatchers.`is` import org.hamcrest.CoreMatchers.not import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.closeTo import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test /** * * * @author Almas Baimagambetov ([email protected]) */ class Vec2Test { @Test fun `Copy`() { val v1 = Vec2() val v2 = v1.copy() assertTrue(v1 == v2) assertFalse(v1 === v2) } @Test fun `Copy ctor`() { val v1 = Vec2(Vec2(3f, 5f)) assertTrue(v1.x == 3f) assertTrue(v1.y == 5f) } @Test fun `Set zero`() { val v1 = Vec2(13.0f, 10.0f) v1.setZero() assertTrue(v1.x == 0.0f) assertTrue(v1.y == 0.0f) v1.x = 3.0f v1.y = 2.0f v1.reset() assertTrue(v1.x == 0.0f) assertTrue(v1.y == 0.0f) } @Test fun `Copy and set from Point2D`() { val v = Vec2(Point2D(10.0, 15.5)) assertThat(v, `is`(Vec2(10.0, 15.5))) v.set(Point2D(-5.0, 3.0)) assertThat(v, `is`(Vec2(-5.0, 3.0))) } @Test fun `Set from angle`() { val v = Vec2().setFromAngle(45.0) assertThat(v.x.toDouble(), closeTo(0.7, 0.01)) assertThat(v.y.toDouble(), closeTo(0.7, 0.01)) } @Test fun `Operations`() { val v1 = Vec2(5.0, 5.0) val v2 = v1.add(Point2D(5.0, 5.0)) assertThat(v2, `is`(Vec2(10.0, 10.0))) val v3 = v2.add(Vec2(-5.0, -10.0)) assertThat(v3, `is`(Vec2(5.0, 0.0))) val v4 = v3.sub(Point2D(5.0, 5.0)) assertThat(v4, `is`(Vec2(0.0, -5.0))) val v5 = v4.sub(Vec2(5.0, -5.0)) assertThat(v5, `is`(Vec2(-5.0, 0.0))) val v6 = v5.mul(3.0) assertThat(v6, `is`(Vec2(-15.0, 0.0))) val v7 = v6.negate() assertThat(v7, `is`(Vec2(15.0, -0.0))) v7.negateLocal() assertThat(v7, `is`(Vec2(-15.0, 0.0))) v7.addLocal(Vec2(3.0, 3.0)) assertThat(v7, `is`(Vec2(-12.0, 3.0))) v7.addLocal(4.0, 3.0) assertThat(v7, `is`(Vec2(-8.0, 6.0))) v7.subLocal(Vec2(4.0, 2.0)) assertThat(v7, `is`(Vec2(-12.0, 4.0))) v7.subLocal(4.0, 3.0) assertThat(v7, `is`(Vec2(-16.0, 1.0))) } @Test fun `Perpendicular CCW`() { val v1 = Vec2(10f, 5f) val v2 = v1.perpendicularCCW() assertThat(v2, `is`(Vec2(5f, -10f))) } @Test fun `Perpendicular CW`() { val v1 = Vec2(10f, 5f) val v2 = v1.perpendicularCW() assertThat(v2, `is`(Vec2(-5f, 10f))) } @Test fun `Length`() { val v = Vec2(3f, -4f) assertThat(v.length(), `is`(5f)) assertThat(v.lengthSquared(), `is`(25f)) } @Test fun `Distance`() { val v = Vec2(3f, -4f) assertThat(v.distance(Vec2(5f, 4f)), closeTo(8.246, 0.01)) assertThat(v.distanceF(Vec2(5f, 4f)) * 1.0, closeTo(8.246, 0.01)) } @Test fun `Distance squared`() { val v1 = Vec2(4f, 3f) assertThat(v1.distanceSquared(0.0, 0.0), `is`(25.0)) assertThat(v1.distanceSquared(Vec2()), `is`(25.0f)) } @Test fun `Normalize`() { val v = Vec2(1f, 1f).normalize() assertThat(v.x.toDouble(), closeTo(0.7, 0.01)) assertThat(v.y.toDouble(), closeTo(0.7, 0.01)) v.x = 0.0f v.y = 0.0f val v2 = v.normalize() assertTrue(v2 == v) } @Test fun `getLengthAndNormalize should return 0 if square of the hypotenuse vector is less than FXGLMath epsilon constant`(){ val v = Vec2().getLengthAndNormalize() assertThat(v, `is`(0f)) } @Test fun `Absolute`() { val v = Vec2(-1f, 1f).abs() assertThat(v, `is`(Vec2(1f, 1f))) assertThat(Vec2(-3f, -4f).absLocal(), `is`(Vec2(3f, 4f))) } @Test fun `Angle`() { val v = Vec2(-1f, 1f) assertThat(v.angle(), `is`(135f)) assertThat(v.angle(Vec2(0f, 1f)), `is`(45f)) assertThat(v.angle(Point2D(0.0, -1.0)), `is`(225f)) } @Test fun `Set length`() { val v = Vec2(3f, -4f) v.setLength(13.0) assertEquals(13f, v.length(), 0.0001f) } @Test fun `Test equality`() { val v1 = Vec2() val v2 = Vec2() assertThat(v1, `is`(v1)) assertThat(v1, `is`(v2)) assertThat(v2, `is`(v1)) assertThat(v1.hashCode(), `is`(v2.hashCode())) v2.x = 10.0f assertThat(v1, `is`(not(v2))) assertThat(v1.hashCode(), `is`(not(v2.hashCode()))) v1.x = 10.0f assertThat(v1, `is`(v2)) assertThat(v1.hashCode(), `is`(v2.hashCode())) v2.y = -3.0f assertThat(v1, `is`(not(v2))) assertThat(v1.hashCode(), `is`(not(v2.hashCode()))) v1.y = -3.0f assertThat(v1, `is`(v2)) assertThat(v1.hashCode(), `is`(v2.hashCode())) } @Test fun `Equals and close to Point2D`() { val v = Vec2(0.0f, 0.0f) assertTrue(v.isCloseTo(Point2D.ZERO, 0.0)) v.set(15.0f, -33.5f) assertTrue(v.isCloseTo(Point2D(15.0, -33.5), 0.0)) v.set(15.0f, -33.4f) assertFalse(v.isCloseTo(Point2D(15.0, -33.5), 0.0)) v.set(15.0f, -33.5001f) assertTrue(v.isCloseTo(Point2D(15.0, -33.5), 0.001)) v.set(15.0f, -33.50001f) assertTrue(v.isCloseTo(Point2D(15.0, -33.5), 0.01)) assertTrue(v.isCloseTo(Point2D(15.0, -33.5), 0.001)) assertTrue(v.isCloseTo(Point2D(15.0, -33.5), 0.0001)) assertTrue(v.isCloseTo(Point2D(15.0, -33.5), 0.00002)) assertFalse(v.isCloseTo(Point2D(15.0, -33.5), 0.000002)) assertFalse(v.isCloseTo(Point2D(15.0, -33.5), 0.000001)) v.set(15.01f, -33.49f) assertTrue(v.isCloseTo(Point2D(15.0, -33.5), 0.1)) v.set(Vec2(15.01f, 8.99f)) assertTrue(v.isCloseTo(Point2D(15.0, 9.0), 0.1)) v.set(900.001f, -1501.330f) assertFalse(v.isNearlyEqualTo(Point2D(900.0, -1501.0))) assertTrue(v.isNearlyEqualTo(Point2D(900.0, -1501.3))) } @Test fun `Midpoint`() { val v1 = Vec2(5.0f, 2.0f) val v2 = Vec2(0.0f, 0.0f) assertThat(v1.midpoint(v2), `is`(Vec2(2.5f, 1.0f))) assertThat(v1.midpoint(Point2D.ZERO), `is`(Vec2(2.5f, 1.0f))) } @Test fun `To Point2D`() { val v1 = Vec2(5.0f, 2.0f) assertThat(v1.toPoint2D(), `is`(Point2D(5.0, 2.0))) } @Test fun `To String`() { val v1 = Vec2(5.0f, 2.0f) assertThat(v1.toString(), `is`("(5.0,2.0)")) } @Test fun `From angle`() { val v1 = Vec2.fromAngle(45.0) assertThat(v1, `is`(Vec2(0.70697117, 0.70724237))) } @Test fun `Dot product`() { assertThat(Vec2.dot(Vec2(2f, 3f), Vec2(4f, 7f)), `is`(29f)) } @Test fun `Cross product`() { assertThat(Vec2.cross(Vec2(2f, 3f), Vec2(4f, 7f)), `is`(2f)) } @Test fun `Min to out should return min x and y from both vector when min x and y are in one vector`() { val v1 = Vec2(2f, 3f) val v2 = Vec2(4f, 5f) val v3 = Vec2() Vec2.minToOut(v1, v2, v3) assertThat(v3, `is`(v1)) Vec2.minToOut(v2, v1, v3) assertThat(v3, `is`(v1)) } @Test fun `Min to out should return min x and y from both vectors when min x and y are in different vectors`() { val v1 = Vec2(2f, 5f) val v2 = Vec2(4f, 3f) val v3 = Vec2() Vec2.minToOut(v1, v2, v3) assertThat(v3, `is`(Vec2(2f, 3f))) Vec2.minToOut(v2, v1, v3) assertThat(v3, `is`(Vec2(2f, 3f))) } @Test fun `Max to out should return max x and y from both vector when max x and y are in one vector`() { val v1 = Vec2(2f, 3f) val v2 = Vec2(4f, 5f) val v3 = Vec2() Vec2.maxToOut(v1, v2, v3) assertThat(v3, `is`(v2)) Vec2.maxToOut(v2, v1, v3) assertThat(v3, `is`(v2)) } @Test fun `Max to out should return max x and y from both vectors when max x and y are in different vectors`() { val v1 = Vec2(2f, 5f) val v2 = Vec2(4f, 3f) val v3 = Vec2() Vec2.maxToOut(v1, v2, v3) assertThat(v3, `is`(Vec2(4f, 5f))) Vec2.maxToOut(v2, v1, v3) assertThat(v3, `is`(Vec2(4f, 5f))) } @Test fun `Equals should return true if passed the same instance`() { val v1 = Vec2() assertTrue(v1 == v1) } @Test fun `Equals should return true if passed the same type and coordinates`() { val v1 = Vec2(1f, 1f) val v2 = Vec2(1f, 1f) assertTrue(v1 == v2) } @Test fun `Equals should return false if passed the same type and different y coordinates`() { val v1 = Vec2(1f, 1f) val v2 = Vec2(1f, 2f) assertFalse(v1 == v2) } @Test fun `Equals should return false if passed the same type and different x coordinates`() { val v1 = Vec2(1f, 1f) val v2 = Vec2(2f, 1f) assertFalse(v1 == v2) } @Test fun `Equals should return false if passed a different type`() { val v1 = Vec2(1f, 1f) assertFalse(v1.equals(1)) } @Test fun `Cross to out unsafe`() { val v1 = Vec2(1f, 1f) val v2 = Vec2() Vec2.crossToOutUnsafe(v1, 5.0f, v2) assertThat(v2, `is`(Vec2(5.0, -5.0))) Vec2.crossToOutUnsafe(5.0f, v1, v2) assertThat(v2, `is`(Vec2(-5.0, 5.0))) } }
fxgl-core/src/test/kotlin/com/almasb/fxgl/core/math/Vec2Test.kt
2303225466
/* * Copyright (C) 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 com.example.constraintlayout import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.layoutId import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.constraintlayout.compose.* import java.util.* @Preview(group = "new") @Composable public fun ExampleLayout() { ConstraintLayout( ConstraintSet(""" { Header: { exportAs: 'example 3'}, g1: { type: 'vGuideline', start: 80 }, g2: { type: 'vGuideline', end: 80 }, button: { width: 'spread', top: ['title', 'bottom', 16], start: ['g1', 'start'], end: ['g2', 'end'] }, title: { width: { value: 'wrap', max: 300 }, centerVertically: 'parent', start: ['g1', 'start'], end: ['g2','end'] } } """), modifier = Modifier.fillMaxSize() ) { Button( modifier = Modifier.layoutId("button"), onClick = {}, ) { Text(text = stringResource(id = R.string.log_in)) } Text(modifier = Modifier.layoutId("title").background(Color.Red), text = "ABC dsa sdfs sdf adfas asdas asdad asdas",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) } }
projects/ComposeConstraintLayout/app/src/main/java/com/example/constraintlayout/test3.kt
4214603619
package assertk /* * Copyright (C) 2018 Touchlab, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ actual open class ThreadLocalRef<T> actual constructor(private val initial: () -> T) : ThreadLocal<T>() { override fun initialValue(): T = initial() }
assertk/src/jvmMain/kotlin/assertk/ThreadLocalRef.kt
1202878054
/*- * ========================LICENSE_START================================= * ids-api * %% * Copyright (C) 2019 Fraunhofer AISEC * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * =========================LICENSE_END================================== */ package de.fhg.aisec.ids.api.settings import java.io.Serializable class ConnectorConfig : Serializable { val appstoreUrl = "https://raw.githubusercontent.com/industrial-data-space/templates/master/templates.json" val brokerUrl = "" val ttpHost = "" val ttpPort = 443 val acmeServerWebcon = "" val acmeDnsWebcon = "" val acmePortWebcon = 80 val tosAcceptWebcon = false val dapsUrl = "https://daps.aisec.fraunhofer.de" val keystoreName = "provider-keystore.p12" val keystorePassword = "password" val keystoreAliasName = "1" val truststoreName = "truststore.p12" companion object { private const val serialVersionUID = 1L } }
ids-api/src/main/java/de/fhg/aisec/ids/api/settings/ConnectorConfig.kt
4074007433
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.languages.bukkit.command import com.rpkit.core.command.RPKCommandExecutor import com.rpkit.core.command.result.CommandResult import com.rpkit.core.command.result.IncorrectUsageFailure import com.rpkit.core.command.sender.RPKCommandSender import com.rpkit.languages.bukkit.RPKLanguagesBukkit import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletableFuture.completedFuture class LanguageCommand(private val plugin: RPKLanguagesBukkit) : RPKCommandExecutor { private val languageListCommand = LanguageListCommand(plugin) private val languageListUnderstandingCommand = LanguageListUnderstandingCommand(plugin) private val languageSetUnderstandingCommand = LanguageSetUnderstandingCommand(plugin) override fun onCommand(sender: RPKCommandSender, args: Array<out String>): CompletableFuture<CommandResult> { return if (args.isNotEmpty()) { val newArgs = args.drop(1).toTypedArray() when (args[0].lowercase()) { "list" -> languageListCommand.onCommand(sender, newArgs) "setunderstanding" -> languageSetUnderstandingCommand.onCommand(sender, newArgs) "listunderstanding" -> languageListUnderstandingCommand.onCommand(sender, newArgs) else -> { sender.sendMessage(plugin.messages.languageUsage) completedFuture(IncorrectUsageFailure()) } } } else { sender.sendMessage(plugin.messages.languageUsage) completedFuture(IncorrectUsageFailure()) } } }
bukkit/rpk-languages-bukkit/src/main/kotlin/com/rpkit/languages/bukkit/command/LanguageCommand.kt
2730157622
package fr.free.nrw.commons.explore.paging import androidx.paging.PositionalDataSource import fr.free.nrw.commons.explore.depictions.search.LoadFunction import io.reactivex.Completable import io.reactivex.processors.PublishProcessor import io.reactivex.schedulers.Schedulers import timber.log.Timber abstract class PagingDataSource<T>( private val loadingStates: PublishProcessor<LoadingState> ) : PositionalDataSource<T>() { private var lastExecutedRequest: (() -> Boolean)? = null private fun storeAndExecute(function: () -> Boolean) { function.also { lastExecutedRequest = it }.invoke() } private fun performWithTryCatch(function: () -> Unit) = try { function.invoke() loadingStates.offer(LoadingState.Complete) } catch (e: Exception) { Timber.e(e) loadingStates.offer(LoadingState.Error) } override fun loadInitial( params: LoadInitialParams, callback: LoadInitialCallback<T> ) { storeAndExecute { loadingStates.offer(LoadingState.InitialLoad) performWithTryCatch { callback.onResult( getItems(params.requestedLoadSize, params.requestedStartPosition), params.requestedStartPosition ) } } } override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<T>) { storeAndExecute { loadingStates.offer(LoadingState.Loading) performWithTryCatch { callback.onResult(getItems(params.loadSize, params.startPosition)) } } } protected abstract fun getItems(loadSize: Int, startPosition: Int): List<T> fun retryFailedRequest() { Completable.fromAction { lastExecutedRequest?.invoke() } .subscribeOn(Schedulers.io()) .subscribe() } } fun <T> dataSource( loadingStates: PublishProcessor<LoadingState>, loadFunction: LoadFunction<T> ) = object : PagingDataSource<T>(loadingStates) { override fun getItems(loadSize: Int, startPosition: Int): List<T> { return loadFunction(loadSize, startPosition) } }
app/src/main/java/fr/free/nrw/commons/explore/paging/PagingDataSource.kt
1397493729
package com.mrstar.kotlin_playground; fun main(args: Array<String>) { // This is compile error. // for (num in IteratorOperator(10)) { // println(num) // } for (num in IteratorImplementation(10)) { println(num) } for (num in CountLooperWithOperatorClass(10)) { println(num) } for (num in CountLooperWithIteratorClass(10)) { println(num) } val team = Team(listOf( Player("Taro"), Player("Jiro"), Player("Saburo") )) for (member in team){ println(member) } } class IteratorImplementation(val count: Int) : kotlin.collections.Iterator<Int> { var currentCount = 0 override operator fun hasNext(): Boolean = currentCount < count override operator fun next(): Int = currentCount++ } class IteratorOperator(val count: Int) { var currentCount = 0 operator fun hasNext(): Boolean = currentCount < count operator fun next(): Int = currentCount++ } class CountLooperWithIteratorClass(val count: Int) { operator fun iterator() = IteratorImplementation(count) } class CountLooperWithOperatorClass(val count: Int) { operator fun iterator() = IteratorOperator(count) } data class Player(val name: String) data class Team(val members: List<Player>) operator fun Team.iterator() = members.iterator()
kotlin/kotlin_playground/src/main/kotlin/iterator_example.kt
1664579000
package com.zj.example.kotlin.basicsknowledge /** * 方法的扩展 * Created by zhengjiong * date: 2017/9/17 15:18 */ fun main(args: Array<String>) { "abc".pl() //println("abc".multiply()) println("zj".multiply(2)) println("zj" * 2) } fun String.pl() { /** * this代表当前调用此方法的对象,比如现在是abc字符串 */ println(this) } fun String.multiply(num: Int): String { var sb = StringBuilder() for (i in 0 until num) { sb.append(this) } return sb.toString() } /** * times相当于是*, 给String扩展一个*方法 */ operator fun String.times(num: Int): String { var sb = StringBuilder() for (i in 0 until num) { sb.append(this) } return sb.toString() }
src/main/kotlin/com/zj/example/kotlin/basicsknowledge/32.ExtendFunctionExample方法扩展.kt
3077035826
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.bet.coinflipglobal import kotlinx.datetime.Clock import net.perfectdreams.discordinteraktions.common.autocomplete.FocusedCommandOption import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.discord.interactions.autocomplete.AutocompleteContext import net.perfectdreams.loritta.cinnamon.discord.interactions.autocomplete.CinnamonAutocompleteHandler import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.declarations.BetCommand import net.perfectdreams.loritta.cinnamon.discord.utils.NumberUtils import net.perfectdreams.loritta.cinnamon.pudding.data.UserId import kotlin.time.Duration.Companion.minutes class CoinFlipBetGlobalSonhosQuantityAutocompleteExecutor(loritta: LorittaBot) : CinnamonAutocompleteHandler<String>(loritta) { override suspend fun handle(context: AutocompleteContext, focusedOption: FocusedCommandOption): Map<String, String> { val currentInput = focusedOption.value val trueNumber = NumberUtils.convertShortenedNumberToLong( context.i18nContext, currentInput ) val trueNumberAsString = trueNumber.toString() val matchedChoices = mutableSetOf<Long>() for (quantity in CoinFlipBetGlobalExecutor.QUANTITIES) { if (focusedOption.value.isEmpty() || quantity.toString().startsWith(trueNumberAsString)) { matchedChoices.add(quantity) } } val discordChoices = mutableMapOf<String, String>() val matchmakingStats = loritta.pudding.bets.getUserCoinFlipBetGlobalMatchmakingStats( UserId(context.sender.id.value), matchedChoices.toList(), Clock.System.now().minus(5.minutes) ) for (choice in matchedChoices) { val mmStat = matchmakingStats[choice] discordChoices[ buildString { if (mmStat == null) { if (choice == 0L) { append( context.i18nContext.get( BetCommand.COINFLIP_GLOBAL_I18N_PREFIX.Options.Quantity.Choice.JustForFun ) ) } else { append( context.i18nContext.get( BetCommand.COINFLIP_GLOBAL_I18N_PREFIX.Options.Quantity.Choice.MatchmakingSonhos( choice ) ) ) } } else { if (mmStat.userPresentInMatchmakingQueue) { append( context.i18nContext.get( BetCommand.COINFLIP_GLOBAL_I18N_PREFIX.Options.Quantity.Choice.QuitMatchmakingQueue( choice ) ) ) } else { if (choice == 0L) { append( context.i18nContext.get( BetCommand.COINFLIP_GLOBAL_I18N_PREFIX.Options.Quantity.Choice.JustForFun ) ) } else { append( context.i18nContext.get( BetCommand.COINFLIP_GLOBAL_I18N_PREFIX.Options.Quantity.Choice.MatchmakingSonhos( choice ) ) ) } val averageTimeOnQueue = mmStat.averageTimeOnQueue if (averageTimeOnQueue != null) { append(" (${ context.i18nContext.get( BetCommand.COINFLIP_GLOBAL_I18N_PREFIX.Options.Quantity.Choice.AverageTimeInSeconds( averageTimeOnQueue.toMillis().toDouble() / 1_000 ) ) })") } append(" ") append("[") if (mmStat.playersPresentInMatchmakingQueue) { append( context.i18nContext.get(BetCommand.COINFLIP_GLOBAL_I18N_PREFIX.Options.Quantity.Choice.PlayersInMatchmakingQueue) ) append(" | ") } append( context.i18nContext.get( BetCommand.COINFLIP_GLOBAL_I18N_PREFIX.Options.Quantity.Choice.RecentMatches( mmStat.recentMatches ) ) ) append("]") } } } ] = if (mmStat?.userPresentInMatchmakingQueue == true) "q$choice" else choice.toString() } return discordChoices } }
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/economy/bet/coinflipglobal/CoinFlipBetGlobalSonhosQuantityAutocompleteExecutor.kt
2717430822
package com.darakeon.dfm.dialogs import android.app.AlertDialog import android.app.DatePickerDialog import android.app.Dialog import android.content.res.Resources import android.view.View import com.darakeon.dfm.testutils.BaseTest import com.darakeon.dfm.testutils.getPrivate import com.darakeon.dfm.testutils.robolectric.waitTasks import com.darakeon.dfm.utils.activity.TestActivity import com.darakeon.dfm.utils.api.ActivityMock import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.shadows.ShadowAlertDialog.getLatestAlertDialog import java.util.Calendar.DECEMBER import java.util.Calendar.MARCH @RunWith(RobolectricTestRunner::class) class DateDialogTest: BaseTest() { private val yearId = getResId("year") private val monthId = getResId("month") private val dayId = getResId("day") private lateinit var mocker: ActivityMock<TestActivity> private val spinner = 1 private val calendar = 2 @Before fun setup() { mocker = ActivityMock(TestActivity::class) } @Test fun getDateDialogWithDayMonthYear() { var year = 1986 var month = MARCH var day = 27 val activity = mocker.create() activity.getDateDialog(2013, DECEMBER, 23) { y, m, d -> year = y month = m day = d }.show() val dialog = getLatestAlertDialog() as DatePickerDialog assertThat(dialog.datePicker.getPrivate("mMode"), `is`(calendar)) dialog.getButton(Dialog.BUTTON_POSITIVE).performClick() activity.waitTasks(mocker.server) assertThat(day, `is`(23)) assertThat(month, `is`(DECEMBER)) assertThat(year, `is`(2013)) } @Test fun getDateDialogWithMonthYear() { var year = 1986 var month = MARCH val activity = mocker.create() activity.getDateDialog(2013, DECEMBER) { y, m -> year = y month = m }.show() val dialog = getLatestAlertDialog() as DatePickerDialog assertThat(dialog.datePicker.getPrivate("mMode"), `is`(spinner)) assertFalse(isVisible(dialog, dayId)) assertTrue(isVisible(dialog, monthId)) assertTrue(isVisible(dialog, yearId)) dialog.getButton(Dialog.BUTTON_POSITIVE).performClick() activity.waitTasks(mocker.server) assertThat(month, `is`(DECEMBER)) assertThat(year, `is`(2013)) } @Test fun getDateDialogWithYear() { var year = 1986 val activity = mocker.create() activity.getDateDialog(2013) { y -> year = y }.show() val dialog = getLatestAlertDialog() as DatePickerDialog assertThat(dialog.datePicker.getPrivate("mMode"), `is`(spinner)) assertFalse(isVisible(dialog, dayId)) assertFalse(isVisible(dialog, monthId)) assertTrue(isVisible(dialog, yearId)) dialog.getButton(Dialog.BUTTON_POSITIVE).performClick() activity.waitTasks(mocker.server) assertThat(year, `is`(2013)) } private fun isVisible(dialog: AlertDialog, resId: Int) = dialog.findViewById<View>(resId) .visibility == View.VISIBLE private fun getResId(name: String) = Resources.getSystem() .getIdentifier(name, "id", "android") }
android/App/src/test/kotlin/com/darakeon/dfm/dialogs/DateDialogTest.kt
1862826816
package com.tlz.rxcommons import android.content.Context import android.content.SharedPreferences import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config /** * Created by LeiShao. * Data 2017/5/24. * Time 19:54. * Email [email protected]. */ @RunWith(RobolectricTestRunner::class) @Config(manifest = Config.NONE) class RxPreferencesTest { lateinit var mPreference: RxPreferences lateinit var mSharePreference: SharedPreferences @Before fun setup(){ mSharePreference = RuntimeEnvironment.application.getSharedPreferences("test", Context.MODE_PRIVATE) mPreference = RxPreferences(mSharePreference) } @Test fun observeBoolean() { var value = false mPreference.observeBoolean("testBoolean", false ,false) .subscribe({ value = it }) mSharePreference.edit().putBoolean("testBoolean", true).apply() Assert.assertTrue(value) } @Test fun observeString() { var value = "test" mPreference.observeString("testString", "" , false) .subscribe({ value = it }) mSharePreference.edit().putString("testString", "test").apply() Assert.assertEquals(value, "test") } @Test fun observeInt() { } @Test fun observeLong() { } @Test fun observeFloat() { } @Test fun observeStringSet() { } }
lib/src/test/java/com/tlz/rxcommons/RxPreferencesTest.kt
2664626928
package com.angcyo.uiview.base import android.os.Bundle import android.support.v4.content.ContextCompat import android.view.LayoutInflater import com.angcyo.uiview.R import com.angcyo.uiview.container.ContentLayout import com.angcyo.uiview.github.tablayout.SlidingTabLayout import com.angcyo.uiview.skin.SkinHelper import com.angcyo.uiview.view.IView import com.angcyo.uiview.widget.viewpager.UIPagerAdapter import com.angcyo.uiview.widget.viewpager.UIViewPager /** * Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved. * 项目名称: * 类的描述:标准的SlidingTab和UIViewPager组合的界面 * 创建人员:Robi * 创建时间:2017/06/28 11:43 * 修改人员:Robi * 修改时间:2017/06/28 11:43 * 修改备注: * Version: 1.0.0 */ abstract class UISlidingTabView : UIContentView(), UIBaseView.OnViewLoadListener { companion object { fun baseInitTabLayout(tabLayout: SlidingTabLayout) { val density = tabLayout.context.resources.displayMetrics.density tabLayout.setIndicatorWidthEqualTitle(true) //tabLayout.indicatorWidth = 100 * density tabLayout.textSelectColor = SkinHelper.getSkin().themeSubColor tabLayout.textUnselectColor = ContextCompat.getColor(tabLayout.context, R.color.base_text_color) tabLayout.indicatorHeight = 1 * density tabLayout.indicatorColor = SkinHelper.getSkin().themeSubColor tabLayout.indicatorStyle = SlidingTabLayout.STYLE_NORMAL tabLayout.indicatorCornerRadius = 3 * density //指示器的圆角 tabLayout.indicatorMarginLeft = 0f //指示器左偏移的距离 tabLayout.tabPadding = 5 * density tabLayout.setTextSizePx(SkinHelper.getSkin().mainTextSize) tabLayout.isTabSpaceEqual = false //tab 是否平分 TabLayout的宽度 tabLayout.setItemNoBackground(false) //item 是否禁用点击效果 } } override fun onShowLoadView() { showLoadView() } override fun onHideLoadView() { hideLoadView() } val pages: ArrayList<TabPageBean> by lazy { arrayListOf<TabPageBean>() } val mViewPager: UIViewPager by lazy { val uiViewPager = mViewHolder.v<UIViewPager>(R.id.base_view_pager) uiViewPager.setParentUIView(this) uiViewPager } val mSlidingTab: SlidingTabLayout by lazy { mViewHolder.v<SlidingTabLayout>(R.id.base_tab_layout) } override fun inflateContentLayout(baseContentLayout: ContentLayout?, inflater: LayoutInflater?) { inflate(R.layout.base_sliding_tab_view) } override fun onViewLoad() { super.onViewLoad() createPages(pages) initTabLayout(mSlidingTab) initViewPager(mViewPager) mViewPager.adapter = createAdapter() mSlidingTab.setViewPager(mViewPager) } override fun onViewShowFirst(bundle: Bundle?) { super.onViewShowFirst(bundle) // createPages(pages) // mViewPager.adapter = createAdapter() // // initTabLayout(mSlidingTab) // initViewPager(mViewPager) // // mSlidingTab.setViewPager(mViewPager) } open fun initTabLayout(tabLayout: SlidingTabLayout) { baseInitTabLayout(tabLayout) } open fun initViewPager(viewPager: UIViewPager) { viewPager.offscreenPageLimit = getPageCount() } /**重写此方法, 创建页面*/ open fun createPages(pages: ArrayList<TabPageBean>) { } /**页面数量*/ open fun getPageCount(): Int = pages.size /**对应页面*/ open fun getPageIView(position: Int): IView = pages[position].iView /**页面标题*/ open fun getPageTitle(position: Int): String? = pages[position].title open fun createAdapter() = object : UIPagerAdapter() { override fun getIView(position: Int): IView = (getPageIView(position) as UIBaseView).apply { this.bindParentILayout(mILayout) this.setOnViewLoadListener(this@UISlidingTabView) } override fun getCount(): Int = getPageCount() override fun getPageTitle(position: Int): CharSequence? = [email protected](position) } /**页面*/ data class TabPageBean(val iView: IView, val title: String? = null) }
uiview/src/main/java/com/angcyo/uiview/base/UISlidingTabView.kt
2886584660
/* * 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.homesampleapp.data import android.content.Context import androidx.datastore.core.CorruptionException import androidx.datastore.core.DataStore import androidx.datastore.core.Serializer import androidx.datastore.dataStore import com.google.homesampleapp.Devices import com.google.protobuf.InvalidProtocolBufferException import java.io.InputStream import java.io.OutputStream object DevicesSerializer : Serializer<Devices> { override val defaultValue: Devices = Devices.getDefaultInstance() override suspend fun readFrom(input: InputStream): Devices { try { return Devices.parseFrom(input) } catch (exception: InvalidProtocolBufferException) { throw CorruptionException("Cannot read proto.", exception) } } override suspend fun writeTo(t: Devices, output: OutputStream) = t.writeTo(output) } val Context.devicesDataStore: DataStore<Devices> by dataStore(fileName = "devices_store.proto", serializer = DevicesSerializer)
app/src/main/java/com/google/homesampleapp/data/DevicesSerializer.kt
1165385055
package com.sksamuel.kotest.specs.describe import io.kotest.core.spec.style.DescribeSpec import io.kotest.matchers.shouldBe class DescribeSpecLambdaTest : DescribeSpec({ var name: String? = null describe("context 1") { it("the name should start off null") { name.shouldBe(null) } name = "foo" context("the name should be foo in this context") { name.shouldBe("foo") it("should still be foo for this nested test") { name.shouldBe("foo") } name = "boo" it("now the name should be boo") { name.shouldBe("boo") } } it("it should still be boo as this test should run after all the above") { name.shouldBe("boo") } name = "koo" it("now the name should be set to koo") { name.shouldBe("koo") } } describe("context 2 should run after context 1") { it("name should still be the last value which was koo") { name shouldBe "koo" } } describe("Should allow nested describe scope") { describe("Nested") { it("runs") { } context("Runs context") { it("Runs") { } } } } })
kotest-tests/kotest-tests-core/src/jvmTest/kotlin/com/sksamuel/kotest/specs/describe/DescribeSpecLambdaTest.kt
575922615
package se.ansman.kotshi @JsonSerializable @Polymorphic(labelKey = "type", onInvalid = Polymorphic.Fallback.NULL) sealed class SealedClassOnInvalidNull { @JsonSerializable @PolymorphicLabel("type1") data class Subclass1(val foo: String) : SealedClassOnInvalidNull() @JsonSerializable @JsonDefaultValue object Default : SealedClassOnInvalidNull() }
tests/src/main/kotlin/se/ansman/kotshi/SealedClassOnInvalidNull.kt
1938518442
package com.epimorphics.android.myrivers.models import android.util.JsonReader import com.epimorphics.android.myrivers.data.CDEPoint import com.epimorphics.android.myrivers.data.RNAG import com.epimorphics.android.myrivers.helpers.InputStreamHelper import java.io.IOException import java.io.InputStream import java.io.InputStreamReader /** * Consumes an InputStream and converts it to a list of RNAGs * * @see CDEPoint * @see RNAG */ class InputStreamToRNAG : InputStreamHelper() { /** * Converts InputStream to JsonReader and consumes it. * * @param cdePoint CDEPoint to which parsed RNAGs belong * @param inputStream InputStream to be consumed * * @throws IOException */ @Throws(IOException::class) fun readJsonStream(cdePoint: CDEPoint, inputStream: InputStream) { val reader = JsonReader(InputStreamReader(inputStream, "UTF-8")) reader.isLenient = true reader.use { readMessagesArray(cdePoint, reader) } } /** * Focuses on the array of objects that are to be converted to RNAGs and parses * them one by one. * * @param cdePoint CDEPoint to which parsed RNAGs belong * @param reader JsonReader to be consumed * * @throws IOException */ @Throws(IOException::class) fun readMessagesArray(cdePoint: CDEPoint, reader: JsonReader) { reader.beginObject() while (reader.hasNext()) { val name = reader.nextName() if (name == "items") { reader.beginArray() while (reader.hasNext()) { readMessage(cdePoint, reader) } reader.endArray() } else { reader.skipValue() } } reader.endObject() } /** * Converts single JsonObject to RNAG and adds it to the given CDEPoint's rnagList. * * @param cdePoint CDEPoint to which parsed RNAG belongs * @param reader JsonReader to be consumed * * @throws IOException */ @Throws(IOException::class) fun readMessage(cdePoint: CDEPoint, reader: JsonReader) { var element = "" var rating = "" var activity = "" var category = "" var year = "" reader.beginObject() while (reader.hasNext()) { val name = reader.nextName() when (name) { "activity" -> activity = readItemToString(reader) "classificationItem" -> element = readItemToString(reader) "classification" -> rating = readClassificationToString(reader) "classificationYear" -> year = reader.nextString() "category" -> category = readItemToString(reader) else -> reader.skipValue() } } reader.endObject() cdePoint.addRNAG(RNAG(element, rating, activity, category, year.toInt())) } /** * Reads group value from the reader and returns it as a string * * @param reader JsonReader to be consumed * @return String group value * * @throws IOException */ fun readClassificationToString(reader: JsonReader): String { var item = "" reader.beginObject() while (reader.hasNext()) { val name = reader.nextName() if (name == "classificationValue") { item = readItemToString(reader) } else { reader.skipValue() } } reader.endObject() return item } }
android/app/src/main/java/com/epimorphics/android/myrivers/models/InputStreamToRNAG.kt
1822046581
package net.pterodactylus.sone.text import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.junit.Test /** * Unit test for [FreenetLinkPart]. */ class FreenetLinkPartTest { @Test fun linkIsUsedAsTitleIfNoTextIsGiven() { assertThat(FreenetLinkPart("link", "text", true).title, equalTo("link")) } }
src/test/kotlin/net/pterodactylus/sone/text/FreenetLinkPartTest.kt
2436862860
package net.pterodactylus.sone.web.ajax import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.junit.Test /** * Unit test for [JsonErrorReturnObject]. */ class JsonErrorReturnObjectTest { private val returnObject = JsonErrorReturnObject("nope") @Test fun `error return object is not successful`() { assertThat(returnObject.isSuccess, equalTo(false)) } @Test fun `error return object exposes error`() { assertThat(returnObject.error, equalTo("nope")) } }
src/test/kotlin/net/pterodactylus/sone/web/ajax/JsonErrorReturnObjectTest.kt
1089238295