content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
// 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.ui.svg import com.intellij.diagnostic.StartUpMeasurer import com.intellij.ui.icons.IconLoadMeasurer import com.intellij.util.ImageLoader import org.jetbrains.annotations.ApiStatus import org.jetbrains.ikv.Ikv import org.jetbrains.ikv.UniversalHash import java.awt.Image import java.nio.ByteBuffer import java.nio.file.Path private val intKeyHash = UniversalHash.IntHash() @ApiStatus.Internal class SvgPrebuiltCacheManager(private val dbDir: Path) { private val lightStores = Stores("") private val darkStores = Stores("-d") @Suppress("PropertyName") private inner class Stores(classifier: String) { val s1 = StoreContainer(1f, classifier) val s1_25 = StoreContainer(1.25f, classifier) val s1_5 = StoreContainer(1.5f, classifier) val s2 = StoreContainer(2f, classifier) val s2_5 = StoreContainer(2.5f, classifier) } private inner class StoreContainer(private val scale: Float, private val classifier: String) { @Volatile private var store: Ikv.SizeUnawareIkv<Int>? = null fun getOrCreate() = store ?: getSynchronized() @Synchronized private fun getSynchronized(): Ikv.SizeUnawareIkv<Int> { var store = store if (store == null) { store = Ikv.loadSizeUnawareIkv(dbDir.resolve("icons-v1-$scale$classifier.db"), intKeyHash) this.store = store } return store } } fun loadFromCache(key: Int, scale: Float, isDark: Boolean, docSize: ImageLoader.Dimension2DDouble): Image? { val start = StartUpMeasurer.getCurrentTimeIfEnabled() val list = if (isDark) darkStores else lightStores // not supported scale val store = when (scale) { 1f -> list.s1.getOrCreate() 1.25f -> list.s1_25.getOrCreate() 1.5f -> list.s1_5.getOrCreate() 2f -> list.s2.getOrCreate() 2.5f -> list.s2_5.getOrCreate() else -> return null } val data = store.getUnboundedValue(key) ?: return null val actualWidth: Int val actualHeight: Int val format = data.get().toInt() and 0xff if (format < 254) { actualWidth = format actualHeight = format } else if (format == 255) { actualWidth = readVar(data) actualHeight = actualWidth } else { actualWidth = readVar(data) actualHeight = readVar(data) } docSize.setSize((actualWidth / scale).toDouble(), (actualHeight / scale).toDouble()) val image = SvgCacheManager.readImage(data, actualWidth, actualHeight) IconLoadMeasurer.svgPreBuiltLoad.end(start) return image } } private fun readVar(buf: ByteBuffer): Int { var aByte = buf.get().toInt() var value: Int = aByte and 127 if (aByte and 128 != 0) { aByte = buf.get().toInt() value = value or (aByte and 127 shl 7) if (aByte and 128 != 0) { aByte = buf.get().toInt() value = value or (aByte and 127 shl 14) if (aByte and 128 != 0) { aByte = buf.get().toInt() value = value or (aByte and 127 shl 21) if (aByte and 128 != 0) { value = value or (buf.get().toInt() shl 28) } } } } return value }
platform/util/ui/src/com/intellij/ui/svg/SvgPrebuiltCacheManager.kt
2077931252
// 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.idea.maven.wizards import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty import com.intellij.openapi.observable.properties.PropertyGraph import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.ui.layout.* import org.jetbrains.idea.maven.project.MavenConfigurableBundle import org.jetbrains.idea.maven.project.MavenGeneralSettings import org.jetbrains.idea.maven.project.MavenProjectBundle import org.jetbrains.idea.maven.utils.MavenUtil class MavenEnvironmentSettingsDialog(private val project: Project, private val settings: MavenGeneralSettings) : DialogWrapper(project) { private val propertyGraph = PropertyGraph() private val userSettingsProperty = propertyGraph.graphProperty { settings.userSettingsFile } private val defaultUserSettingsProperty = propertyGraph.graphProperty { MavenUtil.resolveUserSettingsFile("").path } private val localRepositoryProperty = propertyGraph.graphProperty { settings.localRepository } private val defaultLocalRepositoryProperty = propertyGraph.graphProperty { MavenUtil.resolveLocalRepository("", settings.mavenHome, userSettingsProperty.get()).path } init { title = MavenConfigurableBundle.message("maven.settings.environment.settings.title") init() defaultLocalRepositoryProperty.dependsOn(userSettingsProperty) userSettingsProperty.afterChange(settings::setUserSettingsFile) localRepositoryProperty.afterChange(settings::setLocalRepository) } override fun createActions() = arrayOf(okAction) override fun createCenterPanel() = panel { row(MavenConfigurableBundle.message("maven.settings.environment.user.settings") + ":") { textFieldWithBrowseButton( project = project, property = userSettingsProperty, emptyTextProperty = defaultUserSettingsProperty, browseDialogTitle = MavenProjectBundle.message("maven.select.maven.settings.file"), fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor() ) } row(MavenConfigurableBundle.message("maven.settings.environment.local.repository") + ":") { textFieldWithBrowseButton( project = project, property = localRepositoryProperty, emptyTextProperty = defaultLocalRepositoryProperty, browseDialogTitle = MavenProjectBundle.message("maven.select.local.repository"), fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor() ) } } }
plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenEnvironmentSettingsDialog.kt
1475810832
// 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.quickfix import com.intellij.codeInsight.FileModificationService import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.ide.DataManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.refactoring.RefactoringFactory import com.intellij.refactoring.rename.RenameHandlerRegistry import org.jetbrains.kotlin.idea.KotlinBundle open class RenameIdentifierFix : LocalQuickFix { override fun getName() = KotlinBundle.message("rename.identifier.fix.text") override fun getFamilyName() = name override fun startInWriteAction(): Boolean = false override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement ?: return val file = element.containingFile ?: return if (!FileModificationService.getInstance().prepareFileForWrite(file)) return val editorManager = FileEditorManager.getInstance(project) val fileEditor = editorManager.getSelectedEditor(file.virtualFile) ?: return renameWithoutEditor(element) val dataContext = DataManager.getInstance().getDataContext(fileEditor.component) val renameHandler = RenameHandlerRegistry.getInstance().getRenameHandler(dataContext) val editor = editorManager.selectedTextEditor if (editor != null) { renameHandler?.invoke(project, editor, file, dataContext) } else { val elementToRename = getElementToRename(element) ?: return renameHandler?.invoke(project, arrayOf(elementToRename), dataContext) } } protected open fun getElementToRename(element: PsiElement): PsiElement? = element.parent private fun renameWithoutEditor(element: PsiElement) { val elementToRename = getElementToRename(element) ?: return val factory = RefactoringFactory.getInstance(element.project) val renameRefactoring = factory.createRename(elementToRename, null, true, true) renameRefactoring.run() } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameIdentifierFix.kt
3066055302
interface Trait { fun <A, B : Runnable, E : Map.Entry<A, B>> foo() where B : Cloneable, B : Comparable<B> } class TraitImpl : Trait { <caret> }
plugins/kotlin/idea/tests/testData/codeInsight/overrideImplement/functionWithTypeParameters.kt
1174499925
fun test() { val x: /*T6@*/Function2</*T3@*/Int, /*T4@*/String, /*T5@*/Boolean> = { a: /*T0@*/Int, b: /*T1@*/String -> val a: /*T2@*/Boolean = true/*LIT*/ a/*T2@Boolean*/ }/*Function2<T0@Int, T1@String, T7@Boolean>*/ } //LOWER <: T2 due to 'INITIALIZER' //T2 <: T7 due to 'RETURN' //T3 <: T0 due to 'INITIALIZER' //T4 <: T1 due to 'INITIALIZER' //T7 <: T5 due to 'INITIALIZER'
plugins/kotlin/j2k/new/tests/testData/inference/common/lambdaImplicitReturn.kt
1745729037
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.kotlin import com.intellij.psi.PsiElement import com.intellij.psi.PsiType import org.jetbrains.kotlin.psi.ValueArgument import org.jetbrains.uast.* import org.jetbrains.uast.kotlin.internal.DelegatedMultiResolve class KotlinUNamedExpression private constructor( override val name: String?, override val sourcePsi: PsiElement?, givenParent: UElement?, expressionProducer: (UElement) -> UExpression ) : KotlinAbstractUElement(givenParent), UNamedExpression { override val expression: UExpression by lz { expressionProducer(this) } override val uAnnotations: List<UAnnotation> = emptyList() override val psi: PsiElement? = null override val javaPsi: PsiElement? = null companion object { internal fun create(name: String?, valueArgument: ValueArgument, uastParent: UElement?): UNamedExpression { val expression = valueArgument.getArgumentExpression() return KotlinUNamedExpression(name, valueArgument.asElement(), uastParent) { expressionParent -> expression?.let { expressionParent.getLanguagePlugin().convertOpt<UExpression>(it, expressionParent) } ?: UastEmptyExpression(expressionParent) } } internal fun create( name: String?, valueArguments: List<ValueArgument>, uastParent: UElement? ): UNamedExpression { return KotlinUNamedExpression(name, null, uastParent) { expressionParent -> KotlinUVarargExpression(valueArguments, expressionParent) } } } } class KotlinUVarargExpression( private val valueArgs: List<ValueArgument>, uastParent: UElement? ) : KotlinAbstractUExpression(uastParent), UCallExpressionEx, DelegatedMultiResolve { override val kind: UastCallKind = UastCallKind.NESTED_ARRAY_INITIALIZER override val valueArguments: List<UExpression> by lz { valueArgs.map { it.getArgumentExpression()?.let { argumentExpression -> getLanguagePlugin().convert<UExpression>(argumentExpression, this) } ?: UastEmptyExpression(this) } } override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i) override val valueArgumentCount: Int get() = valueArgs.size override val psi: PsiElement? get() = null override val methodIdentifier: UIdentifier? get() = null override val classReference: UReferenceExpression? get() = null override val methodName: String? get() = null override val typeArgumentCount: Int get() = 0 override val typeArguments: List<PsiType> get() = emptyList() override val returnType: PsiType? get() = null override fun resolve() = null override val receiver: UExpression? get() = null override val receiverType: PsiType? get() = null }
plugins/kotlin/uast/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUNamedExpression.kt
2038296683
package com.kickstarter.ui.activities import android.os.Bundle import android.util.Pair import androidx.core.view.isVisible import androidx.recyclerview.widget.ConcatAdapter import androidx.recyclerview.widget.LinearLayoutManager import com.kickstarter.R import com.kickstarter.databinding.ActivityThreadLayoutBinding import com.kickstarter.libs.BaseActivity import com.kickstarter.libs.KSString import com.kickstarter.libs.RecyclerViewPaginator import com.kickstarter.libs.qualifiers.RequiresActivityViewModel import com.kickstarter.libs.utils.ApplicationUtils import com.kickstarter.libs.utils.UrlUtils import com.kickstarter.libs.utils.extensions.showAlertDialog import com.kickstarter.models.Comment import com.kickstarter.ui.adapters.RepliesAdapter import com.kickstarter.ui.adapters.RepliesStatusAdapter import com.kickstarter.ui.adapters.RootCommentAdapter import com.kickstarter.ui.extensions.hideKeyboard import com.kickstarter.ui.views.OnCommentComposerViewClickedListener import com.kickstarter.viewmodels.ThreadViewModel import org.joda.time.DateTime import rx.android.schedulers.AndroidSchedulers import java.util.concurrent.TimeUnit @RequiresActivityViewModel(ThreadViewModel.ViewModel::class) class ThreadActivity : BaseActivity<ThreadViewModel.ViewModel>(), RepliesStatusAdapter.Delegate, RepliesAdapter.Delegate { private lateinit var binding: ActivityThreadLayoutBinding private lateinit var ksString: KSString /** Replies list adapter **/ private val repliesAdapter = RepliesAdapter(this) /** Replies cell status viewMore or Error **/ private val repliesStatusAdapter = RepliesStatusAdapter(this) /** Replies Root comment cell adapter **/ private val rootCommentAdapter = RootCommentAdapter() /** reverse Layout to bind the replies from bottom **/ private val linearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true) private lateinit var recyclerViewPaginator: RecyclerViewPaginator var isPaginated = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityThreadLayoutBinding.inflate(layoutInflater) setContentView(binding.root) ksString = requireNotNull(environment().ksString()) recyclerViewPaginator = RecyclerViewPaginator(binding.commentRepliesRecyclerView, { viewModel.inputs.nextPage() }, viewModel.outputs.isFetchingReplies(), false) /** use ConcatAdapter to bind adapters to recycler view and replace the section issue **/ binding.commentRepliesRecyclerView.adapter = ConcatAdapter(repliesAdapter, repliesStatusAdapter, rootCommentAdapter) binding.commentRepliesRecyclerView.layoutManager = linearLayoutManager this.viewModel.outputs.getRootComment() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { comment -> /** bind root comment by updating the adapter list**/ rootCommentAdapter.updateRootCommentCell(comment) } this.viewModel.outputs .onCommentReplies() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .doOnNext { linearLayoutManager.stackFromEnd = false } .subscribe { /** bind View more cell if the replies more than 7 or update after refresh initial error state **/ this.repliesStatusAdapter.addViewMoreCell(it.second) if (it.first.isNotEmpty()) { this.repliesAdapter.takeData(it.first) } } viewModel.outputs.shouldShowPaginationErrorUI() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .filter { it } .subscribe { /** bind Error Pagination cell **/ repliesStatusAdapter.addErrorPaginationCell(it) } viewModel.outputs.initialLoadCommentsError() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .filter { it } .subscribe { /** bind Error initial loading cell **/ repliesStatusAdapter.addInitiallyLoadingErrorCell(it) } viewModel.outputs.isFetchingReplies() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { binding.repliesLoadingIndicator.isVisible = it } this.viewModel.shouldFocusOnCompose() .delay(30, TimeUnit.MILLISECONDS) .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { shouldOpenKeyboard -> binding.replyComposer.requestCommentComposerKeyBoard(shouldOpenKeyboard) } viewModel.outputs.currentUserAvatar() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { binding.replyComposer.setAvatarUrl(it) } viewModel.outputs.replyComposerStatus() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { binding.replyComposer.setCommentComposerStatus(it) } viewModel.outputs.scrollToBottom() .compose(bindToLifecycle()) .delay(500, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe { binding.commentRepliesRecyclerView.smoothScrollToPosition(0) } viewModel.outputs.showReplyComposer() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { binding.replyComposer.isVisible = it } viewModel.outputs.loadMoreReplies() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { recyclerViewPaginator.reload() } binding.replyComposer.setCommentComposerActionClickListener(object : OnCommentComposerViewClickedListener { override fun onClickActionListener(string: String) { postReply(string) hideKeyboard() } }) viewModel.outputs.showCommentGuideLinesLink() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { ApplicationUtils.openUrlExternally( this, UrlUtils.appendPath( environment().webEndpoint(), CommentsActivity.COMMENT_KICKSTARTER_GUIDELINES ) ) } viewModel.outputs.hasPendingComments() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { if (it) handleBackAction() else viewModel.inputs.backPressed() } viewModel.outputs.closeThreadActivity() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { closeCommentsActivity() } } private fun handleBackAction() { this.showAlertDialog( getString(R.string.Your_comment_wasnt_posted), getString(R.string.You_will_lose_the_comment_if_you_leave_this_page), getString(R.string.Cancel), getString(R.string.Leave_page), false, positiveAction = { }, negativeAction = { viewModel.inputs.backPressed() } ) } override fun back() { if (binding.replyComposer.isCommentComposerEmpty() == true) { viewModel.inputs.checkIfThereAnyPendingComments() } else { handleBackAction() } } private fun closeCommentsActivity() { super.back() this.finishActivity(taskId) } fun postReply(comment: String) { this.viewModel.inputs.insertNewReplyToList(comment, DateTime.now()) this.binding.replyComposer.clearCommentComposer() } override fun onStop() { super.onStop() hideKeyboard() } override fun exitTransition(): Pair<Int, Int>? { return Pair.create(R.anim.fade_in_slide_in_left, R.anim.slide_out_right) } override fun onRetryViewClicked(comment: Comment) { } override fun onReplyButtonClicked(comment: Comment) { } override fun onFlagButtonClicked(comment: Comment) { TODO("Not yet implemented") } override fun onCommentGuideLinesClicked(comment: Comment) { viewModel.inputs.onShowGuideLinesLinkClicked() } override fun onCommentRepliesClicked(comment: Comment) { } override fun onCommentPostedFailed(comment: Comment, position: Int) { viewModel.inputs.refreshCommentCardInCaseFailedPosted(comment, position) } override fun onCommentPostedSuccessFully(comment: Comment, position: Int) { viewModel.inputs.refreshCommentCardInCaseSuccessPosted(comment, position) } override fun loadMoreCallback() { viewModel.inputs.reloadRepliesPage() } override fun retryCallback() { viewModel.inputs.reloadRepliesPage() } override fun onShowCommentClicked(comment: Comment) { viewModel.inputs.onShowCanceledPledgeComment(comment) } override fun onDestroy() { super.onDestroy() recyclerViewPaginator.stop() binding.commentRepliesRecyclerView.adapter = null this.viewModel = null } }
app/src/main/java/com/kickstarter/ui/activities/ThreadActivity.kt
1634075952
// IS_APPLICABLE: false // WITH_STDLIB fun foo(runnable: Runnable) {} fun bar() { foo<caret>(object : Runnable { override fun run() { } }) }
plugins/kotlin/idea/tests/testData/intentions/objectLiteralToLambda/NotInRange2.kt
2881082528
fun foo(a: Int, b: Int, c: Int, d: Int) : Boolean { return !(a < b && c ==<caret> d && a < d) }
plugins/kotlin/idea/tests/testData/intentions/convertBinaryExpressionWithDemorgansLaw/complexNegation2.kt
1488487303
// 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.internal.statistic.collectors.fus.ui import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.StringEventField import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector class BalloonUsageCollector : CounterUsagesCollector() { companion object { private val GROUP = EventLogGroup("balloons", 4) @JvmField val BALLOON_SHOWN = GROUP.registerEvent("balloon.shown", BalloonIdField()) } override fun getGroup(): EventLogGroup { return GROUP } private class BalloonIdField : StringEventField("balloon_id") { override val validationRule: List<String> get() { return BalloonIdsHolder.EP_NAME.extensionList.flatMap { it.balloonIds } } } }
platform/platform-impl/src/com/intellij/internal/statistic/collectors/fus/ui/BalloonUsageCollector.kt
3483481791
package com.telerik.metadata.parsing.bytecode.methods import com.telerik.metadata.parsing.MetadataInfoAnnotationDescriptor import com.telerik.metadata.parsing.NativeClassDescriptor import com.telerik.metadata.parsing.NativeMethodDescriptor import com.telerik.metadata.parsing.NativeTypeDescriptor import com.telerik.metadata.parsing.bytecode.types.NativeTypeBytecodeDescriptor import org.apache.bcel.classfile.Method abstract class NativeMethodBytecodeDescriptor(private val m: Method, override val declaringClass: NativeClassDescriptor) : NativeMethodDescriptor { override val isSynthetic = m.isSynthetic override val isStatic = m.isStatic override val isAbstract = m.isAbstract override val name: String = m.name override val signature: String = m.signature override val argumentTypes: Array<NativeTypeDescriptor> get() { val ts = m.argumentTypes return Array(ts.size) { NativeTypeBytecodeDescriptor(ts[it]) } } override val returnType = NativeTypeBytecodeDescriptor(m.returnType) override val metadataInfoAnnotation: MetadataInfoAnnotationDescriptor? = null override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false return other is NativeMethodBytecodeDescriptor && m == other.m } override fun hashCode(): Int { return m.hashCode() } }
test-app/build-tools/android-metadata-generator/src/src/com/telerik/metadata/parsing/bytecode/methods/NativeMethodBytecodeDescriptor.kt
4171840808
package com.kingz.library.player /** * Track信息 */ class TrackInfo { enum class TrackType { AUDIO, SUBTITLE } var trackType: TrackType? = null var index = 0 var language: String? = null override fun toString(): String { return "TrackInfo{mTrackType = $trackType, mIndex = $index, mLanguage = $language}" } }
library/player/src/main/java/com/kingz/library/player/TrackInfo.kt
1141115113
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.impl.search import com.intellij.openapi.fileTypes.StdFileTypes import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase import com.intellij.util.indexing.FileContentImpl import com.intellij.util.indexing.IndexingDataKeys import org.intellij.lang.annotations.Language class JavaNullMethodArgumentIndexTest : LightPlatformCodeInsightFixtureTestCase() { fun testIndex() { @Language("JAVA") val file = myFixture.configureByText(StdFileTypes.JAVA, """ package org.some; class Main111 { Main111(Object o) { } void someMethod(Object o, Object o2, Object o3) { } static void staticMethod(Object o, Object o2, Object o3) { } public static void main(String[] args) { staticMethod(null, "", ""); org.some.Main111.staticMethod("", "", null); new Main111(null).someMethod("", "", null); Main111 m = new Main111(null); m.someMethod(null, "", ""); } static class SubClass { SubClass(Object o) { } } static class SubClass2 { SubClass2(Object o) { } } static void main() { new org.some.Main111(null); new org.some.Main111.SubClass(null); new SubClass2(null); new ParametrizedRunnable(null) { @Override void run() { }}; } abstract class ParametrizedRunnable { Object parameter; ParametrizedRunnable(Object parameter){ this.parameter = parameter; } abstract void run(); } } """).virtualFile val content = FileContentImpl.createByFile(file) content.putUserData(IndexingDataKeys.PROJECT, project) val data = JavaNullMethodArgumentIndex().indexer.map(content).keys assertSize(8, data) assertContainsElements(data, JavaNullMethodArgumentIndex.MethodCallData("staticMethod", 0), JavaNullMethodArgumentIndex.MethodCallData("staticMethod", 2), JavaNullMethodArgumentIndex.MethodCallData("someMethod", 0), JavaNullMethodArgumentIndex.MethodCallData("someMethod", 2), JavaNullMethodArgumentIndex.MethodCallData("Main111", 0), JavaNullMethodArgumentIndex.MethodCallData("SubClass", 0), JavaNullMethodArgumentIndex.MethodCallData("SubClass2", 0), JavaNullMethodArgumentIndex.MethodCallData("ParametrizedRunnable", 0)) } }
java/java-tests/testSrc/com/intellij/psi/impl/search/JavaNullMethodArgumentIndexTest.kt
2352770656
package eu.kanade.tachiyomi.data.preference import android.content.Context import eu.kanade.tachiyomi.R /** * This class stores the keys for the preferences in the application. Most of them are defined * in the file "keys.xml". By using this class we can define preferences in one place and get them * referenced here. */ class PreferenceKeys(context: Context) { val theme = context.getString(R.string.pref_theme_key) val rotation = context.getString(R.string.pref_rotation_type_key) val enableTransitions = context.getString(R.string.pref_enable_transitions_key) val showPageNumber = context.getString(R.string.pref_show_page_number_key) val fullscreen = context.getString(R.string.pref_fullscreen_key) val keepScreenOn = context.getString(R.string.pref_keep_screen_on_key) val customBrightness = context.getString(R.string.pref_custom_brightness_key) val customBrightnessValue = context.getString(R.string.pref_custom_brightness_value_key) val colorFilter = context.getString(R.string.pref_color_filter_key) val colorFilterValue = context.getString(R.string.pref_color_filter_value_key) val defaultViewer = context.getString(R.string.pref_default_viewer_key) val imageScaleType = context.getString(R.string.pref_image_scale_type_key) val imageDecoder = context.getString(R.string.pref_image_decoder_key) val zoomStart = context.getString(R.string.pref_zoom_start_key) val readerTheme = context.getString(R.string.pref_reader_theme_key) val readWithTapping = context.getString(R.string.pref_read_with_tapping_key) val readWithVolumeKeys = context.getString(R.string.pref_read_with_volume_keys_key) val reencodeImage = context.getString(R.string.pref_reencode_key) val portraitColumns = context.getString(R.string.pref_library_columns_portrait_key) val landscapeColumns = context.getString(R.string.pref_library_columns_landscape_key) val updateOnlyNonCompleted = context.getString(R.string.pref_update_only_non_completed_key) val autoUpdateMangaSync = context.getString(R.string.pref_auto_update_manga_sync_key) val askUpdateMangaSync = context.getString(R.string.pref_ask_update_manga_sync_key) val lastUsedCatalogueSource = context.getString(R.string.pref_last_catalogue_source_key) val lastUsedCategory = context.getString(R.string.pref_last_used_category_key) val catalogueAsList = context.getString(R.string.pref_display_catalogue_as_list) val displayR18content = context.getString(R.string.pref_R18_content_key) val enabledLanguages = context.getString(R.string.pref_source_languages) val downloadsDirectory = context.getString(R.string.pref_download_directory_key) val downloadThreads = context.getString(R.string.pref_download_slots_key) val downloadOnlyOverWifi = context.getString(R.string.pref_download_only_over_wifi_key) val removeAfterReadSlots = context.getString(R.string.pref_remove_after_read_slots_key) val removeAfterMarkedAsRead = context.getString(R.string.pref_remove_after_marked_as_read_key) val libraryUpdateInterval = context.getString(R.string.pref_library_update_interval_key) val libraryUpdateRestriction = context.getString(R.string.pref_library_update_restriction_key) val libraryUpdateCategories = context.getString(R.string.pref_library_update_categories_key) val filterDownloaded = context.getString(R.string.pref_filter_downloaded_key) val filterUnread = context.getString(R.string.pref_filter_unread_key) val automaticUpdates = context.getString(R.string.pref_enable_automatic_updates_key) val startScreen = context.getString(R.string.pref_start_screen_key) fun sourceUsername(sourceId: String) = "pref_source_username_$sourceId" fun sourcePassword(sourceId: String) = "pref_source_password_$sourceId" fun syncUsername(syncId: Int) = "pref_mangasync_username_$syncId" fun syncPassword(syncId: Int) = "pref_mangasync_password_$syncId" val libraryAsList = context.getString(R.string.pref_display_library_as_list) }
app/src/main/java/eu/kanade/tachiyomi/data/preference/PreferenceKeys.kt
700866023
// WITH_RUNTIME fun String.test(s: String): Boolean { return <caret>toLowerCase() == s.toLowerCase() }
plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceWithIgnoreCaseEquals/extension.kt
3854810471
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.ui.preview import com.intellij.ide.scratch.ScratchUtil import com.intellij.lang.LanguageUtil import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.fileEditor.impl.text.PsiAwareTextEditorProvider import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.VirtualFile import org.intellij.plugins.markdown.lang.MarkdownFileType import org.intellij.plugins.markdown.lang.MarkdownLanguage import org.intellij.plugins.markdown.ui.floating.FloatingToolbar import org.jetbrains.annotations.ApiStatus /** * This provider will create default text editor and attach [FloatingToolbar]. * Toolbar will be disposed right before parent editor disposal. * * This provider is not registered in plugin.xml, so it can be used only manually. */ @ApiStatus.Experimental class MarkdownTextEditorProvider: PsiAwareTextEditorProvider() { override fun accept(project: Project, file: VirtualFile): Boolean { if (!super.accept(project, file)) { return false } return file.fileType == MarkdownFileType.INSTANCE || shouldAcceptScratchFile(project, file) } private fun shouldAcceptScratchFile(project: Project, file: VirtualFile): Boolean { return ScratchUtil.isScratch(file) && LanguageUtil.getLanguageForPsi(project, file, file.fileType) == MarkdownLanguage.INSTANCE } override fun createEditor(project: Project, file: VirtualFile): FileEditor { val actualEditor = super.createEditor(project, file) if (actualEditor is TextEditor) { val toolbar = FloatingToolbar(actualEditor.editor) Disposer.register(actualEditor, toolbar) } return actualEditor } }
plugins/markdown/src/org/intellij/plugins/markdown/ui/preview/MarkdownTextEditorProvider.kt
1227822811
package com.jakewharton.rxbinding.widget import android.widget.RatingBar import rx.Observable import rx.functions.Action1 /** * Create an observable of the rating changes on {@code view}. * <p> * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe * to free this reference. */ public inline fun RatingBar.ratingChanges(): Observable<Float> = RxRatingBar.ratingChanges(this) /** * Create an observable of the rating change events on {@code view}. * <p> * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe * to free this reference. */ public inline fun RatingBar.ratingChangeEvents(): Observable<RatingBarChangeEvent> = RxRatingBar.ratingChangeEvents(this) /** * An action which sets the rating of {@code view}. * <p> * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe * to free this reference. */ public inline fun RatingBar.rating(): Action1<in Float> = RxRatingBar.rating(this) /** * An action which sets whether {@code view} is an indicator (thus non-changeable by the user). * <p> * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe * to free this reference. */ public inline fun RatingBar.isIndicator(): Action1<in Boolean> = RxRatingBar.isIndicator(this)
rxbinding-kotlin/src/main/kotlin/com/jakewharton/rxbinding/widget/RxRatingBar.kt
4097170531
// C // WITH_RUNTIME class C { companion object { @[kotlin.jvm.JvmField] public val foo: String = { "A" }() } } // FIR_COMPARISON
plugins/kotlin/idea/tests/testData/compiler/asJava/lightClasses/publicField/CompanionObject.kt
3689208517
// 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.openapi.vcs.changes import com.intellij.ide.DataManager import com.intellij.ide.DefaultTreeExpander import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionPlaces.CHANGES_VIEW_TOOLBAR import com.intellij.openapi.actionSystem.ActionToolbar import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.changes.ui.ChangesBrowserNode import com.intellij.openapi.vcs.changes.ui.ChangesListView import com.intellij.openapi.vcs.changes.ui.HoverIcon import com.intellij.ui.IdeBorderFactory.createBorder import com.intellij.ui.JBColor import com.intellij.ui.ScrollPaneFactory.createScrollPane import com.intellij.ui.SideBorder import com.intellij.util.EditSourceOnDoubleClickHandler.isToggleEvent import com.intellij.util.OpenSourceUtil.openSourcesFrom import com.intellij.util.Processor import com.intellij.util.ui.JBUI.Panels.simplePanel import com.intellij.util.ui.components.BorderLayoutPanel import com.intellij.util.ui.tree.TreeUtil import javax.swing.JComponent import javax.swing.JTree import javax.swing.SwingConstants import kotlin.properties.Delegates.observable class ChangesViewPanel(project: Project) : BorderLayoutPanel() { val changesView: ChangesListView = MyChangesListView(project).apply { treeExpander = object : DefaultTreeExpander(this) { override fun collapseAll(tree: JTree, keepSelectionLevel: Int) { super.collapseAll(tree, 2) TreeUtil.expand(tree, 1) } } doubleClickHandler = Processor { e -> if (isToggleEvent(this, e)) return@Processor false openSourcesFrom(DataManager.getInstance().getDataContext(this), true) true } enterKeyHandler = Processor { openSourcesFrom(DataManager.getInstance().getDataContext(this), false) true } } val toolbarActionGroup = DefaultActionGroup() var isToolbarHorizontal: Boolean by observable(false) { _, oldValue, newValue -> if (oldValue != newValue) { addToolbar(newValue) // this also removes toolbar from previous parent } } val toolbar: ActionToolbar = ActionManager.getInstance().createActionToolbar(CHANGES_VIEW_TOOLBAR, toolbarActionGroup, isToolbarHorizontal).apply { setTargetComponent(changesView) } var statusComponent by observable<JComponent?>(null) { _, oldValue, newValue -> if (oldValue == newValue) return@observable if (oldValue != null) centerPanel.remove(oldValue) if (newValue != null) centerPanel.addToBottom(newValue) } private val centerPanel = simplePanel(createScrollPane(changesView)) init { addToCenter(centerPanel) addToolbar(isToolbarHorizontal) } private fun addToolbar(isHorizontal: Boolean) { if (isHorizontal) { toolbar.setOrientation(SwingConstants.HORIZONTAL) centerPanel.border = createBorder(JBColor.border(), SideBorder.TOP) addToTop(toolbar.component) } else { toolbar.setOrientation(SwingConstants.VERTICAL) centerPanel.border = createBorder(JBColor.border(), SideBorder.LEFT) addToLeft(toolbar.component) } } private class MyChangesListView(project: Project) : ChangesListView(project, false) { override fun getHoverIcon(node: ChangesBrowserNode<*>): HoverIcon? { return ChangesViewNodeAction.EP_NAME.computeSafeIfAny(project) { it.createNodeHoverIcon(node) } } } }
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ChangesViewPanel.kt
802254134
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtParameter // OPTIONS: usages data class A(val <caret>a: Int, val b: Int) fun takeExtFun(p: A.() -> Unit) { } fun takeFun1(p: (A) -> Unit) { } fun takeFun2(p: ((A?, Int) -> Unit)?) { } fun takeFun3(p: (List<A>) -> Unit) { } fun takeFuns(p: MutableList<(A) -> Unit>) { p[0] = { val (x, y) = it } } fun <T> x(p1: T, p2: (T) -> Unit){} fun foo(p: A) { takeExtFun { val (x, y) = this } takeFun1 { val (x, y) = it } takeFun2 { a, n -> val (x, y) = a!! } takeFun3 { val (x, y) = it[0] } x(p) { val (x, y) = it } x(p, fun (p) { val (x, y) = p }) } var Any.v: (A) -> Unit get() = TODO() set(value) = TODO() fun f() { "".v = { val (x, y ) = it } } // FIR_IGNORE
plugins/kotlin/idea/tests/testData/findUsages/kotlin/conventions/components/lambdas.0.kt
285512602
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package openal.templates import org.lwjgl.generator.* import openal.* val AL_SOFT_UHJ = "SOFTUHJ".nativeClassAL("SOFT_UHJ") { documentation = """ Native bindings to the $specLinkOpenALSoft extension. This extension adds support for UHJ channel formats and a Super Stereo (a.k.a. Stereo Enhance) processor. UHJ is a method of encoding surround sound from a first-order B-Format signal into a stereo-compatible signal. Such signals can be played as normal stereo (with more stable and wider stereo imaging than pan-pot mixing) or decoded back to surround sound, which makes it a decent choice where 3+ channel surround sound isn't available or desirable. When decoded, a UHJ signal behaves like B-Format, which allows it to be rotated through AL_EXT_BFORMAT's source orientation property as with B-Format formats. The standard equation[1] for decoding UHJ to B-Format is: ${codeBlock(""" S = Left + Right D = Left - Right W = 0.981532*S + 0.197484*j(0.828331*D + 0.767820*T) X = 0.418496*S - j(0.828331*D + 0.767820*T) Y = 0.795968*D - 0.676392*T + j(0.186633*S) Z = 1.023332*Q""")} where {@code j} is a wide-band +90 degree phase shift. 2-channel UHJ excludes the T and Q input channels, and 3-channel excludes the Q input channel. Be aware that the resulting W, X, Y, and Z signals are 3dB louder than their FuMa counterparts, and the implementation should account for that to properly balance it against other sounds. An alternative equation for decoding 2-channel-only UHJ is: ${codeBlock(""" S = Left + Right D = Left - Right W = 0.981532*S + j(0.163582*D) X = 0.418496*S - j(0.828331*D) Y = 0.762956*D + j(0.384230*S)""")} Which equation to use depends on the implementation and user preferences. It's relevant to note that the standard decoding equation is reversible with the encoding equation, meaning decoding UHJ to B-Format with the standard equation and then encoding B-Format to UHJ results in the original UHJ signal, even for 2-channel. The alternative 2-channel decoding equation does not result in the original UHJ signal when re- encoded. One additional note for decoding 2-channel UHJ is the resulting B-Format signal should pass through alternate shelf filters for frequency-dependent processing. For the standard equation, suitable shelf filters are given as: ${codeBlock(""" W: LF = 0.661, HF = 1.000 X/Y: LF = 1.293, HF = 1.000""")} And for the alternative equation, suitable shelf filters are given as: ${codeBlock(""" W: LF = 0.646, HF = 1.000 X/Y: LF = 1.263, HF = 1.000""")} 3- and 4-channel UHJ should use the normal shelf filters for B-Format. Super Stereo (occasionally called Stereo Enhance) is a technique for processing a plain (non-UHJ) stereo signal to derive a B-Format signal. It's backed by the same functionality as UHJ decoding, making it an easy addition on top of UHJ support. Super Stereo has a variable width control, allowing the stereo soundfield to "wrap around" the listener while maintaining a stable center image (a more naive virtual speaker approach would cause the center image to collapse as the soundfield widens). Since this derives a B-Format signal like UHJ, it also allows such sources to be rotated through the source orientation property. There are various forms of Super Stereo, with varying equations, but a good suggested option is: ${codeBlock(""" S = Left + Right D = Left - Right W = 0.6098637*S - j(0.6896511*w*D) X = 0.8624776*S + j(0.7626955*w*D) Y = 1.6822415*w*D - j(0.2156194*S)""".trimIndent())} where {@code w} is a variable width factor, in the range {@code [0...0.7]}. As with UHJ, the resulting W, X, Y, and Z signals are 3dB louder than their FuMa counterparts. The normal shelf filters for playing B-Format should apply. """ IntConstant( "Accepted by the {@code format} parameter of #BufferData().", "FORMAT_UHJ2CHN8_SOFT"..0x19A2, "FORMAT_UHJ2CHN16_SOFT"..0x19A3, "FORMAT_UHJ2CHN_FLOAT32_SOFT"..0x19A4, "FORMAT_UHJ3CHN8_SOFT"..0x19A5, "FORMAT_UHJ3CHN16_SOFT"..0x19A6, "FORMAT_UHJ3CHN_FLOAT32_SOFT"..0x19A7, "FORMAT_UHJ4CHN8_SOFT"..0x19A8, "FORMAT_UHJ4CHN16_SOFT"..0x19A9, "FORMAT_UHJ4CHN_FLOAT32_SOFT"..0x19AA ) IntConstant( "Accepted by the {@code param} parameter of #Sourcei(), #Sourceiv(), #GetSourcei(), and #GetSourceiv().", "STEREO_MODE_SOFT"..0x19B0 ) IntConstant( "Accepted by the {@code param} parameter of #Sourcef(), #Sourcefv(), #GetSourcef(), and #GetSourcefv().", "SUPER_STEREO_WIDTH_SOFT"..0x19B1 ) IntConstant( "Accepted by the {@code value} parameter of #Sourcei() and #Sourceiv() for #STEREO_MODE_SOFT.", "NORMAL_SOFT"..0x0000, "SUPER_STEREO_SOFT"..0x0001 ) }
modules/lwjgl/openal/src/templates/kotlin/openal/templates/AL_SOFT_UHJ.kt
4024832655
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.ui.html import com.intellij.diagnostic.runActivity import com.intellij.ide.ui.LafManager import com.intellij.ide.ui.LafManagerListener import com.intellij.openapi.editor.colors.EditorColorsListener import com.intellij.openapi.editor.colors.EditorColorsScheme import org.jetbrains.annotations.ApiStatus.Internal import javax.swing.text.html.HTMLEditorKit import javax.swing.text.html.StyleSheet /** * Holds a reference to global CSS style sheet that should be used by [HTMLEditorKit] to properly render everything * with respect to Look-and-Feel * * Based on a default swing stylesheet at javax/swing/text/html/default.css */ @Internal object GlobalStyleSheetHolder { private val globalStyleSheet = StyleSheet() private var swingStyleSheetHandled = false private var currentLafStyleSheet: StyleSheet? = null /** * Returns a global style sheet that is dynamically updated when LAF changes */ fun getGlobalStyleSheet(): StyleSheet { val result = StyleSheet() // return a linked sheet to avoid mutation of a global variable result.addStyleSheet(globalStyleSheet) return result } /** * Populate global stylesheet with LAF-based overrides */ internal fun updateGlobalStyleSheet() { runActivity("global styleSheet updating") { if (!swingStyleSheetHandled) { // get the default JRE CSS and ... val kit = HTMLEditorKit() val defaultSheet = kit.styleSheet globalStyleSheet.addStyleSheet(defaultSheet) // ... set a new default sheet kit.styleSheet = getGlobalStyleSheet() swingStyleSheetHandled = true } val currentSheet = currentLafStyleSheet if (currentSheet != null) { globalStyleSheet.removeStyleSheet(currentSheet) } val newStyle = StyleSheet() newStyle.addRule(LafCssProvider.getCssForCurrentLaf()) newStyle.addRule(LafCssProvider.getCssForCurrentEditorScheme()) currentLafStyleSheet = newStyle globalStyleSheet.addStyleSheet(newStyle) } } internal class UpdateListener : EditorColorsListener, LafManagerListener { override fun lookAndFeelChanged(source: LafManager) { updateGlobalStyleSheet() } override fun globalSchemeChange(scheme: EditorColorsScheme?) { updateGlobalStyleSheet() } } }
platform/platform-impl/src/com/intellij/ide/ui/html/GlobalStyleSheetHolder.kt
583460561
package com.ninjahoahong.unstoppable import android.support.v4.app.Fragment import com.ninjahoahong.unstoppable.utils.BaseKey import com.ninjahoahong.unstoppable.utils.requireArguments open class BaseFragment : Fragment() { fun <T : BaseKey> getKey(): T = requireArguments.getParcelable<T>("KEY") }
app/src/main/java/com/ninjahoahong/unstoppable/BaseFragment.kt
3337484982
/* * The MIT License (MIT) * * Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved. * Copyright (c) [2016] [ <ether.camp> ] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package org.ethereum.sync /** * @author Mikhail Kalinin * * * @since 14.07.2015 */ enum class PeerState { // Common IDLE, HEADER_RETRIEVING, BLOCK_RETRIEVING, NODE_RETRIEVING, RECEIPT_RETRIEVING, // Peer DONE_HASH_RETRIEVING }
free-ethereum-core/src/main/java/org/ethereum/sync/PeerState.kt
3172561947
package tinderswipe.swipe.mindorks.demo import android.content.Context import android.content.res.Resources import android.graphics.Point import android.os.Build import android.util.DisplayMetrics import android.util.Log import android.view.WindowManager import com.google.gson.GsonBuilder import org.json.JSONArray import java.io.IOException import java.nio.charset.Charset object Utils { private val TAG = "Utils" fun loadProfiles(context: Context): List<Profile> { try { val builder = GsonBuilder() val gson = builder.create() val array = JSONArray(loadJSONFromAsset(context, "profiles.json")) val profileList = ArrayList<Profile>() for (i in 0 until array.length()) { val profile = gson.fromJson(array.getString(i), Profile::class.java) profileList.add(profile) } return profileList } catch (e: Exception) { e.printStackTrace() return ArrayList() } } private fun loadJSONFromAsset(context: Context, jsonFileName: String): String { try { val manager = context.assets Log.d(TAG, "path $jsonFileName") val inputStream = manager.open(jsonFileName) val size = inputStream!!.available() val buffer = ByteArray(size) inputStream.read(buffer) inputStream.close() return String(buffer, Charset.forName("UTF-8")) } catch (ex: IOException) { ex.printStackTrace() return "{}"; } } fun getDisplaySize(windowManager: WindowManager): Point { try { if (Build.VERSION.SDK_INT > 16) { val display = windowManager.defaultDisplay val displayMetrics = DisplayMetrics() display.getMetrics(displayMetrics) return Point(displayMetrics.widthPixels, displayMetrics.heightPixels) } else { return Point(0, 0) } } catch (e: Exception) { e.printStackTrace() return Point(0, 0) } } fun dpToPx(dp: Int): Int { return (dp * Resources.getSystem().displayMetrics.density).toInt() } }
tinder-swipe-kotlin/app/src/main/java/tinderswipe/swipe/mindorks/demo/Utils.kt
4241181033
package org.jetbrains.tools.model.updater.impl data class MavenId(val groupId: String, val artifactId: String, val version: String = "") { val coordinates: String = if (version == "") "$groupId:$artifactId" else "$groupId:$artifactId:$version" companion object { fun fromCoordinates(coordinates: String): MavenId { val (group, artifact, version) = coordinates.split(":").also { check(it.size == 3) { "mavenCoordinates ($coordinates) are expected to two semicolons" } } return MavenId(group, artifact, version) } } } fun MavenId.toJarPath(): String = "${groupId.replace(".", "/")}/$artifactId/$version/$artifactId-$version.jar" fun MavenId.toSourcesJarPath(): String = "${groupId.replace(".", "/")}/$artifactId/$version/$artifactId-$version-sources.jar"
plugins/kotlin/util/project-model-updater/src/org/jetbrains/tools/model/updater/impl/MavenId.kt
3509839943
/* * The MIT License (MIT) * * Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved. * Copyright (c) [2016] [ <ether.camp> ] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package org.ethereum.vm.program.listener interface ProgramListenerAware { fun setProgramListener(listener: ProgramListener) }
free-ethereum-core/src/main/java/org/ethereum/vm/program/listener/ProgramListenerAware.kt
1947547892
package com.intellij.ui.charts import java.awt.BasicStroke import java.awt.BasicStroke.CAP_BUTT import java.awt.BasicStroke.JOIN_ROUND import java.awt.Graphics2D import java.awt.Rectangle import java.awt.geom.Area import java.awt.geom.Path2D import java.awt.geom.Point2D import java.util.* import kotlin.NoSuchElementException import kotlin.math.hypot import kotlin.math.min /** * Simple Line Chart. * * Has options: * <ul> * <li><b>stepped</b> — can be set to LineStepped.(NONE|BEFORE|AFTER) * <li><b>stacked</b> — if <code>true</code> area under chart's line subtracts from result graphic (every next chart cannot paint on this area anymore) * <li><b>stroke</b> — set custom stroke for the line * </ul> */ abstract class LineDataset<X: Number, Y: Number>: Dataset<Coordinates<X, Y>>() { var stepped: LineStepped = LineStepped.NONE var stacked: Boolean = false var stroke = BasicStroke(1.5f, CAP_BUTT, JOIN_ROUND) var smooth: Boolean = false var modificationFirst: Boolean = false set(value) { field = value data = (if (value) LinkedList() else mutableListOf<Coordinates<X, Y>>()).apply { data.forEach { [email protected](it) } } } fun find(x: X): Y? = data.find { it.x == x }?.y companion object { @JvmStatic fun <T: Number> of(vararg values: T) = CategoryLineDataset<T>().apply { addAll(values.mapIndexed(::Coordinates).toList()) } @JvmStatic fun <X: Number, Y: Number> of(xs: Array<X>, ys: Array<Y>) = XYLineDataset<X, Y>().apply { addAll(Array(min(xs.size, ys.size)) { i -> Coordinates(xs[i], ys[i]) }.toList()) } @JvmStatic fun <X: Number, Y: Number> of(vararg points: Coordinates<X, Y>) = XYLineDataset<X, Y>().apply { addAll(points.toList()) } } } /** * Type of stepped line: * * * NONE — line continuously connects every line * * BEFORE — line changes value before connection to another point * * AFTER — line changes value after connection to another point */ enum class LineStepped { NONE, BEFORE, AFTER } /** * Default 2-dimensional dataset for function like f(x) = y. */ open class XYLineDataset<X: Number, Y: Number> : LineDataset<X, Y>() { } /** * Default category dataset, that is specific type of XYLineDataset, when x in range of (0..<value count>). */ open class CategoryLineDataset<X: Number> : LineDataset<Int, X>() { var values: Iterable<X> get() = data.map { it.y } set(value) { data = value.mapIndexed(::Coordinates) } } /** * Base chart component. * * For drawing uses GeneralPath from AWT library. * * Has options: * * * gridColor * * borderPainted — if <code>true</code> draws a border around the chart and respects margins * * ranges — grid based range, that holds all information about grid painting. Has minimal and maximum values for graphic. */ abstract class LineChart<X: Number, Y: Number, D: LineDataset<X, Y>>: GridChartWrapper<X, Y>() { var datasets: List<D> = mutableListOf() companion object { @JvmStatic fun <T: Number, D: CategoryLineDataset<T>> of(vararg values: D) = CategoryLineChart<T>().apply { datasets = mutableListOf(*values) } @JvmStatic fun <X: Number, Y: Number, D: XYLineDataset<X, Y>> of(vararg values: D) = XYLineChart<X, Y>().apply { datasets = mutableListOf(*values) } @JvmStatic fun <T: Number> of(vararg values: T) = CategoryLineChart<T>().apply { datasets = mutableListOf(LineDataset.of(*values)) } @JvmStatic fun <X: Number, Y: Number> of(vararg points: Coordinates<X, Y>) = XYLineChart<X, Y>().apply { datasets = mutableListOf(LineDataset.of(*points)) } } var borderPainted: Boolean = false override val ranges = Grid<X, Y>() override fun paintComponent(g: Graphics2D) { val gridWidth = width - (margins.left + margins.right) val gridHeight = height - (margins.top + margins.bottom) if (borderPainted) { g.color = gridColor g.drawRect(margins.left, margins.top, gridWidth, gridHeight) } val xy = findMinMax() if (xy.isInitialized) { val grid = g.create(margins.left, margins.top, gridWidth, gridHeight) as Graphics2D paintGrid(grid, g, xy) datasets.forEach { it.paintDataset(grid, xy) } grid.dispose() } } override fun findMinMax() = if (ranges.isInitialized) ranges else ranges * (ranges + MinMax()).apply { datasets.forEach { it.data.forEach(::process) } } private fun D.paintDataset(g: Graphics2D, xy: MinMax<X, Y>) { val path = Path2D.Double() lateinit var first: Point2D val bounds = g.clipBounds g.paint = lineColor g.stroke = stroke // set small array to store 4 points of values val useSplines = smooth && stepped == LineStepped.NONE val neighborhood = DoubleArray(8) { Double.NaN } data.forEachIndexed { i, (x, y) -> val px = findX(xy, x) val py = findY(xy, y) neighborhood.shiftLeftByTwo(px, py) if (i == 0) { first = Point2D.Double(px, py) path.moveTo(px, py) } else { if (!useSplines) { when (stepped) { LineStepped.AFTER -> path.lineTo(neighborhood[4], py) LineStepped.BEFORE -> path.lineTo(px, neighborhood[5]) } path.lineTo(px, py) } else if (i > 1) { path.curveTo(neighborhood) } } } // last step to draw tail of graphic, when spline is used if (useSplines) { neighborhood.shiftLeftByTwo(Double.NaN, Double.NaN) path.curveTo(neighborhood) } g.paint = lineColor g.stroke = stroke g.draw(path) // added some points path.currentPoint?.let { last -> path.lineTo(last.x, bounds.height + 1.0) path.lineTo(first.x, bounds.height + 1.0) path.closePath() } fillColor?.let { g.paint = it g.fill(path) } if (stacked) { // fix stroke cutting val area = Area(g.clip) area.subtract(Area(path)) g.clip = area } } fun findLocation(xy: MinMax<X, Y>, coordinates: Coordinates<X, Y>) = Point2D.Double( findX(xy, coordinates.x) + margins.left, findY(xy, coordinates.y) + margins.top ) open fun add(x: X, y: Y) { datasets.firstOrNull()?.add(x to y) } fun getDataset() = datasets.first() @JvmName("getDataset") operator fun get(label: String): LineDataset<X, Y> = datasets.find { it.label == label } ?: throw NoSuchElementException("Cannot find dataset with label $datasets") fun clear() { datasets.forEach { (it.data as MutableList).clear() } } } open class CategoryLineChart<X: Number> : LineChart<Int, X, CategoryLineDataset<X>>() open class XYLineChart<X: Number, Y: Number> : LineChart<X, Y, XYLineDataset<X, Y>>() // HELPERS /** * Calculates control points for bezier function and curves line. * Requires an array of 4 points in format (x0, y0, x1, y1, x2, y2, x3, y3), * where (x2, y2) — is target point, x1, y1 — point, that can be acquired by Path2D.currentPoint. * (x0, y0) — point before current and (x3, y3) —point after. * * @param neighbour array keeps 4 points (size 8) * * Using Monotone Cubic Splines: algorithm https://en.wikipedia.org/wiki/Monotone_cubic_interpolation */ private fun Path2D.Double.curveTo(neighbour: DoubleArray) { assert(neighbour.size == 8) { "Array must contain 4 points in format (x0, y0, x1, y1, x2, y2, x3, y3)" } val x0 = neighbour[0] val y0 = neighbour[1] val x1 = neighbour[2] val y1 = neighbour[3] val x2 = neighbour[4] val y2 = neighbour[5] val x3 = neighbour[6] val y3 = neighbour[7] val slope0 = ((y1 - y0) / (x1 - x0)).orZero() val slope1 = ((y2 - y1) / (x2 - x1)).orZero() val slope2 = ((y3 - y2) / (x3 - x2)).orZero() var tan1 = if (slope0 * slope1 <= 0) 0.0 else (slope0 + slope1) / 2 var tan2 = if (slope1 * slope2 <= 0) 0.0 else (slope1 + slope2) / 2 if (slope1 == 0.0) { tan1 = 0.0 tan2 = 0.0 } else { val a = tan1 / slope1 val b = tan2 / slope1 val h = hypot(a, b) if (h > 3.0) { val t = 3.0 / h tan1 = t * a * slope1 tan2 = t * b * slope1 } } val delta2 = (x2 - x1) / 3 var cx0 = x1 + delta2 var cy0 = y1 + delta2 * tan1 if (x0.isNaN() || y0.isNaN()) { cx0 = x1 cy0 = y1 } val delta0 = (x2 - x1) / 3 var cx1 = x2 - delta0 var cy1 = y2 - delta0 * tan2 if (x3.isNaN() || y3.isNaN()) { cx1 = x2 cy1 = y2 } curveTo(cx0, cy0, cx1, cy1, x2, y2) } private fun Double.orZero() = if (this.isNaN()) 0.0 else this private fun DoubleArray.shiftLeftByTwo(first: Double, second: Double) { for (j in 2 until size) { this[j - 2] = this[j] } this[size - 2] = first this[size - 1] = second }
platform/platform-impl/src/com/intellij/ui/charts/LineChart.kt
2953780035
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package vgrechka.phizdetsidea.phizdets.console import com.intellij.execution.impl.ConsoleViewUtil import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.actionSystem.EditorActionHandler import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.richcopy.settings.RichCopySettings import com.intellij.openapi.ide.CopyPasteManager import com.intellij.openapi.util.Key import com.intellij.openapi.util.Ref import com.intellij.openapi.util.TextRange import java.awt.datatransfer.StringSelection /** * Created by Yuli Fiterman on 9/17/2016. */ class PyConsoleCopyHandler(val originalHandler: EditorActionHandler) : EditorActionHandler() { override fun doExecute(editor: Editor, caret: Caret?, dataContext: DataContext) { if (!RichCopySettings.getInstance().isEnabled) { return originalHandler.execute(editor, null, dataContext); } if (true != editor.getUserData(ConsoleViewUtil.EDITOR_IS_CONSOLE_HISTORY_VIEW)) { return originalHandler.execute(editor, null, dataContext); } doCopyWithoutPrompt(editor as EditorEx); } private fun doCopyWithoutPrompt(editor: EditorEx) { val start = editor.selectionModel.selectionStart val end = editor.selectionModel.selectionEnd val document = editor.document val beginLine = document.getLineNumber(start) val endLine = document.getLineNumber(end) val sb = StringBuilder() for (i in beginLine..endLine) { var lineStart = document.getLineStartOffset(i) val r = Ref.create<Int>() editor.markupModel.processRangeHighlightersOverlappingWith(lineStart, lineStart) { val length = it.getUserData(PROMPT_LENGTH_MARKER) ?: return@processRangeHighlightersOverlappingWith true r.set(length) false } if (!r.isNull) { lineStart += r.get() } val rangeStart = Math.max(lineStart, start) val rangeEnd = Math.min(document.getLineEndOffset(i), end) if (rangeStart < rangeEnd) { sb.append(document.getText(TextRange(rangeStart, rangeEnd))) sb.append("\n") } } if (!sb.isEmpty()) { CopyPasteManager.getInstance().setContents(StringSelection(sb.toString())) } } companion object { @JvmField val PROMPT_LENGTH_MARKER: Key<Int?> = Key.create<Int>("PROMPT_LENGTH_MARKER"); } }
phizdets/phizdets-idea/src/vgrechka/phizdetsidea/phizdets/console/PyConsoleCopyHandler.kt
2840447763
package com.intellij.refactoring.detector.semantic.diff import com.intellij.diff.contents.DiffContent import com.intellij.diff.requests.SimpleDiffRequest import com.intellij.diff.util.DiffUserDataKeysEx import com.intellij.openapi.util.NlsContexts class SemanticFragmentDiffRequest(title: @NlsContexts.DialogTitle String, content1: DiffContent, content2: DiffContent, title1: @NlsContexts.Label String, title2: @NlsContexts.Label String, val closeAction: () -> Unit) : SimpleDiffRequest(title, content1, content2, title1, title2) { init { putUserData(DiffUserDataKeysEx.EDITORS_HIDE_TITLE, true) } override fun getTitle(): String = super.getTitle()!! }
plugins/refactoring-detector/src/com/intellij/refactoring/detector/semantic/diff/SemanticFragmentDiffRequest.kt
4251894398
package com.team2052.frckrawler.metric.types import android.view.View import com.google.common.base.Joiner import com.google.common.base.Strings import com.google.common.collect.Maps import com.google.gson.JsonObject import com.team2052.frckrawler.database.metric.CompiledMetricValue import com.team2052.frckrawler.database.metric.MetricValue import com.team2052.frckrawler.db.Metric import com.team2052.frckrawler.db.Robot import com.team2052.frckrawler.metric.MetricTypeEntry import com.team2052.frckrawler.metrics.view.MetricWidget import com.team2052.frckrawler.tba.JSON import com.team2052.frckrawler.util.MetricHelper import com.team2052.frckrawler.util.Tuple2 open class StringIndexMetricTypeEntry<out W : MetricWidget>(widgetType: Class<W>) : MetricTypeEntry<W>(widgetType) { override fun convertValueToString(value: JsonObject): String { val names = value.get("names").asJsonArray val values = value.get("values").asJsonArray var value = "" for (i in 0..names.size() - 1) { value += String.format("%s - %s%s" + if (i == names.size() - 1) "" else "\n", names.get(i).asString, values.get(i).asDouble, '%') } return value } override fun compileValues(robot: Robot, metric: Metric, metricData: List<MetricValue>, compileWeight: Double): JsonObject {var denominator = 0.0 val compiledValue = JsonObject() val possible_values = JSON.getAsJsonObject(metric.data).get("values").asJsonArray val compiledVal = Maps.newTreeMap<Int, Tuple2<String, Double>>() for (i in 0..possible_values.size() - 1) { compiledVal.put(i, Tuple2(possible_values.get(i).asString, 0.0)) } if (metricData.isEmpty()) { val values = JSON.getGson().toJsonTree(Tuple2.yieldValues(compiledVal.values).toTypedArray()).asJsonArray compiledValue.add("names", possible_values) compiledValue.add("values", values) return compiledValue } for (metricValue in metricData) { val result = MetricHelper.getListIndexMetricValue(metricValue) if (result.t2.isError) continue val weight = CompiledMetricValue.getCompileWeightForMatchNumber(metricValue, metricData, compileWeight) result.t1 .filter { compiledVal.containsKey(it) } .forEach { compiledVal.put(it, compiledVal[it]!!.setT2(compiledVal[it]!!.t2 + weight)) } denominator += weight } for ((key, value) in compiledVal) { compiledVal.put(key, value.setT2(Math.round(value.t2 / denominator * 100 * 100.0) / 100.0)) } val values = JSON.getGson().toJsonTree(Tuple2.yieldValues(compiledVal.values).toTypedArray()).asJsonArray compiledValue.add("names", possible_values) compiledValue.add("values", values) return compiledValue } override fun addInfo(metric: Metric, info: MutableMap<String, String>) { val data = JSON.getAsJsonObject(metric.data) val values = Joiner.on(", ").join(data.get("values").asJsonArray) info.put("Comma Separated List", if (Strings.isNullOrEmpty(values)) "No Values" else values) } override fun buildMetric(name: String, min: Int?, max: Int?, inc: Int?, commaList: List<String>?): MetricHelper.MetricFactory { val metricFactory = MetricHelper.MetricFactory(name) metricFactory.setMetricType(this.typeId) metricFactory.setDataListIndexValue(commaList) return metricFactory } override fun commaListVisibility(): Int = View.VISIBLE }
app/src/main/kotlin/com/team2052/frckrawler/metric/types/StringIndexMetricTypeEntry.kt
926799832
package viper.sample.dagger import dagger.Component import dagger.Subcomponent import viper.sample.model.interactors.SampleInteractors import javax.inject.Singleton /** * Created by Nick Cipollo on 1/3/17. */ @Subcomponent @Singleton interface InteractorComponent { fun interactors() : SampleInteractors }
sample/src/main/kotlin/viper/sample/dagger/InteractorComponent.kt
1494503514
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.ui.sessiondetail import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.google.samples.apps.iosched.model.SessionId import com.google.samples.apps.iosched.model.TestDataRepository import com.google.samples.apps.iosched.shared.data.feedback.FeedbackEndpoint import com.google.samples.apps.iosched.shared.data.session.DefaultSessionRepository import com.google.samples.apps.iosched.shared.data.userevent.DefaultSessionAndUserEventRepository import com.google.samples.apps.iosched.shared.data.userevent.UserEventDataSource import com.google.samples.apps.iosched.shared.domain.sessions.LoadUserSessionUseCase import com.google.samples.apps.iosched.shared.domain.users.FeedbackUseCase import com.google.samples.apps.iosched.shared.result.Result import com.google.samples.apps.iosched.shared.result.data import com.google.samples.apps.iosched.shared.util.NetworkUtils import com.google.samples.apps.iosched.test.data.MainCoroutineRule import com.google.samples.apps.iosched.test.data.TestData import com.google.samples.apps.iosched.test.util.fakes.FakeSignInViewModelDelegate import com.google.samples.apps.iosched.test.util.time.FixedTimeExecutorRule import com.google.samples.apps.iosched.ui.schedule.TestUserEventDataSource import com.google.samples.apps.iosched.ui.signin.SignInViewModelDelegate import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Rule import org.junit.Test /** * Unit tests for the [SessionFeedbackViewModel]. */ class SessionFeedbackViewModelTest { // Executes tasks in the Architecture Components in the same thread @get:Rule var instantTaskExecutorRule = InstantTaskExecutorRule() // Allows explicit setting of "now" @get:Rule var fixedTimeExecutorRule = FixedTimeExecutorRule() // Overrides Dispatchers.Main used in Coroutines @get:Rule var coroutineRule = MainCoroutineRule() private lateinit var viewModel: SessionFeedbackViewModel private val testSession = TestData.session0 private lateinit var mockNetworkUtils: NetworkUtils @Before fun setup() { mockNetworkUtils = mock { on { hasNetworkConnection() }.doReturn(true) } viewModel = createSessionFeedbackViewModel() viewModel.setSessionId(testSession.id) } @Test fun title() = runTest { assertEquals( testSession.title, viewModel.userSession.first().data?.session?.title ) } @Test fun questions() { // TODO: pointless test, left here for when these are dynamic. val questions = viewModel.questions assertEquals(4, questions.size) assertEquals(0, questions[0].currentRating) assertEquals(0, questions[1].currentRating) assertEquals(0, questions[2].currentRating) assertEquals(0, questions[3].currentRating) } private fun createSessionFeedbackViewModel( signInViewModelPlugin: SignInViewModelDelegate = FakeSignInViewModelDelegate(), loadUserSessionUseCase: LoadUserSessionUseCase = createTestLoadUserSessionUseCase(), feedbackUseCase: FeedbackUseCase = createTestFeedbackUseCase() ): SessionFeedbackViewModel { return SessionFeedbackViewModel( signInViewModelDelegate = signInViewModelPlugin, loadUserSessionUseCase = loadUserSessionUseCase, feedbackUseCase = feedbackUseCase ) } private fun createTestLoadUserSessionUseCase( userEventDataSource: UserEventDataSource = TestUserEventDataSource() ): LoadUserSessionUseCase { return LoadUserSessionUseCase( DefaultSessionAndUserEventRepository( userEventDataSource, DefaultSessionRepository(TestDataRepository) ), coroutineRule.testDispatcher ) } private fun createTestFeedbackUseCase( userEventDataSource: UserEventDataSource = TestUserEventDataSource() ): FeedbackUseCase { return FeedbackUseCase( object : FeedbackEndpoint { override suspend fun sendFeedback( sessionId: SessionId, responses: Map<String, Int> ): Result<Unit> { return Result.Success(Unit) } }, DefaultSessionAndUserEventRepository( userEventDataSource, DefaultSessionRepository(TestDataRepository) ), coroutineRule.testDispatcher ) } }
mobile/src/test/java/com/google/samples/apps/iosched/ui/sessiondetail/SessionFeedbackViewModelTest.kt
2648266179
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.navigation /** * A marker interface for [NavDestination] subclasses that float above the view of other * destinations (i.e. [androidx.navigation.fragment.DialogFragmentNavigator.Destination]). * * * Destinations that implement this interface will automatically be popped off the back * stack when you navigate to a new destination. * * * [androidx.navigation.NavController.OnDestinationChangedListener] instances can also * customize their behavior based on whether the destination is a FloatingWindow. */ public interface FloatingWindow
navigation/navigation-common/src/main/java/androidx/navigation/FloatingWindow.kt
3606925083
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.metrics.performance.test import android.content.Context import android.graphics.Canvas import android.os.Build import android.util.AttributeSet import android.view.View import androidx.annotation.RequiresApi /** * This custom view is used to inject an artificial, random delay during drawing, to simulate * jank on the UI thread. */ public class MyCustomView : View { @RequiresApi(Build.VERSION_CODES.LOLLIPOP) public constructor( context: Context?, attrs: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0 ) : super(context, attrs, defStyleAttr, defStyleRes) override fun onDraw(canvas: Canvas) { /** * Inject random delay to cause jank in the app. * For any given item, there should be a 30% chance of jank (>32ms), and a 2% chance of * extreme jank (>500ms). * Regular jank will be between 32 and 82ms, extreme from 500-700ms. */ val probability = Math.random() if (probability > .7) { val delay: Long delay = if (probability > .98) { 500 + (Math.random() * 200).toLong() } else { 32 + (Math.random() * 50).toLong() } try { Thread.sleep(delay) } catch (e: Exception) { } } super.onDraw(canvas) } }
metrics/metrics-performance/src/androidTest/java/androidx/metrics/performance/test/MyCustomView.kt
538989973
package data.autoswipe import domain.recommendation.DomainRecommendationUser internal class ProcessRecommendationActionFactoryWrapper( val delegate: (DomainRecommendationUser) -> ProcessRecommendationAction)
data/src/main/kotlin/data/autoswipe/ProcessRecommendationActionFactoryWrapper.kt
3944776053
package de.droidcon.berlin2018.schedule.backend import de.droidcon.berlin2018.model.Location import de.droidcon.berlin2018.model.Session import de.droidcon.berlin2018.model.Speaker import de.droidcon.berlin2018.schedule.backend.data2018.SessionItem import de.droidcon.berlin2018.schedule.backend.data2018.SessionResult import de.droidcon.berlin2018.schedule.backend.data2018.SpeakerItem import de.droidcon.berlin2018.schedule.backend.data2018.mapping.SimpleLocation import de.droidcon.berlin2018.schedule.backend.data2018.mapping.SimpleSession import de.droidcon.berlin2018.schedule.backend.data2018.mapping.SimpleSpeaker import io.reactivex.Single import io.reactivex.functions.BiFunction /** * [BackendScheduleAdapter] for droidcon Berlin backend * * @author Hannes Dorfmann */ public class DroidconBerlinBackendScheduleAdapter2018( private val backend: DroidconBerlinBackend2018 ) : BackendScheduleAdapter { override fun getSpeakers(): Single<BackendScheduleResponse<Speaker>> = backend.getSpeakers().map { speakerResult -> val list: List<Speaker> = speakerResult.items.map { it.toSpeaker() } BackendScheduleResponse.dataChanged(list) } override fun getLocations(): Single<BackendScheduleResponse<Location>> = backend.getSession().map { result: SessionResult? -> if (result == null) BackendScheduleResponse.dataChanged(emptyList()) else { val locations: List<Location> = result.items.map { SimpleLocation.create( it.roomName, it.roomName ) } // TODO roomId is fucked up on backend .distinct() .toList() BackendScheduleResponse.dataChanged(locations) } } override fun getSessions(): Single<BackendScheduleResponse<Session>> { val sessionsResult = backend.getSession() val spakersMap = backend.getSpeakers().map { it.items.map { it.toSpeaker() }.associateBy { it.id() } } val sessions: Single<List<Session>> = Single.zip(sessionsResult, spakersMap, BiFunction { sessions, speakersMap -> sessions.items.map { it.toSession(speakersMap) } }) return sessions.map { BackendScheduleResponse.dataChanged(it) } } private fun SpeakerItem.toSpeaker(): Speaker = SimpleSpeaker.create( id = id, name = "$firstname $lastname", company = company, info = description, jobTitle = position, profilePic = imageUrl, link1 = if (links != null && links.size >= 1) links[0].url else null, link2 = if (links != null && links.size >= 2) links[1].url else null, link3 = if (links != null && links.size >= 3) links[2].url else null ) private fun SessionItem.toSession(speakers: Map<String, Speaker>): Session { return SimpleSession.create( id = id, title = title, description = description, favorite = false, locationId = roomName, // TODO roomId is fucked up on backend site. locationName = roomName, speakers = when (id) { "3858" -> listOf(speakers["237"]!!, speakers["1135"]!!)// MVI "3785" -> listOf(speakers["1144"]!!, speakers["347"]!!)// Code sharing is caring "3949" -> listOf( speakers["1217"]!!, speakers["276"]!! )// Everything is better with(out) Bluetooth "3859" -> listOf(speakers["127"]!!, speakers["304"]!!)// The build side of an app "5302" -> listOf( speakers["1345"]!!, speakers["1347"]!!, speakers["1348"]!!, speakers["1349"]!! ) // Manage android without an app "5309" -> listOf( speakers["1345"]!!, speakers["1347"]!!, speakers["1348"]!!, speakers["1349"]!! ) // Manage android api hands on "5307" -> listOf( speakers["1354"]!!, speakers["1355"]!! ) // Sharing a success story else -> listOf(speakers[speakerIds]!!) }, tags = category, startTime = startDate, endTime = endDate ) } }
businesslogic/schedule/src/main/java/de/droidcon/berlin2018/schedule/backend/DroidconBerlinBackendScheduleAdapter2018.kt
1845338248
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.core.text import androidx.test.filters.SmallTest import org.junit.Assert.assertEquals import org.junit.Test @SmallTest class StringTest { @Test fun htmlEncode() { assertEquals("&lt;&gt; &amp; &quot; &#39;", """<> & " '""".htmlEncode()) } }
core/core-ktx/src/androidTest/java/androidx/core/text/StringTest.kt
2560398817
package foo actual class <!LINE_MARKER("descr='Has expects in top module'")!>A<!>
plugins/kotlin/idea/tests/testData/multiplatform/duplicateActualsOneWeaklyIncompatible/middle/middle.kt
2641367850
package cn.mijack.imagedrive.entity /** * @author admin * @date 2017/8/26 */ data class Attribute<V>(var name: String, var value: V)
app/src/main/java/cn/mijack/imagedrive/entity/Attribute.kt
1904796608
// IGNORE_FIR // WITH_STDLIB class A fun some() { A().toString(<caret>) } //Text: (<no parameters>), Disabled: false, Strikeout: false, Green: true
plugins/kotlin/idea/tests/testData/parameterInfo/functionCall/NoShadowedDeclarations.kt
1996774194
// "Cast to 'Iterable<Char>'" "true" fun append(x: Any) {} fun append(xs: Collection<*>) {} fun invoke() { append('a'..'c'<caret>) }
plugins/kotlin/idea/tests/testData/quickfix/castDueToProgressionResolveChange/functionArgumentAsChar.kt
4138483578
package io.quartz.tree.ast import io.quartz.tree.util.* sealed class DeclT : Locatable { data class Trait( override val location: Location?, val name: Name, val foralls: Set<Name>, val constraints: List<ConstraintT>, val members: List<Member> ) : DeclT() { data class Member( val name: Name, val location: Location, val schemeT: SchemeT ) } data class Value( override val location: Location?, val name: Name, val scheme: SchemeT?, val expr: ExprT ) : DeclT() data class Instance( override val location: Location?, val name: Name?, val instance: Name, val scheme: SchemeT, val impls: List<Value> ) : DeclT() }
compiler/src/main/kotlin/io/quartz/tree/ast/DeclT.kt
2872530166
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.idea.maven.project class MavenProjectChangesBuilder : MavenProjectChanges() { private var hasPackagingChanges = false private var hasOutputChanges = false private var hasSourceChanges = false private var hasDependencyChanges = false private var hasPluginsChanges = false private var hasPropertyChanges = false override fun hasPackagingChanges(): Boolean { return hasPackagingChanges } fun setHasPackagingChanges(value: Boolean) { hasPackagingChanges = value packaging = value // backward compatibility } override fun hasOutputChanges(): Boolean { return hasOutputChanges } fun setHasOutputChanges(value: Boolean) { hasOutputChanges = value output = value // backward compatibility } override fun hasSourceChanges(): Boolean { return hasSourceChanges } fun setHasSourceChanges(value: Boolean) { hasSourceChanges = value sources = value // backward compatibility } override fun hasDependencyChanges(): Boolean { return hasDependencyChanges } fun setHasDependencyChanges(value: Boolean) { hasDependencyChanges = value dependencies = value // backward compatibility } override fun hasPluginsChanges(): Boolean { return hasPluginsChanges } fun setHasPluginChanges(value: Boolean) { hasPluginsChanges = value plugins = value // backward compatibility } override fun hasPropertyChanges(): Boolean { return hasPropertyChanges } fun setHasPropertyChanges(value: Boolean) { hasPropertyChanges = value properties = value // backward compatibility } fun setAllChanges(value: Boolean) { setHasPackagingChanges(value) setHasOutputChanges(value) setHasSourceChanges(value) setHasDependencyChanges(value) setHasPluginChanges(value) setHasPropertyChanges(value) } companion object { @JvmStatic fun merged(a: MavenProjectChanges, b: MavenProjectChanges): MavenProjectChangesBuilder { val result = MavenProjectChangesBuilder() result.setHasPackagingChanges(a.hasPackagingChanges() || b.hasPackagingChanges()) result.setHasOutputChanges(a.hasOutputChanges() || b.hasOutputChanges()) result.setHasSourceChanges(a.hasSourceChanges() || b.hasSourceChanges()) result.setHasDependencyChanges(a.hasDependencyChanges() || b.hasDependencyChanges()) result.setHasPluginChanges(a.hasPluginsChanges() || b.hasPluginsChanges()) result.setHasPropertyChanges(a.hasPropertyChanges() || b.hasPropertyChanges()) return result } } }
plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectChangesBuilder.kt
1268112228
package com.example.android.inventory.database import android.arch.persistence.room.Database import android.arch.persistence.room.Room import android.arch.persistence.room.RoomDatabase import android.arch.persistence.room.TypeConverters import android.content.Context import com.example.android.inventory.model.Item import com.example.android.inventory.util.Converters @Database(entities = [(Item::class)], version = 1) @TypeConverters(Converters::class) abstract class AppDatabase : RoomDatabase() { abstract fun itemsDao(): ItemsDao companion object { private var INSTANCE: AppDatabase? = null private const val DATABASE_NAME = "items.db" fun getInstance(context: Context): AppDatabase? { if (INSTANCE == null) { INSTANCE = Room.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME).build() } return INSTANCE } } }
app/src/main/java/com/example/android/inventory/database/AppDatabase.kt
2388445452
import kotlin.random.Random val cylinder = Array(6) { false } fun rShift() { val t = cylinder[cylinder.size - 1] for (i in (0 until cylinder.size - 1).reversed()) { cylinder[i + 1] = cylinder[i] } cylinder[0] = t } fun unload() { for (i in cylinder.indices) { cylinder[i] = false } } fun load() { while (cylinder[0]) { rShift() } cylinder[0] = true rShift() } fun spin() { val lim = Random.nextInt(0, 6) + 1 for (i in 1..lim) { rShift() } } fun fire(): Boolean { val shot = cylinder[0] rShift() return shot } fun method(s: String): Int { unload() for (c in s) { when (c) { 'L' -> { load() } 'S' -> { spin() } 'F' -> { if (fire()) { return 1 } } } } return 0 } fun mString(s: String): String { val buf = StringBuilder() fun append(txt: String) { if (buf.isNotEmpty()) { buf.append(", ") } buf.append(txt) } for (c in s) { when (c) { 'L' -> { append("load") } 'S' -> { append("spin") } 'F' -> { append("fire") } } } return buf.toString() } fun test(src: String) { val tests = 100000 var sum = 0 for (t in 0..tests) { sum += method(src) } val str = mString(src) val pc = 100.0 * sum / tests println("%-40s produces %6.3f%% deaths.".format(str, pc)) } fun main() { test("LSLSFSF"); test("LSLSFF"); test("LLSFSF"); test("LLSFF"); }
Two_bullet_roulette/Kotlin/src/main/kotlin/main.kt
315195945
// 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.workspaceModel.ide.impl import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.pointers.VirtualFilePointer import com.intellij.workspaceModel.storage.impl.url.VirtualFileUrlImpl import com.intellij.workspaceModel.storage.impl.url.VirtualFileUrlManagerImpl class VirtualFileUrlBridge(id: Int, manager: VirtualFileUrlManagerImpl, initializeVirtualFileLazily: Boolean) : VirtualFileUrlImpl(id, manager), VirtualFilePointer { @Volatile private var file: VirtualFile? = null @Volatile private var timestampOfCachedFiles = -1L init { if (!initializeVirtualFileLazily) findVirtualFile() } override fun getFile() = findVirtualFile() override fun isValid() = findVirtualFile() != null override fun toString() = url override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as VirtualFileUrlBridge if (id != other.id) return false return true } override fun hashCode(): Int = id private fun findVirtualFile(): VirtualFile? { val fileManager = VirtualFileManager.getInstance() val timestamp = timestampOfCachedFiles val cachedResults = file return if (timestamp == fileManager.modificationCount) cachedResults else { file = fileManager.findFileByUrl(url) timestampOfCachedFiles = fileManager.modificationCount file } } }
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/VirtualFileUrlBridge.kt
158200552
// WITH_RUNTIME val foo = Byte.MAX_VALUE.toByte()<caret>
plugins/kotlin/idea/tests/testData/intentions/removeRedundantCallsOfConversionMethods/byte.kt
2241017269
// WITH_RUNTIME fun test(list: List<Int>) { val find: Int? = list.<caret>filter { it > 1 }.find { true } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/convertCallChainIntoSequence/termination/find.kt
2483670683
// 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. @file:JvmName("TargetEnvironmentFunctions") package com.intellij.execution.target.value import com.intellij.execution.target.HostPort import com.intellij.execution.target.TargetEnvironment import com.intellij.execution.target.TargetEnvironmentRequest import com.intellij.execution.target.TargetPlatform import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.util.io.FileUtil import java.io.File import java.io.IOException import java.nio.file.Path import java.util.function.Function import kotlin.io.path.name /** * The function that is expected to be resolved with provided * [TargetEnvironment]. * * Such functions could be used during the construction of a command line and * play the role of deferred values of, for example: * - the path to an executable; * - the working directory; * - the command-line parameters; * - the values of environment variables. */ typealias TargetEnvironmentFunction<R> = Function<TargetEnvironment, R> /** * This function is preferable to use over function literals in Kotlin * (i.e. `TargetEnvironmentFunction { value }`) and lambdas in Java * (i.e. `ignored -> value`) because it is has more explicit [toString] which * results in clear variable descriptions during debugging and better logging * abilities. */ fun <T> constant(value: T): TargetEnvironmentFunction<T> = TargetEnvironmentFunction { value } fun <T> Iterable<TargetEnvironmentFunction<T>>.joinToStringFunction(separator: CharSequence): TargetEnvironmentFunction<String> = JoinedStringTargetEnvironmentFunction(iterable = this, separator = separator) fun TargetEnvironmentRequest.getTargetEnvironmentValueForLocalPath(localPath: String): TargetEnvironmentFunction<String> { val (uploadRoot, relativePath) = getUploadRootForLocalPath(localPath) ?: throw IllegalArgumentException("Local path \"$localPath\" is not registered within uploads in the request") return TargetEnvironmentFunction { targetEnvironment -> val volume = targetEnvironment.uploadVolumes[uploadRoot] ?: throw IllegalStateException("Upload root \"$uploadRoot\" is expected to be created in the target environment") return@TargetEnvironmentFunction joinPaths(volume.targetRoot, relativePath, targetEnvironment.targetPlatform) } } fun TargetEnvironmentRequest.getUploadRootForLocalPath(localPath: String): Pair<TargetEnvironment.UploadRoot, String>? { val targetFileSeparator = targetPlatform.platform.fileSeparator return uploadVolumes.mapNotNull { uploadRoot -> getRelativePathIfAncestor(ancestor = uploadRoot.localRootPath.toString(), file = localPath)?.let { relativePath -> uploadRoot to if (File.separatorChar != targetFileSeparator) { relativePath.replace(File.separatorChar, targetFileSeparator) } else { relativePath } } }.firstOrNull() } private fun getRelativePathIfAncestor(ancestor: String, file: String): String? = if (FileUtil.isAncestor(ancestor, file, false)) { FileUtil.getRelativePath(ancestor, file, File.separatorChar) } else { null } private fun joinPaths(basePath: String, relativePath: String, targetPlatform: TargetPlatform): String { val fileSeparator = targetPlatform.platform.fileSeparator.toString() return FileUtil.toSystemIndependentName("${basePath.removeSuffix(fileSeparator)}$fileSeparator$relativePath") } fun TargetEnvironment.UploadRoot.getTargetUploadPath(): TargetEnvironmentFunction<String> = TargetEnvironmentFunction { targetEnvironment -> val uploadRoot = this@getTargetUploadPath val uploadableVolume = targetEnvironment.uploadVolumes[uploadRoot] ?: throw IllegalStateException("Upload root \"$uploadRoot\" cannot be found") return@TargetEnvironmentFunction uploadableVolume.targetRoot } fun TargetEnvironmentFunction<String>.getRelativeTargetPath(targetRelativePath: String): TargetEnvironmentFunction<String> = TargetEnvironmentFunction { targetEnvironment -> val targetBasePath = [email protected](targetEnvironment) return@TargetEnvironmentFunction joinPaths(targetBasePath, targetRelativePath, targetEnvironment.targetPlatform) } fun TargetEnvironment.DownloadRoot.getTargetDownloadPath(): TargetEnvironmentFunction<String> = TargetEnvironmentFunction { targetEnvironment -> val downloadRoot = this@getTargetDownloadPath val downloadableVolume = targetEnvironment.downloadVolumes[downloadRoot] ?: throw IllegalStateException("Download root \"$downloadRoot\" cannot be found") return@TargetEnvironmentFunction downloadableVolume.targetRoot } fun TargetEnvironment.LocalPortBinding.getTargetEnvironmentValue(): TargetEnvironmentFunction<HostPort> = TargetEnvironmentFunction { targetEnvironment -> val localPortBinding = this@getTargetEnvironmentValue val resolvedPortBinding = (targetEnvironment.localPortBindings[localPortBinding] ?: throw IllegalStateException("Local port binding \"$localPortBinding\" cannot be found")) return@TargetEnvironmentFunction resolvedPortBinding.targetEndpoint } @Throws(IOException::class) fun TargetEnvironment.downloadFromTarget(localPath: Path, progressIndicator: ProgressIndicator) { val localFileDir = localPath.parent val downloadVolumes = downloadVolumes.values val downloadVolume = downloadVolumes.find { it.localRoot == localFileDir } ?: error("Volume with local root $localFileDir not found") downloadVolume.download(localPath.name, progressIndicator) } private class JoinedStringTargetEnvironmentFunction<T>(private val iterable: Iterable<TargetEnvironmentFunction<T>>, private val separator: CharSequence) : TargetEnvironmentFunction<String> { override fun apply(t: TargetEnvironment): String = iterable.map { it.apply(t) }.joinToString(separator = separator) override fun toString(): String { return "JoinedStringTargetEnvironmentValue(iterable=$iterable, separator=$separator)" } }
platform/lang-api/src/com/intellij/execution/target/value/TargetEnvironmentFunctions.kt
3284838498
package inline inline fun f(): Int { return 0 }
plugins/kotlin/jps/jps-plugin/tests/testData/incremental/inlineFunCallSite/topLevelProperty/inline.kt
927938724
/* * 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. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kotlin.text.regex /** * Node representing non-capturing group */ open internal class NonCapturingJointSet(children: List<AbstractSet>, fSet: FSet) : JointSet(children, fSet) { /** * Returns startIndex+shift, the next position to match */ override fun matches(startIndex: Int, testString: CharSequence, matchResult: MatchResultImpl): Int { val start = matchResult.getConsumed(groupIndex) matchResult.setConsumed(groupIndex, startIndex) children.forEach { val shift = it.matches(startIndex, testString, matchResult) if (shift >= 0) { return shift } } matchResult.setConsumed(groupIndex, start) return -1 } override val name: String get() = "NonCapturingJointSet" override fun hasConsumed(matchResult: MatchResultImpl): Boolean { return matchResult.getConsumed(groupIndex) != 0 } }
runtime/src/main/kotlin/kotlin/text/regex/sets/NonCapturingJointSet.kt
431016414
//ALLOW_AST_ACCESS package test fun nothing(): Array<out Number> = throw Exception()
plugins/kotlin/idea/tests/testData/compiler/loadJava/compiledKotlin/type/ArrayOfOutNumber.kt
3360662920
package com.google.maps.android.ktx import com.google.android.gms.maps.StreetViewPanorama import com.google.android.gms.maps.StreetViewPanoramaView import com.google.android.gms.maps.model.StreetViewPanoramaCamera import com.google.android.gms.maps.model.StreetViewPanoramaLocation import com.google.android.gms.maps.model.StreetViewPanoramaOrientation import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine /** * A suspending function that provides an instance of a [StreetViewPanorama] from this * [StreetViewPanoramaView]. This is an alternative to using * [StreetViewPanoramaView.getStreetViewPanoramaAsync] by using coroutines to obtain a * [StreetViewPanorama]. * * @return the [StreetViewPanorama] instance */ public suspend inline fun StreetViewPanoramaView.awaitStreetViewPanorama(): StreetViewPanorama = suspendCoroutine { continuation -> getStreetViewPanoramaAsync { continuation.resume(it) } } /** * Returns a flow that emits when the street view panorama camera changes. Using this to * observe panorama camera change events will override an existing listener (if any) to * [StreetViewPanorama.setOnStreetViewPanoramaCameraChangeListener]. */ public fun StreetViewPanorama.cameraChangeEvents(): Flow<StreetViewPanoramaCamera> = callbackFlow { setOnStreetViewPanoramaCameraChangeListener { trySend(it) } awaitClose { setOnStreetViewPanoramaCameraChangeListener(null) } } /** * Returns a flow that emits when the street view panorama loads a new panorama. Using this to * observe panorama load change events will override an existing listener (if any) to * [StreetViewPanorama.setOnStreetViewPanoramaChangeListener]. */ public fun StreetViewPanorama.changeEvents(): Flow<StreetViewPanoramaLocation> = callbackFlow { setOnStreetViewPanoramaChangeListener { trySend(it) } awaitClose { setOnStreetViewPanoramaChangeListener(null) } } /** * Returns a flow that emits when the street view panorama is clicked. Using this to * observe panorama click events will override an existing listener (if any) to * [StreetViewPanorama.setOnStreetViewPanoramaClickListener]. */ public fun StreetViewPanorama.clickEvents(): Flow<StreetViewPanoramaOrientation> = callbackFlow { setOnStreetViewPanoramaClickListener { trySend(it) } awaitClose { setOnStreetViewPanoramaClickListener(null) } } /** * Returns a flow that emits when the street view panorama is long clicked. Using this to * observe panorama long click events will override an existing listener (if any) to * [StreetViewPanorama.setOnStreetViewPanoramaLongClickListener]. */ public fun StreetViewPanorama.longClickEvents(): Flow<StreetViewPanoramaOrientation> = callbackFlow { setOnStreetViewPanoramaLongClickListener { trySend(it) } awaitClose { setOnStreetViewPanoramaLongClickListener(null) } }
maps-ktx/src/main/java/com/google/maps/android/ktx/StreetViewPanoramaView.kt
1311698216
package org.jetbrains.completion.full.line.services.managers import com.intellij.lang.Language import org.jetbrains.completion.full.line.local.LocalModelsSchema import org.jetbrains.completion.full.line.local.ModelSchema import org.jetbrains.completion.full.line.settings.state.MLServerCompletionSettings interface ConfigurableModelsManager : ModelsManager { val modelsSchema: LocalModelsSchema fun importLocal(language: Language, modelPath: String): ModelSchema fun remove(language: Language) fun checkFile(language: Language): Boolean fun apply() fun reset() } fun ConfigurableModelsManager.missedLanguage(language: Language): Boolean { return modelsSchema.targetLanguage(language) == null && MLServerCompletionSettings.getInstance().isEnabled(language) } //fun ConfigurableModelsManager.missedFiles(language: Language): Boolean { // return modelsSchema.targetLanguage(language)?.let { // !it.binaryFile().exists() || !it.bpeFile().exists() || !it.configFile().exists() // } ?: false //} fun ConfigurableModelsManager.excessLanguage(language: Language): Boolean { return modelsSchema.targetLanguage(language) != null && !MLServerCompletionSettings.getInstance().isEnabled(language) }
plugins/full-line/src/org/jetbrains/completion/full/line/services/managers/ConfigurableModelsManager.kt
1860448802
// 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 org.jetbrains.plugins.gradle.service.project.wizard import com.intellij.ide.util.projectWizard.JavaSettingsStep import com.intellij.ide.util.projectWizard.SettingsStep import com.intellij.openapi.ui.MessageDialogBuilder import com.intellij.util.lang.JavaVersion import org.gradle.util.GradleVersion import org.jetbrains.plugins.gradle.util.* class GradleSdkSettingsStep( private val settingsStep: SettingsStep, private val builder: AbstractGradleModuleBuilder ) : JavaSettingsStep(settingsStep, builder, builder::isSuitableSdkType) { private val context get() = settingsStep.context private val jdk get() = myJdkComboBox.selectedJdk private val javaVersion get() = JavaVersion.tryParse(jdk?.versionString) private fun getPreferredGradleVersion(): GradleVersion { val project = context.project ?: return GradleVersion.current() return findGradleVersion(project) ?: GradleVersion.current() } private fun getGradleVersion(): GradleVersion? { val preferredGradleVersion = getPreferredGradleVersion() val javaVersion = javaVersion ?: return preferredGradleVersion return when (isSupported(preferredGradleVersion, javaVersion)) { true -> preferredGradleVersion else -> suggestGradleVersion(javaVersion) } } override fun validate(): Boolean { return super.validate() && validateGradleVersion() } private fun validateGradleVersion(): Boolean { val javaVersion = javaVersion ?: return true if (getGradleVersion() != null) { return true } val preferredGradleVersion = getPreferredGradleVersion() return MessageDialogBuilder.yesNo( title = GradleBundle.message( "gradle.settings.wizard.unsupported.jdk.title", if (context.isCreatingNewProject) 0 else 1 ), message = GradleBundle.message( "gradle.settings.wizard.unsupported.jdk.message", javaVersion.toFeatureString(), MINIMUM_SUPPORTED_JAVA.toFeatureString(), MAXIMUM_SUPPORTED_JAVA.toFeatureString(), preferredGradleVersion.version)) .asWarning() .ask(component) } override fun updateDataModel() { super.updateDataModel() builder.gradleVersion = getGradleVersion() ?: getPreferredGradleVersion() } }
plugins/gradle/java/src/service/project/wizard/GradleSdkSettingsStep.kt
1282349351
// HIGHLIGHT: INFORMATION // PROBLEM: Replace 'associateTo' with 'associateByTo' // FIX: Replace with 'associateByTo' // WITH_STDLIB fun getKey(i: Int): Long = 1L fun getValue(i: Int): String = "" fun test() { val destination = mutableMapOf<Long, String>() listOf(1).<caret>associateTo(destination) { i -> getKey(i) to getValue(i) } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceAssociateFunction/associateByToKeyAndValue/basic2.kt
2904095082
// "Remove useless cast" "true" fun test(x: Any): Int { if (x is String) { return (x <caret>as String).length } return -1 }
plugins/kotlin/idea/tests/testData/quickfix/expressions/removeUselessCastInParens.kt
2029292767
// 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.ui import com.intellij.ide.util.AbstractTreeClassChooserDialog import com.intellij.ide.util.TreeChooser import com.intellij.ide.util.gotoByName.GotoFileModel import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts import com.intellij.psi.search.FilenameIndex import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.idea.projectView.KtClassOrObjectTreeNode import org.jetbrains.kotlin.idea.projectView.KtFileTreeNode import org.jetbrains.kotlin.idea.search.projectScope import org.jetbrains.kotlin.idea.search.restrictToKotlinSources import org.jetbrains.kotlin.psi.KtFile import javax.swing.tree.DefaultMutableTreeNode class KotlinFileChooserDialog( @NlsContexts.DialogTitle title: String, project: Project, searchScope: GlobalSearchScope?, packageName: String? ) : AbstractTreeClassChooserDialog<KtFile>( title, project, searchScope ?: project.projectScope().restrictToKotlinSources(), KtFile::class.java, ScopeAwareClassFilter(searchScope, packageName), null, null, false, false ) { override fun getSelectedFromTreeUserObject(node: DefaultMutableTreeNode): KtFile? = when (val userObject = node.userObject) { is KtFileTreeNode -> userObject.ktFile is KtClassOrObjectTreeNode -> { val containingFile = userObject.value.containingKtFile if (containingFile.declarations.size == 1) containingFile else null } else -> null } override fun getClassesByName(name: String, checkBoxState: Boolean, pattern: String, searchScope: GlobalSearchScope): List<KtFile> { return FilenameIndex.getFilesByName(project, name, searchScope).filterIsInstance<KtFile>() } override fun createChooseByNameModel() = GotoFileModel(this.project) /** * Base class [AbstractTreeClassChooserDialog] unfortunately doesn't filter the file tree according to the provided "scope". * As a workaround we use filter preventing wrong file selection. */ private class ScopeAwareClassFilter(val searchScope: GlobalSearchScope?, val packageName: String?) : TreeChooser.Filter<KtFile> { override fun isAccepted(element: KtFile?): Boolean { if (element == null) return false if (searchScope == null && packageName == null) return true val matchesSearchScope = searchScope?.accept(element.virtualFile) ?: true val matchesPackage = packageName?.let { element.packageFqName.asString() == it } ?: true return matchesSearchScope && matchesPackage } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/ui/KotlinFileChooserDialog.kt
150304688
// 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.pushDown import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.idea.refactoring.pullUp.addMemberToTarget import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtCallableDeclaration import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.TypeSubstitutor import org.jetbrains.kotlin.util.findCallableMemberBySignature internal fun moveCallableMemberToClass( member: KtCallableDeclaration, memberDescriptor: CallableMemberDescriptor, targetClass: KtClassOrObject, targetClassDescriptor: ClassDescriptor, substitutor: TypeSubstitutor, makeAbstract: Boolean ): KtCallableDeclaration { val targetMemberDescriptor = memberDescriptor.substitute(substitutor)?.let { targetClassDescriptor.findCallableMemberBySignature(it as CallableMemberDescriptor) } val targetMember = targetMemberDescriptor?.source?.getPsi() as? KtCallableDeclaration return targetMember?.apply { if (memberDescriptor.modality != Modality.ABSTRACT && makeAbstract) { addModifier(KtTokens.OVERRIDE_KEYWORD) } else if (memberDescriptor.overriddenDescriptors.isEmpty()) { removeModifier(KtTokens.OVERRIDE_KEYWORD) } else { addModifier(KtTokens.OVERRIDE_KEYWORD) } } ?: addMemberToTarget(member, targetClass).apply { val sourceClassDescriptor = memberDescriptor.containingDeclaration as? ClassDescriptor if (sourceClassDescriptor?.kind == ClassKind.INTERFACE) { if (targetClassDescriptor.kind != ClassKind.INTERFACE && memberDescriptor.modality == Modality.ABSTRACT) { addModifier(KtTokens.ABSTRACT_KEYWORD) } } if (memberDescriptor.modality != Modality.ABSTRACT && makeAbstract) { KtTokens.VISIBILITY_MODIFIERS.types.forEach { removeModifier(it as KtModifierKeywordToken) } addModifier(KtTokens.OVERRIDE_KEYWORD) } } as KtCallableDeclaration }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/pushDownImpl.kt
2960128370
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.idea.maven.importing import com.intellij.openapi.components.BaseState import com.intellij.openapi.components.SimplePersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.module.Module import org.jetbrains.idea.maven.importing.MavenPomPathModuleService.MavenPomPathState @State(name = "MavenCustomPomFilePath") class MavenPomPathModuleService : SimplePersistentStateComponent<MavenPomPathState>(MavenPomPathState()) { companion object { @JvmStatic fun getInstance(module: Module): MavenPomPathModuleService { return module.getService(MavenPomPathModuleService::class.java) } } var pomFileUrl: String? get() = state.mavenPomFileUrl set(value) { state.mavenPomFileUrl = value } class MavenPomPathState : BaseState() { var mavenPomFileUrl by string() } }
plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenPomPathModuleService.kt
4166719537
import java.util.Arrays import java.util.stream.Collectors import java.util.stream.Stream internal class Test { fun main(lst: List<String>) { val streamOfList = lst.stream() .map { x: String -> x + "e" } .collect(Collectors.toList()) val streamOfElements = Stream.of(1, 2, 3) .map { x: Int -> x + 1 } .collect(Collectors.toList()) val array = arrayOf(1, 2, 3) val streamOfArray = Arrays.stream(array) .map { x: Int -> x + 1 } .collect(Collectors.toList()) val streamOfArray2 = Stream.of(*array) .map { x: Int -> x + 1 } .collect(Collectors.toList()) val streamIterate = Stream.iterate(2) { v: Int -> v * 2 } .map { x: Int -> x + 1 } .collect(Collectors.toList()) val streamGenerate = Stream.generate { 42 } .map { x: Int -> x + 1 } .collect(Collectors.toList()) } }
plugins/kotlin/j2k/new/tests/testData/newJ2k/javaStreamsApi/createStream.kt
3606535863
class InitAndParams { constructor<caret>(x: Int, z: Int) { this.y = x w = foo(y) this.v = w + z } val y: Int val w: Int fun foo(arg: Int) = arg val v: Int }
plugins/kotlin/idea/tests/testData/intentions/convertSecondaryConstructorToPrimary/initAndParams.kt
3977653068
// 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.liveTemplates.macro import com.intellij.codeInsight.template.Template import com.intellij.codeInsight.template.TemplateEditingAdapter import com.intellij.codeInsight.template.impl.TemplateManagerImpl import com.intellij.codeInsight.template.impl.TemplateState import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.overrideImplement.ImplementMembersHandler import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.psi.KtReferenceExpression import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode internal class AnonymousTemplateEditingListener(private val psiFile: PsiFile, private val editor: Editor) : TemplateEditingAdapter() { private var classRef: KtReferenceExpression? = null private var classDescriptor: ClassDescriptor? = null override fun currentVariableChanged(templateState: TemplateState, template: Template?, oldIndex: Int, newIndex: Int) { if (templateState.template == null) return val variableRange = templateState.getVariableRange("SUPERTYPE") ?: return val name = psiFile.findElementAt(variableRange.startOffset) if (name != null && name.parent is KtReferenceExpression) { val ref = name.parent as KtReferenceExpression val descriptor = ref.analyze(BodyResolveMode.FULL).get(BindingContext.REFERENCE_TARGET, ref) if (descriptor is ClassDescriptor) { classRef = ref classDescriptor = descriptor } } } override fun templateFinished(template: Template, brokenOff: Boolean) { editor.putUserData(LISTENER_KEY, null) if (brokenOff) return if (classDescriptor != null) { if (classDescriptor!!.kind == ClassKind.CLASS) { val placeToInsert = classRef!!.textRange.endOffset runWriteAction { PsiDocumentManager.getInstance(psiFile.project).getDocument(psiFile)!!.insertString(placeToInsert, "()") } var hasConstructorsParameters = false for (cd in classDescriptor!!.constructors) { // TODO check for visibility hasConstructorsParameters = hasConstructorsParameters or (cd.valueParameters.size != 0) } if (hasConstructorsParameters) { editor.caretModel.moveToOffset(placeToInsert + 1) } } ImplementMembersHandler().invoke(psiFile.project, editor, psiFile, true) } } companion object { private val LISTENER_KEY = Key.create<AnonymousTemplateEditingListener>("kotlin.AnonymousTemplateEditingListener") fun registerListener(editor: Editor, project: Project) { if (editor.getUserData(LISTENER_KEY) != null) return val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.document)!! val templateState = TemplateManagerImpl.getTemplateState(editor) if (templateState != null) { val listener = AnonymousTemplateEditingListener(psiFile, editor) editor.putUserData(LISTENER_KEY, listener) templateState.addTemplateStateListener(listener) } } } }
plugins/kotlin/live-templates/src/org/jetbrains/kotlin/idea/liveTemplates/macro/AnonymousTemplateEditingListener.kt
3765273313
// "Create actual class for module testModule_JVM (JVM)" "true" package a import b.B expect class <caret>A : B
plugins/kotlin/idea/tests/testData/multiModuleQuickFix/createActual/createWithImport/common/a.kt
2109662799
<error>@file:kotlin.Deprecated("message")</error> @file:Suppress(<error>BAR</error>) <error>@file:Suppress(BAZ)</error> <error><error>@<error>k</error>otlin.Deprecated("message")</error></error> <error>@<error>S</error>uppress(<error>BAR</error>)</error> <error>@<error>S</error>uppress(BAZ)</error> @file:myAnnotation(1, "string") @file:boo.myAnnotation(1, <error>BAR</error>) @file:myAnnotation(N, BAZ) @<error>m</error>yAnnotation(1, "string") @<error>b</error>oo.myAnnotation(1, "string") @<error>m</error>yAnnotation(N, BAZ) package boo const val BAZ = "baz" const val N = 0 @Target(AnnotationTarget.FILE) @Retention(AnnotationRetention.SOURCE) @Repeatable annotation class myAnnotation(val i: Int, val s: String)
plugins/kotlin/idea/tests/testData/checker/AnnotationOnFile.kt
1457500728
fun f() { if (1 in intArrayOf()) { } }
plugins/kotlin/idea/tests/testData/formatter/In.kt
739686135
// WITH_STDLIB // AFTER-WARNING: The expression is unused fun main() { val x = 1..4 x.reversed().forEach<caret> { it } }
plugins/kotlin/idea/tests/testData/intentions/convertForEachToForLoop/complexReceiver.kt
1983506983
// SET_TRUE: USE_TAB_CHARACTER // SET_INT: TAB_SIZE=4 // SET_INT: INDENT_SIZE=4 object A { val a = """blah | <caret>blah""".trimMargin() } // IGNORE_FORMATTER
plugins/kotlin/idea/tests/testData/editor/enterHandler/multilineString/withTabs/tabs4/EnterInsideText.after.kt
3913056261
class A interface T fun foo() { fun bar() { class Test : A(), T } }
plugins/kotlin/idea/tests/testData/stubs/LocalClassInLocalFunction.kt
166231330
// 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.moveFilesOrDirectories import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.LangDataKeys import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.refactoring.move.MoveCallback import com.intellij.refactoring.move.MoveHandler import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesHandler import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade import org.jetbrains.kotlin.idea.refactoring.move.logFusForMoveRefactoring import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui.KotlinAwareMoveFilesOrDirectoriesDialog import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui.KotlinAwareMoveFilesOrDirectoriesModel import org.jetbrains.kotlin.idea.util.application.executeCommand import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtFile class KotlinMoveFilesOrDirectoriesHandler : MoveFilesOrDirectoriesHandler() { private fun adjustElements(elements: Array<out PsiElement>): Array<PsiFileSystemItem>? { return elements.map { when { it is PsiFile -> it it is PsiDirectory -> it it is PsiClass && it.containingClass == null -> it.containingFile it is KtClassOrObject && it.parent is KtFile -> it.parent as KtFile else -> return null } }.toTypedArray() } override fun canMove(elements: Array<out PsiElement>, targetContainer: PsiElement?, reference: PsiReference?): Boolean { val adjustedElements = adjustElements(elements) ?: return false if (adjustedElements.none { it is KtFile }) return false return super.canMove(adjustedElements, targetContainer, reference) } override fun adjustForMove( project: Project, sourceElements: Array<out PsiElement>, targetElement: PsiElement? ): Array<PsiFileSystemItem>? { return adjustElements(sourceElements) } override fun doMove(project: Project, elements: Array<out PsiElement>, targetContainer: PsiElement?, callback: MoveCallback?) { if (!(targetContainer == null || targetContainer is PsiDirectory || targetContainer is PsiDirectoryContainer)) return val adjustedElementsToMove = adjustForMove(project, elements, targetContainer)?.toList() ?: return val targetDirectory = MoveFilesOrDirectoriesUtil.resolveToDirectory(project, targetContainer) if (targetContainer != null && targetDirectory == null) return val initialTargetDirectory = MoveFilesOrDirectoriesUtil.getInitialTargetDirectory(targetDirectory, elements) val isTestUnitMode = isUnitTestMode() if (isTestUnitMode && initialTargetDirectory !== null) { KotlinAwareMoveFilesOrDirectoriesModel( project, adjustedElementsToMove, initialTargetDirectory.virtualFile.presentableUrl, updatePackageDirective = true, searchReferences = true, moveCallback = callback ).run { project.executeCommand(MoveHandler.getRefactoringName()) { with(computeModelResult()) { if (!isTestUnitMode) { logFusForMoveRefactoring( elementsCount, entityToMove, destination, true, processor ) } else { processor.run() } } } } return } KotlinAwareMoveFilesOrDirectoriesDialog(project, initialTargetDirectory, adjustedElementsToMove, callback).show() } override fun tryToMove( element: PsiElement, project: Project, dataContext: DataContext?, reference: PsiReference?, editor: Editor? ): Boolean { if (element is KtLightClassForFacade) { doMove(project, element.files.toTypedArray(), dataContext?.getData(LangDataKeys.TARGET_PSI_ELEMENT), null) return true } return super.tryToMove(element, project, dataContext, reference, editor) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveFilesOrDirectories/KotlinMoveFilesOrDirectoriesHandler.kt
1601749175
/* * * * Apache License * * * * Copyright [2017] Sinyuk * * * * 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.sinyuk.fanfou.util.span import android.annotation.TargetApi import android.content.Context import android.graphics.BlurMaskFilter import android.os.Build import android.text.Layout import android.text.style.* import java.util.* /** * Created by james on 13/10/15. */ class SpanOptions { val listSpan: MutableList<Any> = ArrayList() /** * 下划线 * * @return */ fun addUnderlineSpan(): SpanOptions { val span = UnderlineSpan() listSpan.add(span) return this } fun addBulletSpan(gapWidth: Int, color: Int): SpanOptions { val span = BulletSpan(gapWidth, color) listSpan.add(span) return this } /** * URL效果 * 需要实现textView.setMovementMethod(LinkMovementMethod.getInstance()); * * @param url 格式为:电话:tel:18721850636,邮箱:mailto:[email protected],网站:http://www.baidu.com,短信:mms:4155551212,彩信:mmsto:18721850636,地图:geo:38.899533,-77.036476 * @return */ fun addURLSpan(url: String): SpanOptions { val Urlspan = URLSpan(url) listSpan.add(Urlspan) return this } fun addQuoteSpan(color: Int): SpanOptions { val span = QuoteSpan(color) listSpan.add(span) return this } fun addAlignmentSpan(align: Layout.Alignment): SpanOptions { val span = AlignmentSpan.Standard(align) listSpan.add(span) return this } fun addStrikethroughSpan(): SpanOptions { val span = StrikethroughSpan() listSpan.add(span) return this } fun addBackgroundColorSpan(color: Int): SpanOptions { val span = BackgroundColorSpan(color) listSpan.add(span) return this } /** * @param density * @param style BlurMaskFilter.Blur.NORMAL * @return */ fun addMaskFilterSpan(density: Float, style: BlurMaskFilter.Blur): SpanOptions { val span = MaskFilterSpan(BlurMaskFilter(density, style)) listSpan.add(span) return this } fun addSubscriptSpan(): SpanOptions { val span = SubscriptSpan() listSpan.add(span) return this } fun addSuperscriptSpan(): SpanOptions { val span = SuperscriptSpan() listSpan.add(span) return this } /** * @param style Typeface.BOLD | Typeface.ITALIC * @return */ fun addStyleSpan(style: Int): SpanOptions { val span = StyleSpan(style) listSpan.add(span) return this } fun addAbsoluteSizeSpan(size: Int, dip: Boolean): SpanOptions { val span = AbsoluteSizeSpan(size, dip) listSpan.add(span) return this } /** * 同比放大索小 * * @return */ fun addRelativeSizeSpan(proportion: Float): SpanOptions { val span = RelativeSizeSpan(proportion) listSpan.add(span) return this } fun addTextAppearanceSpan(context: Context, appearance: Int): SpanOptions { val span = TextAppearanceSpan(context, appearance) listSpan.add(span) return this } /** * @param locale Locale.CHINESE * @return */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) fun addLocaleSpan(locale: Locale): SpanOptions { val span = LocaleSpan(locale) listSpan.add(span) return this } fun addScaleXSpan(proportion: Float): SpanOptions { val span = ScaleXSpan(proportion) listSpan.add(span) return this } /** * @param typeface serif * @return */ fun addTypefaceSpan(typeface: String): SpanOptions { val span = TypefaceSpan(typeface) listSpan.add(span) return this } fun addImageSpan(context: Context, imgId: Int): SpanOptions { val span = ImageSpan(context, imgId) listSpan.add(span) return this } /** * 文本颜色 * * @return */ fun addForegroundColor(color: Int): SpanOptions { val span = ForegroundColorSpan(color) listSpan.add(span) return this } /** * 自定义Span * * @param object * @return */ fun addSpan(span: Any): SpanOptions { listSpan.add(span) return this } }
presentation/src/main/java/com/sinyuk/fanfou/util/span/SpanOptions.kt
385778626
package com.xmartlabs.bigbang.ui.extension import android.support.v4.app.Fragment /** Hides the keyboard, if visible. */ fun Fragment.hideKeyboard() { activity?.hideKeyboard() }
ui/src/main/java/com/xmartlabs/bigbang/ui/extension/FragmentExtensions.kt
2104992072
package xyz.nulldev.ts.api.v2.java.impl.chapters import eu.kanade.tachiyomi.data.database.DatabaseHelper import xyz.nulldev.ts.api.v2.http.BaseController import xyz.nulldev.ts.api.v2.java.impl.util.getChapters import xyz.nulldev.ts.api.v2.java.model.chapters.ChaptersController import xyz.nulldev.ts.ext.kInstanceLazy class ChaptersControllerImpl : ChaptersController, BaseController() { private val db: DatabaseHelper by kInstanceLazy() override fun get(vararg chapterIds: Long) = ChapterCollectionImpl(chapterIds.toList()) // TODO Check these chapters exist override fun getAll() = ChapterCollectionImpl(db.getChapters().executeAsBlocking().map { it.id!! }.toList()) }
TachiServer/src/main/java/xyz/nulldev/ts/api/v2/java/impl/chapters/ChaptersControllerImpl.kt
1127529632
package eu.kanade.tachiyomi.network import okhttp3.Call import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import rx.Observable import rx.Producer import rx.Subscription import java.util.concurrent.atomic.AtomicBoolean fun Call.asObservable(): Observable<Response> { return Observable.unsafeCreate { subscriber -> // Since Call is a one-shot type, clone it for each new subscriber. val call = clone() // Wrap the call in a helper which handles both unsubscription and backpressure. val requestArbiter = object : AtomicBoolean(), Producer, Subscription { override fun request(n: Long) { if (n == 0L || !compareAndSet(false, true)) return try { val response = call.execute() if (!subscriber.isUnsubscribed) { subscriber.onNext(response) subscriber.onCompleted() } } catch (error: Exception) { if (!subscriber.isUnsubscribed) { subscriber.onError(error) } } } override fun unsubscribe() { call.cancel() } override fun isUnsubscribed(): Boolean { return call.isCanceled } } subscriber.add(requestArbiter) subscriber.setProducer(requestArbiter) } } fun Call.asObservableSuccess(): Observable<Response> { return asObservable().doOnNext { response -> if (!response.isSuccessful) { response.close() throw Exception("HTTP error ${response.code()}") } } } fun OkHttpClient.newCallWithProgress(request: Request, listener: ProgressListener): Call { val progressClient = newBuilder() .cache(null) .addNetworkInterceptor { chain -> val originalResponse = chain.proceed(chain.request()) originalResponse.newBuilder() .body(ProgressResponseBody(originalResponse.body()!!, listener)) .build() } .build() return progressClient.newCall(request) }
Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/network/OkHttpExtensions.kt
4001399661
/** * HoTT Transmitter Config Copyright (C) 2013 Oliver Treichel * * 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:></http:>//www.gnu.org/licenses/>. */ package de.treichels.hott.model.enums import de.treichels.hott.util.get import java.util.* /** * @author Oliver Treichel &lt;[email protected]&gt; */ enum class ReceiverType(override val productCode: Int = 0, override val orderNo: String = "", val id: Int = 0, val hasGyro: Boolean = false, val hasVario: Boolean = false, override val category: String = ReceiverType.category, override val baudRate: Int = 19200) : Registered<ReceiverType> { falcon12(16007900, "S1035", 0x35, true), falcon12_plus(16008700, "S1034", 0x34, true), gr4(16005600, "33502"), gr8(16005700, "33504"), gr10c(0, "S1029", 0x3d, true), gr12(16003500, "33506"), gr12l(16003510, "S1012"), gr12l_sumd(16003540, "S1037"), gr12L_sumd_div_pcb(16003550, "S1045"), gr12L_sumd_div(16003550, "S1046"), gr12L_sumd_div_2(16003550, "S1051"), gr12sc(0, "33566", 0x91), gr12sh(0, "33565", 0x91), gr12sh_3xg(16006000, "33575", 0x75, true), gr12_3xg(16005400, "33576", 0x76, true), gr12_3xg_vario(16005500, "33577", 0x77, true, true), gr12s(16003400, "33505"), gr16(16003100, "33508"), gr16l(16003112, "S1021"), gr18(16006100, "33579", 0x79, true, true), gr18c(16006160, "S1019", 0x19, true), gr24(16003200, "33512"), gr24l(16003201, "S1022"), gr24pro(16005800, "33583", 0x97, true, true), gr32(16004000, "33516"), gr32l(16004020, "S1023"), gr18_alpha(19000710, "16520", 0x79, true, true), gr18c_alpha(19001000, "16530", 0x19, true), heim3d(16006900, "16100.86", 0x3d, true), aiocopterfc(0, "S1038", 0x38, true); override fun toString(): String = ResourceBundle.getBundle(javaClass.name)[name] + if (orderNo.isNotEmpty()) " ($orderNo)" else "" companion object { fun forProductCode(productCode: Int): ReceiverType? = values().firstOrNull { s -> s.productCode == productCode } fun forId(id: Int): ReceiverType? = values().firstOrNull { s -> s.id == id } fun forOrderNo(orderNo: String): ReceiverType? = values().firstOrNull { s -> s.orderNo == orderNo } const val category = "HoTT_Receiver" } }
HoTT-Model/src/main/kotlin/de/treichels/hott/model/enums/ReceiverType.kt
4159125178
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.navigation.safe.args.generator import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import org.junit.runner.RunWith import org.junit.runners.JUnit4 import java.io.File @RunWith(JUnit4::class) class NavGeneratorTest { @Suppress("MemberVisibilityCanBePrivate") @get:Rule val workingDir = TemporaryFolder() @Test fun test() { val output = generateSafeArgs("foo", "foo.flavor", testData("naive_test.xml"), workingDir.root) val javaNames = output.files val expectedSet = setOf( "androidx.navigation.testapp.MainFragmentDirections", "foo.flavor.NextFragmentDirections", "androidx.navigation.testapp.MainFragmentArgs", "foo.flavor.NextFragmentArgs" ) assertThat(output.errors.isEmpty(), `is`(true)) assertThat(javaNames.toSet(), `is`(expectedSet)) javaNames.forEach { name -> val file = File(workingDir.root, "${name.replace('.', File.separatorChar)}.java") assertThat(file.exists(), `is`(true)) } } }
navigation/safe-args-generator/src/tests/kotlin/androidx/navigation/safe/args/generator/NavGeneratorTest.kt
25325738
package io.blackbox_vision.mvphelpers.ui.loader import android.content.Context import android.support.v4.content.Loader import io.blackbox_vision.mvphelpers.logic.factory.PresenterFactory import io.blackbox_vision.mvphelpers.logic.presenter.BasePresenter class PresenterLoader<P : BasePresenter<*>> constructor(context: Context, private val factory: PresenterFactory<P>) : Loader<P>(context) { private var presenter: P? = null override fun onStartLoading() { super.onStartLoading() if (null != presenter) { deliverResult(presenter) } forceLoad() } override fun onForceLoad() { super.onForceLoad() presenter = factory.create() deliverResult(presenter) } override fun onReset() { super.onReset() if (null != presenter) { presenter!!.detachView() presenter = null } } companion object { fun <P : BasePresenter<*>> newInstance(context: Context, factory: PresenterFactory<P>): PresenterLoader<P> { return PresenterLoader(context, factory) } } }
library/src/main/java/io/blackbox_vision/mvphelpers/ui/loader/PresenterLoader.kt
1391017762
package org.fossasia.openevent.general.speakers import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy.REPLACE import androidx.room.Query import io.reactivex.Flowable import io.reactivex.Single @Dao interface SpeakerDao { @Insert(onConflict = REPLACE) fun insertSpeakers(speakers: List<Speaker>) @Insert(onConflict = REPLACE) fun insertSpeaker(speaker: Speaker) @Query("SELECT * from Speaker WHERE id = :id") fun getSpeaker(id: Long): Flowable<Speaker> @Query("SELECT * FROM speaker WHERE email = :email AND event = :eventId") fun getSpeakerByEmailAndEvent(email: String, eventId: Long): Single<Speaker> }
app/src/main/java/org/fossasia/openevent/general/speakers/SpeakerDao.kt
4189170622
/* * Copyright 2014-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mooregreatsoftware.gradle.util.xml import groovy.util.Node import groovy.util.NodeList import java.util.Collections.emptyMap fun NodeList.findByAttribute(attrName: String, attrValue: String, nodeCreator: () -> Node): Node { @Suppress("UNCHECKED_CAST") return (this as Iterable<Node>).find { it.attributeMatches(attrName, attrValue) } ?: nodeCreator() } fun Node.getOrCreate(elementName: String, nodeCreator: () -> Node): Node { @Suppress("UNCHECKED_CAST") return (this.children() as Iterable<Node>).find { it.name() == elementName } ?: nodeCreator() } private fun Node.attributeMatches(attrName: String, attrValue: String): Boolean { val attr = this.attributes()[attrName] as String? return attr != null && attr.equals(attrValue, ignoreCase = true) } private fun noNodes(): List<NodeBuilder> = listOf() fun n(name: String, attrs: Map<String, String>) = NodeBuilder(name, attrs, null, noNodes()) fun n(name: String, textVal: String): NodeBuilder = NodeBuilder(name, mapOf(), textVal, listOf()) fun n(name: String, children: Iterable<NodeBuilder>) = NodeBuilder(name, emptyMap(), null, children) fun n(name: String) = NodeBuilder(name, emptyMap(), null, noNodes()) fun n(name: String, attrs: Map<String, String>?, child: NodeBuilder) = NodeBuilder(name, attrs, null, listOf(child)) fun n(name: String, attrs: Map<String, String>?, children: Iterable<NodeBuilder>) = NodeBuilder(name, attrs, null, children) fun n(name: String, child: NodeBuilder) = NodeBuilder(name, emptyMap(), null, listOf(child)) fun Node.appendChild(nodeName: String) = this.appendChildren(nodeName, null, listOf()) fun Node.appendChild(nodeName: String, attrs: Map<String, String>) = this.appendChildren(nodeName, attrs, listOf()) fun Node.appendChild(nodeName: String, child: NodeBuilder) = this.appendChild(nodeName, null, child) fun Node.appendChild(nodeName: String, attrs: Map<String, String>?, child: NodeBuilder) = this.appendChildren(nodeName, attrs, null, child) fun Node.appendChildren(nodeName: String, attrs: Map<String, String>?, textVal: String?, child: NodeBuilder) = this.appendChildren(nodeName, attrs, textVal, listOf(child)) fun Node.appendChildren(nodeName: String, children: Iterable<NodeBuilder>) = this.appendChildren(nodeName, null, null, children) fun Node.appendChildren(nodeName: String, attrs: Map<String, String>?, children: Iterable<NodeBuilder>) = this.appendChildren(nodeName, attrs, null, children) fun Node.appendChildren(nodeName: String, attrs: Map<String, String>?, textVal: String?, children: Iterable<NodeBuilder>): Node { val node = when (textVal) { null -> this.appendNode(nodeName, attrs as Map<*, *>?) else -> this.appendNode(nodeName, attrs as Map<*, *>?, textVal) } children.forEach { node.appendChildren(it.name, it.attrs, it.textVal, it.children) } return node }
src/main/kotlin/com/mooregreatsoftware/gradle/util/xml/XmlUtils.kt
2229063809
package motocitizen.user object User { private var role = Role.RO var name = "" var id = 0 var isAuthorized = false val roleName: String get() = role.text fun isReadOnly() = role == Role.RO fun isModerator() = role in arrayOf(Role.MODERATOR, Role.DEVELOPER) fun notIsModerator() = !isModerator() fun logout() { name = "" role = Role.RO id = 0 isAuthorized = false } fun authenticate(id: Int, name: String, role: Role) { this.id = id this.name = name this.role = role isAuthorized = true } }
Motocitizen/src/motocitizen/user/User.kt
2806075252
package com.foo.graphql.inputArray.type data class Flower ( var id: Int? = null, var price: Int? = null)
e2e-tests/spring-graphql/src/main/kotlin/com/foo/graphql/inputArray/type/Flower.kt
3777469606
package org.evomaster.core.problem.rest.resource import io.swagger.parser.OpenAPIParser import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseCommandDto import org.evomaster.client.java.controller.api.dto.database.operations.InsertionResultsDto import org.evomaster.client.java.controller.api.dto.database.operations.QueryResultDto import org.evomaster.client.java.controller.db.SqlScriptRunner import org.evomaster.client.java.controller.internal.db.SchemaExtractor import org.evomaster.core.EMConfig import org.evomaster.core.database.DatabaseExecutor import org.evomaster.core.database.SqlInsertBuilder import org.evomaster.core.problem.rest.RestActionBuilderV3 import org.evomaster.core.problem.rest.resource.dependency.BodyParamRelatedToTable import org.evomaster.core.search.Action import org.evomaster.core.search.ActionFilter import org.evomaster.core.search.gene.Gene import org.evomaster.core.search.gene.numeric.LongGene import org.evomaster.core.search.service.Randomness import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import java.sql.Connection import java.sql.DriverManager class ResourceNodeWithDbTest { companion object { private lateinit var connection: Connection private lateinit var sqlInsertBuilder: SqlInsertBuilder private val schema = OpenAPIParser().readLocation("/swagger/artificial/resource_test.json", null, null).openAPI private val actionCluster: MutableMap<String, Action> = mutableMapOf() private val cluster = ResourceCluster() private val randomness = Randomness() @BeforeAll @JvmStatic fun initClass() { connection = DriverManager.getConnection("jdbc:h2:mem:db_test", "sa", "") SqlScriptRunner.execCommand(connection, """ CREATE TABLE RFOO (id bigint not null, doubleValue double, intValue int, floatValue float, primary key (id)); CREATE TABLE RBAR (id bigint not null, name varchar(256), fooId bigint not null, primary key(id)); alter table RBAR add constraint RBAR_FK foreign key (fooId) references RFOO(id); CREATE TABLE RXYZ (id bigint not null, name varchar(256), barId bigint not null, primary key(id)); alter table RXYZ add constraint RXYZ_FK foreign key (barId) references RBAR(id); """) SqlScriptRunner.execCommand(connection, "INSERT INTO RFOO (id, doubleValue, intValue, floatValue) VALUES (0, 1.0, 2, 3.0)") SqlScriptRunner.execCommand(connection, "INSERT INTO RBAR (id, name, fooId) VALUES (1, 'bar', 0)") SqlScriptRunner.execCommand(connection, "INSERT INTO RXYZ (id, name, barId) VALUES (2, 'xyz', 1)") SqlScriptRunner.execCommand(connection, "INSERT INTO RFOO (id, doubleValue, intValue, floatValue) VALUES (3, 4.0, 5, 6.0)") val dbschema = SchemaExtractor.extract(connection) sqlInsertBuilder = SqlInsertBuilder(dbschema, DbExecutor()) RestActionBuilderV3.addActionsFromSwagger(schema, actionCluster) val config = EMConfig() config.doesApplyNameMatching = true config.probOfEnablingResourceDependencyHeuristics = 1.0 cluster.initResourceCluster(actionCluster, sqlInsertBuilder = sqlInsertBuilder, config = config) cluster.initRelatedTables() } } @Test fun testClusterWithDbInit(){ //rfoo, rfoo/{id}, rbar, rbar/{id}, rxyz assertEquals(6, cluster.getCluster().size) // table in db assertTrue(cluster.getTableInfo().keys.containsAll(setOf("RFOO", "RBAR", "RXYZ"))) // data in db assertEquals(2, cluster.getDataInDb("RFOO")?.size) assertEquals(1, cluster.getDataInDb("RBAR")?.size) assertEquals(1, cluster.getDataInDb("RXYZ")?.size) val rfooNode = cluster.getResourceNode("/v3/api/rfoo") assertNotNull(rfooNode) rfooNode!!.resourceToTable.apply { assertTrue(derivedMap.keys.contains("RFOO")) assertEquals(1, paramToTable.size) assertTrue(paramToTable.values.first() is BodyParamRelatedToTable) (paramToTable.values.first() as BodyParamRelatedToTable).apply { assertEquals(4, fieldsMap.size) fieldsMap.forEach { t, u -> assertEquals(1, u.derivedMap.size) u.derivedMap.forEach { ut, uu -> assertEquals("RFOO", ut) assertEquals(uu.input.toLowerCase(), uu.targetMatched.toLowerCase()) } } } } val rbarNode = cluster.getResourceNode("/v3/api/rfoo/{rfooId}/rbar/{rbarId}") assertNotNull(rbarNode) rbarNode!!.resourceToTable.apply { assertTrue(derivedMap.keys.contains("RFOO")) assertTrue(derivedMap.keys.contains("RBAR")) } val rxyzNode = cluster.getResourceNode("/v3/api/rfoo/{rfooId}/rbar/{rbarId}/rxyz/{rxyzId}") assertNotNull(rxyzNode) rxyzNode!!.resourceToTable.apply { assertTrue(derivedMap.keys.contains("RFOO")) assertTrue(derivedMap.keys.contains("RBAR")) assertTrue(derivedMap.keys.contains("RXYZ")) } } @Test fun testDbActionCreation(){ val fooAndBar = cluster.createSqlAction(listOf("RFOO","RBAR"), sqlInsertBuilder, mutableListOf(), true, randomness= randomness) assertEquals(2, fooAndBar.size) val fooAndBar2 = cluster.createSqlAction(listOf("RFOO","RBAR"), sqlInsertBuilder, fooAndBar, true, randomness= randomness) assertEquals(0, fooAndBar2.size) val xyz = cluster.createSqlAction(listOf("RXYZ"), sqlInsertBuilder, mutableListOf(), true, randomness= randomness) assertEquals(3, xyz.size) val xyz2 = cluster.createSqlAction(listOf("RFOO","RBAR"), sqlInsertBuilder, xyz, true, randomness= randomness) assertEquals(0, xyz2.size) val xyz3 = cluster.createSqlAction(listOf("RFOO","RFOO","RBAR","RBAR"), sqlInsertBuilder, mutableListOf(), false, randomness= randomness) assertEquals(2 + 2*2, xyz3.size) val xyzSelect = cluster.createSqlAction(listOf("RXYZ"), sqlInsertBuilder, mutableListOf(), true, isInsertion = false, randomness = randomness) assertEquals(1, xyzSelect.size) } @Test fun testBindingWithDbInOneCall(){ // /v3/api/rfoo val dbactions = sqlInsertBuilder.createSqlInsertionAction("RFOO") val dbFooId = getGenePredict(dbactions.first(), "id") { g: Gene -> g is LongGene } (dbFooId as LongGene).value = 42L assertEquals(1, dbactions.size) val postFoo = cluster.getResourceNode("/v3/api/rfoo")!!.sampleRestResourceCalls("POST", randomness, 10) postFoo.is2POST = true postFoo.initDbActions(dbactions, cluster, false, false) val fooBodyId = getGenePredict(postFoo.seeActions(ActionFilter.NO_SQL).first(), "id") { g: Gene -> g is LongGene } val fooDbId = getGenePredict(postFoo.seeActions(ActionFilter.ONLY_SQL).first(), "id") { g: Gene -> g is LongGene } // because id here is primary key, param is updated based on db gene assertEquals((fooBodyId as LongGene).value, (fooDbId as LongGene).value) assertEquals(42, fooBodyId.value) // /v3/api/rfoo/{rfooId} val getFoo = cluster.getResourceNode("/v3/api/rfoo/{rfooId}")!!.sampleRestResourceCalls("GET", randomness, maxTestSize = 10) val previousGetFooId = getGenePredict(getFoo.seeActions(ActionFilter.NO_SQL).first(), "rfooId"){g: Gene-> g is LongGene } (previousGetFooId as LongGene).value = 40 getFoo.is2POST = true val createFoo = sqlInsertBuilder.createSqlInsertionAction("RFOO") val createGetFooId = getGenePredict(createFoo.first(), "id") { g: Gene -> g is LongGene } assertNotNull(createGetFooId) (createGetFooId as LongGene).value = 42 getFoo.initDbActions(createFoo, cluster, false, false) val fooGetId = getGenePredict(getFoo.seeActions(ActionFilter.NO_SQL).first(), "rfooId"){g: Gene-> g is LongGene } val fooCreateGetId = getGenePredict(getFoo.seeActions(ActionFilter.ONLY_SQL).first(), "id") { g: Gene -> g is LongGene } assertEquals((fooGetId as LongGene).value, (fooCreateGetId as LongGene).value) assertEquals(42, fooGetId.value) // /v3/api/rfoo/{rfooId}/rbar/{rbarId} val getBarNode = cluster.getResourceNode("/v3/api/rfoo/{rfooId}/rbar/{rbarId}")!! val getBar = getBarNode.sampleRestResourceCalls("GET", randomness, maxTestSize = 10) val fooBarDbActionToCreate = cluster.createSqlAction(listOf("RFOO", "RBAR"), sqlInsertBuilder, mutableListOf(), true, randomness = randomness) assertEquals(2, fooBarDbActionToCreate.size) getBar.initDbActions(fooBarDbActionToCreate, cluster, false, false) val barFooId = getGenePredict(getBar.seeActions(ActionFilter.NO_SQL).first(), "rfooId"){g: Gene-> g is LongGene } val barId = getGenePredict(getBar.seeActions(ActionFilter.NO_SQL).first(), "rbarId"){g: Gene-> g is LongGene } val dbFooIdInGetBar = getGenePredict(getBar.seeActions(ActionFilter.ONLY_SQL).first(), "id"){g: Gene -> g is LongGene } val dbBarIdInGetBar = getGenePredict(getBar.seeActions(ActionFilter.ONLY_SQL)[1], "id"){g: Gene -> g is LongGene } assertEquals((barFooId as LongGene).value, (dbFooIdInGetBar as LongGene).value) assertTrue(dbFooIdInGetBar.isDirectBoundWith(barFooId)) assertEquals((barId as LongGene).value, (dbBarIdInGetBar as LongGene).value) assertTrue(barId.isDirectBoundWith(dbBarIdInGetBar)) // /v3/api/rfoo/{rfooId}/rbar/{rbarId}/rxyz/{rxyzId} val xYZNode = cluster.getResourceNode("/v3/api/rfoo/{rfooId}/rbar/{rbarId}/rxyz/{rxyzId}")!! val getXYZ = xYZNode.sampleRestResourceCalls("GET", randomness, 10) val xyzDbActions = cluster.createSqlAction(listOf("RXYZ", "RBAR", "RFOO"), sqlInsertBuilder, mutableListOf(), true, randomness = randomness) getGenePredict(xyzDbActions[0], "id"){g: Gene-> g is LongGene }.apply { (this as? LongGene)?.value = 42 } getGenePredict(xyzDbActions[1], "id"){g: Gene-> g is LongGene }.apply { (this as? LongGene)?.value = 43 } getGenePredict(xyzDbActions[2], "id"){g: Gene-> g is LongGene }.apply { (this as? LongGene)?.value = 44 } assertEquals(3, xyzDbActions.size) getXYZ.initDbActions(xyzDbActions, cluster, false, false) val xyzFooId = getGenePredict(getXYZ.seeActions(ActionFilter.NO_SQL)[0], "rfooId"){g: Gene-> g is LongGene } val xyzBarId = getGenePredict(getXYZ.seeActions(ActionFilter.NO_SQL)[0], "rbarId"){g: Gene-> g is LongGene } val xyzId = getGenePredict(getXYZ.seeActions(ActionFilter.NO_SQL)[0], "rxyzId"){g: Gene-> g is LongGene } val dbXYZFooId = getGenePredict(getXYZ.seeActions(ActionFilter.ONLY_SQL)[0], "id"){g: Gene-> g is LongGene } val dbXYZBarId = getGenePredict(getXYZ.seeActions(ActionFilter.ONLY_SQL)[1], "id"){g: Gene-> g is LongGene } val dbXYZId = getGenePredict(getXYZ.seeActions(ActionFilter.ONLY_SQL)[2], "id"){g: Gene-> g is LongGene } assertEquals((xyzFooId as LongGene).value, (dbXYZFooId as LongGene).value) assertEquals(42, xyzFooId.value) assertTrue(xyzFooId.isDirectBoundWith(dbXYZFooId)) assertEquals((xyzBarId as LongGene).value, (dbXYZBarId as LongGene).value) assertEquals(43, xyzBarId.value) assertTrue(xyzBarId.isDirectBoundWith(dbXYZBarId)) assertEquals((xyzId as LongGene).value, (dbXYZId as LongGene).value) assertEquals(44, xyzId.value) assertTrue(xyzId.isDirectBoundWith(dbXYZId)) } @Test fun testBindingWithOtherCall(){ val xYZNode = cluster.getResourceNode("/v3/api/rfoo/{rfooId}/rbar/{rbarId}/rxyz/{rxyzId}")!! val getXYZ = xYZNode.sampleRestResourceCalls("GET", randomness, 10) val dbXYZ = cluster.createSqlAction(listOf("RFOO", "RBAR", "RXYZ"), sqlInsertBuilder, mutableListOf(), true, randomness = randomness) getGenePredict(dbXYZ[0], "id"){g: Gene-> g is LongGene }.apply { (this as? LongGene)?.value = 42 } getGenePredict(dbXYZ[1], "id"){g: Gene-> g is LongGene }.apply { (this as? LongGene)?.value = 43 } getGenePredict(dbXYZ[2], "id"){g: Gene-> g is LongGene }.apply { (this as? LongGene)?.value = 44 } getXYZ.initDbActions(dbXYZ, cluster, false, false) val xyzFooId = getGenePredict(getXYZ.seeActions(ActionFilter.NO_SQL)[0], "rfooId"){g: Gene-> g is LongGene } val xyzBarId = getGenePredict(getXYZ.seeActions(ActionFilter.NO_SQL)[0], "rbarId"){g: Gene-> g is LongGene } val dbXYZFooId = getGenePredict(getXYZ.seeActions(ActionFilter.ONLY_SQL)[0], "id"){g: Gene-> g is LongGene } val dbXYZBarId = getGenePredict(getXYZ.seeActions(ActionFilter.ONLY_SQL)[1], "id"){g: Gene-> g is LongGene } val getBarNode = cluster.getResourceNode("/v3/api/rfoo/{rfooId}/rbar/{rbarId}")!! val getBar = getBarNode.sampleRestResourceCalls("GET", randomness, maxTestSize = 10) val dbBar = cluster.createSqlAction(listOf("RFOO", "RBAR"), sqlInsertBuilder, mutableListOf(), true, randomness = randomness) getBar.initDbActions(dbBar, cluster, false, false) assertEquals(2, getBar.seeActionSize(ActionFilter.ONLY_SQL)) getBar.bindWithOtherRestResourceCalls(mutableListOf(getXYZ), cluster,true, randomness = null) assertEquals(0, getBar.seeActionSize(ActionFilter.ONLY_SQL)) assertFalse(getXYZ.isDeletable) assertTrue(getXYZ.shouldBefore.contains(getBar.getResourceNodeKey())) val barFooId = getGenePredict(getBar.seeActions(ActionFilter.NO_SQL).first(), "rfooId"){g: Gene-> g is LongGene } val barId = getGenePredict(getBar.seeActions(ActionFilter.NO_SQL).first(), "rbarId"){g: Gene-> g is LongGene } assertEquals((xyzBarId as LongGene).value, (barId as LongGene).value) assertEquals((dbXYZBarId as LongGene).value, barId.value) assertEquals(43, barId.value) assertEquals((xyzFooId as LongGene).value, (barFooId as LongGene).value) assertEquals(42, barFooId.value) assertEquals((dbXYZFooId as LongGene).value, barFooId.value) } private fun getGenePredict(action: Action, name: String, predict: (Gene) -> Boolean) : Gene?{ return action.seeTopGenes().flatMap { it.flatView() }.find { g-> predict(g) && g.name.equals(name, ignoreCase = true) } } private class DbExecutor : DatabaseExecutor { override fun executeDatabaseInsertionsAndGetIdMapping(dto: DatabaseCommandDto): InsertionResultsDto? { return null } override fun executeDatabaseCommandAndGetQueryResults(dto: DatabaseCommandDto): QueryResultDto? { return SqlScriptRunner.execCommand(connection, dto.command).toDto() } override fun executeDatabaseCommand(dto: DatabaseCommandDto): Boolean { return false } } }
core/src/test/kotlin/org/evomaster/core/problem/rest/resource/ResourceNodeWithDbTest.kt
2844648314
package com.soywiz.kpspemu.format import com.soywiz.korio.error.* import com.soywiz.korio.stream.* class Pbp(val version: Int, val base: AsyncStream, val streams: List<AsyncStream>) { val streamsByName = NAMES.zip(streams).toMap() val PARAM_SFO get() = this[Pbp.PARAM_SFO]!! val ICON0_PNG get() = this[Pbp.ICON0_PNG]!! val ICON1_PMF get() = this[Pbp.ICON1_PMF]!! val PIC0_PNG get() = this[Pbp.PIC0_PNG]!! val PIC1_PNG get() = this[Pbp.PIC1_PNG]!! val SND0_AT3 get() = this[Pbp.SND0_AT3]!! val PSP_DATA get() = this[Pbp.PSP_DATA]!! val PSAR_DATA get() = this[Pbp.PSAR_DATA]!! companion object { const val PBP_MAGIC = 0x50425000 const val PARAM_SFO = "param.sfo" const val ICON0_PNG = "icon0.png" const val ICON1_PMF = "icon1.pmf" const val PIC0_PNG = "pic0.png" const val PIC1_PNG = "pic1.png" const val SND0_AT3 = "snd0.at3" const val PSP_DATA = "psp.data" const val PSAR_DATA = "psar.data" val NAMES = listOf(PARAM_SFO, ICON0_PNG, ICON1_PMF, PIC0_PNG, PIC1_PNG, SND0_AT3, PSP_DATA, PSAR_DATA) suspend fun check(s: AsyncStream): Boolean { return s.duplicate().readS32_le() == PBP_MAGIC } suspend operator fun invoke(s: AsyncStream): Pbp = load(s) suspend fun load(s: AsyncStream): Pbp { val magic = s.readS32_le() if (magic != PBP_MAGIC) invalidOp("Not a PBP file") val version = s.readS32_le() val offsets = s.readIntArray_le(8).toList() + listOf(s.size().toInt()) val streams = (0 until (offsets.size - 1)).map { s.sliceWithBounds(offsets[it].toLong(), offsets[it + 1].toLong()) } return Pbp(version, s, streams) } } operator fun get(name: String) = streamsByName[name.toLowerCase()]?.duplicate() operator fun get(index: Int) = streams[index] }
src/commonMain/kotlin/com/soywiz/kpspemu/format/Pbp.kt
385492013
/* * 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 import com.intellij.application.options.CodeStyleConfigurableWrapper import com.intellij.application.options.CodeStyleSchemesConfigurable import com.intellij.application.options.codeStyle.CodeStyleSchemesModel import com.intellij.application.options.codeStyle.CodeStyleSettingsPanelFactory import com.intellij.application.options.codeStyle.NewCodeStyleSettingsPanel import com.intellij.ide.todo.configurable.TodoConfigurable import com.intellij.openapi.Disposable import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.project.Project import com.intellij.psi.codeStyle.CodeStyleScheme import com.intellij.psi.codeStyle.CodeStyleSettingsProvider open class ConfigurableFactory : Disposable { companion object { @JvmStatic fun getInstance(): ConfigurableFactory { return ServiceManager.getService(ConfigurableFactory::class.java) } } override fun dispose() { } open fun createCodeStyleConfigurable(provider: CodeStyleSettingsProvider, codeStyleSchemesModel: CodeStyleSchemesModel, owner: CodeStyleSchemesConfigurable): CodeStyleConfigurableWrapper { val codeStyleConfigurableWrapper = CodeStyleConfigurableWrapper(provider, object : CodeStyleSettingsPanelFactory() { override fun createPanel(scheme: CodeStyleScheme): NewCodeStyleSettingsPanel { return NewCodeStyleSettingsPanel( provider.createSettingsPage(scheme.codeStyleSettings, codeStyleSchemesModel.getCloneSettings(scheme)), codeStyleSchemesModel) } }, owner) return codeStyleConfigurableWrapper } open fun getTodoConfigurable(project: Project): TodoConfigurable { return TodoConfigurable() } }
platform/lang-impl/src/com/intellij/ConfigurableFactory.kt
4092113132
package com.myls.odes.fragment import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.widget.SwipeRefreshLayout import android.view.* import com.myls.odes.R import com.myls.odes.activity.MainActivity import com.myls.odes.application.AnApplication import com.myls.odes.data.UserList import com.myls.odes.request.QueryUser import com.myls.odes.service.PullJsonService import com.myls.odes.utility.Storage import kotlinx.android.synthetic.main.fragment_person.* import kotlinx.android.synthetic.main.fragment_person.view.* import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode class PersonFragment : Fragment(), SwipeRefreshLayout.OnRefreshListener { private lateinit var saver: Storage private lateinit var useri: UserList.Info override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) (activity.application as AnApplication).let { saver = it.saver useri = it.userlist.list.firstOrNull()?.info ?: return@let post(MainActivity.InvalidDataEvent("UserList is empty")) onUpdateUserLayout() } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, saved: Bundle?) = inflater.inflate(R.layout.fragment_person, container, false)!! .also { it.refresh_layout.setOnRefreshListener(this) } override fun onRefresh() { with(activity) { Intent(Intent.ACTION_SYNC, null, this, PullJsonService::class.java).apply { putExtra(PullJsonService.Contract.REQUEST.name, QueryUser.Request(useri.stid)) startService(this) } } } private fun onUpdateUserLayout() { useri.let { with(basic_layout) { this.name_view.text = it.name this.stid_view.text = it.stid } with(detail_layout) { this. gender_view.text = it.gender this. grade_view.text = it.grade this.location_view.text = it.location } with(room_layout) { this. room_view.text = it.room this.building_view.text = it.building if (it.room.isBlank() && it.building.isBlank()) visibility = View.GONE } } } // 关于 Fragment 的生命周期 // (https://developer.android.com/guide/components/fragments.html#Creating) @Subscribe(threadMode = ThreadMode.MAIN) fun onUserUpdated(event: MainActivity.UserInfoUpdatedEvent) { if (event.done) { useri = event.user onUpdateUserLayout() } with(refresh_layout) { isRefreshing = false } } override fun onStart() { super.onStart() EVENT_BUS.register(this) } override fun onStop() { EVENT_BUS.unregister(this) super.onStop() } companion object { private val TAG = PersonFragment::class.java.canonicalName!! private val EVENT_BUS = EventBus.getDefault() private fun <T> post(data: T) = EVENT_BUS.post(data) // [Android Fragments Tutorial: An Introduction with Kotlin] // (https://www.raywenderlich.com/169885/android-fragments-tutorial-introduction-2) // [Best practice for instantiating a new Android Fragment] // (https://stackoverflow.com/q/9245408) fun create() = PersonFragment().apply { // 由于使用了近似全局的 Application,因此这里不需要通过 arguments: Bundle 传递参数 } } }
2017.AndroidApplicationDevelopment/ODES/app/src/main/java/com/myls/odes/fragment/PersonFragment.kt
611663468
package me.proxer.library.entity.info import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import me.proxer.library.entity.ProxerIdItem import me.proxer.library.enums.Category import me.proxer.library.enums.FskConstraint import me.proxer.library.enums.License import me.proxer.library.enums.MediaState import me.proxer.library.enums.Medium import me.proxer.library.internal.adapter.DelimitedEnumSet import me.proxer.library.internal.adapter.DelimitedStringSet import me.proxer.library.internal.adapter.NumberBasedBoolean /** * Entity holding the data associated with a recommendation. * * @property name The name. * @property genres The genres. * @property fskConstraints The fsk ratings. * @property description The description. * @property medium The medium. * @property episodeAmount The amount of episodes, this entry has. They do not necessarily have to be uploaded. * @property state The current state. * @property ratingSum The sum of all ratings. * @property ratingAmount The clicks on this entry, in this season. * @property category The category. * @property license The type of license. * @property positiveVotes The amount of positive votes. * @property negativeVotes The amount of negative votes. * @property negativeVotes The vote of the user if present when calling the respective api. * * @author Ruben Gees */ @JsonClass(generateAdapter = true) data class Recommendation( @Json(name = "id") override val id: String, @Json(name = "name") val name: String, @field:DelimitedStringSet(valuesToKeep = ["Slice of Life"]) @Json(name = "genre") val genres: Set<String>, @field:DelimitedEnumSet @Json(name = "fsk") val fskConstraints: Set<FskConstraint>, @Json(name = "description") val description: String, @Json(name = "medium") val medium: Medium, @Json(name = "count") val episodeAmount: Int, @Json(name = "state") val state: MediaState, @Json(name = "rate_sum") val ratingSum: Int, @Json(name = "rate_count") val ratingAmount: Int, @Json(name = "clicks") val clicks: Int, @Json(name = "kat") val category: Category, @Json(name = "license") val license: License, @Json(name = "count_positive") val positiveVotes: Int, @Json(name = "count_negative") val negativeVotes: Int, @field:NumberBasedBoolean @Json(name = "positive") val userVote: Boolean? ) : ProxerIdItem { /** * Returns the average of all ratings. */ val rating = when { ratingAmount <= 0 -> 0f else -> ratingSum.toFloat() / ratingAmount.toFloat() } }
library/src/main/kotlin/me/proxer/library/entity/info/Recommendation.kt
3603561021
package io.sonatalang.snc.frontend.domain.token abstract class BasicToken(protected val nextToken: Boolean) : Token { override fun orElse(command: (Token) -> Token) = this.run { if (!nextToken) { command(this) } else { this } } }
frontend/src/main/kotlin/io/sonatalang/snc/frontend/domain/token/BasicToken.kt
481890314
package io.sonatalang.snc.middleEnd.infrastructure.types import io.sonatalang.snc.middleEnd.domain.node.* import io.sonatalang.snc.middleEnd.infrastructure.TreeTraverser class TypeResolver(val entityRegistry: EntityListener) : TreeTraverser { override fun traverse(node: Node): Node = when (node) { is ScriptNode -> ScriptNode(node.currentNode, node.nodes.map { traverse(it) }) is LetConstantNode -> when { node.value is TermNode && node.type == null -> LetConstantNode(node.name, node.value.type, node.value) else -> node } is LetFunctionNode -> { val body = traverse(node.body) as TypedNode LetFunctionNode(node.name, node.parameters.map { ParameterNode(it.name, resolveType(it.type)) }, returnTypeOrBodyType(node), body) } is FunctionCallNode -> FunctionCallNode(node.receiver, node.parameters, "Boolean") is TermNode -> when { node.type == null -> TermNode(node.name, entityRegistry.resolveTypeOfConstant(node.name).qualifiedName()) else -> node } else -> node } private fun returnTypeOrBodyType(fn: LetFunctionNode): String { if (fn.returnType != null) { return resolveType(fn.returnType) } else { return fn.body.getType(entityRegistry).qualifiedName() } } private fun resolveType(name: String) = entityRegistry.resolveTypeByName(name).qualifiedName() }
middle-end/src/main/kotlin/io/sonatalang/snc/middleEnd/infrastructure/types/TypeResolver.kt
2169683888
/* * 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.impl import android.graphics.Canvas import android.graphics.ColorFilter import android.graphics.PixelFormat import android.graphics.Rect import android.graphics.drawable.Drawable import com.facebook.common.closeables.AutoCleanupDelegate import com.facebook.datasource.DataSource import com.facebook.drawee.drawable.VisibilityCallback import com.facebook.fresco.vito.core.FrescoDrawableInterface import com.facebook.fresco.vito.core.VitoImagePerfListener import com.facebook.fresco.vito.core.VitoImageRequest import com.facebook.fresco.vito.listener.ImageListener import com.facebook.fresco.vito.renderer.DrawableImageDataModel import java.io.Closeable import java.io.IOException class KFrescoVitoDrawable(val _imagePerfListener: VitoImagePerfListener = NopImagePerfListener()) : Drawable(), FrescoDrawableInterface { var _imageId: Long = 0 var _isLoading: Boolean = false override var callerContext: Any? = null var _visibilityCallback: VisibilityCallback? = null var _fetchSubmitted: Boolean = false val listenerManager: CombinedImageListenerImpl = CombinedImageListenerImpl() override var extras: Any? = null var viewportDimensions: Rect? = null var dataSource: DataSource<out Any>? by DataSourceCleanupDelegate() val releaseState = ImageReleaseScheduler.createReleaseState(this) private var hasBoundsSet = false override var imageRequest: VitoImageRequest? = null private val closeableCleanupFunction: (Closeable) -> Unit = { ImageReleaseScheduler.cancelAllReleasing(this) try { it.close() } catch (e: IOException) { // swallow } } var closeable: Closeable? by AutoCleanupDelegate(null, closeableCleanupFunction) override var refetchRunnable: Runnable? = null override val imageId: Long get() = _imageId override val imagePerfListener: VitoImagePerfListener get() = _imagePerfListener override fun setMutateDrawables(mutateDrawables: Boolean) { // No-op since we never mutate Drawables } override val actualImageDrawable: Drawable? get() { return when (val model = actualImageLayer.getDataModel()) { is DrawableImageDataModel -> model.drawable else -> null } } override fun hasImage(): Boolean = actualImageLayer.getDataModel() != null fun setFetchSubmitted(fetchSubmitted: Boolean) { _fetchSubmitted = fetchSubmitted } override val isFetchSubmitted: Boolean get() = _fetchSubmitted override fun setVisibilityCallback(visibilityCallback: VisibilityCallback?) { _visibilityCallback = visibilityCallback } override var imageListener: ImageListener? get() = listenerManager.imageListener set(value) { listenerManager.imageListener = value } override fun setOverlayDrawable(drawable: Drawable?): Drawable? { overlayImageLayer.apply { configure( dataModel = if (drawable == null) null else DrawableImageDataModel(drawable), roundingOptions = null, borderOptions = null) } return drawable } override fun setVisible(visible: Boolean, restart: Boolean): Boolean { _visibilityCallback?.onVisibilityChange(visible) return super.setVisible(visible, restart) } fun reset() { imageRequest?.let { listenerManager.onRelease(imageId, it, obtainExtras()) } imagePerfListener.onImageRelease(this) ImageReleaseScheduler.cancelAllReleasing(this) _imageId = 0 closeable = null dataSource = null imageRequest = null _isLoading = false callerContext = null placeholderLayer.reset() actualImageLayer.reset() progressLayer?.reset() overlayImageLayer.reset() debugOverlayImageLayer?.reset() hasBoundsSet = false listenerManager.onReset() listenerManager.imageListener = null } private var drawableAlpha: Int = 255 private var drawableColorFilter: ColorFilter? = null val callbackProvider: (() -> Callback?) = { callback } val invalidateLayerCallback: (() -> Unit) = { invalidateSelf() } val placeholderLayer = createLayer() val actualImageLayer = createLayer() var progressLayer: ImageLayerDataModel? = null val overlayImageLayer = createLayer() var debugOverlayImageLayer: ImageLayerDataModel? = null override fun draw(canvas: Canvas) { if (!hasBoundsSet) { setLayerBounds(bounds) } placeholderLayer.draw(canvas) actualImageLayer.draw(canvas) progressLayer?.draw(canvas) overlayImageLayer.draw(canvas) debugOverlayImageLayer?.draw(canvas) } override fun onBoundsChange(bounds: Rect) { super.onBoundsChange(bounds) setLayerBounds(bounds) } private fun setLayerBounds(bounds: Rect?) { if (bounds != null) { placeholderLayer.configure(bounds = bounds) actualImageLayer.configure(bounds = bounds) progressLayer?.configure(bounds = bounds) overlayImageLayer.configure(bounds = bounds) debugOverlayImageLayer?.configure(bounds = bounds) hasBoundsSet = true } } override fun setAlpha(alpha: Int) { drawableAlpha = alpha } override fun setColorFilter(colorFilter: ColorFilter?) { drawableColorFilter = colorFilter } // TODO(T105148151) Calculate opacity based on layers override fun getOpacity(): Int = PixelFormat.TRANSPARENT internal fun createLayer() = ImageLayerDataModel(callbackProvider, invalidateLayerCallback) }
vito/core-impl/src/main/java/com/facebook/fresco/vito/core/impl/KFrescoVitoDrawable.kt
3306100669
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.resolver import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.async import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.trySendBlocking import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout import kotlinx.coroutines.withTimeoutOrNull import org.gradle.kotlin.dsl.tooling.models.EditorReport import org.gradle.kotlin.dsl.tooling.models.KotlinBuildScriptModel import org.hamcrest.CoreMatchers.nullValue import org.hamcrest.CoreMatchers.sameInstance import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import java.io.File import java.util.concurrent.ArrayBlockingQueue import java.util.concurrent.TimeUnit import kotlin.coroutines.Continuation class KotlinBuildScriptModelRepositoryTest { @Test fun `cancels older requests before returning response to most recent request`() = runBlockingWithTimeout { // given: // Notice the project directory is never written to by the test so its path is immaterial val projectDir = File("/project-dir") val scriptFile = File(projectDir, "build.gradle.kts") /** * Request accepted into the queue. */ val acceptedRequest = Channel<KotlinBuildScriptModelRequest>(3) /** * Request taken off the queue awaiting for a response. */ val pendingRequest = Channel<KotlinBuildScriptModelRequest>(3) /** * Next response to [KotlinBuildScriptModelRepository.fetch]. */ val nextResponse = ArrayBlockingQueue<KotlinBuildScriptModel>(3) val subject = object : KotlinBuildScriptModelRepository() { override fun accept(request: KotlinBuildScriptModelRequest, k: Continuation<KotlinBuildScriptModel?>) { super.accept(request, k) acceptedRequest.trySendBlocking(request).getOrThrow() } override fun fetch(request: KotlinBuildScriptModelRequest): KotlinBuildScriptModel { pendingRequest.trySendBlocking(request).getOrThrow() return nextResponse.poll(defaultTestTimeoutMillis, TimeUnit.MILLISECONDS)!! } } fun newModelRequest() = KotlinBuildScriptModelRequest(projectDir, scriptFile) fun asyncResponseTo(request: KotlinBuildScriptModelRequest): Deferred<KotlinBuildScriptModel?> = async { subject.scriptModelFor(request) } // when: val pendingTasks = (0..2).map { index -> val request = newModelRequest() request to asyncResponseTo(request).also { assertThat( "Request is accepted", acceptedRequest.receive(), sameInstance(request) ) if (index == 0) { // wait for the first request to be taken off the queue // so the remaining requests are received while the request handler is busy assertThat( pendingRequest.receive(), sameInstance(request) ) } } } // submit the first response // this response should satisfy the very first request val resp1 = newModelResponse().also(nextResponse::put) val (_, asyncResp1) = pendingTasks[0] assertThat( asyncResp1.await(), sameInstance(resp1) ) // now we expect to receive the most recent request since the last request that got a response, // that's the last request in our list of pending tasks val (reqLast, asyncRespLast) = pendingTasks.last() assertThat( pendingRequest.receive(), sameInstance(reqLast) ) // submit the second (and last) response val respLast = newModelResponse().also(nextResponse::put) // upon receiving this response, the request handler will first complete // any and all outdated requests off the queue by responding with `null` val (_, asyncResp2) = pendingTasks[1] assertThat( asyncResp2.await(), nullValue() ) // only then the most recent request will be given its response assertThat( asyncRespLast.await(), sameInstance(respLast) ) // and no other requests are left to process assertThat( withTimeoutOrNull(50) { pendingRequest.receive() }, nullValue() ) } private fun newModelResponse(): KotlinBuildScriptModel = StandardKotlinBuildScriptModel() data class StandardKotlinBuildScriptModel( private val classPath: List<File> = emptyList(), private val sourcePath: List<File> = emptyList(), private val implicitImports: List<String> = emptyList(), private val editorReports: List<EditorReport> = emptyList(), private val exceptions: List<String> = emptyList(), private val enclosingScriptProjectDir: File? = null ) : KotlinBuildScriptModel { override fun getClassPath() = classPath override fun getSourcePath() = sourcePath override fun getImplicitImports() = implicitImports override fun getEditorReports() = editorReports override fun getExceptions() = exceptions override fun getEnclosingScriptProjectDir() = enclosingScriptProjectDir } } internal fun runBlockingWithTimeout(timeMillis: Long = defaultTestTimeoutMillis, block: suspend CoroutineScope.() -> Unit) { runBlocking { withTimeout(timeMillis, block) } } internal const val defaultTestTimeoutMillis = 5000L
subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/resolver/KotlinBuildScriptModelRepositoryTest.kt
3570083749
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 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.makeitso.common.composable import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.example.makeitso.common.ext.dropdownSelector @ExperimentalMaterialApi @Composable fun DangerousCardEditor( @StringRes title: Int, @DrawableRes icon: Int, content: String, modifier: Modifier, onEditClick: () -> Unit ) { CardEditor(title, icon, content, onEditClick, MaterialTheme.colors.primary, modifier) } @ExperimentalMaterialApi @Composable fun RegularCardEditor( @StringRes title: Int, @DrawableRes icon: Int, content: String, modifier: Modifier, onEditClick: () -> Unit ) { CardEditor(title, icon, content, onEditClick, MaterialTheme.colors.onSurface, modifier) } @ExperimentalMaterialApi @Composable private fun CardEditor( @StringRes title: Int, @DrawableRes icon: Int, content: String, onEditClick: () -> Unit, highlightColor: Color, modifier: Modifier ) { Card( backgroundColor = MaterialTheme.colors.onPrimary, modifier = modifier, onClick = onEditClick ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(16.dp) ) { Column(modifier = Modifier.weight(1f)) { Text(stringResource(title), color = highlightColor) } if (content.isNotBlank()) { Text(text = content, modifier = Modifier.padding(16.dp, 0.dp)) } Icon(painter = painterResource(icon), contentDescription = "Icon", tint = highlightColor) } } } @Composable @ExperimentalMaterialApi fun CardSelector( @StringRes label: Int, options: List<String>, selection: String, modifier: Modifier, onNewValue: (String) -> Unit ) { Card(backgroundColor = MaterialTheme.colors.onPrimary, modifier = modifier) { DropdownSelector(label, options, selection, Modifier.dropdownSelector(), onNewValue) } }
app/src/main/java/com/example/makeitso/common/composable/CardComposable.kt
3990724315
package com.jayrave.falkon.mapper import com.jayrave.falkon.mapper.exceptions.NameFormatException /** * Formats strings from camelCase to snake_case * * Examples: * - counter to counter * - intCounter to int_counter * - intCounter1 to int_counter_1 * */ class CamelCaseToSnakeCaseFormatter : NameFormatter { override fun format(input: String): String { return if (input.isEmpty()) { throw NameFormatException("Name is empty!! can't format") } else { val sb = StringBuilder(input.length + 4) // Some extra space for connectors sb.append(Character.toLowerCase(input.first())) for (index in 1..input.length - 1) { val ch = input[index] when { ch.isLetter() && ch.isUpperCase() -> sb.append("_${ch.toLowerCase()}") ch.isDigit() && !sb.last().isDigit() -> sb.append("_$ch") else -> sb.append(ch) } } sb.toString() } } }
falkon-mapper-basic/src/main/kotlin/com/jayrave/falkon/mapper/CamelCaseToSnakeCaseFormatter.kt
3141570553
package com.tlz.fragmentbuilder.annotation /** * * Created by Tomlezen. * Date: 2017/7/21. * Time: 11:07. */ class ArrayListCreator { companion object { fun <T> create(source: List<T>?): ArrayList<T> { if (source == null) { return ArrayList() } return ArrayList(source) } } }
annotations/src/main/java/com/tlz/fragmentbuilder/annotation/ArrayListCreator.kt
2400557206
package com.binlly.fastpeak.ext import com.binlly.fastpeak.service.Services /** * Created by yy on 2017/10/16. * Note:未经测试,比如添加的对象和移除的是否是同一个对象 */ fun <R> (() -> R).withDelay(delay: Long = 0L) { Services.postDelayed(delay) { this.invoke() } } fun <R> (() -> R).releaseDelay() { Services.removeRunnable { this } }
app/src/main/java/com/binlly/fastpeak/ext/FunctionExt.kt
795294162
package com.example.examplescomposemotionlayout import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.tween import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.layoutId import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.constraintlayout.compose.Dimension import androidx.constraintlayout.compose.ExperimentalMotionApi import androidx.constraintlayout.compose.MotionLayout import androidx.constraintlayout.compose.MotionScene /** * A demo of using MotionLayout in a Lazy Column written using DSL Syntax */ @OptIn(ExperimentalMotionApi::class) @Preview(group = "scroll", device = "spec:shape=Normal,width=480,height=800,unit=dp,dpi=440") @Composable fun MotionInLazyColumnDsl() { var scene = MotionScene() { val title = createRefFor("title") val image = createRefFor("image") val icon = createRefFor("icon") val start1 = constraintSet { constrain(title) { centerVerticallyTo(icon) start.linkTo(icon.end, 16.dp) } constrain(image) { width = Dimension.value(40.dp) height = Dimension.value(40.dp) centerVerticallyTo(icon) end.linkTo(parent.end, 8.dp) } constrain(icon) { top.linkTo(parent.top, 16.dp) bottom.linkTo(parent.bottom, 16.dp) start.linkTo(parent.start, 16.dp) } } val end1 = constraintSet { constrain(title) { bottom.linkTo(parent.bottom) start.linkTo(parent.start) scaleX = 0.7f scaleY = 0.7f } constrain(image) { width = Dimension.matchParent height = Dimension.value(200.dp) centerVerticallyTo(parent) } constrain(icon) { top.linkTo(parent.top, 16.dp) start.linkTo(parent.start, 16.dp) } } transition("default", start1, end1) {} } val model = remember { BooleanArray(100) } LazyColumn() { items(100) { // Text(text = "item $it", modifier = Modifier.padding(4.dp)) Box(modifier = Modifier.padding(3.dp)) { var animateToEnd by remember { mutableStateOf(model[it]) } val progress = remember { Animatable(if (model[it]) 1f else 0f) } LaunchedEffect(animateToEnd) { progress.animateTo( if (animateToEnd) 1f else 0f, animationSpec = tween(700) ) } MotionLayout( modifier = Modifier .background(Color(0xFF331B1B)) .fillMaxWidth() .padding(1.dp), motionScene = scene, progress = progress.value ) { Image( modifier = Modifier.layoutId("image"), painter = painterResource(R.drawable.bridge), contentDescription = null, contentScale = ContentScale.Crop ) Image( modifier = Modifier .layoutId("icon") .clickable { animateToEnd = !animateToEnd model[it] = animateToEnd; }, painter = painterResource(R.drawable.menu), contentDescription = null ) Text( modifier = Modifier.layoutId("title"), text = "San Francisco $it", fontSize = 30.sp, color = Color.White ) } } } } }
demoProjects/ExamplesComposeMotionLayout/app/src/main/java/com/example/examplescomposemotionlayout/MotionInLazyColumnDsl.kt
437622285
package io.magnaura.protocol open class Handle(val path: Path)
protocol/src/io/magnaura/protocol/Handle.kt
4207161992
package com.arcao.geocaching4locus.import_bookmarks.fragment import android.app.Activity import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.core.os.bundleOf import androidx.databinding.DataBindingUtil import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.paging.LoadState import androidx.recyclerview.widget.LinearLayoutManager import com.arcao.geocaching4locus.R import com.arcao.geocaching4locus.base.paging.handleErrors import com.arcao.geocaching4locus.base.util.exhaustive import com.arcao.geocaching4locus.base.util.invoke import com.arcao.geocaching4locus.base.util.withObserve import com.arcao.geocaching4locus.databinding.FragmentBookmarkListBinding import com.arcao.geocaching4locus.error.hasPositiveAction import com.arcao.geocaching4locus.import_bookmarks.ImportBookmarkViewModel import com.arcao.geocaching4locus.import_bookmarks.adapter.BookmarkListAdapter import com.arcao.geocaching4locus.import_bookmarks.widget.decorator.MarginItemDecoration import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import org.koin.androidx.viewmodel.ext.android.sharedViewModel import org.koin.androidx.viewmodel.ext.android.viewModel class BookmarkListFragment : BaseBookmarkFragment() { private val viewModel by viewModel<BookmarkListViewModel>() private val activityViewModel by sharedViewModel<ImportBookmarkViewModel>() private val toolbar get() = (activity as? AppCompatActivity)?.supportActionBar private val adapter = BookmarkListAdapter { bookmarkList, importAll -> if (importAll) { viewModel.importAll(bookmarkList) } else { viewModel.chooseBookmarks(bookmarkList) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { toolbar?.subtitle = null val binding = DataBindingUtil.inflate<FragmentBookmarkListBinding>( inflater, R.layout.fragment_bookmark_list, container, false ) binding.lifecycleOwner = viewLifecycleOwner binding.vm = viewModel binding.isLoading = true binding.list.apply { adapter = [email protected] layoutManager = LinearLayoutManager(context) addItemDecoration(MarginItemDecoration(context, R.dimen.cardview_space)) } viewLifecycleOwner.lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.RESUMED) { viewModel.pagerFlow.collectLatest { data -> adapter.submitData(data) } } } viewLifecycleOwner.lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.RESUMED) { adapter.loadStateFlow.collect { state -> val isListEmpty = state.refresh is LoadState.NotLoading && adapter.itemCount == 0 binding.isEmpty = isListEmpty binding.isLoading = state.source.refresh is LoadState.Loading state.handleErrors(viewModel::handleLoadError) } } } viewModel.action.withObserve(viewLifecycleOwner, ::handleAction) viewModel.progress.withObserve(viewLifecycleOwner) { state -> activityViewModel.progress(state) } return binding.root } @Suppress("IMPLICIT_CAST_TO_ANY") fun handleAction(action: BookmarkListAction) { when (action) { is BookmarkListAction.Error -> { startActivity(action.intent) requireActivity().apply { setResult( if (action.intent.hasPositiveAction()) { Activity.RESULT_OK } else { Activity.RESULT_CANCELED } ) finish() } } is BookmarkListAction.Finish -> { startActivity(action.intent) requireActivity().apply { setResult(Activity.RESULT_OK) finish() } } BookmarkListAction.Cancel -> { requireActivity().apply { setResult(Activity.RESULT_CANCELED) finish() } } is BookmarkListAction.ChooseBookmarks -> { activityViewModel.chooseBookmarks(action.geocacheList) } is BookmarkListAction.LoadingError -> { startActivity(action.intent) requireActivity().apply { if (adapter.itemCount == 0) { setResult(Activity.RESULT_CANCELED) finish() } } } }.exhaustive } override fun onProgressCancel(requestId: Int) { viewModel.cancelProgress() } companion object { fun newInstance() = BookmarkListFragment().apply { arguments = bundleOf() } } }
app/src/main/java/com/arcao/geocaching4locus/import_bookmarks/fragment/BookmarkListFragment.kt
2481023877
package com.ch3d.android.quicktiles import android.content.Intent import android.graphics.drawable.Icon import android.net.Uri import android.provider.Settings import android.service.quicksettings.Tile import android.service.quicksettings.TileService /** * Created by Dmitry on 6/20/2016. */ abstract class BaseTileService constructor(defaultState: TileState) : TileService() { companion object { const val DEFAULT_VALUE = -1 } private fun hasWriteSettingsPermission() = Settings.System.canWrite(this) protected var mCurrentState: TileState = defaultState override fun onStartListening() { if (hasWriteSettingsPermission()) { updateTile(qsTile) } } abstract fun updateTile(tile: Tile) protected fun updateState(tile: Tile, newState: TileState) { mCurrentState = newState setMode(mCurrentState) tile.apply { label = getString(mCurrentState.titleResId) icon = Icon.createWithResource(this@BaseTileService, mCurrentState.drawableId) state = newState.state updateTile() } } protected abstract fun setMode(state: TileState): Boolean override fun onClick() { if (!hasWriteSettingsPermission()) { startActivity(Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS) .apply { data = Uri.parse("package:" + applicationContext.packageName) flags = Intent.FLAG_ACTIVITY_NEW_TASK }) } else { onTileClick(qsTile) } } protected abstract fun onTileClick(tile: Tile) }
app/src/main/java/com/ch3d/android/quicktiles/BaseTileService.kt
1525083401
package com.kozhevin.rootchecks.data data class CheckInfo(var state: Boolean?, var typeCheck: Int)
appKotlin/src/main/java/com/kozhevin/rootchecks/data/CheckInfo.kt
2559880557