content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.move.moveFilesOrDirectories import com.intellij.openapi.application.runReadAction import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.refactoring.listeners.RefactoringElementListener import com.intellij.refactoring.move.moveClassesOrPackages.MoveDirectoryWithClassesHelper import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil import com.intellij.usageView.UsageInfo import com.intellij.util.Function import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.util.quoteIfNeeded import org.jetbrains.kotlin.idea.core.getFqNameWithImplicitPrefix import org.jetbrains.kotlin.idea.core.getPackage import org.jetbrains.kotlin.idea.refactoring.invokeOnceOnCommandFinish import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.KotlinDirectoryMoveTarget import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.MoveKotlinDeclarationsProcessor import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.analyzeConflictsInFile import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtFile class KotlinMoveDirectoryWithClassesHelper : MoveDirectoryWithClassesHelper() { private data class FileUsagesWrapper( val psiFile: KtFile, val usages: List<UsageInfo>, val moveDeclarationsProcessor: MoveKotlinDeclarationsProcessor? ) : UsageInfo(psiFile) private class MoveContext( val newParent: PsiDirectory, val moveDeclarationsProcessor: MoveKotlinDeclarationsProcessor? ) private val fileHandler = MoveKotlinFileHandler() private var fileToMoveContext: MutableMap<PsiFile, MoveContext>? = null private fun getOrCreateMoveContextMap(): MutableMap<PsiFile, MoveContext> { return fileToMoveContext ?: HashMap<PsiFile, MoveContext>().apply { fileToMoveContext = this invokeOnceOnCommandFinish { fileToMoveContext = null } } } override fun findUsages( filesToMove: MutableCollection<out PsiFile>, directoriesToMove: Array<out PsiDirectory>, result: MutableCollection<in UsageInfo>, searchInComments: Boolean, searchInNonJavaFiles: Boolean, project: Project ) { filesToMove .filterIsInstance<KtFile>() .mapTo(result) { FileUsagesWrapper(it, fileHandler.findUsages(it, null, false), null) } } override fun preprocessUsages( project: Project, files: MutableSet<PsiFile>, infos: Array<UsageInfo>, directory: PsiDirectory?, conflicts: MultiMap<PsiElement, String> ) { val psiPackage = directory?.getPackage() ?: return val moveTarget = KotlinDirectoryMoveTarget(FqName(psiPackage.qualifiedName), directory.virtualFile) for ((index, usageInfo) in infos.withIndex()) { if (usageInfo !is FileUsagesWrapper) continue ProgressManager.getInstance().progressIndicator?.text2 = KotlinBundle.message("text.processing.file.0", usageInfo.psiFile.name) runReadAction { analyzeConflictsInFile(usageInfo.psiFile, usageInfo.usages, moveTarget, files, conflicts) { infos[index] = usageInfo.copy(usages = it) } } } } override fun beforeMove(psiFile: PsiFile) { } // Actual move logic is implemented in postProcessUsages since usages are not available here override fun move( file: PsiFile, moveDestination: PsiDirectory, oldToNewElementsMapping: MutableMap<PsiElement, PsiElement>, movedFiles: MutableList<in PsiFile>, listener: RefactoringElementListener? ): Boolean { if (file !is KtFile) return false val moveDeclarationsProcessor = fileHandler.initMoveProcessor(file, moveDestination, false) val moveContextMap = getOrCreateMoveContextMap() moveContextMap[file] = MoveContext(moveDestination, moveDeclarationsProcessor) if (moveDeclarationsProcessor != null) { moveDestination.getFqNameWithImplicitPrefix()?.quoteIfNeeded()?.let { file.packageDirective?.fqName = it } } return true } override fun afterMove(newElement: PsiElement) { } override fun postProcessUsages(usages: Array<out UsageInfo>, newDirMapper: Function<in PsiDirectory, out PsiDirectory>) { val fileToMoveContext = fileToMoveContext ?: return try { val usagesToProcess = ArrayList<FileUsagesWrapper>() usages .filterIsInstance<FileUsagesWrapper>() .forEach body@{ val file = it.psiFile val moveContext = fileToMoveContext[file] ?: return@body MoveFilesOrDirectoriesUtil.doMoveFile(file, moveContext.newParent) val moveDeclarationsProcessor = moveContext.moveDeclarationsProcessor ?: return@body val movedFile = moveContext.newParent.findFile(file.name) ?: return@body usagesToProcess += FileUsagesWrapper(movedFile as KtFile, it.usages, moveDeclarationsProcessor) } usagesToProcess.forEach { fileHandler.retargetUsages(it.usages, it.moveDeclarationsProcessor!!) } } finally { this.fileToMoveContext = null } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveFilesOrDirectories/KotlinMoveDirectoryWithClassesHelper.kt
1542208539
// 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.plugins.github.api import com.intellij.collaboration.api.data.GraphQLRequestPagination import com.intellij.collaboration.api.dto.GraphQLConnectionDTO import com.intellij.collaboration.api.dto.GraphQLCursorPageInfoDTO import com.intellij.collaboration.api.dto.GraphQLNodesDTO import com.intellij.collaboration.api.dto.GraphQLPagedResponseDataDTO import com.intellij.diff.util.Side import org.jetbrains.plugins.github.api.GithubApiRequest.Post.GQLQuery import org.jetbrains.plugins.github.api.data.* import org.jetbrains.plugins.github.api.data.graphql.query.GHGQLSearchQueryResponse import org.jetbrains.plugins.github.api.data.pullrequest.* import org.jetbrains.plugins.github.api.data.pullrequest.timeline.GHPRTimelineItem import org.jetbrains.plugins.github.api.data.request.GHPullRequestDraftReviewComment import org.jetbrains.plugins.github.api.data.request.GHPullRequestDraftReviewThread import org.jetbrains.plugins.github.api.util.GHSchemaPreview object GHGQLRequests { object User { fun find(server: GithubServerPath, login: String): GQLQuery<GHUser?> { return GQLQuery.OptionalTraversedParsed(server.toGraphQLUrl(), GHGQLQueries.findUser, mapOf("login" to login), GHUser::class.java, "user") } } object Organization { object Team { fun findAll(server: GithubServerPath, organization: String, pagination: GraphQLRequestPagination? = null): GQLQuery<GraphQLPagedResponseDataDTO<GHTeam>> { return GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.findOrganizationTeams, mapOf("organization" to organization, "pageSize" to pagination?.pageSize, "cursor" to pagination?.afterCursor), TeamsConnection::class.java, "organization", "teams") } fun findByUserLogins(server: GithubServerPath, organization: String, logins: List<String>, pagination: GraphQLRequestPagination? = null): GQLQuery<GraphQLPagedResponseDataDTO<GHTeam>> = GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.findOrganizationTeams, mapOf("organization" to organization, "logins" to logins, "pageSize" to pagination?.pageSize, "cursor" to pagination?.afterCursor), TeamsConnection::class.java, "organization", "teams") private class TeamsConnection(pageInfo: GraphQLCursorPageInfoDTO, nodes: List<GHTeam>) : GraphQLConnectionDTO<GHTeam>(pageInfo, nodes) } } object Repo { fun find(repository: GHRepositoryCoordinates): GQLQuery<GHRepository?> { return GQLQuery.OptionalTraversedParsed(repository.serverPath.toGraphQLUrl(), GHGQLQueries.findRepository, mapOf("repoOwner" to repository.repositoryPath.owner, "repoName" to repository.repositoryPath.repository), GHRepository::class.java, "repository") } fun getProtectionRules(repository: GHRepositoryCoordinates, pagination: GraphQLRequestPagination? = null): GQLQuery<GraphQLPagedResponseDataDTO<GHBranchProtectionRule>> { return GQLQuery.TraversedParsed(repository.serverPath.toGraphQLUrl(), GHGQLQueries.getProtectionRules, mapOf("repoOwner" to repository.repositoryPath.owner, "repoName" to repository.repositoryPath.repository, "pageSize" to pagination?.pageSize, "cursor" to pagination?.afterCursor), ProtectedRulesConnection::class.java, "repository", "branchProtectionRules") } private class ProtectedRulesConnection(pageInfo: GraphQLCursorPageInfoDTO, nodes: List<GHBranchProtectionRule>) : GraphQLConnectionDTO<GHBranchProtectionRule>(pageInfo, nodes) } object Comment { fun updateComment(server: GithubServerPath, commentId: String, newText: String): GQLQuery<GHComment> = GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.updateIssueComment, mapOf("id" to commentId, "body" to newText), GHComment::class.java, "updateIssueComment", "issueComment") fun deleteComment(server: GithubServerPath, commentId: String): GQLQuery<Any?> = GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.deleteIssueComment, mapOf("id" to commentId), Any::class.java) } object PullRequest { fun create(repository: GHRepositoryCoordinates, repositoryId: String, baseRefName: String, headRefName: String, title: String, body: String? = null, draft: Boolean? = false): GQLQuery<GHPullRequestShort> { return GQLQuery.TraversedParsed(repository.serverPath.toGraphQLUrl(), GHGQLQueries.createPullRequest, mapOf("repositoryId" to repositoryId, "baseRefName" to baseRefName, "headRefName" to headRefName, "title" to title, "body" to body, "draft" to draft), GHPullRequestShort::class.java, "createPullRequest", "pullRequest").apply { acceptMimeType = GHSchemaPreview.PR_DRAFT.mimeType } } fun findOne(repository: GHRepositoryCoordinates, number: Long): GQLQuery<GHPullRequest?> { return GQLQuery.OptionalTraversedParsed(repository.serverPath.toGraphQLUrl(), GHGQLQueries.findPullRequest, mapOf("repoOwner" to repository.repositoryPath.owner, "repoName" to repository.repositoryPath.repository, "number" to number), GHPullRequest::class.java, "repository", "pullRequest").apply { acceptMimeType = GHSchemaPreview.PR_DRAFT.mimeType } } fun findByBranches(repository: GHRepositoryCoordinates, baseBranch: String, headBranch: String) : GQLQuery<GraphQLPagedResponseDataDTO<GHPullRequest>> = GQLQuery.TraversedParsed(repository.serverPath.toGraphQLUrl(), GHGQLQueries.findOpenPullRequestsByBranches, mapOf("repoOwner" to repository.repositoryPath.owner, "repoName" to repository.repositoryPath.repository, "baseBranch" to baseBranch, "headBranch" to headBranch), PullRequestsConnection::class.java, "repository", "pullRequests").apply { acceptMimeType = GHSchemaPreview.PR_DRAFT.mimeType } private class PullRequestsConnection(pageInfo: GraphQLCursorPageInfoDTO, nodes: List<GHPullRequest>) : GraphQLConnectionDTO<GHPullRequest>(pageInfo, nodes) fun update(repository: GHRepositoryCoordinates, pullRequestId: String, title: String?, description: String?): GQLQuery<GHPullRequest> { val parameters = mutableMapOf<String, Any>("pullRequestId" to pullRequestId) if (title != null) parameters["title"] = title if (description != null) parameters["body"] = description return GQLQuery.TraversedParsed(repository.serverPath.toGraphQLUrl(), GHGQLQueries.updatePullRequest, parameters, GHPullRequest::class.java, "updatePullRequest", "pullRequest").apply { acceptMimeType = GHSchemaPreview.PR_DRAFT.mimeType } } fun markReadyForReview(repository: GHRepositoryCoordinates, pullRequestId: String): GQLQuery<Any?> = GQLQuery.Parsed(repository.serverPath.toGraphQLUrl(), GHGQLQueries.markPullRequestReadyForReview, mutableMapOf<String, Any>("pullRequestId" to pullRequestId), Any::class.java).apply { acceptMimeType = GHSchemaPreview.PR_DRAFT.mimeType } fun mergeabilityData(repository: GHRepositoryCoordinates, number: Long): GQLQuery<GHPullRequestMergeabilityData?> = GQLQuery.OptionalTraversedParsed(repository.serverPath.toGraphQLUrl(), GHGQLQueries.pullRequestMergeabilityData, mapOf("repoOwner" to repository.repositoryPath.owner, "repoName" to repository.repositoryPath.repository, "number" to number), GHPullRequestMergeabilityData::class.java, "repository", "pullRequest").apply { acceptMimeType = "${GHSchemaPreview.CHECKS.mimeType},${GHSchemaPreview.PR_MERGE_INFO.mimeType}" } fun search(server: GithubServerPath, query: String, pagination: GraphQLRequestPagination? = null) : GQLQuery<GHGQLSearchQueryResponse<GHPullRequestShort>> { return GQLQuery.Parsed(server.toGraphQLUrl(), GHGQLQueries.issueSearch, mapOf("query" to query, "pageSize" to pagination?.pageSize, "cursor" to pagination?.afterCursor), PRSearch::class.java).apply { acceptMimeType = GHSchemaPreview.PR_DRAFT.mimeType } } private class PRSearch(search: SearchConnection<GHPullRequestShort>) : GHGQLSearchQueryResponse<GHPullRequestShort>(search) fun reviewThreads( repository: GHRepositoryCoordinates, number: Long, pagination: GraphQLRequestPagination? = null ): GQLQuery<GraphQLPagedResponseDataDTO<GHPullRequestReviewThread>> = GQLQuery.TraversedParsed( repository.serverPath.toGraphQLUrl(), GHGQLQueries.pullRequestReviewThreads, parameters(repository, number, pagination), ThreadsConnection::class.java, "repository", "pullRequest", "reviewThreads" ) private class ThreadsConnection(pageInfo: GraphQLCursorPageInfoDTO, nodes: List<GHPullRequestReviewThread>) : GraphQLConnectionDTO<GHPullRequestReviewThread>(pageInfo, nodes) fun commits( repository: GHRepositoryCoordinates, number: Long, pagination: GraphQLRequestPagination? = null ): GQLQuery<GraphQLPagedResponseDataDTO<GHPullRequestCommit>> = GQLQuery.TraversedParsed( repository.serverPath.toGraphQLUrl(), GHGQLQueries.pullRequestCommits, parameters(repository, number, pagination), CommitsConnection::class.java, "repository", "pullRequest", "commits" ) private class CommitsConnection(pageInfo: GraphQLCursorPageInfoDTO, nodes: List<GHPullRequestCommit>) : GraphQLConnectionDTO<GHPullRequestCommit>(pageInfo, nodes) fun files( repository: GHRepositoryCoordinates, number: Long, pagination: GraphQLRequestPagination ): GQLQuery<GraphQLPagedResponseDataDTO<GHPullRequestChangedFile>> = GQLQuery.TraversedParsed( repository.serverPath.toGraphQLUrl(), GHGQLQueries.pullRequestFiles, parameters(repository, number, pagination), FilesConnection::class.java, "repository", "pullRequest", "files" ) private class FilesConnection(pageInfo: GraphQLCursorPageInfoDTO, nodes: List<GHPullRequestChangedFile>) : GraphQLConnectionDTO<GHPullRequestChangedFile>(pageInfo, nodes) fun markFileAsViewed(server: GithubServerPath, pullRequestId: String, path: String): GQLQuery<Unit> = GQLQuery.TraversedParsed( server.toGraphQLUrl(), GHGQLQueries.markFileAsViewed, mapOf("pullRequestId" to pullRequestId, "path" to path), Unit::class.java ) fun unmarkFileAsViewed(server: GithubServerPath, pullRequestId: String, path: String): GQLQuery<Unit> = GQLQuery.TraversedParsed( server.toGraphQLUrl(), GHGQLQueries.unmarkFileAsViewed, mapOf("pullRequestId" to pullRequestId, "path" to path), Unit::class.java ) object Timeline { fun items(server: GithubServerPath, repoOwner: String, repoName: String, number: Long, pagination: GraphQLRequestPagination? = null) : GQLQuery<GraphQLPagedResponseDataDTO<GHPRTimelineItem>> { return GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.pullRequestTimeline, mapOf("repoOwner" to repoOwner, "repoName" to repoName, "number" to number, "pageSize" to pagination?.pageSize, "cursor" to pagination?.afterCursor, "since" to pagination?.since), TimelineConnection::class.java, "repository", "pullRequest", "timelineItems").apply { acceptMimeType = GHSchemaPreview.PR_DRAFT.mimeType } } private class TimelineConnection(pageInfo: GraphQLCursorPageInfoDTO, nodes: List<GHPRTimelineItem>) : GraphQLConnectionDTO<GHPRTimelineItem>(pageInfo, nodes) } object Review { fun create(server: GithubServerPath, pullRequestId: String, event: GHPullRequestReviewEvent?, body: String?, commitSha: String?, comments: List<GHPullRequestDraftReviewComment>?, threads: List<GHPullRequestDraftReviewThread>?): GQLQuery<GHPullRequestPendingReview> = GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.createReview, mapOf("pullRequestId" to pullRequestId, "event" to event, "commitOid" to commitSha, "comments" to comments, "threads" to threads, "body" to body), GHPullRequestPendingReview::class.java, "addPullRequestReview", "pullRequestReview") fun submit(server: GithubServerPath, reviewId: String, event: GHPullRequestReviewEvent, body: String?): GQLQuery<Any> = GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.submitReview, mapOf("reviewId" to reviewId, "event" to event, "body" to body), Any::class.java) fun updateBody(server: GithubServerPath, reviewId: String, newText: String): GQLQuery<GHPullRequestReview> = GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.updateReview, mapOf("reviewId" to reviewId, "body" to newText), GHPullRequestReview::class.java, "updatePullRequestReview", "pullRequestReview") fun delete(server: GithubServerPath, reviewId: String): GQLQuery<Any> = GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.deleteReview, mapOf("reviewId" to reviewId), Any::class.java) fun pendingReviews(server: GithubServerPath, pullRequestId: String): GQLQuery<GraphQLNodesDTO<GHPullRequestPendingReview>> { return GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.pendingReview, mapOf("pullRequestId" to pullRequestId), PendingReviewNodes::class.java, "node", "reviews") } private class PendingReviewNodes(nodes: List<GHPullRequestPendingReview>) : GraphQLNodesDTO<GHPullRequestPendingReview>(nodes) fun addComment(server: GithubServerPath, reviewId: String, body: String, commitSha: String, fileName: String, diffLine: Int) : GQLQuery<GHPullRequestReviewCommentWithPendingReview> = GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.addReviewComment, mapOf("reviewId" to reviewId, "body" to body, "commit" to commitSha, "file" to fileName, "position" to diffLine), GHPullRequestReviewCommentWithPendingReview::class.java, "addPullRequestReviewComment", "comment") fun addComment(server: GithubServerPath, reviewId: String, inReplyTo: String, body: String) : GQLQuery<GHPullRequestReviewCommentWithPendingReview> = GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.addReviewComment, mapOf("reviewId" to reviewId, "inReplyTo" to inReplyTo, "body" to body), GHPullRequestReviewCommentWithPendingReview::class.java, "addPullRequestReviewComment", "comment") fun deleteComment(server: GithubServerPath, commentId: String): GQLQuery<GHPullRequestPendingReview> = GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.deleteReviewComment, mapOf("id" to commentId), GHPullRequestPendingReview::class.java, "deletePullRequestReviewComment", "pullRequestReview") fun updateComment(server: GithubServerPath, commentId: String, newText: String): GQLQuery<GHPullRequestReviewComment> = GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.updateReviewComment, mapOf("id" to commentId, "body" to newText), GHPullRequestReviewComment::class.java, "updatePullRequestReviewComment", "pullRequestReviewComment") fun addThread(server: GithubServerPath, reviewId: String, body: String, line: Int, side: Side, startLine: Int, fileName: String): GQLQuery<GHPullRequestReviewThread> = GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.addPullRequestReviewThread, mapOf("body" to body, "line" to line, "path" to fileName, "pullRequestReviewId" to reviewId, "side" to side.name, "startSide" to side.name, "startLine" to startLine), GHPullRequestReviewThread::class.java, "addPullRequestReviewThread", "thread") fun resolveThread(server: GithubServerPath, threadId: String): GQLQuery<GHPullRequestReviewThread> = GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.resolveReviewThread, mapOf("threadId" to threadId), GHPullRequestReviewThread::class.java, "resolveReviewThread", "thread") fun unresolveThread(server: GithubServerPath, threadId: String): GQLQuery<GHPullRequestReviewThread> = GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.unresolveReviewThread, mapOf("threadId" to threadId), GHPullRequestReviewThread::class.java, "unresolveReviewThread", "thread") } } } private fun parameters( repository: GHRepositoryCoordinates, pullRequestNumber: Long, pagination: GraphQLRequestPagination? ): Map<String, Any?> = mapOf( "repoOwner" to repository.repositoryPath.owner, "repoName" to repository.repositoryPath.repository, "number" to pullRequestNumber, "pageSize" to pagination?.pageSize, "cursor" to pagination?.afterCursor )
plugins/github/src/org/jetbrains/plugins/github/api/GHGQLRequests.kt
135182714
// JS // FIX: none import react.State external <caret>class ExternalButClassExtendingState : State
plugins/kotlin/idea/tests/testData/inspectionsLocal/nonExternalClassifierExtendingStateOrProps/externalClassState.kt
3199396858
package org.stepik.android.presentation.course_list.mapper import ru.nobird.app.core.model.PagedList import org.stepik.android.domain.base.DataSourceType import org.stepik.android.domain.course.model.SourceTypeComposition import org.stepik.android.domain.course_list.model.CourseListItem import org.stepik.android.domain.course_list.model.CourseListQuery import org.stepik.android.presentation.course_list.CourseListQueryView import org.stepik.android.presentation.course_list.CourseListView import ru.nobird.app.core.model.safeCast import javax.inject.Inject class CourseListQueryStateMapper @Inject constructor() { fun mapToCourseListLoadedSuccess(query: CourseListQuery, items: PagedList<CourseListItem.Data>, source: SourceTypeComposition): CourseListQueryView.State.Data = CourseListQueryView.State.Data( query, courseListViewState = if (items.isNotEmpty()) { CourseListView.State.Content( courseListDataItems = items, courseListItems = items ) } else { CourseListView.State.Empty }, source.generalSourceType ) /** * Если мы находились в кеше, то при скролле до следующей страницы мы добавили фейковый [CourseListItem.PlaceHolder] в конец * Теперь, когда мы скачали страницу из сети мы можем проверить на наличие фейкового итема и скачать вторую страницу */ fun isNeedLoadNextPage(state: CourseListQueryView.State): Boolean { state as CourseListQueryView.State.Data val lastItem = state.courseListViewState .safeCast<CourseListView.State.Content>() ?.courseListItems ?.lastOrNull() return state.sourceType == DataSourceType.CACHE && lastItem is CourseListItem.PlaceHolder } }
app/src/main/java/org/stepik/android/presentation/course_list/mapper/CourseListQueryStateMapper.kt
412294186
import org.springframework.context.annotation.ComponentScan import org.springframework.boot.autoconfigure.EnableAutoConfiguration import kotlin.platform.platformStatic import org.springframework.boot.SpringApplication ComponentScan EnableAutoConfiguration public class Application { class object { platformStatic public fun main(args: Array<String>) { SpringApplication.run(javaClass<Application>(), *args) } } }
code/tutorials/spring-boot-restful/src/main/kotlin/Application.kt
3019827176
object Bob { fun hey(input: String): String { val trimmedInput = input.trim() return when { isSilence(trimmedInput) -> "Fine. Be that way!" isShoutedQuestion(trimmedInput) -> "Calm down, I know what I'm doing!" isShout(trimmedInput) -> "Whoa, chill out!" isQuestion(trimmedInput) -> "Sure." else -> "Whatever." } } private fun isSilence(input: String) = input.isBlank() private fun isQuestion(input: String) = input.endsWith("?") private fun isShout(input: String): Boolean { val isOnlyUppercase = input == input.uppercase() val hasLetter = input.contains(Regex("[A-Z]")) return hasLetter && isOnlyUppercase } private fun isShoutedQuestion(input: String) = isShout(input) && isQuestion(input) }
exercises/practice/bob/.meta/src/reference/kotlin/Bob.kt
2848960533
package behavioral import kotlin.properties.ObservableProperty import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty /** * Returns a property delegate for a read/write property that calls a specified callback function when changed. * @param initialValue the initial value of the property. * @param beforeChange the callback which is called before the change of the property. * @param afterChange the callback which is called after the change of the property is made. The value of the property * has already been changed when this callback is invoked. */ inline fun <T> observable(initialValue: T, crossinline beforeChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Boolean, crossinline afterChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Unit): ReadWriteProperty<Any?, T> = object : ObservableProperty<T>(initialValue) { override fun afterChange(property: KProperty<*>, oldValue: T, newValue: T) = afterChange(property, oldValue, newValue) override fun beforeChange(property: KProperty<*>, oldValue: T, newValue: T) = beforeChange(property, oldValue, newValue) } interface PropertyObserver { fun willChange(propertyName: String, newPropertyValue: Any?) fun didChange(propertyName: String, oldPropertyValue: Any?) } class Observer : PropertyObserver { override fun willChange(propertyName: String, newPropertyValue: Any?) { if (newPropertyValue is String && newPropertyValue == "test") { println("Okay. Look. We both said a lot of things that you're going to regret.") } } override fun didChange(propertyName: String, oldPropertyValue: Any?) { if (oldPropertyValue is String && oldPropertyValue == "<no name>") { println("Sorry about the mess. I've really let the place go since you killed me.") } } } class User(val propertyObserver: PropertyObserver?) { var name: String by observable("<no name>", { prop, old, new -> println("Before change: $old -> $new") propertyObserver?.willChange(name, new) return@observable true }, { prop, old, new -> propertyObserver?.didChange(name, old) println("After change: $old -> $new") }) } fun main(args: Array<String>) { val observer = Observer() val user = User(observer) user.name = "test" }
src/behavioral/Observer.kt
1271782149
/* * Copyright (c) 2017. Manuel Rebollo Báez * * 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.mrebollob.m2p.presentation.view.form import com.mrebollob.m2p.presentation.view.MvpView interface FormMvpView : MvpView { fun showCreditCard(number: String?, expDate: String?) fun showCardBalanceView() fun showInvalidCreditCardError() fun showError() }
app/src/main/java/com/mrebollob/m2p/presentation/view/form/FormMvpView.kt
1434030179
// 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.internal.statistic.eventLog import com.intellij.codeWithMe.ClientId import com.intellij.internal.statistic.collectors.fus.ActionPlaceHolder import com.intellij.internal.statistic.eventLog.StatisticsEventEscaper.escapeFieldName import com.intellij.internal.statistic.utils.PluginInfo import com.intellij.internal.statistic.utils.StatisticsUtil import com.intellij.internal.statistic.utils.addPluginInfoTo import com.intellij.internal.statistic.utils.getPluginInfo import com.intellij.lang.Language import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.Version import com.intellij.openapi.util.text.StringUtil import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.NonNls import java.awt.event.InputEvent import java.awt.event.KeyEvent import java.awt.event.MouseEvent import java.util.* private val LOG = logger<FeatureUsageData>() /** * <p>FeatureUsageData represents additional data for reported event.</p> * * <h3>Example</h3> * * <p>My usage collector collects actions invocations. <i>"my.foo.action"</i> could be invoked from one of the following contexts: * "main.menu", "context.menu", "my.dialog", "all-actions-run".</p> * * <p>If I write {@code FUCounterUsageLogger.logEvent("my.foo.action", "bar")}, I'll know how many times the action "bar" was invoked (e.g. 239)</p> * * <p>If I write {@code FUCounterUsageLogger.logEvent("my.foo.action", "bar", new FeatureUsageData().addPlace(place))}, I'll get the same * total count of action invocations (239), but I'll also know that the action was called 3 times from "main.menu", 235 times from "my.dialog" and only once from "context.menu". * <br/> * </p> */ @ApiStatus.Internal class FeatureUsageData(private val recorderId: String) { constructor() : this("FUS") private var data: MutableMap<String, Any> = HashMap() init { val clientId = ClientId.currentOrNull if (clientId != null && clientId != ClientId.defaultLocalId) { addClientId(clientId.value) } } companion object { // don't list "version" as "platformDataKeys" because it format depends a lot on the tool val platformDataKeys: List<String> = listOf("plugin", "project", "os", "plugin_type", "lang", "current_file", "input_event", "place", "file_path", "anonymous_id", "client_id") } fun addClientId(clientId: String?): FeatureUsageData { clientId?.let { val permanentClientId = parsePermanentClientId(clientId) data["client_id"] = EventLogConfiguration.getOrCreate(recorderId).anonymize(permanentClientId) } return this } private fun parsePermanentClientId(clientId: String): String { val separator = clientId.indexOf('-') if (separator > 0) { return clientId.substring(0, separator) } return clientId } /** * Project data is added automatically for project state collectors and project-wide counter events. * * @see com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector * @see com.intellij.internal.statistic.eventLog.events.EventId.log(Project) */ fun addProject(project: Project?): FeatureUsageData { if (project != null) { data["project"] = StatisticsUtil.getProjectId(project, recorderId) } return this } fun addVersionByString(@NonNls version: String?): FeatureUsageData { if (version == null) { data["version"] = "unknown" } else { addVersion(Version.parseVersion(version)) } return this } fun addVersion(@NonNls version: Version?): FeatureUsageData { data["version"] = if (version != null) "${version.major}.${version.minor}" else "unknown.format" return this } fun addPluginInfo(info: PluginInfo?): FeatureUsageData { info?.let { addPluginInfoTo(info, data) } return this } fun addLanguage(@NonNls id: String?): FeatureUsageData { id?.let { addLanguage(Language.findLanguageByID(id)) } return this } fun addLanguage(language: Language?): FeatureUsageData { return addLanguageInternal("lang", language) } fun addCurrentFile(language: Language?): FeatureUsageData { return addLanguageInternal("current_file", language) } private fun addLanguageInternal(fieldName: String, language: Language?): FeatureUsageData { language?.let { val type = getPluginInfo(language.javaClass) if (type.isSafeToReport()) { data[fieldName] = language.id } else { data[fieldName] = "third.party" } } return this } fun addInputEvent(event: InputEvent?, @NonNls place: String?): FeatureUsageData { val inputEvent = ShortcutDataProvider.getInputEventText(event, place) if (inputEvent != null && StringUtil.isNotEmpty(inputEvent)) { data["input_event"] = inputEvent } return this } fun addInputEvent(event: AnActionEvent?): FeatureUsageData { val inputEvent = ShortcutDataProvider.getActionEventText(event) if (inputEvent != null && StringUtil.isNotEmpty(inputEvent)) { data["input_event"] = inputEvent } return this } fun addInputEvent(event: KeyEvent): FeatureUsageData { val inputEvent = ShortcutDataProvider.getKeyEventText(event) if (inputEvent != null && StringUtil.isNotEmpty(inputEvent)) { data["input_event"] = inputEvent } return this } fun addInputEvent(event: MouseEvent): FeatureUsageData { val inputEvent = ShortcutDataProvider.getMouseEventText(event) if (inputEvent != null && StringUtil.isNotEmpty(inputEvent)) { data["input_event"] = inputEvent } return this } fun addPlace(@NonNls place: String?): FeatureUsageData { if (place == null) return this var reported = ActionPlaces.UNKNOWN if (isCommonPlace(place) || ActionPlaceHolder.isCustomActionPlace(place)) { reported = place } else if (ActionPlaces.isPopupPlace(place)) { reported = ActionPlaces.POPUP } data["place"] = reported return this } private fun isCommonPlace(place: String): Boolean { return ActionPlaces.isCommonPlace(place) || ActionPlaces.TOOLWINDOW_POPUP == place } fun addAnonymizedPath(@NonNls path: String?): FeatureUsageData { data["file_path"] = path?.let { EventLogConfiguration.getOrCreate(recorderId).anonymize(path) } ?: "undefined" return this } fun addAnonymizedId(@NonNls id: String): FeatureUsageData { data["anonymous_id"] = EventLogConfiguration.getOrCreate(recorderId).anonymize(id) return this } fun addAnonymizedValue(@NonNls key: String, @NonNls value: String?): FeatureUsageData { data[key] = value?.let { EventLogConfiguration.getOrCreate(recorderId).anonymize(value) } ?: "undefined" return this } fun addValue(value: Any): FeatureUsageData { if (value is String || value is Boolean || value is Int || value is Long || value is Float || value is Double) { return addDataInternal("value", value) } return addData("value", value.toString()) } fun addEnabled(enabled: Boolean): FeatureUsageData { return addData("enabled", enabled) } fun addCount(count: Int): FeatureUsageData { return addData("count", count) } /** * @param key can contain "-", "_", latin letters or digits. All not allowed symbols will be replaced with "_" or "?". */ fun addData(@NonNls key: String, value: Boolean): FeatureUsageData { return addDataInternal(key, value) } /** * @param key can contain "-", "_", latin letters or digits. All not allowed symbols will be replaced with "_" or "?". */ fun addData(@NonNls key: String, value: Int): FeatureUsageData { return addDataInternal(key, value) } /** * @param key can contain "-", "_", latin letters or digits. All not allowed symbols will be replaced with "_" or "?". */ fun addData(@NonNls key: String, value: Long): FeatureUsageData { return addDataInternal(key, value) } /** * @param key can contain "-", "_", latin letters or digits. All not allowed symbols will be replaced with "_" or "?". */ fun addData(@NonNls key: String, value: Float): FeatureUsageData { return addDataInternal(key, value) } /** * @param key can contain "-", "_", latin letters or digits. All not allowed symbols will be replaced with "_" or "?". */ fun addData(@NonNls key: String, value: Double): FeatureUsageData { return addDataInternal(key, value) } /** * @param key can contain "-", "_", latin letters or digits. All not allowed symbols will be replaced with "_" or "?". * @param value can contain "-", "_", ".", latin letters or digits. All not allowed symbols will be replaced with "_" or "?". */ fun addData(@NonNls key: String, @NonNls value: String): FeatureUsageData { return addDataInternal(key, value) } /** * The data reported by this method will be available ONLY for ad-hoc analysis. * * @param key key can contain "-", "_", latin letters or digits. All not allowed symbols will be replaced with "_" or "?". */ fun addData(@NonNls key: String, value: List<String>): FeatureUsageData { return addDataInternal(key, value) } /** * The data reported by this method will be available ONLY for ad-hoc analysis. * * @param key key can contain "-", "_", latin letters or digits. All not allowed symbols will be replaced with "_" or "?". */ internal fun addListLongData(@NonNls key: String, value: List<Long>): FeatureUsageData { return addDataInternal(key, value) } internal fun addObjectData(@NonNls key: String, value: Map<String, Any>): FeatureUsageData { return addDataInternal(key, value) } internal fun addListObjectData(@NonNls key: String, value: List<Map<String, Any>>): FeatureUsageData { return addDataInternal(key, value) } private fun addDataInternal(key: String, value: Any): FeatureUsageData { if (!ApplicationManager.getApplication().isUnitTestMode && platformDataKeys.contains(key)) { LOG.warn("Collectors should not reuse platform keys: $key") return this } val escapedKey = escapeFieldName(key) if (escapedKey != key) { LOG.warn("Key contains invalid symbols, they will be escaped: '$key' -> '$escapedKey'") } data[escapedKey] = value return this } fun build(): Map<String, Any> { if (data.isEmpty()) { return Collections.emptyMap() } return data } fun addAll(from: FeatureUsageData) : FeatureUsageData{ data.putAll(from.data) return this } fun merge(next: FeatureUsageData, @NonNls prefix: String): FeatureUsageData { for ((key, value) in next.build()) { val newKey = if (key.startsWith("data_")) "$prefix$key" else key data[newKey] = value } return this } fun copy(): FeatureUsageData { val result = FeatureUsageData() for ((key, value) in data) { result.data[key] = value } return result } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as FeatureUsageData if (data != other.data) return false return true } override fun hashCode(): Int { return data.hashCode() } override fun toString(): String { return data.toString() } }
platform/statistics/src/com/intellij/internal/statistic/eventLog/FeatureUsageData.kt
394474857
package io.fluidsonic.json public object BooleanArrayJsonCodec : AbstractJsonEncoderCodec<BooleanArray, JsonCodingContext>() { override fun JsonEncoder<JsonCodingContext>.encode(value: BooleanArray): Unit = writeList(value) }
coding/sources-jvm/codecs/basic/BooleanArrayJsonCodec.kt
2147602252
package com.aemtools.lang.java import com.aemtools.common.constant.const.java.POJO_USE import com.aemtools.common.constant.const.java.USE_INTERFACE import com.aemtools.common.constant.const.java.WCM_USE_CLASS import com.aemtools.service.IJavaSearchService import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.project.Project import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClass import com.intellij.psi.search.searches.AnnotatedElementsSearch import com.intellij.psi.search.searches.ClassInheritorsSearch /** * Utility object for java search. * * @author Dmytro Troynikov */ object JavaSearch { val USE_CLASSES = listOf(USE_INTERFACE, WCM_USE_CLASS, POJO_USE) /** * Search for [PsiClass] by qualified name with predefined "allScope". * * Shortcut for [JavaPsiFacade.findClass] * @param qualifiedName the full qualified name of class * @param project the project * @see JavaPsiFacade * @return [PsiClass] instance, __null__ if no instance was found */ fun findClass(qualifiedName: String, project: Project) : PsiClass? = service() ?.findClass(qualifiedName, project) /** * Search for inheritors of given [PsiClass]. * * Shortcut for [ClassInheritorsSearch.search] * @see ClassInheritorsSearch * @param psiClass the base class * @param project the project * @return list of inheritors of given class */ fun findInheritors(psiClass: PsiClass, project: Project): List<PsiClass> = service() ?.findInheritors(psiClass, project) ?: emptyList() /** * Search classes annotated by given annotation. * * Shortcut for [AnnotatedElementsSearch.searchPsiClasses] * @see AnnotatedElementsSearch * @param annotation the type of annotation * @param project the project * @return list of annotated classes */ fun findAnnotatedClasses(annotation: PsiClass, project: Project): List<PsiClass> = service() ?.findAnnotatedClasses(annotation, project) ?: emptyList() /** * Find all sling models in the project. * @param project the project * @return list of sling models */ fun findSlingModels(project: Project): List<PsiClass> = service() ?.findSlingModels(project) ?: emptyList() /** * Find all __io.sightly.java.api.Use__ and __com.adobe.cq.sightly.WCMUse__ * inheritors in given project. * @param project the project * @return list of inheritors */ fun findWcmUseClasses(project: Project): List<PsiClass> = service() ?.findWcmUseClasses(project) ?: emptyList() private fun service(): IJavaSearchService? = ServiceManager.getService(IJavaSearchService::class.java) }
aem-intellij-core/src/main/kotlin/com/aemtools/lang/java/JavaSearch.kt
101509874
package com.aemtools.documentation.htl import com.aemtools.test.documentation.BaseDocumentationTest import com.aemtools.test.documentation.model.IDocTestFixture /** * @author Dmytro Troynikov */ class HtlElDocumentationListHelperTest : BaseDocumentationTest(HtlELDocumentationProvider()) { fun testIndexDocumentation() = docCase { listField("index") documentation(""" zero-based counter (0..length-1) """) } fun testCountDocumentation() = docCase { listField("count") documentation(""" one-based counter (1..length) """) } fun testFirstDocumentation() = docCase { listField("first") documentation(""" <b>true</b> for the first element being iterated """) } fun testMiddleDocumentation() = docCase { listField("middle") documentation(""" <b>true</b> if element being iterated is neither the first nor the last """) } fun testLastDocumentation() = docCase { listField("last") documentation(""" <b>true</b> for the last element being iterated """) } fun testOddDocumentation() = docCase { listField("odd") documentation(""" <b>true</b> if index is odd """) } fun testEvenDocumentation() = docCase { listField("even") documentation(""" <b>true</b> if index is even """) } fun testDocForDataSlyRepeat() = docCase { addHtml("test.html", """ <div data-sly-repeat="$DOLLAR{}"> $DOLLAR{itemList.${CARET}index} </div> """) documentation(""" zero-based counter (0..length-1) """) } fun testDocRenamedItemListInDataSlyList() = docCase { addHtml("test.html", """ <div data-sly-list.renamed="$DOLLAR{}"> $DOLLAR{renamedList.${CARET}index} </div> """) documentation(""" zero-based counter (0..length-1) """) } fun testDocRenamedItemListInDataSlyRepeat() = docCase { addHtml("test.html", """ <div data-sly-repeat.renamed="$DOLLAR{}"> $DOLLAR{renamedList.${CARET}index} </div> """) documentation(""" zero-based counter (0..length-1) """) } private fun IDocTestFixture.listField(field: String) = addHtml("test.html", """ <div data-sly-list="$DOLLAR{}">$DOLLAR{itemList.$CARET$field}</div> """) }
aem-intellij-core/src/test/kotlin/com/aemtools/documentation/htl/HtlElDocumentationListHelperTest.kt
3574292156
package io.petros.posts.kotlin.model import android.arch.persistence.room.* @Entity(tableName = "post", foreignKeys = arrayOf( ForeignKey(entity = User::class, parentColumns = arrayOf("id"), childColumns = arrayOf("user_id"), onDelete = ForeignKey.CASCADE)), indices = arrayOf(Index(value = "user_id"))) data class Post(@PrimaryKey val id: String, @ColumnInfo(name = "user_id") val userId: String, val title: String, val body: String)
app/src/main/java/io/petros/posts/kotlin/model/Post.kt
3903156459
/* * Westford Wayland Compositor. * Copyright (C) 2016 Erik De Rijcke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.westford.compositor.core.events class TouchDown
compositor/src/main/kotlin/org/westford/compositor/core/events/TouchDown.kt
3252459775
package com.rightfromleftsw.weather.ui.test.factory.ui import java.util.concurrent.ThreadLocalRandom /** * Factory class for data instances */ class DataFactory { companion object Factory { fun randomUuid(): String { return java.util.UUID.randomUUID().toString() } fun randomInt(): Int { return ThreadLocalRandom.current().nextInt(0, 1000 + 1) } fun randomLong(): Long { return randomInt().toLong() } fun randomBoolean(): Boolean { return Math.random() < 0.5 } fun makeStringList(count: Int): List<String> { val items: MutableList<String> = mutableListOf() repeat(count) { items.add(randomUuid()) } return items } } }
mobile-ui/src/androidTest/java/com/rightfromleftsw/weather/ui/test/factory/DataFactory.kt
141149574
package test.setup import slatekit.apis.* import slatekit.apis.AuthModes import slatekit.apis.Verbs import slatekit.apis.ApiBase import slatekit.context.Context import slatekit.common.Sources import slatekit.connectors.entities.AppEntContext @Api(area = "app", name = "tests", desc = "sample to test features of Slate Kit APIs", auth = AuthModes.TOKEN, roles= ["admin"], verb = Verbs.AUTO, sources = [Sources.ALL]) class SampleApi(context: AppEntContext): ApiBase(context) { @Action(desc = "accepts supplied basic data types from send") fun defaultAnnotationValues(string1: String): String { return "$string1" } @Action(desc = "test partial override", auth = AuthModes.KEYED, roles= ["user"]) fun overridePartial(string1: String): String { return "$string1" } @Action(desc = "test overrides", auth = AuthModes.KEYED, roles= ["user"], sources = [Sources.CLI], access = AccessLevel.INTERNAL) fun overrideFull(string1: String): String { return "$string1" } } @Api(area = "app", name = "tests", desc = "sample to test features of Slate Kit APIs", roles= ["admin"]) class SampleApi1(val context: Context) { @Action(desc = "test simple action with inputs") @Documented(path = "docs/apis", key = "actions.tests.repeat") fun repeat(word: String, count:Int): String { return (0 until count).map { word }.joinToString(" ") } } @Api(area = "app", name = "tests", desc = "sample to test features of Slate Kit APIs", roles= ["admin"], auth = AuthModes.TOKEN, verb = Verbs.AUTO, access = AccessLevel.PUBLIC, sources = [Sources.ALL]) class SampleApi2(val context: Context) { @Action(desc = "test simple action with inputs") @Input(name = "word" , desc = "word to return back", required = true, examples = ["hello"]) @Input(name = "count", desc = "number of times to repeat", required = true, examples = ["3"]) fun repeat(word: String, count:Int): String { return (0 until count).map { word }.joinToString(" ") } }
src/lib/kotlin/slatekit-tests/src/test/kotlin/test/setup/SampleApi.kt
4146149576
// 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.externalSystem.autoimport import org.jetbrains.annotations.ApiStatus @ApiStatus.Experimental interface ExternalSystemProjectReloadContext { /** * Project reload is submitted explicitly for user * * Expected, project will be reloaded explicitly if this parameter is `true` */ val isExplicitReload: Boolean /** * Project has undefined modifications * Undefined modifications are modifications, provided by [ExternalSystemProjectTracker.markDirty] * e.g. changes in settings from UI, cache invalidation and etc. * * Project is expected to be fully reloaded when this flag is set to true */ val hasUndefinedModifications: Boolean /** * Reload context that describes modifications in settings files * @see [ExternalSystemProjectAware.settingsFiles] for details */ val settingsFilesContext: ExternalSystemSettingsFilesReloadContext }
platform/external-system-api/src/com/intellij/openapi/externalSystem/autoimport/ExternalSystemProjectReloadContext.kt
662815251
package com.jetbrains.packagesearch.intellij.plugin.api.model import com.google.gson.annotations.SerializedName import com.intellij.openapi.util.NlsSafe import com.jetbrains.packagesearch.intellij.plugin.api.RequiresWhitespaceCleanup internal data class StandardV2GitHub( @RequiresWhitespaceCleanup @SerializedName("description") @NlsSafe val description: String?, @SerializedName("is_fork") val isFork: Boolean?, @SerializedName("stars") val stars: Int?, @SerializedName("watchers") val watchers: Int?, @SerializedName("forks") val forks: Int?, @SerializedName("subscribers") val subscribers: Int?, @SerializedName("network") val network: Int?, @SerializedName("community_profile") val communityProfile: StandardV2GitHubCommunityProfile?, @SerializedName("last_checked") val lastChecked: Long ) internal data class StandardV2GitHubCommunityProfile( @SerializedName("files") val files: StandardV2GitHubCommunityProfileFiles, @SerializedName("documentation") val documentationUrl: String?, @RequiresWhitespaceCleanup @SerializedName("description") val description: String?, @SerializedName("health_percentage") val healthPercentage: Int ) internal data class StandardV2GitHubCommunityProfileFiles( @SerializedName("license") val license: StandardV2LinkedFile?, @SerializedName("readme") val readme: StandardV2LinkedFile?, @SerializedName("code_of_conduct") val codeOfConduct: StandardV2LinkedFile?, @SerializedName("contributing") val contributing: StandardV2LinkedFile? )
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/api/model/StandardV2GitHub.kt
581408658
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage import com.intellij.workspaceModel.storage.entities.* import com.intellij.workspaceModel.storage.entities.ModifiableSampleEntity import com.intellij.workspaceModel.storage.entities.ModifiableSecondSampleEntity import com.intellij.workspaceModel.storage.entities.SampleEntity import com.intellij.workspaceModel.storage.entities.SecondSampleEntity import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test class CollectChangesInBuilderTest { private lateinit var initialStorage: WorkspaceEntityStorage private lateinit var builder: WorkspaceEntityStorageBuilder @Before fun setUp() { initialStorage = createEmptyBuilder().apply { addSampleEntity("initial") addEntity(ModifiableSecondSampleEntity::class.java, SampleEntitySource("test")) { intProperty = 1 } }.toStorage() builder = createBuilderFrom(initialStorage) } @Test fun `add remove entity`() { builder.addSampleEntity("added") builder.addEntity(ModifiableSecondSampleEntity::class.java, SampleEntitySource("test")) { intProperty = 2 } builder.removeEntity(initialStorage.singleSampleEntity()) builder.removeEntity(initialStorage.entities(SecondSampleEntity::class.java).single()) @Suppress("UNCHECKED_CAST") val changes = builder.collectChanges(initialStorage).getValue(SampleEntity::class.java) as List<EntityChange<SampleEntity>> assertEquals(2, changes.size) val (change1, change2) = changes assertEquals("added", (change1 as EntityChange.Added).entity.stringProperty) assertEquals("initial", (change2 as EntityChange.Removed).entity.stringProperty) } @Test fun `modify entity`() { builder.modifyEntity(ModifiableSampleEntity::class.java, initialStorage.singleSampleEntity()) { stringProperty = "changed" } builder.modifyEntity(ModifiableSecondSampleEntity::class.java, initialStorage.entities(SecondSampleEntity::class.java).single()) { intProperty = 2 } @Suppress("UNCHECKED_CAST") val change = builder.collectChanges(initialStorage).getValue(SampleEntity::class.java).single() as EntityChange.Replaced<SampleEntity> assertEquals("changed", change.newEntity.stringProperty) assertEquals("initial", change.oldEntity.stringProperty) } @Test fun `modify modified entity`() { builder.modifyEntity(ModifiableSampleEntity::class.java, initialStorage.singleSampleEntity()) { stringProperty = "changed" } builder.modifyEntity(ModifiableSampleEntity::class.java, initialStorage.singleSampleEntity()) { stringProperty = "changed again" } val change = collectSampleEntityChanges().single() as EntityChange.Replaced assertEquals("changed again", change.newEntity.stringProperty) assertEquals("initial", change.oldEntity.stringProperty) } @Test fun `remove modified entity`() { val modified = builder.modifyEntity(ModifiableSampleEntity::class.java, initialStorage.singleSampleEntity()) { stringProperty = "changed" } builder.removeEntity(modified) assertEquals("initial", (collectSampleEntityChanges().single() as EntityChange.Removed).entity.stringProperty) } @Test fun `remove added entity`() { val added = builder.addSampleEntity("added") builder.removeEntity(added) assertTrue(collectSampleEntityChanges().isEmpty()) } @Test fun `modify added entity`() { val added = builder.addSampleEntity("added") builder.modifyEntity(ModifiableSampleEntity::class.java, added) { stringProperty = "changed" } assertEquals("changed", (collectSampleEntityChanges().single() as EntityChange.Added).entity.stringProperty) } @Test fun `removed modified added entity`() { val added = builder.addSampleEntity("added") val modified = builder.modifyEntity(ModifiableSampleEntity::class.java, added) { stringProperty = "changed" } builder.removeEntity(modified) assertTrue(collectSampleEntityChanges().isEmpty()) } @Suppress("UNCHECKED_CAST") private fun collectSampleEntityChanges(): List<EntityChange<SampleEntity>> { val changes = builder.collectChanges(initialStorage) if (changes.isEmpty()) return emptyList() return changes.entries.single().value as List<EntityChange<SampleEntity>> } }
platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/CollectChangesInBuilderTest.kt
3116229101
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.actions import com.intellij.application.options.editor.EditorTabsConfigurable import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.project.DumbAwareAction class ConfigureEditorTabsAction : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { ShowSettingsUtil.getInstance().showSettingsDialog(e.project, EditorTabsConfigurable::class.java) } }
platform/platform-impl/src/com/intellij/ide/actions/ConfigureEditorTabsAction.kt
1943352285
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT import kotlin.test.assertEquals interface Variance<A, in B, out C, D> class OneBound<T : Enum<T>> class SeveralBounds<T : Cloneable> where T : Enum<T>, T : Variance<String, Int?, Double?, Number> fun box(): String { assertEquals("[A, in B, out C, D]", Variance::class.typeParameters.toString()) assertEquals("[T]", OneBound::class.typeParameters.toString()) assertEquals("[T]", SeveralBounds::class.typeParameters.toString()) return "OK" }
backend.native/tests/external/codegen/box/reflection/methodsFromAny/typeParametersToString.kt
2093561316
class C() { companion object Foo } fun C.Foo.create() = 3 fun box(): String { val c1 = C.Foo.create() val c2 = C.create() return if (c1 == 3 && c2 == 3) "OK" else "fail" }
backend.native/tests/external/codegen/box/classes/extensionOnNamedClassObject.kt
2832807608
// WITH_RUNTIME fun exhaustive(x: Int): Int { var r: Int when (x) { 1 -> r = 1 2 -> r = 2 3 -> r = 3 else -> r = 4 } return r } fun nonExhaustive(x: Int): Int { var r: Int = 4 when (x) { 1 -> r = 1 2 -> r = 2 3 -> r = 3 } return r } fun box(): String { var result = (0..3).map(::exhaustive).joinToString() if (result != "4, 1, 2, 3") return "exhaustive:" + result result = (0..3).map(::nonExhaustive).joinToString() if (result != "4, 1, 2, 3") return "non-exhaustive:" + result return "OK" }
backend.native/tests/external/codegen/box/when/switchOptimizationStatement.kt
2478686071
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_RUNTIME fun check(x: Any?): Boolean { if (x is Int) { return x in 239..240 } throw java.lang.AssertionError() } fun check(x: Any?, l: Any?, r: Any?): Boolean { if (x is Int && l is Int && r is Int) { return x in l..r } throw java.lang.AssertionError() } fun box(): String { assert(check(239)) assert(check(239, 239, 240)) assert(!check(238)) assert(!check(238, 239, 240)) return "OK" }
backend.native/tests/external/codegen/box/ranges/contains/inRangeWithSmartCast.kt
3842469640
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.core.i18n.messageformat_icu.simple import androidx.core.i18n.DateTimeFormatter import java.text.DateFormat import java.text.FieldPosition import java.text.Format import java.text.ParseException import java.text.ParsePosition import java.util.Calendar import java.util.Date import java.util.Objects /** * Decorator for [DateTimeFormatter], because [MessageFormat] expects formatters that * extend [java.text.Format]. */ internal class DateTimeFormatterAsFormat(private val realFormatter: DateTimeFormatter) : Format() { override fun format( obj: Any, stringBuffer: StringBuffer, fieldPosition: FieldPosition ): StringBuffer { val result = when (obj) { is Date -> realFormatter.format(obj) is Calendar -> realFormatter.format(obj) is Long -> realFormatter.format(obj) else -> Objects.toString(obj) } return stringBuffer.append(result) } override fun parseObject(s: String, parsePosition: ParsePosition): Any { java.text.SimpleDateFormat.getDateInstance(DateFormat.LONG).parseObject("") throw ParseException("Parsing not implemented", 0) } }
core/core-i18n/src/main/java/androidx/core/i18n/messageformat_icu/simple/DateTimeFormatterAsFormat.kt
428523327
package com.peterlaurence.trekme.core.providers.urltilebuilder class UrlTileBuilderUSGS : UrlTileBuilder { override fun build(level: Int, row: Int, col: Int): String { return "https://basemap.nationalmap.gov/arcgis/rest/services/USGSTopo/MapServer/WMTS/tile/1.0.0/USGSTopo/default/GoogleMapsCompatible/$level/$row/$col" } }
app/src/main/java/com/peterlaurence/trekme/core/providers/urltilebuilder/UrlTileBuilderUSGS.kt
1842430423
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.runtime.collection import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue class MutableVectorTest { val list: MutableVector<Int> = mutableVectorOf(1, 2, 3, 4, 5) @Test fun emptyConstruction() { val l = mutableVectorOf<String>() assertEquals(0, l.size) assertEquals(16, l.content.size) repeat(16) { assertNull(l.content[it]) } } @Test fun sizeConstruction() { val l = MutableVector<String>(4) assertEquals(4, l.content.size) repeat(4) { assertNull(l.content[it]) } } @Test fun contentConstruction() { val l = mutableVectorOf("a", "b", "c") assertEquals(3, l.size) assertEquals("a", l[0]) assertEquals("b", l[1]) assertEquals("c", l[2]) assertEquals(3, l.content.size) repeat(2) { val l2 = mutableVectorOf(1, 2, 3, 4, 5) assertTrue(list.contentEquals(l2)) l2.removeAt(0) } } @Test fun initConstruction() { val l = MutableVector(5) { it + 1 } assertTrue(l.contentEquals(list)) } @Test fun get() { assertEquals(1, list[0]) assertEquals(5, list[4]) } @Test fun isEmpty() { assertFalse(list.isEmpty()) assertTrue(mutableVectorOf<String>().isEmpty()) } @Test fun isNotEmpty() { assertTrue(list.isNotEmpty()) assertFalse(mutableVectorOf<String>().isNotEmpty()) } @Test fun any() { assertTrue(list.any { it == 5 }) assertTrue(list.any { it == 1 }) assertFalse(list.any { it == 0 }) } @Test fun reversedAny() { val reversedList = mutableListOf<Int>() assertFalse( list.reversedAny { reversedList.add(it) false } ) assertEquals(reversedList, list.asMutableList().reversed()) val reversedSublist = mutableListOf<Int>() assertTrue( list.reversedAny { reversedSublist.add(it) reversedSublist.size == 2 } ) assertEquals(reversedSublist, listOf(5, 4)) } @Test fun forEach() { val copy = mutableVectorOf<Int>() list.forEach { copy += it } assertTrue(copy.contentEquals(list)) } @Test fun forEachReversed() { val copy = mutableVectorOf<Int>() list.forEachReversed { copy += it } assertTrue(copy.contentEquals(mutableVectorOf(5, 4, 3, 2, 1))) } @Test fun forEachIndexed() { val copy = mutableVectorOf<Int>() val indices = mutableVectorOf<Int>() list.forEachIndexed { index, item -> copy += item indices += index } assertTrue(copy.contentEquals(list)) assertTrue(indices.contentEquals(mutableVectorOf(0, 1, 2, 3, 4))) } @Test fun forEachReversedIndexed() { val copy = mutableVectorOf<Int>() val indices = mutableVectorOf<Int>() list.forEachReversedIndexed { index, item -> copy += item indices += index } assertTrue(copy.contentEquals(mutableVectorOf(5, 4, 3, 2, 1))) assertTrue(indices.contentEquals(mutableVectorOf(4, 3, 2, 1, 0))) } @Test fun indexOfFirst() { assertEquals(0, list.indexOfFirst { it == 1 }) assertEquals(4, list.indexOfFirst { it == 5 }) assertEquals(-1, list.indexOfFirst { it == 0 }) assertEquals(0, mutableVectorOf("a", "a").indexOfFirst { it == "a" }) } @Test fun indexOfLast() { assertEquals(0, list.indexOfLast { it == 1 }) assertEquals(4, list.indexOfLast { it == 5 }) assertEquals(-1, list.indexOfLast { it == 0 }) assertEquals(1, mutableVectorOf("a", "a").indexOfLast { it == "a" }) } @Test fun contains() { assertTrue(list.contains(5)) assertTrue(list.contains(1)) assertFalse(list.contains(0)) } @Test fun containsAllList() { assertTrue(list.containsAll(listOf(2, 3, 1))) assertFalse(list.containsAll(listOf(2, 3, 6))) } @Test fun containsAllVector() { assertTrue(list.containsAll(mutableVectorOf(2, 3, 1))) assertFalse(list.containsAll(mutableVectorOf(2, 3, 6))) } @Test fun containsAllCollection() { assertTrue(list.containsAll(setOf(2, 3, 1))) assertFalse(list.containsAll(setOf(2, 3, 6))) } @Test fun lastIndexOf() { assertEquals(4, list.lastIndexOf(5)) assertEquals(1, list.lastIndexOf(2)) val copy = mutableVectorOf<Int>() copy.addAll(list) copy.addAll(list) assertEquals(5, copy.lastIndexOf(1)) } @Test fun map() { val mapped = list.map { it - 1 } repeat(5) { assertEquals(it, mapped[it]) } assertEquals(5, mapped.size) } @Test fun mapIndexed() { val mapped = list.mapIndexed { index, item -> index + item } assertEquals(5, mapped.size) repeat(5) { assertEquals(it * 2 + 1, mapped[it]) } } @Test fun mapIndexedNotNull() { val mapped = list.mapIndexedNotNull { index, item -> if (item == 5) null else index + item } assertEquals(4, mapped.size) repeat(4) { assertEquals(it * 2 + 1, mapped[it]) } } @Test fun mapNotNull() { val mapped = list.mapNotNull { item -> if (item == 5) null else item - 1 } assertEquals(4, mapped.size) repeat(4) { assertEquals(it, mapped[it]) } } @Test fun first() { assertEquals(1, list.first()) } @Test fun firstException() { assertFailsWith(NoSuchElementException::class) { mutableVectorOf<String>().first() } } @Test fun firstOrNull() { assertEquals(1, list.firstOrNull()) assertNull(mutableVectorOf<Int>().firstOrNull()) } @Test fun firstWithPredicate() { assertEquals(5, list.first { it == 5 }) assertEquals(1, mutableVectorOf(1, 5).first { it != 0 }) } @Test fun firstWithPredicateException() { assertFailsWith(NoSuchElementException::class) { mutableVectorOf<String>().first { it == "Hello" } } } @Test fun firstOrNullWithPredicate() { assertEquals(5, list.firstOrNull { it == 5 }) assertNull(list.firstOrNull { it == 0 }) } @Test fun last() { assertEquals(5, list.last()) } @Test fun lastException() { assertFailsWith(NoSuchElementException::class) { mutableVectorOf<String>().last() } } @Test fun lastOrNull() { assertEquals(5, list.lastOrNull()) assertNull(mutableVectorOf<Int>().lastOrNull()) } @Test fun lastWithPredicate() { assertEquals(1, list.last { it == 1 }) assertEquals(5, mutableVectorOf(1, 5).last { it != 0 }) } @Test fun lastWithPredicateException() { assertFailsWith(NoSuchElementException::class) { mutableVectorOf<String>().last { it == "Hello" } } } @Test fun lastOrNullWithPredicate() { assertEquals(1, list.lastOrNull { it == 1 }) assertNull(list.lastOrNull { it == 0 }) } @Test fun sumBy() { assertEquals(15, list.sumBy { it }) } @Test fun fold() { assertEquals("12345", list.fold("") { acc, i -> acc + i.toString() }) } @Test fun foldIndexed() { assertEquals( "01-12-23-34-45-", list.foldIndexed("") { index, acc, i -> "$acc$index$i-" } ) } @Test fun foldRight() { assertEquals("54321", list.foldRight("") { i, acc -> acc + i.toString() }) } @Test fun foldRightIndexed() { assertEquals( "45-34-23-12-01-", list.foldRightIndexed("") { index, i, acc -> "$acc$index$i-" } ) } @Test fun add() { val l = mutableVectorOf(1, 2, 3) l += 4 l.add(5) assertTrue(l.contentEquals(list)) } @Test fun addAtIndex() { val l = mutableVectorOf(2, 4) l.add(2, 5) l.add(0, 1) l.add(2, 3) assertTrue(l.contentEquals(list)) } @Test fun addAllListAtIndex() { val l = listOf(4) val l2 = listOf(1, 2) val l3 = listOf(5) val l4 = mutableVectorOf(3) assertTrue(l4.addAll(1, l3)) assertTrue(l4.addAll(0, l2)) assertTrue(l4.addAll(3, l)) assertFalse(l4.addAll(0, emptyList())) assertTrue(l4.contentEquals(list)) } @Test fun addAllVectorAtIndex() { val l = mutableVectorOf(4) val l2 = mutableVectorOf(1, 2) val l3 = mutableVectorOf(5) val l4 = mutableVectorOf(3) assertTrue(l4.addAll(1, l3)) assertTrue(l4.addAll(0, l2)) assertTrue(l4.addAll(3, l)) assertFalse(l4.addAll(0, mutableVectorOf())) assertTrue(l4.contentEquals(list)) } @Test fun addAllList() { val l = listOf(3, 4, 5) val l2 = mutableVectorOf(1, 2) assertTrue(l2.addAll(l)) assertFalse(l2.addAll(emptyList())) } @Test fun addAllVector() { val l = MutableVector<Int>() l.add(3) l.add(4) l.add(5) val l2 = mutableVectorOf(1, 2) assertTrue(l2.addAll(l)) assertFalse(l2.addAll(mutableVectorOf())) } @Test fun addAllCollectionAtIndex() { val l = listOf(4) as Collection<Int> val l2 = listOf(1, 2) as Collection<Int> val l3 = listOf(5) as Collection<Int> val l4 = mutableVectorOf(3) assertTrue(l4.addAll(1, l3)) assertTrue(l4.addAll(0, l2)) assertTrue(l4.addAll(3, l)) assertFalse(l4.addAll(0, emptyList())) assertTrue(l4.contentEquals(list)) } @Test fun addAllCollection() { val l = listOf(3, 4, 5) as Collection<Int> val l2 = mutableVectorOf(1, 2) assertTrue(l2.addAll(l)) assertFalse(l2.addAll(emptyList())) } @Test fun addAllArray() { val a = arrayOf(3, 4, 5) val v = mutableVectorOf(1, 2) v.addAll(a) assertEquals(5, v.size) assertEquals(3, v[2]) assertEquals(4, v[3]) assertEquals(5, v[4]) } @Test fun clear() { val l = mutableVectorOf<Int>() l.addAll(list) assertTrue(l.isNotEmpty()) l.clear() assertTrue(l.isEmpty()) repeat(5) { assertNull(l.content[it]) } } @Test fun remove() { val l = mutableVectorOf(1, 2, 3, 4, 5) l.remove(3) assertTrue(l.contentEquals(mutableVectorOf(1, 2, 4, 5))) assertNull(l.content[4]) } @Test fun removeAt() { val l = mutableVectorOf(1, 2, 3, 4, 5) l.removeAt(2) assertTrue(l.contentEquals(mutableVectorOf(1, 2, 4, 5))) assertNull(l.content[4]) } @Test fun set() { val l = mutableVectorOf(0, 0, 0, 0, 0) l[0] = 1 l[4] = 5 l[2] = 3 l[1] = 2 l[3] = 4 assertTrue(l.contentEquals(list)) } @Test fun ensureCapacity() { val l = mutableVectorOf(1) assertEquals(1, l.content.size) l.ensureCapacity(5) assertEquals(5, l.content.size) } @Test fun removeAllList() { assertFalse(list.removeAll(listOf(0, 10, 15))) val l = mutableVectorOf(0, 1, 15, 10, 2, 3, 4, 5, 20, 5) assertTrue(l.removeAll(listOf(20, 0, 15, 10, 5))) assertTrue(l.contentEquals(list)) } @Test fun removeAllVector() { assertFalse(list.removeAll(mutableVectorOf(0, 10, 15))) val l = mutableVectorOf(0, 1, 15, 10, 2, 3, 4, 5, 20, 5) assertTrue(l.removeAll(mutableVectorOf(20, 0, 15, 10, 5))) assertTrue(l.contentEquals(list)) } @Test fun removeAllCollection() { assertFalse(list.removeAll(setOf(0, 10, 15))) val l = mutableVectorOf(0, 1, 15, 10, 2, 3, 4, 5, 20, 5) assertTrue(l.removeAll(setOf(20, 0, 15, 10, 5))) assertTrue(l.contentEquals(list)) } @Test fun retainAll() { assertFalse(list.retainAll(setOf(1, 2, 3, 4, 5, 6))) val l = mutableVectorOf(0, 1, 15, 10, 2, 3, 4, 5, 20) assertTrue(l.retainAll(setOf(1, 2, 3, 4, 5, 6))) assertTrue(l.contentEquals(list)) } @Test fun contentEquals() { assertTrue(list.contentEquals(mutableVectorOf(1, 2, 3, 4, 5))) assertFalse(list.contentEquals(mutableVectorOf(2, 1, 3, 4, 5))) assertFalse(list.contentEquals(mutableVectorOf(1, 2, 3, 4, 5, 6))) } @Test fun iterator() { val l = mutableVectorOf(1, 2, 3, 4, 5) val iterator = l.asMutableList().iterator() assertTrue(iterator.hasNext()) assertEquals(1, iterator.next()) assertTrue(iterator.hasNext()) assertEquals(2, iterator.next()) assertTrue(iterator.hasNext()) assertEquals(3, iterator.next()) assertTrue(iterator.hasNext()) iterator.remove() assertTrue(iterator.hasNext()) assertTrue(l.contentEquals(mutableVectorOf(1, 2, 4, 5))) assertEquals(4, iterator.next()) assertTrue(iterator.hasNext()) assertEquals(5, iterator.next()) assertFalse(iterator.hasNext()) iterator.remove() assertTrue(l.contentEquals(mutableVectorOf(1, 2, 4))) } @Test fun listIterator() { val l = mutableVectorOf(1, 2, 3, 4, 5) val iterator = l.asMutableList().listIterator() assertEquals(1, iterator.next()) assertEquals(1, iterator.previous()) assertEquals(0, iterator.nextIndex()) iterator.add(6) assertEquals(1, iterator.nextIndex()) assertEquals(0, iterator.previousIndex()) assertEquals(6, iterator.previous()) assertTrue(l.contentEquals(mutableVectorOf(6, 1, 2, 3, 4, 5))) } @Test fun listIteratorInitialIndex() { val iterator = list.asMutableList().listIterator(2) assertEquals(2, iterator.nextIndex()) } @Test fun subList() { val l = list.asMutableList().subList(1, 4) assertEquals(3, l.size) assertEquals(2, l[0]) assertEquals(3, l[1]) assertEquals(4, l[2]) } @Test fun subListContains() { val l = list.asMutableList().subList(1, 4) assertTrue(l.contains(2)) assertTrue(l.contains(3)) assertTrue(l.contains(4)) assertFalse(l.contains(5)) assertFalse(l.contains(1)) } @Test fun subListContainsAll() { val l = list.asMutableList().subList(1, 4) val smallList = listOf(2, 3, 4) assertTrue(l.containsAll(smallList)) val largeList = listOf(3, 4, 5) assertFalse(l.containsAll(largeList)) } @Test fun subListIndexOf() { val l = list.asMutableList().subList(1, 4) assertEquals(0, l.indexOf(2)) assertEquals(2, l.indexOf(4)) assertEquals(-1, l.indexOf(1)) val l2 = mutableVectorOf(2, 1, 1, 3).asMutableList().subList(1, 2) assertEquals(0, l2.indexOf(1)) } @Test fun subListIsEmpty() { val l = list.asMutableList().subList(1, 4) assertFalse(l.isEmpty()) assertTrue(list.asMutableList().subList(4, 4).isEmpty()) } @Test fun subListIterator() { val l = list.asMutableList().subList(1, 4) val l2 = mutableListOf<Int>() l.forEach { l2 += it } assertEquals(3, l2.size) assertEquals(2, l2[0]) assertEquals(3, l2[1]) assertEquals(4, l2[2]) } @Test fun subListLastIndexOf() { val l = list.asMutableList().subList(1, 4) assertEquals(0, l.lastIndexOf(2)) assertEquals(2, l.lastIndexOf(4)) assertEquals(-1, l.lastIndexOf(1)) val l2 = mutableVectorOf(2, 1, 1, 3).asMutableList().subList(1, 3) assertEquals(1, l2.lastIndexOf(1)) } @Test fun subListAdd() { val v = mutableVectorOf(1, 2, 3) val l = v.asMutableList().subList(1, 2) assertTrue(l.add(4)) assertEquals(2, l.size) assertEquals(4, v.size) assertEquals(2, l[0]) assertEquals(4, l[1]) assertEquals(2, v[1]) assertEquals(4, v[2]) assertEquals(3, v[3]) } @Test fun subListAddIndex() { val v = mutableVectorOf(6, 1, 2, 3) val l = v.asMutableList().subList(1, 3) l.add(1, 4) assertEquals(3, l.size) assertEquals(5, v.size) assertEquals(1, l[0]) assertEquals(4, l[1]) assertEquals(2, l[2]) assertEquals(1, v[1]) assertEquals(4, v[2]) assertEquals(2, v[3]) } @Test fun subListAddAllAtIndex() { val v = mutableVectorOf(6, 1, 2, 3) val l = v.asMutableList().subList(1, 3) l.addAll(1, listOf(4, 5)) assertEquals(4, l.size) assertEquals(6, v.size) assertEquals(1, l[0]) assertEquals(4, l[1]) assertEquals(5, l[2]) assertEquals(2, l[3]) assertEquals(1, v[1]) assertEquals(4, v[2]) assertEquals(5, v[3]) assertEquals(2, v[4]) } @Test fun subListAddAll() { val v = mutableVectorOf(6, 1, 2, 3) val l = v.asMutableList().subList(1, 3) l.addAll(listOf(4, 5)) assertEquals(4, l.size) assertEquals(6, v.size) assertEquals(1, l[0]) assertEquals(2, l[1]) assertEquals(4, l[2]) assertEquals(5, l[3]) assertEquals(1, v[1]) assertEquals(2, v[2]) assertEquals(4, v[3]) assertEquals(5, v[4]) assertEquals(3, v[5]) } @Test fun subListClear() { val v = mutableVectorOf(1, 2, 3, 4, 5) val l = v.asMutableList().subList(1, 4) l.clear() assertEquals(0, l.size) assertEquals(2, v.size) assertEquals(1, v[0]) assertEquals(5, v[1]) assertNull(v.content[2]) assertNull(v.content[3]) assertNull(v.content[4]) } @Test fun subListListIterator() { val l = list.asMutableList().subList(1, 4) val listIterator = l.listIterator() assertTrue(listIterator.hasNext()) assertFalse(listIterator.hasPrevious()) assertEquals(0, listIterator.nextIndex()) assertEquals(2, listIterator.next()) } @Test fun subListListIteratorWithIndex() { val l = list.asMutableList().subList(1, 4) val listIterator = l.listIterator(1) assertTrue(listIterator.hasNext()) assertTrue(listIterator.hasPrevious()) assertEquals(1, listIterator.nextIndex()) assertEquals(3, listIterator.next()) } @Test fun subListRemove() { val l = mutableVectorOf(1, 2, 3, 4, 5) val l2 = l.asMutableList().subList(1, 4) assertTrue(l2.remove(3)) assertTrue(l.contentEquals(mutableVectorOf(1, 2, 4, 5))) assertEquals(2, l2.size) assertEquals(2, l2[0]) assertEquals(4, l2[1]) assertFalse(l2.remove(3)) assertTrue(l.contentEquals(mutableVectorOf(1, 2, 4, 5))) assertEquals(2, l2.size) } @Test fun subListRemoveAll() { val l = mutableVectorOf(1, 2, 3, 4, 5) val l2 = l.asMutableList().subList(1, 4) assertFalse(l2.removeAll(listOf(1, 5, -1))) assertEquals(5, l.size) assertEquals(3, l2.size) assertTrue(l2.removeAll(listOf(3, 4, 5))) assertEquals(3, l.size) assertEquals(1, l2.size) } @Test fun subListRemoveAt() { val l = mutableVectorOf(1, 2, 3, 4, 5) val l2 = l.asMutableList().subList(1, 4) assertEquals(3, l2.removeAt(1)) assertEquals(4, l.size) assertEquals(2, l2.size) assertEquals(4, l2.removeAt(1)) assertEquals(1, l2.size) } @Test fun subListRetainAll() { val l = mutableVectorOf(1, 2, 3, 4, 5) val l2 = l.asMutableList().subList(1, 4) assertFalse(l2.retainAll(list.asMutableList())) assertFalse(l2.retainAll(listOf(2, 3, 4))) assertEquals(3, l2.size) assertEquals(5, l.size) assertTrue(l2.retainAll(setOf(1, 2, 4))) assertEquals(4, l.size) assertEquals(2, l2.size) assertTrue(l.contentEquals(mutableVectorOf(1, 2, 4, 5))) } @Test fun subListSet() { val l = mutableVectorOf(1, 2, 3, 4, 5) val l2 = l.asMutableList().subList(1, 4) l2[1] = 10 assertEquals(10, l2[1]) assertEquals(3, l2.size) assertEquals(10, l[2]) } @Test fun subListSubList() { val l = list.asMutableList().subList(1, 5) val l2 = l.subList(1, 3) assertEquals(2, l2.size) assertEquals(3, l2[0]) } @Test fun removeRange() { val l = mutableVectorOf(1, 2, 3, 4, 5) l.removeRange(1, 4) assertNull(l.content[2]) assertNull(l.content[3]) assertNull(l.content[4]) assertTrue(l.contentEquals(mutableVectorOf(1, 5))) val l2 = mutableVectorOf(1, 2, 3, 4, 5) l2.removeRange(3, 5) assertTrue(l2.contentEquals(mutableVectorOf(1, 2, 3))) l2.removeRange(3, 3) assertTrue(l2.contentEquals(mutableVectorOf(1, 2, 3))) } @Test fun sortWith() { val l = mutableVectorOf(1, 4, 2, 5, 3) l.sortWith(Comparator { p0, p1 -> p0 - p1 }) assertTrue(l.contentEquals(list)) } @Test fun list_outOfBounds_Get_Below() { assertFailsWith(IndexOutOfBoundsException::class) { val l = mutableVectorOf(1, 2, 3, 4).asMutableList() l[-1] } } @Test fun sublist_outOfBounds_Get_Below() { assertFailsWith(IndexOutOfBoundsException::class) { val l = mutableVectorOf(1, 2, 3, 4).asMutableList().subList(1, 2) l[-1] } } @Test fun list_outOfBounds_Get_Above() { assertFailsWith(IndexOutOfBoundsException::class) { val l = mutableVectorOf(1, 2, 3, 4).asMutableList() l[4] } } @Test fun sublist_outOfBounds_Get_Above() { assertFailsWith(IndexOutOfBoundsException::class) { val l = mutableVectorOf(1, 2, 3, 4).asMutableList().subList(1, 2) l[1] } } @Test fun list_outOfBounds_RemoveAt_Below() { assertFailsWith(IndexOutOfBoundsException::class) { val l = mutableVectorOf(0, 1, 2, 3).asMutableList() l.removeAt(-1) } } @Test fun sublist_outOfBounds_RemoveAt_Below() { assertFailsWith(IndexOutOfBoundsException::class) { val l = mutableVectorOf(0, 1, 2, 3).asMutableList().subList(1, 2) l.removeAt(-1) } } @Test fun list_outOfBounds_RemoveAt_Above() { assertFailsWith(IndexOutOfBoundsException::class) { val l = mutableVectorOf(0, 1, 2, 3).asMutableList() l.removeAt(4) } } @Test fun sublist_outOfBounds_RemoveAt_Above() { assertFailsWith(IndexOutOfBoundsException::class) { val l = mutableVectorOf(0, 1, 2, 3).asMutableList().subList(1, 2) l.removeAt(1) } } @Test fun list_outOfBounds_Set_Below() { assertFailsWith(IndexOutOfBoundsException::class) { val l = mutableVectorOf(0, 1, 2, 3).asMutableList() l[-1] = 1 } } @Test fun sublist_outOfBounds_Set_Below() { assertFailsWith(IndexOutOfBoundsException::class) { val l = mutableVectorOf(0, 1, 2, 3).asMutableList().subList(1, 2) l[-1] = 1 } } @Test fun list_outOfBounds_Set_Above() { assertFailsWith(IndexOutOfBoundsException::class) { val l = mutableVectorOf(0, 1, 2, 3).asMutableList() l[4] = 1 } } @Test fun sublist_outOfBounds_Set_Above() { assertFailsWith(IndexOutOfBoundsException::class) { val l = mutableVectorOf(0, 1, 2, 3).asMutableList().subList(1, 2) l[1] = 1 } } @Test fun list_outOfBounds_SubList_Below() { assertFailsWith(IndexOutOfBoundsException::class) { val l = mutableVectorOf(0, 1, 2, 3).asMutableList() l.subList(-1, 1) } } @Test fun sublist_outOfBounds_SubList_Below() { assertFailsWith(IndexOutOfBoundsException::class) { val l = mutableVectorOf(0, 1, 2, 3).asMutableList().subList(1, 2) l.subList(-1, 1) } } @Test fun list_outOfBounds_SubList_Above() { assertFailsWith(IndexOutOfBoundsException::class) { val l = mutableVectorOf(0, 1, 2, 3).asMutableList() l.subList(5, 5) } } @Test fun sublist_outOfBounds_SubList_Above() { assertFailsWith(IndexOutOfBoundsException::class) { val l = mutableVectorOf(0, 1, 2, 3).asMutableList().subList(1, 2) l.subList(1, 2) } } @Test fun list_outOfBounds_SubList_Order() { assertFailsWith(IllegalArgumentException::class) { val l = mutableVectorOf(0, 1, 2, 3).asMutableList() l.subList(3, 2) } } @Test fun sublist_outOfBounds_SubList_Order() { assertFailsWith(IllegalArgumentException::class) { val l = mutableVectorOf(0, 1, 2, 3).asMutableList().subList(1, 2) l.subList(1, 0) } } }
compose/runtime/runtime/src/commonTest/kotlin/androidx/compose/runtime/collection/MutableVectorTest.kt
4167964044
/* * This file is part of MythicDrops, licensed under the MIT License. * * Copyright (C) 2019 Richard Harrah * * Permission is hereby granted, free of charge, * to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.tealcube.minecraft.bukkit.mythicdrops.api.choices /** * Simple utility for making choices. */ open class Choice<T> { companion object { /** * Constructs a [Choice] for the given [option]. * * @param option Option(s) for choice. * @return constructed choice */ @JvmStatic fun <T> between(vararg option: T): Choice<T> = between(option.asIterable()) /** * Constructs a [Choice] for the given [option]. * * @param option Option(s) for choice. * @return constructed choice */ @JvmStatic fun <T> between(options: Iterable<T>): Choice<T> = Choice<T>().also { it.addOptions(options) } } protected val options = mutableSetOf<T>() /** * Adds an option to the available options when choosing. * * @param option Option to add * @return if adding was successful */ fun addOption(option: T) = options.add(option) /** * Adds options to the available options when choosing. * * @param option Option to add * @return if adding was successful */ fun addOptions(vararg option: T) = options.addAll(option) /** * Adds options to the available options when choosing. * * @param pOptions Options to add * @return if adding was successful */ fun addOptions(pOptions: Iterable<T>) = options.addAll(pOptions) /** * Chooses one of the available options and returns it. * * @param block Extra block to execute to determine if option is selectable * @return chosen option or null if one cannot be chosen */ open fun choose(): T? { if (options.isEmpty()) { return null } return options.random() } }
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/api/choices/Choice.kt
2212635467
package a val c: Int = 1 var b: Int = 0 <selection>fun f() = c + b</selection>
plugins/kotlin/idea/tests/testData/copyPaste/imports/TopLevelProperty.kt
3453088516
// IS_APPLICABLE: false // WITH_STDLIB fun test() { J().<caret>setR(::test) }
plugins/kotlin/idea/tests/testData/intentions/usePropertyAccessSyntax/setFunctionReferenceArgument.kt
1583410031
// FLOW: OUT fun String.foo(<caret>p: String) { val v = bar(p) { this } } fun <T, R> bar(receiver: T, block: T.() -> R): R { val b = block return receiver.b() }
plugins/kotlin/idea/tests/testData/slicer/outflow/invokeExtensionLambda3.kt
391187324
// "Replace with 'gau()'" "true" package test @Deprecated("...", ReplaceWith("gau()", "test.dependency.gau")) fun gau() { test.dependency.gau() } fun use() { <caret>gau() }
plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/imports/addImportsWithSameName.before.Main.kt
590664662
package c import a.* fun bar() { val t: A = A() foo() println(x) x = "" }
plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/movePackage/movePackage/before/c/onDemandImport.kt
894233739
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.builtInHelp.search import com.google.gson.Gson import com.intellij.openapi.diagnostic.Logger import org.apache.commons.compress.utils.IOUtils import org.apache.lucene.analysis.standard.StandardAnalyzer import org.apache.lucene.index.DirectoryReader import org.apache.lucene.search.spell.LuceneDictionary import org.apache.lucene.search.suggest.analyzing.BlendedInfixSuggester import org.apache.lucene.store.FSDirectory import org.jetbrains.annotations.NotNull import java.io.FileOutputStream import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import org.jetbrains.annotations.NonNls class HelpComplete { companion object { val resources = arrayOf("_0.cfe", "_0.cfs", "_0.si", "segments_1") @NonNls val PREFIX = "/search/" @NonNls val NOT_FOUND = "[]" private val analyzer: StandardAnalyzer = StandardAnalyzer() @NotNull fun complete(query: String, maxHits: Int): String { val indexDir: Path? = Files.createTempDirectory("search-index") var indexDirectory: FSDirectory? = null var reader: DirectoryReader? = null var suggester: BlendedInfixSuggester? = null if (indexDir != null) try { for (resourceName in resources) { val input = HelpSearch::class.java.getResourceAsStream( PREFIX + resourceName) val fos: FileOutputStream = FileOutputStream(Paths.get(indexDir.toAbsolutePath().toString(), resourceName).toFile()) IOUtils.copy(input, fos) fos.flush() fos.close() input.close() } indexDirectory = FSDirectory.open(indexDir) reader = DirectoryReader.open(indexDirectory) suggester = BlendedInfixSuggester(indexDirectory, analyzer) suggester.build(LuceneDictionary(reader, "contents")) val completionResults = suggester.lookup(query, maxHits, false, true) return Gson().toJson(completionResults) } catch (e: Exception) { Logger.getInstance(HelpComplete::class.java).error("Error searching help for $query", e) } finally { suggester?.close() indexDirectory?.close() reader?.close() for (f in indexDir.toFile().listFiles()) f.delete() Files.delete(indexDir) } return NOT_FOUND } } }
plugins/built-in-help/src/com/jetbrains/builtInHelp/search/HelpComplete.kt
66054804
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.configurationStore import com.intellij.configurationStore.* import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.util.JDOMUtil import org.jdom.Element import org.jetbrains.jps.model.serialization.SerializationConstants internal class ExternalModuleStorage(private val module: Module, storageManager: StateStorageManager) : XmlElementStorage(StoragePathMacros.MODULE_FILE, "module", storageManager.macroSubstitutor, RoamingType.DISABLED) { private val manager = StreamProviderFactory.EP_NAME.getExtensions(module.project).first { it is ExternalSystemStreamProviderFactory } as ExternalSystemStreamProviderFactory override fun loadLocalData() = manager.readModuleData(module.name) override fun createSaveSession(states: StateMap) = object : XmlElementStorageSaveSession<ExternalModuleStorage>(states, this) { override fun saveLocally(element: Element?) { manager.moduleStorage.write(module.name, element) } } } internal open class ExternalProjectStorage @JvmOverloads constructor(fileSpec: String, project: Project, storageManager: StateStorageManager, rootElementName: String? = ProjectStateStorageManager.ROOT_TAG_NAME /* several components per file */) : XmlElementStorage(fileSpec, rootElementName, storageManager.macroSubstitutor, RoamingType.DISABLED) { protected val manager = StreamProviderFactory.EP_NAME.getExtensions(project).first { it is ExternalSystemStreamProviderFactory } as ExternalSystemStreamProviderFactory override final fun loadLocalData() = manager.fileStorage.read(fileSpec) override fun createSaveSession(states: StateMap) = object : XmlElementStorageSaveSession<ExternalProjectStorage>(states, this) { override fun saveLocally(element: Element?) { manager.fileStorage.write(fileSpec, element) } } } // for libraries only for now - we use null rootElementName because the only component is expected (libraryTable) internal class ExternalProjectFilteringStorage(fileSpec: String, project: Project, storageManager: StateStorageManager) : ExternalProjectStorage(fileSpec, project, storageManager, null /* the only component per file */) { override fun createSaveSession(states: StateMap) = object : XmlElementStorageSaveSession<ExternalProjectStorage>(states, this) { override fun saveLocally(element: Element?) { if (element == null || !element.children.any { it.isMarkedAsExternal() }) { manager.fileStorage.remove(fileSpec) } else { manager.fileStorage.write(fileSpec, element, JDOMUtil.ElementOutputFilter { childElement, level -> level != 1 || childElement.isMarkedAsExternal() }) } } } } private fun Element.isMarkedAsExternal() = getAttribute(SerializationConstants.EXTERNAL_SYSTEM_ID_ATTRIBUTE) != null
platform/external-system-impl/src/com/intellij/openapi/externalSystem/configurationStore/ExternalSystemStorage.kt
2335115288
// HIGHLIGHT: INFORMATION fun test(n: Int): String { if (n == 1) return "one" else <caret>return "two" }
plugins/kotlin/idea/tests/testData/inspectionsLocal/liftOut/ifToReturn/onReturn2.kt
2527806117
open class A { open var p: Int = 1 } class AA : A() { override var p: Int = 1 } class B : J() { override var p: Int = 1 } fun test() { val t = A().p A().p = 1 val t2 = AA().p AA().p = 1 val t3 = J().p J().p = 1 val t4 = B().p B().p = 1 }
plugins/kotlin/idea/tests/testData/findUsages/java/findJavaPropertyUsages/javaPropertySetterUsagesKJ.1.kt
1216419621
package com.lapismc.minecraft.yggdrasil /** * Information about an authenticated user for a client. * @param profile Selected profile used for the session. * @param tokenPair Client and access token pair used for authentication. */ data class Session(val profile: Profile, val tokenPair: TokenPair)
src/main/kotlin/com/lapismc/minecraft/yggdrasil/Session.kt
1790179232
package info.nightscout.androidaps.plugins.general.persistentNotification import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.Build import android.os.IBinder import androidx.annotation.RequiresApi import info.nightscout.androidaps.interfaces.NotificationHolderInterface import javax.inject.Inject import javax.inject.Singleton /* This code replaces following val alarm = Intent(context, DummyService::class.java) alarm.putExtra("soundid", n.soundId) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(alarm) else context.startService(alarm) it fails randomly with error Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{e317f7e u0 info.nightscout.nsclient/info.nightscout.androidaps.services.DummyService} */ @RequiresApi(Build.VERSION_CODES.O) @Singleton class DummyServiceHelper @Inject constructor( private val notificationHolder: NotificationHolderInterface ) { fun startService(context: Context) { val connection = object : ServiceConnection { override fun onServiceConnected(name: ComponentName?, service: IBinder?) { // The binder of the service that returns the instance that is created. val binder: DummyService.LocalBinder = service as DummyService.LocalBinder val dummyService: DummyService = binder.getService() context.startForegroundService(Intent(context, DummyService::class.java)) // This is the key: Without waiting Android Framework to call this method // inside Service.onCreate(), immediately call here to post the notification. dummyService.startForeground(notificationHolder.notificationID, notificationHolder.notification) // Release the connection to prevent leaks. context.unbindService(this) } override fun onServiceDisconnected(name: ComponentName?) { } } try { context.bindService(Intent(context, DummyService::class.java), connection, Context.BIND_AUTO_CREATE) } catch (ignored: RuntimeException) { // This is probably a broadcast receiver context even though we are calling getApplicationContext(). // Just call startForegroundService instead since we cannot bind a service to a // broadcast receiver context. The service also have to call startForeground in // this case. context.startForegroundService(Intent(context, DummyService::class.java)) } } fun stopService(context: Context) { context.stopService(Intent(context, DummyService::class.java)) } }
app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyServiceHelper.kt
1211350860
package com.tonicartos.superslim.internal.layout import com.tonicartos.superslim.LayoutHelper import com.tonicartos.superslim.SectionLayoutManager import com.tonicartos.superslim.internal.SectionState import com.tonicartos.superslim.internal.SectionState.LayoutState import com.tonicartos.superslim.internal.SectionState.PaddingLayoutState import com.tonicartos.superslim.internal.SectionState.PaddingLayoutState.Companion.BOTTOM_ADDED import com.tonicartos.superslim.internal.SectionState.PaddingLayoutState.Companion.TOP_ADDED internal object PaddingLayoutManager : SectionLayoutManager<SectionState> { override fun isAtTop(section: SectionState, layoutState: LayoutState): Boolean { val state = layoutState as PaddingLayoutState return state.overdraw == 0 && state.paddingTop > 0 || section.atTop } override fun onLayout(helper: LayoutHelper, section: SectionState, layoutState: LayoutState) { val state = layoutState as PaddingLayoutState state.paddingTop = helper.paddingTop state.paddingBottom = helper.paddingBottom if (state.paddingTop > 0) { if (state.onScreen && state flagUnset TOP_ADDED && state.overdraw > 0) { // Must be in a layout pass with requested position. state set TOP_ADDED } else if (!state.onScreen) { state.overdraw = 0 state set TOP_ADDED } } state.onScreen = true var y = if (state flagSet TOP_ADDED) state.paddingTop - state.overdraw else 0 section.layout(helper, section.leftGutter { 0 }, y, helper.layoutWidth - section.rightGutter { 0 }) state.disappearedOrRemovedHeight += section.disappearedHeight y += section.height helper.filledArea += section.height if (state.paddingBottom > 0 && y < helper.layoutLimit) { state set BOTTOM_ADDED y += helper.paddingBottom } state.bottom = y } override fun onFillTop(dy: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState): Int { val state = layoutState as PaddingLayoutState var toFill = dy - state.overdraw if (state.paddingBottom > 0 && !state.onScreen) { state.paddingTop = helper.paddingTop state.paddingBottom = helper.paddingBottom // Add bottom padding. val filled = state.paddingBottom state.overdraw += filled toFill -= filled state set BOTTOM_ADDED } state.onScreen = true // Add content. state.overdraw += section.fillTop(Math.max(0, toFill), section.leftGutter { 0 }, -state.overdraw, helper.layoutWidth - section.rightGutter { 0 }, helper) if (state.paddingTop > 0 && state flagUnset TOP_ADDED && state.overdraw < dy) { // Add top padding. state.overdraw += state.paddingTop state set TOP_ADDED } val filled = Math.min(dy, state.overdraw) state.overdraw -= filled state.bottom += filled return filled } override fun onFillBottom(dy: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState): Int { val state = layoutState as PaddingLayoutState var filled = 0 if (state.paddingTop > 0 && !state.onScreen) { state.paddingBottom = helper.paddingBottom state.paddingTop = helper.paddingTop // Add top padding. filled += state.paddingTop state.bottom = state.paddingTop state.overdraw = 0 state set TOP_ADDED } state.onScreen = true val y = if (state flagSet TOP_ADDED) state.paddingTop - state.overdraw else 0 // Add content val before = section.height filled += section.fillBottom(dy, section.leftGutter { 0 }, y, helper.layoutWidth - section.rightGutter { 0 }, helper) state.bottom += section.height - before if (state.paddingBottom > 0 && filled < dy) { if (state flagUnset BOTTOM_ADDED) { // Add bottom padding. filled += state.paddingBottom state.bottom += state.paddingBottom state set BOTTOM_ADDED } else { filled += Math.max(0, state.bottom - helper.layoutLimit) } } return Math.min(dy, filled) } override fun onTrimTop(scrolled: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState): Int { val state = layoutState as PaddingLayoutState var removedHeight = 0 var contentTop = 0 if (state flagSet TOP_ADDED) { val before = state.overdraw state.overdraw = Math.min(state.paddingTop, state.overdraw + scrolled) removedHeight += state.overdraw - before // Do padding top. if (state.overdraw >= state.paddingTop) { state.overdraw = 0 state unset TOP_ADDED } else { contentTop = state.paddingTop - state.overdraw } } removedHeight += section.trimTop(scrolled, contentTop, helper) if (helper.numViews == 0 && state flagSet BOTTOM_ADDED) { val before = state.overdraw state.overdraw = Math.min(state.paddingBottom, state.overdraw + (scrolled - removedHeight)) removedHeight += state.overdraw - before // Do padding bottom. if (state.bottom < 0) { state.overdraw = 0 state unset BOTTOM_ADDED state.onScreen = false } } state.bottom -= removedHeight return removedHeight } override fun onTrimBottom(scrolled: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState): Int { val state = layoutState as PaddingLayoutState var removedHeight = 0 if (state flagSet BOTTOM_ADDED) { // Do padding bottom. if (state.bottom - state.paddingBottom > helper.layoutLimit) { removedHeight += state.paddingBottom state unset BOTTOM_ADDED } } val contentTop = if (state flagSet TOP_ADDED) state.paddingTop - state.overdraw else 0 // Do content. removedHeight += section.trimBottom(scrolled - removedHeight, contentTop, helper) if (state flagSet TOP_ADDED) { // Do padding top. if (helper.layoutLimit < 0) { removedHeight += state.paddingBottom state unset TOP_ADDED state.onScreen = false } } state.bottom -= removedHeight return removedHeight } }
library/src/main/kotlin/com/tonicartos/superslim/internal/layout/padding.kt
311080554
package com.jlangen.vaultbox.vaults.vault import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.Glide import com.jlangen.vaultbox.R class VaultEntryAdapter(var vaultEntries: List<VaultEntry>) : RecyclerView.Adapter<VaultEntryAdapter.VaultEntryViewHolder>() { override fun getItemCount(): Int { return vaultEntries.size } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VaultEntryViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.row_vault_entry, parent, false) return VaultEntryViewHolder(view) } override fun onBindViewHolder(holder: VaultEntryViewHolder, position: Int) { val entry = vaultEntries[position] if (entry.icon != null) { Glide.with(holder.itemView.context) .asBitmap() .load(entry.icon) .into(holder.groupIconView) } else { holder.groupIconView.setImageResource(entry.vaultIcon.iconId) } holder.titleView.text = entry.title holder.groupView.text = entry.group } class VaultEntryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val groupIconView = itemView.findViewById(R.id.vault_entry_group_icon) as ImageView val titleView = itemView.findViewById(R.id.vault_entry_title) as TextView val groupView = itemView.findViewById(R.id.vault_entry_group) as TextView } }
app/src/main/java/com/jlangen/vaultbox/vaults/vault/VaultEntryAdapter.kt
3252446636
// 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.collaboration.ui.codereview.list.search import com.intellij.collaboration.messages.CollaborationToolsBundle import com.intellij.collaboration.ui.codereview.InlineIconButton import com.intellij.collaboration.ui.codereview.list.search.ChooserPopupUtil.showAndAwaitListSubmission import com.intellij.icons.AllIcons import com.intellij.ide.DataManager import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.Separator import com.intellij.openapi.actionSystem.Toggleable import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.ui.* import com.intellij.ui.components.GradientViewport import com.intellij.ui.components.JBThinOverlappingScrollBar import com.intellij.ui.components.panels.HorizontalLayout import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.JBUI import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.jetbrains.annotations.Nls import java.awt.* import java.awt.event.ActionListener import java.awt.geom.Ellipse2D import javax.swing.Icon import javax.swing.JComponent import javax.swing.JPanel import javax.swing.ScrollPaneConstants abstract class ReviewListSearchPanelFactory<S : ReviewListSearchValue, VM : ReviewListSearchPanelViewModel<S>>( protected val vm: VM ) { fun create(viewScope: CoroutineScope, quickFilters: List<Pair<@Nls String, S>>): JComponent { val searchField = ReviewListSearchTextFieldFactory(vm.queryState).create(viewScope, chooseFromHistory = { point -> val value = JBPopupFactory.getInstance() .createPopupChooserBuilder(vm.getSearchHistory().reversed()) .setRenderer(SimpleListCellRenderer.create { label, value, _ -> label.text = getShortText(value) }) .createPopup() .showAndAwaitListSubmission<S>(point) if (value != null) { vm.searchState.update { value } } }) val filters = createFilters(viewScope) val filtersPanel = JPanel(HorizontalLayout(4)).apply { isOpaque = false filters.forEach { add(it, HorizontalLayout.LEFT) } }.let { ScrollPaneFactory.createScrollPane(it, true).apply { viewport = GradientViewport(it, JBUI.insets(0, 10), false) verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS horizontalScrollBar = JBThinOverlappingScrollBar(Adjustable.HORIZONTAL) } } val quickFilterButton = QuickFilterButtonFactory().create(viewScope, quickFilters) val filterPanel = JPanel(BorderLayout()).apply { border = JBUI.Borders.emptyTop(10) isOpaque = false add(quickFilterButton, BorderLayout.WEST) add(filtersPanel, BorderLayout.CENTER) } val searchPanel = JPanel(BorderLayout()).apply { border = JBUI.Borders.compound(IdeBorderFactory.createBorder(SideBorder.BOTTOM), JBUI.Borders.empty(8, 10, 0, 10)) add(searchField, BorderLayout.CENTER) add(filterPanel, BorderLayout.SOUTH) } return searchPanel } protected abstract fun getShortText(searchValue: S): @Nls String protected abstract fun createFilters(viewScope: CoroutineScope): List<JComponent> private inner class QuickFilterButtonFactory { fun create(viewScope: CoroutineScope, quickFilters: List<Pair<String, S>>): JComponent { val button = InlineIconButton(AllIcons.General.Filter).apply { border = JBUI.Borders.empty(3) }.also { it.actionListener = ActionListener { _ -> showQuickFiltersPopup(it, quickFilters) } } viewScope.launch { vm.searchState.collect { button.icon = if (it.filterCount == 0) AllIcons.General.Filter else IconWithNotifyDot(AllIcons.General.Filter) } } return button } private fun showQuickFiltersPopup(parentComponent: JComponent, quickFilters: List<Pair<@Nls String, S>>) { val quickFiltersActions = quickFilters.map { (name, search) -> QuickFilterAction(name, search) } + Separator() + ClearFiltersAction() JBPopupFactory.getInstance() .createActionGroupPopup(CollaborationToolsBundle.message("review.list.filter.quick.title"), DefaultActionGroup(quickFiltersActions), DataManager.getInstance().getDataContext(parentComponent), JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false) .showUnderneathOf(parentComponent) } private inner class QuickFilterAction(name: @Nls String, private val search: S) : DumbAwareAction(name), Toggleable { override fun update(e: AnActionEvent) = Toggleable.setSelected(e.presentation, vm.searchState.value == search) override fun actionPerformed(e: AnActionEvent) = vm.searchState.update { search } } private inner class ClearFiltersAction : DumbAwareAction(CollaborationToolsBundle.message("review.list.filter.quick.clear", vm.searchState.value.filterCount)) { override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = vm.searchState.value.filterCount > 0 } override fun actionPerformed(e: AnActionEvent) = vm.searchState.update { vm.emptySearch } } //TODO: request a ready-made icon from UI and also a proper icon for old UI private inner class IconWithNotifyDot(private val originalIcon: Icon) : Icon by originalIcon { override fun paintIcon(c: Component?, g: Graphics?, x: Int, y: Int) { originalIcon.paintIcon(c, g, x, y) g as Graphics2D val dotSize = JBUIScale.scale(6) val notifyDotShape = Ellipse2D.Float((iconWidth - dotSize).toFloat(), 0f, dotSize.toFloat(), dotSize.toFloat()) g.color = ColorUtil.fromHex("#3574F0") g.fill(notifyDotShape) } } } }
platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/list/search/ReviewListSearchPanelFactory.kt
283374043
package com.intellij.workspaceModel.test.api import com.intellij.workspaceModel.deft.api.annotations.Default import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type interface FinalFieldsEntity: WorkspaceEntity { val descriptor: AnotherDataClass val version: Int get() = descriptor.version val source: Boolean get() = descriptor.source val displayName: String? get() = descriptor.displayName val gitUrl: String? get() = descriptor.url val gitRevision: String? get() = descriptor.revision fun isEditable(): Boolean { return descriptor.source && displayName != null } fun isReadOnly(): Boolean { return !isEditable() && descriptor.url != null } } data class AnotherDataClass(val name: String, val version: Int, val source: Boolean, val displayName: String? = null, val url: String? = null, val revision: String? = null)
platform/workspaceModel/codegen/test/testData/finalProperty/before/entity.kt
2805819700
// 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.codeInsight import com.intellij.testFramework.UsefulTestCase import org.jetbrains.kotlin.idea.KotlinDocumentationProvider import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.kotlin.test.InTextDirectivesUtils //BUNCH 201 abstract class AbstractRenderingKDocTest : KotlinLightCodeInsightFixtureTestCase() { override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE protected fun doTest(path: String) { myFixture.configureByFile(fileName()) val file = myFixture.file val kDocProvider = KotlinDocumentationProvider() val comments = mutableListOf<String>() kDocProvider.collectDocComments(file) { val rendered = kDocProvider.generateRenderedDoc(it) if (rendered != null) { comments.add(rendered.replace("\n", "")) } } val expectedRenders = InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, "// RENDER: ") UsefulTestCase.assertOrderedEquals(comments, expectedRenders) } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeInsight/AbstractRenderingKDocTest.kt
2303851110
package com.reactnativenavigation.views.element.animators import android.animation.Animator import android.animation.ObjectAnimator import android.graphics.Rect import android.view.View import androidx.core.animation.doOnEnd import com.facebook.react.views.view.ReactViewGroup import com.reactnativenavigation.options.SharedElementTransitionOptions import com.reactnativenavigation.utils.areDimensionsWithInheritedScaleEqual import com.reactnativenavigation.utils.computeInheritedScale import kotlin.math.roundToInt class ReactViewRotationAnimator(from: View, to: View) : PropertyAnimatorCreator<ReactViewGroup>(from, to) { private val fromRotation = from.rotation private val toRotation = to.rotation override fun shouldAnimateProperty(fromChild: ReactViewGroup, toChild: ReactViewGroup): Boolean { return fromRotation != toRotation && fromChild.childCount == 0 && toChild.childCount == 0 } override fun create(options: SharedElementTransitionOptions): Animator { to.rotation = fromRotation to.pivotX = 0f to.pivotY = 0f return ObjectAnimator.ofFloat(to, View.ROTATION, fromRotation, toRotation) } }
lib/android/app/src/main/java/com/reactnativenavigation/views/element/animators/ReactViewRotationAnimator.kt
770772147
// WITH_RUNTIME fun test() { val x = when<caret> (val a = create()) { else -> use(a, a) } } fun create(): String = "" fun use(s: String, t: String) {}
plugins/kotlin/idea/tests/testData/inspectionsLocal/whenWithOnlyElse/subjectVariable/singleElse/multiReferenceUsedAsExpression.kt
2134982291
/** * Copyright 2010 - 2022 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.exodus.env.management import jetbrains.exodus.env.EnvironmentConfig import jetbrains.exodus.env.EnvironmentTestsBase import jetbrains.exodus.log.LogConfig import org.junit.Assert import org.junit.Test import java.lang.management.ManagementFactory import javax.management.ObjectName class DatabaseProfilerMBeanTest : EnvironmentTestsBase() { @Test fun beanIsAccessible() { val profilerBeans = platformMBeanServer.queryMBeans(ObjectName(DatabaseProfiler.getObjectName(env)), null) Assert.assertNotNull(profilerBeans) Assert.assertFalse(profilerBeans.isEmpty()) } override fun createEnvironment() { env = newEnvironmentInstance(LogConfig.create(reader, writer), EnvironmentConfig().setProfilerEnabled(true)) } companion object { private val platformMBeanServer = ManagementFactory.getPlatformMBeanServer() } }
environment/src/test/kotlin/jetbrains/exodus/env/management/DatabaseProfilerMBeanTest.kt
1237108411
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger abstract class SuspendContextBase<F : CallFrame>(protected val explicitPaused: Boolean) : SuspendContext<F> { override val state: SuspendState get() = if (exceptionData == null) (if (explicitPaused) SuspendState.PAUSED else SuspendState.NORMAL) else SuspendState.EXCEPTION }
platform/script-debugger/backend/src/SuspendContextBase.kt
1703051241
package com.github.kerubistan.kerub.planner.steps.storage.gvinum.create import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonTypeName import com.github.kerubistan.kerub.model.GvinumStorageCapability import com.github.kerubistan.kerub.model.Host import com.github.kerubistan.kerub.model.OperatingSystem import com.github.kerubistan.kerub.model.VirtualStorageDevice import com.github.kerubistan.kerub.model.dynamic.VirtualStorageDeviceDynamic import com.github.kerubistan.kerub.model.dynamic.VirtualStorageGvinumAllocation import com.github.kerubistan.kerub.model.dynamic.gvinum.ConcatenatedGvinumConfiguration import com.github.kerubistan.kerub.model.dynamic.gvinum.GvinumConfiguration import com.github.kerubistan.kerub.model.io.VirtualDiskFormat import com.github.kerubistan.kerub.planner.OperationalState import com.github.kerubistan.kerub.planner.costs.Cost import com.github.kerubistan.kerub.planner.costs.Risk import com.github.kerubistan.kerub.planner.steps.storage.AbstractCreateVirtualStorage import io.github.kerubistan.kroki.collections.update import io.github.kerubistan.kroki.time.now @JsonTypeName("create-gvinum-volume") data class CreateGvinumVolume( override val host: Host, override val capability: GvinumStorageCapability, override val disk: VirtualStorageDevice, val config: GvinumConfiguration ) : AbstractCreateVirtualStorage<VirtualStorageGvinumAllocation, GvinumStorageCapability> { init { check(capability in host.capabilities?.storageCapabilities ?: listOf()) { "Capability must be registered in the host" } check(capability.devicesByName.keys.containsAll(config.diskNames)) { "Not all of ${config.diskNames} could be found in ${capability.devicesByName.keys}" } } @get:JsonIgnore override val format: VirtualDiskFormat get() = VirtualDiskFormat.raw @get:JsonIgnore override val allocation: VirtualStorageGvinumAllocation by lazy { VirtualStorageGvinumAllocation( hostId = host.id, actualSize = disk.size, configuration = config, capabilityId = capability.id ) } override fun getCost(): List<Cost> { return when (config) { is ConcatenatedGvinumConfiguration -> { listOf<Cost>( Risk( score = maxOf(config.disks.size - 1, 1), comment = "Loss of any of the ${config.disks.size} disks causes failure of the vstorage" ) ) } else -> { listOf() } } } override fun take(state: OperationalState): OperationalState { require(host.capabilities?.os == OperatingSystem.BSD) { "Need BSD operating system, got ${host.capabilities?.os}" } require(host.capabilities?.distribution?.name == "FreeBSD") { "Gvinum runs on FreeBSD, got ${host.capabilities?.distribution?.name}" } val hostDyn = requireNotNull(state.hosts[host.id]?.dynamic) { "Host dynamic not found - host must be running" } return state.copy( hosts = state.hosts.update(host.id) { hostData -> hostData.copy( dynamic = hostDyn.copy( storageStatus = hostDyn.storageStatus // TODO tell about the storage ) ) }, vStorage = state.vStorage.update(disk.id) { vStorageData -> vStorageData.copy( dynamic = VirtualStorageDeviceDynamic( id = disk.id, lastUpdated = now(), allocations = listOf(allocation) ) ) } ) } }
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/gvinum/create/CreateGvinumVolume.kt
2379482612
package com.github.tslamic.dn import android.content.Context import android.content.SharedPreferences import android.content.res.AssetManager import com.github.tslamic.dn.impl.Cache import com.github.tslamic.dn.impl.PREFS_NAME import com.github.tslamic.dn.impl.PREFS_VERSION import com.google.common.truth.Truth.assertThat import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import org.mockito.ArgumentCaptor import org.mockito.ArgumentMatchers import org.mockito.Mock import org.mockito.Mockito.* import org.mockito.junit.MockitoJUnit import java.io.File class CacheTest { @JvmField @Rule val folder = TemporaryFolder() @JvmField @Rule val mockito = MockitoJUnit.rule()!! @Mock private lateinit var context: Context @Mock private lateinit var assets: AssetManager @Mock private lateinit var prefs: SharedPreferences @Mock private lateinit var editor: SharedPreferences.Editor private lateinit var database: File private lateinit var cache: Cache @Before fun setUp() { `when`(context.getSharedPreferences(eq(PREFS_NAME), anyInt())).thenReturn(prefs) `when`(prefs.edit()).thenReturn(editor) `when`(context.assets).thenReturn(assets) database = folder.newFile() cache = Cache(context, database) } @Test fun getVersion() { val version = 123 setMockVersion(version) assertThat(cache.getVersion()).isEqualTo(version) } @Test fun setVersion() { val name = ArgumentCaptor.forClass(String::class.java) val version = ArgumentCaptor.forClass(Int::class.java) `when`(editor.putInt(name.capture(), version.capture())).thenReturn(editor) cache.setCurrentVersion() assertThat(name.value).isEqualTo(PREFS_VERSION) assertThat(version.value).isEqualTo(BuildConfig.DATABASE_VERSION) } @Test fun isStale_returnsTrue() { setMockVersion(-1) assertThat(cache.isStale()).isTrue() } @Test fun isStale_returnsFalse() { setMockVersion(BuildConfig.DATABASE_VERSION) assertThat(cache.isStale()).isFalse() } @Test fun update() { setMockVersion(-1) val stream = resourceInputStream(DUMMY_ZIP) `when`(assets.open(ArgumentMatchers.anyString())).thenReturn(stream) `when`(editor.putInt(ArgumentMatchers.anyString(), ArgumentMatchers.anyInt())) .thenReturn(editor) val updated = cache.updateDatabase("") assertThat(updated).isTrue() assertThat(database.readText()).isEqualTo(DUMMY_ZIP_CONTENT) verify(editor, times(1)) .putInt(PREFS_VERSION, BuildConfig.DATABASE_VERSION) } private fun setMockVersion(version: Int) { `when`(prefs.getInt(eq(PREFS_VERSION), eq(0))).thenReturn(version) } }
dn/src/test/java/com/github/tslamic/dn/CacheTest.kt
1727967085
/* * 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.jsontestsuite.suite.model class BlockHeaderTck { var bloom: String? = null var coinbase: String? = null var difficulty: String? = null var extraData: String? = null var gasLimit: String? = null var gasUsed: String? = null var hash: String? = null var mixHash: String? = null var nonce: String? = null var number: String? = null var parentHash: String? = null var receiptTrie: String? = null var seedHash: String? = null var stateRoot: String? = null var timestamp: String? = null var transactionsTrie: String? = null var uncleHash: String? = null override fun toString(): String { return "BlockHeader{" + "bloom='" + bloom + '\'' + ", coinbase='" + coinbase + '\'' + ", difficulty='" + difficulty + '\'' + ", extraData='" + extraData + '\'' + ", gasLimit='" + gasLimit + '\'' + ", gasUsed='" + gasUsed + '\'' + ", hash='" + hash + '\'' + ", mixHash='" + mixHash + '\'' + ", nonce='" + nonce + '\'' + ", number='" + number + '\'' + ", parentHash='" + parentHash + '\'' + ", receiptTrie='" + receiptTrie + '\'' + ", seedHash='" + seedHash + '\'' + ", stateRoot='" + stateRoot + '\'' + ", timestamp='" + timestamp + '\'' + ", transactionsTrie='" + transactionsTrie + '\'' + ", uncleHash='" + uncleHash + '\'' + '}' } }
free-ethereum-core/src/test/java/org/ethereum/jsontestsuite/suite/model/BlockHeaderTck.kt
1716315113
/* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package org.jetbrains.kotlin.backend.konan.llvm import llvm.* import org.jetbrains.kotlin.backend.konan.Context import org.jetbrains.kotlin.ir.declarations.IrConstructor import org.jetbrains.kotlin.ir.declarations.IrFunction import org.jetbrains.kotlin.ir.types.isNothing import org.jetbrains.kotlin.ir.util.isThrowable import org.jetbrains.kotlin.konan.target.Family internal fun addLlvmFunctionWithDefaultAttributes( context: Context, module: LLVMModuleRef, name: String, type: LLVMTypeRef ): LLVMValueRef = LLVMAddFunction(module, name, type)!!.also { addDefaultLlvmFunctionAttributes(context, it) } /** * Mimics parts of clang's `CodeGenModule::getDefaultFunctionAttributes` * that are required for Kotlin/Native compiler. */ private fun addDefaultLlvmFunctionAttributes(context: Context, llvmFunction: LLVMValueRef) { if (shouldEnforceFramePointer(context)) { // Note: this is default for clang on at least on iOS and macOS. enforceFramePointer(llvmFunction) } } internal fun addLlvmAttributesForKotlinFunction(context: Context, irFunction: IrFunction, llvmFunction: LLVMValueRef) { if (irFunction.returnType.isNothing()) { setFunctionNoReturn(llvmFunction) } if (mustNotInline(context, irFunction)) { setFunctionNoInline(llvmFunction) } } private fun mustNotInline(context: Context, irFunction: IrFunction): Boolean { if (context.shouldContainLocationDebugInfo()) { if (irFunction is IrConstructor && irFunction.isPrimary && irFunction.returnType.isThrowable()) { // To simplify skipping this constructor when scanning call stack in Kotlin_getCurrentStackTrace. return true } } return false } private fun shouldEnforceFramePointer(context: Context): Boolean { // TODO: do we still need it? if (!context.shouldOptimize()) { return true } return when (context.config.target.family) { Family.OSX, Family.IOS, Family.WATCHOS, Family.TVOS -> context.shouldContainLocationDebugInfo() Family.LINUX, Family.MINGW, Family.ANDROID, Family.WASM, Family.ZEPHYR -> false } } private fun enforceFramePointer(llvmFunction: LLVMValueRef) { LLVMAddTargetDependentFunctionAttr(llvmFunction, "no-frame-pointer-elim", "true") LLVMAddTargetDependentFunctionAttr(llvmFunction, "no-frame-pointer-elim-non-leaf", "") }
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/LlvmAttributes.kt
3723364166
// 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.compilerPlugin.samWithReceiver.maven import org.jetbrains.idea.maven.project.MavenProject import org.jetbrains.kotlin.idea.maven.compilerPlugin.AbstractMavenImportHandler import org.jetbrains.kotlin.idea.compilerPlugin.CompilerPluginSetup.PluginOption import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts import org.jetbrains.kotlin.idea.compilerPlugin.toJpsVersionAgnosticKotlinBundledPath import org.jetbrains.kotlin.samWithReceiver.SamWithReceiverCommandLineProcessor class SamWithReceiverMavenProjectImportHandler : AbstractMavenImportHandler() { private companion object { val ANNOTATION_PARAMETER_PREFIX = "sam-with-receiver:${SamWithReceiverCommandLineProcessor.ANNOTATION_OPTION.optionName}=" } override val compilerPluginId = SamWithReceiverCommandLineProcessor.PLUGIN_ID override val pluginName = "samWithReceiver" override val mavenPluginArtifactName = "kotlin-maven-sam-with-receiver" override val pluginJarFileFromIdea = KotlinArtifacts.instance.samWithReceiverCompilerPlugin.toJpsVersionAgnosticKotlinBundledPath() override fun getOptions( mavenProject: MavenProject, enabledCompilerPlugins: List<String>, compilerPluginOptions: List<String> ): List<PluginOption>? { if ("sam-with-receiver" !in enabledCompilerPlugins) { return null } val annotations = mutableListOf<String>() for ((presetName, presetAnnotations) in SamWithReceiverCommandLineProcessor.SUPPORTED_PRESETS) { if (presetName in enabledCompilerPlugins) { annotations.addAll(presetAnnotations) } } annotations.addAll(compilerPluginOptions.mapNotNull { text -> if (!text.startsWith(ANNOTATION_PARAMETER_PREFIX)) return@mapNotNull null text.substring(ANNOTATION_PARAMETER_PREFIX.length) }) return annotations.map { PluginOption(SamWithReceiverCommandLineProcessor.ANNOTATION_OPTION.optionName, it) } } }
plugins/kotlin/compiler-plugins/sam-with-receiver/maven/src/org/jetbrains/kotlin/idea/compilerPlugin/samWithReceiver/maven/SamWithReceiverMavenProjectImportHandler.kt
1197654297
package org.jetbrains.spek.api open class ItImpl : It {}
spek-core/src/main/kotlin/org/jetbrains/spek/api/It.kt
2495460507
package com.tungnui.abccomputer.activity import android.app.Activity import android.content.Context import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import android.view.View import android.widget.TextView import com.google.android.gms.ads.AdView import com.tungnui.abccomputer.adapter.NotificationAdapter import com.tungnui.abccomputer.data.constant.AppConstants import com.tungnui.abccomputer.data.sqlite.NotificationDBController import com.tungnui.abccomputer.listener.OnItemClickListener import com.tungnui.abccomputer.model.NotificationModel import com.tungnui.abccomputer.R import com.tungnui.abccomputer.utils.ActivityUtils import com.tungnui.abccomputer.utils.AdUtils import java.util.ArrayList class NotificationActivity : AppCompatActivity() { private var mToolbar: Toolbar? = null private var recyclerView: RecyclerView? = null private var mAdapter: NotificationAdapter? = null private var dataList: ArrayList<NotificationModel>? = null private var emptyView: TextView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initVars() initialView() initFunctionality() initialListener() } private fun initVars() { dataList = ArrayList() } private fun initialView() { setContentView(R.layout.activity_notification) mToolbar = findViewById<View>(R.id.toolbar) as Toolbar emptyView = findViewById<View>(R.id.emptyView) as TextView setSupportActionBar(mToolbar) supportActionBar?.title = getString(R.string.notifications) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) //productList recyclerView = findViewById<View>(R.id.recycler_view) as RecyclerView mAdapter = NotificationAdapter(this@NotificationActivity, dataList) recyclerView!!.layoutManager = LinearLayoutManager(this@NotificationActivity) recyclerView!!.adapter = mAdapter } private fun initFunctionality() { val notifyController = NotificationDBController(applicationContext) notifyController.open() dataList?.addAll(notifyController.allNotification) notifyController.close() if (dataList != null && !dataList!!.isEmpty()) { emptyView?.visibility = View.GONE mAdapter?.notifyDataSetChanged() } else { emptyView?.visibility = View.VISIBLE } } private fun initialListener() { mToolbar?.setNavigationOnClickListener { finish() } mAdapter?.setItemClickListener { view, position -> when(dataList!![position].notificationType){ AppConstants.NOTIFY_TYPE_MESSAGE -> ActivityUtils.instance.invokeNotifyContentActivity(this@NotificationActivity,dataList!![position].title, dataList!![position].message) AppConstants.NOTIFY_TYPE_PRODUCT-> ActivityUtils.instance.invokeProductDetails(this@NotificationActivity, dataList!![position].productId) AppConstants.NOTIFY_TYPE_URL -> if (dataList!![position].url != null && !dataList!![position].url.isEmpty()) { ActivityUtils.instance.invokeWebPageActivity(this@NotificationActivity, resources.getString(R.string.app_name), dataList!![position].url) } } updateStatus(dataList!![position].id) } } private fun updateStatus(id: Int) { val notifyController = NotificationDBController(applicationContext) notifyController.open() notifyController.updateStatus(id, true) notifyController.close() } override fun onResume() { super.onResume() } }
app/src/main/java/com/tungnui/abccomputer/activity/NotificationActivity.kt
3464087197
import com.intellij.openapi.util.Couple import com.intellij.openapi.util.Pair object UseCoupleOfFactoryMethodInConstantWhenPairCreateUsed { private val ANY: Pair<String, String> = Couple.of("a", "b") }
plugins/devkit/devkit-kotlin-tests/testData/inspections/useCoupleFix/UseCoupleOfFactoryMethodInConstantWhenPairCreateUsed_after.kt
2402177020
package org.thoughtcrime.securesms.keyvalue import org.thoughtcrime.securesms.database.model.DistributionListId import org.thoughtcrime.securesms.groups.GroupId import org.thoughtcrime.securesms.recipients.Recipient data class StorySend( val timestamp: Long, val identifier: Identifier ) { companion object { @JvmStatic fun newSend(recipient: Recipient): StorySend { return if (recipient.isGroup) { StorySend(System.currentTimeMillis(), Identifier.Group(recipient.requireGroupId())) } else { StorySend(System.currentTimeMillis(), Identifier.DistributionList(recipient.requireDistributionListId())) } } } sealed class Identifier { data class Group(val groupId: GroupId) : Identifier() { override fun matches(recipient: Recipient) = recipient.groupId.orElse(null) == groupId } data class DistributionList(val distributionListId: DistributionListId) : Identifier() { override fun matches(recipient: Recipient) = recipient.distributionListId.orElse(null) == distributionListId } abstract fun matches(recipient: Recipient): Boolean } }
app/src/main/java/org/thoughtcrime/securesms/keyvalue/StorySend.kt
3083720915
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.tv.foundation.lazy.grid import androidx.compose.animation.core.FloatSpringSpec import androidx.compose.foundation.gestures.animateScrollBy import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.unit.Dp import androidx.test.filters.MediumTest import androidx.tv.foundation.lazy.AutoTestFrameClock import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import java.util.concurrent.TimeUnit import kotlin.math.roundToInt import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.junit.Before import org.junit.Ignore import org.junit.Rule import org.junit.Test @MediumTest // @RunWith(Parameterized::class) class LazyScrollTest { // (private val orientation: Orientation) @get:Rule val rule = createComposeRule() private val vertical: Boolean get() = true // orientation == Orientation.Vertical private val itemsCount = 40 private lateinit var state: TvLazyGridState private val itemSizePx = 100 private var itemSizeDp = Dp.Unspecified private var containerSizeDp = Dp.Unspecified lateinit var scope: CoroutineScope @Before fun setup() { with(rule.density) { itemSizeDp = itemSizePx.toDp() containerSizeDp = itemSizeDp * 3 } rule.setContent { state = rememberTvLazyGridState() scope = rememberCoroutineScope() TestContent() } } @Test fun setupWorks() { assertThat(state.firstVisibleItemIndex).isEqualTo(0) assertThat(state.firstVisibleItemScrollOffset).isEqualTo(0) assertThat(state.firstVisibleItemIndex).isEqualTo(0) } @Test fun scrollToItem() = runBlocking { withContext(Dispatchers.Main + AutoTestFrameClock()) { state.scrollToItem(2) } assertThat(state.firstVisibleItemIndex).isEqualTo(2) assertThat(state.firstVisibleItemScrollOffset).isEqualTo(0) withContext(Dispatchers.Main + AutoTestFrameClock()) { state.scrollToItem(0) state.scrollToItem(3) } assertThat(state.firstVisibleItemIndex).isEqualTo(2) assertThat(state.firstVisibleItemScrollOffset).isEqualTo(0) } @Test fun scrollToItemWithOffset() = runBlocking { withContext(Dispatchers.Main + AutoTestFrameClock()) { state.scrollToItem(6, 10) } assertThat(state.firstVisibleItemIndex).isEqualTo(6) assertThat(state.firstVisibleItemScrollOffset).isEqualTo(10) } @Test fun scrollToItemWithNegativeOffset() = runBlocking { withContext(Dispatchers.Main + AutoTestFrameClock()) { state.scrollToItem(6, -10) } assertThat(state.firstVisibleItemIndex).isEqualTo(4) val item6Offset = state.layoutInfo.visibleItemsInfo.first { it.index == 6 }.offset.y assertThat(item6Offset).isEqualTo(10) } @Test fun scrollToItemWithPositiveOffsetLargerThanAvailableSize() = runBlocking { withContext(Dispatchers.Main + AutoTestFrameClock()) { state.scrollToItem(itemsCount - 6, 10) } assertThat(state.firstVisibleItemIndex).isEqualTo(itemsCount - 6) assertThat(state.firstVisibleItemScrollOffset).isEqualTo(0) // not 10 } @Test fun scrollToItemWithNegativeOffsetLargerThanAvailableSize() = runBlocking { withContext(Dispatchers.Main + AutoTestFrameClock()) { state.scrollToItem(1, -(itemSizePx + 10)) } assertThat(state.firstVisibleItemIndex).isEqualTo(0) assertThat(state.firstVisibleItemScrollOffset).isEqualTo(0) // not -10 } @Test fun scrollToItemWithIndexLargerThanItemsCount() = runBlocking { withContext(Dispatchers.Main + AutoTestFrameClock()) { state.scrollToItem(itemsCount + 4) } assertThat(state.firstVisibleItemIndex).isEqualTo(itemsCount - 6) } @Test fun animateScrollBy() = runBlocking { val scrollDistance = 320 val expectedLine = scrollDistance / itemSizePx // resolves to 3 val expectedItem = expectedLine * 2 // resolves to 6 val expectedOffset = scrollDistance % itemSizePx // resolves to 20px withContext(Dispatchers.Main + AutoTestFrameClock()) { state.animateScrollBy(scrollDistance.toFloat()) } assertThat(state.firstVisibleItemIndex).isEqualTo(expectedItem) assertThat(state.firstVisibleItemScrollOffset).isEqualTo(expectedOffset) } @Test fun animateScrollToItem() = runBlocking { withContext(Dispatchers.Main + AutoTestFrameClock()) { state.animateScrollToItem(10, 10) } assertThat(state.firstVisibleItemIndex).isEqualTo(10) assertThat(state.firstVisibleItemScrollOffset).isEqualTo(10) } @Test fun animateScrollToItemWithOffset() = runBlocking { withContext(Dispatchers.Main + AutoTestFrameClock()) { state.animateScrollToItem(6, 10) } assertThat(state.firstVisibleItemIndex).isEqualTo(6) assertThat(state.firstVisibleItemScrollOffset).isEqualTo(10) } @Test fun animateScrollToItemWithNegativeOffset() = runBlocking { withContext(Dispatchers.Main + AutoTestFrameClock()) { state.animateScrollToItem(6, -10) } assertThat(state.firstVisibleItemIndex).isEqualTo(4) val item6Offset = state.layoutInfo.visibleItemsInfo.first { it.index == 6 }.offset.y assertThat(item6Offset).isEqualTo(10) } @Test fun animateScrollToItemWithPositiveOffsetLargerThanAvailableSize() = runBlocking { withContext(Dispatchers.Main + AutoTestFrameClock()) { state.animateScrollToItem(itemsCount - 6, 10) } assertThat(state.firstVisibleItemIndex).isEqualTo(itemsCount - 6) assertThat(state.firstVisibleItemScrollOffset).isEqualTo(0) // not 10 } @Test fun animateScrollToItemWithNegativeOffsetLargerThanAvailableSize() = runBlocking { withContext(Dispatchers.Main + AutoTestFrameClock()) { state.animateScrollToItem(2, -(itemSizePx + 10)) } assertThat(state.firstVisibleItemIndex).isEqualTo(0) assertThat(state.firstVisibleItemScrollOffset).isEqualTo(0) // not -10 } @Test fun animateScrollToItemWithIndexLargerThanItemsCount() = runBlocking { withContext(Dispatchers.Main + AutoTestFrameClock()) { state.animateScrollToItem(itemsCount + 2) } assertThat(state.firstVisibleItemIndex).isEqualTo(itemsCount - 6) } @Test fun animatePerFrameForwardToVisibleItem() { assertSpringAnimation(toIndex = 4) } @Test fun animatePerFrameForwardToVisibleItemWithOffset() { assertSpringAnimation(toIndex = 4, toOffset = 35) } @Test fun animatePerFrameForwardToNotVisibleItem() { assertSpringAnimation(toIndex = 16) } @Test fun animatePerFrameForwardToNotVisibleItemWithOffset() { assertSpringAnimation(toIndex = 20, toOffset = 35) } @Test fun animatePerFrameBackward() { assertSpringAnimation(toIndex = 2, fromIndex = 12) } @Test fun animatePerFrameBackwardWithOffset() { assertSpringAnimation(toIndex = 2, fromIndex = 10, fromOffset = 58) } @Test fun animatePerFrameBackwardWithInitialOffset() { assertSpringAnimation(toIndex = 0, toOffset = 40, fromIndex = 8) } @Test fun canScrollForward() = runBlocking { assertThat(state.firstVisibleItemScrollOffset).isEqualTo(0) assertThat(state.canScrollForward).isTrue() assertThat(state.canScrollBackward).isFalse() } @Ignore("b/259608530") @Test fun canScrollBackward() = runBlocking { withContext(Dispatchers.Main + AutoTestFrameClock()) { state.scrollToItem(itemsCount) } assertThat(state.firstVisibleItemIndex).isEqualTo(itemsCount - 6) assertThat(state.canScrollForward).isFalse() assertThat(state.canScrollBackward).isTrue() } @Test fun canScrollForwardAndBackward() = runBlocking { withContext(Dispatchers.Main + AutoTestFrameClock()) { state.scrollToItem(10) } assertThat(state.firstVisibleItemIndex).isEqualTo(10) assertThat(state.canScrollForward).isTrue() assertThat(state.canScrollBackward).isTrue() } private fun assertSpringAnimation( toIndex: Int, toOffset: Int = 0, fromIndex: Int = 0, fromOffset: Int = 0 ) { if (fromIndex != 0 || fromOffset != 0) { rule.runOnIdle { runBlocking { state.scrollToItem(fromIndex, fromOffset) } } } rule.waitForIdle() assertThat(state.firstVisibleItemIndex).isEqualTo(fromIndex) assertThat(state.firstVisibleItemScrollOffset).isEqualTo(fromOffset) rule.mainClock.autoAdvance = false scope.launch { state.animateScrollToItem(toIndex, toOffset) } while (!state.isScrollInProgress) { Thread.sleep(5) } val startOffset = (fromIndex / 2 * itemSizePx + fromOffset).toFloat() val endOffset = (toIndex / 2 * itemSizePx + toOffset).toFloat() val spec = FloatSpringSpec() val duration = TimeUnit.NANOSECONDS.toMillis(spec.getDurationNanos(startOffset, endOffset, 0f)) rule.mainClock.advanceTimeByFrame() var expectedTime = rule.mainClock.currentTime for (i in 0..duration step FrameDuration) { val nanosTime = TimeUnit.MILLISECONDS.toNanos(i) val expectedValue = spec.getValueFromNanos(nanosTime, startOffset, endOffset, 0f) val actualValue = (state.firstVisibleItemIndex / 2 * itemSizePx + state.firstVisibleItemScrollOffset) assertWithMessage( "On animation frame at $i index=${state.firstVisibleItemIndex} " + "offset=${state.firstVisibleItemScrollOffset} expectedValue=$expectedValue" ).that(actualValue).isEqualTo(expectedValue.roundToInt(), tolerance = 1) rule.mainClock.advanceTimeBy(FrameDuration) expectedTime += FrameDuration assertThat(expectedTime).isEqualTo(rule.mainClock.currentTime) rule.waitForIdle() } assertThat(state.firstVisibleItemIndex).isEqualTo(toIndex) assertThat(state.firstVisibleItemScrollOffset).isEqualTo(toOffset) } @Composable private fun TestContent() { if (vertical) { TvLazyVerticalGrid(TvGridCells.Fixed(2), Modifier.height(containerSizeDp), state) { items(itemsCount) { ItemContent() } } } else { // LazyRow(Modifier.width(300.dp), state) { // items(items) { // ItemContent() // } // } } } @Composable private fun ItemContent() { val modifier = if (vertical) { Modifier.height(itemSizeDp) } else { Modifier.width(itemSizeDp) } Spacer(modifier) } // companion object { // @JvmStatic // @Parameterized.Parameters(name = "{0}") // fun params() = arrayOf(Orientation.Vertical, Orientation.Horizontal) // } } private val FrameDuration = 16L
tv/tv-foundation/src/androidTest/java/androidx/tv/foundation/lazy/grid/LazyScrollTest.kt
2101432853
/* * Copyright 2013-2013 Eugene Petrenko * * 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.jonnyzzz.teamcity.plugins.node.common /** * @author Eugene Petrenko ([email protected]) * Date: 16.08.13 21:42 */ public class NVMBean { public val NVMUsed : String = "Use_NodeJS_Install_Runner" public val NVMAvailable : String = "node.js.nvm" public val NVMFeatureType: String = "jonnyzzz.nvm" public val NVMVersion : String = "version" public val NVMSource : String = "fromSource" public val NVMURL : String = "fromURL" public val NVM_Creatonix : String = "https://github.com/creationix/nvm/archive/v0.7.0.zip" //"https://github.com/creationix/nvm/archive/master.zip" }
common/src/com/jonnyzzz/teamcity/plugins/node/common/NVMBean.kt
4012150622
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.lazy.list import android.os.Build import androidx.compose.foundation.AutoTestFrameClock import androidx.compose.foundation.background import androidx.compose.foundation.gestures.scrollBy import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.requiredSize import androidx.compose.foundation.layout.requiredWidth import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.text.BasicText import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.testutils.assertPixels import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.layout import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.assertCountEquals import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertPositionInRootIsEqualTo import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.getUnclippedBoundsInRoot import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onChildren import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performTouchInput import androidx.compose.ui.test.swipeUp import androidx.compose.ui.unit.dp import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.test.filters.SdkSuppress import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import kotlinx.coroutines.runBlocking import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @LargeTest @RunWith(AndroidJUnit4::class) /** * This class contains all LazyColumn-specific tests, as well as (by convention) tests that don't * need to be run in both orientations. * * To have a test run in both orientations (LazyRow and LazyColumn), add it to [LazyListTest] */ class LazyColumnTest { private val LazyListTag = "LazyListTag" @get:Rule val rule = createComposeRule() @Test fun compositionsAreDisposed_whenDataIsChanged() { var composed = 0 var disposals = 0 val data1 = (1..3).toList() val data2 = (4..5).toList() // smaller, to ensure removal is handled properly var part2 by mutableStateOf(false) rule.setContentWithTestViewConfiguration { LazyColumn(Modifier.testTag(LazyListTag).fillMaxSize()) { items(if (!part2) data1 else data2) { DisposableEffect(NeverEqualObject) { composed++ onDispose { disposals++ } } Spacer(Modifier.height(50.dp)) } } } rule.runOnIdle { assertWithMessage("Not all items were composed") .that(composed).isEqualTo(data1.size) composed = 0 part2 = true } rule.runOnIdle { assertWithMessage( "No additional items were composed after data change, something didn't work" ).that(composed).isEqualTo(data2.size) // We may need to modify this test once we prefetch/cache items outside the viewport assertWithMessage( "Not enough compositions were disposed after scrolling, compositions were leaked" ).that(disposals).isEqualTo(data1.size) } } @Test fun compositionsAreDisposed_whenLazyListIsDisposed() { var emitLazyList by mutableStateOf(true) var disposeCalledOnFirstItem = false var disposeCalledOnSecondItem = false rule.setContentWithTestViewConfiguration { if (emitLazyList) { LazyColumn(Modifier.fillMaxSize()) { items(2) { Box(Modifier.requiredSize(100.dp)) DisposableEffect(Unit) { onDispose { if (it == 1) { disposeCalledOnFirstItem = true } else { disposeCalledOnSecondItem = true } } } } } } } rule.runOnIdle { assertWithMessage("First item was incorrectly immediately disposed") .that(disposeCalledOnFirstItem).isFalse() assertWithMessage("Second item was incorrectly immediately disposed") .that(disposeCalledOnFirstItem).isFalse() emitLazyList = false } rule.runOnIdle { assertWithMessage("First item was not correctly disposed") .that(disposeCalledOnFirstItem).isTrue() assertWithMessage("Second item was not correctly disposed") .that(disposeCalledOnSecondItem).isTrue() } } @Test fun removeItemsTest() { val startingNumItems = 3 var numItems = startingNumItems var numItemsModel by mutableStateOf(numItems) val tag = "List" rule.setContentWithTestViewConfiguration { LazyColumn(Modifier.testTag(tag)) { items((1..numItemsModel).toList()) { BasicText("$it") } } } while (numItems >= 0) { // Confirm the number of children to ensure there are no extra items rule.onNodeWithTag(tag) .onChildren() .assertCountEquals(numItems) // Confirm the children's content for (i in 1..3) { rule.onNodeWithText("$i").apply { if (i <= numItems) { assertExists() } else { assertDoesNotExist() } } } numItems-- if (numItems >= 0) { // Don't set the model to -1 rule.runOnIdle { numItemsModel = numItems } } } } @Test fun changeItemsCountAndScrollImmediately() { lateinit var state: LazyListState var count by mutableStateOf(100) val composedIndexes = mutableListOf<Int>() rule.setContent { state = rememberLazyListState() LazyColumn(Modifier.fillMaxWidth().height(10.dp), state) { items(count) { index -> composedIndexes.add(index) Box(Modifier.size(20.dp)) } } } rule.runOnIdle { composedIndexes.clear() count = 10 runBlocking(AutoTestFrameClock()) { state.scrollToItem(50) } composedIndexes.forEach { assertThat(it).isLessThan(count) } assertThat(state.firstVisibleItemIndex).isEqualTo(9) } } @Test fun changingDataTest() { val dataLists = listOf( (1..3).toList(), (4..8).toList(), (3..4).toList() ) var dataModel by mutableStateOf(dataLists[0]) val tag = "List" rule.setContentWithTestViewConfiguration { LazyColumn(Modifier.testTag(tag)) { items(dataModel) { BasicText("$it") } } } for (data in dataLists) { rule.runOnIdle { dataModel = data } // Confirm the number of children to ensure there are no extra items val numItems = data.size rule.onNodeWithTag(tag) .onChildren() .assertCountEquals(numItems) // Confirm the children's content for (item in data) { rule.onNodeWithText("$item").assertExists() } } } private val firstItemTag = "firstItemTag" private val secondItemTag = "secondItemTag" private fun prepareLazyColumnsItemsAlignment(horizontalGravity: Alignment.Horizontal) { rule.setContentWithTestViewConfiguration { LazyColumn( Modifier.testTag(LazyListTag).requiredWidth(100.dp), horizontalAlignment = horizontalGravity ) { items(listOf(1, 2)) { if (it == 1) { Spacer(Modifier.size(50.dp).testTag(firstItemTag)) } else { Spacer(Modifier.size(70.dp).testTag(secondItemTag)) } } } } rule.onNodeWithTag(firstItemTag) .assertIsDisplayed() rule.onNodeWithTag(secondItemTag) .assertIsDisplayed() val lazyColumnBounds = rule.onNodeWithTag(LazyListTag) .getUnclippedBoundsInRoot() with(rule.density) { // Verify the width of the column assertThat(lazyColumnBounds.left.roundToPx()).isWithin1PixelFrom(0.dp.roundToPx()) assertThat(lazyColumnBounds.right.roundToPx()).isWithin1PixelFrom(100.dp.roundToPx()) } } @Test fun lazyColumnAlignmentCenterHorizontally() { prepareLazyColumnsItemsAlignment(Alignment.CenterHorizontally) rule.onNodeWithTag(firstItemTag) .assertPositionInRootIsEqualTo(25.dp, 0.dp) rule.onNodeWithTag(secondItemTag) .assertPositionInRootIsEqualTo(15.dp, 50.dp) } @Test fun lazyColumnAlignmentStart() { prepareLazyColumnsItemsAlignment(Alignment.Start) rule.onNodeWithTag(firstItemTag) .assertPositionInRootIsEqualTo(0.dp, 0.dp) rule.onNodeWithTag(secondItemTag) .assertPositionInRootIsEqualTo(0.dp, 50.dp) } @Test fun lazyColumnAlignmentEnd() { prepareLazyColumnsItemsAlignment(Alignment.End) rule.onNodeWithTag(firstItemTag) .assertPositionInRootIsEqualTo(50.dp, 0.dp) rule.onNodeWithTag(secondItemTag) .assertPositionInRootIsEqualTo(30.dp, 50.dp) } @Test fun flingAnimationStopsOnFingerDown() { val items by mutableStateOf((1..20).toList()) val state = LazyListState() rule.setContentWithTestViewConfiguration { LazyColumn( Modifier.requiredSize(100.dp).testTag(LazyListTag), state = state ) { items(items) { Spacer(Modifier.requiredSize(20.dp).testTag("$it")) } } } rule.runOnIdle { assertThat(state.firstVisibleItemIndex).isEqualTo(0) assertThat(state.firstVisibleItemScrollOffset).isEqualTo(0) } rule.mainClock.autoAdvance = false rule.onNodeWithTag(LazyListTag) .performTouchInput { swipeUp() } rule.mainClock.advanceTimeBy(100) val itemIndexWhenInterrupting = state.firstVisibleItemIndex val itemOffsetWhenInterrupting = state.firstVisibleItemScrollOffset assertThat(itemIndexWhenInterrupting).isNotEqualTo(0) assertThat(itemOffsetWhenInterrupting).isNotEqualTo(0) rule.onNodeWithTag(LazyListTag) .performTouchInput { down(center) } rule.mainClock.advanceTimeBy(100) assertThat(state.firstVisibleItemIndex).isEqualTo(itemIndexWhenInterrupting) assertThat(state.firstVisibleItemScrollOffset).isEqualTo(itemOffsetWhenInterrupting) } @Test fun removalWithMutableStateListOf() { val items = mutableStateListOf("1", "2", "3") val itemSize = with(rule.density) { 15.toDp() } rule.setContentWithTestViewConfiguration { LazyColumn { items(items) { item -> Spacer(Modifier.size(itemSize).testTag(item)) } } } rule.runOnIdle { items.removeLast() } rule.onNodeWithTag("1") .assertIsDisplayed() rule.onNodeWithTag("2") .assertIsDisplayed() rule.onNodeWithTag("3") .assertDoesNotExist() } @Test fun recompositionOrder() { val outerState = mutableStateOf(0) val innerState = mutableStateOf(0) val recompositions = mutableListOf<Pair<Int, Int>>() rule.setContent { val localOuterState = outerState.value LazyColumn { items(count = 1) { recompositions.add(localOuterState to innerState.value) Box(Modifier.fillMaxSize()) } } } rule.runOnIdle { innerState.value++ outerState.value++ } rule.runOnIdle { assertThat(recompositions).isEqualTo( listOf(0 to 0, 1 to 1) ) } } @SdkSuppress(minSdkVersion = Build.VERSION_CODES.O) @Test fun scrolledAwayItemIsNotDisplayedAnymore() { lateinit var state: LazyListState rule.setContentWithTestViewConfiguration { state = rememberLazyListState() LazyColumn( Modifier .requiredSize(10.dp) .testTag(LazyListTag) .graphicsLayer() .background(Color.Blue), state = state ) { items(2) { val size = if (it == 0) 5.dp else 100.dp val color = if (it == 0) Color.Red else Color.Transparent Box( Modifier .fillMaxWidth() .height(size) .background(color) .testTag("$it") ) } } } rule.runOnIdle { with(rule.density) { runBlocking { // we scroll enough to make the Red item not visible anymore state.scrollBy(6.dp.toPx()) } } } // and verify there is no Red item displayed rule.onNodeWithTag(LazyListTag) .captureToImage() .assertPixels { Color.Blue } } @Test fun wrappedNestedLazyRowDisplayCorrectContent() { lateinit var state: LazyListState rule.setContentWithTestViewConfiguration { state = rememberLazyListState() LazyColumn(Modifier.size(20.dp), state = state) { items(100) { LazyRowWrapped { BasicText("$it", Modifier.size(21.dp)) } } } } (1..10).forEach { item -> rule.runOnIdle { runBlocking { state.scrollToItem(item) } } rule.onNodeWithText("$item") .assertIsDisplayed() } } @Test fun nestedLazyRowChildrenAreReused() { lateinit var state: LazyListState var remeasuresCount = 0 val measureModifier = Modifier.layout { _, constraints -> remeasuresCount++ layout(constraints.maxWidth, constraints.maxHeight) {} } rule.setContentWithTestViewConfiguration { state = rememberLazyListState() LazyColumn( Modifier .fillMaxWidth() .height(10.dp), state = state ) { items(100) { LazyRow { item { Box(Modifier.size(25.dp).then(measureModifier)) } } } } } rule.runOnIdle { state.prefetchingEnabled = false runBlocking { state.scrollToItem(1) // now item 0 should be kept for reuse assertThat(remeasuresCount).isEqualTo(2) remeasuresCount = 0 state.scrollToItem(2) // item 2 should reuse item 0 slot } } rule.runOnIdle { // no remeasures are expected as the LayoutNode should be reused and modifiers // didn't change. assertThat(remeasuresCount).isEqualTo(0) } } @Composable private fun LazyRowWrapped(content: @Composable () -> Unit) { LazyRow { items(count = 1) { content() } } } } internal fun Modifier.drawOutsideOfBounds() = drawBehind { val inflate = 20.dp.roundToPx().toFloat() drawRect( Color.Red, Offset(-inflate, -inflate), Size(size.width + inflate * 2, size.height + inflate * 2) ) }
compose/foundation/foundation/src/androidAndroidTest/kotlin/androidx/compose/foundation/lazy/list/LazyColumnTest.kt
3719469447
package data.tinder.like import data.ObjectMapper import data.network.RequestFacade import domain.like.DomainLikedRecommendationAnswer import domain.recommendation.DomainRecommendationUser internal class LikeFacade( source: LikeSource, requestMapper: ObjectMapper<DomainRecommendationUser, LikeRequestParameters>, responseMapper: ObjectMapper<LikeResponse, DomainLikedRecommendationAnswer>) : RequestFacade<DomainRecommendationUser, LikeRequestParameters, LikeResponse, DomainLikedRecommendationAnswer>( source, requestMapper, responseMapper)
data/src/main/kotlin/data/tinder/like/LikeFacade.kt
2751377727
/* * 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.work.testing import android.content.Context import android.net.Uri import android.os.Build import androidx.work.Data import androidx.work.Worker import java.util.concurrent.Executor /** * Builds an instance of [TestWorkerBuilder]. * * @param W The subtype of [Worker] * @param context The application [Context] * @param executor The [Executor] that the [Worker] runs on * @param inputData The input data for the [Worker] * @param runAttemptCount The run attempt count of the [Worker] * @param triggeredContentUris The list of triggered content [Uri]s * @param triggeredContentAuthorities The list of triggered content authorities * @return The instance of [TestWorkerBuilder] */ public inline fun <reified W : Worker> TestWorkerBuilder( context: Context, executor: Executor, inputData: Data = Data.EMPTY, tags: List<String> = emptyList(), runAttemptCount: Int = 1, triggeredContentUris: List<Uri> = emptyList(), triggeredContentAuthorities: List<String> = emptyList() ): TestWorkerBuilder<W> { val builder = TestWorkerBuilder.from(context, W::class.java, executor) builder.apply { setInputData(inputData) setTags(tags) setRunAttemptCount(runAttemptCount) if (Build.VERSION.SDK_INT >= 24) { setTriggeredContentUris(triggeredContentUris) setTriggeredContentAuthorities(triggeredContentAuthorities) } } return builder }
work/work-testing/src/main/java/androidx/work/testing/TestWorkerBuilder.kt
2971438678
// PROBLEM: Fewer arguments provided (2) than placeholders specified (3) // FIX: none package org.apache.logging.log4j private val logger: Logger? = null fun foo(a: Int, b: Int) { logger?.trace("<caret>test {} {} {}", 1, 2) } interface Logger { fun trace(format: String, param1: Any, param2: Any) }
plugins/kotlin/idea/tests/testData/inspectionsLocal/logging/placeholderCountMatchesArgumentCount/log4j/trace.kt
2819462102
package com.onyx.extension import com.onyx.exception.AttributeNonNullException import com.onyx.exception.AttributeSizeException import com.onyx.exception.IdentifierRequiredException import com.onyx.exception.OnyxException import com.onyx.extension.common.ClassMetadata import com.onyx.persistence.IManagedEntity import com.onyx.persistence.annotations.values.IdentifierGenerator import com.onyx.persistence.context.SchemaContext /** * Checks an entity to to see if it is valid within a context * * @param context Context to verify entity against * * @throws OnyxException The entity is invalid * @return true if it is valid * @since 2.0.0 */ @Throws(OnyxException::class) fun IManagedEntity.isValid(context:SchemaContext):Boolean { val descriptor = descriptor(context) descriptor.attributes.values.forEach { val attributeValue:Any? = this[context, descriptor, it.name] // Nullable if(!it.isNullable && attributeValue == null) throw AttributeNonNullException(AttributeNonNullException.ATTRIBUTE_NULL_EXCEPTION, it.name) // Size if(it.type.isAssignableFrom(ClassMetadata.STRING_TYPE) && attributeValue != null && (attributeValue as String).length > it.size && it.size > -1) throw AttributeSizeException(AttributeSizeException.ATTRIBUTE_SIZE_EXCEPTION, it.name) } // Null Identifier if not auto generated if(descriptor.identifier!!.generator === IdentifierGenerator.NONE){ if(identifier(context) == null) throw IdentifierRequiredException(IdentifierRequiredException.IDENTIFIER_REQUIRED_EXCEPTION, descriptor.identifier!!.name) } return true }
onyx-database/src/main/kotlin/com/onyx/extension/IManagedEntity$Validate.kt
3150999448
package com.github.firenox89.shinobooru.ui.post import android.graphics.Bitmap import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.fragment.app.DialogFragment import com.github.firenox89.shinobooru.R class ZoomFragment : DialogFragment() { lateinit var image: Bitmap override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setStyle(STYLE_NO_FRAME, android.R.style.Theme_Black_NoTitleBar_Fullscreen) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_zoom, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) view.findViewById<ImageView>(R.id.zoomImageView).setImageBitmap(image) } override fun onPause() { dismiss() super.onPause() } }
app/src/main/java/com/github/firenox89/shinobooru/ui/post/ZoomFragment.kt
500930358
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.hierarchy.calls import com.intellij.ide.hierarchy.call.CallHierarchyNodeDescriptor import com.intellij.psi.PsiMember fun extractMemberFromDescriptor(nodeDescriptor: CallHierarchyNodeDescriptor): PsiMember? { return nodeDescriptor.enclosingElement }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/KotlinCalleeTreeStructureUtils.kt
1520842279
// WITH_RUNTIME class Wrapper<T>(private val x: T) { fun unwrap() = x } val unwrapped = listOf(Wrapper(1), Wrapper("B")).map(<caret>Wrapper<out Any>::unwrap)
plugins/kotlin/idea/tests/testData/intentions/convertReferenceToLambda/unwrap.kt
2259889621
package org.schabi.newpipe.database.feed.dao import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Transaction import androidx.room.Update import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.core.Maybe import org.schabi.newpipe.database.feed.model.FeedEntity import org.schabi.newpipe.database.feed.model.FeedGroupEntity import org.schabi.newpipe.database.feed.model.FeedLastUpdatedEntity import org.schabi.newpipe.database.stream.StreamWithState import org.schabi.newpipe.database.stream.model.StreamStateEntity import org.schabi.newpipe.database.subscription.NotificationMode import org.schabi.newpipe.database.subscription.SubscriptionEntity import java.time.OffsetDateTime @Dao abstract class FeedDAO { @Query("DELETE FROM feed") abstract fun deleteAll(): Int /** * @param groupId the group id to get feed streams of; use * [FeedGroupEntity.GROUP_ALL_ID] to not filter by group * @param includePlayed if false, only return all of the live, never-played or non-finished * feed streams (see `@see` items); if true no filter is applied * @param uploadDateBefore get only streams uploaded before this date (useful to filter out * future streams); use null to not filter by upload date * @return the feed streams filtered according to the conditions provided in the parameters * @see StreamStateEntity.isFinished() * @see StreamStateEntity.PLAYBACK_FINISHED_END_MILLISECONDS */ @Query( """ SELECT s.*, sst.progress_time FROM streams s LEFT JOIN stream_state sst ON s.uid = sst.stream_id LEFT JOIN stream_history sh ON s.uid = sh.stream_id INNER JOIN feed f ON s.uid = f.stream_id LEFT JOIN feed_group_subscription_join fgs ON ( :groupId <> ${FeedGroupEntity.GROUP_ALL_ID} AND fgs.subscription_id = f.subscription_id ) WHERE ( :groupId = ${FeedGroupEntity.GROUP_ALL_ID} OR fgs.group_id = :groupId ) AND ( :includePlayed OR sh.stream_id IS NULL OR sst.stream_id IS NULL OR sst.progress_time < s.duration * 1000 - ${StreamStateEntity.PLAYBACK_FINISHED_END_MILLISECONDS} OR sst.progress_time < s.duration * 1000 * 3 / 4 OR s.stream_type = 'LIVE_STREAM' OR s.stream_type = 'AUDIO_LIVE_STREAM' ) AND ( :uploadDateBefore IS NULL OR s.upload_date IS NULL OR s.upload_date < :uploadDateBefore ) ORDER BY s.upload_date IS NULL DESC, s.upload_date DESC, s.uploader ASC LIMIT 500 """ ) abstract fun getStreams( groupId: Long, includePlayed: Boolean, uploadDateBefore: OffsetDateTime? ): Maybe<List<StreamWithState>> @Query( """ DELETE FROM feed WHERE feed.stream_id IN ( SELECT s.uid FROM streams s INNER JOIN feed f ON s.uid = f.stream_id WHERE s.upload_date < :offsetDateTime ) """ ) abstract fun unlinkStreamsOlderThan(offsetDateTime: OffsetDateTime) @Query( """ DELETE FROM feed WHERE feed.subscription_id = :subscriptionId AND feed.stream_id IN ( SELECT s.uid FROM streams s INNER JOIN feed f ON s.uid = f.stream_id WHERE s.stream_type = "LIVE_STREAM" OR s.stream_type = "AUDIO_LIVE_STREAM" ) """ ) abstract fun unlinkOldLivestreams(subscriptionId: Long) @Insert(onConflict = OnConflictStrategy.IGNORE) abstract fun insert(feedEntity: FeedEntity) @Insert(onConflict = OnConflictStrategy.IGNORE) abstract fun insertAll(entities: List<FeedEntity>): List<Long> @Insert(onConflict = OnConflictStrategy.IGNORE) internal abstract fun insertLastUpdated(lastUpdatedEntity: FeedLastUpdatedEntity): Long @Update(onConflict = OnConflictStrategy.IGNORE) internal abstract fun updateLastUpdated(lastUpdatedEntity: FeedLastUpdatedEntity) @Transaction open fun setLastUpdatedForSubscription(lastUpdatedEntity: FeedLastUpdatedEntity) { val id = insertLastUpdated(lastUpdatedEntity) if (id == -1L) { updateLastUpdated(lastUpdatedEntity) } } @Query( """ SELECT MIN(lu.last_updated) FROM feed_last_updated lu INNER JOIN feed_group_subscription_join fgs ON fgs.subscription_id = lu.subscription_id AND fgs.group_id = :groupId """ ) abstract fun oldestSubscriptionUpdate(groupId: Long): Flowable<List<OffsetDateTime>> @Query("SELECT MIN(last_updated) FROM feed_last_updated") abstract fun oldestSubscriptionUpdateFromAll(): Flowable<List<OffsetDateTime>> @Query("SELECT COUNT(*) FROM feed_last_updated WHERE last_updated IS NULL") abstract fun notLoadedCount(): Flowable<Long> @Query( """ SELECT COUNT(*) FROM subscriptions s INNER JOIN feed_group_subscription_join fgs ON s.uid = fgs.subscription_id AND fgs.group_id = :groupId LEFT JOIN feed_last_updated lu ON s.uid = lu.subscription_id WHERE lu.last_updated IS NULL """ ) abstract fun notLoadedCountForGroup(groupId: Long): Flowable<Long> @Query( """ SELECT s.* FROM subscriptions s LEFT JOIN feed_last_updated lu ON s.uid = lu.subscription_id WHERE lu.last_updated IS NULL OR lu.last_updated < :outdatedThreshold """ ) abstract fun getAllOutdated(outdatedThreshold: OffsetDateTime): Flowable<List<SubscriptionEntity>> @Query( """ SELECT s.* FROM subscriptions s INNER JOIN feed_group_subscription_join fgs ON s.uid = fgs.subscription_id AND fgs.group_id = :groupId LEFT JOIN feed_last_updated lu ON s.uid = lu.subscription_id WHERE lu.last_updated IS NULL OR lu.last_updated < :outdatedThreshold """ ) abstract fun getAllOutdatedForGroup(groupId: Long, outdatedThreshold: OffsetDateTime): Flowable<List<SubscriptionEntity>> @Query( """ SELECT s.* FROM subscriptions s LEFT JOIN feed_last_updated lu ON s.uid = lu.subscription_id WHERE (lu.last_updated IS NULL OR lu.last_updated < :outdatedThreshold) AND s.notification_mode = :notificationMode """ ) abstract fun getOutdatedWithNotificationMode( outdatedThreshold: OffsetDateTime, @NotificationMode notificationMode: Int ): Flowable<List<SubscriptionEntity>> }
app/src/main/java/org/schabi/newpipe/database/feed/dao/FeedDAO.kt
551561614
/* // codegen.kt:7 ApLight.kt:179 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 * (C) Copyright 2018 Vladimir Grechka // codegen.kt:8 ApLight.kt:179 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 * // codegen.kt:9 ApLight.kt:179 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 * YOU DON'T MESS AROUND WITH THIS SHIT, IT WAS GENERATED BY A TOOL SMARTER THAN YOU // codegen.kt:10 ApLight.kt:179 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 */ // codegen.kt:11 ApLight.kt:179 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 // codegen.kt:12 ApLight.kt:179 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 // // codegen.kt:13 ApLight.kt:179 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 // Generated on Mon Feb 19 13:42:43 EET 2018 // codegen.kt:14 ApLight.kt:179 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 // Model: /home/into/pro/fe/alraune/alraune/src/main/java/alraune/entity/Bid.kt // codegen.kt:16 ApLight.kt:179 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 // // codegen.kt:18 ApLight.kt:179 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 // codegen.kt:19 ApLight.kt:179 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 package alraune.entity // ApLight.kt:181 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 // ApLight.kt:183 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 import alraune.* // ApLight.kt:185 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 import aplight.GelFill // ApLight.kt:185 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 import aplight.GelNew // ApLight.kt:185 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 import vgrechka.* // ApLight.kt:185 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 import java.sql.Timestamp // ApLight.kt:185 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 import kotlin.reflect.* // ApLight.kt:189 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 // ApLight.kt:241 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 /* // ApLight.kt:243 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 id = zz, // ApLight.kt:245 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 orderId = zz, // ApLight.kt:245 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 userId = zz, // ApLight.kt:245 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 userKind = zz, // ApLight.kt:245 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 commentRecipientId = zz, // ApLight.kt:245 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 time = zz, // ApLight.kt:245 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 money = zz, // ApLight.kt:245 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 data = zz // ApLight.kt:245 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 */ // ApLight.kt:247 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 fun Bid.fill( // ApLight.kt:228 ApLight.kt:249 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 id: Long, // ApLight.kt:258 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 orderId: Long, // ApLight.kt:258 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 userId: Long, // ApLight.kt:258 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 userKind: AlUserKind, // ApLight.kt:258 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 commentRecipientId: Long?, // ApLight.kt:258 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 time: Timestamp, // ApLight.kt:258 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 money: Int?, // ApLight.kt:258 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 data: Bid.Data // ApLight.kt:258 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 ): Bid { // ApLight.kt:232 ApLight.kt:261 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 this.id = id // ApLight.kt:268 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 this.orderId = orderId // ApLight.kt:268 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 this.userId = userId // ApLight.kt:268 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 this.userKind = userKind // ApLight.kt:268 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 this.commentRecipientId = commentRecipientId // ApLight.kt:268 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 this.time = time // ApLight.kt:268 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 this.money = money // ApLight.kt:268 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 this.data = data // ApLight.kt:268 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 return this // ApLight.kt:269 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 } // ApLight.kt:270 ApLight.kt:21 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 // ApLight.kt:278 ApLight.kt:274 ApLight.kt:24 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:199 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 fun new_Bid_Data( // ApLight.kt:281 ApLight.kt:274 ApLight.kt:24 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:199 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 comment: String, // ApLight.kt:290 ApLight.kt:274 ApLight.kt:24 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:199 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 isCancelation: Boolean = false // ApLight.kt:290 ApLight.kt:274 ApLight.kt:24 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:199 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 ): Bid.Data { // ApLight.kt:232 ApLight.kt:293 ApLight.kt:274 ApLight.kt:24 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:199 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 val inst = Bid.Data() // ApLight.kt:295 ApLight.kt:274 ApLight.kt:24 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:199 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 inst.comment = comment // ApLight.kt:308 ApLight.kt:274 ApLight.kt:24 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:199 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 inst.isCancelation = isCancelation // ApLight.kt:308 ApLight.kt:274 ApLight.kt:24 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:199 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 return inst // ApLight.kt:310 ApLight.kt:274 ApLight.kt:24 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:199 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175 } // ApLight.kt:313 ApLight.kt:274 ApLight.kt:24 ApLight.kt:12 ApLight.kt:222 ApLight.kt:170 ApLight.kt:198 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:199 ApLight.kt:191 KtVisitor.java:33 KtClass.kt:34 KtElementImplStub.java:58 ApLight.kt:193 ApLight.kt:191 KtFile.kt:225 KtFile.kt:211 ApLight.kt:191 ApLight.kt:74 CoroutineImpl.kt:54 CoroutineImpl.kt:53 CoroutineDispatcher.kt:123 ForkJoinTask.java:1409 ForkJoinTask.java:283 ForkJoinPool.java:950 ForkJoinPool.java:1607 ForkJoinWorkerThread.java:175
alraune/alraune/src/main/gen/alraune/entity/Bid--generated2.kt
1859298756
/* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package org.jetbrains.complexNumbers const val benchmarkSize = 10000 expect class ComplexNumber expect class ComplexNumbersBenchmark() { fun generateNumbersSequence(): List<ComplexNumber> fun sumComplex() fun subComplex() fun classInheritance() fun categoryMethods() fun stringToObjC() fun stringFromObjC() fun fft() fun invertFft() }
performance/objcinterop/src/main/kotlin/org/jetbrains/objCinteropBenchmarks/complexNumbers.kt
391429363
// FIR_COMPARISON package test @Deprecated("hidden", level = DeprecationLevel.HIDDEN) fun hiddenFunFromSameFile(){} @Deprecated("error", level = DeprecationLevel.ERROR) fun errorNotHiddenFunFromSameFile(){} fun String.foo() { hid<caret> } // ABSENT: hiddenFun // ABSENT: hiddenProperty // ABSENT: hiddenFunFromSameFile // ABSENT: hiddenExtension // EXIST: notHiddenFun // EXIST: notHiddenProperty // EXIST: errorNotHiddenFunFromSameFile // EXIST: errorNotHiddenFun // EXIST: errorNotHiddenProperty // EXIST: errorNotHiddenExtension
plugins/kotlin/completion/tests/testData/basic/multifile/HiddenDeclarations/HiddenDeclarations.kt
392188279
package com.github.kerubistan.kerub.services import com.github.kerubistan.kerub.model.dynamic.HostDynamic import com.github.kerubistan.kerub.security.admin import org.apache.shiro.authz.annotation.RequiresAuthentication import org.apache.shiro.authz.annotation.RequiresRoles import javax.ws.rs.Consumes import javax.ws.rs.Path import javax.ws.rs.Produces import javax.ws.rs.core.MediaType @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @RequiresRoles(admin) @RequiresAuthentication @Path("host-dyn") interface HostDynamicService : DynamicService<HostDynamic>
src/main/kotlin/com/github/kerubistan/kerub/services/HostDynamicService.kt
1937468629
// A class A { fun foo(p1: P?, p2: P?) {} fun foo(listener: suspend RS.(P?, P?) -> Unit) {} } interface P interface RS // FIR_COMPARISON
plugins/kotlin/idea/tests/testData/compiler/asJava/lightClasses/StubOrderForOverloads.kt
3233019771
package io.github.fvasco.pinpoi.importer import android.util.Log import io.github.fvasco.pinpoi.BuildConfig import io.github.fvasco.pinpoi.model.Placemark import java.io.InputStream /** * Abstract base importer. * @author Francesco Vasco */ abstract class AbstractImporter { var consumer: ((Placemark) -> Unit)? = null var collectionId: Long = 0 var fileFormatFilter: FileFormatFilter = FileFormatFilter.NONE /** * Import data * * @param inputStream data source */ fun importPlacemarks(inputStream: InputStream) { requireNotNull(consumer) { "No consumer" } require(collectionId > 0) { "Collection id not valid: $collectionId" } // do import importImpl(inputStream) } fun importPlacemark(placemark: Placemark) { val (latitude, longitude) = placemark.coordinates if (latitude >= -90f && latitude <= 90f && longitude >= -180f && longitude <= 180f ) { val name = placemark.name.trim() var description: String = placemark.description.trim() if (description == name) description = "" placemark.name = name placemark.description = description placemark.collectionId = collectionId if (BuildConfig.DEBUG) { Log.d(AbstractImporter::class.java.simpleName, "importPlacemark $placemark") } consumer!!(placemark) } else if (BuildConfig.DEBUG) { Log.d(AbstractImporter::class.java.simpleName, "importPlacemark skip $placemark") } } /** * Configure importer from another */ fun configureFrom(importer: AbstractImporter) { collectionId = importer.collectionId consumer = importer.consumer fileFormatFilter = importer.fileFormatFilter } /** * Read datas, use [importPlacemark] to persistence it * @param inputStream data source */ abstract fun importImpl(inputStream: InputStream) }
app/src/main/java/io/github/fvasco/pinpoi/importer/AbstractImporter.kt
3395773081
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.test.java import com.intellij.psi.JavaPsiFacade import com.intellij.testFramework.UsefulTestCase import com.intellij.util.asSafely import junit.framework.TestCase import org.jetbrains.uast.* abstract class JavaUJumpExpressionBase : AbstractJavaUastLightTest() { protected inline fun <reified TElement : UElement, reified TJumpFromElement> doTest(fileSource: String) { val file = myFixture.configureByText("File.java", fileSource) val element = file.findElementAt(myFixture.editor.caretModel.offset)?.parent?.toUElementOfType<TElement>() ?: fail("cannot find element") UsefulTestCase.assertInstanceOf((element as? UJumpExpression)?.jumpTarget, TJumpFromElement::class.java) } protected inline fun <reified TElement : UJumpExpression> doTestWithNullTarget(fileSource: String) { val file = myFixture.configureByText("File.java", fileSource) val element = file.findElementAt(myFixture.editor.caretModel.offset)?.parent?.toUElementOfType<TElement>() ?: fail("cannot find element") TestCase.assertNull(element.jumpTarget) } } class JavaUJumpExpressionTest : JavaUJumpExpressionBase() { fun `test break`() = doTest<UBreakExpression, UForExpression>(""" class Break { static void a() { while (true) { for (int i = 0; i < 10; i++) { brea<caret>k; } } } } """) fun `test break with label`() = doTest<UBreakExpression, UWhileExpression>(""" class Break { static void a() { a: while (true) { for (int i = 0; i < 10; i++) { brea<caret>k a; } } } } """) fun `test break in switch`() = doTest<UBreakExpression, USwitchExpression>(""" class Break { static void a() { while (true) { switch (1) { case 2: bre<caret>ak; } } } } """) fun `test continue`() = doTest<UContinueExpression, UForExpression>(""" class Break { static void a() { while (true) { for (int i = 0; i < 10; i++) { con<caret>tinue; } } } } """) fun `test continue with label`() = doTest<UContinueExpression, UWhileExpression>(""" class Break { static void a() { a: while (true) { for (int i = 0; i < 10; i++) { con<caret>tinue a; } } } } """) fun `test return`() = doTest<UReturnExpression, UMethod>(""" class Break { static void a() { ret<caret>urn; } } """) fun `test return from lambda`() = doTest<UReturnExpression, ULambdaExpression>(""" class Break { static void a() { Supplier a = () -> { ret<caret>urn a; } } } """) fun `test return from inner method`() = doTest<UReturnExpression, UMethod>(""" class Break { static Consumer a = (b) -> { new Object() { Object kek() { ret<caret>urn b; } }; }; } """) fun `test implicit return`() { val lambda = JavaPsiFacade.getElementFactory(project).createExpressionFromText("() -> 10", null) .toUElementOfType<ULambdaExpression>() ?: fail("cannot create lambda") val returnExpr = (lambda.body as? UBlockExpression)?.expressions?.singleOrNull()?.asSafely<UReturnExpression>() TestCase.assertEquals((returnExpr as? UJumpExpression)?.jumpTarget, lambda) } fun `test strange break`() = doTestWithNullTarget<UBreakExpression>(""" class Break { static void a() { while (true) { for (int i = 0; i < 10; i++) { a: brea<caret>k a; } } } } """) fun `test strange continue`() = doTestWithNullTarget<UContinueExpression>(""" class Break { static void a() { while (true) { for (int i = 0; i < 10; i++) { a: continu<caret>e a; } } } } """) } class Java13UJumpExpressionTest : JavaUJumpExpressionBase() { fun `test break in switch`() = doTest<UYieldExpression, USwitchExpression>(""" class Break { static void a() { while (true) { int a = switch (1) { case 2: yie<caret>ld 10; default: yield 15; } } } } """) }
uast/uast-tests/test/org/jetbrains/uast/test/java/JavaUJumpExpressionTest.kt
704692235
/* * Copyright 2017 Lloyd Ramey <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lloydramey.cfn.scripting.helpers import com.lloydramey.cfn.model.functions.Condition import com.lloydramey.cfn.model.functions.ConditionFunction import com.lloydramey.cfn.scripting.CfnTemplateScript import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty class ConditionDelegate(supplier: () -> ConditionFunction) : ReadOnlyProperty<CfnTemplateScript, Condition> { val func = supplier() override fun getValue(thisRef: CfnTemplateScript, property: KProperty<*>) = Condition(property.name, func) }
plugin/src/main/kotlin/com/lloydramey/cfn/scripting/helpers/condition.kt
312181124
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtClass // OPTIONS: propertyUsages interface X { val a: String get() { return "" } var b: Int get() { return 0 } set(value: Int) { } fun foo(s: String) { println(s) } } open class <caret>A(val t: String, var u: String) : X { override val a: String get() { return "?" } override var b: Int get() { return 1 } set(value: Int) { println(value) } override fun foo(s: String) { println("!$s!") } } // FIR_COMPARISON
plugins/kotlin/idea/tests/testData/findUsages/kotlin/findClassUsages/kotlinClassPropertyUsages2.0.kt
4274820058
fun Main.test3() { val (_, b) = this }
plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/constructorParameterFromDataClass/componentB/Implicit2.kt
2962008707
// PROBLEM: none interface A { val s: String } fun foo() = Any() fun test(): String { val y = foo() <caret>if (y !is A) return y.toString() return y.s }
plugins/kotlin/idea/tests/testData/inspectionsLocal/foldInitializerAndIfToElvis/UsedInside.kt
2361645171
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package com.example.splitties.prefs import splitties.coroutines.SuspendLazy import splitties.coroutines.suspendBlockingLazyIO import splitties.preferences.Preferences class GamePreferences private constructor() : Preferences("gameState") { companion object : SuspendLazy<GamePreferences> by suspendBlockingLazyIO(::GamePreferences) var magicNumber by intPref("magicNumber", 0) var currentLevel by IntPref("currentLevel", 1) var bossesFought by IntPref("bossBattleVictories", 0) var lastTimePlayed by LongPref("lastSessionTime", 0L) var pseudo by StringPref("playerPseudo", "Player 1") }
samples/android-app/src/main/kotlin/com/example/splitties/prefs/GamePreferences.kt
3051370021
/* * 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 * * 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.jetcaster.ui.player import android.net.Uri import android.os.Bundle import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.AbstractSavedStateViewModelFactory import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.savedstate.SavedStateRegistryOwner import com.example.jetcaster.Graph import com.example.jetcaster.data.EpisodeStore import com.example.jetcaster.data.PodcastStore import java.time.Duration import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch data class PlayerUiState( val title: String = "", val subTitle: String = "", val duration: Duration? = null, val podcastName: String = "", val author: String = "", val summary: String = "", val podcastImageUrl: String = "" ) /** * ViewModel that handles the business logic and screen state of the Player screen */ class PlayerViewModel( episodeStore: EpisodeStore, podcastStore: PodcastStore, savedStateHandle: SavedStateHandle ) : ViewModel() { // episodeUri should always be present in the PlayerViewModel. // If that's not the case, fail crashing the app! private val episodeUri: String = Uri.decode(savedStateHandle.get<String>("episodeUri")!!) var uiState by mutableStateOf(PlayerUiState()) private set init { viewModelScope.launch { val episode = episodeStore.episodeWithUri(episodeUri).first() val podcast = podcastStore.podcastWithUri(episode.podcastUri).first() uiState = PlayerUiState( title = episode.title, duration = episode.duration, podcastName = podcast.title, summary = episode.summary ?: "", podcastImageUrl = podcast.imageUrl ?: "" ) } } /** * Factory for PlayerViewModel that takes EpisodeStore and PodcastStore as a dependency */ companion object { fun provideFactory( episodeStore: EpisodeStore = Graph.episodeStore, podcastStore: PodcastStore = Graph.podcastStore, owner: SavedStateRegistryOwner, defaultArgs: Bundle? = null, ): AbstractSavedStateViewModelFactory = object : AbstractSavedStateViewModelFactory(owner, defaultArgs) { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create( key: String, modelClass: Class<T>, handle: SavedStateHandle ): T { return PlayerViewModel(episodeStore, podcastStore, handle) as T } } } }
Jetcaster/app/src/main/java/com/example/jetcaster/ui/player/PlayerViewModel.kt
3790826112
interface A { fun f() {} } interface B { fun f() {} } interface C : A, B { } fun usage(c: C) { c.<caret>f() }
plugins/kotlin/idea/tests/testData/refactoring/changeSignature/FakeOverrideBefore.kt
1826563884
// WITH_STDLIB //FILE: a/a.kt package a val a = run { val a = 5 val b = run { val c = 2 } 5 } fun x() { println("") } //FILE: b/a.kt package b val b = 5 fun y() { println("") }
plugins/kotlin/jvm-debugger/test/testData/fileRanking/topLevel.kt
689811102
package lib.threejs @native("THREE.Mesh") class Mesh( geometry: Geometry = noImpl, material: Material = noImpl ) : Object3D() { } @native("THREE.PointCloud") class PointCloud(geometry: Geometry, material: Material) : Object3D() { } @native("THREE.Points") class Points( geometry: Geometry = noImpl, material: Material = noImpl ) : Object3D() { } @native("THREE.Line") class Line(geometry: Geometry, material: Material) : Object3D() { }
client/src/lib/threejs/Objects.kt
1094487348
package stan.androiddemo.project.petal.HttpUtiles /** * Created by stanhu on 11/8/2017. */ interface OnProgressResponseListener { fun onResponseProgress(bytesRead: Long, contentLength: Long, done: Boolean) }
app/src/main/java/stan/androiddemo/project/petal/HttpUtiles/OnProgressResponseListener.kt
555199305
// GENERATED package com.fkorotkov.kubernetes.admissionregistration.v1 import io.fabric8.kubernetes.api.model.LabelSelector as model_LabelSelector import io.fabric8.kubernetes.api.model.admissionregistration.v1.MutatingWebhook as v1_MutatingWebhook import io.fabric8.kubernetes.api.model.admissionregistration.v1.ValidatingWebhook as v1_ValidatingWebhook fun v1_MutatingWebhook.`namespaceSelector`(block: model_LabelSelector.() -> Unit = {}) { if(this.`namespaceSelector` == null) { this.`namespaceSelector` = model_LabelSelector() } this.`namespaceSelector`.block() } fun v1_ValidatingWebhook.`namespaceSelector`(block: model_LabelSelector.() -> Unit = {}) { if(this.`namespaceSelector` == null) { this.`namespaceSelector` = model_LabelSelector() } this.`namespaceSelector`.block() }
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/admissionregistration/v1/namespaceSelector.kt
1455163312
package com.marverenic.reader.data.database import com.marverenic.reader.model.Category import com.marverenic.reader.model.Stream import org.joda.time.DateTime interface RssDatabase { fun getStream(streamId: String, unreadOnly: Boolean): Stream? fun getStreamTimestamp(streamId: String, unreadOnly: Boolean): DateTime? fun insertStream(stream: Stream, unreadOnly: Boolean) fun getCategories(): List<Category> fun setCategories(categories: List<Category>) }
app/src/main/java/com/marverenic/reader/data/database/RssDatabase.kt
1501727024
/* * Copyright 2002-2022 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 * * 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 org.springframework.security.config.annotation.web.headers import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.annotation.web.invoke import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension import org.springframework.security.web.SecurityFilterChain import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.get /** * Tests for [ReferrerPolicyDsl] * * @author Eleftheria Stein */ @ExtendWith(SpringTestContextExtension::class) class ReferrerPolicyDslTests { @JvmField val spring = SpringTestContext(this) @Autowired lateinit var mockMvc: MockMvc @Test fun `headers when referrer policy configured then header in response`() { this.spring.register(ReferrerPolicyConfig::class.java).autowire() this.mockMvc.get("/") .andExpect { header { string("Referrer-Policy", ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER.policy) } } } @Configuration @EnableWebSecurity open class ReferrerPolicyConfig { @Bean open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { http { headers { defaultsDisabled = true referrerPolicy { } } } return http.build() } } @Test fun `headers when referrer policy configured with custom policy then custom policy in header`() { this.spring.register(ReferrerPolicyCustomPolicyConfig::class.java).autowire() this.mockMvc.get("/") .andExpect { header { string("Referrer-Policy", ReferrerPolicyHeaderWriter.ReferrerPolicy.SAME_ORIGIN.policy) } } } @Configuration @EnableWebSecurity open class ReferrerPolicyCustomPolicyConfig { @Bean open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { http { headers { defaultsDisabled = true referrerPolicy { policy = ReferrerPolicyHeaderWriter.ReferrerPolicy.SAME_ORIGIN } } } return http.build() } } }
config/src/test/kotlin/org/springframework/security/config/annotation/web/headers/ReferrerPolicyDslTests.kt
2465786485
/* * Copyright 2019 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.ui.badge import android.content.Context import android.os.Build import im.vector.Matrix import me.leolin.shortcutbadger.ShortcutBadger import org.matrix.androidsdk.MXDataHandler import org.matrix.androidsdk.MXSession import org.matrix.androidsdk.core.Log import org.matrix.androidsdk.data.Room import java.util.* /** * Manage application badge (displayed in the launcher) */ object BadgeProxy { private const val LOG_TAG = "BadgeProxy" /** * Badge is now managed by notification channel, so no need to use compatibility library in recent versions * * @return true if library ShortcutBadger can be used */ private fun useShortcutBadger() = Build.VERSION.SDK_INT < Build.VERSION_CODES.O /** * Update the application badge value. * * @param context the context * @param badgeValue the new badge value */ fun updateBadgeCount(context: Context, badgeValue: Int) { if (!useShortcutBadger()) { return } try { ShortcutBadger.setBadge(context, badgeValue) } catch (e: Exception) { Log.e(LOG_TAG, "## updateBadgeCount(): Exception Msg=" + e.message, e) } } /** * Refresh the badge count for specific configurations.<br></br> * The refresh is only effective if the device is: * * offline * does not support FCM * * FCM registration failed * <br></br>Notifications rooms are parsed to track the notification count value. * * @param aSession session value * @param aContext App context */ fun specificUpdateBadgeUnreadCount(aSession: MXSession?, aContext: Context?) { if (!useShortcutBadger()) { return } val dataHandler: MXDataHandler // sanity check if (null == aContext || null == aSession) { Log.w(LOG_TAG, "## specificUpdateBadgeUnreadCount(): invalid input null values") } else { dataHandler = aSession.dataHandler if (dataHandler == null) { Log.w(LOG_TAG, "## specificUpdateBadgeUnreadCount(): invalid DataHandler instance") } else { if (aSession.isAlive) { var isRefreshRequired: Boolean val pushManager = Matrix.getInstance(aContext)!!.pushManager // update the badge count if the device is offline, FCM is not supported or FCM registration failed isRefreshRequired = !Matrix.getInstance(aContext)!!.isConnected isRefreshRequired = isRefreshRequired or (null != pushManager && (!pushManager.useFcm() || !pushManager.hasRegistrationToken())) if (isRefreshRequired) { updateBadgeCount(aContext, dataHandler) } } } } } /** * Update the badge count value according to the rooms content. * * @param aContext App context * @param aDataHandler data handler instance */ private fun updateBadgeCount(aContext: Context?, aDataHandler: MXDataHandler?) { if (!useShortcutBadger()) { return } //sanity check if (null == aContext || null == aDataHandler) { Log.w(LOG_TAG, "## updateBadgeCount(): invalid input null values") } else if (null == aDataHandler.store) { Log.w(LOG_TAG, "## updateBadgeCount(): invalid store instance") } else { val roomCompleteList = aDataHandler.store?.rooms?.toList().orEmpty() var unreadRoomsCount = 0 for (room in roomCompleteList) { if (room.notificationCount > 0) { unreadRoomsCount++ } } // update the badge counter Log.d(LOG_TAG, "## updateBadgeCount(): badge update count=$unreadRoomsCount") updateBadgeCount(aContext, unreadRoomsCount) } } }
vector/src/main/java/im/vector/ui/badge/BadgeProxy.kt
568844170
package com.sksamuel.kotest.matchers import io.kotest.assertions.shouldFail import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.WordSpec import io.kotest.matchers.nulls.beNull import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNot import io.kotest.matchers.string.shouldEndWith import io.kotest.matchers.string.shouldHaveLength import io.kotest.matchers.string.shouldStartWith class ShouldNotBeNullTest : WordSpec() { init { "notBeNull" should { val nullString: String? = null val nonNullString: String? = "Foo" "Pass for a non-null value" { nonNullString.shouldNotBeNull() nonNullString shouldNot beNull() } "Fail for a null value" { shouldThrow<AssertionError> { nullString.shouldNotBeNull() } shouldThrow<AssertionError> { nullString shouldNot beNull() } } "Allow automatic type cast" { fun useString(string: String) {} nonNullString.shouldNotBeNull() useString(nonNullString) nonNullString shouldBe "Foo" } "return the receiver" { val a: String? = "foo" a.shouldNotBeNull().shouldHaveLength(3) val b: String? = null shouldFail { b.shouldNotBeNull() } } "allow fluent chaining" { val a: String? = "foo" a.shouldNotBeNull() .shouldHaveLength(3) .shouldStartWith("fo") .shouldEndWith("oo") } } } }
kotest-assertions/kotest-assertions-core/src/jvmTest/kotlin/com/sksamuel/kotest/matchers/ShouldNotBeNullTest.kt
3275682202
package me.kirimin.mitsumine._common.database import com.activeandroid.query.Select import me.kirimin.mitsumine._common.domain.model.Account object AccountDAO { fun save(account: Account) { account.save() } fun delete() { Select().from(Account::class.java).executeSingle<Account>()?.delete() } fun get(): Account? { return Select().from(Account::class.java).executeSingle<Account>() } }
app/src/main/java/me/kirimin/mitsumine/_common/database/AccountDAO.kt
3469634674
package com.hannesdorfmann.mosby3.conductor.sample.tasks import android.util.Log import com.hannesdorfmann.mosby3.conductor.sample.R import com.hannesdorfmann.mosby3.conductor.sample.model.tasks.TaskDao import com.hannesdorfmann.mosby3.mvp.MvpBasePresenter import com.hannesdorfmann.mosby3.conductor.sample.R.string import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import java.util.* import javax.inject.Inject /** * Tasks Presenter. Responsible to interact with [TasksView] to display a list of tasks * * @author Hannes Dorfmann */ class TasksPresenter @Inject constructor(private val dao: TaskDao) : MvpBasePresenter<TasksView>() { private lateinit var subscription: Subscription /** * Loads the tasks and keep subscribed, so we get automatically updated when we add or remove an item */ fun getTasks() { view?.showLoading(false) subscription = dao.getTasks() .map { val items = ArrayList<TaskListItem>() val (done, open) = it.partition { task -> task.completed } if (open.isNotEmpty()) { items.add(TasksSection(-1, string.tasks_open)) items.addAll(open) } if (done.isNotEmpty()) { items.add(TasksSection(-2, string.tasks_done)) items.addAll(done) } items } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe ({ // onNext list -> view?.setData(list) view?.showContent() }, { // onError view?.showError(it, false) } ) } override fun detachView(retainInstance: Boolean) { super.detachView(retainInstance) if (!retainInstance) { subscription.unsubscribe() } Log.d("Test", "detachView $retainInstance") } }
app/src/main/java/com/hannesdorfmann/mosby3/conductor/sample/tasks/TasksPresenter.kt
772553893
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NOTHING_TO_INLINE") // Aliases to other public API. package androidx.core.util import android.util.AtomicFile import androidx.annotation.RequiresApi import java.io.FileOutputStream import java.nio.charset.Charset /** * Perform the write operations inside [block] on this file. If [block] throws an exception the * write will be failed. Otherwise the write will be applied atomically to the file. */ @RequiresApi(17) inline fun AtomicFile.tryWrite(block: (out: FileOutputStream) -> Unit) { val stream = startWrite() var success = false try { block(stream) success = true } finally { if (success) { finishWrite(stream) } else { failWrite(stream) } } } /** * Sets the content of this file as an [array] of bytes. */ @RequiresApi(17) fun AtomicFile.writeBytes(array: ByteArray) { tryWrite { it.write(array) } } /** * Sets the content of this file as [text] encoded using UTF-8 or specified [charset]. * If this file exists, it becomes overwritten. */ @RequiresApi(17) fun AtomicFile.writeText(text: String, charset: Charset = Charsets.UTF_8) { writeBytes(text.toByteArray(charset)) } /** * Gets the entire content of this file as a byte array. * * This method is not recommended on huge files. It has an internal limitation of 2 GB file size. */ @RequiresApi(17) inline fun AtomicFile.readBytes(): ByteArray = readFully() /** * Gets the entire content of this file as a String using UTF-8 or specified [charset]. * * This method is not recommended on huge files. It has an internal limitation of 2 GB file size. */ @RequiresApi(17) fun AtomicFile.readText(charset: Charset = Charsets.UTF_8): String { return readFully().toString(charset) }
core/ktx/src/main/java/androidx/core/util/AtomicFile.kt
565901952
/* * 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.os import android.os.Build import android.os.PersistableBundle import androidx.annotation.RequiresApi /** * Returns a new [PersistableBundle] with the given key/value pairs as elements. * * @throws IllegalArgumentException When a value is not a supported type of [PersistableBundle]. */ @RequiresApi(21) fun persistableBundleOf(vararg pairs: Pair<String, Any?>) = PersistableBundle(pairs.size).apply { for ((key, value) in pairs) { when (value) { null -> putString(key, null) // Any nullable type will suffice. // Scalars is Boolean -> { if (Build.VERSION.SDK_INT >= 22) { putBoolean(key, value) } else { throw IllegalArgumentException("Illegal value type boolean for key \"$key\"") } } is Double -> putDouble(key, value) is Int -> putInt(key, value) is Long -> putLong(key, value) // References is String -> putString(key, value) // Scalar arrays is BooleanArray -> { if (Build.VERSION.SDK_INT >= 22) { putBooleanArray(key, value) } else { throw IllegalArgumentException("Illegal value type boolean[] for key \"$key\"") } } is DoubleArray -> putDoubleArray(key, value) is IntArray -> putIntArray(key, value) is LongArray -> putLongArray(key, value) // Reference arrays is Array<*> -> { val componentType = value::class.java.componentType @Suppress("UNCHECKED_CAST") // Checked by reflection. when { String::class.java.isAssignableFrom(componentType) -> { putStringArray(key, value as Array<String>) } else -> { val valueType = componentType.canonicalName throw IllegalArgumentException( "Illegal value array type $valueType for key \"$key\"") } } } else -> { val valueType = value.javaClass.canonicalName throw IllegalArgumentException("Illegal value type $valueType for key \"$key\"") } } } }
core/ktx/src/main/java/androidx/core/os/PersistableBundle.kt
2091751553
package com.github.kerubistan.kerub.services import com.github.kerubistan.kerub.data.stat.BasicBalanceReport import com.github.kerubistan.kerub.security.admin import org.apache.shiro.authz.annotation.RequiresAuthentication import org.apache.shiro.authz.annotation.RequiresRoles import javax.ws.rs.Consumes import javax.ws.rs.GET import javax.ws.rs.Path import javax.ws.rs.Produces import javax.ws.rs.core.MediaType @Path("/stats/usage") @RequiresAuthentication @RequiresRoles(admin) @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) interface UsageStatisticsService { @GET @Path("/balance") fun basicBalanceReport(): BasicBalanceReport }
src/main/kotlin/com/github/kerubistan/kerub/services/UsageStatisticsService.kt
155885073
package com.jgabrielfreitas.provider.demo.view.ui.todo import com.jgabrielfreitas.provider.demo.model.Todo /** * Created by JGabrielFreitas on 31/12/16. */ interface TodoListPresenter { fun getTodos(): MutableList<Todo> }
app/src/main/java/com/jgabrielfreitas/provider/demo/view/ui/todo/TodoListPresenter.kt
3661938873
package it.achdjian.paolo.cs5463.domusEngine.rest import android.util.Log import it.achdjian.paolo.cs5463.domusEngine.DomusEngine import it.achdjian.paolo.cs5463.domusEngine.MessageType import it.achdjian.paolo.cs5463.zigbee.ZEndpoint import it.achdjian.paolo.cs5463.zigbee.ZEndpointJSon import java.io.IOException /** * Created by Paolo Achdjian on 7/11/17. */ class GetEndpoint(val nwkAddress: Int, val endpoint_id: Int) : ZigbeeRunnable() { override fun run() { val body = DomusEngineRest.get("/devices/" +nwkAddress.toString(16)+"/endpoint/" + endpoint_id.toString(16)) if (body.isNotBlank()) { try { Log.i("REST", body) val endpointJson = MAPPER.readValue(body, ZEndpointJSon::class.java) if (endpointJson != null) { val zEndpoint = ZEndpoint(endpointJson) Log.i("REST",zEndpoint.toString()) DomusEngine.handler.sendMessage(DomusEngine.handler.obtainMessage(MessageType.NEW_ENDPOINT, zEndpoint)) } } catch (e: IOException) { Log.e(TAG, "Error parsing response for /devices/$nwkAddress/endpoint/$endpoint_id", e) Log.e(TAG, "Response: " + body) e.printStackTrace() } } } }
cs5463/app/src/main/java/it/achdjian/paolo/cs5463/domusEngine/rest/GetEndpoint.kt
3573200398
package org.evomaster.core.problem.rest.resource import org.evomaster.core.Lazy import org.evomaster.core.database.DbAction import org.evomaster.core.problem.rest.* import org.evomaster.core.problem.rest.param.BodyParam import org.evomaster.core.problem.api.service.param.Param import org.evomaster.core.problem.enterprise.EnterpriseActionGroup import org.evomaster.core.problem.rest.param.PathParam import org.evomaster.core.problem.rest.resource.dependency.* import org.evomaster.core.problem.util.ParamUtil import org.evomaster.core.problem.rest.util.ParserUtil import org.evomaster.core.problem.util.RestResourceTemplateHandler import org.evomaster.core.search.ActionFilter import org.evomaster.core.search.ActionResult import org.evomaster.core.search.gene.Gene import org.evomaster.core.search.gene.ObjectGene import org.evomaster.core.search.gene.sql.SqlForeignKeyGene import org.evomaster.core.search.gene.sql.SqlPrimaryKeyGene import org.evomaster.core.search.service.Randomness import org.slf4j.Logger import org.slf4j.LoggerFactory /** * @property path resource path * @property actions actions under the resource, with references of tables * @property initMode configurable option to init resource with additional info, e.g., related tables * @property employNLP specified whether to employ natural language parser */ open class RestResourceNode( val path : RestPath, val actions: MutableList<RestCallAction> = mutableListOf(), val initMode : InitMode, val employNLP : Boolean ) { companion object { private const val PROB_EXTRA_PATCH = 0.8 val log: Logger = LoggerFactory.getLogger(RestResourceNode::class.java) } /** * key is original text of the token * value is PathRToken which contains more analysis info about the original text */ private val tokens : MutableMap<String, PathRToken> = mutableMapOf() /** * segments of a path * since a token may be a combined word, the word can be separator by processing text analysis, * the [segments] can be a flatten list of words for the path (at index 1) or a list of original tokens (at index 0). */ private val segments : MutableList<List<String>> = mutableListOf() init { when(initMode){ InitMode.WITH_TOKEN, InitMode.WITH_DERIVED_DEPENDENCY, InitMode.WITH_DEPENDENCY ->{ if(path.getNonParameterTokens().isNotEmpty()){ tokens.clear() ParserUtil.parsePathTokens(this.path, tokens, employNLP && initMode != InitMode.WITH_DEPENDENCY) } initSegments() } else ->{ //do nothing } } } /** * [ancestors] is ordered, first is closest ancestor, and last is deepest one. */ private val ancestors : MutableList<RestResourceNode> = mutableListOf() /** * possible solutions to prepare resources */ private val creations : MutableList<CreationChain> = mutableListOf() /** * key is id of param which is [getLastTokensOfPath] + [Param.name] * value is detailed info [ParamInfo] including * e.g., whether the param is required to be bound with existing resource (i.e., POST action or table), */ val paramsInfo : MutableMap<String, ParamInfo> = mutableMapOf() /** * collect related tables */ val resourceToTable : ResourceRelatedToTable = ResourceRelatedToTable(path.toString()) /** * HTTP methods under the resource, including possible POST in its ancestors' * last means if there are post actions in its ancestors */ private val verbs : Array<Boolean> = Array(RestResourceTemplateHandler.getSizeOfHandledVerb() + 1){false} /** * key is template with string format * value is template info */ private val templates : MutableMap<String, CallsTemplate> = mutableMapOf() /** * In REST, params of the action might be modified, e.g., for WebRequest * In this case, we modify the [actions] with updated action with new params if there exist, * and backup its original form with [originalActions] */ private val originalActions : MutableList<RestCallAction> = mutableListOf() /** * this init occurs after actions and ancestors are set up */ fun init(){ initVerbs() initCreationPoints() when(initMode){ InitMode.WITH_TOKEN, InitMode.WITH_DERIVED_DEPENDENCY, InitMode.WITH_DEPENDENCY -> initParamInfo() else -> { } } } /** * init ancestors of [this] resource node */ fun initAncestors(resources : List<RestResourceNode>){ resources.forEach {r -> if(!r.path.isEquivalent(this.path) && r.path.isAncestorOf(this.path)) ancestors.add(r) } } /** * @return resource node based on [path] */ fun getResourceNode(path: RestPath) : RestResourceNode?{ if (path.toString() == path.toString()) return this return ancestors.find { it.path.toString() == path.toString() } } /** * @return mutable genes in [dbactions] and they do not bind with rest actions. */ fun getMutableSQLGenes(dbactions: List<DbAction>, template: String, is2POST : Boolean) : List<out Gene>{ val related = getPossiblyBoundParams(template, is2POST).map { resourceToTable.paramToTable[it.key] } return dbactions.filterNot { it.representExistingData }.flatMap { db-> val exclude = related.flatMap { r-> r?.getRelatedColumn(db.table.name)?.toList()?:listOf() } db.seeGenesForInsertion(exclude) }.filter{it.isMutable() && it !is SqlForeignKeyGene && it !is SqlPrimaryKeyGene} } /** * @return mutable genes in [actions] which perform action on current [this] resource node * with [callsTemplate] template, e.g., POST-GET */ private fun getMutableRestGenes(actions: List<RestCallAction>, template: String) : List<out Gene>{ if (!RestResourceTemplateHandler.isNotSingleAction(template)) return actions.flatMap(RestCallAction::seeTopGenes).filter(Gene::isMutable) val missing = getPossiblyBoundParams(template, false) val params = mutableListOf<Param>() (actions.indices).forEach { i -> val a = actions[i] if (i != actions.size-1 && (i == 0 || a.verb == HttpVerb.POST)) { params.addAll(a.parameters) } else{ //add the parameters which does not bind with POST if exist params.addAll(a.parameters.filter { p-> missing.none { m-> m.key == getParamId(a.parameters, p) } }) } } return params.flatMap(Param::seeGenes).filter(Gene::isMutable) } private fun initVerbs(){ actions.forEach { a-> RestResourceTemplateHandler.getIndexOfHttpVerb(a.verb).let { if(it == -1) throw IllegalArgumentException("cannot handle the action with ${a.verb}") else verbs[it] = true } } verbs[verbs.size - 1] = verbs[RestResourceTemplateHandler.getIndexOfHttpVerb(HttpVerb.POST)] if (!verbs[verbs.size - 1]){ if(ancestors.isNotEmpty()) verbs[verbs.size - 1] = ancestors.any { a -> a.actions.any { ia-> ia.verb == HttpVerb.POST } } } RestResourceTemplateHandler.initSampleSpaceOnlyPOST(verbs, templates) assert(templates.isNotEmpty()) } //if only get fun isIndependent() : Boolean{ return templates.all { it.value.independent } && (creations.none { c->c.isComplete() } && resourceToTable.paramToTable.isEmpty()) } // if only post, the resource does not contain any independent action fun hasIndependentAction() : Boolean{ return (1 until (verbs.size - 1)).find { verbs[it]} != null } /************************** creation manage*********************************/ /** * @return related table for creating resource for [this] node with sql */ fun getSqlCreationPoints() : List<String>{ if (resourceToTable.confirmedSet.isNotEmpty()) return resourceToTable.confirmedSet.keys.toList() return resourceToTable.derivedMap.keys.toList() } /** * @return whether there exist POST action (either from [this] node or its [ancestors]) to create the resource */ fun hasPostCreation() = creations.any { it is PostCreationChain && it.actions.isNotEmpty() } || verbs.first() private fun initCreationPoints(){ val postCreation = PostCreationChain(mutableListOf()) val posts = actions.filter { it.verb == HttpVerb.POST} val post : RestCallAction? = when { posts.isEmpty() -> { chooseClosestAncestor(path, listOf(HttpVerb.POST)) } posts.size == 1 -> { posts[0] } else -> null }?.copy() as? RestCallAction if(post != null){ postCreation.actions.add(0, post) if ((post).path.hasVariablePathParameters() && (!post.path.isLastElementAParameter()) || post.path.getVariableNames().size >= 2) { nextCreationPoints(post.path, postCreation) }else postCreation.confirmComplete() }else{ if(path.hasVariablePathParameters()) { postCreation.confirmIncomplete(path.toString()) }else postCreation.confirmComplete() } if (postCreation.actions.isNotEmpty()) creations.add(postCreation) } private fun nextCreationPoints(path:RestPath, postCreationChain: PostCreationChain){ val post = chooseClosestAncestor(path, listOf(HttpVerb.POST))?.copy() as? RestCallAction if(post != null){ postCreationChain.actions.add(0, post) if (post.path.hasVariablePathParameters() && (!post.path.isLastElementAParameter()) || post.path.getVariableNames().size >= 2) { nextCreationPoints(post.path, postCreationChain) }else postCreationChain.confirmComplete() }else{ postCreationChain.confirmIncomplete(path.toString()) } } private fun getCreation(predicate: (CreationChain) -> Boolean) : CreationChain?{ return creations.find(predicate) } fun getPostChain() : PostCreationChain?{ return getCreation { creationChain : CreationChain -> (creationChain is PostCreationChain) }?.run { this as PostCreationChain } } /***********************************************************/ /** * generated another resource calls which differs from [calls] */ fun generateAnother(calls : RestResourceCalls, randomness: Randomness, maxTestSize: Int) : RestResourceCalls?{ val current = calls.template?.template?: RestResourceTemplateHandler.getStringTemplateByActions(calls.seeActions(ActionFilter.NO_SQL).filterIsInstance<RestCallAction>()) val rest = templates.filter { it.value.template != current} if(rest.isEmpty()) return null val selected = randomness.choose(rest.keys) return createRestResourceCallBasedOnTemplate(selected,randomness, maxTestSize) } /** * @return a number of dependent templates in [this] resource node */ fun numOfDepTemplate() : Int{ return templates.values.count { !it.independent } } /** * @return a number of templates in [this] resource node */ fun numOfTemplates() : Int{ return templates.size } /** * @return a rest resource call at random */ fun randomRestResourceCalls(randomness: Randomness, maxTestSize: Int): RestResourceCalls{ val randomTemplates = templates.filter { e-> e.value.size in 1..maxTestSize }.map { it.key } if(randomTemplates.isEmpty()) return sampleOneAction(null, randomness) return createRestResourceCallBasedOnTemplate(randomness.choose(randomTemplates), randomness, maxTestSize) } /** * sample an independent rest resource call, i.e., with an independent template */ fun sampleIndResourceCall(randomness: Randomness, maxTestSize: Int) : RestResourceCalls{ selectTemplate({ call : CallsTemplate -> call.independent || (call.template == HttpVerb.POST.toString() && call.size > 1)}, randomness)?.let { return createRestResourceCallBasedOnTemplate(it.template, randomness, maxTestSize) } return createRestResourceCallBasedOnTemplate(HttpVerb.POST.toString(), randomness,maxTestSize) } /** * sample a rest resource with one action based on the specified [verb] * if [verb] is null, select an action at random from available [actions] in this node */ fun sampleOneAction(verb : HttpVerb? = null, randomness: Randomness) : RestResourceCalls{ val al = if(verb != null) getActionByHttpVerb(actions, verb) else randomness.choose(actions) return sampleOneAction(al!!.copy() as RestCallAction, randomness) } /** * sample a rest resource call with given [action]. * The return action is initialized */ fun sampleOneAction(action : RestCallAction, randomness: Randomness) : RestResourceCalls{ val copy = action.copy() as RestCallAction if(copy.isInitialized()){ copy.randomize(randomness,false) } else { copy.doInitialize(randomness) } val template = templates[copy.verb.toString()] ?: throw IllegalArgumentException("${copy.verb} is not one of templates of ${this.path}") val call = RestResourceCalls(template, this, mutableListOf(EnterpriseActionGroup(copy))) if(action.verb == HttpVerb.POST){ getCreation { c : CreationChain -> (c is PostCreationChain) }.let { if(it != null && (it as PostCreationChain).actions.size == 1 && it.isComplete()){ call.status = ResourceStatus.CREATED_REST }else{ call.status = ResourceStatus.NOT_FOUND_DEPENDENT } } }else call.status = ResourceStatus.NOT_NEEDED return call } /** * sample a rest resource call * @param randomness * @param maxTestSize specified the max size of rest actions in this call * @param prioriDependent specified whether it is perferred to sample an independent call * @param prioriIndependent specified whether it is perferred to sample a dependent call */ fun sampleAnyRestResourceCalls(randomness: Randomness, maxTestSize: Int, prioriIndependent : Boolean = false, prioriDependent : Boolean = false) : RestResourceCalls{ if (maxTestSize < 1 && prioriDependent == prioriIndependent && prioriDependent){ throw IllegalArgumentException("unaccepted args") } val fchosen = templates.filter { it.value.size <= maxTestSize } if(fchosen.isEmpty()) return sampleOneAction(null,randomness) val chosen = if (prioriDependent) fchosen.filter { !it.value.independent } else if (prioriIndependent) fchosen.filter { it.value.independent } else fchosen if (chosen.isEmpty()) return createRestResourceCallBasedOnTemplate(randomness.choose(fchosen).template,randomness, maxTestSize) return createRestResourceCallBasedOnTemplate(randomness.choose(chosen).template,randomness, maxTestSize) } /** * sample a resource call with the specified [template] */ fun sampleRestResourceCalls(template: String, randomness: Randomness, maxTestSize: Int) : RestResourceCalls{ assert(maxTestSize > 0) return createRestResourceCallBasedOnTemplate(template,randomness, maxTestSize) } /** * @return creation chain with POST */ fun genPostChain(randomness: Randomness, maxTestSize: Int) : RestResourceCalls?{ val template = templates["POST"]?: return null return createRestResourceCallBasedOnTemplate(template.template, randomness, maxTestSize) } private fun handleHeadLocation(actions: List<RestCallAction>) : RestCallAction{ if (actions.size == 1) return actions.first() (1 until actions.size).forEach { i-> handleHeaderLocation(actions[i-1], actions[i]) } return actions.last() } private fun handleHeaderLocation(post: RestCallAction, target: RestCallAction){ /* Once the POST is fully initialized, need to fix links with target */ if (!post.path.isEquivalent(target.path)) { /* eg POST /x GET /x/{id} */ post.saveLocation = true target.locationId = post.path.lastElement() } else { /* eg POST /x POST /x/{id}/y GET /x/{id}/y */ //not going to save the position of last POST, as same as target post.saveLocation = false // the target (eg GET) needs to use the location of first POST, or more correctly // the same location used for the last POST (in case there is a deeper chain) target.locationId = post.locationId } } /** * create rest resource call based on the specified [template] */ fun createRestResourceCallBasedOnTemplate(template: String, randomness: Randomness, maxTestSize: Int): RestResourceCalls{ if(!templates.containsKey(template)) throw IllegalArgumentException("$template does not exist in $path") val ats = RestResourceTemplateHandler.parseTemplate(template) // POST-*, * val results = mutableListOf<RestCallAction>() var status = ResourceStatus.NOT_NEEDED val first = ats.first() var lastPost:RestCallAction? = null if (first == HttpVerb.POST){ val post = getPostChain() if (post == null) status = ResourceStatus.NOT_FOUND else{ results.addAll(post.createPostChain(randomness)) // handle header location lastPost = handleHeadLocation(results) if (!post.isComplete()) status = ResourceStatus.NOT_FOUND_DEPENDENT else{ status = ResourceStatus.CREATED_REST } } }else{ results.add(createActionByVerb(first, randomness)) } if (ats.size == 2){ val action = createActionByVerb(ats[1], randomness) if (lastPost != null) handleHeaderLocation(lastPost, action) results.add(action) }else if (ats.size > 2){ throw IllegalStateException("the size of action with $template should be less than 2, but it is ${ats.size}") } //append extra patch if (ats.last() == HttpVerb.PATCH && results.size +1 <= maxTestSize && randomness.nextBoolean(PROB_EXTRA_PATCH)){ val second = results.last().copy() as RestCallAction if (lastPost != null) handleHeaderLocation(lastPost, second) results.add(second) } if (results.size > maxTestSize){ log.info("the size (${results.size}) of actions exceeds the max size ($maxTestSize) in resource node $path") val removeFirst = results.size - maxTestSize results.drop(removeFirst) status = ResourceStatus.NOT_ENOUGH_LENGTH } //TODO unsure about this one results.forEach { if(!it.isInitialized()) it.doInitialize(randomness) } return RestResourceCalls( templates[template]!!, this, results.map { EnterpriseActionGroup(it) }.toMutableList(), withBinding= true, randomness = randomness ).apply { this.status = status } } private fun createActionByVerb(verb : HttpVerb, randomness: Randomness) : RestCallAction{ val action = (getActionByHttpVerb(actions, verb) ?:throw IllegalStateException("cannot get $verb action in the resource $path")) .copy() as RestCallAction if(action.isInitialized()) action.randomize(randomness, false) else action.doInitialize(randomness) return action } private fun templateSelected(callsTemplate: CallsTemplate){ templates.getValue(callsTemplate.template).times += 1 } private fun selectTemplate(predicate: (CallsTemplate) -> Boolean, randomness: Randomness, chosen : Map<String, CallsTemplate>?=null, chooseLessVisit : Boolean = false) : CallsTemplate?{ val ts = if(chosen == null) templates.filter { predicate(it.value) } else chosen.filter { predicate(it.value) } if(ts.isEmpty()) return null val template = if(chooseLessVisit) ts.asSequence().sortedBy { it.value.times }.first().value else randomness.choose(ts.values) templateSelected(template) return template } private fun getActionByHttpVerb(actions : List<RestCallAction>, verb : HttpVerb) : RestCallAction? { return actions.find { a -> a.verb == verb } } private fun chooseLongestPath(actions: List<RestCallAction>, randomness: Randomness? = null): RestCallAction { if (actions.isEmpty()) { throw IllegalArgumentException("Cannot choose from an empty collection") } val candidates = ParamUtil.selectLongestPathAction(actions) if(randomness == null){ return candidates.first() }else return randomness.choose(candidates).copy() as RestCallAction } private fun chooseClosestAncestor(path: RestPath, verbs: List<HttpVerb>): RestCallAction? { val ar = if(path.toString() == this.path.toString()){ this }else{ ancestors.find { it.path.toString() == path.toString() } } ar?.let{ val others = hasWithVerbs(it.ancestors.flatMap { it.actions }, verbs) if(others.isEmpty()) return null return chooseLongestPath(others) } return null } private fun hasWithVerbs(actions: List<RestCallAction>, verbs: List<HttpVerb>): List<RestCallAction> { return actions.filter { a -> verbs.contains(a.verb) } } /********************** utility *************************/ /** * during the search, params of the Rest Action might be updated, * this method is to update [actions] in this node based on the updated [action] */ open fun updateActionsWithAdditionalParams(action: RestCallAction){ val org = actions.find { it.verb == action.verb } org?:throw IllegalStateException("cannot find the action (${action.getName()}) in the node $path") if (action.parameters.size > org.parameters.size){ originalActions.add(org) actions.remove(org) val example = action.copy() as RestCallAction example.resetLocalId() example.resetProperties() actions.add(example) } } /** * @return whether the [text] is part of static tokens in the path of [this] resource node */ fun isPartOfStaticTokens(text : String) : Boolean{ return tokens.any { token -> token.equals(text) } } /** * @return derived tables */ fun getDerivedTables() : Set<String> = resourceToTable.derivedMap.flatMap { it.value.map { m->m.targetMatched } }.toHashSet() /** * @return is any POST, GET, PATCH, DELETE, PUT action? */ fun isAnyAction() : Boolean{ verbs.forEach { if (it) return true } return false } /** * @return name of the resource node */ fun getName() : String = path.toString() /** * @return tokens map */ fun getTokenMap() : Map<String, PathRToken> = tokens.toMap() /** * @return flatten tokens */ fun getFlatViewOfTokens(excludeStar : Boolean = true) : List<PathRToken> = tokens.values.filter { !excludeStar || !it.isStar()}.flatMap { p -> if(p.subTokens.isNotEmpty()) p.subTokens else mutableListOf(p) }.toList() /******************** manage param *************************/ /** * @return param id of [param] with given [params] */ fun getParamId(params: List<Param>, param : Param) : String = "${param::class.java.simpleName}:${getParamName(params, param)}" private fun getParamName(params: List<Param>, param : Param) : String = ParamUtil.appendParam(getSegment(false, params, param), param.name) /* e.g., /A/{a}/B/c/{b} return B@c */ private fun getLastSegment() : String = if(tokens.isNotEmpty()) tokens.values.last().segment else "" private fun getLastSegment(flatten : Boolean) : String { if(tokens.isEmpty()) return "" return getSegment(flatten, tokens.values.last()) } private fun getSegment(flatten : Boolean, level: Int) : String{ if(tokens.isEmpty()) return "" val target = tokens.values.find { it.level == level }?:tokens.values.last() return getSegment(flatten, target) } private fun getSegment(flatten : Boolean, target: PathRToken) : String{ if (!flatten) return target.segment val nearLevel = target.nearestParamLevel val array = tokens.values.filter { it.level > nearLevel && (if(target.isParameter) it.level < target.level else it.level <= target.level)} .flatMap { if(it.subTokens.isNotEmpty()) it.subTokens.map { s->s.getKey() } else mutableListOf(it.getKey()) }.toTypedArray() return ParamUtil.generateParamId(array) } private fun getParamLevel(params: List<Param>, param: Param) : Int{ if (param !is PathParam) return tokens.size tokens.values.filter { it.isParameter && it.originalText.equals(param.name, ignoreCase = true) }.let { if(it.isEmpty()){ //log.warn(("cannot find the path param ${param.name} in the path of the resource ${getName()}")) if(params.any { p-> param.name.equals(p.name, ignoreCase = true) }) return tokens.size } if(it.size == 1) return it.first().level val index = params.filter { p->p.name == param.name }.indexOf(param) return it[index].level } } private fun getSegment(flatten: Boolean, params: List<Param>, param: Param) : String{ val level = getParamLevel(params, param) return getSegment(flatten, level) } /** * @return all segments of the path * @param flatten specified whether to return flatten segments or not */ fun getAllSegments(flatten: Boolean) : List<String>{ assert(segments.size == 2) return if(flatten) segments[1] else segments[0] } private fun initSegments(){ val levels = mutableSetOf<Int>() tokens.values.filter { it.isParameter }.forEach { levels.add(it.level) } if (!path.isLastElementAParameter()) levels.add(tokens.size) segments.add(0, levels.toList().sorted().map { getSegment(false, it) }) segments.add(1, levels.toList().sorted().map { getSegment(true, it) }) assert(segments.size == 2) } /** * @return reference types in [this] resource node */ fun getRefTypes() : Set<String>{ return paramsInfo.filter { it.value.referParam is BodyParam && it.value.referParam.gene is ObjectGene && (it.value.referParam.gene as ObjectGene).refType != null}.map { ((it.value.referParam as BodyParam).gene as ObjectGene).refType!! }.toSet() } /** * @return is any parameter different with the given [action]? * Note that here the difference does not mean the value, and it means e.g., whether there exist a new parameter */ fun anyParameterChanged(action : RestCallAction) : Boolean{ val target = actions.find { it.getName() == action.getName() } ?: throw IllegalArgumentException("cannot find the action ${action.getName()} in the resource ${getName()}") return action.parameters.size != target.parameters.size } /** * @return whether there exists any additional parameters by comparing with [action]? */ fun updateAdditionalParams(action: RestCallAction) : Map<String, ParamInfo>?{ (actions.find { it.getName() == action.getName() } ?: throw IllegalArgumentException("cannot find the action ${action.getName()} in the resource ${getName()}")) as RestCallAction val additionParams = action.parameters.filter { p-> paramsInfo[getParamId(action.parameters, p)] == null} if(additionParams.isEmpty()) return null return additionParams.map { p-> Pair(getParamId(action.parameters, p), initParamInfo(action.verb, action.parameters, p)) }.toMap() } /** * update param info of [param] based on [action] and [param] */ fun updateAdditionalParam(action: RestCallAction, param: Param) : ParamInfo{ return initParamInfo(action.verb, action.parameters, param).also { it.fromAdditionInfo = true } } private fun initParamInfo(){ paramsInfo.clear() /* parameter that is required to bind with post action, or row of tables 1) path parameter in the middle of the path, i.e., /A/{a}/B/{b}, {a} is required to bind 2) GET, DELETE, PATCH, PUT(-prob), if the parameter refers to "id", it is required to bind, in most case, the parameter is either PathParam or QueryParam 3) other parameter, it is not necessary to bind, but it helps if it is bound. e.g., Request to get a list of data whose value is less than "parameter", if bind with an existing data, the requests make more sentence than a random data */ if (tokens.isEmpty()) return actions.forEach { a -> a.parameters.forEach{p-> initParamInfo(a.verb, a.parameters, p) } } } private fun initParamInfo(verb: HttpVerb, params: List<Param>, param: Param) : ParamInfo{ val key = getParamId(params,param) val segment = getSegment(flatten = true, params = params,param = param) val level = getAllSegments(true).indexOf(segment) val doesReferToOther = when(param){ /* if has POST, ignore the last path param, otherwise all path param */ is PathParam->{ !verbs[RestResourceTemplateHandler.getIndexOfHttpVerb(HttpVerb.POST)] || getParamLevel(params, param) < tokens.size - 1 }else->{ false } } val paramInfo = paramsInfo.getOrPut(key){ ParamInfo(param.name, key, segment, level, param, doesReferToOther) } paramInfo.involvedAction.add(verb) return paramInfo } /** * @return params in a [RestResourceCalls] that are not bounded with POST actions if there exist based on the template [actionTemplate] * */ open fun getPossiblyBoundParams(actionTemplate: String, withSql : Boolean) : List<ParamInfo>{ val actions = RestResourceTemplateHandler.parseTemplate(actionTemplate) Lazy.assert { actions.isNotEmpty() } when(actions[0]){ HttpVerb.POST->{ if (withSql) return paramsInfo.values.toList() return paramsInfo.values.filter { it.doesReferToOther } } HttpVerb.PATCH, HttpVerb.PUT->{ return paramsInfo.values.filter { it.involvedAction.contains(actions[0]) && (it.referParam is PathParam || it.name.toLowerCase().contains("id"))} } HttpVerb.GET, HttpVerb.DELETE->{ return paramsInfo.values.filter { it.involvedAction.contains(actions[0]) } } else ->{ return listOf() } } } /** * @return template based on the [key] */ fun getTemplate(key: String) : CallsTemplate{ if (templates.containsKey(key)) return templates.getValue(key) throw IllegalArgumentException("cannot find $key template in the node $path") } /** * @return all templates */ fun getTemplates() : Map<String, CallsTemplate> = templates.toMap() /** * collect feedbacks of prepared resources based on the execution */ fun confirmFailureCreationByPost(calls: RestResourceCalls, action: RestCallAction, result: ActionResult){ if (result !is RestCallResult) return val fail = action.verb.run { this == HttpVerb.POST || this == HttpVerb.PUT} && calls.status == ResourceStatus.CREATED_REST && result.getStatusCode().run { this !in 200..299} if (fail && creations.isNotEmpty()){ creations.filter { it is PostCreationChain && calls.seeActions(ActionFilter.NO_SQL).map { a->a.getName() }.containsAll(it.actions.map { a-> a.getName() }) }.apply { if (size == 1) (first() as PostCreationChain).confirmFailure() } } } override fun toString(): String { return getName() } } enum class InitMode{ NONE, WITH_TOKEN, /** * [WITH_DERIVED_DEPENDENCY] subsume [WITH_TOKEN] */ WITH_DERIVED_DEPENDENCY, WITH_DEPENDENCY } /** * extract info for a parm * * @property name a name of param * @property key is generated based on [getParamId] * @property preSegment refers to the segment of the param in the path * @property segmentLevel refers to the level of param * @property referParam refers to the instance of Param in the cluster * @property doesReferToOther indicates whether the param is required to refer to a resource, * e.g., GET /foo/{id}, with GET, {id} refers to a resource which cannot be created by the current action * @property involvedAction indicates the actions which exists such param, * e.g., GET, PATCH might have the same param named id * @property fromAdditionInfo indicates whether the param is added later, * e.g., during the search */ data class ParamInfo( val name : String, val key : String, val preSegment : String, //by default is flatten segment val segmentLevel : Int, val referParam : Param, val doesReferToOther : Boolean, val involvedAction : MutableSet<HttpVerb> = mutableSetOf(), var fromAdditionInfo : Boolean = false )
core/src/main/kotlin/org/evomaster/core/problem/rest/resource/RestResourceNode.kt
154572126
package wiki.depasquale.mcache enum class CacheMode { CACHE, FILE }
mcache/src/main/java/wiki/depasquale/mcache/CacheMode.kt
880320872
package com.sonnyrodriguez.fittrainer.fittrainerbasic.ui.layout import android.content.Context import android.widget.Button import android.widget.TextView import org.jetbrains.anko._LinearLayout class StatusLayout(ctx: Context) : _LinearLayout(ctx) { lateinit var muscleGroupTextView: TextView lateinit var muscleCountText: TextView lateinit var exerciseTitleText: TextView lateinit var startAction: Button }
mobile/src/main/java/com/sonnyrodriguez/fittrainer/fittrainerbasic/ui/layout/StatusLayout.kt
699016631