content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
// WITH_STDLIB // INTENTION_TEXT: "Replace with 'firstOrNull{}'" // IS_APPLICABLE_2: false fun foo(list: List<String>): String? { <caret>for (s in list) { if (s.isEmpty()) continue else return s } return null }
plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/filter/ifElse.kt
815904209
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]> * Copyright (c) contributors * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ @file:JvmName("Identity") package com.github.jonathanxd.kores.util import com.github.jonathanxd.kores.Types import com.github.jonathanxd.kores.type.KoresType import com.github.jonathanxd.kores.type.GenericType import com.github.jonathanxd.kores.type.LoadedKoresType import com.github.jonathanxd.iutils.string.ToStringHelper import com.github.jonathanxd.kores.type.koresType import java.lang.reflect.Type import java.util.* /** * Non-strict generic equality check, only works for generic types. * * This method will not make strict bound checks, it means that `List<?>` is equal to `List`, * `List<? extends Person>` is equal to `List<Person>`, but `List<Number>` is not equal to `List<Integer>`. */ fun KoresType.nonStrictEq(other: KoresType): Boolean { if (this is GenericType) return this.nonStrictEq(other) if (other is GenericType) return other.nonStrictEq(this) return this.`is`(other) } /** * Non-strict generic bound equality check, only works for generic types. * * This method will not make strict bound checks, it means that `List<?>` is equal to `List`, * `List<? extends Person>` is equal to `List<Person>`, but `List<Number>` is not equal to `List<Integer>`. */ fun GenericType.nonStrictEq(other: KoresType): Boolean { if (other is GenericType) { return this.isWildcard == other.isWildcard && this.isType == other.isType && this.name == other.name && this.bounds.nonStrictEq(other.bounds) } else { if (this.bounds.all { it.type is GenericType && it.type.isWildcard }) return this.resolvedType.identification == other.identification return this.isType && this.bounds.isEmpty() && this.identification == other.identification } } /** * Non-strict bound comparison. */ private fun GenericType.Bound.nonStrictEq(other: GenericType.Bound): Boolean { val thisType = this.type val otherType = other.type val comparator = { it: KoresType, second: KoresType -> (it is GenericType && it.isWildcard) && (it.bounds.isEmpty() && ( second is GenericType && second.bounds.size == 1 && second.bounds.first().nonStrictEq(GenericType.GenericBound(Types.OBJECT)) || second.`is`(Types.OBJECT) ) || ( it.bounds.isNotEmpty() && it.bounds.any { it.type.`is`(second) } )) } return comparator(thisType, otherType) || comparator( otherType, thisType ) || thisType.`is`(other.type) } /** * Non-strict array bound comparison. */ private fun Array<out GenericType.Bound>.nonStrictEq(others: Array<out GenericType.Bound>): Boolean { if (this.size != others.size) return false this.forEachIndexed { index, bound -> if (!bound.nonStrictEq(others[index])) return@nonStrictEq false } return true } /** * Default equals algorithm for [GenericType] */ fun GenericType.eq(other: Any?): Boolean = this.identityEq(other) /** * Default hashCode algorithm for [GenericType] */ fun GenericType.hash(): Int { if (this.isType && this.bounds.isEmpty()) return (this as KoresType).hash() var result = Objects.hash(this.name, this.isType, this.isWildcard) result = 31 * result + Arrays.deepHashCode(this.bounds) return result } /** * Default to string conversion for [GenericType]. * * This method convert [GenericType] to a Java Source representation of the [GenericType], * see the algorithm of translation [here][toSourceString]. */ fun GenericType.toStr(): String { return this.toSourceString() } /** * * Creates string representation of components of [GenericType]. * * **This method is not recommended for object comparison.** */ fun GenericType.toComponentString(): String = ToStringHelper.defaultHelper(this::class.java.simpleName) .add("name", this.name) .add("isWildcard", this.isWildcard) .add(if (this.isType) "codeType" else "inferredType", this.resolvedType) .add("isType", this.isWildcard) .add("bounds", this.bounds.map { it.toComponentString() }) .toString() /** * Creates a string representation of components of [GenericType.Bound]. * * **This method is not recommended for object comparison.** */ fun GenericType.Bound.toComponentString(): String = ToStringHelper.defaultHelper(this::class.java.simpleName) .add("sign", this.sign) .add("type", this.type) .toString() /** * Default hash algorithm. * * @return Hash code. */ fun KoresType.identityHash(): Int = this.identification.hashCode() /** * Default equals method. * * @param obj Object to test. * @return True if this [KoresType] is equals to another [KoresType]. */ fun KoresType.identityEq(obj: Any?): Boolean = obj is KoresType && this.identification == obj.identification /** * Default hash algorithm. * * @return Hash code. */ fun KoresType.hash(): Int = this.identityHash() /** * Default equals method. * * @param obj Object to test. * @return True if this [KoresType] is equals to another [KoresType]. */ fun KoresType.eq(obj: Any?): Boolean = this.identityEq(obj) /** * Default to string conversion for [KoresType]. * * This methods generates a string with the simple name of current class and the [Type Identification][KoresType.identification]. */ fun KoresType.toStr(): String = "${this::class.java.simpleName}[${this.identification}]" /** * Default equality check for [LoadedKoresType], this method checks if the loaded types are equal. */ fun <T> LoadedKoresType<T>.eq(obj: Any?) = when (obj) { null -> false is LoadedKoresType<*> -> this.loadedType == obj.loadedType else -> (this as KoresType).eq(obj) } /** * Helper for checking equality of two types. Delegates to [KoresType.identityEq] */ operator fun Type.contains(other: Type) = this.koresType.`is`(other.koresType) /** * Helper for checking equality of two types. Delegates to [KoresType.identityEq] */ operator fun Type.contains(others: List<Type>) = others.any { it.koresType.`is`(this.koresType) }
src/main/kotlin/com/github/jonathanxd/kores/util/Identity.kt
3877213457
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.index.ui import com.intellij.openapi.Disposable import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.containers.DisposableWrapperList import com.intellij.util.ui.JBUI.Borders.empty import com.intellij.vcs.commit.CommitProgressPanel import com.intellij.vcs.commit.EditedCommitDetails import com.intellij.vcs.commit.NonModalCommitPanel import git4idea.i18n.GitBundle import git4idea.index.ContentVersion import git4idea.index.GitFileStatus import git4idea.index.GitStageTracker import git4idea.index.createChange import kotlin.properties.Delegates.observable private fun GitStageTracker.State.getStaged(): Set<GitFileStatus> = rootStates.values.flatMapTo(mutableSetOf()) { it.getStaged() } private fun GitStageTracker.RootState.getStaged(): Set<GitFileStatus> = statuses.values.filterTo(mutableSetOf()) { it.getStagedStatus() != null } private fun GitStageTracker.RootState.getStagedChanges(project: Project): List<Change> = getStaged().mapNotNull { createChange(project, root, it, ContentVersion.HEAD, ContentVersion.STAGED) } class GitStageCommitPanel(project: Project) : NonModalCommitPanel(project) { private val progressPanel = GitStageCommitProgressPanel() override val commitProgressUi: GitStageCommitProgressPanel get() = progressPanel @Volatile private var state: InclusionState = InclusionState(emptySet(), GitStageTracker.State.EMPTY) val rootsToCommit get() = state.rootsToCommit val includedRoots get() = state.includedRoots val conflictedRoots get() = state.conflictedRoots private val editedCommitListeners = DisposableWrapperList<() -> Unit>() override var editedCommit: EditedCommitDetails? by observable(null) { _, _, _ -> editedCommitListeners.forEach { it() } } init { Disposer.register(this, commitMessage) commitMessage.setChangesSupplier { state.stagedChanges } progressPanel.setup(this, commitMessage.editorField) bottomPanel = { add(progressPanel.apply { border = empty(6) }) add(commitAuthorComponent.apply { border = empty(0, 5, 4, 0) }) add(commitActionsPanel) } buildLayout() } fun setIncludedRoots(includedRoots: Collection<VirtualFile>) { setState(includedRoots, state.trackerState) } fun setTrackerState(trackerState: GitStageTracker.State) { setState(state.includedRoots, trackerState) } private fun setState(includedRoots: Collection<VirtualFile>, trackerState: GitStageTracker.State) { val newState = InclusionState(includedRoots, trackerState) if (state != newState) { state = newState fireInclusionChanged() } } fun addEditedCommitListener(listener: () -> Unit, parent: Disposable) { editedCommitListeners.add(listener, parent) } override fun activate(): Boolean = true override fun refreshData() = Unit override fun getDisplayedChanges(): List<Change> = emptyList() override fun getIncludedChanges(): List<Change> = state.stagedChanges override fun getDisplayedUnversionedFiles(): List<FilePath> = emptyList() override fun getIncludedUnversionedFiles(): List<FilePath> = emptyList() override fun includeIntoCommit(items: Collection<*>) = Unit private inner class InclusionState(val includedRoots: Collection<VirtualFile>, val trackerState: GitStageTracker.State) { private val stagedStatuses: Set<GitFileStatus> = trackerState.getStaged() val conflictedRoots: Set<VirtualFile> = trackerState.rootStates.filter { it.value.hasConflictedFiles() }.keys val stagedChanges by lazy { trackerState.rootStates.filterKeys { includedRoots.contains(it) }.values.flatMap { it.getStagedChanges(project) } } val rootsToCommit get() = trackerState.stagedRoots.intersect(includedRoots) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as InclusionState if (includedRoots != other.includedRoots) return false if (stagedStatuses != other.stagedStatuses) return false if (conflictedRoots != other.conflictedRoots) return false return true } override fun hashCode(): Int { var result = includedRoots.hashCode() result = 31 * result + stagedStatuses.hashCode() result = 31 * result + conflictedRoots.hashCode() return result } } } class GitStageCommitProgressPanel : CommitProgressPanel() { var isEmptyRoots by stateFlag() var isUnmerged by stateFlag() override fun clearError() { super.clearError() isEmptyRoots = false isUnmerged = false } override fun buildErrorText(): String? = when { isEmptyRoots -> GitBundle.message("error.no.selected.roots.to.commit") isUnmerged -> GitBundle.message("error.unresolved.conflicts") isEmptyChanges && isEmptyMessage -> GitBundle.message("error.no.staged.changes.no.commit.message") isEmptyChanges -> GitBundle.message("error.no.staged.changes.to.commit") isEmptyMessage -> VcsBundle.message("error.no.commit.message") else -> null } }
plugins/git4idea/src/git4idea/index/ui/GitStageCommitPanel.kt
4007568914
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.completion.ml.personalization.impl import com.intellij.completion.ml.personalization.* /** * @author Vitaliy.Bibaev */ class TimeBetweenTypingReader(factor: DailyAggregatedDoubleFactor) : UserFactorReaderBase(factor) { fun averageTime(): Double? { return FactorsUtil.calculateAverageByAllDays(factor) } } class TimeBetweenTypingUpdater(factor: MutableDoubleFactor) : UserFactorUpdaterBase(factor) { fun fireTypingPerformed(delayMs: Int) { factor.updateOnDate(DateUtil.today()) { FactorsUtil.updateAverageValue(this, delayMs.toDouble()) } } } class AverageTimeBetweenTyping : UserFactorBase<TimeBetweenTypingReader>("averageTimeBetweenTyping", UserFactorDescriptions.TIME_BETWEEN_TYPING) { override fun compute(reader: TimeBetweenTypingReader): String? = reader.averageTime()?.toString() }
plugins/completion-ml-ranking/src/com/intellij/completion/ml/personalization/impl/TimeBetweenTypingFactors.kt
934320244
// MODE: inheritors <# block [ 1 Implementation] #> interface SomeInterface { <# block [ 1 Override] #> open val interfaceProperty: String } class SomeClass : SomeInterface { override val interfaceProperty: String = "overridden" // <== (1) }
plugins/kotlin/idea/tests/testData/codeInsight/codeVision/InterfacePropertiesOverrides.kt
4132333626
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.example.awsapp import aws.sdk.kotlin.services.dynamodb.DynamoDbClient import aws.sdk.kotlin.services.dynamodb.model.AttributeValue import aws.sdk.kotlin.services.dynamodb.model.PutItemRequest import aws.sdk.kotlin.services.dynamodb.model.DynamoDbException import kotlin.system.exitProcess class Database { suspend fun putItemInTable2( ddb: DynamoDbClient, tableNameVal: String, key: String, keyVal: String, moneyTotal: String, moneyTotalValue: String, name: String, nameValue: String, email: String, emailVal: String, date: String, dateVal: String, ) { val itemValues = mutableMapOf<String, AttributeValue>() // Add all content to the table. itemValues[key] = AttributeValue.S(keyVal) itemValues[moneyTotal] = AttributeValue.S(moneyTotalValue) itemValues[name] = AttributeValue.S(nameValue) itemValues[email] = AttributeValue.S(emailVal) itemValues[date] = AttributeValue.S(dateVal) val request = PutItemRequest { tableName=tableNameVal item = itemValues } try { ddb.putItem(request) println(" A new item was placed into $tableNameVal.") } catch (ex: DynamoDbException) { println(ex.message) ddb.close() exitProcess(0) } } }
kotlin/usecases/first_android_app/src/main/kotlin/com/example/awsapp/Database.kt
2940365451
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package de.dreier.mytargets.features.training.input enum class ETrainingScope { END, ROUND, TRAINING }
app/src/main/java/de/dreier/mytargets/features/training/input/ETrainingScope.kt
3362956049
package mapzen.com.sdksampleapp.presenters import mapzen.com.sdksampleapp.controllers.MainController import mapzen.com.sdksampleapp.models.Sample /** * Interface for main presenter logic. */ interface MainPresenter { var controller: MainController? var navItemId: Int? var sample: Sample? // IN // Call when the activity is created fun onCreate() // Call when an item in the bottom navigation bar has been selected fun onNavBarItemSelected(navItemId: Int) // Call when a sample has been selected from the scroll view fun onSampleSelected(selected: Sample) // Call when item from the action bar is selected fun onOptionsItemSelected(itemId: Int?) // Call when the activity is destroyed fun onDestroy() // OUT // Call to get the sample view's title fun getTitleText(sample: Sample): String // Call to get sample view's tag fun getTag(sample: Sample): Sample }
samples/mapzen-sample/src/main/java/mapzen/com/sdksampleapp/presenters/MainPresenter.kt
2478530087
package com.airbnb.epoxy.preload import android.content.Context import android.view.View import android.widget.ImageView import androidx.annotation.IdRes import androidx.annotation.Px import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.airbnb.epoxy.BaseEpoxyAdapter import com.airbnb.epoxy.EpoxyAdapter import com.airbnb.epoxy.EpoxyController import com.airbnb.epoxy.EpoxyModel import com.airbnb.epoxy.getModelForPositionInternal import kotlin.math.max import kotlin.math.min /** * A scroll listener that prefetches view content. * * To use this, create implementations of [EpoxyModelPreloader] for each EpoxyModel class that you want to preload. * Then, use the [EpoxyPreloader.with] methods to create an instance that preloads models of that type. * Finally, add the resulting scroll listener to your RecyclerView. * * If you are using [com.airbnb.epoxy.EpoxyRecyclerView] then use [com.airbnb.epoxy.EpoxyRecyclerView.addPreloader] * to setup the preloader as a listener. * * Otherwise there is a [RecyclerView.addEpoxyPreloader] extension for easy usage. */ class EpoxyPreloader<P : PreloadRequestHolder> private constructor( private val adapter: BaseEpoxyAdapter, preloadTargetFactory: () -> P, errorHandler: PreloadErrorHandler, private val maxItemsToPreload: Int, modelPreloaders: List<EpoxyModelPreloader<*, *, out P>> ) : RecyclerView.OnScrollListener() { private var lastVisibleRange: IntRange = IntRange.EMPTY private var lastPreloadRange: IntProgression = IntRange.EMPTY private var totalItemCount = -1 private var scrollState: Int = RecyclerView.SCROLL_STATE_IDLE private val modelPreloaders: Map<Class<out EpoxyModel<*>>, EpoxyModelPreloader<*, *, out P>> = modelPreloaders.associateBy { it.modelType } private val requestHolderFactory = PreloadTargetProvider(maxItemsToPreload, preloadTargetFactory) private val viewDataCache = PreloadableViewDataProvider(adapter, errorHandler) constructor( epoxyController: EpoxyController, requestHolderFactory: () -> P, errorHandler: PreloadErrorHandler, maxItemsToPreload: Int, modelPreloaders: List<EpoxyModelPreloader<*, *, out P>> ) : this( epoxyController.adapter, requestHolderFactory, errorHandler, maxItemsToPreload, modelPreloaders ) constructor( adapter: EpoxyAdapter, requestHolderFactory: () -> P, errorHandler: PreloadErrorHandler, maxItemsToPreload: Int, modelPreloaders: List<EpoxyModelPreloader<*, *, out P>> ) : this( adapter as BaseEpoxyAdapter, requestHolderFactory, errorHandler, maxItemsToPreload, modelPreloaders ) init { require(maxItemsToPreload > 0) { "maxItemsToPreload must be greater than 0. Was $maxItemsToPreload" } } override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { scrollState = newState } override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { if (dx == 0 && dy == 0) { // Sometimes flings register a bunch of 0 dx/dy scroll events. To avoid redundant prefetching we just skip these // Additionally, the first RecyclerView layout notifies a scroll of 0, since that can be an important time for // performance (eg page load) we avoid prefetching at the same time. return } if (dx.isFling() || dy.isFling()) { // We avoid preloading during flings for two reasons // 1. Image requests are expensive and we don't want to drop frames on fling // 2. We'll likely scroll past the preloading item anyway return } // Update item count before anything else because validations depend on it totalItemCount = recyclerView.adapter?.itemCount ?: 0 val layoutManager = recyclerView.layoutManager as LinearLayoutManager val firstVisiblePosition = layoutManager.findFirstVisibleItemPosition() val lastVisiblePosition = layoutManager.findLastVisibleItemPosition() if (firstVisiblePosition.isInvalid() || lastVisiblePosition.isInvalid()) { lastVisibleRange = IntRange.EMPTY lastPreloadRange = IntRange.EMPTY return } val visibleRange = IntRange(firstVisiblePosition, lastVisiblePosition) if (visibleRange == lastVisibleRange) { return } val isIncreasing = visibleRange.first > lastVisibleRange.first || visibleRange.last > lastVisibleRange.last val preloadRange = calculatePreloadRange(firstVisiblePosition, lastVisiblePosition, isIncreasing) // Start preload for any items that weren't already preloaded preloadRange .subtract(lastPreloadRange) .forEach { preloadAdapterPosition(it) } lastVisibleRange = visibleRange lastPreloadRange = preloadRange } /** * @receiver The number of pixels scrolled. * @return True if this distance is large enough to be considered a fast fling. */ private fun Int.isFling() = Math.abs(this) > FLING_THRESHOLD_PX private fun calculatePreloadRange( firstVisiblePosition: Int, lastVisiblePosition: Int, isIncreasing: Boolean ): IntProgression { val from = if (isIncreasing) lastVisiblePosition + 1 else firstVisiblePosition - 1 val to = from + if (isIncreasing) maxItemsToPreload - 1 else 1 - maxItemsToPreload return IntProgression.fromClosedRange( rangeStart = from.clampToAdapterRange(), rangeEnd = to.clampToAdapterRange(), step = if (isIncreasing) 1 else -1 ) } /** Check if an item index is valid. It may not be if the adapter is empty, or if adapter changes have been dispatched since the last layout pass. */ private fun Int.isInvalid() = this == RecyclerView.NO_POSITION || this >= totalItemCount private fun Int.clampToAdapterRange() = min(totalItemCount - 1, max(this, 0)) private fun preloadAdapterPosition(position: Int) { @Suppress("UNCHECKED_CAST") val epoxyModel = adapter.getModelForPositionInternal(position) as? EpoxyModel<Any> ?: return @Suppress("UNCHECKED_CAST") val preloader = modelPreloaders[epoxyModel::class.java] as? EpoxyModelPreloader<EpoxyModel<*>, ViewMetadata?, P> ?: return viewDataCache .dataForModel(preloader, epoxyModel, position) .forEach { viewData -> val preloadTarget = requestHolderFactory.next() preloader.startPreload(epoxyModel, preloadTarget, viewData) } } /** * Cancels all current preload requests in progress. */ fun cancelPreloadRequests() { requestHolderFactory.clearAll() } companion object { /** * * Represents a threshold for fast scrolling. * This is a bit arbitrary and was determined by looking at values while flinging vs slow scrolling. * Ideally it would be based on DP, but this is simpler. */ private const val FLING_THRESHOLD_PX = 75 /** * Helper to create a preload scroll listener. Add the result to your RecyclerView. * for different models or content types. * * @param maxItemsToPreload How many items to prefetch ahead of the last bound item * @param errorHandler Called when the preloader encounters an exception. By default this throws only * if the app is not in a debuggle model * @param modelPreloader Describes how view content for the EpoxyModel should be preloaded * @param requestHolderFactory Should create and return a new [PreloadRequestHolder] each time it is invoked */ fun <P : PreloadRequestHolder> with( epoxyController: EpoxyController, requestHolderFactory: () -> P, errorHandler: PreloadErrorHandler, maxItemsToPreload: Int, modelPreloader: EpoxyModelPreloader<out EpoxyModel<*>, out ViewMetadata?, out P> ): EpoxyPreloader<P> = with( epoxyController, requestHolderFactory, errorHandler, maxItemsToPreload, listOf(modelPreloader) ) fun <P : PreloadRequestHolder> with( epoxyController: EpoxyController, requestHolderFactory: () -> P, errorHandler: PreloadErrorHandler, maxItemsToPreload: Int, modelPreloaders: List<EpoxyModelPreloader<out EpoxyModel<*>, out ViewMetadata?, out P>> ): EpoxyPreloader<P> { return EpoxyPreloader( epoxyController, requestHolderFactory, errorHandler, maxItemsToPreload, modelPreloaders ) } /** Helper to create a preload scroll listener. Add the result to your RecyclerView. */ fun <P : PreloadRequestHolder> with( epoxyAdapter: EpoxyAdapter, requestHolderFactory: () -> P, errorHandler: PreloadErrorHandler, maxItemsToPreload: Int, modelPreloaders: List<EpoxyModelPreloader<out EpoxyModel<*>, out ViewMetadata?, out P>> ): EpoxyPreloader<P> { return EpoxyPreloader( epoxyAdapter, requestHolderFactory, errorHandler, maxItemsToPreload, modelPreloaders ) } } } class EpoxyPreloadException(errorMessage: String) : RuntimeException(errorMessage) typealias PreloadErrorHandler = (Context, RuntimeException) -> Unit /** * Data about an image view to be preloaded. This data is used to construct a Glide image request. * * @param metadata Any custom, additional data that the [EpoxyModelPreloader] chooses to provide that may be necessary to create the image request. */ class ViewData<out U : ViewMetadata?>( @IdRes val viewId: Int, @Px val width: Int, @Px val height: Int, val metadata: U ) interface ViewMetadata { companion object { fun getDefault(view: View): ViewMetadata? { return when (view) { is ImageView -> ImageViewMetadata(view.scaleType) else -> null } } } } /** * Default implementation of [ViewMetadata] for an ImageView. * This data can help the preload request know how to configure itself. */ open class ImageViewMetadata( val scaleType: ImageView.ScaleType ) : ViewMetadata
epoxy-adapter/src/main/java/com/airbnb/epoxy/preload/EpoxyPreloader.kt
479001708
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.debugger import com.intellij.codeInsight.hint.HintManager import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Pair import com.intellij.xdebugger.XDebugSession import com.intellij.xdebugger.impl.DebuggerSupport import com.intellij.xdebugger.impl.XDebuggerUtilImpl import com.intellij.xdebugger.impl.actions.XDebuggerActionBase import com.intellij.xdebugger.impl.actions.XDebuggerSuspendedActionHandler import com.jetbrains.python.debugger.pydev.PyDebugCallback class PySetNextStatementAction : XDebuggerActionBase(true) { private val setNextStatementActionHandler: XDebuggerSuspendedActionHandler init { setNextStatementActionHandler = object : XDebuggerSuspendedActionHandler() { override fun perform(session: XDebugSession, dataContext: DataContext) { val debugProcess = session.debugProcess as? PyDebugProcess ?: return val position = XDebuggerUtilImpl.getCaretPosition(session.project, dataContext) ?: return val editor = CommonDataKeys.EDITOR.getData(dataContext) ?: FileEditorManager.getInstance(session.project).selectedTextEditor val suspendContext = debugProcess.session.suspendContext ApplicationManager.getApplication().executeOnPooledThread(Runnable { debugProcess.startSetNextStatement(suspendContext, position, object : PyDebugCallback<Pair<Boolean, String>> { override fun ok(response: Pair<Boolean, String>) { if (!response.first && editor != null) { ApplicationManager.getApplication().invokeLater(Runnable { if (!editor.isDisposed) { editor.caretModel.moveToOffset(position.offset) HintManager.getInstance().showErrorHint(editor, response.second) } }, ModalityState.defaultModalityState()) } } override fun error(e: PyDebuggerException) { LOG.error(e) } }) }) } override fun isEnabled(project: Project, event: AnActionEvent): Boolean { return super.isEnabled(project, event) && PyDebugSupportUtils.isCurrentPythonDebugProcess(project) } } } override fun getHandler(debuggerSupport: DebuggerSupport): XDebuggerSuspendedActionHandler = setNextStatementActionHandler override fun isHidden(event: AnActionEvent): Boolean { val project = event.getData(CommonDataKeys.PROJECT) return project == null || !PyDebugSupportUtils.isCurrentPythonDebugProcess(project) } companion object { private val LOG = Logger.getInstance("#com.jetbrains.python.debugger.PySetNextStatementAction") } }
python/src/com/jetbrains/python/debugger/PySetNextStatementAction.kt
3202436507
/* * Copyright (C) 2017 grandcentrix GmbH * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.grandcentrix.thirtyinch.sample import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import net.grandcentrix.thirtyinch.TiFragment class SampleFragment : TiFragment<SamplePresenter, SampleView>(), SampleView { private lateinit var sampleText: TextView override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) val view = inflater.inflate(R.layout.fragment_sample, container, false) as ViewGroup sampleText = view.findViewById(R.id.sample_text) return view } override fun providePresenter(): SamplePresenter = SamplePresenter() override fun showText(text: String) { sampleText.text = text } }
sample/src/main/java/net/grandcentrix/thirtyinch/sample/SampleFragment.kt
787439085
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget import org.jetbrains.kotlin.descriptors.annotations.KotlinTarget import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.util.mustHaveOnlyPropertiesInPrimaryConstructor import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClass import org.jetbrains.kotlin.psi.psiUtil.isPropertyParameter import org.jetbrains.kotlin.resolve.AnnotationChecker import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class MovePropertyToClassBodyIntention : SelfTargetingIntention<KtParameter>( KtParameter::class.java, KotlinBundle.lazyMessage("move.to.class.body") ) { override fun isApplicableTo(element: KtParameter, caretOffset: Int): Boolean { if (!element.isPropertyParameter()) return false val containingClass = element.containingClass() ?: return false return !containingClass.mustHaveOnlyPropertiesInPrimaryConstructor() } override fun applyTo(element: KtParameter, editor: Editor?) { val parentClass = PsiTreeUtil.getParentOfType(element, KtClass::class.java) ?: return val propertyDeclaration = KtPsiFactory(element).createProperty("${element.valOrVarKeyword?.text} ${element.name} = ${element.name}") val firstProperty = parentClass.getProperties().firstOrNull() parentClass.addDeclarationBefore(propertyDeclaration, firstProperty).apply { val propertyModifierList = element.modifierList?.copy() as? KtModifierList propertyModifierList?.getModifier(KtTokens.VARARG_KEYWORD)?.delete() propertyModifierList?.let { modifierList?.replace(it) ?: addBefore(it, firstChild) } modifierList?.annotationEntries?.forEach { if (!it.isAppliedToProperty()) { it.delete() } else if (it.useSiteTarget?.getAnnotationUseSiteTarget() == AnnotationUseSiteTarget.PROPERTY) { it.useSiteTarget?.removeWithColon() } } } element.valOrVarKeyword?.delete() val parameterAnnotationsText = element.modifierList?.annotationEntries ?.filter { it.isAppliedToConstructorParameter() } ?.takeIf { it.isNotEmpty() } ?.joinToString(separator = " ") { it.textWithoutUseSite() } val hasVararg = element.hasModifier(KtTokens.VARARG_KEYWORD) if (parameterAnnotationsText != null) { element.modifierList?.replace(KtPsiFactory(element).createModifierList(parameterAnnotationsText)) } else { element.modifierList?.delete() } if (hasVararg) element.addModifier(KtTokens.VARARG_KEYWORD) } private fun KtAnnotationEntry.isAppliedToProperty(): Boolean { useSiteTarget?.getAnnotationUseSiteTarget()?.let { return it == AnnotationUseSiteTarget.FIELD || it == AnnotationUseSiteTarget.PROPERTY || it == AnnotationUseSiteTarget.PROPERTY_GETTER || it == AnnotationUseSiteTarget.PROPERTY_SETTER || it == AnnotationUseSiteTarget.SETTER_PARAMETER } return !isApplicableToConstructorParameter() } private fun KtAnnotationEntry.isAppliedToConstructorParameter(): Boolean { useSiteTarget?.getAnnotationUseSiteTarget()?.let { return it == AnnotationUseSiteTarget.CONSTRUCTOR_PARAMETER } return isApplicableToConstructorParameter() } private fun KtAnnotationEntry.isApplicableToConstructorParameter(): Boolean { val context = analyze(BodyResolveMode.PARTIAL) val descriptor = context[BindingContext.ANNOTATION, this] ?: return false val applicableTargets = AnnotationChecker.applicableTargetSet(descriptor) return applicableTargets.contains(KotlinTarget.VALUE_PARAMETER) } private fun KtAnnotationEntry.textWithoutUseSite() = "@" + typeReference?.text.orEmpty() + valueArgumentList?.text.orEmpty() private fun KtAnnotationUseSiteTarget.removeWithColon() { nextSibling?.delete() // ':' symbol after use site delete() } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/MovePropertyToClassBodyIntention.kt
3089484882
package com.virtlink.editorservices.resources import com.virtlink.editorservices.Offset import com.virtlink.editorservices.Position interface IAesiContent: IContent { fun getOffset(position: Position): Offset? fun getPosition(offset: Offset): Position? }
aesi/src/main/kotlin/com/virtlink/editorservices/resources/IAesiContent.kt
3962482891
package com.github.vhromada.catalog.web.controller import com.github.vhromada.catalog.web.connector.AccountConnector import com.github.vhromada.catalog.web.fo.AccountFO import com.github.vhromada.catalog.web.mapper.AccountMapper import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.validation.Errors import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.ModelAttribute import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestMapping import javax.validation.Valid /** * A class represents controller for registration. * * @author Vladimir Hromada */ @Controller("registrationController") @RequestMapping("/registration") class RegistrationController( /** * Connector for accounts */ private val connector: AccountConnector, /** * Mapper for accounts */ private val mapper: AccountMapper ) { /** * Shows page for registration. * * @param model model * @return view for page for registration */ @GetMapping fun login(model: Model): String { return createFormView(model = model, account = AccountFO(username = null, password = null, copyPassword = null)) } /** * Process creating account. * * @param model model * @param account FO for account * @param errors errors * @return view for redirect to page with login (no errors) or view for page for creating user (errors) */ @PostMapping(params = ["create"]) fun processAdd(model: Model, @ModelAttribute("account") @Valid account: AccountFO, errors: Errors): String { if (errors.hasErrors()) { return createFormView(model = model, account = account) } connector.addCredentials(credentials = mapper.map(source = account)) return "redirect:/login" } /** * Cancel creating account. * * @return view for redirect to page with login */ @PostMapping(params = ["cancel"]) fun cancelAdd(): String { return "redirect:/login" } /** * Returns page's view with form. * * @param model model * @param account FO for account * @return page's view with form */ private fun createFormView(model: Model, account: AccountFO): String { model.addAttribute("account", account) model.addAttribute("title", "Registration") return "registration/registration" } }
web/src/main/kotlin/com/github/vhromada/catalog/web/controller/RegistrationController.kt
2289940616
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.stepping.smartStepInto import com.intellij.debugger.engine.MethodFilter import com.intellij.openapi.application.runReadAction import com.intellij.psi.PsiElement import com.intellij.psi.SmartPsiElementPointer import com.intellij.util.Range import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.decompiler.navigation.SourceNavigationHelper import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.renderer.ParameterNameRenderingPolicy import org.jetbrains.kotlin.renderer.PropertyAccessorRenderingPolicy import javax.swing.Icon class KotlinMethodSmartStepTarget( lines: Range<Int>, highlightElement: PsiElement, label: String, declaration: KtDeclaration?, val ordinal: Int, val methodInfo: CallableMemberInfo ) : KotlinSmartStepTarget(label, highlightElement, false, lines) { companion object { private val renderer = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.withOptions { parameterNameRenderingPolicy = ParameterNameRenderingPolicy.NONE withoutReturnType = true propertyAccessorRenderingPolicy = PropertyAccessorRenderingPolicy.PRETTY startFromName = true modifiers = emptySet() } fun calcLabel(descriptor: DeclarationDescriptor): String { return renderer.render(descriptor) } } private val declarationPtr = declaration?.let(SourceNavigationHelper::getNavigationElement)?.createSmartPointer() init { assert(declaration != null || methodInfo.isInvoke) } override fun getIcon(): Icon = if (methodInfo.isExtension) KotlinIcons.EXTENSION_FUNCTION else KotlinIcons.FUNCTION fun getDeclaration(): KtDeclaration? = declarationPtr.getElementInReadAction() override fun createMethodFilter(): MethodFilter { val declaration = declarationPtr.getElementInReadAction() return KotlinMethodFilter(declaration, callingExpressionLines, methodInfo) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || other !is KotlinMethodSmartStepTarget) return false if (methodInfo.isInvoke && other.methodInfo.isInvoke) { // Don't allow to choose several invoke targets in smart step into as we can't distinguish them reliably during debug return true } return highlightElement === other.highlightElement } override fun hashCode(): Int { if (methodInfo.isInvoke) { // Predefined value to make all FunctionInvokeDescriptor targets equal return 42 } return highlightElement.hashCode() } } internal fun <T : PsiElement> SmartPsiElementPointer<T>?.getElementInReadAction(): T? = this?.let { runReadAction { element } }
plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/KotlinMethodSmartStepTarget.kt
3723329313
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.config.gpg import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.coroutineToIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vcs.VcsException import git4idea.commands.GitImpl import git4idea.config.GitConfigUtil import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager import git4idea.util.StringScanner import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext @Throws(VcsException::class) private fun readGitGpgConfig(repository: GitRepository): RepoConfig { // TODO: "tag.gpgSign" ? val isEnabled = GitConfigUtil.getBooleanValue(GitConfigUtil.getValue(repository.project, repository.root, GitConfigUtil.GPG_COMMIT_SIGN)) if (isEnabled != true) return RepoConfig(null) val keyValue = GitConfigUtil.getValue(repository.project, repository.root, GitConfigUtil.GPG_COMMIT_SIGN_KEY) if (keyValue == null) return RepoConfig(null) return RepoConfig(GpgKey(keyValue.trim())) } @Throws(VcsException::class) private fun readAvailableSecretKeys(project: Project): SecretKeys { val repository = GitRepositoryManager.getInstance(project).repositories.firstOrNull() if (repository == null) return SecretKeys(emptyList(), emptyMap()) val gpgCommand = GitConfigUtil.getValue(project, repository.root, GitConfigUtil.GPG_PROGRAM) ?: "gpg" val output = GitImpl.runBundledCommand(project, gpgCommand, "--list-secret-keys", "--with-colons", "--fixed-list-mode", "--batch", "--no-tty") return parseSecretKeys(output) } /** * See https://github.com/gpg/gnupg/blob/master/doc/DETAILS */ private fun parseSecretKeys(output: String): SecretKeys { val result = mutableListOf<GpgKey>() val descriptions = mutableMapOf<GpgKey, @NlsSafe String>() var lastKey: GpgKey? = null val scanner = StringScanner(output) while (scanner.hasMoreData()) { val line = scanner.line() val fields = line.split(':') val type = fields.getOrNull(0) // Field 1 - Type of record if (type == "sec") { val keyId = fields.getOrNull(4) // Field 5 - KeyID val capabilities = fields.getOrNull(11) // Field 12 - Key capabilities if (keyId != null && capabilities != null && checkKeyCapabilities(capabilities)) { val gpgKey = GpgKey(keyId) result.add(gpgKey) lastKey = gpgKey } else { lastKey = null } } if (type == "uid") { val userId = fields.getOrNull(9) // Field 10 - User-ID if (userId != null && lastKey != null) { descriptions[lastKey] = StringUtil.unescapeAnsiStringCharacters(userId) } lastKey = null } } return SecretKeys(result, descriptions) } private fun checkKeyCapabilities(capabilities: String): Boolean { if (capabilities.contains("D")) return false // key Disabled return capabilities.contains("s") || capabilities.contains("S") // can Sign } @Throws(VcsException::class) fun writeGitGpgConfig(repository: GitRepository, gpgKey: GpgKey?) { if (gpgKey != null) { GitConfigUtil.setValue(repository.project, repository.root, GitConfigUtil.GPG_COMMIT_SIGN, "true") GitConfigUtil.setValue(repository.project, repository.root, GitConfigUtil.GPG_COMMIT_SIGN_KEY, gpgKey.id) } else { GitConfigUtil.setValue(repository.project, repository.root, GitConfigUtil.GPG_COMMIT_SIGN, "false") } } class RepoConfig(val key: GpgKey?) class SecretKeys(val keys: List<GpgKey>, val descriptions: Map<GpgKey, @NlsSafe String>) data class GpgKey(val id: @NlsSafe String) class RepoConfigValue(val repository: GitRepository) : Value<RepoConfig>() { override fun compute(): RepoConfig = readGitGpgConfig(repository) } class SecretKeysValue(val project: Project) : Value<SecretKeys>() { override fun compute(): SecretKeys = readAvailableSecretKeys(project) } abstract class Value<T> { private val listeners = mutableListOf<ValueListener>() @Volatile var value: T? = null private set var error: VcsException? = null private set @Throws(VcsException::class) protected abstract fun compute(): T @Throws(VcsException::class) suspend fun reload(): T { try { val newValue = withContext(Dispatchers.IO) { coroutineToIndicator { compute() } } value = newValue error = null notifyListeners() return newValue } catch (e: VcsException) { value = null error = e notifyListeners() throw e } } suspend fun tryReload(): T? { try { return reload() } catch (e: VcsException) { logger<Value<*>>().warn(e) return null } } @Throws(VcsException::class) suspend fun load(): T { val value = value if (value != null) return value return reload() } suspend fun tryLoad(): T? { try { return load() } catch (e: VcsException) { logger<Value<*>>().warn(e) return null } } fun addListener(listener: ValueListener) { listeners.add(listener) } private fun notifyListeners() { for (listener in listeners) { listener() } } } private typealias ValueListener = () -> Unit
plugins/git4idea/src/git4idea/config/gpg/GitGpgConfigUtils.kt
3333044638
package com.masahirosaito.spigot.homes.nms.v1_12_R1 import com.masahirosaito.spigot.homes.nms.HomesEntity import com.masahirosaito.spigot.homes.nms.NMSController import com.masahirosaito.spigot.homes.nms.NMSEntityArmorStand import com.masahirosaito.spigot.homes.strings.HomeDisplayStrings.DEFAULT_HOME_DISPLAY_NAME import com.masahirosaito.spigot.homes.strings.HomeDisplayStrings.NAMED_HOME_DISPLAY_NAME import org.bukkit.craftbukkit.v1_12_R1.CraftWorld import org.bukkit.event.entity.CreatureSpawnEvent class NMSController_v1_12_R1 : NMSController { override fun setUp() { CustomEntities.registerEntities() } override fun spawn(homesEntity: HomesEntity): List<NMSEntityArmorStand> { val texts = if (homesEntity.homeName == null) { DEFAULT_HOME_DISPLAY_NAME(homesEntity.offlinePlayer.name).split("\n") } else { NAMED_HOME_DISPLAY_NAME(homesEntity.offlinePlayer.name, homesEntity.homeName!!).split("\n") } val list: MutableList<NMSEntityArmorStand> = mutableListOf() val location = homesEntity.location texts.forEachIndexed { index, text -> list.add(EntityNMSArmorStand((location.world as CraftWorld).handle).apply { setNMSName(text) setNameVisible(!homesEntity.isPrivate) setPosition(location.x, location.y + 0.8 - (index * 0.2), location.z) (homesEntity.location.world as CraftWorld).handle .addEntity(this, CreatureSpawnEvent.SpawnReason.CUSTOM) }) } return list } }
src/main/kotlin/com/masahirosaito/spigot/homes/nms/v1_12_R1/NMSController_v1_12_R1.kt
591285477
package com.glodanif.bluetoothchat.data.service.message import androidx.annotation.ColorInt import java.io.File class Contract { var partnerVersion: Int = MESSAGE_CONTRACT_VERSION infix fun setupWith(version: Int) { partnerVersion = version } fun reset() { partnerVersion = MESSAGE_CONTRACT_VERSION } fun createChatMessage(message: String) = Message(generateUniqueId(), message, MessageType.MESSAGE) fun createConnectMessage(name: String, @ColorInt color: Int) = Message(0, "$name$DIVIDER$color$DIVIDER$MESSAGE_CONTRACT_VERSION", true, MessageType.CONNECTION_REQUEST) fun createDisconnectMessage() = Message(false, MessageType.CONNECTION_REQUEST) fun createAcceptConnectionMessage(name: String, @ColorInt color: Int) = Message("$name$DIVIDER$color$DIVIDER$MESSAGE_CONTRACT_VERSION", true, MessageType.CONNECTION_RESPONSE) fun createRejectConnectionMessage(name: String, @ColorInt color: Int) = Message("$name$DIVIDER$color$DIVIDER$MESSAGE_CONTRACT_VERSION", false, MessageType.CONNECTION_RESPONSE) fun createSuccessfulDeliveryMessage(id: Long) = Message(id, true, MessageType.DELIVERY) fun createFileStartMessage(file: File, type: PayloadType): Message { val uid = if (partnerVersion >= 2) generateUniqueId() else 0L return Message(uid, "${file.name.replace(DIVIDER, "")}$DIVIDER${file.length()}$DIVIDER${type.value}", false, MessageType.FILE_START) } fun createFileEndMessage() = Message(false, MessageType.FILE_END) fun isFeatureAvailable(feature: Feature) = when (feature) { Feature.IMAGE_SHARING -> partnerVersion >= 1 } enum class MessageType(val value: Int) { UNEXPECTED(-1), MESSAGE(0), DELIVERY(1), CONNECTION_RESPONSE(2), CONNECTION_REQUEST(3), SEEING(4), EDITING(5), FILE_START(6), FILE_END(7), FILE_CANCELED(8); companion object { fun from(findValue: Int) = values().first { it.value == findValue } } } enum class Feature { IMAGE_SHARING; } companion object { const val DIVIDER = "#" const val MESSAGE_CONTRACT_VERSION = 2 fun generateUniqueId() = System.nanoTime() } }
app/src/main/kotlin/com/glodanif/bluetoothchat/data/service/message/Contract.kt
2340416996
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.wear.tiles.golden import android.content.Context import androidx.wear.tiles.ColorBuilders import androidx.wear.tiles.DeviceParametersBuilders.DeviceParameters import androidx.wear.tiles.ModifiersBuilders.Clickable import androidx.wear.tiles.material.ChipColors import androidx.wear.tiles.material.CompactChip import androidx.wear.tiles.material.Text import androidx.wear.tiles.material.Typography import androidx.wear.tiles.material.layouts.PrimaryLayout object HeartRate { fun simpleLayout( context: Context, deviceParameters: DeviceParameters, heartRateBpm: Int, clickable: Clickable ) = PrimaryLayout.Builder(deviceParameters) .setPrimaryLabelTextContent( Text.Builder(context, "Now") .setTypography(Typography.TYPOGRAPHY_CAPTION1) .setColor(ColorBuilders.argb(GoldenTilesColors.White)) .build() ) .setContent( Text.Builder(context, heartRateBpm.toString()) .setTypography(Typography.TYPOGRAPHY_DISPLAY1) .setColor(ColorBuilders.argb(GoldenTilesColors.White)) .build() ) .setSecondaryLabelTextContent( Text.Builder(context, "bpm") .setTypography(Typography.TYPOGRAPHY_CAPTION1) .setColor(ColorBuilders.argb(GoldenTilesColors.LightGray)) .build() ) .setPrimaryChipContent( CompactChip.Builder(context, "Measure", clickable, deviceParameters) .setChipColors( ChipColors( /*backgroundColor=*/ ColorBuilders.argb(GoldenTilesColors.LightRed), /*contentColor=*/ ColorBuilders.argb(GoldenTilesColors.Black) ) ) .build() ) .build() }
WearTilesKotlin/app/src/debug/java/com/example/wear/tiles/golden/HeartRate.kt
3707009582
// 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.codeInsight.actions import com.intellij.codeInsight.actions.ReaderModeSettings.Companion.matchMode import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.icons.AllIcons import com.intellij.ide.HelpTooltip import com.intellij.lang.LangBundle import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.actionSystem.impl.ActionButtonWithText import com.intellij.openapi.application.Experiments import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.colors.ColorKey import com.intellij.openapi.editor.markup.InspectionWidgetActionProvider import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.project.DumbAwareToggleAction import com.intellij.openapi.project.Project import com.intellij.openapi.project.isNotificationSilentMode import com.intellij.openapi.ui.popup.JBPopupListener import com.intellij.openapi.ui.popup.LightweightWindowEvent import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.registry.Registry import com.intellij.psi.PsiDocumentManager import com.intellij.ui.GotItTooltip import com.intellij.ui.JBColor import com.intellij.ui.scale.JBUIScale import com.intellij.util.NotNullProducer import com.intellij.util.ui.EmptyIcon import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import java.awt.Insets import javax.swing.JComponent import javax.swing.plaf.FontUIResource private class ReaderModeActionProvider : InspectionWidgetActionProvider { override fun createAction(editor: Editor): AnAction? { val project: Project? = editor.project return if (project == null || project.isDefault) null else object : DefaultActionGroup(ReaderModeAction(editor), Separator.create()) { override fun update(e: AnActionEvent) { if (!Experiments.getInstance().isFeatureEnabled("editor.reader.mode")) { e.presentation.isEnabledAndVisible = false } else { if (project.isInitialized) { val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document)?.virtualFile e.presentation.isEnabledAndVisible = matchMode(project, file, editor) } else { e.presentation.isEnabledAndVisible = false } } } } } private class ReaderModeAction(private val editor: Editor) : DumbAwareToggleAction( LangBundle.messagePointer("action.ReaderModeProvider.text"), LangBundle.messagePointer("action.ReaderModeProvider.description"), null), CustomComponentAction { override fun createCustomComponent(presentation: Presentation, place: String): JComponent = object : ActionButtonWithText(this, presentation, place, JBUI.size(18)) { override fun iconTextSpace() = JBUI.scale(2) override fun updateToolTipText() { val project = editor.project if (Registry.`is`("ide.helptooltip.enabled") && project != null) { HelpTooltip.dispose(this) HelpTooltip() .setTitle(myPresentation.description) .setDescription(LangBundle.message("action.ReaderModeProvider.description")) .setLink(LangBundle.message("action.ReaderModeProvider.link.configure")) { ShowSettingsUtil.getInstance().showSettingsDialog(project, ReaderModeConfigurable::class.java) } .installOn(this) } else { toolTipText = myPresentation.description } } override fun getInsets(): Insets = JBUI.insets(2) override fun getMargins(): Insets = if (myPresentation.icon == AllIcons.General.ReaderMode) JBUI.emptyInsets() else JBUI.insetsRight(5) override fun updateUI() { super.updateUI() if (!SystemInfo.isWindows) { font = FontUIResource(font.deriveFont(font.style, font.size - JBUIScale.scale(2).toFloat())) } } }.also { it.foreground = JBColor(NotNullProducer { editor.colorsScheme.getColor(FOREGROUND) ?: FOREGROUND.defaultColor }) if (!SystemInfo.isWindows) { it.font = FontUIResource(it.font.deriveFont(it.font.style, it.font.size - JBUIScale.scale(2).toFloat())) } editor.project?.let { p -> if (!ReaderModeSettings.instance(p).enabled || isNotificationSilentMode(p)) return@let val connection = p.messageBus.connect(p) val gotItTooltip = GotItTooltip("reader.mode.got.it", LangBundle.message("text.reader.mode.got.it.popup"), p) .withHeader(LangBundle.message("title.reader.mode.got.it.popup")) if (gotItTooltip.canShow()) { connection.subscribe(DaemonCodeAnalyzer.DAEMON_EVENT_TOPIC, object : DaemonCodeAnalyzer.DaemonListener { override fun daemonFinished(fileEditors: Collection<FileEditor>) { fileEditors.find { fe -> (fe is TextEditor) && editor == fe.editor }?.let { _ -> gotItTooltip.setOnBalloonCreated { balloon -> balloon.addListener(object: JBPopupListener { override fun onClosed(event: LightweightWindowEvent) { connection.disconnect() } })}. show(it, GotItTooltip.BOTTOM_MIDDLE) } } }) } } } override fun isSelected(e: AnActionEvent): Boolean { return true } override fun setSelected(e: AnActionEvent, state: Boolean) { val project = e.project ?: return ReaderModeSettings.instance(project).enabled = !ReaderModeSettings.instance(project).enabled project.messageBus.syncPublisher(ReaderModeSettingsListener.TOPIC).modeChanged(project) } override fun update(e: AnActionEvent) { val project = editor.project ?: return val presentation = e.presentation if (!ReaderModeSettings.instance(project).enabled) { presentation.text = null presentation.icon = AllIcons.General.ReaderMode presentation.hoveredIcon = null presentation.description = LangBundle.message("action.ReaderModeProvider.text.enter") } else { presentation.text = LangBundle.message("action.ReaderModeProvider.text") presentation.icon = EmptyIcon.ICON_16 presentation.hoveredIcon = AllIcons.Actions.CloseDarkGrey presentation.description = LangBundle.message("action.ReaderModeProvider.text.exit") } } } companion object { val FOREGROUND = ColorKey.createColorKey("ActionButton.iconTextForeground", UIUtil.getContextHelpForeground()) } }
platform/lang-impl/src/com/intellij/codeInsight/actions/ReaderModeActionProvider.kt
2812103499
/* * 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 org.matrix.androidsdk.crypto.cryptostore.db.query import io.realm.Realm import io.realm.kotlin.where import org.matrix.androidsdk.crypto.cryptostore.db.model.CryptoRoomEntity import org.matrix.androidsdk.crypto.cryptostore.db.model.CryptoRoomEntityFields /** * Get or create a room */ internal fun CryptoRoomEntity.Companion.getOrCreate(realm: Realm, roomId: String): CryptoRoomEntity { return getById(realm, roomId) ?: let { realm.createObject(CryptoRoomEntity::class.java, roomId) } } /** * Get a room */ internal fun CryptoRoomEntity.Companion.getById(realm: Realm, roomId: String): CryptoRoomEntity? { return realm.where<CryptoRoomEntity>() .equalTo(CryptoRoomEntityFields.ROOM_ID, roomId) .findFirst() }
matrix-sdk-crypto/src/main/java/org/matrix/androidsdk/crypto/cryptostore/db/query/CryptoRoomEntityQueries.kt
1435465024
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines import kotlinx.coroutines.channels.* import org.junit.Test import kotlin.test.* class ReusableCancellableContinuationLeakStressTest : TestBase() { @Suppress("UnnecessaryVariable") private suspend fun <T : Any> ReceiveChannel<T>.receiveBatch(): T { val r = receive() // DO NOT MERGE LINES, otherwise TCE will kick in return r } private val iterations = 100_000 * stressTestMultiplier class Leak(val i: Int) @Test // Simplified version of #2564 fun testReusableContinuationLeak() = runTest { val channel = produce(capacity = 1) { // from the main thread (0 until iterations).forEach { send(Leak(it)) } } launch(Dispatchers.Default) { repeat (iterations) { val value = channel.receiveBatch() assertEquals(it, value.i) } (channel as Job).join() FieldWalker.assertReachableCount(0, coroutineContext.job, false) { it is Leak } } } }
kotlinx-coroutines-core/jvm/test/ReusableCancellableContinuationLeakStressTest.kt
2640224872
import org.http4k.server.Netty fun main(args: Array<String>) { Http4kBenchmarkServer().start(Netty(9000)) }
frameworks/Kotlin/http4k/netty/src/main/kotlin/Http4kNettyServer.kt
2434814225
/* * (C) Copyright 2019 Lukas Morawietz (https://github.com/F43nd1r) * * 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.faendir.acra.ui.component import com.googlecode.gentyref.GenericTypeReflector import com.vaadin.flow.component.Component import com.vaadin.flow.component.Composite import com.vaadin.flow.internal.ReflectTools import com.vaadin.flow.server.VaadinService import com.vaadin.flow.spring.annotation.SpringComponent import org.springframework.core.annotation.AnnotationUtils import java.lang.reflect.ParameterizedType import java.lang.reflect.Type import java.lang.reflect.TypeVariable abstract class SpringComposite<T : Component> : Composite<T>() { @Suppress("UNCHECKED_CAST") override fun initContent(): T { val contentType = findContentType(javaClass as Class<out Composite<*>?>) return if (AnnotationUtils.findAnnotation(contentType, org.springframework.stereotype.Component::class.java) != null) { VaadinService.getCurrent().instantiator.createComponent(contentType) as T } else { ReflectTools.createInstance(contentType) as T } } companion object { /** * adapted from Composite#findContentType(Class) */ private fun findContentType( compositeClass: Class<out Composite<*>?> ): Class<out Component> { val type = GenericTypeReflector.getTypeParameter(compositeClass.genericSuperclass, Composite::class.java.typeParameters[0]) if (type is Class<*> || type is ParameterizedType) return GenericTypeReflector.erase(type).asSubclass(Component::class.java) throw IllegalStateException(getExceptionMessage(type)) } /** * adapted from Composite#getExceptionMessage(Type) */ private fun getExceptionMessage(type: Type?): String { return when (type) { null -> "Composite is used as raw type: either add type information or override initContent()." is TypeVariable<*> -> String.format( "Could not determine the composite content type for TypeVariable '%s'. Either specify exact type or override initContent().", type.getTypeName() ) else -> String.format("Could not determine the composite content type for %s. Override initContent().", type.typeName) } } } }
acrarium/src/main/kotlin/com/faendir/acra/ui/component/SpringComposite.kt
1448892946
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.fileEditor.impl import com.intellij.CommonBundle import com.intellij.ide.BrowserUtil import com.intellij.ide.IdeBundle import com.intellij.ide.plugins.MultiPanel import com.intellij.openapi.application.invokeLater import com.intellij.openapi.editor.EditorBundle import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorLocation import com.intellij.openapi.fileEditor.FileEditorState import com.intellij.openapi.project.Project import com.intellij.openapi.util.ActionCallback import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.UserDataHolderBase import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.StatusBar import com.intellij.testFramework.LightVirtualFile import com.intellij.ui.components.JBLoadingPanel import com.intellij.ui.jcef.JBCefBrowserBase.ErrorPage import com.intellij.ui.jcef.JCEFHtmlPanel import com.intellij.util.Alarm import com.intellij.util.AlarmFactory import com.intellij.util.ui.UIUtil import org.cef.browser.CefBrowser import org.cef.browser.CefFrame import org.cef.handler.* import org.cef.network.CefRequest import java.awt.BorderLayout import java.beans.PropertyChangeListener import java.util.concurrent.atomic.AtomicBoolean import javax.swing.JComponent internal class HTMLFileEditor(private val project: Project, private val file: LightVirtualFile, url: String) : UserDataHolderBase(), FileEditor { private val loadingPanel = JBLoadingPanel(BorderLayout(), this) private val contentPanel = JCEFHtmlPanel(null) private val alarm = AlarmFactory.getInstance().create(Alarm.ThreadToUse.SWING_THREAD, this) private val initial = AtomicBoolean(true) private val navigating = AtomicBoolean(false) private val multiPanel = object : MultiPanel() { override fun create(key: Int): JComponent = when (key) { LOADING_KEY -> loadingPanel CONTENT_KEY -> contentPanel.component else -> throw IllegalArgumentException("Unknown key: ${key}") } override fun select(key: Int, now: Boolean): ActionCallback { val callback = super.select(key, now) if (key == CONTENT_KEY) { UIUtil.invokeLaterIfNeeded { contentPanel.component.requestFocusInWindow() } } return callback } } init { loadingPanel.setLoadingText(CommonBundle.getLoadingTreeNodeText()) contentPanel.jbCefClient.addLoadHandler(object : CefLoadHandlerAdapter() { override fun onLoadingStateChange(browser: CefBrowser, isLoading: Boolean, canGoBack: Boolean, canGoForward: Boolean) { if (initial.get()) { if (isLoading) { invokeLater { loadingPanel.startLoading() multiPanel.select(LOADING_KEY, true) } } else { alarm.cancelAllRequests() initial.set(false) invokeLater { loadingPanel.stopLoading() multiPanel.select(CONTENT_KEY, true) } } } } }, contentPanel.cefBrowser) contentPanel.jbCefClient.addRequestHandler(object : CefRequestHandlerAdapter() { override fun onBeforeBrowse(browser: CefBrowser, frame: CefFrame, request: CefRequest, userGesture: Boolean, isRedirect: Boolean): Boolean = if (userGesture) { navigating.set(true); BrowserUtil.browse(request.url); true } else false }, contentPanel.cefBrowser) contentPanel.jbCefClient.addLifeSpanHandler(object : CefLifeSpanHandlerAdapter() { override fun onBeforePopup(browser: CefBrowser, frame: CefFrame, targetUrl: String, targetFrameName: String?): Boolean { BrowserUtil.browse(targetUrl) return true } }, contentPanel.cefBrowser) contentPanel.jbCefClient.addDisplayHandler(object : CefDisplayHandlerAdapter() { override fun onStatusMessage(browser: CefBrowser, text: @NlsSafe String) = StatusBar.Info.set(text, project) }, contentPanel.cefBrowser) contentPanel.setErrorPage { errorCode, errorText, failedUrl -> if (errorCode == CefLoadHandler.ErrorCode.ERR_ABORTED && navigating.getAndSet(false)) null else ErrorPage.DEFAULT.create(errorCode, errorText, failedUrl) } multiPanel.select(CONTENT_KEY, true) if (url.isNotEmpty()) { if (file.content.isEmpty()) { file.setContent(this, EditorBundle.message("message.html.editor.timeout"), false) } alarm.addRequest({ contentPanel.loadHTML(file.content.toString()) }, Registry.intValue("html.editor.timeout", 10000)) contentPanel.loadURL(url) } else { contentPanel.loadHTML(file.content.toString()) } } override fun getComponent(): JComponent = multiPanel override fun getPreferredFocusedComponent(): JComponent = multiPanel override fun getName(): String = IdeBundle.message("tab.title.html.preview") override fun setState(state: FileEditorState) { } override fun isModified(): Boolean = false override fun isValid(): Boolean = true override fun addPropertyChangeListener(listener: PropertyChangeListener) { } override fun removePropertyChangeListener(listener: PropertyChangeListener) { } override fun getCurrentLocation(): FileEditorLocation? = null override fun dispose() { } override fun getFile(): VirtualFile = file private companion object { private const val LOADING_KEY = 1 private const val CONTENT_KEY = 0 } }
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/HTMLFileEditor.kt
3436179857
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.extenstions import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.psi.PsiManager import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.QualifiedName import com.jetbrains.extensions.getSdk import com.jetbrains.python.PyNames import com.jetbrains.python.psi.PyClass import com.jetbrains.python.psi.PyFile import com.jetbrains.python.psi.resolve.* import com.jetbrains.python.psi.stubs.PyModuleNameIndex import com.jetbrains.python.psi.types.TypeEvalContext import com.jetbrains.python.sdk.PythonSdkType import org.jetbrains.annotations.ApiStatus //TODO: move to extensions /** * @deprecated use [com.jetbrains.extensions] */ @ApiStatus.ScheduledForRemoval(inVersion = "2020.3") @Deprecated("Use com.jetbrains.extensions") interface ContextAnchor { val sdk: Sdk? val project: Project val qualifiedNameResolveContext: PyQualifiedNameResolveContext? val scope: GlobalSearchScope fun getRoots(): Array<VirtualFile> { return sdk?.rootProvider?.getFiles(OrderRootType.CLASSES) ?: emptyArray() } } /** * @deprecated use [com.jetbrains.extensions] */ @ApiStatus.ScheduledForRemoval(inVersion = "2020.3") @Deprecated("Use com.jetbrains.extensions") class ModuleBasedContextAnchor(val module: Module) : ContextAnchor { override val sdk: Sdk? = module.getSdk() override val project: Project = module.project override val qualifiedNameResolveContext: PyQualifiedNameResolveContext = fromModule(module) override val scope: GlobalSearchScope = module.moduleContentScope override fun getRoots(): Array<VirtualFile> { val manager = ModuleRootManager.getInstance(module) return super.getRoots() + manager.contentRoots + manager.sourceRoots } } /** * @deprecated use [com.jetbrains.extensions] */ @ApiStatus.ScheduledForRemoval(inVersion = "2020.3") @Deprecated("Use com.jetbrains.extensions") class ProjectSdkContextAnchor(override val project: Project, override val sdk: Sdk?) : ContextAnchor { override val qualifiedNameResolveContext: PyQualifiedNameResolveContext? = sdk?.let { fromSdk(project, it) } override val scope: GlobalSearchScope = GlobalSearchScope.projectScope(project) //TODO: Check if project scope includes SDK override fun getRoots(): Array<VirtualFile> { val manager = ProjectRootManager.getInstance(project) return super.getRoots() + manager.contentRoots + manager.contentSourceRoots } } /** * @deprecated use [com.jetbrains.extensions] */ @ApiStatus.ScheduledForRemoval(inVersion = "2020.3") @Deprecated("Use com.jetbrains.extensions") data class QNameResolveContext( val contextAnchor: ContextAnchor, /** * Used for language level etc */ val sdk: Sdk? = contextAnchor.sdk, val evalContext: TypeEvalContext, /** * If not provided resolves against roots only. Resolved also against this folder otherwise */ val folderToStart: VirtualFile? = null, /** * Use index, plain dirs with Py2 and so on. May resolve names unresolvable in other cases, but may return false results. */ val allowInaccurateResult: Boolean = false ) /** * @deprecated use [com.jetbrains.extensions] */ @ApiStatus.ScheduledForRemoval(inVersion = "2020.3") @Deprecated("Use com.jetbrains.extensions") fun QualifiedName.getRelativeNameTo(root: QualifiedName): QualifiedName? { if (!toString().startsWith(root.toString())) { return null } return subQualifiedName(root.componentCount, componentCount) } /** * @deprecated use [com.jetbrains.extensions] */ @ApiStatus.ScheduledForRemoval(inVersion = "2020.3") @Deprecated("Use com.jetbrains.extensions") fun QualifiedName.resolveToElement(context: QNameResolveContext, stopOnFirstFail: Boolean = false): PsiElement? { return getElementAndResolvableName(context, stopOnFirstFail)?.element } /** * @deprecated use [com.jetbrains.extensions] */ @ApiStatus.ScheduledForRemoval(inVersion = "2020.3") @Deprecated("Use com.jetbrains.extensions") data class NameAndElement(val name: QualifiedName, val element: PsiElement) /** * @deprecated use [com.jetbrains.extensions] */ @ApiStatus.ScheduledForRemoval(inVersion = "2020.3") @Deprecated("Use com.jetbrains.extensions") fun QualifiedName.getElementAndResolvableName(context: QNameResolveContext, stopOnFirstFail: Boolean = false): NameAndElement? { var currentName = QualifiedName.fromComponents(this.components) var element: PsiElement? = null var lastElement: String? = null var psiDirectory: PsiDirectory? = null var resolveContext = context.contextAnchor.qualifiedNameResolveContext?.copyWithMembers() ?: return null if (PythonSdkType.getLanguageLevelForSdk(context.sdk).isPy3K || context.allowInaccurateResult) { resolveContext = resolveContext.copyWithPlainDirectories() } if (context.folderToStart != null) { psiDirectory = PsiManager.getInstance(context.contextAnchor.project).findDirectory(context.folderToStart) } // Drill as deep, as we can while (currentName.componentCount > 0 && element == null) { if (psiDirectory != null) { // Resolve against folder // There could be folder and module on the same level. Empty folder should be ignored in this case. element = resolveModuleAt(currentName, psiDirectory, resolveContext).filterNot { it is PsiDirectory && it.children.filterIsInstance<PyFile>().isEmpty() }.firstOrNull() } if (element == null) { // Resolve against roots element = resolveQualifiedName(currentName, resolveContext).firstOrNull() } if (element != null || stopOnFirstFail) { break } lastElement = currentName.lastComponent!! currentName = currentName.removeLastComponent() } if (lastElement != null && element is PyClass) { // Drill in class //TODO: Support nested classes val method = element.findMethodByName(lastElement, true, context.evalContext) if (method != null) { return NameAndElement(currentName.append(lastElement), method) } } if (element == null && this.firstComponent != null && context.allowInaccurateResult) { // If name starts with file which is not in root nor in folders -- use index. val nameToFind = this.firstComponent!! val pyFile = PyModuleNameIndex.find(nameToFind, context.contextAnchor.project, false).firstOrNull() ?: return element val folder = if (pyFile.name == PyNames.INIT_DOT_PY) { // We are in folder pyFile.virtualFile.parent.parent } else { pyFile.virtualFile.parent } return getElementAndResolvableName(context.copy(folderToStart = folder)) } return if (element != null) NameAndElement(currentName, element) else null }
python/src/com/jetbrains/extenstions/QualifiedNameExt.kt
3297785253
package info.vividcode.ktor.twitter.login import info.vividcode.ktor.twitter.login.application.TemporaryCredentialNotFoundException import info.vividcode.ktor.twitter.login.application.TestServerTwitter import info.vividcode.ktor.twitter.login.application.TwitterCallFailedException import info.vividcode.ktor.twitter.login.application.responseBuilder import info.vividcode.ktor.twitter.login.test.TestCallFactory import info.vividcode.ktor.twitter.login.test.TestTemporaryCredentialStore import info.vividcode.oauth.OAuth import io.ktor.application.Application import io.ktor.application.call import io.ktor.http.HttpMethod import io.ktor.http.HttpStatusCode import io.ktor.response.respondText import io.ktor.routing.routing import io.ktor.server.testing.handleRequest import io.ktor.server.testing.withTestApplication import kotlinx.coroutines.newSingleThreadContext import okhttp3.Call import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.ResponseBody.Companion.toResponseBody import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import java.time.Clock import java.time.Instant import java.time.ZoneId import kotlin.coroutines.CoroutineContext internal class RoutingTest { private val testServer = TestServerTwitter() private val testTemporaryCredentialStore = TestTemporaryCredentialStore() private val testEnv = object : Env { override val oauth: OAuth = OAuth(object : OAuth.Env { override val clock: Clock = Clock.fixed(Instant.parse("2015-01-01T00:00:00Z"), ZoneId.systemDefault()) override val nextInt: (Int) -> Int = { (it - 1) / 2 } }) override val httpClient: Call.Factory = TestCallFactory(testServer) override val httpCallContext: CoroutineContext = newSingleThreadContext("TestHttpCall") override val temporaryCredentialStore: TemporaryCredentialStore = testTemporaryCredentialStore } private val outputPort = object : OutputPort { override val success: OutputInterceptor<TwitterToken> = { call.respondText("test success") } override val twitterCallFailed: OutputInterceptor<TwitterCallFailedException> = { call.respondText("test twitter call failed") } override val temporaryCredentialNotFound: OutputInterceptor<TemporaryCredentialNotFoundException> = { call.respondText("test temporary credential not found (identifier : ${it.temporaryCredentialIdentifier})") } } private val testableModule: Application.() -> Unit = { routing { setupTwitterLogin("/start", "/callback", "http://example.com", ClientCredential("test-identifier", "test-secret"), testEnv, outputPort) } } @Test fun testRequest() = withTestApplication(testableModule) { testServer.responseBuilders.add(responseBuilder { code(200).message("OK") body( "oauth_token=test-temporary-token&oauth_token_secret=test-token-secret" .toResponseBody("application/x-www-form-urlencoded".toMediaTypeOrNull()) ) }) handleRequest(HttpMethod.Post, "/start").run { assertEquals(HttpStatusCode.Found, response.status()) assertEquals( "https://api.twitter.com/oauth/authenticate?oauth_token=test-temporary-token", response.headers["Location"] ) } testServer.responseBuilders.add(responseBuilder { code(200).message("OK") body( "oauth_token=test-access-token&oauth_token_secret=test-token-secret&user_id=101&screen_name=foo" .toResponseBody("application/x-www-form-urlencoded".toMediaTypeOrNull()) ) }) handleRequest(HttpMethod.Get, "/callback?oauth_token=test-temporary-token&verifier=test-verifier").run { assertEquals(HttpStatusCode.OK, response.status()) assertEquals("test success", response.content) } } }
ktor-twitter-login/src/test/kotlin/info/vividcode/ktor/twitter/login/RoutingTest.kt
1278374235
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.intentions.style.inference.driver.closure import com.intellij.psi.* import com.intellij.psi.impl.source.resolve.graphInference.constraints.ConstraintFormula import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.parentOfType import org.jetbrains.plugins.groovy.intentions.style.inference.NameGenerator import org.jetbrains.plugins.groovy.intentions.style.inference.SignatureInferenceOptions import org.jetbrains.plugins.groovy.intentions.style.inference.driver.* import org.jetbrains.plugins.groovy.intentions.style.inference.driver.BoundConstraint.ContainMarker.INHABIT import org.jetbrains.plugins.groovy.intentions.style.inference.driver.BoundConstraint.ContainMarker.UPPER import org.jetbrains.plugins.groovy.intentions.style.inference.forceWildcardsAsTypeArguments import org.jetbrains.plugins.groovy.intentions.style.inference.isClosureTypeDeep import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod import kotlin.LazyThreadSafetyMode.NONE class ClosureDriver private constructor(private val closureParameters: Map<GrParameter, ParameterizedClosure>, private val method: GrMethod, private val options: SignatureInferenceOptions) : InferenceDriver { companion object { fun createFromMethod(method: GrMethod, virtualMethod: GrMethod, generator: NameGenerator, options: SignatureInferenceOptions): InferenceDriver { val builder = ClosureParametersStorageBuilder(generator, virtualMethod) val visitedParameters = builder.extractClosuresFromOuterCalls(method, virtualMethod, options.calls.value) virtualMethod.forEachParameterUsage { parameter, instructions -> if (!parameter.type.isClosureTypeDeep() || parameter in visitedParameters) { return@forEachParameterUsage } val callUsages = instructions.mapNotNull { it.element?.parentOfType<GrCall>() } if (!builder.extractClosuresFromCallInvocation(callUsages, parameter)) { builder.extractClosuresFromOtherMethodInvocations(callUsages, parameter) } } val closureParameters = builder.build() return if (closureParameters.isEmpty()) EmptyDriver else ClosureDriver(closureParameters, virtualMethod, options) } } private fun produceParameterizedClosure(parameterMapping: Map<GrParameter, GrParameter>, closureParameter: ParameterizedClosure, substitutor: PsiSubstitutor, manager: ParameterizationManager): ParameterizedClosure { val newParameter = parameterMapping.getValue(closureParameter.parameter) val newTypes = mutableListOf<PsiType>() val newTypeParameters = mutableListOf<PsiTypeParameter>() for (directInnerParameter in closureParameter.typeParameters) { val substitutedType = substitutor.substitute(directInnerParameter)?.forceWildcardsAsTypeArguments() val generifiedType = substitutedType ?: getJavaLangObject(closureParameter.parameter) val (createdType, createdTypeParameters) = manager.createDeeplyParameterizedType(generifiedType) newTypes.add(createdType) newTypeParameters.addAll(createdTypeParameters) } return ParameterizedClosure(newParameter, newTypeParameters, closureParameter.closureArguments, newTypes) } override fun createParameterizedDriver(manager: ParameterizationManager, targetMethod: GrMethod, substitutor: PsiSubstitutor): InferenceDriver { val parameterMapping = setUpParameterMapping(method, targetMethod) val newClosureParameters = mutableMapOf<GrParameter, ParameterizedClosure>() val typeParameterList = targetMethod.typeParameterList ?: return EmptyDriver for ((_, closureParameter) in closureParameters) { val newClosureParameter = produceParameterizedClosure(parameterMapping, closureParameter, substitutor, manager) newClosureParameter.typeParameters.forEach { typeParameterList.add(it) } newClosureParameters[newClosureParameter.parameter] = newClosureParameter } return ClosureDriver(newClosureParameters, targetMethod, options) } override fun typeParameters(): Collection<PsiTypeParameter> { return closureParameters.flatMap { it.value.typeParameters } } override fun collectOuterConstraints(): Collection<ConstraintFormula> { val constraintCollector = mutableListOf<ConstraintFormula>() method.forEachParameterUsage { parameter, instructions -> if (parameter in closureParameters) { constraintCollector.addAll(extractConstraintsFromClosureInvocations(closureParameters.getValue(parameter), instructions)) } } return constraintCollector } private fun collectDeepClosureArgumentsConstraints(): List<TypeUsageInformation> { return closureParameters.values.flatMap { parameter -> parameter.closureArguments.map { closureBlock -> val newMethod = createMethodFromClosureBlock(closureBlock, parameter, method.typeParameterList!!) val emptyOptions = SignatureInferenceOptions(GlobalSearchScope.EMPTY_SCOPE, options.signatureInferenceContext, lazy(NONE) { emptyList<PsiReference>() }) val commonDriver = CommonDriver.createDirectlyFromMethod(newMethod, emptyOptions) val usageInformation = commonDriver.collectInnerConstraints() val typeParameterMapping = newMethod.typeParameters.zip(method.typeParameters).toMap() val shiftedRequiredTypes = usageInformation.requiredClassTypes.map { (param, list) -> typeParameterMapping.getValue(param) to list.map { if (it.marker == UPPER) BoundConstraint(it.type, INHABIT) else it } }.toMap() val newUsageInformation = usageInformation.run { TypeUsageInformation(shiftedRequiredTypes, constraints, dependentTypes.map { typeParameterMapping.getValue(it) }.toSet(), constrainingExpressions) } newUsageInformation } } } private fun collectClosureInvocationConstraints(): TypeUsageInformation { val builder = TypeUsageInformationBuilder(method, options.signatureInferenceContext) method.forEachParameterUsage { parameter, instructions -> if (parameter in closureParameters.keys) { analyzeClosureUsages(closureParameters.getValue(parameter), instructions, builder) } } return builder.build() } override fun collectInnerConstraints(): TypeUsageInformation { val closureBodyAnalysisResult = TypeUsageInformation.merge(collectDeepClosureArgumentsConstraints()) val closureInvocationConstraints = collectClosureInvocationConstraints() return closureInvocationConstraints + closureBodyAnalysisResult } override fun instantiate(resultMethod: GrMethod) { val mapping = setUpParameterMapping(method, resultMethod) for ((_, closureParameter) in closureParameters) { val createdAnnotations = closureParameter.renderTypes(method.parameterList) for ((parameter, anno) in createdAnnotations) { if (anno.isEmpty()) { continue } mapping.getValue(parameter).modifierList.addAnnotation(anno.substring(1)) } } } override fun acceptTypeVisitor(visitor: PsiTypeMapper, resultMethod: GrMethod): InferenceDriver { val mapping = setUpParameterMapping(method, resultMethod) val parameterizedClosureCollector = mutableListOf<Pair<GrParameter, ParameterizedClosure>>() for ((parameter, closure) in closureParameters) { val newTypes = closure.types.map { it.accept(visitor) } val newParameter = mapping.getValue(parameter) val newParameterizedClosure = ParameterizedClosure(newParameter, closure.typeParameters, closure.closureArguments, newTypes, closure.delegatesToCombiner) parameterizedClosureCollector.add(newParameter to newParameterizedClosure) } return ClosureDriver(parameterizedClosureCollector.toMap(), resultMethod, options) } }
plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/inference/driver/closure/ClosureDriver.kt
492291037
// 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.execution.target import com.intellij.openapi.application.Experiments import com.intellij.openapi.options.Configurable import com.intellij.openapi.options.ConfigurableProvider import com.intellij.openapi.project.Project class TargetEnvironmentsConfigurableProvider(private val project: Project) : ConfigurableProvider() { override fun createConfigurable(): Configurable? { return TargetEnvironmentsConfigurable(project) } override fun canCreateConfigurable(): Boolean = Experiments.getInstance().isFeatureEnabled("run.targets") }
platform/execution-impl/src/com/intellij/execution/target/TargetEnvironmentsConfigurableProvider.kt
962942123
class A { public val f : ()->String = {"OK"} } fun box(): String { val a = A() return a.f() // does not work: (in runtime) ClassCastException: A cannot be cast to kotlin.Function0 }
backend.native/tests/external/codegen/box/classes/kt1976.kt
1233264586
package codegen.inline.inline21 import kotlin.test.* inline fun foo2(block2: () -> Int) : Int { println("foo2") return block2() } inline fun foo1(block1: () -> Int) : Int { println("foo1") return foo2(block1) } fun bar(block: () -> Int) : Int { println("bar") return foo1(block) } @Test fun runTest() { println(bar { 33 }) }
backend.native/tests/codegen/inline/inline21.kt
2877830135
import kotlin.test.* import kotlin.properties.* class UnsafeNullableLazyValTest { var resultA = 0 var resultB = 0 val a: Int? by lazy(LazyThreadSafetyMode.NONE) { resultA++; null } val b by lazy(LazyThreadSafetyMode.NONE) { foo() } fun doTest() { a b assertTrue(a == null, "fail: a should be null") assertTrue(b == null, "fail: a should be null") assertTrue(resultA == 1, "fail: initializer for a should be invoked only once") assertTrue(resultB == 1, "fail: initializer for b should be invoked only once") } fun foo(): String? { resultB++ return null } } fun box() { UnsafeNullableLazyValTest().doTest() }
backend.native/tests/external/stdlib/properties/delegation/lazy/LazyValuesTest/UnsafeNullableLazyValTest.kt
1960064862
package a class A() { } operator fun A.component1() = 1 operator fun A.component2() = 1 fun main(args: Array<String>) { val (a, <caret>b) = A() } // REF: b
plugins/kotlin/idea/tests/testData/resolve/references/MultiDeclarationExtension.kt
614968477
// IMPORT: class: kotlin.String package p import java.lang.String fun foo(): ArrayList<String> {}
plugins/kotlin/idea/tests/testData/addImport/CannotImportClass1.kt
1792668601
// 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 import com.intellij.execution.configurations.DebuggingRunnerData import com.intellij.execution.configurations.JavaParameters import com.intellij.execution.configurations.RunConfigurationBase import com.intellij.execution.configurations.RunnerSettings import com.intellij.openapi.project.Project import com.intellij.xdebugger.XDebuggerManagerListener import org.jetbrains.kotlin.idea.debugger.KotlinDebuggerSettings import org.jetbrains.kotlin.idea.debugger.coroutine.util.logger interface DebuggerListener : XDebuggerManagerListener { fun registerDebuggerConnection( configuration: RunConfigurationBase<*>, params: JavaParameters?, runnerSettings: RunnerSettings? ): DebuggerConnection? } class CoroutineDebuggerListener(val project: Project) : DebuggerListener { companion object { val log by logger } override fun registerDebuggerConnection( configuration: RunConfigurationBase<*>, params: JavaParameters?, runnerSettings: RunnerSettings? ): DebuggerConnection? { val coroutineDebugIsDisabledInSettings = KotlinDebuggerSettings.getInstance().debugDisableCoroutineAgent val coroutineDebugIsDisabledInParameters = params != null && params.isKotlinxCoroutinesDebugDisabled() if (!coroutineDebugIsDisabledInSettings && !coroutineDebugIsDisabledInParameters && runnerSettings is DebuggingRunnerData) { return DebuggerConnection( project, configuration, params, argumentsShouldBeModified(configuration) ) } return null } } private const val KOTLINX_COROUTINES_DEBUG_PROPERTY_NAME = "kotlinx.coroutines.debug" private const val KOTLINX_COROUTINES_DEBUG_OFF_VALUE = "off" private fun JavaParameters.isKotlinxCoroutinesDebugDisabled(): Boolean { val kotlinxCoroutinesDebugProperty = vmParametersList.properties[KOTLINX_COROUTINES_DEBUG_PROPERTY_NAME] return kotlinxCoroutinesDebugProperty == KOTLINX_COROUTINES_DEBUG_OFF_VALUE } private fun argumentsShouldBeModified(configuration: RunConfigurationBase<*>): Boolean = !configuration.isGradleConfiguration() && !configuration.isMavenConfiguration() private fun RunConfigurationBase<*>.isGradleConfiguration(): Boolean { val name = type.id return name == "GradleRunConfiguration" || name == "KotlinGradleRunConfiguration" } private fun RunConfigurationBase<*>.isMavenConfiguration(): Boolean = type.id == "MavenRunConfiguration"
plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/DebuggerListener.kt
650991765
package uy.kohesive.iac.model.aws.contexts import com.amazonaws.services.dynamodbv2.AmazonDynamoDB import com.amazonaws.services.dynamodbv2.model.* import uy.kohesive.iac.model.aws.IacContext import uy.kohesive.iac.model.aws.KohesiveIdentifiable import uy.kohesive.iac.model.aws.utils.DslScope interface DynamoDBIdentifiable : KohesiveIdentifiable { } interface DynamoDBEnabled : DynamoDBIdentifiable { val dynamoDBClient: AmazonDynamoDB val dynamoDBContext: DynamoDBContext fun <T> withDynamoDBContext(init: DynamoDBContext.(AmazonDynamoDB) -> T): T = dynamoDBContext.init(dynamoDBClient) } open class BaseDynamoDBContext(protected val context: IacContext) : DynamoDBEnabled by context { open fun createTable(tableName: String, init: CreateTableRequest.() -> Unit): TableDescription { return dynamoDBClient.createTable(CreateTableRequest().apply { withTableName(tableName) init() }).getTableDescription() } }
model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/contexts/DynamoDB.kt
1796710651
package uy.kohesive.iac.model.aws.cloudformation.resources.builders import com.amazonaws.AmazonWebServiceRequest import com.amazonaws.services.lambda.model.* import uy.kohesive.iac.model.aws.cloudformation.ResourcePropertiesBuilder import uy.kohesive.iac.model.aws.cloudformation.resources.Lambda class LambdaVersionResourcePropertiesBuilder : ResourcePropertiesBuilder<PublishVersionRequest> { override val requestClazz = PublishVersionRequest::class override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) = (request as PublishVersionRequest).let { Lambda.Version( CodeSha256 = it.codeSha256, FunctionName = it.functionName, Description = it.description ) } } class LambdaPermissionResourcePropertiesBuilder : ResourcePropertiesBuilder<AddPermissionRequest> { override val requestClazz = AddPermissionRequest::class override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) = (request as AddPermissionRequest).let { Lambda.Permission( Action = it.action, Principal = it.principal, FunctionName = it.functionName, SourceAccount = it.sourceAccount, SourceArn = it.sourceArn ) } } class LambdaAliasResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateAliasRequest> { override val requestClazz = CreateAliasRequest::class override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) = (request as CreateAliasRequest).let { Lambda.Alias( Description = request.description, FunctionName = request.functionName, FunctionVersion = request.functionVersion, Name = request.name ) } } class LambdaEventSourceMappingResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateEventSourceMappingRequest> { override val requestClazz = CreateEventSourceMappingRequest::class override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) = (request as CreateEventSourceMappingRequest).let { Lambda.EventSourceMapping( BatchSize = request.batchSize?.toString(), Enabled = request.enabled?.toString(), EventSourceArn = request.eventSourceArn, FunctionName = request.functionName, StartingPosition = request.startingPosition ) } } class LambdaFunctionResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateFunctionRequest> { override val requestClazz = CreateFunctionRequest::class override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) = (request as CreateFunctionRequest).let { Lambda.Function( Code = request.code.let { Lambda.Function.CodeProperty( S3Key = it.s3Key, S3Bucket = it.s3Bucket, S3ObjectVersion = it.s3ObjectVersion, ZipFile = it.zipFile?.let { String(it.array()) } ) }, Description = request.description, Environment = request.environment?.let { Lambda.Function.EnvironmentProperty( Variables = it.variables ) }, FunctionName = request.functionName, Handler = request.handler, KmsKeyArn = request.kmsKeyArn, MemorySize = request.memorySize?.toString(), Role = request.role, Runtime = request.runtime, Timeout = request.timeout?.toString(), VpcConfig = request.vpcConfig?.let { Lambda.Function.VPCConfigProperty( SecurityGroupIds = it.securityGroupIds, SubnetIds = it.subnetIds ) } ) } }
model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/cloudformation/resources/builders/Lambda.kt
70790381
package com.habitrpg.android.habitica.helpers import android.content.Context import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.data.ApiClient import com.habitrpg.android.habitica.events.ShowAchievementDialog import com.habitrpg.android.habitica.events.ShowCheckinDialog import com.habitrpg.android.habitica.events.ShowSnackbarEvent import com.habitrpg.android.habitica.models.Notification import com.habitrpg.android.habitica.models.notifications.LoginIncentiveData import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.functions.Consumer import io.reactivex.subjects.BehaviorSubject import org.greenrobot.eventbus.EventBus import java.util.* class NotificationsManager (private val context: Context) { private val seenNotifications: MutableMap<String, Boolean> private var apiClient: ApiClient? = null private val notifications: BehaviorSubject<List<Notification>> private var lastNotificationHandling: Date? = null init { this.seenNotifications = HashMap() this.notifications = BehaviorSubject.create() } fun setNotifications(current: List<Notification>) { this.notifications.onNext(current) this.handlePopupNotifications(current) } fun getNotifications(): Flowable<List<Notification>> { return this.notifications .startWith(emptyList<Notification>()) .toFlowable(BackpressureStrategy.LATEST) } fun getNotification(id: String): Notification? { return this.notifications.value?.find { it.id == id } } fun setApiClient(apiClient: ApiClient?) { this.apiClient = apiClient } fun handlePopupNotifications(notifications: List<Notification>): Boolean? { val now = Date() if (now.time - (lastNotificationHandling?.time ?: 0) < 500) { return true } lastNotificationHandling = now notifications .filter { !this.seenNotifications.containsKey(it.id) } .map { val notificationDisplayed = when (it.type) { Notification.Type.LOGIN_INCENTIVE.type -> displayLoginIncentiveNotification(it) Notification.Type.ACHIEVEMENT_PARTY_UP.type -> displayAchievementNotification(it) Notification.Type.ACHIEVEMENT_PARTY_ON.type -> displayAchievementNotification(it) Notification.Type.ACHIEVEMENT_BEAST_MASTER.type -> displayAchievementNotification(it) Notification.Type.ACHIEVEMENT_MOUNT_MASTER.type -> displayAchievementNotification(it) Notification.Type.ACHIEVEMENT_TRIAD_BINGO.type -> displayAchievementNotification(it) Notification.Type.ACHIEVEMENT_GUILD_JOINED.type -> displayAchievementNotification(it) Notification.Type.ACHIEVEMENT_CHALLENGE_JOINED.type -> displayAchievementNotification(it) Notification.Type.ACHIEVEMENT_INVITED_FRIEND.type -> displayAchievementNotification(it) else -> false } if (notificationDisplayed == true) { this.seenNotifications[it.id] = true } } return true } fun displayLoginIncentiveNotification(notification: Notification): Boolean? { val notificationData = notification.data as? LoginIncentiveData val nextUnlockText = context.getString(R.string.nextPrizeUnlocks, notificationData?.nextRewardAt) if (notificationData?.rewardKey != null) { val event = ShowCheckinDialog(notification, nextUnlockText, notificationData.nextRewardAt ?: 0) EventBus.getDefault().post(event) } else { val event = ShowSnackbarEvent() event.title = notificationData?.message event.text = nextUnlockText event.type = HabiticaSnackbar.SnackbarDisplayType.BLUE EventBus.getDefault().post(event) if (apiClient != null) { apiClient?.readNotification(notification.id) ?.subscribe(Consumer {}, RxErrorHandler.handleEmptyError()) } } return true } private fun displayAchievementNotification(notification: Notification): Boolean { EventBus.getDefault().post(ShowAchievementDialog(notification.type ?: "", notification.id)) return true } }
Habitica/src/main/java/com/habitrpg/android/habitica/helpers/NotificationsManager.kt
1790044466
package com.cn29.aac.ui.shoppingkart import androidx.databinding.DataBindingUtil import androidx.lifecycle.ViewModelProvider import com.cn29.aac.R import com.cn29.aac.databinding.ActivityShoppingKartBinding import com.cn29.aac.ui.shoppingkart.vm.ShoppingKartActivityViewModel import com.cn29.aac.ui.shoppingkart.vm.ShoppingKartActivityViewModelFactory import dagger.Module import dagger.Provides @Module class ShoppingKartActivityModule { @Provides fun provideBinding(activity: ShoppingKartActivity): ActivityShoppingKartBinding { return DataBindingUtil.setContentView(activity, R.layout.activity_shopping_kart) } @Provides fun provideVm(factory: ShoppingKartActivityViewModelFactory, activity: ShoppingKartActivity): ShoppingKartActivityViewModel { return ViewModelProvider(activity, factory) .get(ShoppingKartActivityViewModel::class.java) } }
app/src/main/java/com/cn29/aac/ui/shoppingkart/ShoppingKartActivityModule.kt
3155251963
package com.antyzero.smoksmog.ui.screen.start interface TitleProvider { val title: String val subtitle: String }
app/src/main/kotlin/com/antyzero/smoksmog/ui/screen/start/TitleProvider.kt
2315210674
// PROBLEM: Condition is always false // FIX: none // WITH_RUNTIME fun test() { for(i in 1..10) { if (<caret>i >= 11) {} if (i >= 10) {} } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/dfa/basicFor3.kt
2278011568
package com.replaymod.replay.gui.overlay import com.replaymod.core.gui.utils.hiddenChildOf import com.replaymod.replay.gui.overlay.panels.UIHotkeyButtonsPanel import gg.essential.elementa.ElementaVersion import gg.essential.elementa.components.UIContainer import gg.essential.elementa.components.Window import gg.essential.elementa.constraints.ChildBasedMaxSizeConstraint import gg.essential.elementa.constraints.ChildBasedSizeConstraint import gg.essential.elementa.dsl.* class GuiReplayOverlayKt { val window = Window(ElementaVersion.V1, 60) val bottomLeftPanel by UIContainer().constrain { x = 6.pixels(alignOpposite = false) y = 6.pixels(alignOpposite = true) // Children will be next to each other width = ChildBasedSizeConstraint() height = ChildBasedMaxSizeConstraint() } childOf window val bottomRightPanel by UIContainer().constrain { x = 6.pixels(alignOpposite = true) y = 6.pixels(alignOpposite = true) // Children will be on top of each other width = ChildBasedMaxSizeConstraint() height = ChildBasedSizeConstraint() } childOf window val hotkeyButtonsPanel by UIHotkeyButtonsPanel().apply { toggleButton childOf bottomRightPanel } hiddenChildOf window }
src/main/kotlin/com/replaymod/replay/gui/overlay/GuiReplayOverlayKt.kt
3123107837
import utils.* fun main() { Foo().bar() Foo.CONST util1() util2() }
plugins/kotlin/jps/jps-plugin/tests/testData/general/RelocatableCaches/src/main.kt
2699397266
// 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.caches import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiClass import com.intellij.psi.PsiField import com.intellij.psi.PsiMethod import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.PsiShortNamesCache import com.intellij.psi.stubs.StubIndex import com.intellij.util.ArrayUtil import com.intellij.util.Processor import com.intellij.util.Processors import com.intellij.util.containers.ContainerUtil import com.intellij.util.indexing.IdFilter import org.jetbrains.kotlin.asJava.LightClassUtil import org.jetbrains.kotlin.asJava.defaultImplsChild import org.jetbrains.kotlin.asJava.finder.JavaElementFinder import org.jetbrains.kotlin.asJava.getAccessorLightMethods import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName import org.jetbrains.kotlin.idea.decompiler.builtIns.KotlinBuiltInFileType import org.jetbrains.kotlin.idea.stubindex.* import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.load.java.getPropertyNamesCandidatesByAccessorName import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtNamedFunction class KotlinShortNamesCache(private val project: Project) : PsiShortNamesCache() { companion object { private val LOG = Logger.getInstance(KotlinShortNamesCache::class.java) } //hacky way to avoid searches for Kotlin classes, when looking for Java (from Kotlin) val disableSearch: ThreadLocal<Boolean> = object : ThreadLocal<Boolean>() { override fun initialValue(): Boolean = false } //region Classes override fun processAllClassNames(processor: Processor<in String>): Boolean { if (disableSearch.get()) return true return KotlinClassShortNameIndex.getInstance().processAllKeys(project, processor) && KotlinFileFacadeShortNameIndex.INSTANCE.processAllKeys(project, processor) } override fun processAllClassNames(processor: Processor<in String>, scope: GlobalSearchScope, filter: IdFilter?): Boolean { if (disableSearch.get()) return true return processAllClassNames(processor) } /** * Return kotlin class names from project sources which should be visible from java. */ override fun getAllClassNames(): Array<String> { if (disableSearch.get()) return ArrayUtil.EMPTY_STRING_ARRAY return withArrayProcessor(ArrayUtil.EMPTY_STRING_ARRAY) { processor -> processAllClassNames(processor) } } override fun processClassesWithName( name: String, processor: Processor<in PsiClass>, scope: GlobalSearchScope, filter: IdFilter? ): Boolean { if (disableSearch.get()) return true val effectiveScope = kotlinDeclarationsVisibleFromJavaScope(scope) val fqNameProcessor = Processor<FqName> { fqName: FqName? -> if (fqName == null) return@Processor true val isInterfaceDefaultImpl = name == JvmAbi.DEFAULT_IMPLS_CLASS_NAME && fqName.shortName().asString() != name if (fqName.shortName().asString() != name && !isInterfaceDefaultImpl) { LOG.error( "A declaration obtained from index has non-matching name:" + "\nin index: $name" + "\ndeclared: ${fqName.shortName()}($fqName)" ) return@Processor true } val fqNameToSearch = if (isInterfaceDefaultImpl) fqName.defaultImplsChild() else fqName val psiClass = JavaElementFinder.getInstance(project).findClass(fqNameToSearch.asString(), effectiveScope) ?: return@Processor true return@Processor processor.process(psiClass) } val allKtClassOrObjectsProcessed = StubIndex.getInstance().processElements( KotlinClassShortNameIndex.getInstance().key, name, project, effectiveScope, filter, KtClassOrObject::class.java ) { ktClassOrObject -> fqNameProcessor.process(ktClassOrObject.fqName) } if (!allKtClassOrObjectsProcessed) { return false } return StubIndex.getInstance().processElements( KotlinFileFacadeShortNameIndex.getInstance().key, name, project, effectiveScope, filter, KtFile::class.java ) { ktFile -> fqNameProcessor.process(ktFile.javaFileFacadeFqName) } } /** * Return class names form kotlin sources in given scope which should be visible as Java classes. */ override fun getClassesByName(name: String, scope: GlobalSearchScope): Array<PsiClass> { if (disableSearch.get()) return PsiClass.EMPTY_ARRAY return withArrayProcessor(PsiClass.EMPTY_ARRAY) { processor -> processClassesWithName(name, processor, scope, null) } } private fun kotlinDeclarationsVisibleFromJavaScope(scope: GlobalSearchScope): GlobalSearchScope { val noBuiltInsScope: GlobalSearchScope = object : GlobalSearchScope(project) { override fun isSearchInModuleContent(aModule: Module) = true override fun compare(file1: VirtualFile, file2: VirtualFile) = 0 override fun isSearchInLibraries() = true override fun contains(file: VirtualFile) = file.fileType != KotlinBuiltInFileType } return KotlinSourceFilterScope.sourceAndClassFiles(scope, project).intersectWith(noBuiltInsScope) } //endregion //region Methods override fun processAllMethodNames( processor: Processor<in String>, scope: GlobalSearchScope, filter: IdFilter? ): Boolean { if (disableSearch.get()) return true return processAllMethodNames(processor) } override fun getAllMethodNames(): Array<String> { if (disableSearch.get()) ArrayUtil.EMPTY_STRING_ARRAY return withArrayProcessor(ArrayUtil.EMPTY_STRING_ARRAY) { processor -> processAllMethodNames(processor) } } private fun processAllMethodNames(processor: Processor<in String>): Boolean { if (disableSearch.get()) return true if (!KotlinFunctionShortNameIndex.getInstance().processAllKeys(project, processor)) { return false } return KotlinPropertyShortNameIndex.getInstance().processAllKeys(project) { name -> return@processAllKeys processor.process(JvmAbi.setterName(name)) && processor.process(JvmAbi.getterName(name)) } } override fun processMethodsWithName( name: String, processor: Processor<in PsiMethod>, scope: GlobalSearchScope, filter: IdFilter? ): Boolean { if (disableSearch.get()) return true val allFunctionsProcessed = StubIndex.getInstance().processElements( KotlinFunctionShortNameIndex.getInstance().key, name, project, scope, filter, KtNamedFunction::class.java ) { ktNamedFunction -> val methods = LightClassUtil.getLightClassMethodsByName(ktNamedFunction, name) return@processElements methods.all { method -> processor.process(method) } } if (!allFunctionsProcessed) { return false } for (propertyName in getPropertyNamesCandidatesByAccessorName(Name.identifier(name))) { val allProcessed = StubIndex.getInstance().processElements( KotlinPropertyShortNameIndex.getInstance().key, propertyName.asString(), project, scope, filter, KtNamedDeclaration::class.java ) { ktNamedDeclaration -> val methods: Sequence<PsiMethod> = ktNamedDeclaration.getAccessorLightMethods() .asSequence() .filter { it.name == name } return@processElements methods.all { method -> processor.process(method) } } if (!allProcessed) { return false } } return true } override fun getMethodsByName(name: String, scope: GlobalSearchScope): Array<PsiMethod> { if (disableSearch.get()) return PsiMethod.EMPTY_ARRAY return withArrayProcessor(PsiMethod.EMPTY_ARRAY) { processor -> processMethodsWithName(name, processor, scope, null) } } override fun getMethodsByNameIfNotMoreThan(name: String, scope: GlobalSearchScope, maxCount: Int): Array<PsiMethod> { if (disableSearch.get()) return PsiMethod.EMPTY_ARRAY require(maxCount >= 0) return withArrayProcessor(PsiMethod.EMPTY_ARRAY) { processor -> processMethodsWithName( name, { psiMethod -> processor.size != maxCount && processor.process(psiMethod) }, scope, null ) } } override fun processMethodsWithName( name: String, scope: GlobalSearchScope, processor: Processor<in PsiMethod> ): Boolean { if (disableSearch.get()) return true return ContainerUtil.process(getMethodsByName(name, scope), processor) } //endregion //region Fields override fun processAllFieldNames(processor: Processor<in String>, scope: GlobalSearchScope, filter: IdFilter?): Boolean { if (disableSearch.get()) return true return processAllFieldNames(processor) } override fun getAllFieldNames(): Array<String> { if (disableSearch.get()) return ArrayUtil.EMPTY_STRING_ARRAY return withArrayProcessor(ArrayUtil.EMPTY_STRING_ARRAY) { processor -> processAllFieldNames(processor) } } private fun processAllFieldNames(processor: Processor<in String>): Boolean { if (disableSearch.get()) return true return KotlinPropertyShortNameIndex.getInstance().processAllKeys(project, processor) } override fun processFieldsWithName( name: String, processor: Processor<in PsiField>, scope: GlobalSearchScope, filter: IdFilter? ): Boolean { if (disableSearch.get()) return true return StubIndex.getInstance().processElements( KotlinPropertyShortNameIndex.getInstance().key, name, project, scope, filter, KtNamedDeclaration::class.java ) { ktNamedDeclaration -> val field = LightClassUtil.getLightClassBackingField(ktNamedDeclaration) ?: return@processElements true return@processElements processor.process(field) } } override fun getFieldsByName(name: String, scope: GlobalSearchScope): Array<PsiField> { if (disableSearch.get()) return PsiField.EMPTY_ARRAY return withArrayProcessor(PsiField.EMPTY_ARRAY) { processor -> processFieldsWithName(name, processor, scope, null) } } override fun getFieldsByNameIfNotMoreThan(name: String, scope: GlobalSearchScope, maxCount: Int): Array<PsiField> { if (disableSearch.get()) return PsiField.EMPTY_ARRAY require(maxCount >= 0) return withArrayProcessor(PsiField.EMPTY_ARRAY) { processor -> processFieldsWithName( name, { psiField -> processor.size != maxCount && processor.process(psiField) }, scope, null ) } } //endregion private inline fun <T> withArrayProcessor( result: Array<T>, process: (CancelableArrayCollectProcessor<T>) -> Unit ): Array<T> { return CancelableArrayCollectProcessor<T>().also { processor -> process(processor) }.toArray(result) } private class CancelableArrayCollectProcessor<T> : Processor<T> { private val set = HashSet<T>() private val processor = Processors.cancelableCollectProcessor<T>(set) override fun process(value: T): Boolean { return processor.process(value) } val size: Int get() = set.size fun toArray(a: Array<T>): Array<T> = set.toArray(a) } }
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/KotlinShortNamesCache.kt
899438627
// "Import" "true" // ERROR: Unresolved reference: someVal package test fun some() { "".<caret>someVal } /* IGNORE_FIR */
plugins/kotlin/idea/tests/testData/quickfix/autoImports/extensionPropertyImport.before.Main.kt
4019027753
package com.github.kerubistan.kerub.utils.junix.zfs enum class ZfsObjectType { filesystem, volume, snapshot }
src/main/kotlin/com/github/kerubistan/kerub/utils/junix/zfs/ZfsObjectType.kt
2956748489
package com.google.firebase.example.fireeats import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.DialogFragment import com.google.firebase.auth.ktx.auth import com.google.firebase.example.fireeats.databinding.DialogRatingBinding import com.google.firebase.example.fireeats.model.Rating import com.google.firebase.ktx.Firebase /** * Dialog Fragment containing rating form. */ class RatingDialogFragment : DialogFragment() { private var _binding: DialogRatingBinding? = null private val binding get() = _binding!! private var ratingListener: RatingListener? = null internal interface RatingListener { fun onRating(rating: Rating) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = DialogRatingBinding.inflate(inflater, container, false) binding.restaurantFormButton.setOnClickListener { onSubmitClicked() } binding.restaurantFormCancel.setOnClickListener { onCancelClicked() } return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onAttach(context: Context) { super.onAttach(context) if (parentFragment is RatingListener) { ratingListener = parentFragment as RatingListener } } override fun onResume() { super.onResume() dialog?.window?.setLayout( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) } private fun onSubmitClicked() { val user = Firebase.auth.currentUser user?.let { val rating = Rating( it, binding.restaurantFormRating.rating.toDouble(), binding.restaurantFormText.text.toString()) ratingListener?.onRating(rating) } dismiss() } private fun onCancelClicked() { dismiss() } companion object { const val TAG = "RatingDialog" } }
app/src/main/java/com/google/firebase/example/fireeats/RatingDialogFragment.kt
3947108975
/* * 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 import kotlin.native.internal.TypedIntrinsic import kotlin.native.internal.IntrinsicType /** * Represents a value which is either `true` or `false`. On the JVM, non-nullable values of this type are * represented as values of the primitive type `boolean`. */ public class Boolean private constructor() : Comparable<Boolean> { @SinceKotlin("1.3") companion object {} /** * Returns the inverse of this boolean. */ @TypedIntrinsic(IntrinsicType.NOT) external public operator fun not(): Boolean /** * Performs a logical `and` operation between this Boolean and the [other] one. Unlike the `&&` operator, * this function does not perform short-circuit evaluation. Both `this` and [other] will always be evaluated. */ @TypedIntrinsic(IntrinsicType.AND) external public infix fun and(other: Boolean): Boolean /** * Performs a logical `or` operation between this Boolean and the [other] one. Unlike the `||` operator, * this function does not perform short-circuit evaluation. Both `this` and [other] will always be evaluated. */ @TypedIntrinsic(IntrinsicType.OR) external public infix fun or(other: Boolean): Boolean /** * Performs a logical `xor` operation between this Boolean and the [other] one. */ @TypedIntrinsic(IntrinsicType.XOR) external public infix fun xor(other: Boolean): Boolean @TypedIntrinsic(IntrinsicType.UNSIGNED_COMPARE_TO) external public override fun compareTo(other: Boolean): Int public fun equals(other: Boolean): Boolean = kotlin.native.internal.areEqualByValue(this, other) public override fun equals(other: Any?): Boolean = other is Boolean && kotlin.native.internal.areEqualByValue(this, other) public override fun toString() = if (this) "true" else "false" public override fun hashCode() = if (this) 1 else 0 }
runtime/src/main/kotlin/kotlin/Boolean.kt
2501564351
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.actions import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ToggleAction import com.intellij.openapi.project.Project import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration class TogglePackageDetailsAction( private val project: Project, private val selectedCallback: (Boolean) -> Unit ) : ToggleAction( PackageSearchBundle.message("packagesearch.actions.showDetails.text"), PackageSearchBundle.message("packagesearch.actions.showDetails.description"), AllIcons.Actions.PreviewDetails ) { override fun isSelected(e: AnActionEvent) = PackageSearchGeneralConfiguration.getInstance(project).packageDetailsVisible override fun setSelected(e: AnActionEvent, state: Boolean) { PackageSearchGeneralConfiguration.getInstance(project).packageDetailsVisible = state selectedCallback.invoke(state) } override fun getActionUpdateThread() = ActionUpdateThread.BGT }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/actions/TogglePackageDetailsAction.kt
139100612
/* * Copyright (C) 2022 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 okhttp3.internal.connection import java.io.IOException import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.LinkedBlockingDeque import java.util.concurrent.TimeUnit import okhttp3.internal.concurrent.Task import okhttp3.internal.concurrent.TaskRunner import okhttp3.internal.connection.RoutePlanner.ConnectResult import okhttp3.internal.connection.RoutePlanner.Plan import okhttp3.internal.okHttpName /** * Speculatively connects to each IP address of a target address, returning as soon as one of them * connects successfully. This kicks off new attempts every 250 ms until a connect succeeds. */ internal class FastFallbackExchangeFinder( private val routePlanner: RoutePlanner, private val taskRunner: TaskRunner, ) { private val connectDelayMillis = 250L /** Plans currently being connected, and that will later be added to [connectResults]. */ private var connectsInFlight = CopyOnWriteArrayList<Plan>() /** * Results are posted here as they occur. The find job is done when either one plan completes * successfully or all plans fail. */ private val connectResults = taskRunner.backend.decorate(LinkedBlockingDeque<ConnectResult>()) /** Exceptions accumulate here. */ private var firstException: IOException? = null /** True until we've launched all the connects we'll ever launch. */ private var morePlansExist = true fun find(): RealConnection { try { while (morePlansExist || connectsInFlight.isNotEmpty()) { if (routePlanner.isCanceled()) throw IOException("Canceled") launchConnect() val connection = awaitConnection() if (connection != null) return connection morePlansExist = morePlansExist && routePlanner.hasMoreRoutes() } throw firstException!! } finally { for (plan in connectsInFlight) { plan.cancel() } } } private fun launchConnect() { if (!morePlansExist) return val plan = try { routePlanner.plan() } catch (e: IOException) { trackFailure(e) return } connectsInFlight += plan // Already connected? Enqueue the result immediately. if (plan.isConnected) { connectResults.put(ConnectResult(plan)) return } // Connect asynchronously. val taskName = "$okHttpName connect ${routePlanner.address.url.redact()}" taskRunner.newQueue().schedule(object : Task(taskName) { override fun runOnce(): Long { val connectResult = try { connectAndDoRetries() } catch (e: Throwable) { ConnectResult(plan, throwable = e) } connectResults.put(connectResult) return -1L } private fun connectAndDoRetries(): ConnectResult { var firstException: Throwable? = null var currentPlan = plan while (true) { val connectResult = currentPlan.connect() if (connectResult.throwable == null) { if (connectResult.nextPlan == null) return connectResult // Success. } else { if (firstException == null) { firstException = connectResult.throwable } else { firstException.addSuppressed(connectResult.throwable) } // Fail if there's no next plan, or if this failure exception is not recoverable. if (connectResult.nextPlan == null || connectResult.throwable !is IOException) break } // Replace the currently-running plan with its successor. connectsInFlight.add(connectResult.nextPlan) connectsInFlight.remove(currentPlan) currentPlan = connectResult.nextPlan } return ConnectResult(currentPlan, throwable = firstException) } }) } private fun awaitConnection(): RealConnection? { if (connectsInFlight.isEmpty()) return null val completed = connectResults.poll(connectDelayMillis, TimeUnit.MILLISECONDS) ?: return null connectsInFlight.remove(completed.plan) val exception = completed.throwable if (exception is IOException) { trackFailure(exception) return null } else if (exception != null) { throw exception } return completed.plan.handleSuccess() } private fun trackFailure(exception: IOException) { routePlanner.trackFailure(exception) if (firstException == null) { firstException = exception } else { firstException!!.addSuppressed(exception) } } }
okhttp/src/jvmMain/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinder.kt
2453106479
package taiwan.no1.app.ssfm.features.search import android.databinding.ObservableField import android.graphics.Bitmap import android.view.View import com.devrapid.kotlinknifer.formatToMoneyKarma import com.devrapid.kotlinknifer.glideListener import com.devrapid.kotlinknifer.palette import com.hwangjr.rxbus.RxBus import taiwan.no1.app.ssfm.R import taiwan.no1.app.ssfm.features.base.BaseViewModel import taiwan.no1.app.ssfm.features.chart.ChartArtistDetailFragment import taiwan.no1.app.ssfm.misc.constants.Constant.RXBUS_PARAMETER_FRAGMENT import taiwan.no1.app.ssfm.misc.constants.Constant.RXBUS_PARAMETER_FRAGMENT_NEEDBACK import taiwan.no1.app.ssfm.misc.constants.Constant.VIEWMODEL_PARAMS_FOG_COLOR import taiwan.no1.app.ssfm.misc.constants.Constant.VIEWMODEL_PARAMS_IMAGE_URL import taiwan.no1.app.ssfm.misc.constants.Constant.VIEWMODEL_PARAMS_KEYWORD import taiwan.no1.app.ssfm.misc.constants.ImageSizes.EXTRA_LARGE import taiwan.no1.app.ssfm.misc.constants.RxBusTag import taiwan.no1.app.ssfm.misc.constants.RxBusTag.NAVIGATION_TO_FRAGMENT import taiwan.no1.app.ssfm.misc.extension.gAlphaIntColor import taiwan.no1.app.ssfm.misc.extension.gColor import taiwan.no1.app.ssfm.models.entities.lastfm.ArtistEntity import taiwan.no1.app.ssfm.models.entities.lastfm.BaseEntity import kotlin.properties.Delegates /** * * @author jieyi * @since 9/20/17 */ class RecyclerViewSearchArtistChartViewModel(private var artist: BaseEntity) : BaseViewModel() { val artistName by lazy { ObservableField<String>() } val playCount by lazy { ObservableField<String>() } val thumbnail by lazy { ObservableField<String>() } val imageCallback = glideListener<Bitmap> { onResourceReady = { resource, _, _, _, _ -> resource.palette(24).let { color = gAlphaIntColor(it.darkVibrantSwatch?.rgb ?: gColor(R.color.colorPrimaryDark), 0.65f) false } } } private var color by Delegates.notNull<Int>() init { refreshView() } fun setArtistItem(item: BaseEntity) { this.artist = item refreshView() } /** * A callback event for clicking a item to list track. * * @param view [android.widget.RelativeLayout] * * @event_to [taiwan.no1.app.ssfm.features.search.SearchViewModel.receiveClickHistoryEvent] * @event_to [taiwan.no1.app.ssfm.features.chart.ChartActivity.navigate] */ fun artistOnClick(view: View) { val (keyword, imageUrl) = (artist as ArtistEntity.Artist).let { val k = it.name.orEmpty() val u = it.images?.get(EXTRA_LARGE)?.text.orEmpty() k to u } // For `searching activity`. RxBus.get().post(RxBusTag.VIEWMODEL_CLICK_HISTORY, hashMapOf(VIEWMODEL_PARAMS_KEYWORD to keyword, VIEWMODEL_PARAMS_IMAGE_URL to imageUrl, VIEWMODEL_PARAMS_FOG_COLOR to color.toString())) // For `top chart activity`. (artist as ArtistEntity.Artist).let { RxBus.get().post(NAVIGATION_TO_FRAGMENT, hashMapOf(RXBUS_PARAMETER_FRAGMENT to ChartArtistDetailFragment.newInstance(it.mbid.orEmpty(), it.name.orEmpty()), RXBUS_PARAMETER_FRAGMENT_NEEDBACK to true)) } } private fun refreshView() { (artist as ArtistEntity.Artist).let { val count = (it.playCount?.toInt() ?: 0) / 1000 artistName.set(it.name) playCount.set("${count.toString().formatToMoneyKarma()}K") thumbnail.set(it.images?.get(EXTRA_LARGE)?.text.orEmpty()) } } }
app/src/main/kotlin/taiwan/no1/app/ssfm/features/search/RecyclerViewSearchArtistChartViewModel.kt
2319266205
package com.jrvermeer.psalter.models import android.support.v4.media.session.MediaControllerCompat abstract class MediaServiceCallbacks : MediaControllerCompat.Callback() { open fun onAudioUnavailable(psalter: Psalter) { } open fun onBeginShuffling() { } }
app/src/main/java/com/jrvermeer/psalter/models/MediaServiceCallbacks.kt
4196239567
package com.kamer.orny.interaction.model data class Statistics( val daysTotal: Int, val currentDay: Int, val budgetLimit: Double, val budgetLeft: Double, val spendTotal: Double, val budgetSpendTotal: Double, val offBudgetSpendTotal: Double, val budgetDifference: Double, val toSpendToday: Double, val averageSpendPerDay: Double, val averageSpendPerDayAccordingBudgetLeft: Double, val usersStatistics: List<UserStatistics>, val debts: List<Debt> )
app/src/main/kotlin/com/kamer/orny/interaction/model/Statistics.kt
272901041
// !DIAGNOSTICS_NUMBER: 1 // !DIAGNOSTICS: NONE_APPLICABLE // !MESSAGE_TYPE: TEXT package a.b fun foo(a: kotlin.String) { } fun foo(b: String) { } fun foo(i: Int) { } class String val c = foo(1, 2)
plugins/kotlin/idea/tests/testData/diagnosticMessage/noneApplicableTxt.kt
1988285321
// COMPILER_ARGUMENTS: -XXLanguage:+DataObjects open class Base { open protected fun foo() = "Base" } object<caret> Foo : Base() { override fun toString(): String = "Foo" }
plugins/kotlin/idea/tests/testData/inspectionsLocal/convertObjectToDataObject/inheritanceThatDoesntAffectDataObject.kt
29268990
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.observable.properties import com.intellij.openapi.Disposable import java.util.concurrent.atomic.AtomicReference /** * Atomic implementation of boolean property. */ @Suppress("DEPRECATION") class AtomicBooleanProperty( initial: Boolean ) : AbstractObservableBooleanProperty(), AtomicMutableBooleanProperty, BooleanProperty { private val value = AtomicReference(initial) override fun get(): Boolean = value.get() override fun set() = set(true) override fun reset() = set(false) override fun set(value: Boolean) { val oldValue = this.value.getAndSet(value) fireChangeEvents(oldValue, value) } override fun updateAndGet(update: (Boolean) -> Boolean): Boolean { var oldValue: Boolean? = null val newValue = value.updateAndGet { oldValue = it update(it) } fireChangeEvents(oldValue!!, newValue) return newValue } fun compareAndSet(expect: Boolean, update: Boolean): Boolean { val succeed = value.compareAndSet(expect, update) if (succeed) { fireChangeEvents(expect, update) } return succeed } //TODO: Remove with BooleanProperty override fun afterSet(listener: () -> Unit) = afterSet(null, listener) override fun afterSet(listener: () -> Unit, parentDisposable: Disposable) = afterSet(parentDisposable, listener) override fun afterReset(listener: () -> Unit) = afterReset(null, listener) override fun afterReset(listener: () -> Unit, parentDisposable: Disposable) = afterReset(parentDisposable, listener) }
platform/platform-api/src/com/intellij/openapi/observable/properties/AtomicBooleanProperty.kt
2898374302
package com.zeke.network import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.zeke.network.test", appContext.packageName) } }
library/network/src/androidTest/java/com/zeke/network/ExampleInstrumentedTest.kt
1836094493
package foo fun A(a: Int = 1){}
plugins/kotlin/jps/jps-plugin/tests/testData/incremental/pureKotlin/addClass/funA.kt
298420104
// WITH_RUNTIME fun Int.foo(): Int { return <caret>let { it.hashCode().hashCode() } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/simpleRedundantLet/this.kt
590080120
package com.github.kerubistan.kerub.planner.steps.storage.share.nfs import com.github.kerubistan.kerub.model.config.HostConfiguration import com.github.kerubistan.kerub.model.controller.config.ControllerConfig import com.github.kerubistan.kerub.model.controller.config.StorageTechnologiesConfig import com.github.kerubistan.kerub.model.dynamic.VirtualStorageDeviceDynamic import com.github.kerubistan.kerub.model.dynamic.VirtualStorageFsAllocation import com.github.kerubistan.kerub.model.io.VirtualDiskFormat import com.github.kerubistan.kerub.model.services.NfsDaemonService import com.github.kerubistan.kerub.model.services.NfsService import com.github.kerubistan.kerub.planner.OperationalState import com.github.kerubistan.kerub.planner.steps.AbstractFactoryVerifications import com.github.kerubistan.kerub.testDisk import com.github.kerubistan.kerub.testFsCapability import com.github.kerubistan.kerub.testHost import com.github.kerubistan.kerub.testHostCapabilities import io.github.kerubistan.kroki.size.MB import org.junit.Test import kotlin.test.assertTrue class ShareNfsFactoryTest : AbstractFactoryVerifications(ShareNfsFactory) { @Test fun produce() { assertTrue("when nfs disabled, no share steps") { ShareNfsFactory.produce( OperationalState.fromLists( hosts = listOf(testHost), hostCfgs = listOf( HostConfiguration( id = testHost.id, services = listOf(NfsDaemonService()) ) ), vStorage = listOf(), config = ControllerConfig( storageTechnologies = StorageTechnologiesConfig( nfsEnabled = false ) ) ) ).isEmpty() } assertTrue("when nfs enabled, produce steps") { ShareNfsFactory.produce( OperationalState.fromLists( hosts = listOf(testHost), hostCfgs = listOf( HostConfiguration( id = testHost.id, services = listOf(NfsDaemonService()) ) ), vStorage = listOf( testDisk ), vStorageDyns = listOf( VirtualStorageDeviceDynamic( id = testDisk.id, allocations = listOf( VirtualStorageFsAllocation( hostId = testHost.id, actualSize = 100.MB, mountPoint = "/kerub", fileName = "/kerub/${testDisk.id}.qcow2", type = VirtualDiskFormat.qcow2, capabilityId = testFsCapability.id ) ) ) ), config = ControllerConfig( storageTechnologies = StorageTechnologiesConfig( nfsEnabled = true ) ) ) ) == listOf(ShareNfs(host = testHost, directory = "/kerub")) } assertTrue("if it is already shared, do not share it again") { val host = testHost.copy( capabilities = testHostCapabilities.copy( storageCapabilities = listOf(testFsCapability) ) ) ShareNfsFactory.produce( OperationalState.fromLists( hosts = listOf(host), hostCfgs = listOf( HostConfiguration( id = host.id, services = listOf(NfsDaemonService(), NfsService("/kerub", write = true)) ) ), vStorage = listOf( testDisk ), vStorageDyns = listOf( VirtualStorageDeviceDynamic( id = testDisk.id, allocations = listOf( VirtualStorageFsAllocation( hostId = testHost.id, actualSize = 100.MB, mountPoint = testFsCapability.mountPoint, fileName = "${testFsCapability.mountPoint}/${testDisk.id}.qcow2", type = VirtualDiskFormat.qcow2, capabilityId = testFsCapability.id ) ) ) ), config = ControllerConfig( storageTechnologies = StorageTechnologiesConfig( nfsEnabled = true ) ) ) ).isEmpty() } } }
src/test/kotlin/com/github/kerubistan/kerub/planner/steps/storage/share/nfs/ShareNfsFactoryTest.kt
198501292
// "Change type arguments to <*>" "false" // ACTION: Compiler warning 'UNCHECKED_CAST' options // ACTION: Do not show return expression hints fun <T> test(list: List<*>) { val a: List<T> = list as List<T><caret> }
plugins/kotlin/idea/tests/testData/quickfix/addStarProjections/cast/genericTypeParameter5.kt
469915555
class KKKK : KKK() { override var prope<caret>rty: Int = 42 }
plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/hierarchy/kotlin/get/KKKK/KKKK.kt
840046132
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gwt.dev.js import org.jetbrains.kotlin.js.backend.ast.* import java.util.Stack class ScopeContext(scope: JsScope) { private val rootScope = generateSequence(scope) { it.parent }.first { it is JsRootScope } private val scopes = Stack<JsScope>() init { scopes.push(scope) } fun enterFunction(): JsFunction { val fn = JsFunction(currentScope, "<js function>") enterScope(fn.scope) return fn } fun exitFunction() { assert(currentScope is JsFunctionScope) exitScope() } fun enterCatch(ident: String): JsCatch { val jsCatch = JsCatch(currentScope, ident) enterScope(jsCatch.scope) return jsCatch } fun exitCatch() { assert(currentScope is JsCatchScope) exitScope() } fun enterLabel(ident: String): JsName = (currentScope as JsFunctionScope).enterLabel(ident) fun exitLabel() = (currentScope as JsFunctionScope).exitLabel() fun labelFor(ident: String): JsName? = (currentScope as JsFunctionScope).findLabel(ident) fun globalNameFor(ident: String): JsName = currentScope.findName(ident) ?: rootScope.declareName(ident) fun localNameFor(ident: String): JsName = currentScope.findOwnNameOrDeclare(ident) fun referenceFor(ident: String): JsNameRef = JsNameRef(ident) private fun enterScope(scope: JsScope) = scopes.push(scope) private fun exitScope() = scopes.pop() private val currentScope: JsScope get() = scopes.peek() } /** * Overrides JsFunctionScope declareName as it's mapped to declareFreshName */ private fun JsScope.findOwnNameOrDeclare(ident: String): JsName = when (this) { is JsFunctionScope -> declareNameUnsafe(ident) else -> declareName(ident) }
phizdets/phizdetsc/src/com/google/gwt/dev/js/ScopeContext.kt
4269551988
// FIR_IDENTICAL // FIR_COMPARISON enum class A { AAA } enum class E(val one: A, val two: A) { EE(A.<caret>, A.AAA) } // EXIST: AAA
plugins/kotlin/completion/tests/testData/basic/common/KT31762.kt
2633324458
interface Intf { fun v(): Int } interface IntfWithProp : Intf { val x: Int } abstract class Base(p: Int) { open protected fun v(): Int? { } fun nv() { } abstract fun abs(): Int internal open val x: Int get() { } open var y = 1 open protected var z = 1 } class Derived(p: Int) : Base(p), IntfWithProp { override fun v() = unknown() override val x = 3 override fun abs() = 0 } abstract class AnotherDerived(override val x: Int, override val y: Int, override val z: Int) : Base(2) { final override fun v() { } abstract fun noReturn(s: String) abstract val abstractProp: Int } private class Private { override val overridesNothing: Boolean get() = false }
plugins/kotlin/idea/tests/testData/compiler/asJava/ultraLightClasses/inheritance.kt
2409660519
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.injection import com.intellij.lang.injection.InjectedLanguageManager import com.intellij.lang.injection.MultiHostRegistrar import com.intellij.lang.injection.general.Injection import com.intellij.lang.injection.general.LanguageInjectionPerformer import com.intellij.psi.PsiElement import org.intellij.plugins.intelliLang.inject.InjectorUtils import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull class KotlinLanguageInjectionPerformer : LanguageInjectionPerformer { override fun isPrimary(): Boolean = true override fun performInjection(registrar: MultiHostRegistrar, injection: Injection, context: PsiElement): Boolean { if (context !is KtElement || !isSupportedElement(context)) return false val support = InjectorUtils.getActiveInjectionSupports() .firstIsInstanceOrNull<KotlinLanguageInjectionSupport>() ?: return false val language = InjectorUtils.getLanguageByString(injection.injectedLanguageId) ?: return false val file = context.containingKtFile val parts = transformToInjectionParts(injection, context) ?: return false if (parts.ranges.isEmpty()) return false InjectorUtils.registerInjection(language, file, parts.ranges, registrar) InjectorUtils.registerSupport(support, false, context, language) InjectorUtils.putInjectedFileUserData( context, language, InjectedLanguageManager.FRANKENSTEIN_INJECTION, if (parts.isUnparsable) java.lang.Boolean.TRUE else null ) return true } }
plugins/kotlin/injection/src/org/jetbrains/kotlin/idea/injection/KotlinLanguageInjectionPerformer.kt
431930981
// WITH_STDLIB // AFTER-WARNING: Parameter 'f' is never used // AFTER-WARNING: Variable 'x' is never used // AFTER-WARNING: Variable 'z' is never used data class A(var x: Int) fun convert(f: (A) -> Unit) {} fun test() { convert <caret>{ val x = it.x run { val x = 1 val z = it.x } } }
plugins/kotlin/idea/tests/testData/intentions/destructuringInLambda/hasShadowedVariable.kt
58835397
// PROBLEM: none package my.sample class Class { companion object Class { fun say() {} } } fun test() { Class<caret>.say() }
plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantCompanionReference/notApplicableCollision.kt
402719230
// 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.refactoring.move.moveDeclarations.ui import com.intellij.BundleBase import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.util.RadioUpDownListener import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtEnumEntry import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import java.awt.BorderLayout import javax.swing.* internal class KotlinSelectNestedClassRefactoringDialog private constructor( project: Project, private val nestedClass: KtClassOrObject, private val targetContainer: PsiElement? ) : DialogWrapper(project, true) { private val moveToUpperLevelButton = JRadioButton() private val moveMembersButton = JRadioButton() init { title = RefactoringBundle.message("select.refactoring.title") init() } override fun createNorthPanel() = JLabel(RefactoringBundle.message("what.would.you.like.to.do")) override fun getPreferredFocusedComponent() = moveToUpperLevelButton override fun getDimensionServiceKey(): String { return "#org.jetbrains.kotlin.idea.refactoring.move.moveTopLevelDeclarations.ui.KotlinSelectInnerOrMembersRefactoringDialog" } override fun createCenterPanel(): JComponent? { moveToUpperLevelButton.text = KotlinBundle.message("button.text.move.nested.class.0.to.upper.level", nestedClass.name.toString()) moveToUpperLevelButton.isSelected = true moveMembersButton.text = KotlinBundle.message("button.text.move.nested.class.0.to.another.class", nestedClass.name.toString()) ButtonGroup().apply { add(moveToUpperLevelButton) add(moveMembersButton) } RadioUpDownListener(moveToUpperLevelButton, moveMembersButton) return JPanel(BorderLayout()).apply { val box = Box.createVerticalBox().apply { add(Box.createVerticalStrut(5)) add(moveToUpperLevelButton) add(moveMembersButton) } add(box, BorderLayout.CENTER) } } fun getNextDialog(): DialogWrapper? { return when { moveToUpperLevelButton.isSelected -> MoveKotlinNestedClassesToUpperLevelDialog(nestedClass, targetContainer) moveMembersButton.isSelected -> MoveKotlinNestedClassesDialog(nestedClass, targetContainer) else -> null } } companion object { private fun MoveKotlinNestedClassesToUpperLevelDialog( nestedClass: KtClassOrObject, targetContainer: PsiElement? ): MoveKotlinNestedClassesToUpperLevelDialog? { val outerClass = nestedClass.containingClassOrObject ?: return null val newTarget = targetContainer ?: outerClass.containingClassOrObject ?: outerClass.containingFile.let { it.containingDirectory ?: it } return MoveKotlinNestedClassesToUpperLevelDialog(nestedClass.project, nestedClass, newTarget) } private fun MoveKotlinNestedClassesDialog( nestedClass: KtClassOrObject, targetContainer: PsiElement? ): MoveKotlinNestedClassesDialog { return MoveKotlinNestedClassesDialog( nestedClass.project, listOf(nestedClass), nestedClass.containingClassOrObject!!, targetContainer as? KtClassOrObject ?: nestedClass.containingClassOrObject!!, targetContainer as? PsiDirectory, null ) } fun chooseNestedClassRefactoring(nestedClass: KtClassOrObject, targetContainer: PsiElement?) { val project = nestedClass.project val dialog = when { targetContainer.isUpperLevelFor(nestedClass) -> MoveKotlinNestedClassesToUpperLevelDialog(nestedClass, targetContainer) nestedClass is KtEnumEntry -> return else -> { val selectionDialog = KotlinSelectNestedClassRefactoringDialog( project, nestedClass, targetContainer ) selectionDialog.show() if (selectionDialog.exitCode != OK_EXIT_CODE) return selectionDialog.getNextDialog() ?: return } } dialog?.show() } private fun PsiElement?.isUpperLevelFor(nestedClass: KtClassOrObject) = this != null && this !is KtClassOrObject && this !is PsiDirectory || nestedClass is KtClass && nestedClass.isInner() } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/ui/KotlinSelectNestedClassRefactoringDialog.kt
2065774281
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.keymap.impl import com.intellij.configurationStore.SchemeDataHolder import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.actionSystem.MouseShortcut import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.keymap.Keymap import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.options.SchemeState import com.intellij.openapi.util.SystemInfo import org.jdom.Element import java.awt.event.MouseEvent open class DefaultKeymapImpl(dataHolder: SchemeDataHolder<KeymapImpl>, private val defaultKeymapManager: DefaultKeymap, val plugin: PluginDescriptor) : KeymapImpl(dataHolder) { final override var canModify: Boolean get() = false set(_) { // ignore } override fun getSchemeState(): SchemeState = SchemeState.NON_PERSISTENT override fun getPresentableName() = DefaultKeymap.getInstance().getKeymapPresentableName(this) override fun readExternal(keymapElement: Element) { super.readExternal(keymapElement) if (KeymapManager.DEFAULT_IDEA_KEYMAP == name && !SystemInfo.isXWindow) { addShortcut(IdeActions.ACTION_GOTO_DECLARATION, MouseShortcut(MouseEvent.BUTTON2, 0, 1)) } } // default keymap can have parent only in the defaultKeymapManager // also, it allows us to avoid dependency on KeymapManager (maybe not initialized yet) override fun findParentScheme(parentSchemeName: String): Keymap? = defaultKeymapManager.findScheme(parentSchemeName) }
platform/platform-impl/src/com/intellij/openapi/keymap/impl/DefaultKeymapImpl.kt
780235962
// "Make 'Foo' data class" "false" // ACTION: Create extension function 'Foo.component1' // ACTION: Create extension function 'Foo.component2' // ACTION: Create member function 'Foo.component1' // ACTION: Create member function 'Foo.component2' // ACTION: Enable a trailing comma by default in the formatter // ACTION: Put arguments on separate lines // ERROR: Cannot access '<init>': it is protected in 'Foo' // ERROR: Destructuring declaration initializer of type Foo must have a 'component1()' function // ERROR: Destructuring declaration initializer of type Foo must have a 'component2()' function // ERROR: Sealed types cannot be instantiated sealed class Foo(val bar: String, val baz: Int) fun test() { var (bar, baz) = Foo("A", 1)<caret> }
plugins/kotlin/idea/tests/testData/quickfix/addDataModifier/sealed.kt
3387744277
// 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.jetbrains.plugins.github.pullrequest.data.service import com.intellij.openapi.progress.ProgressIndicator import org.jetbrains.annotations.CalledInAny import org.jetbrains.plugins.github.api.data.GHLabel import org.jetbrains.plugins.github.api.data.GHUser import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequest import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestRequestedReviewer import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier import org.jetbrains.plugins.github.util.CollectionDelta import java.util.concurrent.CompletableFuture interface GHPRDetailsService { @CalledInAny fun loadDetails(progressIndicator: ProgressIndicator, pullRequestId: GHPRIdentifier): CompletableFuture<GHPullRequest> @CalledInAny fun updateDetails(indicator: ProgressIndicator, pullRequestId: GHPRIdentifier, title: String?, description: String?) : CompletableFuture<GHPullRequest> @CalledInAny fun adjustReviewers(indicator: ProgressIndicator, pullRequestId: GHPRIdentifier, delta: CollectionDelta<GHPullRequestRequestedReviewer>) : CompletableFuture<Unit> @CalledInAny fun adjustAssignees(indicator: ProgressIndicator, pullRequestId: GHPRIdentifier, delta: CollectionDelta<GHUser>) : CompletableFuture<Unit> @CalledInAny fun adjustLabels(indicator: ProgressIndicator, pullRequestId: GHPRIdentifier, delta: CollectionDelta<GHLabel>) : CompletableFuture<Unit> }
plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/service/GHPRDetailsService.kt
3608675566
// "Create class 'A'" "true" // ERROR: Unresolved reference: A class B { } class Foo: J.<caret>A(abc = 1, ghi = "2", def = B()) { }
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/delegationSpecifier/delegatorToNestedJavaSupercallWithParamNames.before.Main.kt
2519763606
package com.goldenpiedevs.schedule.app.core.utils.work import com.evernote.android.job.Job import com.evernote.android.job.JobRequest import com.evernote.android.job.util.support.PersistableBundleCompat import com.goldenpiedevs.schedule.app.ScheduleApplication import com.goldenpiedevs.schedule.app.core.notifications.manger.NotificationManager import javax.inject.Inject class ShowNotificationWork : Job() { override fun onRunJob(params: Params): Result { (context.applicationContext as ScheduleApplication).appComponent.inject(this) notificationManager.showNotification(params.extras.getString(LESSON_ID, "")) return Result.SUCCESS } @Inject lateinit var notificationManager: NotificationManager companion object { const val TAG = "ShowNotificationWork" private const val LESSON_ID = "lesson_id" fun enqueueWork(lessonId: String, timeToNotify: Long): Int { val dataBuilder = PersistableBundleCompat().apply { putString(LESSON_ID, lessonId) } return JobRequest.Builder(TAG) .setExact(timeToNotify) .setExtras(dataBuilder) .build() .schedule() } } }
app/src/main/java/com/goldenpiedevs/schedule/app/core/utils/work/ShowNotificationWork.kt
4035357963
// 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.workspaceModel.storage.impl import com.intellij.openapi.diagnostic.thisLogger import com.intellij.workspaceModel.storage.WorkspaceEntity import it.unimi.dsi.fastutil.ints.IntOpenHashSet import it.unimi.dsi.fastutil.ints.IntSet internal class ImmutableEntityFamily<E : WorkspaceEntity>( override val entities: ArrayList<WorkspaceEntityData<E>?>, private val emptySlotsSize: Int ) : EntityFamily<E>() { constructor(): this(ArrayList(), 0) fun toMutable() = MutableEntityFamily(entities, true) override fun size(): Int = entities.size - emptySlotsSize override fun familyCheck() { val emptySlotsCounter = entities.count { it == null } assert(emptySlotsCounter == emptySlotsSize) { "EntityFamily has unregistered gaps" } } } internal class MutableEntityFamily<E : WorkspaceEntity>( override var entities: ArrayList<WorkspaceEntityData<E>?>, // if [freezed] is true, [entities] array MUST BE copied before modifying it. private var freezed: Boolean ) : EntityFamily<E>() { // This set contains empty slots at the moment of MutableEntityFamily creation // New empty slots MUST NOT be added this this set, otherwise it would be impossible to distinguish (remove + add) and (replace) events private val availableSlots: IntSet = IntOpenHashSet().also { entities.mapIndexed { index, pEntityData -> if (pEntityData == null) it.add(index) } } // Current amount of nulls in entities private var amountOfGapsInEntities = availableSlots.size // Indexes of entity data that are copied for modification. These entities can be safely modified. private val copiedToModify: IntSet = IntOpenHashSet() fun remove(id: Int) { if (availableSlots.contains(id)) { thisLogger().error("id $id is already removed") return } startWrite() copiedToModify.remove(id) entities[id] = null amountOfGapsInEntities++ } /** * This method adds entityData and changes it's id to the actual one */ fun add(other: WorkspaceEntityData<E>) { startWrite() if (availableSlots.isEmpty()) { other.id = entities.size entities.add(other) } else { val emptySlot = availableSlots.pop() other.id = emptySlot entities[emptySlot] = other amountOfGapsInEntities-- } copiedToModify.add(other.id) } fun book(): Int { startWrite() val bookedId = if (availableSlots.isEmpty()) { entities.add(null) amountOfGapsInEntities++ entities.lastIndex } else { val emptySlot = availableSlots.pop() entities[emptySlot] = null emptySlot } copiedToModify.add(bookedId) return bookedId } fun insertAtId(data: WorkspaceEntityData<E>) { startWrite() val prevValue = entities[data.id] entities[data.id] = data availableSlots.remove(data.id) if (prevValue == null) amountOfGapsInEntities-- copiedToModify.add(data.id) } fun replaceById(entity: WorkspaceEntityData<E>) { val id = entity.id if (entities[id] == null) { thisLogger().error("Nothing to replace. EntityData: $entity") return } startWrite() entities[id] = entity copiedToModify.add(id) } /** * Get entity data that can be modified in a save manne */ fun getEntityDataForModification(arrayId: Int): WorkspaceEntityData<E> { val entity = entities.getOrNull(arrayId) ?: error("Nothing to modify") if (arrayId in copiedToModify) return entity startWrite() val clonedEntity = entity.clone() entities[arrayId] = clonedEntity copiedToModify.add(arrayId) return clonedEntity } fun set(position: Int, value: WorkspaceEntityData<E>) { startWrite() entities[position] = value } fun toImmutable(): ImmutableEntityFamily<E> { freezed = true copiedToModify.clear() return ImmutableEntityFamily(entities, amountOfGapsInEntities) } override fun size(): Int = entities.size - amountOfGapsInEntities override fun familyCheck() {} internal fun isEmpty() = entities.size == amountOfGapsInEntities /** This method should always be called before any modification */ private fun startWrite() { if (!freezed) return entities = ArrayList(entities) freezed = false } private fun IntSet.pop(): Int { val iterator = this.iterator() if (!iterator.hasNext()) error("Set is empty") val res = iterator.nextInt() iterator.remove() return res } companion object { // Do not remove parameter. Kotlin fails with compilation without it @Suppress("RemoveExplicitTypeArguments") fun <T: WorkspaceEntity> createEmptyMutable() = MutableEntityFamily<T>(ArrayList(), false) } } internal sealed class EntityFamily<E : WorkspaceEntity> { internal abstract val entities: List<WorkspaceEntityData<E>?> operator fun get(idx: Int) = entities.getOrNull(idx) fun exists(id: Int) = get(id) != null fun all() = entities.asSequence().filterNotNull() abstract fun size(): Int override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is EntityFamily<*>) return false if (entities != other.entities) return false return true } override fun hashCode(): Int = entities.hashCode() override fun toString(): String { return "EntityFamily(entities=$entities)" } protected abstract fun familyCheck() inline fun assertConsistency(entityAssertion: (WorkspaceEntityData<E>) -> Unit = {}) { entities.forEachIndexed { idx, entity -> if (entity != null) { assert(idx == entity.id) { "Entity with id ${entity.id} is placed at index $idx" } entityAssertion(entity) } } familyCheck() } }
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/EntityFamily.kt
3187928895
// "Create member function 'B.foo'" "true" // ERROR: Unresolved reference: foo class A<T> internal constructor(val b: B<T>) { fun test(): Int { return b.<caret>foo<T, Int, String>(2, "2") } }
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createFunction/call/typeArguments/javaClassMemberWithReceiverArg.before.Main.kt
1582393007
package com.timepath.launcher import java.rmi.Remote import java.rmi.RemoteException public interface Protocol : Remote { throws(RemoteException::class) public fun newFrame() }
src/main/kotlin/com/timepath/launcher/Protocol.kt
258646359
package com.cognifide.gradle.aem.common.mvn import org.gradle.api.tasks.util.PatternFilterable import java.io.File class ModuleResolver(val build: MvnBuild) { val aem = build.aem val all = aem.obj.list<ModuleDescriptor> { finalizeValueOnRead() set(aem.project.provider { when { build.available -> aem.project.fileTree(build.rootDir).matching(pomFilter).files.map { pom -> ModuleDescriptor(this@ModuleResolver, typeResolver(pom), pom) } else -> listOf() } }) } val pomExclusions = aem.obj.strings { set(listOf( "**/test/**", "**/tests/**", "**/*.test/**", "**/*-test/**", "**/*.tests/**", "**/*-tests/**", "**/pipeline/**", "**/pipelines/**" )) aem.prop.list("mvnBuild.moduleResolver.pomExclusions")?.let { set(it) } } val pomFilter: PatternFilterable.() -> Unit = { include("pom.xml", "**/pom.xml") exclude(build.outputExclusions.get()) exclude(pomExclusions.get()) } val namePrefixes = aem.obj.strings { set(listOf()) aem.prop.list("mvnBuild.moduleResolver.namePrefixes")?.let { set(it) } } fun findByName(name: String) = all.get().firstOrNull { it.name == name } fun byName(name: String) = findByName(name) ?: throw MvnException("Cannot find module named '$name' in Maven build at path '$rootDir'!") fun findByArtifact(artifact: Artifact) = all.get().firstOrNull { it.artifactId == artifact.id } fun byArtifact(notation: String) = byArtifact(Artifact(notation)) fun byArtifact(artifact: Artifact) = findByArtifact(artifact) ?: throw MvnException(listOf( "Cannot find module for artifact '${artifact.notation}' in Maven build at path '$rootDir'!", "Consider regenerating a dependency graph file '${build.depGraph.dotFile.get().asFile}' by deleting it." ).joinToString("\n")) fun dependency(nameFrom: String, nameTo: String) = Dependency(byName(nameFrom).artifact, byName(nameTo).artifact) val rootDir get() = build.rootDir.get().asFile val root = all.map { descriptors -> descriptors.firstOrNull { it.dir == rootDir } ?: throw MvnException("Cannot find root module in Maven build at path '$rootDir'!") } val projectPaths = all.map { descriptors -> descriptors.map { it.projectPath }.sorted() } val packagePlugins = aem.obj.strings { set(listOf("content-package-maven-plugin", "wcmio-content-package-maven-plugin")) aem.prop.list("mvnBuild.moduleResolver.contentPackagePlugins")?.let { set(it) } } fun typeResolver(resolver: (File) -> ModuleType) { this.typeResolver = resolver } private var typeResolver: (File) -> ModuleType = { pom -> resolveType(pom) } fun resolveType(pom: File) = when { isJar(pom) -> ModuleType.JAR isPackage(pom) -> ModuleType.PACKAGE isFrontend(pom) -> ModuleType.FRONTEND isDispatcher(pom) -> ModuleType.DISPATCHER isRoot(pom) -> ModuleType.POM else -> ModuleType.RUN } fun isRoot(pom: File) = pom.parentFile == rootDir fun isPackage(pom: File) = pom.parentFile.resolve(build.contentPath.get()).exists() || pom.readText().let { text -> text.contains("<packaging>content-package</packaging>") || packagePlugins.get().any { text.substringBetweenTag("build").substringBetweenTag("plugins").contains("<artifactId>$it</artifactId>") } } fun isJar(pom: File) = pom.parentFile.resolve("src/main/java").exists() || pom.readText().contains("<packaging>bundle</packaging>") fun isFrontend(pom: File) = pom.parentFile.resolve("clientlib.config.js").exists() fun isDispatcher(pom: File) = pom.parentFile.resolve("src/conf.dispatcher.d").exists() private fun String.substringBetweenTag(tag: String) = this.substringAfter("<$tag>").substringBefore("</$tag>") }
src/main/kotlin/com/cognifide/gradle/aem/common/mvn/ModuleResolver.kt
2706336236
package vr import lib.webvrapi.getVRDisplays import lib.webvrapi.navigator import vr.client.VrClient var CLIENT: VrClient? = null fun main(args: Array<String>) { println("Main begin...") navigator.getVRDisplays().then({ displays -> if (displays.size == 0) { println("VR display detected: none") } else { println("VR display detected: " + displays[0].displayName) CLIENT = VrClient(displays[0]) } }).catch({ error -> println("Error getting VR displays: $error") }) println("Main end.") }
client/src/vr/Main.kt
297639033
package io.vertx.kotlin.core.internal /** */ interface Delegator<T> { val delegate: T }
vertx-lang-kotlin/src/main/kotlin/io/vertx/kotlin/core/internal/Delegator.kt
2680276701
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.ROBOT_COMMANDO @LargeTest @RunWith(AndroidJUnit4::class) class TestRC : TestST() { override val gamebook = ROBOT_COMMANDO }
src/androidTest/java/pt/joaomneto/titancompanion/TestRC.kt
182415420
package com.excref.kotblog.blog.service.test import com.excref.kotblog.blog.service.test.helper.ServiceImplTestHelper import org.easymock.EasyMockRunner import org.easymock.EasyMockSupport import org.junit.runner.RunWith /** * @author Arthur Asatryan * @since 6/4/17 4:08 PM */ @RunWith(EasyMockRunner::class) abstract class AbstractServiceImplTest constructor(protected val helper: ServiceImplTestHelper = ServiceImplTestHelper()) : EasyMockSupport()
blog/service/impl/src/test/kotlin/com/excref/kotblog/blog/service/test/AbstractServiceImplTest.kt
1763257342
package io.builderscon.conference2017.infra import io.builderscon.client.model.Session interface SessionDAO { fun findAll(): List<Session>? }
app/src/main/kotlin/io/builderscon/conference2017/infra/SessionDAO.kt
2113388273
package io.kotest.inspectors import io.kotest.assertions.ErrorCollectionMode import io.kotest.assertions.errorCollector fun <T> runTests(col: Collection<T>, f: (T) -> Unit): List<ElementResult<T>> { return col.map { val originalAssertionMode = errorCollector.getCollectionMode() try { errorCollector.setCollectionMode(ErrorCollectionMode.Hard) f(it) ElementPass(it) } catch (e: Throwable) { ElementFail(it, e) } finally { errorCollector.setCollectionMode(originalAssertionMode) } } }
kotest-assertions/kotest-assertions-shared/src/commonMain/kotlin/io/kotest/inspectors/runTests.kt
2520246306
package com.dreampany.framework.ui.adapter import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import com.dreampany.framework.ui.fragment.BaseFragment /** * Created by Hawladar Roman on 5/25/2018. * BJIT Group * [email protected] */ class SmartPagerAdapter<T : BaseFragment>(fragmentManager: FragmentManager) : BaseStateAdapter<T>(fragmentManager) { override fun getItem(position: Int): Fragment { val fragment = getFragment(position) return if (fragment != null) fragment else newFragment(position) } }
frame/src/main/kotlin/com/dreampany/framework/ui/adapter/SmartPagerAdapter.kt
1771322089
package be.rijckaert.tim.lib import be.rijckaert.tim.lib.LottiePullToRefreshes import io.reactivex.Observable import io.reactivex.Observer import io.reactivex.android.MainThreadDisposable class LottiePullToRefreshLayoutObservable(private val lottiePullToRefreshLayout: LottiePullToRefreshLayout) : Observable<LottiePullToRefreshes>() { override fun subscribeActual(observer: Observer<in LottiePullToRefreshes>) { val listener = Listener(lottiePullToRefreshLayout, observer) observer.onSubscribe(listener) lottiePullToRefreshLayout.onTriggerListener(listener.onPullToRefresh) } class Listener(private val lottiePullToRefreshLayout: LottiePullToRefreshLayout, private val observer: Observer<in LottiePullToRefreshes>) : MainThreadDisposable() { val onPullToRefresh : () -> Unit = { if (!isDisposed) { observer.onNext(LottiePullToRefreshes) } } override fun onDispose() { lottiePullToRefreshLayout.removeOnTriggerListener(onPullToRefresh) } } } fun LottiePullToRefreshLayout.refreshes(): Observable<LottiePullToRefreshes> = LottiePullToRefreshLayoutObservable(this)
lib/src/main/kotlin/be/rijckaert/tim/lib/LottiePullToRefreshLayoutObservable.kt
956922675
package com.github.parkee.messenger.model.request import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonValue enum class RequestAttachmentType(private val type: String) { IMAGE("image"), TEMPLATE("template"); @JsonCreator fun fromString(type: String?): RequestAttachmentType? { type ?: return null return valueOf(type) } @JsonValue override fun toString(): String{ return type } }
src/main/kotlin/com/github/parkee/messenger/model/request/RequestAttachmentType.kt
1240740790
package moonpi import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths class EnvironmentTest { @get:Rule val tempFolder = TemporaryFolder() @Test fun checkHomeFolderPath() { assertEquals( Environment().getHomeFolder(), Paths.get(System.getProperty("user.home"), ".moonpi") ) } @Test fun checkConfigurationFilePath() { assertEquals( Environment().getConfigurationFile(), Paths.get(System.getProperty("user.home"), ".moonpi", "config.json") ) } @Test fun checkHistoryFilePath() { assertEquals( Environment().getHistoryFile(), Paths.get(System.getProperty("user.home"), ".moonpi", "history.json") ) } @Test fun checkPicturesFolder() { assertEquals( Environment().getPicturesFolder(), Paths.get(System.getProperty("user.home"), ".moonpi", "pictures") ) } @Test fun checkDefaultUsername() { assertEquals( Environment().getDefaultUsername(), "pi" ) } @Test fun checkDefaultPrivateKey() { assertEquals( Environment().getDefaultPrivateKey(), Paths.get(System.getProperty("user.home"), ".ssh", "id_rsa") ) } @Test fun checkEnvironmentPreparation() { // Given val environment = FakeEnvironment(tempFolder) // When environment.prepare() // Then assertTrue(Files.isDirectory(environment.getHomeFolder())) assertTrue(Files.exists(environment.getConfigurationFile())) assertTrue(Files.exists(environment.getHistoryFile())) assertTrue(Files.isDirectory(environment.getPicturesFolder())) } } class FakeEnvironment(private val tempFolder: TemporaryFolder) : Environment() { override fun getHomeFolder(): Path = Paths.get(tempFolder.root.toString(), "moonpi_tmp_tests") override fun getConfigurationFile(): Path = Paths.get(getHomeFolder().toString(), "fakeConfig") override fun getHistoryFile(): Path = Paths.get(getHomeFolder().toString(), "fakeHistory") override fun getPicturesFolder(): Path = Paths.get(getHomeFolder().toString(), "fakePictures") }
src/test/kotlin/moonpi/environmentTest.kt
3978140030
/* * Copyright 2020 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.chat.bukkit.chatchannel import com.rpkit.chat.bukkit.chatchannel.pipeline.DirectedChatChannelPipelineComponent import com.rpkit.chat.bukkit.chatchannel.pipeline.UndirectedChatChannelPipelineComponent import com.rpkit.core.database.Entity import com.rpkit.players.bukkit.player.RPKPlayer import com.rpkit.players.bukkit.profile.RPKMinecraftProfile import com.rpkit.players.bukkit.profile.RPKThinProfile import java.awt.Color /** * Represents a chat channel */ interface RPKChatChannel: Entity { /** * The name of the chat channel. */ val name: String /** * The colour used to represent the chat channel. * Associating a colour with each channel allows players to easily distinguish between channels. */ val color: Color /** * The radius up to which messages sent to the chat channel may be heard. * If the radius is less than or equal to zero, chat messages are global. * This is measured in metres, which is the size of one Minecraft block. */ val radius: Double /** * A list of all speakers in the channel. * If a speaker sends a message without indicating who it is directed to, it will be sent to this channel. * Players may only be speakers in a single channel. */ @Deprecated("Old players API. Please move to new profiles APIs.", ReplaceWith("speakerParticipants")) val speakers: List<RPKPlayer> /** * A list of all speakers in the channel. * If a speaker sends a message without indicating who it is directed to, it will be sent to this channel. * Chat participants may only be speakers in a single channel. */ val speakerMinecraftProfiles: List<RPKMinecraftProfile> /** * A list of all listeners in the channel. * If a message is sent to a channel, it will be heard by all listeners. * Players may listen to multiple channels. */ @Deprecated("Old players API. Please move to new profiles APIs.", ReplaceWith("listenerMinecraftProfiles")) val listeners: List<RPKPlayer> /** * A list of all listeners in the channel. * If a message is sent to a channel, it will be heard by all listeners. * Chat participants may listen to multiple channels. */ val listenerMinecraftProfiles: List<RPKMinecraftProfile> /** * The directed pipeline for the channel. * Messages to this channel will pass through this pipeline for each listener, so that formatting may be applied for * each recipient. */ val directedPipeline: List<DirectedChatChannelPipelineComponent> /** * The undirected pipeline for the channel. * Messages to this channel will pass through this pipeline once, so that messages may be logged or sent to IRC only * a single time. */ val undirectedPipeline: List<UndirectedChatChannelPipelineComponent> /** * The match pattern for this channel. * If a player's message matches the match pattern, it should be directed to this channel. * In the case of a chat channel not having a match pattern, this may be set to null. */ val matchPattern: String? /** * Whether this channel should be joined by default. * If a channel is joined by default, all new players are added as listeners to the channel upon joining for the * first time. If they are not, the channel is muted until they join it. */ val isJoinedByDefault: Boolean /** * Adds a speaker to the channel. * * @param speaker The player to add */ fun addSpeaker(speaker: RPKPlayer) /** * Removes a speaker from the channel. * * @param speaker The player to remove */ fun removeSpeaker(speaker: RPKPlayer) /** * Adds a speaker to the channel. * * @param speaker The chat participant to add */ fun addSpeaker(speaker: RPKMinecraftProfile) /** * Removes a speaker from the channel. * * @param speaker The chat participant to remove */ fun removeSpeaker(speaker: RPKMinecraftProfile) /** * Adds a listener to the channel. * * @param listener The player to add */ fun addListener(listener: RPKPlayer) /** * Removes a listener from the channel. * * @param listener The player to remove */ fun removeListener(listener: RPKPlayer) /** * Adds a listener to the channel. * * @param listener The Minecraft profile to add * @param isAsync Whether adding the listener is being done asynchronously */ fun addListener(listener: RPKMinecraftProfile, isAsync: Boolean = false) /** * Removes a listener from the channel. * * @param listener The Minecraft profile to remove */ fun removeListener(listener: RPKMinecraftProfile) /** * Sends a message to the channel, passing it through the directed pipeline once for each listener, and the * undirected pipeline once. * * @param sender The player sending the message * @param message The message * @param isAsync Whether the message is being sent asynchronously */ fun sendMessage(sender: RPKPlayer, message: String, isAsync: Boolean = false) /** * Sends the message to the channel, passing it through the specified directed pipeline once for each listener, and * the specified undirected pipeline once. * * @param sender The player sending the message * @param message The message * @param directedPipeline The directed pipeline * @param undirectedPipeline The undirected pipeline * @param isAsync Whether the message is being sent asynchronously */ fun sendMessage(sender: RPKPlayer, message: String, directedPipeline: List<DirectedChatChannelPipelineComponent>, undirectedPipeline: List<UndirectedChatChannelPipelineComponent>, isAsync: Boolean = false) /** * Sends a message to the channel, passing it through the directed pipeline once for each listener, and the * undirected pipeline once. * * @param sender The profile sending the message * @param senderMinecraftProfile The Minecraft profile used to send the message, or null if not sent from Minecraft * @param message The message * @param isAsync Whether the message is being sent asynchronously */ fun sendMessage(sender: RPKThinProfile, senderMinecraftProfile: RPKMinecraftProfile?, message: String, isAsync: Boolean = false) /** * Sends a message to the channel, passing it through the specified directed pipeline once for each listener, and * the specified undirected pipeline once. * * @param sender The profile sending the message * @param senderMinecraftProfile The Minecraft profile used to send the message, or null if not sent from Minecraft * @param message The message * @param directedPipeline The directed pipeline * @param undirectedPipeline The undirected pipeline * @param isAsync Whether the message is being sent asynchronously */ fun sendMessage(sender: RPKThinProfile, senderMinecraftProfile: RPKMinecraftProfile?, message: String, directedPipeline: List<DirectedChatChannelPipelineComponent>, undirectedPipeline: List<UndirectedChatChannelPipelineComponent>, isAsync: Boolean = false) }
bukkit/rpk-chat-lib-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/chatchannel/RPKChatChannel.kt
3638567518
package org.blitzortung.android.map import android.content.Context import android.content.SharedPreferences import android.os.Bundle import android.preference.PreferenceManager import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import org.blitzortung.android.app.Main import org.blitzortung.android.app.view.OnSharedPreferenceChangeListener import org.blitzortung.android.app.view.PreferenceKey import org.blitzortung.android.app.view.get import org.osmdroid.tileprovider.tilesource.TileSourceFactory import org.osmdroid.util.GeoPoint import org.osmdroid.views.CustomZoomButtonsController import org.osmdroid.views.overlay.CopyrightOverlay import org.osmdroid.views.overlay.ScaleBarOverlay import org.osmdroid.views.overlay.compass.CompassOverlay import org.osmdroid.views.overlay.compass.InternalCompassOrientationProvider import kotlin.math.min class MapFragment : Fragment(), OnSharedPreferenceChangeListener { private lateinit var mPrefs: SharedPreferences lateinit var mapView: OwnMapView private set private lateinit var mCopyrightOverlay: CopyrightOverlay private lateinit var mScaleBarOverlay: ScaleBarOverlay private lateinit var compassOverlay: CompassOverlay override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { mapView = OwnMapView(inflater.context) mapView.tileProvider.tileCache.apply { protectedTileComputers.clear(); setAutoEnsureCapacity(false) }; return mapView } @Deprecated("Deprecated in Java") override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) val context = this.requireContext() val dm = context.resources.displayMetrics val preferences = PreferenceManager.getDefaultSharedPreferences(context) preferences.registerOnSharedPreferenceChangeListener(this) mPrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) mCopyrightOverlay = CopyrightOverlay(context) mCopyrightOverlay.setTextSize(7) mapView.overlays.add(mCopyrightOverlay) mScaleBarOverlay = ScaleBarOverlay(mapView) mScaleBarOverlay.setScaleBarOffset(dm.widthPixels / 2, 15) mScaleBarOverlay.setCentred(true) mScaleBarOverlay.setAlignBottom(true) val centered = mScaleBarOverlay.javaClass.getDeclaredField("centred") centered.isAccessible = true centered.setBoolean(mScaleBarOverlay, true) mapView.overlays.add(this.mScaleBarOverlay) compassOverlay = CompassOverlay(context, InternalCompassOrientationProvider(context), mapView) compassOverlay.enableCompass() compassOverlay.setCompassCenter(mapView.width / 2.0f, mapView.height / 2.0f) mapView.overlays.add(this.compassOverlay) //built in zoom controls mapView.zoomController.setVisibility(CustomZoomButtonsController.Visibility.SHOW_AND_FADEOUT) //needed for pinch zooms mapView.setMultiTouchControls(true) //scales tiles to the current screen's DPI, helps with readability of labels mapView.isTilesScaledToDpi = true //the rest of this is restoring the last map location the user looked at val zoomLevel = mPrefs.getFloat(PREFS_ZOOM_LEVEL_DOUBLE, mPrefs.getInt(PREFS_ZOOM_LEVEL, 0).toFloat()) mapView.controller.setZoom(zoomLevel.toDouble()) mapView.setMapOrientation(0f, false) val latitudeString = mPrefs.getString(PREFS_LATITUDE_STRING, null) val longitudeString = mPrefs.getString(PREFS_LONGITUDE_STRING, null) if (latitudeString == null || longitudeString == null) { // case handled for historical reasons only val scrollX = mPrefs.getInt(PREFS_SCROLL_X, 0) val scrollY = mPrefs.getInt(PREFS_SCROLL_Y, 0) mapView.scrollTo(scrollX, scrollY) } else { val latitude = latitudeString.toDouble() val longitude = longitudeString.toDouble() mapView.setExpectedCenter(GeoPoint(latitude, longitude)) } setHasOptionsMenu(true) onSharedPreferenceChanged(preferences, PreferenceKey.MAP_TYPE, PreferenceKey.MAP_SCALE) } fun updateForgroundColor(fgcolor: Int) { mScaleBarOverlay.barPaint = mScaleBarOverlay.barPaint.apply { color = fgcolor } mScaleBarOverlay.textPaint = mScaleBarOverlay.textPaint.apply { color = fgcolor } mapView.postInvalidate() } override fun onPause() { //save the current location val edit = mPrefs.edit() edit.putString(PREFS_TILE_SOURCE, mapView.tileProvider.tileSource.name()) edit.putString(PREFS_LATITUDE_STRING, mapView.mapCenter.latitude.toString()) edit.putString(PREFS_LONGITUDE_STRING, mapView.mapCenter.longitude.toString()) edit.putFloat(PREFS_ZOOM_LEVEL_DOUBLE, mapView.zoomLevelDouble.toFloat()) edit.apply() mapView.onPause() super.onPause() } override fun onDestroyView() { super.onDestroyView() mapView.onDetach() } override fun onResume() { super.onResume() mapView.onResume() } fun calculateTargetZoomLevel(widthInMeters: Float): Double { val equatorLength = 40075004.0 // in meters val widthInPixels = min(mapView.height, mapView.width).toDouble() var metersPerPixel = equatorLength / 256 var zoomLevel = 0.0 while ((metersPerPixel * widthInPixels) > widthInMeters) { metersPerPixel /= 2.7 ++zoomLevel } return zoomLevel - 1.0 } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: PreferenceKey) { @Suppress("NON_EXHAUSTIVE_WHEN") when (key) { PreferenceKey.MAP_TYPE -> { val mapTypeString = sharedPreferences.get(key, "SATELLITE") mapView.setTileSource(if (mapTypeString == "SATELLITE") TileSourceFactory.DEFAULT_TILE_SOURCE else TileSourceFactory.MAPNIK) } PreferenceKey.MAP_SCALE -> { val scaleFactor = sharedPreferences.get(key, 100) / 100f Log.v(Main.LOG_TAG, "MapFragment scale $scaleFactor") mapView.tilesScaleFactor = scaleFactor } else -> {} } } companion object { // =========================================================== // Constants // =========================================================== const val PREFS_NAME = "org.andnav.osm.prefs" const val PREFS_TILE_SOURCE = "tilesource" const val PREFS_SCROLL_X = "scrollX" const val PREFS_SCROLL_Y = "scrollY" const val PREFS_LATITUDE_STRING = "latitudeString" const val PREFS_LONGITUDE_STRING = "longitudeString" const val PREFS_ZOOM_LEVEL = "zoomLevel" const val PREFS_ZOOM_LEVEL_DOUBLE = "zoomLevelDouble" } }
app/src/main/java/org/blitzortung/android/map/MapFragment.kt
4029354204
package site.yanglong.promotion.config.shiro import org.apache.commons.collections.MapUtils import org.apache.shiro.authc.credential.CredentialsMatcher import org.apache.shiro.cache.ehcache.EhCacheManager import org.apache.shiro.codec.Base64 import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor import org.apache.shiro.spring.web.ShiroFilterFactoryBean import org.apache.shiro.web.filter.authc.AnonymousFilter import org.apache.shiro.web.filter.authc.LogoutFilter import org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter import org.apache.shiro.web.filter.authc.UserFilter import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter import org.apache.shiro.web.mgt.CookieRememberMeManager import org.apache.shiro.web.mgt.DefaultWebSecurityManager import org.apache.shiro.web.servlet.AbstractShiroFilter import org.apache.shiro.web.servlet.SimpleCookie import org.apache.shiro.web.session.mgt.DefaultWebSessionManager import org.slf4j.LoggerFactory import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.autoconfigure.AutoConfigureAfter import org.springframework.boot.autoconfigure.condition.ConditionalOnBean import org.springframework.cache.CacheManager import org.springframework.cache.ehcache.EhCacheCacheManager import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.DependsOn import site.yanglong.promotion.config.shiro.authentication.RealmService import site.yanglong.promotion.config.shiro.authentication.ShiroRealm import site.yanglong.promotion.config.shiro.dynamic.DynamicPermissionServiceImpl import site.yanglong.promotion.config.shiro.dynamic.JdbcPermissionDao import javax.servlet.Filter @Configuration @AutoConfigureAfter(ShiroLifeCycleConfig::class,CacheManager::class) class ShiroConfig { private val log = LoggerFactory.getLogger(ShiroConfig::class.java) @Autowired private var shiroProps: ShiroProperties?=null @Autowired private var cachemanager: EhCacheCacheManager? = null private var shiroFilter: ShiroFilterFactoryBean? = null @Bean(name = arrayOf("ehCacheManager")) fun ehCacheManager(): EhCacheManager { val ehCacheManager = EhCacheManager() val manager = cachemanager?.cacheManager ehCacheManager.cacheManager = manager return ehCacheManager } /** * 生成realm * * @return shiroRealm */ @Bean(name = arrayOf("shiroRealm")) @DependsOn("lifecycleBeanPostProcessor") fun shiroRealm(realmService: RealmService, credentialsMatcher: CredentialsMatcher): ShiroRealm { val shiroRealm = ShiroRealm() shiroRealm.name = "drRealm" shiroRealm.identity_in_map_key=shiroProps!!.identityInMapKey shiroRealm.password_in_map_key=shiroProps!!.passwordInMapKey shiroRealm.isEnablePerms=shiroProps!!.enablePerms shiroRealm.isEnableRoles=shiroProps!!.enableRoles shiroRealm.perms_in_map_key=shiroProps!!.permsInMapKey shiroRealm.roles_in_map_key=shiroProps!!.rolesInMapKey shiroRealm.user_status_in_map_key=shiroProps!!.userStatusInMapKey shiroRealm.user_status_forbidden=shiroProps!!.userStatusForbidden shiroRealm.user_status_locked=shiroProps!!.userStatusLocked shiroRealm.realmService = realmService shiroRealm.cacheManager = ehCacheManager() shiroRealm.credentialsMatcher = credentialsMatcher shiroRealm.isCachingEnabled = shiroProps!!.cachingEnabled shiroRealm.isAuthenticationCachingEnabled = shiroProps!!.authenticationCachingEnabled//认证缓存 shiroRealm.authenticationCacheName = shiroProps!!.authenticationCacheName shiroRealm.isAuthorizationCachingEnabled = shiroProps!!.authorizationCachingEnabled//授权缓存 shiroRealm.authorizationCacheName = shiroProps!!.authorizationCacheName return shiroRealm } /** * 代理 * * @return */ @Bean fun advisorAutoProxyCreator(): DefaultAdvisorAutoProxyCreator { val advisorAutoProxyCreator = DefaultAdvisorAutoProxyCreator() advisorAutoProxyCreator.isProxyTargetClass = true return advisorAutoProxyCreator } /** * 记住我cookie */ @Bean(name = arrayOf("rememberMeCookie")) fun rememberMeCookie(): SimpleCookie { val cookie = SimpleCookie(shiroProps!!.rmCookieName) cookie.isHttpOnly = shiroProps!!.cookieIsHttpOnly cookie.maxAge = shiroProps!!.rmCookieMaxAge//有效期,秒,7天 cookie.path = shiroProps!!.rmCookiePath return cookie } /** * 记住我cookie管理器 */ @Bean fun cookieRememberMeManager(): CookieRememberMeManager { val remember = CookieRememberMeManager() remember.cipherKey = Base64.decode(shiroProps!!.rmCipherKey)//用于cookie加密的key remember.cookie = rememberMeCookie()//cookie return remember } /** * 会话dao,如果要进行集群或者分布式应用,这里可以改造为自己的会话dao,也可以对DAO的缓存管理器进行改造 * {@link #ehCacheManager()} */ @Bean fun sessionDAO(): EnterpriseCacheSessionDAO { val sessionDAO = EnterpriseCacheSessionDAO() sessionDAO.activeSessionsCacheName = shiroProps!!.sessionCacheName//session缓存的名称 sessionDAO.cacheManager = ehCacheManager()//缓存管理器 return sessionDAO } /** * 会话cookie */ @Bean fun sessionIdCookie(): SimpleCookie { val sessionIdCookie = SimpleCookie(shiroProps!!.sessionCookieName) sessionIdCookie.domain = shiroProps!!.sessionCookieDomain//注意用域名时必须匹配或者设置跨域 sessionIdCookie.isHttpOnly = shiroProps!!.cookieIsHttpOnly sessionIdCookie.maxAge = shiroProps!!.sessionCookieMaxAge//cookie有效期,单位秒,-1为浏览器进度 sessionIdCookie.path = shiroProps!!.sessionCookiePath//cookie路径 return sessionIdCookie } /** * 会话管理器 */ @Bean fun sessionManager(): DefaultWebSessionManager { val sessionManager = DefaultWebSessionManager() sessionManager.sessionDAO = sessionDAO() sessionManager.isSessionIdCookieEnabled = true//使用cookie传递sessionId sessionManager.sessionIdCookie = sessionIdCookie() sessionManager.globalSessionTimeout = shiroProps!!.globalSessionTimeout//服务端session过期时间,单位毫秒 return sessionManager } /** * securityManager * * @return securityManager */ @Bean(name = arrayOf("securityManager")) fun webSecurityManager(shiroRealm: ShiroRealm): DefaultWebSecurityManager { val securityManager = DefaultWebSecurityManager() securityManager.setRealm(shiroRealm) securityManager.cacheManager = ehCacheManager() securityManager.rememberMeManager = cookieRememberMeManager() securityManager.sessionManager = sessionManager() return securityManager } /** * 授权验证代理设置 * @param securityManager * @return */ @Bean fun authorizationAttributeSourceAdvisor(securityManager: DefaultWebSecurityManager): AuthorizationAttributeSourceAdvisor { val authorizationAttributeSourceAdvisor = AuthorizationAttributeSourceAdvisor() authorizationAttributeSourceAdvisor.securityManager = securityManager return authorizationAttributeSourceAdvisor } /** * 凭证匹配器 * @return */ @Bean(name = arrayOf("credentialsMatcher")) fun credentialsMatcher(): CredentialsMatcher { return DrCredentialsMatcher() } /** * filter工厂 * @return */ @Bean(name = arrayOf("shiroFilter")) fun shiroFilter(webSecurityManager: DefaultWebSecurityManager): ShiroFilterFactoryBean { val shiroFilter = ShiroFilterFactoryBean() shiroFilter.loginUrl = shiroProps!!.loginUrl shiroFilter.successUrl = shiroProps!!.successUrl shiroFilter.unauthorizedUrl = shiroProps!!.unauthorizedUrl if (MapUtils.isNotEmpty(shiroProps!!.definitionMap)) { shiroFilter.filterChainDefinitionMap = shiroProps!!.definitionMap } shiroFilter.securityManager = webSecurityManager val filters = HashMap<String, Filter>() if (MapUtils.isNotEmpty(shiroProps!!.filtersMap)) { shiroProps!!.filtersMap?.forEach { t, u -> filters.put(t, (Class.forName(u).newInstance()) as Filter) } } else { filters.put("anon", AnonymousFilter()) filters.put("authc", PassThruAuthenticationFilter()) filters.put("logout", LogoutFilter()) filters.put("roles", RolesAuthorizationFilter()) filters.put("perms", PermissionsAuthorizationFilter()) filters.put("user", UserFilter()) } shiroFilter.filters = filters log.debug("shiro初始化完成,filter数量为:{}", shiroFilter.filters.size) this.shiroFilter = shiroFilter return shiroFilter } @Bean("dynamicPermissionService") @ConditionalOnBean(AbstractShiroFilter::class, ShiroFilterFactoryBean::class) fun filterChainDefinitionsFactory(jdbcPermissionDao: JdbcPermissionDao): DynamicPermissionServiceImpl { val service = DynamicPermissionServiceImpl() service.shiroFilter = shiroFilter?.`object` as? AbstractShiroFilter service.dynamicPermissionDao = jdbcPermissionDao service.definitions = shiroProps!!.definitions return service } }
src/main/kotlin/site/yanglong/promotion/config/shiro/ShiroConfig.kt
994479705
package org.evomaster.core.search.impact.impactinfocollection.value.numeric import org.evomaster.core.search.gene.Gene import org.evomaster.core.search.gene.numeric.LongGene import org.evomaster.core.search.impact.impactinfocollection.GeneImpact import org.evomaster.core.search.impact.impactinfocollection.SharedImpactInfo import org.evomaster.core.search.impact.impactinfocollection.SpecificImpactInfo /** * created by manzh on 2019-09-09 */ class LongGeneImpact(sharedImpactInfo: SharedImpactInfo, specificImpactInfo: SpecificImpactInfo) : GeneImpact(sharedImpactInfo, specificImpactInfo){ constructor( id : String ) : this(SharedImpactInfo(id), SpecificImpactInfo()) override fun copy(): LongGeneImpact { return LongGeneImpact( shared.copy(), specific.copy() ) } override fun clone(): LongGeneImpact { return LongGeneImpact( shared.clone(), specific.clone() ) } override fun validate(gene: Gene): Boolean = gene is LongGene }
core/src/main/kotlin/org/evomaster/core/search/impact/impactinfocollection/value/numeric/LongGeneImpact.kt
1619076264
package com.piticlistudio.playednext.util import android.support.test.espresso.IdlingResource import timber.log.Timber import java.util.concurrent.atomic.AtomicInteger /** * Espresso Idling resource that handles waiting for RxJava Observables executions. * This class must be used with RxIdlingExecutionHook. * Before registering this idling resource you must: * 1. Create an instance of RxIdlingExecutionHook by passing an instance of this class. * 2. Register RxIdlingExecutionHook with the RxJavaPlugins using registerObservableExecutionHook() * 3. Register this idle resource with Espresso using Espresso.registerIdlingResources() */ class RxIdlingResource : IdlingResource { private val mActiveSubscriptionsCount = AtomicInteger(0) private var mResourceCallback: IdlingResource.ResourceCallback? = null override fun getName(): String { return javaClass.simpleName } override fun isIdleNow(): Boolean { return mActiveSubscriptionsCount.get() <= 0 } override fun registerIdleTransitionCallback(callback: IdlingResource.ResourceCallback) { mResourceCallback = callback } fun incrementActiveSubscriptionsCount() { val count = mActiveSubscriptionsCount.incrementAndGet() Timber.i("Active subscriptions count increased to %d", count) } fun decrementActiveSubscriptionsCount() { val count = mActiveSubscriptionsCount.decrementAndGet() Timber.i("Active subscriptions count decreased to %d", count) if (isIdleNow) { Timber.i("There is no active subscriptions, transitioning to Idle") mResourceCallback?.onTransitionToIdle() } } }
app/src/androidTest/java/com/piticlistudio/playednext/util/RxIdlingResource.kt
566673763
package kscript.integration class CliReplTest : TestBase { fun `CLI REPL tests`() { // ## interactive mode without dependencies // #assert "kscript -i 'exitProcess(0)'" "To create a shell with script dependencies run:\nkotlinc -classpath ''" // #assert "echo '' | kscript -i -" "To create a shell with script dependencies run:\nkotlinc -classpath ''" // // // ## first version is disabled because support-auto-prefixing kicks in // #assert "kscript -i '//DEPS log4j:log4j:1.2.14'" "To create a shell with script dependencies run:\nkotlinc -classpath '${HOME}/.m2/repository/log4j/log4j/1.2.14/log4j-1.2.14.jar'" // #assert "kscript -i <(echo '//DEPS log4j:log4j:1.2.14')" "To create a shell with script dependencies run:\nkotlinc -classpath '${HOME}/.m2/repository/log4j/log4j/1.2.14/log4j-1.2.14.jar'" } }
src/integration/kotlin/kscript/integration/CliReplTest.kt
2619730297
/* * Transportr * * Copyright (c) 2013 - 2021 Torsten Grote * * This program is Free Software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.grobox.transportr.utils import androidx.lifecycle.MutableLiveData class LiveTrigger : MutableLiveData<Unit>() { fun trigger() { value = null } }
app/src/main/java/de/grobox/transportr/utils/LiveTrigger.kt
946635167
package ru.ustimov.weather.util private const val CALLER_INDEX: Int = 1 fun Throwable?.println(logger: Logger) { val stackTraceThrowable = Throwable() val traces = stackTraceThrowable.stackTrace if (traces?.size ?: 0 > CALLER_INDEX + 1) { val trace = traces[CALLER_INDEX] val fileName: String? = trace.fileName val tag: String = if (fileName.isNullOrEmpty()) trace.className else fileName.orEmpty() val lineNumber = if (trace.lineNumber > 0) " at line ${trace.lineNumber}" else "" val message = "Exception in ${trace.className}.${trace.methodName}$lineNumber" logger.e(tag, message, this) } else { logger.e("Throwables", this?.message.orEmpty(), this); } }
app/src/main/java/ru/ustimov/weather/util/Throwables.kt
504332254
package com.encodeering.conflate.experimental.test import org.mockito.Mockito /** * @author Michael Clausen - [email protected] */ fun <T> eq (value : T) : T = Mockito.eq (value) inline fun <reified T> any () : T = Mockito.any (T::class.java) inline fun <reified T> mock () : T = Mockito.mock (T::class.java) fun <T> whenever (element : T) = Mockito.`when` (element) fun spy () = mock<() -> Unit> () inline fun <reified T> spy () = mock<(T) -> Unit> ()
modules/conflate-test/src/main/kotlin/com/encodeering/conflate/experimental/test/Spy.kt
3105212100
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.fresco.vito.core import android.net.Uri import com.facebook.fresco.vito.options.DecodedImageOptions import com.facebook.fresco.vito.options.EncodedImageOptions import com.facebook.imagepipeline.request.ImageRequest interface ImagePipelineUtils { fun buildImageRequest(uri: Uri?, imageOptions: DecodedImageOptions): ImageRequest? fun wrapDecodedImageRequest( originalRequest: ImageRequest, imageOptions: DecodedImageOptions ): ImageRequest? fun buildEncodedImageRequest(uri: Uri?, imageOptions: EncodedImageOptions): ImageRequest? }
vito/core/src/main/java/com/facebook/fresco/vito/core/ImagePipelineUtils.kt
1834971623
package com.battlelancer.seriesguide.sync import android.content.Context import android.content.SharedPreferences import android.text.format.DateUtils import androidx.core.content.edit import com.battlelancer.seriesguide.movies.MoviesSettings import com.battlelancer.seriesguide.movies.tools.MovieTools import com.battlelancer.seriesguide.provider.SgRoomDatabase import com.battlelancer.seriesguide.settings.TmdbSettings import com.battlelancer.seriesguide.util.Errors import com.uwetrottmann.androidutils.AndroidUtils import com.uwetrottmann.tmdb2.services.ConfigurationService import timber.log.Timber class TmdbSync internal constructor( private val context: Context, private val configurationService: ConfigurationService, private val movieTools: MovieTools ) { /** * Downloads and stores the latest image url configuration from themoviedb.org. */ fun updateConfiguration(prefs: SharedPreferences): Boolean { try { val response = configurationService.configuration().execute() if (response.isSuccessful) { val config = response.body() if (!config?.images?.secure_base_url.isNullOrEmpty()) { prefs.edit { putString(TmdbSettings.KEY_TMDB_BASE_URL, config!!.images!!.secure_base_url) } return true } } else { Errors.logAndReport("get config", response) } } catch (e: Exception) { Errors.logAndReport("get config", e) } return false } /** * Regularly updates current and future movies (or those without a release date) with data from * themoviedb.org. All other movies are updated rarely. */ fun updateMovies(progress: SyncProgress): Boolean { val currentTimeMillis = System.currentTimeMillis() // update movies released 6 months ago or newer, should cover most edits val releasedAfter = currentTimeMillis - RELEASED_AFTER_DAYS // exclude movies updated in the last 7 days val updatedBefore = currentTimeMillis - UPDATED_BEFORE_DAYS val updatedBeforeOther = currentTimeMillis - UPDATED_BEFORE_90_DAYS val movies = SgRoomDatabase.getInstance(context).movieHelper() .getMoviesToUpdate(releasedAfter, updatedBefore, updatedBeforeOther) Timber.d("Updating %d movie(s)...", movies.size) val languageCode = MoviesSettings.getMoviesLanguage(context) val regionCode = MoviesSettings.getMoviesRegion(context) var result = true for (movie in movies) { if (!AndroidUtils.isNetworkConnected(context)) { return false // stop updates: no network connection } if (movie.tmdbId == 0) { continue // skip invalid id } // try loading details from tmdb val details = movieTools.getMovieDetails( languageCode, regionCode, movie.tmdbId, false ) if (details.tmdbMovie() != null) { // update local database movieTools.updateMovie(details, movie.tmdbId) } else { // Treat as failure if updating at least one fails. result = false val movieTitle = SgRoomDatabase.getInstance(context) .movieHelper() .getMovieTitle(movie.tmdbId) val message = "Failed to update movie ('${movieTitle}', TMDB id ${movie.tmdbId})." progress.setImportantErrorIfNone(message) Timber.e(message) } } return result } companion object { const val RELEASED_AFTER_DAYS = 6 * 30 * DateUtils.DAY_IN_MILLIS const val UPDATED_BEFORE_DAYS = 7 * DateUtils.DAY_IN_MILLIS const val UPDATED_BEFORE_90_DAYS = 3 * 30 * DateUtils.DAY_IN_MILLIS } }
app/src/main/java/com/battlelancer/seriesguide/sync/TmdbSync.kt
908955043
package com.cruftlab.words.exception import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ResponseStatus /** * Exception to be used when trying to find a word, * and no such word exists */ @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "No such word") class WordNotFoundException(message: String?) : RuntimeException("Word not found: " + message)
src/main/kotlin/com/cruftlab/words/exception/WordNotFoundException.kt
1298703268