content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.core
typealias Checker = Reader.() -> Boolean
val ALWAYS_AVAILABLE_CHECKER = checker { true }
fun checker(check: Checker) = check
interface ContextOwner {
val context: Context
}
interface ActivityCheckerOwner {
val isAvailable: Checker
fun isActive(reader: Reader) = isAvailable(reader)
} | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/Checker.kt | 1965515389 |
package com.jetbrains.builtInHelp.search
data class HelpSearchResult(var number: Int, var url: String, var snippet: String, var title: String, var categories: List<String>)
| plugins/built-in-help/src/com/jetbrains/builtInHelp/search/HelpSearchResult.kt | 74070427 |
fun foo(p: Any?) {
if (x(p == null)) {
print("returned true")
return
}
<caret>p?.hashCode()
} | plugins/kotlin/idea/tests/testData/resolve/partialBodyResolve/IfCallWithConditionReturn.kt | 1553195597 |
/*
* Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores>
*
* The MIT License (MIT)
*
* Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.jonathanxd.kores.base
import com.github.jonathanxd.kores.Instruction
/**
* Throws [value].
*/
data class ThrowException(override val value: Instruction) : Instruction, ValueHolder {
override fun builder(): Builder = Builder(this)
class Builder() : ValueHolder.Builder<ThrowException, Builder> {
lateinit var value: Instruction
constructor(defaults: ThrowException) : this() {
this.value = defaults.value
}
override fun value(value: Instruction): Builder {
this.value = value
return this
}
override fun build(): ThrowException = ThrowException(this.value)
companion object {
@JvmStatic
fun builder(): Builder = Builder()
@JvmStatic
fun builder(defaults: ThrowException): Builder = Builder(defaults)
}
}
}
| src/main/kotlin/com/github/jonathanxd/kores/base/ThrowException.kt | 3418651014 |
class A {
operator fun <caret>get(s: String, i: Int) {}
}
fun usage(a: A) {
a["", 42]
A()["", 42]
a.get("", 42)
} | plugins/kotlin/idea/tests/testData/refactoring/changeSignature/GetConventionSwapParametersBefore.kt | 2478847167 |
package org.yframework.android.util.network
import com.google.gson.GsonBuilder
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.*
import java.util.concurrent.TimeUnit
object NetManager {
private const val CONNECT_TIMEOUT_MILLS = 10 * 1000L
private const val READ_TIMEOUT_MILLS = 10 * 1000L
var commonProvider: NetProvider? = null
private set
private val providerMap = HashMap<String, NetProvider>()
private val retrofitMap = HashMap<String, Retrofit>()
private val clientMap = HashMap<String, OkHttpClient>()
operator fun <S> get(baseURL: String, service: Class<S>, provider: NetProvider? = null): S {
return getRetrofit(baseURL, provider).create(service)
}
@JvmOverloads
fun getRetrofit(baseURL: String, provider: NetProvider? = null): Retrofit {
var p = provider
check(!empty(baseURL)) { "基础URL不能为空" }
if (retrofitMap[baseURL] != null) {
return retrofitMap[baseURL]!!
}
if (p == null) {
p = providerMap[baseURL]
if (p == null) {
p = commonProvider
}
}
checkProvider(p)
val gson = GsonBuilder()
.setDateFormat("yyyy-MM-dd HH:mm:ss")
.create()
val builder = Retrofit.Builder()
.baseUrl(baseURL)
.client(getClient(baseURL, p!!))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
val retrofit = builder.build()
retrofitMap[baseURL] = retrofit
providerMap[baseURL] = p
return retrofit
}
fun getRetrofitMap(): Map<String, Retrofit> {
return retrofitMap
}
fun getClientMap(): Map<String, OkHttpClient> {
return clientMap
}
fun registerProvider(provider: NetProvider) {
commonProvider = provider
}
fun registerProvider(baseURL: String, provider: NetProvider) {
providerMap[baseURL] = provider
}
fun clearCache() {
retrofitMap.clear()
clientMap.clear()
}
private fun empty(baseURL: String?): Boolean {
return baseURL == null || baseURL.isEmpty()
}
private fun getClient(baseURL: String, provider: NetProvider): OkHttpClient {
if (empty(baseURL)) {
throw IllegalStateException("baseURL can not be null")
}
if (clientMap[baseURL] != null) {
return clientMap[baseURL]!!
}
checkProvider(provider)
val builder = OkHttpClient.Builder()
builder.connectTimeout(
if (provider.configConnectTimeoutSecs() != 0L)
provider.configConnectTimeoutSecs()
else
CONNECT_TIMEOUT_MILLS, TimeUnit.SECONDS
)
builder.readTimeout(
if (provider.configReadTimeoutSecs() != 0L)
provider.configReadTimeoutSecs()
else
READ_TIMEOUT_MILLS, TimeUnit.SECONDS
)
builder.writeTimeout(
if (provider.configWriteTimeoutSecs() != 0L)
provider.configReadTimeoutSecs()
else
READ_TIMEOUT_MILLS, TimeUnit.SECONDS
)
val cookieJar = provider.configCookie()
if (cookieJar != null) {
builder.cookieJar(cookieJar)
}
provider.configHttps(builder)
val handler = provider.configHandler()
builder.addInterceptor(NetInterceptor(handler))
val interceptors = provider.configInterceptors()
if (!empty(interceptors)) {
for (interceptor in interceptors!!) {
builder.addInterceptor(interceptor)
}
}
if (provider.configLogEnable()) {
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
builder.addInterceptor(loggingInterceptor)
}
val client = builder.build()
clientMap[baseURL] = client
providerMap[baseURL] = provider
return client
}
private fun empty(interceptors: Array<Interceptor>?): Boolean {
return interceptors == null || interceptors.isEmpty()
}
private fun checkProvider(provider: NetProvider?) {
if (provider == null) {
throw IllegalStateException("must register provider first")
}
}
}
| yframework-android/framework/src/main/java/org/yframework/android/util/network/NetManager.kt | 4266978859 |
package pl.elpassion.elspace.debate.chat
import com.elpassion.android.commons.recycler.basic.WithStableId
data class Comment(override val id: Long,
val userInitials: String,
val userInitialsBackgroundColor: String,
val fullName: String,
val content: String,
val createdAt: Long,
val userId: Long,
val status: String,
var wasShown: Boolean = false) : WithStableId {
val commentStatus: CommentStatus
get() = CommentStatus.valueOf(status.toUpperCase())
}
enum class CommentStatus {
PENDING, ACCEPTED, REJECTED
}
| el-debate/src/main/java/pl/elpassion/elspace/debate/chat/Comment.kt | 762853770 |
package io.dwak.reddit.bot.model.reddit
import com.squareup.moshi.Json
data class AuthData(
@Json(name = "access_token") val accessToken : String,
@Json(name = "expires_in") val expiresIn : Long,
val scope : String,
@Json(name = "token_type") val tokenType : String)
fun AuthData.isValid() {
}
| bot/src/main/kotlin/io/dwak/reddit/bot/model/reddit/AuthData.kt | 103132744 |
package com.github.kurtyan.fanfou4j.request.user
import com.github.kurtyan.fanfou4j.core.AbstractRequest
import com.github.kurtyan.fanfou4j.core.HttpMethod
/**
* Created by yanke on 2016/12/18.
*/
class ListTagsRequest : AbstractRequest<Array<String>>("/users/tag_list.json", HttpMethod.GET){
var id: String by stringDelegate
} | src/main/java/com/github/kurtyan/fanfou4j/request/user/ListTagsRequest.kt | 2129023170 |
package org.pac4j.async.vertx.profile.indirect
import org.pac4j.async.core.context.AsyncWebContext
import org.pac4j.async.core.credentials.extractor.AsyncCredentialsExtractor
import org.pac4j.async.vertx.TEST_CREDENTIALS
import org.pac4j.oauth.credentials.OAuth20Credentials
import java.util.concurrent.CompletableFuture
/**
*
*/
class TestOAuthCredentialsExtractor: AsyncCredentialsExtractor<OAuth20Credentials> {
override fun extract(context: AsyncWebContext?): CompletableFuture<OAuth20Credentials> {
return CompletableFuture.completedFuture(TEST_CREDENTIALS)
}
} | vertx-pac4j-async-demo/src/test/kotlin/org/pac4j/async/vertx/profile/indirect/TestOAuthCredentialsExtractor.kt | 818142185 |
package me.dmillerw.loreexpansion.proxy
import me.dmillerw.loreexpansion.LoreExpansion
import me.dmillerw.loreexpansion.core.LoreLoader
import me.dmillerw.loreexpansion.core.player.PlayerEventHandler
import me.dmillerw.loreexpansion.item.ItemLore
import net.minecraftforge.common.MinecraftForge
import net.minecraftforge.fml.common.event.FMLInitializationEvent
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent
/**
* @author dmillerw
*/
open class CommonProxy {
public open fun preInit(event: FMLPreInitializationEvent) {
ItemLore.register()
LoreLoader.initialize(LoreExpansion.loreFolder)
MinecraftForge.EVENT_BUS.register(PlayerEventHandler)
}
public open fun init(event: FMLInitializationEvent) {
}
public open fun postInit(event: FMLPostInitializationEvent) {
}
} | src/main/kotlin/me/dmillerw/loreexpansion/proxy/CommonProxy.kt | 4248572017 |
package aoc2018.day4
import aoc.util.TestResourceReader
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class SleepyGuardsTest {
@Test
fun part1_mostSleepyGuard_Problem1() {
val guardsWithSleepDurations = parseData(TestResourceReader.readFile("aoc2018/day4/input.txt"))
val (guardId, sleepDurations) = SleepyGuards.mostSleepyGuard(guardsWithSleepDurations)
val totalSleepyMinutes = SleepyGuards.totalSleepDuration(sleepDurations)
val mostSleepyMinute = SleepyGuards.mostSleepyMinute(guardId, sleepDurations)
val answer = guardId * mostSleepyMinute
println("Most Sleepy: #$guardId ($totalSleepyMinutes min asleep, most on min $mostSleepyMinute). Answer: $answer!")
Assertions.assertEquals(2851, guardId)
Assertions.assertEquals(524, totalSleepyMinutes)
Assertions.assertEquals(44, mostSleepyMinute)
}
@Test
fun part2_mostSleepyGuardOnAMinute_Problem1() {
val guardsWithSleepDurations = parseData(TestResourceReader.readFile("aoc2018/day4/input.txt"))
val (guardId, mostSleepyMinuteWithCount) = SleepyGuards.mostSleepyGuardOnAnyMinute(guardsWithSleepDurations)!!
val mostSleepyMinute = mostSleepyMinuteWithCount.first
val mostSleepyMinuteCount = mostSleepyMinuteWithCount.second
val answer = guardId * mostSleepyMinute
println("Most Sleepy: #$guardId, on min $mostSleepyMinute, count: $mostSleepyMinuteCount. Answer: $answer!")
Assertions.assertEquals(733, guardId)
Assertions.assertEquals(25, mostSleepyMinute)
Assertions.assertEquals(16, mostSleepyMinuteCount)
}
@Test
fun part1_mostSleepyGuard_Example1() {
val guardsWithSleepDurations = parseData("""
[1518-11-01 00:00] Guard #10 begins shift
[1518-11-01 00:05] falls asleep
[1518-11-01 00:25] wakes up
[1518-11-01 00:30] falls asleep
[1518-11-01 00:55] wakes up
[1518-11-01 23:58] Guard #99 begins shift
[1518-11-02 00:40] falls asleep
[1518-11-02 00:50] wakes up
[1518-11-03 00:05] Guard #10 begins shift
[1518-11-03 00:24] falls asleep
[1518-11-03 00:29] wakes up
[1518-11-04 00:02] Guard #99 begins shift
[1518-11-04 00:36] falls asleep
[1518-11-04 00:46] wakes up
[1518-11-05 00:03] Guard #99 begins shift
[1518-11-05 00:45] falls asleep
[1518-11-05 00:55] wakes up
""".trimIndent())
val (guardId, sleepDurations) = SleepyGuards.mostSleepyGuard(guardsWithSleepDurations)
val totalSleepyMinutes = SleepyGuards.totalSleepDuration(sleepDurations)
val mostSleepyMinute = SleepyGuards.mostSleepyMinute(guardId, sleepDurations)
val answer = guardId * mostSleepyMinute
println("Most Sleepy: #$guardId ($totalSleepyMinutes min asleep, most on min $mostSleepyMinute). Answer: $answer!")
Assertions.assertEquals(10, guardId)
Assertions.assertEquals(50, totalSleepyMinutes)
Assertions.assertEquals(24, mostSleepyMinute)
}
@Test
fun part2_mostSleepyGuardOnAMinute_Example1() {
val guardsWithSleepDurations = parseData("""
[1518-11-01 00:00] Guard #10 begins shift
[1518-11-01 00:05] falls asleep
[1518-11-01 00:25] wakes up
[1518-11-01 00:30] falls asleep
[1518-11-01 00:55] wakes up
[1518-11-01 23:58] Guard #99 begins shift
[1518-11-02 00:40] falls asleep
[1518-11-02 00:50] wakes up
[1518-11-03 00:05] Guard #10 begins shift
[1518-11-03 00:24] falls asleep
[1518-11-03 00:29] wakes up
[1518-11-04 00:02] Guard #99 begins shift
[1518-11-04 00:36] falls asleep
[1518-11-04 00:46] wakes up
[1518-11-05 00:03] Guard #99 begins shift
[1518-11-05 00:45] falls asleep
[1518-11-05 00:55] wakes up
""".trimIndent())
val (guardId, mostSleepyMinuteWithCount) = SleepyGuards.mostSleepyGuardOnAnyMinute(guardsWithSleepDurations)!!
val mostSleepyMinute = mostSleepyMinuteWithCount.first
val mostSleepyMinuteCount = mostSleepyMinuteWithCount.second
val answer = guardId * mostSleepyMinute
println("Most Sleepy: #$guardId, on min $mostSleepyMinute, count: $mostSleepyMinuteCount. Answer: $answer!")
Assertions.assertEquals(99, guardId)
Assertions.assertEquals(45, mostSleepyMinute)
Assertions.assertEquals(3, mostSleepyMinuteCount)
}
private fun parseData(data: String): Map<Int, List<SleepDuration>> {
val rawDataLines = data.split("\n")
.sorted()
.filterNot(String::isEmpty)
return SleepyGuards.recordGuardSchedules(rawDataLines)
}
}
| src/test/kotlin/aoc2018/day4/SleepyGuardsTest.kt | 1716439222 |
package library
annotation class RecentKotlinAnnotation | plugins/devkit/devkit-java-tests/testData/inspections/missingApi/library/RecentKotlinAnnotation.kt | 811889632 |
// 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 org.jetbrains.plugins.github.api
import com.google.gson.*
import com.google.gson.reflect.TypeToken
import org.jetbrains.io.mandatory.NullCheckingFactory
import org.jetbrains.plugins.github.exceptions.GithubJsonException
import java.awt.Image
import java.io.IOException
import java.io.InputStream
import java.io.Reader
import javax.imageio.ImageIO
object GithubApiContentHelper {
const val JSON_MIME_TYPE = "application/json"
const val V3_JSON_MIME_TYPE = "application/vnd.github.v3+json"
const val V3_HTML_JSON_MIME_TYPE = "application/vnd.github.v3.html+json"
val gson: Gson = GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.registerTypeAdapterFactory(NullCheckingFactory.INSTANCE)
.create()
@Throws(GithubJsonException::class)
inline fun <reified T> fromJson(string: String): T = fromJson(string, T::class.java)
@JvmStatic
@Throws(GithubJsonException::class)
fun <T> fromJson(string: String, clazz: Class<T>): T {
try {
return gson.fromJson(string, TypeToken.get(clazz).type)
}
catch (e: JsonParseException) {
throw GithubJsonException("Can't parse GitHub response", e)
}
}
@JvmStatic
@Throws(GithubJsonException::class)
fun <T> readJson(reader: Reader, typeToken: TypeToken<T>): T {
try {
return gson.fromJson(reader, typeToken.type)
}
catch (e: JsonParseException) {
throw GithubJsonException("Can't parse GitHub response", e)
}
}
@JvmStatic
@Throws(GithubJsonException::class)
fun toJson(content: Any): String {
try {
return gson.toJson(content)
}
catch (e: JsonIOException) {
throw GithubJsonException("Can't serialize GitHub request body", e)
}
}
@JvmStatic
@Throws(IOException::class)
fun loadImage(stream: InputStream): Image {
return ImageIO.read(stream)
}
} | plugins/github/src/org/jetbrains/plugins/github/api/GithubApiContentHelper.kt | 1773527912 |
// 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.service.project.settings
import com.intellij.openapi.application.TransactionGuard
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.model.project.settings.ConfigurationData
import com.intellij.openapi.externalSystem.service.project.IdeModelsProvider
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.encoding.EncodingProjectManager
import com.intellij.openapi.vfs.encoding.EncodingProjectManagerImpl
import com.intellij.openapi.vfs.encoding.EncodingProjectManagerImpl.*
import java.nio.charset.Charset
class EncodingConfigurationHandler : ConfigurationHandler {
override fun onSuccessImport(project: Project,
projectData: ProjectData?,
modelsProvider: IdeModelsProvider,
configuration: ConfigurationData) {
configuration.onEncodingBlock {
val encodingManager = EncodingProjectManager.getInstance(project) as EncodingProjectManagerImpl
val mapping = getCharsetProjectMapping(encodingManager)
TransactionGuard.getInstance().submitTransactionAndWait {
encodingManager.setMapping(mapping)
onCharset("encoding") {
encodingManager.defaultCharsetName = it?.name() ?: ""
}
onBomPolicy("bomPolicy") {
encodingManager.setBOMForNewUtf8Files(it)
}
onMap("properties") {
onCharset("encoding") {
encodingManager.setDefaultCharsetForPropertiesFiles(null, it)
}
onBoolean("transparentNativeToAsciiConversion") {
encodingManager.setNative2AsciiForPropertiesFiles(null, it)
}
}
}
}
}
companion object {
private const val DEFAULT_CHARSET = "<System Default>"
private fun ConfigurationData.onEncodingBlock(action: Map<*, *>.() -> Unit) {
val data = find("encodings")
if (data !is Map<*, *>) return
data.action()
}
private inline fun <reified T> Map<*, *>.on(name: String, action: (T) -> Unit) {
val data = get(name) ?: return
if (data !is T) {
LOG.warn("unexpected type ${data.javaClass.name} of $name encoding configuration, skipping")
return
}
action(data)
}
private fun Map<*, *>.onBomPolicy(name: String, action: (BOMForNewUTF8Files) -> Unit) = on<String>(name) {
val option = when (it) {
"WITH_BOM" -> BOMForNewUTF8Files.ALWAYS
"WITH_NO_BOM" -> BOMForNewUTF8Files.NEVER
"WITH_BOM_ON_WINDOWS" -> BOMForNewUTF8Files.WINDOWS_ONLY
else -> {
LOG.warn("unsupported BOM policy $it of encoding configuration, skipping")
return@on
}
}
action(option)
}
private fun Map<*, *>.onCharset(name: String, action: (Charset?) -> Unit) = on<String>(name) {
if (it == DEFAULT_CHARSET) {
action(null)
return@on
}
val charset = CharsetToolkit.forName(it)
if (charset == null) {
LOG.warn("unsupported charset $it of $name encoding configuration, skipping")
return@on
}
action(charset)
}
private fun Map<*, *>.onMap(name: String, action: Map<*, *>.() -> Unit) = on(name, action)
private fun Map<*, *>.onBoolean(name: String, action: (Boolean) -> Unit) = on(name, action)
private fun Map<*, *>.forEachCharsetMapping(action: (String, String) -> Unit) = onMap("mapping") {
for ((path, charsetName) in this) {
if (path !is String) {
LOG.warn("unexpected path type ${path?.javaClass?.name}, skipping")
continue
}
if (charsetName !is String) {
LOG.warn("unexpected type ${charsetName?.javaClass?.name} of $path encoding configuration, skipping")
continue
}
action(path, charsetName)
}
}
private fun Map<*, *>.getCharsetProjectMapping(encodingManager: EncodingProjectManagerImpl): Map<VirtualFile, Charset> {
val mapping = encodingManager.allMappings.toMutableMap()
forEachCharsetMapping { path, charsetName ->
val url = VfsUtilCore.pathToUrl(FileUtil.toCanonicalPath(path))
val virtualFileManager = VirtualFileManager.getInstance()
val virtualFile = virtualFileManager.findFileByUrl(url)
if (virtualFile == null) {
LOG.warn("mappings file $path not found, skipping")
return@forEachCharsetMapping
}
if (charsetName == DEFAULT_CHARSET) {
mapping.remove(virtualFile)
return@forEachCharsetMapping
}
val charset = CharsetToolkit.forName(charsetName)
if (charset == null) {
LOG.warn("unsupported charset $charsetName of $path encoding configuration, skipping")
return@forEachCharsetMapping
}
mapping[virtualFile] = charset
}
return mapping
}
}
} | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/settings/EncodingConfigurationHandler.kt | 11551602 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.daemon.impl.tagTreeHighlighting
import com.intellij.application.options.editor.WebEditorOptions
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.options.UiDslUnnamedConfigurable
import com.intellij.openapi.project.ProjectManager
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import com.intellij.xml.XmlBundle
import com.intellij.xml.breadcrumbs.BreadcrumbsPanel
class XmlTagTreeHighlightingConfigurable : UiDslUnnamedConfigurable.Simple() {
override fun Panel.createContent() {
val options = WebEditorOptions.getInstance()
lateinit var enable: Cell<JBCheckBox>
panel {
row {
enable = checkBox(XmlBundle.message("settings.enable.html.xml.tag.tree.highlighting"))
.bindSelected(options::isTagTreeHighlightingEnabled, options::setTagTreeHighlightingEnabled)
.onApply { clearTagTreeHighlighting() }
}
indent {
row(XmlBundle.message("settings.levels.to.highlight")) {
spinner(1..50)
.bindIntValue({ options.tagTreeHighlightingLevelCount }, { options.tagTreeHighlightingLevelCount = it })
.onApply { clearTagTreeHighlighting() }
.horizontalAlign(HorizontalAlign.FILL)
cell()
}.layout(RowLayout.PARENT_GRID)
row(XmlBundle.message("settings.opacity")) {
spinner(0.0..1.0, step = 0.05)
.bind({ ((it.value as Double) * 100).toInt() }, { it, value -> it.value = value * 0.01 },
MutableProperty(options::getTagTreeHighlightingOpacity, options::setTagTreeHighlightingOpacity))
.onApply { clearTagTreeHighlighting() }
.horizontalAlign(HorizontalAlign.FILL)
cell()
}.layout(RowLayout.PARENT_GRID)
.bottomGap(BottomGap.SMALL)
}.enabledIf(enable.selected)
}
}
companion object {
private fun clearTagTreeHighlighting() {
for (project in ProjectManager.getInstance().openProjects) {
for (fileEditor in FileEditorManager.getInstance(project).allEditors) {
if (fileEditor is TextEditor) {
val editor = fileEditor.editor
XmlTagTreeHighlightingPass.clearHighlightingAndLineMarkers(editor, project)
val breadcrumbs = BreadcrumbsPanel.getBreadcrumbsComponent(editor)
breadcrumbs?.queueUpdate()
}
}
}
}
}
}
| xml/impl/src/com/intellij/codeInsight/daemon/impl/tagTreeHighlighting/XmlTagTreeHighlightingConfigurable.kt | 765203331 |
package au.com.dius.pact.model
import com.google.gson.GsonBuilder
import mu.KLogging
import java.io.PrintWriter
/**
* Class to write out a pact to a file
*/
object PactWriter : KLogging() {
/**
* Writes out the pact to the provided pact file
* @param pact Pact to write
* @param writer Writer to write out with
* @param pactSpecVersion Pact version to use to control writing
*/
@JvmStatic
@JvmOverloads
fun <I> writePact(pact: Pact<I>, writer: PrintWriter, pactSpecVersion: PactSpecVersion = PactSpecVersion.V3)
where I: Interaction {
pact.sortInteractions()
val jsonData = pact.toMap(pactSpecVersion)
val gson = GsonBuilder().setPrettyPrinting().create()
gson.toJson(jsonData, writer)
}
}
| pact-jvm-model/src/main/kotlin/au/com/dius/pact/model/PactWriter.kt | 3984669409 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.codeInsight
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiManager
import com.intellij.psi.impl.PsiModificationTrackerImpl
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.trackers.outOfBlockModificationCount
import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager
import org.jetbrains.kotlin.idea.test.DirectiveBasedActionUtils
import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.kdoc.psi.api.KDoc
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
import org.jetbrains.kotlin.resolve.lazy.ResolveSession
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
abstract class AbstractOutOfBlockModificationTest : KotlinLightCodeInsightFixtureTestCase() {
protected fun doTest(unused: String?) {
val psiFile = myFixture.configureByFile(fileName())
val ktFile = psiFile.safeAs<KtFile>()
if (ktFile?.isScript() == true) {
ScriptConfigurationManager.updateScriptDependenciesSynchronously(ktFile)
}
val expectedOutOfBlock = expectedOutOfBlockResult
val text = psiFile.text
val isErrorChecksDisabled = InTextDirectivesUtils.isDirectiveDefined(text, DISABLE_ERROR_CHECKS_DIRECTIVE)
val isSkipCheckDefined = InTextDirectivesUtils.isDirectiveDefined(text, SKIP_ANALYZE_CHECK_DIRECTIVE)
val project = myFixture.project
val tracker =
PsiManager.getInstance(project).modificationTracker as PsiModificationTrackerImpl
val element = psiFile.findElementAt(myFixture.caretOffset)
assertNotNull("Should be valid element", element)
val oobBeforeType = ktFile?.outOfBlockModificationCount
val modificationCountBeforeType = tracker.modificationCount
// have to analyze file before any change to support incremental analysis
ktFile?.analyzeWithAllCompilerChecks()
myFixture.type(stringToType)
PsiDocumentManager.getInstance(project).commitDocument(myFixture.getDocument(myFixture.file))
val oobAfterCount = ktFile?.outOfBlockModificationCount
val modificationCountAfterType = tracker.modificationCount
assertTrue(
"Modification tracker should always be changed after type",
modificationCountBeforeType != modificationCountAfterType
)
assertEquals(
"Result for out of block test differs from expected on element in file:\n"
+ FileUtil.loadFile(dataFile()),
expectedOutOfBlock, oobBeforeType != oobAfterCount
)
ktFile?.let {
if (!isErrorChecksDisabled) {
checkForUnexpectedErrors(it)
}
DirectiveBasedActionUtils.inspectionChecks(name, it)
if (!isSkipCheckDefined && !isErrorChecksDisabled) {
checkOOBWithDescriptorsResolve(expectedOutOfBlock)
}
}
}
private fun checkForUnexpectedErrors(ktFile: KtFile) {
val diagnosticsProvider: (KtFile) -> Diagnostics = { it.analyzeWithAllCompilerChecks().bindingContext.diagnostics }
DirectiveBasedActionUtils.checkForUnexpectedWarnings(ktFile, diagnosticsProvider = diagnosticsProvider)
DirectiveBasedActionUtils.checkForUnexpectedErrors(ktFile, diagnosticsProvider = diagnosticsProvider)
}
private fun checkOOBWithDescriptorsResolve(expectedOutOfBlock: Boolean) {
ApplicationManager.getApplication().runWriteAction {
(PsiManager.getInstance(myFixture.project).modificationTracker as PsiModificationTrackerImpl)
.incOutOfCodeBlockModificationCounter()
}
val updateElement = myFixture.file.findElementAt(myFixture.caretOffset - 1)
val kDoc: KDoc? = PsiTreeUtil.getParentOfType(updateElement, KDoc::class.java, false)
val ktExpression: KtExpression? = PsiTreeUtil.getParentOfType(updateElement, KtExpression::class.java, false)
val ktDeclaration: KtDeclaration? = PsiTreeUtil.getParentOfType(updateElement, KtDeclaration::class.java, false)
val ktElement = ktExpression ?: ktDeclaration ?: return
val facade = ktElement.containingKtFile.getResolutionFacade()
@OptIn(FrontendInternals::class)
val session = facade.getFrontendService(ResolveSession::class.java)
session.forceResolveAll()
val context = session.bindingContext
if (ktExpression != null && ktExpression !== ktDeclaration) {
val expression = if (ktExpression is KtFunctionLiteral) ktExpression.getParent() as KtLambdaExpression else ktExpression
val processed = context.get(BindingContext.PROCESSED, expression)
val expressionProcessed = processed === java.lang.Boolean.TRUE
assertEquals(
"Expected out-of-block should result expression analyzed and vise versa", expectedOutOfBlock,
expressionProcessed
)
} else if (updateElement !is PsiComment && kDoc == null) { // comments could be ignored from analyze
val declarationProcessed =
context.get(
BindingContext.DECLARATION_TO_DESCRIPTOR,
ktDeclaration
) != null
assertEquals(
"Expected out-of-block should result declaration analyzed and vise versa", expectedOutOfBlock,
declarationProcessed
)
}
}
private val stringToType: String
get() = stringToType(myFixture)
private val expectedOutOfBlockResult: Boolean
get() {
val text = myFixture.getDocument(myFixture.file).text
val outOfCodeBlockDirective = InTextDirectivesUtils.findStringWithPrefixes(
text,
OUT_OF_CODE_BLOCK_DIRECTIVE
)
assertNotNull(
"${fileName()}: Expectation of code block result test should be configured with " +
"\"// " + OUT_OF_CODE_BLOCK_DIRECTIVE + " TRUE\" or " +
"\"// " + OUT_OF_CODE_BLOCK_DIRECTIVE + " FALSE\" directive in the file",
outOfCodeBlockDirective
)
return outOfCodeBlockDirective?.toBoolean() ?: false
}
companion object {
const val OUT_OF_CODE_BLOCK_DIRECTIVE = "OUT_OF_CODE_BLOCK:"
const val DISABLE_ERROR_CHECKS_DIRECTIVE = "DISABLE_ERROR_CHECKS"
const val SKIP_ANALYZE_CHECK_DIRECTIVE = "SKIP_ANALYZE_CHECK"
const val TYPE_DIRECTIVE = "TYPE:"
fun stringToType(fixture: JavaCodeInsightTestFixture): String {
val text = fixture.getDocument(fixture.file).text
val typeDirectives =
InTextDirectivesUtils.findStringWithPrefixes(text, TYPE_DIRECTIVE)
return if (typeDirectives != null) StringUtil.unescapeStringCharacters(typeDirectives) else "a"
}
}
} | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeInsight/AbstractOutOfBlockModificationTest.kt | 1167785611 |
package au.com.dius.pact.consumer
import au.com.dius.pact.model.FullRequestMatch
import au.com.dius.pact.model.MockHttpsProviderConfig
import au.com.dius.pact.model.MockProviderConfig
import au.com.dius.pact.model.OptionalBody
import au.com.dius.pact.model.PactReader
import au.com.dius.pact.model.PactSpecVersion
import au.com.dius.pact.model.PartialRequestMatch
import au.com.dius.pact.model.Request
import au.com.dius.pact.model.RequestMatching
import au.com.dius.pact.model.RequestResponseInteraction
import au.com.dius.pact.model.RequestResponsePact
import au.com.dius.pact.model.Response
import com.sun.net.httpserver.HttpExchange
import com.sun.net.httpserver.HttpHandler
import com.sun.net.httpserver.HttpServer
import com.sun.net.httpserver.HttpsServer
import mu.KLogging
import org.apache.commons.lang3.StringEscapeUtils
import org.apache.http.client.methods.HttpOptions
import org.apache.http.entity.ContentType
import org.apache.http.impl.client.HttpClients
import org.apache.http.impl.conn.BasicHttpClientConnectionManager
import scala.collection.JavaConversions
import java.lang.Thread.sleep
import java.nio.charset.Charset
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentLinkedQueue
/**
* Returns a mock server for the pact and config
*/
fun mockServer(pact: RequestResponsePact, config: MockProviderConfig): MockServer {
return when (config) {
is MockHttpsProviderConfig -> MockHttpsServer(pact, config)
else -> MockHttpServer(pact, config)
}
}
interface MockServer {
/**
* Returns the URL for this mock server. The port will be the one bound by the server.
*/
fun getUrl(): String
/**
* Returns the port of the mock server. This will be the port the server is bound to.
*/
fun getPort(): Int
/**
* This will start the mock server and execute the test function. Returns the result of running the test.
*/
fun runAndWritePact(pact: RequestResponsePact, pactVersion: PactSpecVersion, testFn: PactTestRun):
PactVerificationResult
/**
* Returns the results of validating the mock server state
*/
fun validateMockServerState(): PactVerificationResult
}
abstract class BaseMockServer(
val pact: RequestResponsePact,
val config: MockProviderConfig,
private val server: HttpServer,
private var stopped: Boolean = false
) : HttpHandler, MockServer {
private val mismatchedRequests = ConcurrentHashMap<Request, MutableList<PactVerificationResult>>()
private val matchedRequests = ConcurrentLinkedQueue<Request>()
private val requestMatcher = RequestMatching.apply(JavaConversions.asScalaBuffer(pact.interactions).toSeq())
override fun handle(exchange: HttpExchange) {
if (exchange.requestMethod == "OPTIONS" && exchange.requestHeaders.containsKey("X-PACT-BOOTCHECK")) {
exchange.responseHeaders.add("X-PACT-BOOTCHECK", "true")
exchange.sendResponseHeaders(200, 0)
exchange.close()
} else {
try {
val request = toPactRequest(exchange)
logger.debug { "Received request: $request" }
val response = generatePactResponse(request)
logger.debug { "Generating response: $response" }
pactResponseToHttpExchange(response, exchange)
} catch (e: Exception) {
logger.error(e) { "Failed to generate response" }
pactResponseToHttpExchange(Response(500, mutableMapOf("Content-Type" to "application/json"),
OptionalBody.body("{\"error\": ${e.message}}")), exchange)
}
}
}
private fun pactResponseToHttpExchange(response: Response, exchange: HttpExchange) {
val headers = response.headers
if (headers != null) {
exchange.responseHeaders.putAll(headers.mapValues { listOf(it.value) })
}
val body = response.body
if (body != null && body.isPresent()) {
val bytes = body.unwrap().toByteArray()
exchange.sendResponseHeaders(response.status, bytes.size.toLong())
exchange.responseBody.write(bytes)
} else {
exchange.sendResponseHeaders(response.status, 0)
}
exchange.close()
}
private fun generatePactResponse(request: Request): Response {
val matchResult = requestMatcher.matchInteraction(request)
when (matchResult) {
is FullRequestMatch -> {
val interaction = matchResult.interaction() as RequestResponseInteraction
matchedRequests.add(interaction.request)
return interaction.response.generatedResponse()
}
is PartialRequestMatch -> {
val interaction = matchResult.problems().keys().head() as RequestResponseInteraction
mismatchedRequests.putIfAbsent(interaction.request, mutableListOf())
mismatchedRequests[interaction.request]?.add(PactVerificationResult.PartialMismatch(
ScalaCollectionUtils.toList(matchResult.problems()[interaction])))
}
else -> {
mismatchedRequests.putIfAbsent(request, mutableListOf())
mismatchedRequests[request]?.add(PactVerificationResult.UnexpectedRequest(request))
}
}
return invalidResponse(request)
}
private fun invalidResponse(request: Request) =
Response(500, mapOf("Access-Control-Allow-Origin" to "*", "Content-Type" to "application/json",
"X-Pact-Unexpected-Request" to "1"), OptionalBody.body("{ \"error\": \"Unexpected request : " +
StringEscapeUtils.escapeJson(request.toString()) + "\" }"))
private fun toPactRequest(exchange: HttpExchange): Request {
val headers = exchange.requestHeaders.mapValues { it.value.joinToString(", ") }
val bodyContents = exchange.requestBody.bufferedReader(calculateCharset(headers)).readText()
val body = if (bodyContents.isNullOrEmpty()) {
OptionalBody.empty()
} else {
OptionalBody.body(bodyContents)
}
return Request(exchange.requestMethod, exchange.requestURI.path,
PactReader.queryStringToMap(exchange.requestURI.rawQuery), headers, body)
}
private fun initServer() {
server.createContext("/", this)
}
fun start() = server.start()
fun stop() {
if (!stopped) {
stopped = true
server.stop(0)
}
}
init {
initServer()
}
override fun runAndWritePact(pact: RequestResponsePact, pactVersion: PactSpecVersion, testFn: PactTestRun):
PactVerificationResult {
start()
waitForServer()
try {
testFn.run(this)
sleep(100) // give the mock server some time to have consistent state
} catch (e: Throwable) {
return PactVerificationResult.Error(e, validateMockServerState())
} finally {
stop()
}
val result = validateMockServerState()
if (result is PactVerificationResult.Ok) {
val pactDirectory = pactDirectory()
logger.debug { "Writing pact ${pact.consumer.name} -> ${pact.provider.name} to file " +
"${pact.fileForPact(pactDirectory)}" }
pact.write(pactDirectory, pactVersion)
}
return result
}
override fun validateMockServerState(): PactVerificationResult {
if (mismatchedRequests.isNotEmpty()) {
return PactVerificationResult.Mismatches(mismatchedRequests.values.flatten())
}
val expectedRequests = pact.interactions.map { it.request }.filter { !matchedRequests.contains(it) }
if (expectedRequests.isNotEmpty()) {
return PactVerificationResult.ExpectedButNotReceived(expectedRequests)
}
return PactVerificationResult.Ok
}
fun waitForServer() {
val httpclient = HttpClients.createMinimal(BasicHttpClientConnectionManager())
val httpOptions = HttpOptions(getUrl())
httpOptions.addHeader("X-PACT-BOOTCHECK", "true")
httpclient.execute(httpOptions).close()
}
override fun getUrl(): String {
return if (config.port == 0) {
"${config.scheme}://${server.address.hostName}:${server.address.port}"
} else {
config.url()
}
}
override fun getPort(): Int = server.address.port
companion object : KLogging()
}
open class MockHttpServer(pact: RequestResponsePact, config: MockProviderConfig)
: BaseMockServer(pact, config, HttpServer.create(config.address(), 0))
open class MockHttpsServer(pact: RequestResponsePact, config: MockProviderConfig)
: BaseMockServer(pact, config, HttpsServer.create(config.address(), 0))
fun calculateCharset(headers: Map<String, String>): Charset {
val contentType = headers.entries.find { it.key.toUpperCase() == "CONTENT-TYPE" }
val default = Charset.forName("UTF-8")
if (contentType != null) {
try {
return ContentType.parse(contentType.value)?.charset ?: default
} catch (e: Exception) {
BaseMockServer.Companion.logger.debug(e) { "Failed to parse the charset from the content type header" }
}
}
return default
}
fun pactDirectory() = System.getProperty("pact.rootDir", "target/pacts")!!
| pact-jvm-consumer/src/main/kotlin/au/com/dius/pact/consumer/MockHttpServer.kt | 429917463 |
// 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.intentions.canBeReplacedWithInvokeCall
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getImplicitReceiverValue
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
object ReplaceWithSafeCallFixFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val psiElement = diagnostic.psiElement
val qualifiedExpression = psiElement.parent as? KtDotQualifiedExpression
if (qualifiedExpression != null) {
val call = qualifiedExpression.callExpression
if (call != null) {
val context = qualifiedExpression.analyze(BodyResolveMode.PARTIAL)
val psiFactory = KtPsiFactory(psiElement.project)
val safeQualifiedExpression = psiFactory.createExpressionByPattern(
"$0?.$1", qualifiedExpression.receiverExpression, call,
reformat = false
)
val newContext = safeQualifiedExpression.analyzeAsReplacement(qualifiedExpression, context)
if (safeQualifiedExpression.getResolvedCall(newContext)?.canBeReplacedWithInvokeCall() == true) {
return ReplaceInfixOrOperatorCallFix(call, call.shouldHaveNotNullType())
}
}
return ReplaceWithSafeCallFix(qualifiedExpression, qualifiedExpression.shouldHaveNotNullType())
} else {
if (psiElement !is KtNameReferenceExpression) return null
if (psiElement.getResolvedCall(psiElement.analyze())?.getImplicitReceiverValue() != null) {
val expressionToReplace: KtExpression = psiElement.parent as? KtCallExpression ?: psiElement
return ReplaceImplicitReceiverCallFix(expressionToReplace, expressionToReplace.shouldHaveNotNullType())
}
return null
}
}
}
object ReplaceWithSafeCallForScopeFunctionFixFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val element = diagnostic.psiElement
val scopeFunctionLiteral = element.getStrictParentOfType<KtFunctionLiteral>() ?: return null
val scopeCallExpression = scopeFunctionLiteral.getStrictParentOfType<KtCallExpression>() ?: return null
val scopeDotQualifiedExpression = scopeCallExpression.getStrictParentOfType<KtDotQualifiedExpression>() ?: return null
val context = scopeCallExpression.analyze()
val scopeFunctionLiteralDescriptor = context[BindingContext.FUNCTION, scopeFunctionLiteral] ?: return null
val scopeFunctionKind = scopeCallExpression.scopeFunctionKind(context) ?: return null
val internalReceiver = (element.parent as? KtDotQualifiedExpression)?.receiverExpression
val internalReceiverDescriptor = internalReceiver.getResolvedCall(context)?.candidateDescriptor
val internalResolvedCall = (element.getParentOfType<KtElement>(strict = false))?.getResolvedCall(context)
?: return null
when (scopeFunctionKind) {
ScopeFunctionKind.WITH_PARAMETER -> {
if (internalReceiverDescriptor != scopeFunctionLiteralDescriptor.valueParameters.singleOrNull()) {
return null
}
}
ScopeFunctionKind.WITH_RECEIVER -> {
if (internalReceiverDescriptor != scopeFunctionLiteralDescriptor.extensionReceiverParameter &&
internalResolvedCall.getImplicitReceiverValue() == null
) {
return null
}
}
}
return ReplaceWithSafeCallForScopeFunctionFix(
scopeDotQualifiedExpression, scopeDotQualifiedExpression.shouldHaveNotNullType()
)
}
private fun KtCallExpression.scopeFunctionKind(context: BindingContext): ScopeFunctionKind? {
val methodName = getResolvedCall(context)?.resultingDescriptor?.fqNameUnsafe?.asString()
return ScopeFunctionKind.values().firstOrNull { kind -> kind.names.contains(methodName) }
}
private enum class ScopeFunctionKind(vararg val names: String) {
WITH_PARAMETER("kotlin.let", "kotlin.also"),
WITH_RECEIVER("kotlin.apply", "kotlin.run")
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceCallFix.kt | 3002713788 |
package com.simplemobiletools.gallery.pro.extensions
import androidx.exifinterface.media.ExifInterface
import java.lang.reflect.Field
import java.lang.reflect.Modifier
fun ExifInterface.copyNonDimensionAttributesTo(destination: ExifInterface) {
val attributes = ExifInterfaceAttributes.AllNonDimensionAttributes
attributes.forEach {
val value = getAttribute(it)
if (value != null) {
destination.setAttribute(it, value)
}
}
try {
destination.saveAttributes()
} catch (ignored: Exception) {
}
}
private class ExifInterfaceAttributes {
companion object {
val AllNonDimensionAttributes = getAllNonDimensionExifAttributes()
private fun getAllNonDimensionExifAttributes(): List<String> {
val tagFields = ExifInterface::class.java.fields.filter { field -> isExif(field) }
val excludeAttributes = arrayListOf(
ExifInterface.TAG_IMAGE_LENGTH,
ExifInterface.TAG_IMAGE_WIDTH,
ExifInterface.TAG_PIXEL_X_DIMENSION,
ExifInterface.TAG_PIXEL_Y_DIMENSION,
ExifInterface.TAG_THUMBNAIL_IMAGE_LENGTH,
ExifInterface.TAG_THUMBNAIL_IMAGE_WIDTH,
ExifInterface.TAG_ORIENTATION)
return tagFields
.map { tagField -> tagField.get(null) as String }
.filter { x -> !excludeAttributes.contains(x) }
.distinct()
}
private fun isExif(field: Field): Boolean {
return field.type == String::class.java &&
isPublicStaticFinal(field.modifiers) &&
field.name.startsWith("TAG_")
}
private const val publicStaticFinal = Modifier.PUBLIC or Modifier.STATIC or Modifier.FINAL
private fun isPublicStaticFinal(modifiers: Int): Boolean {
return modifiers and publicStaticFinal > 0
}
}
}
| app/src/main/kotlin/com/simplemobiletools/gallery/pro/extensions/ExifInterface.kt | 1217351864 |
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.shared.domain.sessions
import com.google.gson.Gson
import com.google.samples.apps.iosched.model.schedule.PinnedSession
import com.google.samples.apps.iosched.model.schedule.PinnedSessionsSchedule
import com.google.samples.apps.iosched.model.userdata.UserSession
import com.google.samples.apps.iosched.shared.data.userevent.DefaultSessionAndUserEventRepository
import com.google.samples.apps.iosched.shared.data.userevent.ObservableUserEvents
import com.google.samples.apps.iosched.shared.di.IoDispatcher
import com.google.samples.apps.iosched.shared.domain.FlowUseCase
import com.google.samples.apps.iosched.shared.result.Result
import com.google.samples.apps.iosched.shared.util.TimeUtils
import com.google.samples.apps.iosched.shared.util.toEpochMilli
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
/**
* Load a list of pinned (starred or reserved) [UserSession]s for a given user as a json format.
*
* Example JSON is structured as
*
* { schedule : [
* {
* "name": "session1",
* "location": "Room 1",
* "day": "5/07",
* "time": "13:30",
* "timestamp": 82547983,
* "description": "Session description1"
* },
* {
* "name": "session2",
* "location": "Room 2",
* "day": "5/08",
* "time": "13:30",
* "timestamp": 19238489,
* "description": "Session description2"
* }, .....
* ]
* }
*/
open class LoadPinnedSessionsJsonUseCase @Inject constructor(
private val userEventRepository: DefaultSessionAndUserEventRepository,
private val gson: Gson,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher
) : FlowUseCase<String, String>(ioDispatcher) {
override fun execute(parameters: String): Flow<Result<String>> {
return userEventRepository.getObservableUserEvents(parameters)
.map { observableResult: Result<ObservableUserEvents> ->
when (observableResult) {
is Result.Success -> {
val useCaseResult = observableResult.data.userSessions.filter {
it.userEvent.isStarredOrReserved()
}.map {
val session = it.session
// We assume the conference time zone because only on-site attendees are
// going to use the feature
val zonedTime =
TimeUtils.zonedTime(
session.startTime,
TimeUtils.CONFERENCE_TIMEZONE
)
PinnedSession(
name = session.title,
location = session.room?.name ?: "",
day = TimeUtils.abbreviatedDayForAr(zonedTime),
time = TimeUtils.abbreviatedTimeForAr(zonedTime),
timestamp = session.startTime.toEpochMilli(),
description = session.description
)
}
val jsonResult = gson.toJson(PinnedSessionsSchedule(useCaseResult))
Result.Success(jsonResult)
}
is Result.Error -> Result.Error(observableResult.exception)
is Result.Loading -> observableResult
}
}
}
}
| shared/src/main/java/com/google/samples/apps/iosched/shared/domain/sessions/LoadPinnedSessionsJsonUseCase.kt | 128509737 |
package com.baculsoft.kotlin.android.internal.injectors.module
import com.baculsoft.kotlin.android.utils.Commons
import com.baculsoft.kotlin.android.utils.Dates
import com.baculsoft.kotlin.android.utils.Keyboards
import com.baculsoft.kotlin.android.utils.Navigators
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
/**
* @author Budi Oktaviyan Suryanto ([email protected])
*/
@Module
class UtilityModule {
@Provides
@Singleton
internal fun provideCommonUtils(): Commons = Commons()
@Provides
@Singleton
internal fun provideDates(): Dates = Dates()
@Provides
@Singleton
internal fun provideKeyboards(): Keyboards = Keyboards()
@Provides
@Singleton
internal fun provideNavigators(): Navigators = Navigators()
} | app/src/main/kotlin/com/baculsoft/kotlin/android/internal/injectors/module/UtilityModule.kt | 266420660 |
package skedgo.datetimerangepicker
import android.app.Activity
import android.app.TimePickerDialog
import android.content.Context
import android.content.Intent
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.format.DateFormat
import com.squareup.timessquare.CalendarPickerView
import org.joda.time.DateTime
import skedgo.datetimerangepicker.databinding.DateTimeRangePickerBinding
import java.util.*
class DateTimeRangePickerActivity : AppCompatActivity() {
companion object {
fun newIntent(
context: Context?,
timeZone: TimeZone?,
startTimeInMillis: Long?,
endTimeInMillis: Long?): Intent {
val intent = Intent(context!!, DateTimeRangePickerActivity::class.java)
startTimeInMillis?.let { intent.putExtra(DateTimeRangePickerViewModel.KEY_START_TIME_IN_MILLIS, it) }
endTimeInMillis?.let { intent.putExtra(DateTimeRangePickerViewModel.KEY_END_TIME_IN_MILLIS, it) }
intent.putExtra(DateTimeRangePickerViewModel.KEY_TIME_ZONE, timeZone!!.id)
return intent
}
}
private val viewModel: DateTimeRangePickerViewModel by lazy {
DateTimeRangePickerViewModel(TimeFormatter(applicationContext))
}
private val binding: DateTimeRangePickerBinding by lazy {
DataBindingUtil.setContentView<DateTimeRangePickerBinding>(
this,
R.layout.date_time_range_picker
)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.handleArgs(intent.extras)
binding.setViewModel(viewModel)
val toolbar = binding.toolbar
toolbar.inflateMenu(R.menu.date_time_range_picker)
toolbar.setNavigationOnClickListener { v -> finish() }
toolbar.setOnMenuItemClickListener { item ->
when {
item.itemId == R.id.dateTimeRangePickerDoneItem -> {
setResult(Activity.RESULT_OK, viewModel.createResultIntent())
finish()
}
}
true
}
val calendarPickerView = binding.calendarPickerView
calendarPickerView.init(viewModel.minDate, viewModel.maxDate)
.inMode(CalendarPickerView.SelectionMode.RANGE)
viewModel.startDateTime.value?.let { calendarPickerView.selectDate(it.toDate()) }
viewModel.endDateTime.value?.let { calendarPickerView.selectDate(it.toDate()) }
calendarPickerView.setOnDateSelectedListener(object : CalendarPickerView.OnDateSelectedListener {
override fun onDateSelected(date: Date) {
viewModel.updateSelectedDates(calendarPickerView.selectedDates)
}
override fun onDateUnselected(date: Date) {
viewModel.updateSelectedDates(calendarPickerView.selectedDates)
}
})
binding.pickStartTimeView.setOnClickListener { v ->
showTimePicker(viewModel.startDateTime.value, viewModel.onStartTimeSelected)
}
binding.pickEndTimeView.setOnClickListener { v ->
showTimePicker(viewModel.endDateTime.value, viewModel.onEndTimeSelected)
}
}
private fun showTimePicker(
initialTime: DateTime,
listener: TimePickerDialog.OnTimeSetListener) {
TimePickerDialog(
this,
listener,
initialTime.hourOfDay,
initialTime.minuteOfHour,
DateFormat.is24HourFormat(this)
).show()
}
}
| src/main/java/skedgo/datetimerangepicker/DateTimeRangePickerActivity.kt | 62934462 |
package net.kibotu.base.ui.markdown
import android.os.Bundle
import android.text.TextUtils.isEmpty
import android.view.View
import kotlinx.android.synthetic.main.fragment_markdown.*
import net.kibotu.base.R
import net.kibotu.base.ui.BaseFragment
/**
* Created by [Jan Rabe](https://about.me/janrabe).
*/
class MarkdownFragment : BaseFragment() {
override val layout: Int
get() = R.layout.fragment_markdown
override fun onEnterStatusBarColor(): Int {
return R.color.gray
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val arguments = arguments
if (arguments != null && !isEmpty(arguments.getString(MARKDOWN_FILENAME)))
markdownView.loadMarkdownFromAssets(arguments.getString(MARKDOWN_FILENAME))
else if (arguments != null && !isEmpty(arguments.getString(MARKDOWN_URL)))
markdownView.loadUrl(arguments.getString(MARKDOWN_URL))
}
companion object {
val MARKDOWN_FILENAME = "MARKDOWN_FILENAME"
val MARKDOWN_URL = "MARKDOWN_URL"
}
}
| app/src/main/kotlin/net/kibotu/base/ui/markdown/MarkdownFragment.kt | 1918175360 |
package org.stepik.android.domain.course_list.interactor
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.Single
import ru.nobird.app.core.model.PagedList
import org.stepic.droid.util.then
import org.stepik.android.domain.base.DataSourceType
import org.stepik.android.domain.course.analytic.CourseViewSource
import org.stepik.android.domain.course.model.SourceTypeComposition
import org.stepik.android.domain.course_list.model.CourseListItem
import org.stepik.android.domain.search.repository.SearchRepository
import org.stepik.android.domain.search_result.model.SearchResultQuery
import org.stepik.android.domain.search_result.repository.SearchResultRepository
import org.stepik.android.model.SearchResult
import javax.inject.Inject
class CourseListSearchInteractor
@Inject
constructor(
private val searchResultRepository: SearchResultRepository,
private val courseListInteractor: CourseListInteractor,
private val searchRepository: SearchRepository
) {
fun getCoursesBySearch(searchResultQuery: SearchResultQuery): Observable<Pair<PagedList<CourseListItem.Data>, DataSourceType>> =
addSearchQuery(searchResultQuery) then
searchResultRepository
.getSearchResults(searchResultQuery)
.flatMapObservable { searchResult ->
val ids = searchResult.mapNotNull(SearchResult::course)
Single
.concat(
getCourseListItems(ids, searchResult, searchResultQuery, SourceTypeComposition.CACHE),
getCourseListItems(ids, searchResult, searchResultQuery, SourceTypeComposition.REMOTE)
)
.toObservable()
}
private fun addSearchQuery(searchResultQuery: SearchResultQuery): Completable =
if (searchResultQuery.query.isNullOrEmpty()) {
Completable.complete()
} else {
searchRepository.saveSearchQuery(query = searchResultQuery.query)
}
fun getCourseListItems(
courseId: List<Long>,
courseViewSource: CourseViewSource,
sourceTypeComposition: SourceTypeComposition = SourceTypeComposition.REMOTE
): Single<PagedList<CourseListItem.Data>> =
courseListInteractor.getCourseListItems(courseId, courseViewSource = courseViewSource, sourceTypeComposition = sourceTypeComposition)
private fun getCourseListItems(
courseIds: List<Long>,
searchResult: PagedList<SearchResult>,
searchResultQuery: SearchResultQuery,
sourceTypeComposition: SourceTypeComposition
): Single<Pair<PagedList<CourseListItem.Data>, DataSourceType>> =
courseListInteractor
.getCourseListItems(courseIds, courseViewSource = CourseViewSource.Search(searchResultQuery), sourceTypeComposition = sourceTypeComposition)
.map { courseListItems ->
PagedList(
list = courseListItems,
page = searchResult.page,
hasPrev = searchResult.hasPrev,
hasNext = searchResult.hasNext
) to sourceTypeComposition.generalSourceType
}
} | app/src/main/java/org/stepik/android/domain/course_list/interactor/CourseListSearchInteractor.kt | 1783348225 |
package graphics.scenery.tests.examples.basic
import org.joml.Vector3f
import graphics.scenery.*
import graphics.scenery.backends.Renderer
import graphics.scenery.numerics.Random
import graphics.scenery.Mesh
import graphics.scenery.primitives.TextBoard
import org.joml.Vector4f
import org.scijava.ui.behaviour.ClickBehaviour
import kotlin.concurrent.thread
/**
* Demo loading the Sponza Model, demonstrating multiple moving lights
* and transparent objects.
*
* @author Ulrik Günther <[email protected]>
*/
class SponzaExample : SceneryBase("SponzaExample", windowWidth = 1280, windowHeight = 720) {
private var movingLights = true
override fun init() {
renderer = hub.add(Renderer.createRenderer(hub, applicationName,
scene,
windowWidth,
windowHeight))
val cam: Camera = DetachedHeadCamera()
with(cam) {
spatial {
position = Vector3f(0.0f, 1.0f, 0.0f)
}
perspectiveCamera(50.0f, windowWidth, windowHeight)
scene.addChild(this)
}
val ambient = AmbientLight(0.05f)
scene.addChild(ambient)
val lights = (0 until 128).map {
Box(Vector3f(0.1f, 0.1f, 0.1f))
}.map {
it.spatial {
position = Vector3f(
Random.randomFromRange(-6.0f, 6.0f),
Random.randomFromRange(0.1f, 1.2f),
Random.randomFromRange(-10.0f, 10.0f)
)
}
val light = PointLight(radius = Random.randomFromRange(0.5f, 4.0f))
it.material {
diffuse = Random.random3DVectorFromRange(0.1f, 0.9f)
light.emissionColor = diffuse
}
light.intensity = Random.randomFromRange(0.1f, 0.5f)
it.addChild(light)
scene.addChild(it)
it
}
val mesh = Mesh()
with(mesh) {
readFromOBJ(getDemoFilesPath() + "/sponza.obj", importMaterials = true)
spatial {
rotation.rotateY(Math.PI.toFloat() / 2.0f)
scale = Vector3f(0.01f, 0.01f, 0.01f)
}
name = "Sponza Mesh"
scene.addChild(this)
}
val desc = TextBoard()
desc.text = "sponza"
desc.spatial {
position = Vector3f(-2.0f, -0.1f, -4.0f)
}
desc.fontColor = Vector4f(0.0f, 0.0f, 0.0f, 1.0f)
desc.backgroundColor = Vector4f(0.1f, 0.1f, 0.1f, 1.0f)
desc.transparent = 0
scene.addChild(desc)
thread {
var ticks = 0L
while (true) {
if(movingLights) {
lights.mapIndexed { i, light ->
val phi = (Math.PI * 2.0f * ticks / 1000.0f) % (Math.PI * 2.0f)
light.spatial {
position = Vector3f(
position.x(),
5.0f * Math.cos(phi + (i * 0.5f)).toFloat() + 5.2f,
position.z())
}
light.children.forEach { it.spatialOrNull()?.needsUpdateWorld = true }
}
ticks++
}
Thread.sleep(15)
}
}
}
override fun inputSetup() {
setupCameraModeSwitching(keybinding = "C")
inputHandler?.addBehaviour("toggle_light_movement", ClickBehaviour { _, _ -> movingLights = !movingLights })
inputHandler?.addKeyBinding("toggle_light_movement", "T")
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
SponzaExample().main()
}
}
}
| src/test/kotlin/graphics/scenery/tests/examples/basic/SponzaExample.kt | 894210690 |
// 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 training.dsl
import com.intellij.ide.util.treeView.NodeRenderer
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.wm.impl.IdeFrameImpl
import com.intellij.ui.KeyStrokeAdapter
import com.intellij.ui.MultilineTreeCellRenderer
import com.intellij.ui.SimpleColoredComponent
import org.fest.swing.core.GenericTypeMatcher
import org.fest.swing.core.Robot
import org.fest.swing.driver.BasicJListCellReader
import org.fest.swing.driver.ComponentDriver
import org.fest.swing.exception.ComponentLookupException
import org.fest.swing.exception.WaitTimedOutError
import org.fest.swing.fixture.AbstractComponentFixture
import org.fest.swing.fixture.ContainerFixture
import org.fest.swing.fixture.JButtonFixture
import org.fest.swing.fixture.JListFixture
import org.fest.swing.timing.Condition
import org.fest.swing.timing.Pause
import org.fest.swing.timing.Timeout
import training.ui.LearningUiUtil
import training.ui.LearningUiUtil.findComponentWithTimeout
import training.util.invokeActionForFocusContext
import java.awt.Component
import java.awt.Container
import java.util.*
import java.util.concurrent.TimeUnit
import javax.swing.JButton
import javax.swing.JDialog
import javax.swing.JLabel
import javax.swing.JList
import kotlin.collections.ArrayList
@LearningDsl
class TaskTestContext(rt: TaskRuntimeContext): TaskRuntimeContext(rt) {
private val defaultTimeout = Timeout.timeout(3, TimeUnit.SECONDS)
val robot: Robot get() = LearningUiUtil.robot
data class TestScriptProperties (
val duration: Int = 15, //seconds
val skipTesting: Boolean = false
)
fun type(text: String) {
robot.waitForIdle()
for (element in text) {
robot.type(element)
Pause.pause(10, TimeUnit.MILLISECONDS)
}
Pause.pause(300, TimeUnit.MILLISECONDS)
}
fun actions(vararg actionIds: String) {
for (actionId in actionIds) {
val action = ActionManager.getInstance().getAction(actionId) ?: error("Action $actionId is non found")
invokeActionForFocusContext(action)
}
}
fun ideFrame(action: ContainerFixture<IdeFrameImpl>.() -> Unit) {
with(findIdeFrame(robot, defaultTimeout)) {
action()
}
}
fun <ComponentType : Component> waitComponent(componentClass: Class<ComponentType>, partOfName: String? = null) {
LearningUiUtil.waitUntilFound(robot, null, typeMatcher(componentClass) {
(if (partOfName != null) it.javaClass.name.contains(partOfName)
else true) && it.isShowing
}, defaultTimeout)
}
/**
* Finds a JList component in hierarchy of context component with a containingItem and returns JListFixture.
*
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <C : Container> ContainerFixture<C>.jList(containingItem: String? = null, timeout: Timeout = defaultTimeout): JListFixture {
return generalListFinder(timeout, containingItem) { element, p -> element == p }
}
/**
* Finds a JButton component in hierarchy of context component with a name and returns ExtendedButtonFixture.
*
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <C : Container> ContainerFixture<C>.button(name: String, timeout: Timeout = defaultTimeout): JButtonFixture {
val jButton: JButton = findComponentWithTimeout(timeout) { it.isShowing && it.isVisible && it.text == name }
return JButtonFixture(robot(), jButton)
}
fun <C : Container> ContainerFixture<C>.actionButton(actionName: String, timeout: Timeout = defaultTimeout)
: AbstractComponentFixture<*, ActionButton, ComponentDriver<*>> {
val actionButton: ActionButton = findComponentWithTimeout(timeout) {
it.isShowing && it.isEnabled && actionName == it.action.templatePresentation.text
}
return ActionButtonFixture(robot(), actionButton)
}
// Modified copy-paste
fun <C : Container> ContainerFixture<C>.jListContains(partOfItem: String? = null, timeout: Timeout = defaultTimeout): JListFixture {
return generalListFinder(timeout, partOfItem) { element, p -> element.contains(p) }
}
/**
* Finds JDialog with a specific title (if title is null showing dialog should be only one) and returns created JDialogFixture
*/
fun dialog(title: String? = null,
ignoreCaseTitle: Boolean = false,
predicate: (String, String) -> Boolean = { found: String, wanted: String -> found == wanted },
timeout: Timeout = defaultTimeout,
func: ContainerFixture<JDialog>.() -> Unit = {})
: AbstractComponentFixture<*, JDialog, ComponentDriver<*>> {
val jDialogFixture = if (title == null) {
val jDialog = LearningUiUtil.waitUntilFound(robot, null, typeMatcher(JDialog::class.java) { true }, timeout)
JDialogFixture(robot, jDialog)
}
else {
try {
val dialog = withPauseWhenNull(timeout = timeout) {
val allMatchedDialogs = robot.finder().findAll(typeMatcher(JDialog::class.java) {
it.isFocused &&
if (ignoreCaseTitle) predicate(it.title.toLowerCase(), title.toLowerCase()) else predicate(it.title, title)
}).filter { it.isShowing && it.isEnabled && it.isVisible }
if (allMatchedDialogs.size > 1) throw Exception(
"Found more than one (${allMatchedDialogs.size}) dialogs matched title \"$title\"")
allMatchedDialogs.firstOrNull()
}
JDialogFixture(robot, dialog)
}
catch (timeoutError: WaitTimedOutError) {
throw ComponentLookupException("Timeout error for finding JDialog by title \"$title\" for ${timeout.duration()}")
}
}
func(jDialogFixture)
return jDialogFixture
}
fun ContainerFixture<*>.jComponent(target: Component): AbstractComponentFixture<*, Component, ComponentDriver<*>> {
return SimpleComponentFixture(robot(), target)
}
fun invokeActionViaShortcut(shortcut: String) {
val keyStroke = KeyStrokeAdapter.getKeyStroke(shortcut)
robot.pressAndReleaseKey(keyStroke.keyCode, keyStroke.modifiers)
}
companion object {
@Volatile
var inTestMode: Boolean = false
}
////////////------------------------------
private fun <C : Container> ContainerFixture<C>.generalListFinder(timeout: Timeout,
containingItem: String?,
predicate: (String, String) -> Boolean): JListFixture {
val extCellReader = ExtendedJListCellReader()
val myJList: JList<*> = findComponentWithTimeout(timeout) { jList: JList<*> ->
if (containingItem == null) true //if were searching for any jList()
else {
val elements = (0 until jList.model.size).mapNotNull { extCellReader.valueAt(jList, it) }
elements.any { predicate(it, containingItem) } && jList.isShowing
}
}
val jListFixture = JListFixture(robot(), myJList)
jListFixture.replaceCellReader(extCellReader)
return jListFixture
}
/**
* waits for [timeout] when functionProbeToNull() not return null
*
* @throws WaitTimedOutError with the text: "Timed out waiting for $timeout second(s) until {@code conditionText} will be not null"
*/
private fun <ReturnType> withPauseWhenNull(conditionText: String = "function to probe",
timeout: Timeout = defaultTimeout,
functionProbeToNull: () -> ReturnType?): ReturnType {
var result: ReturnType? = null
waitUntil("$conditionText will be not null", timeout) {
result = functionProbeToNull()
result != null
}
return result!!
}
private fun waitUntil(condition: String, timeout: Timeout = defaultTimeout, conditionalFunction: () -> Boolean) {
Pause.pause(object : Condition("${timeout.duration()} until $condition") {
override fun test() = conditionalFunction()
}, timeout)
}
private class SimpleComponentFixture(robot: Robot, target: Component) :
ComponentFixture<SimpleComponentFixture, Component>(SimpleComponentFixture::class.java, robot, target)
private fun <ComponentType : Component?> typeMatcher(componentTypeClass: Class<ComponentType>,
matcher: (ComponentType) -> Boolean): GenericTypeMatcher<ComponentType> {
return object : GenericTypeMatcher<ComponentType>(componentTypeClass) {
override fun isMatching(component: ComponentType): Boolean = matcher(component)
}
}
}
private fun getValueWithCellRenderer(cellRendererComponent: Component, isExtended: Boolean = true): String? {
val result = when (cellRendererComponent) {
is JLabel -> cellRendererComponent.text
is NodeRenderer -> {
if (isExtended) cellRendererComponent.getFullText()
else cellRendererComponent.getFirstText()
} //should stands before SimpleColoredComponent because it is more specific
is SimpleColoredComponent -> cellRendererComponent.getFullText()
is MultilineTreeCellRenderer -> cellRendererComponent.text
else -> cellRendererComponent.findText()
}
return result?.trimEnd()
}
private class ExtendedJListCellReader : BasicJListCellReader() {
override fun valueAt(list: JList<*>, index: Int): String? {
val element = list.model.getElementAt(index) ?: return null
@Suppress("UNCHECKED_CAST")
val cellRendererComponent = (list as JList<Any>).cellRenderer
.getListCellRendererComponent(list, element, index, true, true)
return getValueWithCellRenderer(cellRendererComponent)
}
}
private fun SimpleColoredComponent.getFullText(): String {
return invokeAndWaitIfNeeded {
this.getCharSequence(false).toString()
}
}
private fun SimpleColoredComponent.getFirstText(): String {
return invokeAndWaitIfNeeded {
this.getCharSequence(true).toString()
}
}
private fun Component.findText(): String? {
try {
assert(this is Container)
val container = this as Container
val resultList = ArrayList<String>()
resultList.addAll(
findAllWithBFS(container, JLabel::class.java)
.asSequence()
.filter { !it.text.isNullOrEmpty() }
.map { it.text }
.toList()
)
resultList.addAll(
findAllWithBFS(container, SimpleColoredComponent::class.java)
.asSequence()
.filter {
it.getFullText().isNotEmpty()
}
.map {
it.getFullText()
}
.toList()
)
return resultList.firstOrNull { it.isNotEmpty() }
}
catch (ignored: ComponentLookupException) {
return null
}
}
private fun <ComponentType : Component> findAllWithBFS(container: Container, clazz: Class<ComponentType>): List<ComponentType> {
val result = LinkedList<ComponentType>()
val queue: Queue<Component> = LinkedList()
@Suppress("UNCHECKED_CAST")
fun check(container: Component) {
if (clazz.isInstance(container)) result.add(container as ComponentType)
}
queue.add(container)
while (queue.isNotEmpty()) {
val polled = queue.poll()
check(polled)
if (polled is Container)
queue.addAll(polled.components)
}
return result
}
private open class ComponentFixture<S, C : Component>(selfType: Class<S>, robot: Robot, target: C)
: AbstractComponentFixture<S, C, ComponentDriver<*>>(selfType, robot, target) {
override fun createDriver(robot: Robot): ComponentDriver<*> {
return ComponentDriver<Component>(robot)
}
}
private class ActionButtonFixture(robot: Robot, target: ActionButton):
ComponentFixture<ActionButtonFixture, ActionButton>(ActionButtonFixture::class.java, robot, target), ContainerFixture<ActionButton>
private class IdeFrameFixture(robot: Robot, target: IdeFrameImpl)
: ComponentFixture<IdeFrameFixture, IdeFrameImpl>(IdeFrameFixture::class.java, robot, target), ContainerFixture<IdeFrameImpl>
private class JDialogFixture(robot: Robot, jDialog: JDialog) :
ComponentFixture<JDialogFixture, JDialog>(JDialogFixture::class.java, robot, jDialog), ContainerFixture<JDialog>
private fun findIdeFrame(robot: Robot, timeout: Timeout): IdeFrameFixture {
val matcher: GenericTypeMatcher<IdeFrameImpl> = object : GenericTypeMatcher<IdeFrameImpl>(
IdeFrameImpl::class.java) {
override fun isMatching(frame: IdeFrameImpl): Boolean {
return true
}
}
return try {
Pause.pause(object : Condition("IdeFrame to show up") {
override fun test(): Boolean {
return !robot.finder().findAll(matcher).isEmpty()
}
}, timeout)
val ideFrame = robot.finder().find(matcher)
IdeFrameFixture(robot, ideFrame)
}
catch (timedOutError: WaitTimedOutError) {
throw ComponentLookupException("Unable to find IdeFrame in " + timeout.duration())
}
}
| plugins/ide-features-trainer/src/training/dsl/TaskTestContext.kt | 4156333868 |
package graphics.scenery.backends
/**
* Exception to throw when a problem occurs during shader introspection.
* @param[message] A message that may specify the problem in more detail.
* @param[vulkanSemantics] Indicates whether Vulkan semantics are used.
* @param[version] The GLSL version used.
*
* @author Ulrik Guenther <[email protected]>
*/
class ShaderIntrospectionException(message: String, vulkanSemantics: Boolean, version: Int) : Exception("Shader introspection exception: $message (GLSL version $version${if(vulkanSemantics) { ", Vulkan semantics" } else {""}})")
| src/main/kotlin/graphics/scenery/backends/ShaderIntrospectionException.kt | 2904130829 |
package com.github.droibit.plugin.truth.postfix.template
import com.github.droibit.plugin.truth.postfix.template.selector.JavaSelectorConditions.IS_SUBJECT_FACTORY
import com.github.droibit.plugin.truth.postfix.utils.TRUTH_CLASS_NAME
import com.github.droibit.plugin.truth.postfix.utils.getTemplateStringIfWithinTestModule
import com.intellij.codeInsight.template.Template
import com.intellij.codeInsight.template.Template.Property.USE_STATIC_IMPORT_IF_POSSIBLE
import com.intellij.codeInsight.template.TemplateManager
import com.intellij.codeInsight.template.impl.MacroCallNode
import com.intellij.codeInsight.template.macro.SuggestVariableNameMacro
import com.intellij.codeInsight.template.postfix.templates.StringBasedPostfixTemplate
import com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils.selectorTopmost
import com.intellij.psi.PsiElement
/**
* @author kumagai
*/
class AssertAboutTemplate : StringBasedPostfixTemplate(
"assertAbout",
"assertAbout(expr).that(target)",
selectorTopmost(IS_SUBJECT_FACTORY)) {
override fun createTemplate(manager: TemplateManager, templateString: String): Template {
return super.createTemplate(manager, templateString).apply {
setValue(USE_STATIC_IMPORT_IF_POSSIBLE, true)
}
}
override fun getTemplateString(psiElement: PsiElement): String? {
return getTemplateStringIfWithinTestModule(element = psiElement,
template = "$TRUTH_CLASS_NAME.assertAbout(\$expr\$).that(\$target\$)\$END\$")
}
override fun setVariables(template: Template, element: PsiElement) {
template.addVariable("target", MacroCallNode(SuggestVariableNameMacro()), false)
}
} | plugin/src/main/kotlin/com/github/droibit/plugin/truth/postfix/template/AssertAboutTemplate.kt | 3252865651 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.builtInWebServer
import com.intellij.openapi.project.Project
import com.intellij.util.PathUtilRt
import io.netty.buffer.ByteBufUtf8Writer
import io.netty.channel.Channel
import io.netty.handler.codec.http.FullHttpRequest
import io.netty.handler.codec.http.HttpHeaders
import io.netty.handler.codec.http.HttpMethod
import io.netty.handler.codec.http.HttpUtil
import io.netty.handler.stream.ChunkedStream
import org.jetbrains.builtInWebServer.liveReload.WebServerPageConnectionService
import org.jetbrains.builtInWebServer.ssi.SsiExternalResolver
import org.jetbrains.builtInWebServer.ssi.SsiProcessor
import org.jetbrains.io.FileResponses
import org.jetbrains.io.addKeepAliveIfNeeded
import org.jetbrains.io.flushChunkedResponse
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
private class StaticFileHandler : WebServerFileHandler() {
@Suppress("HardCodedStringLiteral")
override val pageFileExtensions = arrayOf("html", "htm", "shtml", "stm", "shtm")
private var ssiProcessor: SsiProcessor? = null
override fun process(pathInfo: PathInfo, canonicalPath: CharSequence, project: Project, request: FullHttpRequest, channel: Channel, projectNameIfNotCustomHost: String?, extraHeaders: HttpHeaders): Boolean {
if (pathInfo.ioFile != null || pathInfo.file!!.isInLocalFileSystem) {
val ioFile = pathInfo.ioFile ?: Paths.get(pathInfo.file!!.path)
val nameSequence = ioFile.fileName.toString()
//noinspection SpellCheckingInspection
if (nameSequence.endsWith(".shtml", true) || nameSequence.endsWith(".stm", true) || nameSequence.endsWith(".shtm", true)) {
processSsi(ioFile, PathUtilRt.getParentPath(canonicalPath.toString()), project, request, channel, extraHeaders)
return true
}
val extraSuffix = WebServerPageConnectionService.getInstance().fileRequested(request, pathInfo::getOrResolveVirtualFile)
FileResponses.sendFile(request, channel, ioFile, extraHeaders, extraSuffix)
return true
}
val file = pathInfo.file!!
val response = FileResponses.prepareSend(request, channel, file.timeStamp, file.name, extraHeaders) ?: return true
val isKeepAlive = response.addKeepAliveIfNeeded(request)
if (request.method() != HttpMethod.HEAD) {
HttpUtil.setContentLength(response, file.length)
}
channel.write(response)
if (request.method() != HttpMethod.HEAD) {
channel.write(ChunkedStream(file.inputStream))
}
flushChunkedResponse(channel, isKeepAlive)
return true
}
private fun processSsi(file: Path, path: String, project: Project, request: FullHttpRequest, channel: Channel, extraHeaders: HttpHeaders) {
if (ssiProcessor == null) {
ssiProcessor = SsiProcessor()
}
val buffer = channel.alloc().ioBuffer()
val isKeepAlive: Boolean
var releaseBuffer = true
try {
val lastModified = ssiProcessor!!.process(SsiExternalResolver(project, request, path, file.parent), file, ByteBufUtf8Writer(buffer))
val response = FileResponses.prepareSend(request, channel, lastModified, file.fileName.toString(), extraHeaders) ?: return
isKeepAlive = response.addKeepAliveIfNeeded(request)
if (request.method() != HttpMethod.HEAD) {
HttpUtil.setContentLength(response, buffer.readableBytes().toLong())
}
channel.write(response)
if (request.method() != HttpMethod.HEAD) {
releaseBuffer = false
channel.write(buffer)
}
}
finally {
if (releaseBuffer) {
buffer.release()
}
}
flushChunkedResponse(channel, isKeepAlive)
}
}
internal fun checkAccess(file: Path, root: Path = file.root): Boolean {
var parent = file
do {
if (!hasAccess(parent)) {
return false
}
parent = parent.parent ?: break
}
while (parent != root)
return true
}
// deny access to any dot prefixed file
internal fun hasAccess(result: Path) = Files.isReadable(result) && !(Files.isHidden(result) || result.fileName.toString().startsWith('.')) | platform/built-in-server/src/org/jetbrains/builtInWebServer/StaticFileHandler.kt | 1958120429 |
package com.intellij.buildsystem.model
interface OperationFailureException<T : OperationItem>
class DependencyConflictException(dependency: BuildDependency) : RuntimeException(
"The dependency $dependency or an equivalent one is already declared in the build file"
), OperationFailureException<BuildDependency>
class RepositoryConflictException(repository: BuildDependencyRepository) : RuntimeException(
"The repository $repository or an equivalent one is already declared in the build file"
), OperationFailureException<BuildDependencyRepository>
class DependencyNotFoundException(dependency: BuildDependency) : RuntimeException(
"The dependency $dependency or an equivalent is not declared in the build file"
), OperationFailureException<BuildDependency>
class RepositoryNotFoundException(repository: BuildDependencyRepository) : RuntimeException(
"The repository $repository or an equivalent is not declared in the build file"
), OperationFailureException<BuildDependencyRepository>
| plugins/dependency-updater/src/com/intellij/buildsystem/model/BuildSystemExceptions.kt | 2289597181 |
// 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.jetbrains.python.run
import com.intellij.execution.target.TargetEnvironmentRequest
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Experimental
interface PythonScriptTargetedCommandLineBuilder {
/**
* Takes [pythonScript] and modifies it along with [targetEnvironmentRequest]
* for specific execution strategy (e.g. debugging, profiling, etc).
*/
fun build(targetEnvironmentRequest: TargetEnvironmentRequest, pythonScript: PythonExecution): PythonExecution
} | python/src/com/jetbrains/python/run/PythonScriptTargetedCommandLineBuilder.kt | 2447015971 |
/* Copyright (c) 2020 DeflatedPickle under the MIT license */
package com.deflatedpickle.quiver.frontend.widget
import com.deflatedpickle.undulation.constraints.FillHorizontal
import com.deflatedpickle.undulation.constraints.FinishLine
import java.awt.GridBagLayout
import javax.swing.text.DocumentFilter
import javax.swing.text.PlainDocument
import org.jdesktop.swingx.JXButton
import org.jdesktop.swingx.JXPanel
import org.jdesktop.swingx.JXTextField
class ButtonField(
prompt: String,
tooltip: String,
filter: DocumentFilter,
actionString: String,
action: (ButtonField) -> Unit
) : JXPanel() {
val field = JXTextField(prompt).apply {
toolTipText = tooltip
(document as PlainDocument).documentFilter = filter
}
val button = JXButton(actionString).apply {
addActionListener { action(this@ButtonField) }
}
init {
this.isOpaque = false
this.layout = GridBagLayout()
add(this.field, FillHorizontal)
add(this.button, FinishLine)
}
}
| core/src/main/kotlin/com/deflatedpickle/quiver/frontend/widget/ButtonField.kt | 2986727513 |
package jp.cordea.mackerelclient.repository
import io.reactivex.Single
import jp.cordea.mackerelclient.api.MackerelApiClient
import jp.cordea.mackerelclient.api.response.MetricsResponse
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ServiceMetricsRemoteDataSource @Inject constructor(
private val apiClient: MackerelApiClient
) {
fun getMetrics(
serviceName: String,
name: String,
from: Long,
to: Long
): Single<MetricsResponse> =
apiClient.getServiceMetrics(serviceName, name, from, to)
}
| app/src/main/java/jp/cordea/mackerelclient/repository/ServiceMetricsRemoteDataSource.kt | 2589371699 |
/*
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
// This file was automatically generated from flow.md by Knit tool. Do not edit.
package kotlinx.coroutines.guide.exampleFlow03
import kotlinx.coroutines.*
suspend fun simple(): List<Int> {
delay(1000) // pretend we are doing something asynchronous here
return listOf(1, 2, 3)
}
fun main() = runBlocking<Unit> {
simple().forEach { value -> println(value) }
}
| kotlinx-coroutines-core/jvm/test/guide/example-flow-03.kt | 3987015015 |
package com.rightfromleftsw.weather.data.repository
/**
* Created by clivelee on 9/21/17.
*/
interface IWeatherLocal : IWeatherDataStore | data/src/main/java/com/rightfromleftsw/weather/data/repository/IWeatherLocal.kt | 3895117469 |
package cookbook.test_driven_apps
import com.natpryce.hamkrest.and
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.should.shouldMatch
import org.http4k.client.OkHttp
import org.http4k.core.HttpHandler
import org.http4k.core.Method.GET
import org.http4k.core.Method.POST
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status.Companion.NOT_FOUND
import org.http4k.core.Status.Companion.OK
import org.http4k.core.Uri
import org.http4k.core.then
import org.http4k.filter.ClientFilters.SetHostFrom
import org.http4k.filter.ServerFilters
import org.http4k.hamkrest.hasBody
import org.http4k.hamkrest.hasStatus
import org.http4k.routing.bind
import org.http4k.routing.path
import org.http4k.routing.routes
import org.http4k.server.Http4kServer
import org.http4k.server.Jetty
import org.http4k.server.asServer
import org.junit.After
import org.junit.Before
import org.junit.Test
class AnswerRecorder(private val httpClient: HttpHandler) : (Int) -> Unit {
override fun invoke(answer: Int): Unit {
httpClient(Request(POST, "/" + answer.toString()))
}
}
fun myMathsEndpoint(fn: (Int, Int) -> Int, recorder: (Int) -> Unit): HttpHandler = {
req ->
val answer = fn(req.query("first")!!.toInt(), req.query("second")!!.toInt())
recorder(answer)
Response(OK).body("the answer is $answer")
}
class EndpointUnitTest {
@Test
fun `adds numbers and records answer`() {
var answer: Int? = null
val unit = myMathsEndpoint({ first, second -> first + second }, { answer = it })
val response = unit(Request(GET, "/").query("first", "123").query("second", "456"))
answer shouldMatch equalTo(579)
response shouldMatch hasStatus(OK).and(hasBody("the answer is 579"))
}
}
fun MyMathsApp(recorderHttp: HttpHandler) =
ServerFilters.CatchAll().then(routes(
"/add" bind GET to myMathsEndpoint({ first, second -> first + second }, AnswerRecorder(recorderHttp))
))
class FakeRecorderHttp : HttpHandler {
val calls = mutableListOf<Int>()
private val app = routes(
"/{answer}" bind POST to { request -> calls.add(request.path("answer")!!.toInt()); Response(OK) }
)
override fun invoke(request: Request): Response = app(request)
}
class FunctionalTest {
private val recorderHttp = FakeRecorderHttp()
private val app = MyMathsApp(recorderHttp)
@Test
fun `adds numbers`() {
val response = app(Request(GET, "/add").query("first", "123").query("second", "456"))
response shouldMatch hasStatus(OK).and(hasBody("the answer is 579"))
recorderHttp.calls shouldMatch equalTo(listOf(579))
}
@Test
fun `not found`() {
val response = app(Request(GET, "/nothing").query("first", "123").query("second", "456"))
response shouldMatch hasStatus(NOT_FOUND)
}
}
fun MyMathServer(port: Int, recorderUri: Uri): Http4kServer {
val recorderHttp = SetHostFrom(recorderUri).then(OkHttp())
return MyMathsApp(recorderHttp).asServer(Jetty(port))
}
class EndToEndTest {
private val client = OkHttp()
private val recorderHttp = FakeRecorderHttp()
private val recorder = recorderHttp.asServer(Jetty(8001))
private val server = MyMathServer(8000, Uri.of("http://localhost:8001"))
@Before
fun setup(): Unit {
recorder.start()
server.start()
}
@After
fun teardown(): Unit {
server.stop()
recorder.stop()
}
@Test
fun `adds numbers`() {
val response = client(Request(GET, "http://localhost:8000/add").query("first", "123").query("second", "456"))
response shouldMatch hasStatus(OK).and(hasBody("the answer is 579"))
recorderHttp.calls shouldMatch equalTo(listOf(579))
}
}
| src/docs/cookbook/test_driven_apps/example.kt | 2580194301 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.impl.statistics
import com.intellij.execution.impl.statistics.RunConfigurationTypeUsagesCollector.ID_FIELD
import com.intellij.execution.ui.FragmentStatisticsService
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.FusInputEvent
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
class RunConfigurationOptionUsagesCollector: CounterUsagesCollector() {
override fun getGroup() = GROUP
companion object {
val GROUP = EventLogGroup("run.configuration.ui.interactions", 6)
val optionId = EventFields.String("option_id", listOf("before.launch.editSettings", "before.launch.openToolWindow", "beforeRunTasks", "commandLineParameters", "coverage", "doNotBuildBeforeRun", "environmentVariables", "jrePath", "log.monitor", "mainClass", "module.classpath", "redirectInput", "runParallel", "shorten.command.line", "target.project.path", "vmParameters", "workingDirectory",
"count", "junit.test.kind", "repeat", "testScope", // junit
"maven.params.workingDir", "maven.params.goals", "maven.params.profiles", "maven.params.resolveToWorkspace",
"maven.general.useProjectSettings", "maven.general.workOffline", "maven.general.produceExceptionErrorMessages", "maven.general.usePluginRegistry", "maven.general.recursive", "maven.general.alwaysUpdateSnapshots", "maven.general.threadsEditor", "maven.general.outputLevel", "maven.general.checksumPolicy", "maven.general.failPolicy", "maven.general.showDialogWithAdvancedSettings",
"maven.general.mavenHome", "maven.general.settingsFileOverride.checkbox", "maven.general.settingsFileOverride.text", "maven.general.localRepoOverride.checkbox", "maven.general.localRepoOverride.text",
"maven.runner.useProjectSettings", "maven.runner.delegateToMaven", "maven.runner.runInBackground", "maven.runner.vmParameters", "maven.runner.envVariables", "maven.runner.jdk", "maven.runner.targetJdk", "maven.runner.skipTests", "maven.runner.properties",
"Dump_file_path", "Exe_path", "Program_arguments", "Working_directory", "Environment_variables", "Runtime_arguments", "Use_Mono_runtime", "Use_external_console", "Project", "Target_framework", "Launch_profile", "Open_browser", "Application_URL", "Launch_URL", "IIS_Express_Certificate", "Hosting_model", "Generate_applicationhost.config", "Show_IIS_Express_output", "Send_debug_request", "Additional_IIS_Express_arguments", "Static_method", "URL", "Session_name", "Arguments", "Solution_Configuration", "Executable_file", "Default_arguments", "Optional_arguments" // Rider
)) // maven
val projectSettingsAvailableField = EventFields.Boolean("projectSettingsAvailable")
val useProjectSettingsField = EventFields.Boolean("useProjectSettings")
val modifyOption = GROUP.registerVarargEvent("modify.run.option", optionId, projectSettingsAvailableField, useProjectSettingsField, ID_FIELD, EventFields.InputEvent)
val navigateOption = GROUP.registerVarargEvent("option.navigate", optionId, ID_FIELD, EventFields.InputEvent)
val removeOption = GROUP.registerEvent("remove.run.option", optionId, ID_FIELD, EventFields.InputEvent)
val addNew = GROUP.registerEvent("add", ID_FIELD)
val remove = GROUP.registerEvent("remove", ID_FIELD)
val hintsShown = GROUP.registerEvent("hints.shown", ID_FIELD, EventFields.Int("hint_number"), EventFields.DurationMs)
@JvmStatic
fun logAddNew(project: Project?, config: String?) {
addNew.log(project, config)
}
@JvmStatic
fun logRemove(project: Project?, config: String?) {
remove.log(project, config)
}
@JvmStatic
fun logModifyOption(project: Project?, option: String?, config: String?, inputEvent: FusInputEvent?) {
modifyOption.log(project, optionId.with(option),
ID_FIELD.with(config),
EventFields.InputEvent.with(inputEvent))
}
@JvmStatic
fun logNavigateOption(project: Project?, option: String?, config: String?, inputEvent: FusInputEvent?) {
navigateOption.log(project, optionId.with(option),
ID_FIELD.with(config),
EventFields.InputEvent.with(inputEvent))
}
@JvmStatic
fun logModifyOption(project: Project?, option: String?, config: String?, projectSettingsAvailable: Boolean, useProjectSettings: Boolean, inputEvent: FusInputEvent?) {
modifyOption.log(project, optionId.with(option),
ID_FIELD.with(config),
projectSettingsAvailableField.with(projectSettingsAvailable),
useProjectSettingsField.with(useProjectSettings),
EventFields.InputEvent.with(inputEvent))
}
@JvmStatic
fun logRemoveOption(project: Project?, option: String?, config: String?, inputEvent: FusInputEvent?) {
removeOption.log(project, option, config, inputEvent)
}
@JvmStatic
fun logShowHints(project: Project?, config: String?, hintsCount: Int, duration: Long) {
hintsShown.log(project, config, hintsCount, duration)
}
}
}
class FragmentedStatisticsServiceImpl: FragmentStatisticsService() {
override fun logOptionModified(project: Project?, optionId: String?, runConfigId: String?, inputEvent: AnActionEvent?) {
RunConfigurationOptionUsagesCollector.
logModifyOption(project, optionId, runConfigId, FusInputEvent.from(inputEvent))
}
override fun logOptionRemoved(project: Project?, optionId: String?, runConfigId: String?, inputEvent: AnActionEvent?) {
RunConfigurationOptionUsagesCollector.logRemoveOption(project, optionId, runConfigId, FusInputEvent.from(inputEvent))
}
override fun logNavigateOption(project: Project?, optionId: String?, runConfigId: String?, inputEvent: AnActionEvent?) {
RunConfigurationOptionUsagesCollector.logNavigateOption(project, optionId, runConfigId, FusInputEvent.from(inputEvent))
}
override fun logHintsShown(project: Project?, runConfigId: String?, hintNumber: Int, duration: Long) {
RunConfigurationOptionUsagesCollector.logShowHints(project, runConfigId, hintNumber, duration)
}
}
| platform/execution-impl/src/com/intellij/execution/impl/statistics/RunConfigurationOptionUsagesCollector.kt | 385282122 |
package slatekit.apis.routes
open class Lookup<T>(
val items: List<T>,
val nameFetcher: (T) -> String
) {
val size = items.size
val keys = items.map(this.nameFetcher)
val map = items.map { it -> Pair(this.nameFetcher(it), it) }.toMap()
fun contains(name: String): Boolean = map.contains(name)
operator fun get(name: String): T? = if (contains(name)) map[name] else null
}
| src/lib/kotlin/slatekit-apis/src/main/kotlin/slatekit/apis/routes/Lookup.kt | 3522495892 |
package com.antyzero.smoksmog.job
import android.content.Context
import com.firebase.jobdispatcher.FirebaseJobDispatcher
import com.firebase.jobdispatcher.GooglePlayDriver
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
@Singleton
class JobModule {
@Provides
@Singleton
internal fun provideFirebaseJobDispatcher(context: Context): FirebaseJobDispatcher {
return FirebaseJobDispatcher(GooglePlayDriver(context))
}
}
| app/src/main/kotlin/com/antyzero/smoksmog/job/JobModule.kt | 951945965 |
package org.purescript.parser
class ForeignParserTest: PSLanguageParserTestBase("foreign") {
fun testImportData() = doTest(true, true)
} | src/test/kotlin/org/purescript/parser/ForeignParserTest.kt | 634891285 |
/*
* Copyright 2017 Xuqiang ZHENG
*
* 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 `in`.nerd_is.android_showcase.dribbble
import `in`.nerd_is.android_showcase.dribbble.model.repository.DribbbleDataSource
import `in`.nerd_is.android_showcase.dribbble.model.repository.remote.FakeDribbbleRemoteRepository
import dagger.Binds
import dagger.Module
/**
* @author Xuqiang ZHENG on 2017/6/30.
*/
@Module
abstract class DribbbleModule {
@Binds
abstract fun provideDribbbleDataSource(
dataSource: FakeDribbbleRemoteRepository): DribbbleDataSource
} | app/src/mock/kotlin/in/nerd_is/android_showcase/dribbble/DribbbleModule.kt | 2478285458 |
package acr.browser.lightning.browser.tab
import acr.browser.lightning.R
import acr.browser.lightning.adblock.AdBlocker
import acr.browser.lightning.adblock.allowlist.AllowListModel
import acr.browser.lightning.browser.proxy.Proxy
import acr.browser.lightning.databinding.DialogAuthRequestBinding
import acr.browser.lightning.databinding.DialogSslWarningBinding
import acr.browser.lightning.extensions.resizeAndShow
import acr.browser.lightning.js.TextReflow
import acr.browser.lightning.log.Logger
import acr.browser.lightning.preference.UserPreferences
import acr.browser.lightning.ssl.SslState
import acr.browser.lightning.ssl.SslWarningPreferences
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.net.http.SslError
import android.os.Build
import android.os.Message
import android.view.LayoutInflater
import android.webkit.HttpAuthHandler
import android.webkit.SslErrorHandler
import android.webkit.URLUtil
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import io.reactivex.subjects.PublishSubject
import java.io.ByteArrayInputStream
import kotlin.math.abs
/**
* A [WebViewClient] that supports the tab adaptation.
*/
class TabWebViewClient @AssistedInject constructor(
private val adBlocker: AdBlocker,
private val allowListModel: AllowListModel,
private val urlHandler: UrlHandler,
@Assisted private val headers: Map<String, String>,
private val proxy: Proxy,
private val userPreferences: UserPreferences,
private val sslWarningPreferences: SslWarningPreferences,
private val textReflow: TextReflow,
private val logger: Logger
) : WebViewClient() {
/**
* Emits changes to the current URL.
*/
val urlObservable: PublishSubject<String> = PublishSubject.create()
/**
* Emits changes to the current SSL state.
*/
val sslStateObservable: PublishSubject<SslState> = PublishSubject.create()
/**
* Emits changes to the can go back state of the browser.
*/
val goBackObservable: PublishSubject<Boolean> = PublishSubject.create()
/**
* Emits changes to the can go forward state of the browser.
*/
val goForwardObservable: PublishSubject<Boolean> = PublishSubject.create()
/**
* The current SSL state of the page.
*/
var sslState: SslState = SslState.None
private set
private var currentUrl: String = ""
private var isReflowRunning: Boolean = false
private var zoomScale: Float = 0.0F
private var urlWithSslError: String? = null
private fun shouldBlockRequest(pageUrl: String, requestUrl: String) =
!allowListModel.isUrlAllowedAds(pageUrl) &&
adBlocker.isAd(requestUrl)
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
currentUrl = url
urlObservable.onNext(url)
if (urlWithSslError != url) {
urlWithSslError = null
sslState = if (URLUtil.isHttpsUrl(url)) {
SslState.Valid
} else {
SslState.None
}
}
sslStateObservable.onNext(sslState)
}
override fun onPageFinished(view: WebView, url: String) {
super.onPageFinished(view, url)
urlObservable.onNext(url)
goBackObservable.onNext(view.canGoBack())
goForwardObservable.onNext(view.canGoForward())
}
override fun onScaleChanged(view: WebView, oldScale: Float, newScale: Float) {
if (view.isShown && userPreferences.textReflowEnabled) {
if (isReflowRunning)
return
val changeInPercent = abs(100 - 100 / zoomScale * newScale)
if (changeInPercent > 2.5f && !isReflowRunning) {
isReflowRunning = view.postDelayed({
zoomScale = newScale
view.evaluateJavascript(textReflow.provideJs()) { isReflowRunning = false }
}, 100)
}
}
}
override fun onReceivedHttpAuthRequest(
view: WebView,
handler: HttpAuthHandler,
host: String,
realm: String
) {
val context = view.context
AlertDialog.Builder(context).apply {
val dialogView = DialogAuthRequestBinding.inflate(LayoutInflater.from(context))
val realmLabel = dialogView.authRequestRealmTextview
val name = dialogView.authRequestUsernameEdittext
val password = dialogView.authRequestPasswordEdittext
realmLabel.text = context.getString(R.string.label_realm, realm)
setView(dialogView.root)
setTitle(R.string.title_sign_in)
setCancelable(true)
setPositiveButton(R.string.title_sign_in) { _, _ ->
val user = name.text.toString()
val pass = password.text.toString()
handler.proceed(user.trim(), pass.trim())
logger.log(TAG, "Attempting HTTP Authentication")
}
setNegativeButton(R.string.action_cancel) { _, _ ->
handler.cancel()
}
}.resizeAndShow()
}
override fun onFormResubmission(view: WebView, dontResend: Message, resend: Message) {
val context = view.context
AlertDialog.Builder(context).apply {
setTitle(context.getString(R.string.title_form_resubmission))
setMessage(context.getString(R.string.message_form_resubmission))
setCancelable(true)
setPositiveButton(context.getString(R.string.action_yes)) { _, _ ->
resend.sendToTarget()
}
setNegativeButton(context.getString(R.string.action_no)) { _, _ ->
dontResend.sendToTarget()
}
}.resizeAndShow()
}
@SuppressLint("WebViewClientOnReceivedSslError")
override fun onReceivedSslError(webView: WebView, handler: SslErrorHandler, error: SslError) {
val context = webView.context
urlWithSslError = webView.url
sslState = SslState.Invalid(error)
sslStateObservable.onNext(sslState)
sslState = SslState.Invalid(error)
when (sslWarningPreferences.recallBehaviorForDomain(webView.url)) {
SslWarningPreferences.Behavior.PROCEED -> return handler.proceed()
SslWarningPreferences.Behavior.CANCEL -> return handler.cancel()
null -> Unit
}
val errorCodeMessageCodes = error.getAllSslErrorMessageCodes()
val stringBuilder = StringBuilder()
for (messageCode in errorCodeMessageCodes) {
stringBuilder.append(" - ").append(context.getString(messageCode)).append('\n')
}
val alertMessage =
context.getString(R.string.message_insecure_connection, stringBuilder.toString())
AlertDialog.Builder(context).apply {
val view = DialogSslWarningBinding.inflate(LayoutInflater.from(context))
val dontAskAgain = view.checkBoxDontAskAgain
setTitle(context.getString(R.string.title_warning))
setMessage(alertMessage)
setCancelable(true)
setView(view.root)
setOnCancelListener { handler.cancel() }
setPositiveButton(context.getString(R.string.action_yes)) { _, _ ->
if (dontAskAgain.isChecked) {
sslWarningPreferences.rememberBehaviorForDomain(
webView.url.orEmpty(),
SslWarningPreferences.Behavior.PROCEED
)
}
handler.proceed()
}
setNegativeButton(context.getString(R.string.action_no)) { _, _ ->
if (dontAskAgain.isChecked) {
sslWarningPreferences.rememberBehaviorForDomain(
webView.url.orEmpty(),
SslWarningPreferences.Behavior.CANCEL
)
}
handler.cancel()
}
}.resizeAndShow()
}
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
if (!proxy.isProxyReady()) return true
return urlHandler.shouldOverrideLoading(view, url, headers) ||
super.shouldOverrideUrlLoading(view, url)
}
@RequiresApi(Build.VERSION_CODES.N)
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
if (!proxy.isProxyReady()) return true
return urlHandler.shouldOverrideLoading(view, request.url.toString(), headers) ||
super.shouldOverrideUrlLoading(view, request)
}
override fun shouldInterceptRequest(
view: WebView,
request: WebResourceRequest
): WebResourceResponse? {
if (shouldBlockRequest(currentUrl, request.url.toString()) || !proxy.isProxyReady()) {
val empty = ByteArrayInputStream(emptyResponseByteArray)
return WebResourceResponse(BLOCKED_RESPONSE_MIME_TYPE, BLOCKED_RESPONSE_ENCODING, empty)
}
return null
}
private fun SslError.getAllSslErrorMessageCodes(): List<Int> {
val errorCodeMessageCodes = ArrayList<Int>(1)
if (hasError(SslError.SSL_DATE_INVALID)) {
errorCodeMessageCodes.add(R.string.message_certificate_date_invalid)
}
if (hasError(SslError.SSL_EXPIRED)) {
errorCodeMessageCodes.add(R.string.message_certificate_expired)
}
if (hasError(SslError.SSL_IDMISMATCH)) {
errorCodeMessageCodes.add(R.string.message_certificate_domain_mismatch)
}
if (hasError(SslError.SSL_NOTYETVALID)) {
errorCodeMessageCodes.add(R.string.message_certificate_not_yet_valid)
}
if (hasError(SslError.SSL_UNTRUSTED)) {
errorCodeMessageCodes.add(R.string.message_certificate_untrusted)
}
if (hasError(SslError.SSL_INVALID)) {
errorCodeMessageCodes.add(R.string.message_certificate_invalid)
}
return errorCodeMessageCodes
}
/**
* The factory for constructing the client.
*/
@AssistedFactory
interface Factory {
/**
* Create the client.
*/
fun create(headers: Map<String, String>): TabWebViewClient
}
companion object {
private const val TAG = "TabWebViewClient"
private val emptyResponseByteArray: ByteArray = byteArrayOf()
private const val BLOCKED_RESPONSE_MIME_TYPE = "text/plain"
private const val BLOCKED_RESPONSE_ENCODING = "utf-8"
}
}
| app/src/main/java/acr/browser/lightning/browser/tab/TabWebViewClient.kt | 3686132346 |
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
// FILE: J.java
public class J {
private final String result;
private J(String result) {
this.result = result;
}
private String getResult() {
return result;
}
}
// FILE: K.kt
import kotlin.reflect.full.*
import kotlin.reflect.jvm.*
import kotlin.test.*
fun box(): String {
val c = J::class.constructors.single()
assertFalse(c.isAccessible)
assertFailsWith(IllegalCallableAccessException::class) { c.call("") }
c.isAccessible = true
assertTrue(c.isAccessible)
val j = c.call("OK")
val m = J::class.members.single { it.name == "getResult" }
assertFalse(m.isAccessible)
assertFailsWith(IllegalCallableAccessException::class) { m.call(j)!! }
m.isAccessible = true
return m.call(j) as String
}
| backend.native/tests/external/codegen/box/reflection/call/callPrivateJavaMethod.kt | 3833555973 |
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.test
/**
* Default [Asserter] implementation for Kotlin/Native.
*/
object DefaultAsserter : Asserter {
override fun fail(message: String?): Nothing {
if (message == null)
throw AssertionError()
else
throw AssertionError(message)
}
} | runtime/src/main/kotlin/kotlin/test/DefaultAsserter.kt | 3280085631 |
class Foo {
fun bar(): String {
fun <T> foo(t:() -> T) : T = t()
foo { }
return "OK"
}
}
fun box(): String {
return Foo().bar()
}
| backend.native/tests/external/codegen/box/regressions/kt3903.kt | 3550072578 |
@file:JsQualifier("THREE")
package three.lights
import three.core.Object3D
import three.math.Color
@JsName("Light")
open external class Light(color: Int, intensity: Float) : Object3D {
var color: Color
var intensity : Float
}
| threejs/src/main/kotlin/three/lights/Light.kt | 3400590221 |
package com.github.triplet.gradle.androidpublisher.internal
import com.github.triplet.gradle.androidpublisher.CommitResponse
import com.github.triplet.gradle.androidpublisher.EditResponse
import com.github.triplet.gradle.androidpublisher.GppProduct
import com.github.triplet.gradle.androidpublisher.PlayPublisher
import com.github.triplet.gradle.androidpublisher.UpdateProductResponse
import com.github.triplet.gradle.androidpublisher.UploadInternalSharingArtifactResponse
import com.google.api.client.googleapis.json.GoogleJsonResponseException
import com.google.api.client.googleapis.media.MediaHttpUploader
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest
import com.google.api.client.http.FileContent
import com.google.api.client.json.gson.GsonFactory
import com.google.api.services.androidpublisher.AndroidPublisher
import com.google.api.services.androidpublisher.model.Apk
import com.google.api.services.androidpublisher.model.AppDetails
import com.google.api.services.androidpublisher.model.Bundle
import com.google.api.services.androidpublisher.model.DeobfuscationFilesUploadResponse
import com.google.api.services.androidpublisher.model.ExpansionFile
import com.google.api.services.androidpublisher.model.Image
import com.google.api.services.androidpublisher.model.InAppProduct
import com.google.api.services.androidpublisher.model.Listing
import com.google.api.services.androidpublisher.model.Track
import java.io.File
import java.io.InputStream
import kotlin.math.roundToInt
internal class DefaultPlayPublisher(
private val publisher: AndroidPublisher,
override val appId: String,
) : InternalPlayPublisher {
override fun insertEdit(): EditResponse {
return try {
EditResponse.Success(publisher.edits().insert(appId, null).execute().id)
} catch (e: GoogleJsonResponseException) {
EditResponse.Failure(e)
}
}
override fun getEdit(id: String): EditResponse {
return try {
EditResponse.Success(publisher.edits().get(appId, id).execute().id)
} catch (e: GoogleJsonResponseException) {
EditResponse.Failure(e)
}
}
override fun commitEdit(id: String, sendChangesForReview: Boolean): CommitResponse {
return try {
publisher.edits().commit(appId, id)
.setChangesNotSentForReview(!sendChangesForReview)
.execute()
CommitResponse.Success
} catch (e: GoogleJsonResponseException) {
CommitResponse.Failure(e)
}
}
override fun validateEdit(id: String) {
publisher.edits().validate(appId, id).execute()
}
override fun getAppDetails(editId: String): AppDetails {
return publisher.edits().details().get(appId, editId).execute()
}
override fun getListings(editId: String): List<Listing> {
return publisher.edits().listings().list(appId, editId).execute()?.listings.orEmpty()
}
override fun getImages(editId: String, locale: String, type: String): List<Image> {
val response = publisher.edits().images().list(appId, editId, locale, type).execute()
return response?.images.orEmpty()
}
override fun updateDetails(editId: String, details: AppDetails) {
publisher.edits().details().update(appId, editId, details).execute()
}
override fun updateListing(editId: String, locale: String, listing: Listing) {
publisher.edits().listings().update(appId, editId, locale, listing).execute()
}
override fun deleteImages(editId: String, locale: String, type: String) {
publisher.edits().images().deleteall(appId, editId, locale, type).execute()
}
override fun uploadImage(editId: String, locale: String, type: String, image: File) {
val content = FileContent(MIME_TYPE_IMAGE, image)
publisher.edits().images().upload(appId, editId, locale, type, content).execute()
}
override fun getTrack(editId: String, track: String): Track {
return try {
publisher.edits().tracks().get(appId, editId, track).execute()
} catch (e: GoogleJsonResponseException) {
if (e has "notFound") {
Track().setTrack(track)
} else {
throw e
}
}
}
override fun listTracks(editId: String): List<Track> {
return publisher.edits().tracks().list(appId, editId).execute()?.tracks.orEmpty()
}
override fun updateTrack(editId: String, track: Track) {
println("Updating ${track.releases.map { it.status }.distinct()} release " +
"($appId:${track.releases.flatMap { it.versionCodes.orEmpty() }}) " +
"in track '${track.track}'")
publisher.edits().tracks().update(appId, editId, track.track, track).execute()
}
override fun uploadBundle(editId: String, bundleFile: File): Bundle {
val content = FileContent(MIME_TYPE_STREAM, bundleFile)
return publisher.edits().bundles().upload(appId, editId, content)
.trackUploadProgress("App Bundle", bundleFile)
.execute()
}
override fun uploadApk(editId: String, apkFile: File): Apk {
val content = FileContent(MIME_TYPE_APK, apkFile)
return publisher.edits().apks().upload(appId, editId, content)
.trackUploadProgress("APK", apkFile)
.execute()
}
override fun attachObb(editId: String, type: String, appVersion: Int, obbVersion: Int) {
val obb = ExpansionFile().also { it.referencesVersion = obbVersion }
publisher.edits().expansionfiles()
.update(appId, editId, appVersion, type, obb)
.execute()
}
override fun uploadDeobfuscationFile(
editId: String,
file: File,
versionCode: Int,
type: String,
): DeobfuscationFilesUploadResponse {
val mapping = FileContent(MIME_TYPE_STREAM, file)
val humanFileName = when (type) {
"proguard" -> "mapping"
"nativeCode" -> "native debug symbols"
else -> type
}
return publisher.edits().deobfuscationfiles()
.upload(appId, editId, versionCode, type, mapping)
.trackUploadProgress("$humanFileName file", file)
.execute()
}
override fun uploadInternalSharingBundle(bundleFile: File): UploadInternalSharingArtifactResponse {
val bundle = publisher.internalappsharingartifacts()
.uploadbundle(appId, FileContent(MIME_TYPE_STREAM, bundleFile))
.trackUploadProgress("App Bundle", bundleFile)
.execute()
return UploadInternalSharingArtifactResponse(bundle.toPrettyString(), bundle.downloadUrl)
}
override fun uploadInternalSharingApk(apkFile: File): UploadInternalSharingArtifactResponse {
val apk = publisher.internalappsharingartifacts()
.uploadapk(appId, FileContent(MIME_TYPE_APK, apkFile))
.trackUploadProgress("APK", apkFile)
.execute()
return UploadInternalSharingArtifactResponse(apk.toPrettyString(), apk.downloadUrl)
}
override fun getInAppProducts(): List<GppProduct> {
fun AndroidPublisher.Inappproducts.List.withToken(token: String?) = apply {
this.token = token
}
val products = mutableListOf<InAppProduct>()
var token: String? = null
do {
val response = publisher.inappproducts().list(appId).withToken(token).execute()
products += response.inappproduct.orEmpty()
token = response.tokenPagination?.nextPageToken
} while (token != null)
return products.map {
GppProduct(it.sku, it.toPrettyString())
}
}
override fun insertInAppProduct(productFile: File) {
publisher.inappproducts().insert(appId, readProductFile(productFile))
.apply { autoConvertMissingPrices = true }
.execute()
}
override fun updateInAppProduct(productFile: File): UpdateProductResponse {
val product = readProductFile(productFile)
try {
publisher.inappproducts().update(appId, product.sku, product)
.apply { autoConvertMissingPrices = true }
.execute()
} catch (e: GoogleJsonResponseException) {
if (e.statusCode == 404) {
return UpdateProductResponse(true)
} else {
throw e
}
}
return UpdateProductResponse(false)
}
private fun readProductFile(product: File) = product.inputStream().use {
GsonFactory.getDefaultInstance()
.createJsonParser(it)
.parse(InAppProduct::class.java)
}
private fun <T, R : AbstractGoogleClientRequest<T>> R.trackUploadProgress(
thing: String,
file: File,
): R {
mediaHttpUploader?.setProgressListener {
@Suppress("NON_EXHAUSTIVE_WHEN")
when (it.uploadState) {
MediaHttpUploader.UploadState.INITIATION_STARTED ->
println("Starting $thing upload: $file")
MediaHttpUploader.UploadState.MEDIA_IN_PROGRESS ->
println("Uploading $thing: ${(it.progress * 100).roundToInt()}% complete")
MediaHttpUploader.UploadState.MEDIA_COMPLETE ->
println("${thing.capitalize()} upload complete")
}
}
return this
}
class Factory : PlayPublisher.Factory {
override fun create(
credentials: InputStream,
appId: String,
): PlayPublisher {
val publisher = createPublisher(credentials)
return DefaultPlayPublisher(publisher, appId)
}
}
private companion object {
const val MIME_TYPE_STREAM = "application/octet-stream"
const val MIME_TYPE_APK = "application/vnd.android.package-archive"
const val MIME_TYPE_IMAGE = "image/*"
}
}
| play/android-publisher/src/main/kotlin/com/github/triplet/gradle/androidpublisher/internal/DefaultPlayPublisher.kt | 1286317735 |
// WITH_RUNTIME
fun box(): String {
val a = Array<Int>(5, {it})
val x = a.indices.iterator()
while (x.hasNext()) {
val i = x.next()
if (a[i] != i) return "Fail $i ${a[i]}"
}
return "OK"
}
| backend.native/tests/external/codegen/box/arrays/indices.kt | 1385861945 |
import kotlin.test.*
fun box() {
fun <T, K> verifyGrouping(grouping: Grouping<T, K>, expectedElements: List<T>, expectedKeys: List<K>) {
val elements = grouping.sourceIterator().asSequence().toList()
val keys = elements.map { grouping.keyOf(it) } // TODO: replace with grouping::keyOf when supported in JS
assertEquals(expectedElements, elements)
assertEquals(expectedKeys, keys)
}
val elements = listOf("foo", "bar", "value", "x")
val keySelector: (String) -> Int = { it.length }
val keys = elements.map(keySelector)
fun verifyGrouping(grouping: Grouping<String, Int>) = verifyGrouping(grouping, elements, keys)
verifyGrouping(elements.groupingBy { it.length })
verifyGrouping(elements.toTypedArray().groupingBy(keySelector))
verifyGrouping(elements.asSequence().groupingBy(keySelector))
val charSeq = "some sequence of chars"
verifyGrouping(charSeq.groupingBy { it.toInt() }, charSeq.toList(), charSeq.map { it.toInt() })
}
| backend.native/tests/external/stdlib/collections/GroupingTest/groupingProducers.kt | 3371040353 |
/*
* 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
import com.google.common.collect.Multimap
import io.pixeloutlaw.minecraft.spigot.hilt.getFromItemMeta
import io.pixeloutlaw.minecraft.spigot.hilt.getThenSetItemMeta
import io.pixeloutlaw.minecraft.spigot.hilt.setDisplayName
import io.pixeloutlaw.minecraft.spigot.hilt.setLore
import org.bukkit.attribute.Attribute
import org.bukkit.attribute.AttributeModifier
import org.bukkit.enchantments.Enchantment
import org.bukkit.inventory.EquipmentSlot
import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.meta.Damageable
import org.bukkit.inventory.meta.ItemMeta
import org.bukkit.inventory.meta.Repairable
internal fun ItemStack.setUnsafeEnchantments(enchantments: Map<Enchantment, Int>) {
this.enchantments.keys.toSet().forEach { removeEnchantment(it) }
addUnsafeEnchantments(enchantments)
}
internal const val DEFAULT_REPAIR_COST = 1000
internal fun <R> ItemStack.getFromItemMetaAsDamageable(action: Damageable.() -> R): R? {
return (this.itemMeta as? Damageable)?.run(action)
}
internal fun ItemStack.getThenSetItemMetaAsDamageable(action: Damageable.() -> Unit) {
(this.itemMeta as? Damageable)?.let {
action(it)
this.itemMeta = it as ItemMeta
}
}
internal fun <R> ItemStack.getFromItemMetaAsRepairable(action: Repairable.() -> R): R? {
return (this.itemMeta as? Repairable)?.run(action)
}
internal fun ItemStack.getThenSetItemMetaAsRepairable(action: Repairable.() -> Unit) {
(this.itemMeta as? Repairable)?.let {
action(it)
this.itemMeta = it as ItemMeta
}
}
@JvmOverloads
internal fun ItemStack.setRepairCost(cost: Int = DEFAULT_REPAIR_COST) = getThenSetItemMetaAsRepairable { this.repairCost = cost }
internal fun ItemStack.setDisplayNameChatColorized(string: String) = setDisplayName(string.chatColorize())
internal fun ItemStack.setLoreChatColorized(strings: List<String>) = setLore(strings.chatColorize())
internal fun ItemStack.getAttributeModifiers() = getFromItemMeta { attributeModifiers }
internal fun ItemStack.getAttributeModifiers(attribute: Attribute) =
getFromItemMeta { [email protected](attribute) }
internal fun ItemStack.getAttributeModifiers(equipmentSlot: EquipmentSlot) =
getFromItemMeta { [email protected](equipmentSlot) }
internal fun ItemStack.setAttributeModifiers(attributeModifiers: Multimap<Attribute, AttributeModifier>) =
getThenSetItemMeta { setAttributeModifiers(attributeModifiers) }
internal fun ItemStack.addAttributeModifier(attribute: Attribute, attributeModifier: AttributeModifier) =
getThenSetItemMeta { addAttributeModifier(attribute, attributeModifier) }
| src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/ItemStackExtensions.kt | 3461494185 |
/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.tensorflow.rule.attribute
import org.nd4j.ir.OpNamespace
import org.nd4j.samediff.frameworkimport.argDescriptorType
import org.nd4j.samediff.frameworkimport.findOp
import org.nd4j.samediff.frameworkimport.ir.IRAttribute
import org.nd4j.samediff.frameworkimport.isNd4jTensorName
import org.nd4j.samediff.frameworkimport.isOutputFrameworkAttributeName
import org.nd4j.samediff.frameworkimport.opdefs.OpDescriptorLoaderHolder
import org.nd4j.samediff.frameworkimport.process.MappingProcess
import org.nd4j.samediff.frameworkimport.rule.MappingRule
import org.nd4j.samediff.frameworkimport.rule.attribute.AttributeValueType
import org.nd4j.samediff.frameworkimport.rule.attribute.NDArrayExtractScalarValue
import org.nd4j.samediff.frameworkimport.tensorflow.ir.TensorflowIRAttr
import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowAttributeName
import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowTensorName
import org.nd4j.samediff.frameworkimport.tensorflow.ir.tensorflowAttributeValueTypeFor
import org.tensorflow.framework.*
@MappingRule("tensorflow","ndarrayextractscalarvalue","attribute")
class TensorflowNDArrayExtractScalarValue(mappingNamesToPerform: Map<String, String> = emptyMap(),
transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>> = emptyMap()) :
NDArrayExtractScalarValue<GraphDef, OpDef, NodeDef, OpDef.AttrDef, AttrValue, TensorProto, DataType>
( mappingNamesToPerform, transformerArgs) {
override fun createIRAttribute(name: String, attrDef: OpDef.AttrDef, attributeValueType: AttrValue): IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType> {
return TensorflowIRAttr(attrDef, attributeValueType)
}
override fun convertAttributesReverse(allInputArguments: List<OpNamespace.ArgDescriptor>, inputArgumentsToProcess: List<OpNamespace.ArgDescriptor>): List<IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType>> {
TODO("Not yet implemented")
}
override fun isInputFrameworkTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean {
val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!!
return isTensorflowTensorName(name, opDef)
}
override fun isNd4jTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean {
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName())
return isNd4jTensorName(name,nd4jOpDescriptor)
}
override fun isInputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean {
val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!!
return isTensorflowAttributeName(name, opDef)
}
override fun isOutputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean {
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName())
return isOutputFrameworkAttributeName(name,nd4jOpDescriptor)
}
override fun argDescriptorType(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): OpNamespace.ArgDescriptor.ArgType {
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName())
return argDescriptorType(name,nd4jOpDescriptor)
}
override fun attributeValueTypeFor(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): AttributeValueType {
val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!!
return tensorflowAttributeValueTypeFor(attributeName = name, opDef = opDef)
}
} | nd4j/samediff-import/samediff-import-tensorflow/src/main/kotlin/org/nd4j/samediff/frameworkimport/tensorflow/rule/attribute/TensorflowNDArrayExtractScalarValue.kt | 2467857709 |
package test
class A {
@get:JvmName("getFoo")
@set:JvmName("setBar")
var /*rename*/first = 1
}
fun test() {
A().first
A().first = 1
} | plugins/kotlin/idea/tests/testData/refactoring/rename/renameKotlinPropertyWithGetterSetterJvmName/before/test/test.kt | 4130068606 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Vic Lau
*
* 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.swordess.common.lang.test.foo.baz
class MyBaz | src/test/kotlin/org/swordess/common/lang/test/foo/baz/MyBaz.kt | 2204586643 |
// PROBLEM: none
fun test() {
var i = 1
i <caret>+= 2
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/suspiciousCollectionReassignment/int.kt | 2684549473 |
package test
private enum class Pr {
A
}
internal enum class In {
A
}
public enum class Pu {
A
}
| plugins/kotlin/idea/tests/testData/compiler/loadJava/compiledKotlin/enum/enumVisibility.kt | 1926966112 |
package io.fotoapparat.selector
import io.fotoapparat.characteristic.LensPosition
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
class LensPositionSelectorsTest {
@Test
fun `Select front camera which is available`() {
// Given
val availablePositions = listOf(
LensPosition.Back,
LensPosition.Front,
LensPosition.External
)
// When
val result = front()(availablePositions)
// Then
assertEquals(
LensPosition.Front,
result
)
}
@Test
fun `Select front camera which is not available`() {
// Given
val availablePositions = listOf(
LensPosition.Back,
LensPosition.External
)
// When
val result = front()(availablePositions)
// Then
assertNull(result)
}
@Test
fun `Select back camera which is available`() {
// Given
val availablePositions = listOf(
LensPosition.Back,
LensPosition.Front,
LensPosition.External
)
// When
val result = back()(availablePositions)
// Then
assertEquals(
LensPosition.Back,
result
)
}
@Test
fun `Select back camera which is not available`() {
// Given
val availablePositions = listOf(
LensPosition.Front,
LensPosition.External
)
// When
val result = back()(availablePositions)
// Then
assertNull(result)
}
@Test
fun `Select external camera which is available`() {
// Given
val availablePositions = listOf(
LensPosition.Back,
LensPosition.Front,
LensPosition.External
)
// When
val result = external()(availablePositions)
// Then
assertEquals(
LensPosition.External,
result
)
}
@Test
fun `Select external camera which is not available`() {
// Given
val availablePositions = listOf(
LensPosition.Front,
LensPosition.Back
)
// When
val result = external()(availablePositions)
// Then
assertNull(result)
}
} | fotoapparat/src/test/java/io/fotoapparat/selector/LensPositionSelectorsTest.kt | 3244360047 |
// "Surround with null check" "true"
fun foo(arg: Int?, flag: Boolean) {
if (flag) arg<caret>.hashCode()
} | plugins/kotlin/idea/tests/testData/quickfix/surroundWithNullCheck/unsafeCallInsideIf.kt | 1931485868 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.sequence.trace.impl.handler
import com.intellij.debugger.streams.wrapper.*
import com.intellij.debugger.streams.wrapper.impl.IntermediateStreamCallImpl
import com.intellij.debugger.streams.wrapper.impl.TerminatorStreamCallImpl
import org.jetbrains.kotlin.idea.debugger.sequence.trace.dsl.KotlinSequenceTypes
fun IntermediateStreamCall.withArgs(args: List<CallArgument>) =
IntermediateStreamCallImpl(name, args, typeBefore, typeAfter, textRange)
fun TerminatorStreamCall.withArgs(args: List<CallArgument>) =
TerminatorStreamCallImpl(name, args, typeBefore, resultType, textRange)
fun StreamCall.typeBefore() = if (this is TypeBeforeAware) this.typeBefore else KotlinSequenceTypes.ANY
fun StreamCall.typeAfter() = if (this is TypeAfterAware) this.typeAfter else KotlinSequenceTypes.ANY | plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/trace/impl/handler/CallUtils.kt | 2262010248 |
package flank.scripts.data.github
import com.github.kittinunf.fuel.Fuel
import com.github.kittinunf.fuel.core.Parameters
import com.github.kittinunf.fuel.core.Request
import com.github.kittinunf.fuel.core.extensions.authentication
import com.github.kittinunf.fuel.coroutines.awaitResult
import com.github.kittinunf.fuel.coroutines.awaitStringResult
import com.github.kittinunf.result.Result
import com.github.kittinunf.result.onError
import com.github.kittinunf.result.success
import com.jcabi.github.Coordinates
import com.jcabi.github.Release
import com.jcabi.github.Releases
import com.jcabi.github.Repo
import com.jcabi.github.RtGithub
import flank.common.config.flankRepository
import flank.scripts.data.github.objects.GitHubCommit
import flank.scripts.data.github.objects.GitHubCommitListDeserializer
import flank.scripts.data.github.objects.GitHubCreateIssueCommentRequest
import flank.scripts.data.github.objects.GitHubCreateIssueCommentResponse
import flank.scripts.data.github.objects.GitHubCreateIssueCommentResponseDeserializer
import flank.scripts.data.github.objects.GitHubCreateIssueRequest
import flank.scripts.data.github.objects.GitHubCreateIssueResponse
import flank.scripts.data.github.objects.GitHubCreateIssueResponseDeserializer
import flank.scripts.data.github.objects.GitHubLabelDeserializable
import flank.scripts.data.github.objects.GitHubRelease
import flank.scripts.data.github.objects.GitHubSetAssigneesRequest
import flank.scripts.data.github.objects.GitHubSetLabelsRequest
import flank.scripts.data.github.objects.GitHubUpdateIssueRequest
import flank.scripts.data.github.objects.GitHubWorkflowRunsSummary
import flank.scripts.data.github.objects.GithubPullRequest
import flank.scripts.data.github.objects.GithubPullRequestDeserializer
import flank.scripts.data.github.objects.GithubPullRequestListDeserializer
import flank.scripts.data.github.objects.GithubReleaseDeserializable
import flank.scripts.data.github.objects.GithubWorkflowRunsSummaryDeserializer
import flank.scripts.utils.exceptions.mapClientErrorToGithubException
import flank.scripts.utils.toJson
private const val URL_BASE = "https://api.github.com/repos"
// ============= HTTP GITHUB API =============
suspend fun getPrDetailsByCommit(
commitSha: String,
githubToken: String,
repo: String = flankRepository
): Result<List<GithubPullRequest>, Exception> =
Fuel.get("$URL_BASE/$repo/commits/$commitSha/pulls")
.appendGitHubHeaders(githubToken, "application/vnd.github.groot-preview+json")
.awaitResult(GithubPullRequestListDeserializer)
.mapClientErrorToGithubException()
.onError { println("Could not download info for commit $commitSha, because of ${it.message}") }
suspend fun getLatestReleaseTag(githubToken: String, repo: String = flankRepository): Result<GitHubRelease, Exception> =
Fuel.get("$URL_BASE/$repo/releases/latest")
.appendGitHubHeaders(githubToken)
.awaitResult(GithubReleaseDeserializable)
.mapClientErrorToGithubException()
suspend fun getGitHubPullRequest(
githubToken: String,
issueNumber: Int,
repo: String = flankRepository
): Result<GithubPullRequest, Exception> =
Fuel.get("$URL_BASE/$repo/pulls/$issueNumber")
.appendGitHubHeaders(githubToken)
.awaitResult(GithubPullRequestDeserializer)
.mapClientErrorToGithubException()
suspend fun getGitHubIssue(
githubToken: String,
issueNumber: Int,
repo: String = flankRepository
): Result<GithubPullRequest, Exception> =
Fuel.get("$URL_BASE/$repo/issues/$issueNumber")
.appendGitHubHeaders(githubToken)
.awaitResult(GithubPullRequestDeserializer)
.mapClientErrorToGithubException()
suspend fun getGitHubIssueList(
githubToken: String,
parameters: Parameters = emptyList(),
repo: String = flankRepository
): Result<List<GithubPullRequest>, Exception> =
Fuel.get("$URL_BASE/$repo/issues", parameters)
.appendGitHubHeaders(githubToken)
.awaitResult(GithubPullRequestListDeserializer)
.mapClientErrorToGithubException()
suspend fun getGitHubCommitList(
githubToken: String,
parameters: Parameters = emptyList(),
repo: String = flankRepository
): Result<List<GitHubCommit>, Exception> =
Fuel.get("$URL_BASE/$repo/commits", parameters)
.appendGitHubHeaders(githubToken)
.awaitResult(GitHubCommitListDeserializer)
.mapClientErrorToGithubException()
suspend fun getGitHubWorkflowRunsSummary(
githubToken: String,
workflow: String,
parameters: Parameters = emptyList(),
repo: String = flankRepository
): Result<GitHubWorkflowRunsSummary, Exception> =
Fuel.get("$URL_BASE/$repo/actions/workflows/$workflow/runs", parameters)
.appendGitHubHeaders(githubToken)
.awaitResult(GithubWorkflowRunsSummaryDeserializer)
.mapClientErrorToGithubException()
suspend fun postNewIssueComment(
githubToken: String,
issueNumber: Int,
payload: GitHubCreateIssueCommentRequest,
repo: String = flankRepository
): Result<GitHubCreateIssueCommentResponse, Exception> =
Fuel.post("$URL_BASE/$repo/issues/$issueNumber/comments")
.appendGitHubHeaders(githubToken)
.body(payload.toJson())
.awaitResult(GitHubCreateIssueCommentResponseDeserializer)
.mapClientErrorToGithubException()
suspend fun postNewIssue(
githubToken: String,
payload: GitHubCreateIssueRequest,
repo: String = flankRepository
): Result<GitHubCreateIssueResponse, Exception> =
Fuel.post("$URL_BASE/$repo/issues")
.appendGitHubHeaders(githubToken)
.body(payload.toJson())
.awaitResult(GitHubCreateIssueResponseDeserializer)
.mapClientErrorToGithubException()
suspend fun getLabelsFromIssue(githubToken: String, issueNumber: Int, repo: String = flankRepository) =
Fuel.get("$URL_BASE/$repo/issues/$issueNumber/labels")
.appendGitHubHeaders(githubToken)
.awaitResult(GitHubLabelDeserializable)
.mapClientErrorToGithubException()
suspend fun setLabelsToPullRequest(
githubToken: String,
pullRequestNumber: Int,
labels: List<String>,
repo: String = flankRepository
) {
Fuel.post("$URL_BASE/$repo/issues/$pullRequestNumber/labels")
.appendGitHubHeaders(githubToken)
.body(GitHubSetLabelsRequest(labels).toJson())
.awaitStringResult()
.onError { println("Could not set assignees because of ${it.message}") }
.success { println("$labels set to pull request #$pullRequestNumber") }
}
suspend fun setAssigneesToPullRequest(
githubToken: String,
pullRequestNumber: Int,
assignees: List<String>,
repo: String = flankRepository
) {
Fuel.post("$URL_BASE/$repo/issues/$pullRequestNumber/assignees")
.appendGitHubHeaders(githubToken)
.body(GitHubSetAssigneesRequest(assignees).toJson())
.awaitStringResult()
.onError {
println("Could not set assignees because of ${it.message}")
it.printStackTrace()
}
.success { println("$assignees set to pull request #$pullRequestNumber") }
}
fun patchIssue(
githubToken: String,
issueNumber: Int,
payload: GitHubUpdateIssueRequest,
repo: String = flankRepository
): Result<ByteArray, Exception> =
Fuel.patch("$URL_BASE/$repo/issues/$issueNumber")
.appendGitHubHeaders(githubToken)
.body(payload.toJson())
.response()
.third
.mapClientErrorToGithubException()
fun deleteOldTag(
tag: String,
username: String,
password: String,
repo: String = flankRepository
): Result<ByteArray, Exception> =
Fuel.delete("$URL_BASE/$repo/git/refs/tags/$tag")
.authentication()
.basic(username, password)
.response()
.third
.mapClientErrorToGithubException()
fun Request.appendGitHubHeaders(githubToken: String, contentType: String = "application/vnd.github.v3+json") =
appendHeader("Accept", contentType).also {
if (githubToken.isNotBlank())
appendHeader("Authorization", "token $githubToken")
}
// ============= JCABI GITHUB API =============
fun githubRepo(
token: String,
repoPath: String
): Repo = createGitHubClient(token).repos().get(Coordinates.Simple(repoPath))
private fun createGitHubClient(gitHubToken: String) = when {
gitHubToken.isEmpty() -> RtGithub()
else -> RtGithub(gitHubToken)
}
fun Repo.getRelease(tag: String): Release.Smart? =
Releases.Smart(releases()).run {
if (!exists(tag)) null
else Release.Smart(find(tag))
}
fun Repo.getOrCreateRelease(tag: String): Release.Smart = releases().getOrCreateRelease(tag)
private fun Releases.getOrCreateRelease(tag: String) =
Release.Smart(
try {
print("* Fetching release $tag - ")
Releases.Smart(this).find(tag).also { println("OK") }
} catch (e: IllegalArgumentException) {
println("FAILED")
print("* Creating new release $tag - ")
create(tag).also { println("OK") }
}
)
| flank-scripts/src/main/kotlin/flank/scripts/data/github/GithubApi.kt | 3680501387 |
package de.fabmax.kool.physics
interface TriggerListener {
fun onActorEntered(trigger: RigidActor, actor: RigidActor) { }
fun onActorExited(trigger: RigidActor, actor: RigidActor) { }
fun onShapeEntered(trigger: RigidActor, actor: RigidActor, shape: Shape) { }
fun onShapeExited(trigger: RigidActor, actor: RigidActor, shape: Shape) { }
} | kool-physics/src/commonMain/kotlin/de/fabmax/kool/physics/TriggerListener.kt | 4215447065 |
package uy.kohesive.iac.model.aws.cloudformation.resources.builders
import com.amazonaws.AmazonWebServiceRequest
import com.amazonaws.services.codedeploy.model.CreateApplicationRequest
import com.amazonaws.services.codedeploy.model.CreateDeploymentConfigRequest
import com.amazonaws.services.codedeploy.model.CreateDeploymentGroupRequest
import com.amazonaws.services.codedeploy.model.CreateDeploymentRequest
import uy.kohesive.iac.model.aws.cloudformation.ResourcePropertiesBuilder
import uy.kohesive.iac.model.aws.cloudformation.resources.CodeDeploy
class CodeDeployApplicationResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateApplicationRequest> {
override val requestClazz = CreateApplicationRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateApplicationRequest).let {
CodeDeploy.Application(
ApplicationName = request.applicationName
)
}
}
class CodeDeployDeploymentConfigResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateDeploymentConfigRequest> {
override val requestClazz = CreateDeploymentConfigRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateDeploymentConfigRequest).let {
CodeDeploy.DeploymentConfig(
DeploymentConfigName = request.deploymentConfigName,
MinimumHealthyHosts = request.minimumHealthyHosts?.let {
CodeDeploy.DeploymentConfig.MinimumHealthyHostProperty(
Type = it.type,
Value = it.value?.toString()
)
}
)
}
}
class CodeDeployDeploymentGroupResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateDeploymentGroupRequest> {
override val requestClazz = CreateDeploymentGroupRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateDeploymentGroupRequest).let {
CodeDeploy.DeploymentGroup(
ApplicationName = request.applicationName,
AutoScalingGroups = request.autoScalingGroups,
DeploymentConfigName = request.deploymentConfigName,
DeploymentGroupName = request.deploymentGroupName,
Ec2TagFilters = request.ec2TagFilters.map {
CodeDeploy.DeploymentGroup.Ec2TagFilterProperty(
Key = it.key,
Value = it.value,
Type = it.type
)
},
OnPremisesInstanceTagFilters = request.onPremisesInstanceTagFilters?.map {
CodeDeploy.DeploymentGroup.OnPremisesInstanceTagFilterProperty(
Key = it.key,
Value = it.value
)
},
ServiceRoleArn = request.serviceRoleArn,
Deployment = relatedObjects.filterIsInstance<CreateDeploymentRequest>().firstOrNull()?.let {
CodeDeploy.DeploymentGroup.DeploymentProperty(
Description = it.description,
IgnoreApplicationStopFailures = it.ignoreApplicationStopFailures?.toString(),
Revision = it.revision.let {
CodeDeploy.DeploymentGroup.RevisionProperty(
GitHubLocation = it.gitHubLocation?.let {
CodeDeploy.DeploymentGroup.RevisionProperty.GitHubLocationProperty(
CommitId = it.commitId,
Repository = it.repository
)
},
S3Location = it.s3Location?.let {
CodeDeploy.DeploymentGroup.RevisionProperty.S3LocationProperty(
Bucket = it.bucket,
Key = it.key,
BundleType = it.bundleType,
ETag = it.eTag,
Version = it.version
)
},
RevisionType = it.revisionType
)
}
)
}
)
}
}
| model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/cloudformation/resources/builders/CodeDeploy.kt | 467976244 |
package com.simplemobiletools.musicplayer.models
import androidx.room.*
import com.simplemobiletools.commons.helpers.AlphanumericComparator
import com.simplemobiletools.commons.helpers.SORT_DESCENDING
import com.simplemobiletools.musicplayer.helpers.PLAYER_SORT_BY_TITLE
@Entity(tableName = "playlists", indices = [(Index(value = ["id"], unique = true))])
data class Playlist(
@PrimaryKey(autoGenerate = true) var id: Int,
@ColumnInfo(name = "title") var title: String,
@Ignore var trackCount: Int = 0
) : Comparable<Playlist> {
constructor() : this(0, "", 0)
companion object {
var sorting = 0
}
override fun compareTo(other: Playlist): Int {
var result = when {
sorting and PLAYER_SORT_BY_TITLE != 0 -> AlphanumericComparator().compare(title.toLowerCase(), other.title.toLowerCase())
else -> trackCount.compareTo(other.trackCount)
}
if (sorting and SORT_DESCENDING != 0) {
result *= -1
}
return result
}
fun getBubbleText() = when {
sorting and PLAYER_SORT_BY_TITLE != 0 -> title
else -> trackCount.toString()
}
}
| app/src/main/kotlin/com/simplemobiletools/musicplayer/models/Playlist.kt | 4008024355 |
/**
* <slate_header>
* author: Kishore Reddy
* url: www.github.com/code-helix/slatekit
* copyright: 2015 Kishore Reddy
* license: www.github.com/code-helix/slatekit/blob/master/LICENSE.md
* desc: A tool-kit, utility library and server-backend
* usage: Please refer to license on github for more info.
* </slate_header>
*/
package slatekit.examples
//<doc:import_required>
import slatekit.notifications.sms.SmsMessage
import slatekit.notifications.sms.SmsService
import slatekit.notifications.sms.TwilioSms
//</doc:import_required>
//<doc:import_examples>
import slatekit.common.templates.Template
import slatekit.common.templates.TemplatePart
import slatekit.common.templates.Templates
import slatekit.common.conf.Config
import slatekit.common.info.ApiLogin
import slatekit.common.types.Vars
import slatekit.common.ext.env
import slatekit.results.Try
import slatekit.results.Success
import kotlinx.coroutines.runBlocking
import slatekit.common.ext.orElse
import slatekit.common.io.Uris
import slatekit.common.types.Countries
//</doc:import_examples>
class Example_Sms : Command("sms") {
override fun execute(request: CommandRequest): Try<Any> {
//<doc:setup>
// Setup 1: Getting Api key/login info from config
// Load the config file from slatekit directory in user_home directory
// e.g. {user_home}/myapp/conf/sms.conf
// NOTE: It is safer/more secure to store config files there.
val conf = Config.of("~/.slatekit/conf/sms.conf")
val apiKey1 = conf.apiLogin("sms")
// Setup 2: Get the api key either through conf or explicitly
val apiKey2 = ApiLogin("17181234567", "ABC1234567", "password", "dev", "twilio-sms")
// Setup 3a: Setup the sms service ( basic ) with api key
// Note: The sms service will default to only USA ( you can customize this later )
val apiKey = apiKey1 ?: apiKey2
val sms1 = TwilioSms(apiKey.key, apiKey.pass, apiKey.account)
// Setup 3b: Setup the sms service with support for templates
// Template 1: With explicit text and embedded variables
// Template 2: Loaded from text file
val templates = Templates.build(
templates = listOf(
Template("sms_welcome", """
Hi @{user.name}, Welcome to @{app.name}!
We have sent a welcome email and account confirmation to @{user.email}.
""".trimIndent()),
Template("sms_confirm", Uris.readText("~/slatekit/templates/sms_confirm.txt") ?: "")
),
subs = listOf(
"app.name" to { s: TemplatePart -> "My App" },
"app.from" to { s: TemplatePart -> "My App Team" }
)
)
val sms2 = TwilioSms(apiKey.key, apiKey.pass, apiKey.account, templates)
// Setup 3b: Setup the templates with support for different country codes
val countries = Countries.filter(listOf("US", "FR"))
val sms3 = TwilioSms(apiKey.key, apiKey.pass, apiKey.account, templates, countries)
val sms: SmsService = sms3
//</doc:setup>
//<doc:examples>
runBlocking {
// Sample phone number ( loaded from environment variable for test/example purposes )
val phone = "SLATEKIT_EXAMPLE_PHONE".env().orElse("1234567890")
// Use case 1: Send an invitation message to phone "234567890 in the United States.
sms.send("Invitation to MyApp.com 1", "us", phone)
// Use case 2: Send using a constructed message object
sms.sendSync(SmsMessage("Invitation to MyApp.com 2", "us", phone))
// Use case 3: Send message using one of the templates
sms.sendTemplate("sms_welcome", "us", phone,
Vars(listOf(
"user.name" to "user1",
"user.email" to "[email protected]"
)))
}
//</doc:examples>
return Success("")
}
}
| src/apps/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/Example_Sms.kt | 3020876322 |
package io.github.feelfreelinux.wykopmobilny.ui.modules.links.linkdetails
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.Menu
import android.view.MenuItem
import androidx.core.content.ContextCompat
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.api.WykopImageFile
import io.github.feelfreelinux.wykopmobilny.api.suggest.SuggestApi
import io.github.feelfreelinux.wykopmobilny.base.BaseActivity
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Link
import io.github.feelfreelinux.wykopmobilny.models.dataclass.LinkComment
import io.github.feelfreelinux.wykopmobilny.ui.adapters.LinkDetailsAdapter
import io.github.feelfreelinux.wykopmobilny.ui.fragments.linkcomments.LinkCommentViewListener
import io.github.feelfreelinux.wykopmobilny.ui.modules.input.BaseInputActivity
import io.github.feelfreelinux.wykopmobilny.ui.widgets.InputToolbarListener
import io.github.feelfreelinux.wykopmobilny.utils.isVisible
import io.github.feelfreelinux.wykopmobilny.utils.preferences.LinksPreferencesApi
import io.github.feelfreelinux.wykopmobilny.utils.preferences.SettingsPreferencesApi
import io.github.feelfreelinux.wykopmobilny.utils.prepare
import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserManagerApi
import kotlinx.android.synthetic.main.activity_link_details.*
import kotlinx.android.synthetic.main.toolbar.*
import javax.inject.Inject
class LinkDetailsActivity : BaseActivity(), LinkDetailsView, androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener,
InputToolbarListener, LinkCommentViewListener {
companion object {
const val EXTRA_LINK = "LINK_PARCEL"
const val EXTRA_LINK_ID = "EXTRA_LINKID"
const val EXTRA_COMMENT_ID = "EXTRA_COMMENT_ID"
fun createIntent(context: Context, link: Link) =
Intent(context, LinkDetailsActivity::class.java).apply {
putExtra(EXTRA_LINK, link)
}
fun createIntent(context: Context, linkId: Int, commentId: Int? = null) =
Intent(context, LinkDetailsActivity::class.java).apply {
putExtra(EXTRA_LINK_ID, linkId)
putExtra(EXTRA_COMMENT_ID, commentId)
}
}
@Inject lateinit var userManagerApi: UserManagerApi
@Inject lateinit var settingsApi: SettingsPreferencesApi
@Inject lateinit var suggestionsApi: SuggestApi
@Inject lateinit var linkPreferences: LinksPreferencesApi
@Inject lateinit var adapter: LinkDetailsAdapter
@Inject lateinit var presenter: LinkDetailsPresenter
lateinit var contentUri: Uri
override val enableSwipeBackLayout: Boolean = true
val linkId by lazy {
if (intent.hasExtra(EXTRA_LINK)) link.id else
intent.getIntExtra(EXTRA_LINK_ID, -1)
}
private val link by lazy { intent.getParcelableExtra<Link>(EXTRA_LINK) }
private var replyLinkId: Int = 0
private val linkCommentId by lazy {
intent.getIntExtra(EXTRA_COMMENT_ID, -1)
}
override fun updateLinkComment(comment: LinkComment) {
adapter.updateLinkComment(comment)
}
override fun replyComment(comment: LinkComment) {
replyLinkId = comment.id
inputToolbar.addAddressant(comment.author.nick)
}
override fun setCollapsed(comment: LinkComment, isCollapsed: Boolean) {
adapter.link?.comments?.forEach {
when (comment.id) {
it.id -> {
it.isCollapsed = isCollapsed
it.isParentCollapsed = false
}
it.parentId -> it.isParentCollapsed = isCollapsed
}
}
adapter.notifyDataSetChanged()
}
override fun getReplyCommentId(): Int {
return if (replyLinkId != 0 && inputToolbar.textBody.contains("@")) replyLinkId
else -1
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_link_details)
setSupportActionBar(toolbar)
presenter.subscribe(this)
adapter.linkCommentViewListener = this
adapter.linkHeaderActionListener = presenter
adapter.linkCommentActionListener = presenter
supportActionBar?.apply {
title = null
setDisplayHomeAsUpEnabled(true)
}
toolbar.overflowIcon = ContextCompat.getDrawable(this, R.drawable.ic_sort)
// Prepare RecyclerView
recyclerView?.apply {
prepare()
// Set margin, adapter
this.adapter = [email protected]
}
supportActionBar?.title = "Znalezisko"
presenter.linkId = linkId
if (intent.hasExtra(EXTRA_LINK)) {
adapter.link = link
adapter.notifyDataSetChanged()
}
adapter.highlightCommentId = linkCommentId
// Prepare InputToolbar
inputToolbar.setup(userManagerApi, suggestionsApi)
inputToolbar.inputToolbarListener = this
swiperefresh.setOnRefreshListener(this)
presenter.sortBy = linkPreferences.linkCommentsDefaultSort ?: "best"
adapter.notifyDataSetChanged()
loadingView?.isVisible = true
hideInputToolbar()
if (adapter.link != null) {
presenter.loadComments()
presenter.updateLink()
} else {
presenter.loadLinkAndComments()
}
setSubtitle()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater?.inflate(R.menu.link_details_menu, menu)
return true
}
private fun setSubtitle() {
supportActionBar?.setSubtitle(
when (presenter.sortBy) {
"new" -> R.string.sortby_newest
"old" -> R.string.sortby_oldest
else -> R.string.sortby_best
}
)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.refresh -> onRefresh()
R.id.sortbyBest -> {
presenter.sortBy = "best"
linkPreferences.linkCommentsDefaultSort = "best"
setSubtitle()
presenter.loadComments()
swiperefresh?.isRefreshing = true
}
R.id.sortbyNewest -> {
presenter.sortBy = "new"
linkPreferences.linkCommentsDefaultSort = "new"
setSubtitle()
presenter.loadComments()
swiperefresh?.isRefreshing = true
}
R.id.sortbyOldest -> {
presenter.sortBy = "old"
linkPreferences.linkCommentsDefaultSort = "old"
setSubtitle()
presenter.loadComments()
swiperefresh?.isRefreshing = true
}
android.R.id.home -> finish()
}
return true
}
override fun onRefresh() {
presenter.loadComments()
presenter.updateLink()
adapter.notifyDataSetChanged()
}
override fun showLinkComments(comments: List<LinkComment>) {
adapter.link?.comments = comments.toMutableList()
// Auto-Collapse comments depending on settings
if (settingsApi.hideLinkCommentsByDefault) {
adapter.link?.comments?.forEach {
if (it.parentId == it.id) {
it.isCollapsed = true
} else {
it.isParentCollapsed = true
}
}
}
loadingView?.isVisible = false
swiperefresh?.isRefreshing = false
adapter.notifyDataSetChanged()
inputToolbar.show()
if (linkCommentId != -1 && adapter.link != null) {
if (settingsApi.hideLinkCommentsByDefault) {
expandAndScrollToComment(linkCommentId)
} else {
scrollToComment(linkCommentId)
}
}
}
private fun expandAndScrollToComment(linkCommentId: Int) {
adapter.link?.comments?.let { allComments ->
val parentId = allComments.find { it.id == linkCommentId }?.parentId
allComments.forEach {
if (it.parentId == parentId) {
it.isCollapsed = false
it.isParentCollapsed = false
}
}
}
adapter.notifyDataSetChanged()
val comments = adapter.link!!.comments
var index = 0
for (i in 0 until comments.size) {
if (!comments[i].isParentCollapsed) index++
if (comments[i].id == linkCommentId) break
}
recyclerView?.scrollToPosition(index + 1)
}
override fun scrollToComment(id: Int) {
val index = adapter.link!!.comments.indexOfFirst { it.id == id }
recyclerView?.scrollToPosition(index + 1)
}
override fun updateLink(link: Link) {
link.comments = adapter.link?.comments ?: mutableListOf()
adapter.updateLinkHeader(link)
inputToolbar.show()
}
override fun openGalleryImageChooser() {
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(
Intent.createChooser(
intent,
getString(R.string.insert_photo_galery)
), BaseInputActivity.USER_ACTION_INSERT_PHOTO
)
}
override fun sendPhoto(photo: String?, body: String, containsAdultContent: Boolean) {
presenter.sendReply(body, photo, containsAdultContent)
}
override fun sendPhoto(photo: WykopImageFile, body: String, containsAdultContent: Boolean) {
presenter.sendReply(body, photo, containsAdultContent)
}
override fun hideInputToolbar() {
inputToolbar.hide()
}
override fun hideInputbarProgress() {
inputToolbar.showProgress(false)
}
override fun resetInputbarState() {
hideInputbarProgress()
inputToolbar.resetState()
replyLinkId = 0
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
BaseInputActivity.USER_ACTION_INSERT_PHOTO -> {
inputToolbar.setPhoto(data?.data)
}
BaseInputActivity.REQUEST_CODE -> {
onRefresh()
}
BaseInputActivity.USER_ACTION_INSERT_PHOTO_CAMERA -> {
inputToolbar.setPhoto(contentUri)
}
BaseInputActivity.EDIT_LINK_COMMENT -> {
val commentId = data?.getIntExtra("commentId", -1)
onRefresh()
scrollToComment(commentId ?: -1)
}
}
}
}
override fun openCamera(uri: Uri) {
contentUri = uri
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
startActivityForResult(intent, BaseInputActivity.USER_ACTION_INSERT_PHOTO_CAMERA)
}
override fun onDestroy() {
super.onDestroy()
presenter.unsubscribe()
}
} | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/links/linkdetails/LinkDetailsActivity.kt | 486471217 |
// 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.hints
import com.intellij.codeInsight.hints.InlayInfo
import com.intellij.codeInsight.hints.chain.AbstractCallChainHintsProvider
import com.intellij.codeInsight.hints.presentation.InlayPresentation
import com.intellij.codeInsight.hints.presentation.PresentationFactory
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.parameterInfo.HintsTypeRenderer
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
/**
* Kotlin's analog for Java's [com.intellij.codeInsight.hints.MethodChainsInlayProvider]
*
* Test - [org.jetbrains.kotlin.idea.codeInsight.hints.KotlinCallChainHintsProviderTest]
*/
class KotlinCallChainHintsProvider : AbstractCallChainHintsProvider<KtQualifiedExpression, KotlinType, BindingContext>() {
override val previewText: String
get() = """
fun main() {
(1..100).filter { it % 2 == 0 }
.map { it * 2 }
.takeIf { list ->
list.all { it % 2 == 0 }
}
?.map { "item: ${'$'}it" }
?.forEach { println(it) }
}
inline fun IntRange.filter(predicate: (Int) -> Boolean): List<Int> = TODO()
inline fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R> = TODO()
inline fun <T> T.takeIf(predicate: (T) -> Boolean): T? = TODO()
inline fun <T> Iterable<T>.all(predicate: (T) -> Boolean): Boolean = TODO()
inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit = TODO()
inline fun println(message: Any?) = TODO()
""".trimIndent()
override fun KotlinType.getInlayPresentation(
expression: PsiElement,
factory: PresentationFactory,
project: Project,
context: BindingContext
): InlayPresentation {
val inlayInfoDetails = HintsTypeRenderer
.getInlayHintsTypeRenderer(context, expression as? KtElement ?: error("Only Kotlin psi are possible"))
.renderType(this)
return KotlinAbstractHintsProvider.getInlayPresentationForInlayInfoDetails(
InlayInfoDetails(InlayInfo("", expression.textRange.endOffset), inlayInfoDetails),
factory,
project,
this@KotlinCallChainHintsProvider
)
}
override fun getTypeComputationContext(topmostDotQualifiedExpression: KtQualifiedExpression): BindingContext {
return topmostDotQualifiedExpression.analyze(BodyResolveMode.PARTIAL_NO_ADDITIONAL)
}
override fun PsiElement.getType(context: BindingContext): KotlinType? {
return context.getType(this as? KtExpression ?: return null)
}
override val dotQualifiedClass: Class<KtQualifiedExpression>
get() = KtQualifiedExpression::class.java
override fun KtQualifiedExpression.getReceiver(): PsiElement {
return receiverExpression
}
override fun KtQualifiedExpression.getParentDotQualifiedExpression(): KtQualifiedExpression? {
var expr: PsiElement? = parent
while (
expr is KtPostfixExpression ||
expr is KtParenthesizedExpression ||
expr is KtArrayAccessExpression ||
expr is KtCallExpression
) {
expr = expr.parent
}
return expr as? KtQualifiedExpression
}
override fun PsiElement.skipParenthesesAndPostfixOperatorsDown(): PsiElement? {
var expr: PsiElement? = this
while (true) {
expr = when (expr) {
is KtPostfixExpression -> expr.baseExpression
is KtParenthesizedExpression -> expr.expression
is KtArrayAccessExpression -> expr.arrayExpression
is KtCallExpression -> expr.calleeExpression
else -> break
}
}
return expr
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/hints/KotlinCallChainHintsProvider.kt | 2524315079 |
public open class X: A() {
public override fun foo() {
}
}
public class Y: X() {
public override fun foo() {
}
}
public class Z: B() {
public override fun foo() {
}
} | plugins/kotlin/idea/tests/testData/findUsages/java/findJavaMethodUsages/JKMethodOverrides.1.kt | 2294129188 |
package io.github.feelfreelinux.wykopmobilny.ui.modules.settings
import dagger.Module
import dagger.Provides
import io.github.feelfreelinux.wykopmobilny.ui.modules.NewNavigator
import io.github.feelfreelinux.wykopmobilny.ui.modules.NewNavigatorApi
@Module
class SettingsActivityModule {
@Provides
fun provideNavigator(settingsActivity: SettingsActivity): NewNavigatorApi = NewNavigator(settingsActivity)
} | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/settings/SettingsActivityModule.kt | 2884768553 |
package io.github.feelfreelinux.wykopmobilny.api.user
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.LoginResponse
import io.reactivex.Single
interface LoginApi {
fun getUserSessionToken(): Single<LoginResponse>
} | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/api/user/LoginApi.kt | 2219847639 |
package com.zhou.android.common
import android.content.Context
import android.graphics.Rect
import android.support.v7.widget.RecyclerView
import android.view.View
/**
* 边距设置
* Created by mxz on 2020/3/23.
*/
class PaddingItemDecoration(context: Context, left: Int = 0, top: Int = 0, right: Int = 0, bottom: Int = 0)
: RecyclerView.ItemDecoration() {
private var leftPadding = 0
private var topPadding = 0
private var rightPadding = 0
private var bottomPadding = 0
init {
val density = context.resources.displayMetrics.density
leftPadding = (density * left).toInt()
topPadding = (density * top).toInt()
rightPadding = (density * right).toInt()
bottomPadding = (density * bottom).toInt()
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) {
outRect.set(leftPadding, topPadding, rightPadding, bottomPadding)
}
} | app/src/main/java/com/zhou/android/common/PaddingItemDecoration.kt | 349373764 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:ApiStatus.Experimental
package com.intellij.openapi.progress
import kotlinx.coroutines.suspendCancellableCoroutine
import org.jetbrains.annotations.ApiStatus
import java.util.concurrent.atomic.AtomicReference
import kotlin.coroutines.AbstractCoroutineContextElement
import kotlin.coroutines.Continuation
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.resume
/**
* Coroutine pause-ability is cooperative, the coroutine must periodically invoke [checkCanceled] to achieve that.
*
* Example:
* ```
* val suspender = coroutineSuspender()
* launch(Dispatchers.Default + suspender) {
* for (item in data) {
* checkCanceled()
* // process data
* }
* }
*
* // later e.g. when user clicks the button:
* suspender.pause() // after this call the coroutine (and its children) will suspend in the checkCanceled()
* ```
*
* @param active `true` means non-paused, while `false` creates a suspender in paused state
* @return handle which can be used to pause and resume the coroutine
* @see checkCanceled
*/
fun coroutineSuspender(active: Boolean = true): CoroutineSuspender = CoroutineSuspenderElement(active)
/**
* Implementation of this interface is thread-safe.
*/
@ApiStatus.NonExtendable
interface CoroutineSuspender : CoroutineContext {
fun pause()
fun resume()
}
private val EMPTY_PAUSED_STATE: CoroutineSuspenderState = CoroutineSuspenderState.Paused(emptyArray())
private sealed class CoroutineSuspenderState {
object Active : CoroutineSuspenderState()
class Paused(val continuations: Array<Continuation<Unit>>) : CoroutineSuspenderState()
}
/**
* Internal so it's not possible to access this element from the client code,
* because clients must not be able to pause themselves.
* The code which calls [coroutineSuspender] must store the reference somewhere,
* because this code is responsible for pausing/resuming.
*/
internal object CoroutineSuspenderElementKey : CoroutineContext.Key<CoroutineSuspenderElement>
internal class CoroutineSuspenderElement(active: Boolean)
: AbstractCoroutineContextElement(CoroutineSuspenderElementKey),
CoroutineSuspender {
private val myState: AtomicReference<CoroutineSuspenderState> = AtomicReference(
if (active) CoroutineSuspenderState.Active else EMPTY_PAUSED_STATE
)
override fun pause() {
myState.compareAndSet(CoroutineSuspenderState.Active, EMPTY_PAUSED_STATE)
}
override fun resume() {
val oldState = myState.getAndSet(CoroutineSuspenderState.Active)
if (oldState is CoroutineSuspenderState.Paused) {
for (suspendedContinuation in oldState.continuations) {
suspendedContinuation.resume(Unit)
}
}
}
suspend fun checkPaused() {
while (true) {
when (val state = myState.get()) {
is CoroutineSuspenderState.Active -> return // don't suspend
is CoroutineSuspenderState.Paused -> suspendCancellableCoroutine { continuation: Continuation<Unit> ->
val newState = CoroutineSuspenderState.Paused(state.continuations + continuation)
if (!myState.compareAndSet(state, newState)) {
// don't suspend here; on the next loop iteration either the CAS will succeed, or the suspender will be in Active state
continuation.resume(Unit)
}
}
}
}
}
}
| platform/util-ex/src/com/intellij/openapi/progress/suspender.kt | 2314245839 |
package uk.co.alt236.btlescan.ui.main.recyclerview.model
import uk.co.alt236.bluetoothlelib.device.beacon.ibeacon.IBeaconDevice
import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewItem
class IBeaconItem(val device: IBeaconDevice) : RecyclerViewItem | sample_app/src/main/java/uk/co/alt236/btlescan/ui/main/recyclerview/model/IBeaconItem.kt | 578114015 |
/*
* Copyright 2012-2016 Dmitri Pisarenko
*
* WWW: http://altruix.cc
* E-Mail: [email protected]
* Skype: dp118m (voice calls must be scheduled in advance)
*
* Physical address:
*
* 4-i Rostovskii pereulok 2/1/20
* 119121 Moscow
* Russian Federation
*
* This file is part of econsim-tr01.
*
* econsim-tr01 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* econsim-tr01 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with econsim-tr01. If not, see <http://www.gnu.org/licenses/>.
*
*/
package cc.altruix.econsimtr01.ch0202
import org.fest.assertions.Assertions
import org.junit.Test
/**
* @author Dmitri Pisarenko ([email protected])
* @version $Id$
* @since 1.0
*/
class PersonTests {
@Test
fun willingToRecommendSetterWorks() {
val out = Person()
out.willingToRecommend = true
Assertions.assertThat(out.willingToRecommend).isTrue()
}
}
| src/test/java/cc/altruix/econsimtr01/ch0202/PersonTests.kt | 3782319836 |
// 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.stubindex
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.stubs.StubIndex
import com.intellij.psi.stubs.StubIndexKey
import org.jetbrains.kotlin.psi.KtNamedFunction
object KotlinFunctionShortNameIndex : KotlinStringStubIndexExtension<KtNamedFunction>(KtNamedFunction::class.java) {
private val KEY: StubIndexKey<String, KtNamedFunction> =
StubIndexKey.createIndexKey("org.jetbrains.kotlin.idea.stubindex.KotlinFunctionShortNameIndex")
override fun getKey(): StubIndexKey<String, KtNamedFunction> = KEY
override fun get(s: String, project: Project, scope: GlobalSearchScope): Collection<KtNamedFunction> {
return StubIndex.getElements(KEY, s, project, scope, KtNamedFunction::class.java)
}
@JvmStatic
@Deprecated("Use KotlinFunctionShortNameIndex as an object.", ReplaceWith("KotlinFunctionShortNameIndex"))
fun getInstance(): KotlinFunctionShortNameIndex = KotlinFunctionShortNameIndex
} | plugins/kotlin/base/indices/src/org/jetbrains/kotlin/idea/stubindex/KotlinFunctionShortNameIndex.kt | 923292859 |
package alraune
import pieces100.*
import vgrechka.*
class SeedApprovedWriters {
companion object {
val includeDostoebskys by FeatureFlag(false, "Bunch of users to test Select2")
}
val seeds = AlSeeds()
class Fucker(val testUser: TestUser, val afterApproval: () -> Unit = {}, val fill: (WriterProfileFields) -> Unit)
fun dance(mode: SeedMode) {
val fuckers = listOf(
TestUsers.pushkin.let {tu-> Fucker(tu,
fill = {it.accept(
firstName = {it.set("Ас")},
lastName = {it.set("Пушкин")},
phone = {it.set("043 844-23-84")},
timeZone = {it.set("Europe/Kiev")},
dateOfBirth = {it.set(JsonizableLocalDate().fill(year = 1974, month = 5, day = 13))},
experience = {it.set(Experience().fill(
years = 5,
details = "В соседней комнате, куда К. прошел медленнее, чем ему того хотелось, на первый взгляд со вчерашнего вечера почти ничего не изменилось"
))},
resume = {it.set("<h2>Ас Пушкин</h2>Всегда он был склонен относиться ко всему чрезвычайно легко, признавался, что дело плохо, только когда действительно становилось очень плохо, и привык ничего не предпринимать заранее, даже если надвигалась угроза. Но сейчас ему показалось, что это неправильно, хотя все происходящее можно было почесть и за шутку, грубую шутку, которую неизвестно почему - может быть, потому, что сегодня ему исполнилось тридцать лет? - решили с ним сыграть коллеги по банку. Да, конечно, это вполне вероятно; по-видимому, следовало бы просто рассмеяться в лицо этим стражам, и они рассмеялись бы вместе с ним; а может, это просто рассыльные, вполне похоже, но почему же тогда при первом взгляде на Франца он твердо решил ни в чем не уступать этим людям?")},
currentOccupation = {it.set("Кладу кирпич")},
educationDegree = {it.set(UAEducationDegree.School)},
profession = {it.set("Продавец")},
apartment = {it.set("858")},
building = {it.set("33")},
city = {it.set("Новодружеск")},
country = {it.set("Украина")},
street = {it.set("Горького")}
)})
},
TestUsers.shelley.let {tu-> Fucker(tu,
fill = {it.accept(
firstName = {it.set("Маня")},
lastName = {it.set("Шелли")},
phone = {it.set("094 8849275")},
timeZone = {it.set("Europe/Kiev")},
dateOfBirth = {it.set(JsonizableLocalDate().fill(year = 1958, month = 10, day = 24))},
experience = {it.set(Experience().fill(
years = 11,
details = "В комнате он тотчас же стал выдвигать ящики стола; там был образцовый порядок, но удостоверение личности, которое он искал, он от волнения никак найти не мог. Наконец он нашел удостоверение на велосипед и уже хотел идти с ним к стражам, но потом эта бумажка показалась ему неубедительной, и он снова стал искать, пока не нашел свою метрику."
))},
resume = {it.set("<h2>Маня Шелли</h2>Он бросился на кровать и взял с умывальника прекрасное яблоко - он припас его на завтрак еще с вечера. Другого завтрака у него сейчас не было, и откусив большой кусок, он уверил себя, что это куда лучше, чем завтрак из грязного ночного кафе напротив, который он мог бы получить по милости своей стражи.")},
currentOccupation = {it.set("Мою посуду")},
educationDegree = {it.set(UAEducationDegree.Degree)},
profession = {it.set("Слесарь")},
apartment = {it.set("949")},
building = {it.set("92")},
city = {it.set("Носовка")},
country = {it.set("Колумбия")},
street = {it.set("Евгении Бош")}
)})
},
TestUsers.tolst.let {tu-> Fucker(tu,
fill = {
it.accept(
firstName = {it.set("Лева")},
lastName = {it.set("Толстый")},
phone = {it.set("022 435-85-88")},
timeZone = {it.set("Europe/Kiev")},
dateOfBirth = {it.set(JsonizableLocalDate().fill(year = 1948, month = 5, day = 11))},
experience = {it.set(Experience().fill(
years = 8,
details = "Он чувствовал себя хорошо и уверенно; правда, он на полдня опаздывал в банк, где служил, но при своей сравнительно высокой должности, какую он занимал, ему простят это опоздание."
))},
resume = {it.set("<h2>Лева Толстый</h2>Не привести ли в оправдание истинную причину? Он так и решил сделать. Если же ему не поверят, чему он нисколько не удивится, то он сможет сослаться на фрау Грубах или на тех стариков напротив - сейчас они, наверно, уже переходят к другому своему окошку. К. был удивлен, вернее, он удивлялся, становясь на точку зрения стражи: как это они прогнали его в другую комнату и оставили одного там, где он мог десятком способов покончить с собой? Однако он тут же подумал, уже со своей точки зрения: какая же причина могла бы его на это толкнуть? Неужели то, что рядом сидят двое и поедают его завтрак? Покончить с собой было бы настолько бессмысленно, что при всем желании он не мог бы совершить такой бессмысленный поступок.")},
currentOccupation = {it.set("Продаю всякую хуйню")},
educationDegree = {it.set(UAEducationDegree.College)},
profession = {it.set("Дворецкий")},
apartment = {it.set("42")},
building = {it.set("245")},
city = {it.set("Перевальск")},
country = {it.set("Мозамбик")},
street = {it.set("Воровского")}
)})
},
TestUsers.flaubert.let {tu-> Fucker(tu,
fill = {it.accept(
firstName = {it.set("Гюставка")},
lastName = {it.set("Флобер")},
phone = {it.set("012 488-18-88")},
timeZone = {it.set("Europe/Kiev")},
dateOfBirth = {it.set(JsonizableLocalDate().fill(year = 1977, month = 1, day = 15))},
experience = {it.set(Experience().fill(
years = 3,
details = "И если бы умственная ограниченность этих стражей не была столь очевидна, то можно было бы предположить, что и они пришли к такому же выводу и поэтому не видят никакой опасности в том, что оставили его одного."
))},
resume = {it.set("<h2>Гюставка Флобер</h2>Пусть бы теперь посмотрели, если им угодно, как он подходит к стенному шкафчику, где спрятан отличный коньяк, опрокидывает первую рюмку взамен завтрака, а потом и вторую - для храбрости, на тот случай, если храбрость понадобится, что, впрочем, маловероятно. Но тут он так испугался окрика из соседней комнаты, что зубы лязгнули о стекло.")},
currentOccupation = {it.set("Пописываю фразочки")},
educationDegree = {it.set(UAEducationDegree.School)},
profession = {it.set("Дизайнер женского белья")},
apartment = {it.set("991")},
building = {it.set("1104")},
city = {it.set("Луанда")},
country = {it.set("Ангола")},
street = {it.set("Красноармейская")})})}
)
exhaustive=when (mode) {
SeedMode.Seed -> {
fun fart(list: List<Fucker>) {
for (fucker in list) {
seeds.insertWriterAndSession(fucker.testUser)
UserSeedingFarts.createProfileAndSendForApproval(fucker.testUser, fucker.fill)
UserSeedingFarts.approveProfile(fucker.testUser)
fucker.afterApproval()
}
}
fart(fuckers)
includeDostoebskys.flag.thenElseUnit {
fart(dostoebskys)}
}
SeedMode.Render -> {
oo(li().add(simpleClassName(this)).with {
fun fart(list: List<Fucker>) {
oo(ul().with {
for (fucker in list) {
ooTestUserListItem(fucker.testUser)
}
})
}
fart(fuckers)
if (includeDostoebskys.flag)
fart(dostoebskys)
else
oo(includeDostoebskys.compose())
})
}
}
}
val dostoebskys by lazy {(1..25).map {i->
val testUser = new_TestUser(email = "[email protected]", password = "ddd",
sessionUuid = "e4c45942-2129-48b9-8e4e-d4a3c564ca27--$i", siteSuffix = "-dostoebsky-$i")
Fucker(testUser,
fill = {it.accept(
firstName = {it.set("Федя")},
lastName = {it.set("Достоебский $i")},
phone = {it.set("022 758-34-29-$i")},
timeZone = {it.set("Europe/Kiev")},
dateOfBirth = {it.set(JsonizableLocalDate().fill(year = 1988, month = 7, day = i))},
experience = {it.set(Experience().fill(
years = i,
details = "$i. Вовсе это не глупости, фрау Грубах, по крайней мере я с вами отчасти согласен."
))},
resume = {it.set("<h2>Федя Достоебский $i</h2>Правда, я сужу об этом гораздо строже, чем вы, для меня тут не только ничего научного нет, но и вообще за всем этим нет ничего. На меня напали врасплох, вот и все. Если бы я встал с постели, как только проснулся, не растерялся бы оттого, что не пришла Анна, не обратил бы внимания, попался мне кто навстречу или нет, а сразу пошел бы к вам и на этот раз в виде исключения позавтракал бы на кухне, а вас попросил бы принести мое платье из комнаты, тогда ничего и не произошло бы, все, что потом случилось, было бы задушено в корне.")},
currentOccupation = {it.set("Продаю орифлейм")},
educationDegree = {it.set(UAEducationDegree.College)},
profession = {it.set("Агроном")},
apartment = {it.set("93")},
building = {it.set("331")},
city = {it.set("Прилуки")},
country = {it.set("Украина")},
street = {it.set("Чекистов")}
)})
}}
}
| alraune/alraune/src/main/java/alraune/SeedApprovedWriters.kt | 3738910837 |
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
inline fun foo() {
do {
var x: Int = 999
println(x)
} while (x != 999)
}
| backend.native/tests/serialization/do_while.kt | 2399280148 |
// 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.resolve.lazy
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiRecursiveElementVisitor
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.idea.base.psi.KotlinPsiHeuristics
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.StatementFilter
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import org.jetbrains.kotlin.utils.addToStdlib.swap
import java.util.*
//TODO: do resolve anonymous object's body
class PartialBodyResolveFilter(
elementsToResolve: Collection<KtElement>,
private val declaration: KtDeclaration,
forCompletion: Boolean
) : StatementFilter() {
private val statementMarks = StatementMarks()
private val globalProbablyNothingCallableNames = ProbablyNothingCallableNames.getInstance(declaration.project)
private val globalProbablyContractedCallableNames = ProbablyContractedCallableNames.getInstance(declaration.project)
private val contextNothingFunctionNames = HashSet<String>()
private val contextNothingVariableNames = HashSet<String>()
override val filter: ((KtExpression) -> Boolean)? = { statementMarks.statementMark(it) != MarkLevel.NONE }
val allStatementsToResolve: Collection<KtExpression>
get() = statementMarks.allMarkedStatements()
init {
elementsToResolve.forEach { assert(declaration.isAncestor(it)) }
assert(!KtPsiUtil.isLocal(declaration)) { "Should never be invoked on local declaration otherwise we may miss some local declarations with type Nothing" }
declaration.forEachDescendantOfType<KtCallableDeclaration> { declaration ->
if (declaration.typeReference.containsProbablyNothing()) {
val name = declaration.name
if (name != null) {
if (declaration is KtNamedFunction) {
contextNothingFunctionNames.add(name)
} else {
contextNothingVariableNames.add(name)
}
}
}
}
elementsToResolve.forEach {
statementMarks.mark(it, if (forCompletion) MarkLevel.NEED_COMPLETION else MarkLevel.NEED_REFERENCE_RESOLVE)
}
declaration.forTopLevelBlocksInside { processBlock(it) }
}
//TODO: do..while is special case
private fun processBlock(block: KtBlockExpression): NameFilter {
if (isValueNeeded(block)) {
block.lastStatement()?.let { statementMarks.mark(it, MarkLevel.NEED_REFERENCE_RESOLVE) }
}
val nameFilter = NameFilter()
val startStatement = statementMarks.lastMarkedStatement(block, MarkLevel.NEED_REFERENCE_RESOLVE) ?: return nameFilter
for (statement in startStatement.siblings(forward = false)) {
if (statement !is KtExpression) continue
if (statement is KtNamedDeclaration) {
val name = statement.getName()
if (name != null && nameFilter(name)) {
statementMarks.mark(statement, MarkLevel.NEED_REFERENCE_RESOLVE)
}
} else if (statement is KtDestructuringDeclaration) {
if (statement.entries.any {
val name = it.name
name != null && nameFilter(name)
}) {
statementMarks.mark(statement, MarkLevel.NEED_REFERENCE_RESOLVE)
}
}
fun updateNameFilter() {
when (statementMarks.statementMark(statement)) {
MarkLevel.NONE, MarkLevel.TAKE -> {
}
MarkLevel.NEED_REFERENCE_RESOLVE -> nameFilter.addUsedNames(statement)
MarkLevel.NEED_COMPLETION -> nameFilter.addAllNames()
}
}
updateNameFilter()
if (!nameFilter.isEmpty) {
val smartCastPlaces = potentialSmartCastPlaces(statement) { it.affectsNames(nameFilter) }
if (!smartCastPlaces.isEmpty()) {
//TODO: do we really need correct resolve for ALL smart cast places?
smartCastPlaces.values
.flatten()
.forEach { statementMarks.mark(it, MarkLevel.NEED_REFERENCE_RESOLVE) }
updateNameFilter()
}
}
val level = statementMarks.statementMark(statement)
if (level > MarkLevel.TAKE) { // otherwise there are no statements inside that need processBlock which only works when reference resolve needed
statement.forTopLevelBlocksInside { nestedBlock ->
val childFilter = processBlock(nestedBlock)
nameFilter.addNamesFromFilter(childFilter)
}
}
}
return nameFilter
}
/**
* Finds places within the given statement that may affect smart-casts after it.
* That is, such places whose containing statements must be left in code to keep the smart-casts.
* Returns map from smart-cast expression names (variable name or qualified variable name) to places.
*/
private fun potentialSmartCastPlaces(
statement: KtExpression,
filter: (SmartCastName) -> Boolean = { true }
): Map<SmartCastName, List<KtExpression>> {
val map = HashMap<SmartCastName, ArrayList<KtExpression>>(0)
fun addPlace(name: SmartCastName, place: KtExpression) {
map.getOrPut(name) { ArrayList(1) }.add(place)
}
fun addPlaces(name: SmartCastName, places: Collection<KtExpression>) {
if (places.isNotEmpty()) {
map.getOrPut(name) { ArrayList(places.size) }.addAll(places)
}
}
fun addIfCanBeSmartCast(expression: KtExpression) {
val name = expression.smartCastExpressionName() ?: return
if (filter(name)) {
addPlace(name, expression)
}
}
statement.accept(object : ControlFlowVisitor() {
override fun visitPostfixExpression(expression: KtPostfixExpression) {
expression.acceptChildren(this)
if (expression.operationToken == KtTokens.EXCLEXCL) {
addIfCanBeSmartCast(expression.baseExpression ?: return)
}
}
override fun visitCallExpression(expression: KtCallExpression) {
super.visitCallExpression(expression)
val nameReference = expression.calleeExpression as? KtNameReferenceExpression ?: return
if (!globalProbablyContractedCallableNames.isProbablyContractedCallableName(nameReference.getReferencedName())) return
val mentionedSmartCastName = expression.findMentionedName(filter)
if (mentionedSmartCastName != null) {
addPlace(mentionedSmartCastName, expression)
}
}
override fun visitBinaryWithTypeRHSExpression(expression: KtBinaryExpressionWithTypeRHS) {
expression.acceptChildren(this)
if (expression.operationReference.getReferencedNameElementType() == KtTokens.AS_KEYWORD) {
addIfCanBeSmartCast(expression.left)
}
}
override fun visitBinaryExpression(expression: KtBinaryExpression) {
expression.acceptChildren(this)
if (expression.operationToken == KtTokens.ELVIS) {
val left = expression.left
val right = expression.right
if (left != null && right != null) {
val smartCastName = left.smartCastExpressionName()
if (smartCastName != null && filter(smartCastName)) {
val exits = collectAlwaysExitPoints(right)
addPlaces(smartCastName, exits)
}
}
}
}
override fun visitIfExpression(expression: KtIfExpression) {
val condition = expression.condition
val thenBranch = expression.then
val elseBranch = expression.`else`
val (thenSmartCastNames, elseSmartCastNames) = possiblySmartCastInCondition(condition)
fun processBranchExits(smartCastNames: Collection<SmartCastName>, branch: KtExpression?) {
if (branch == null) return
val filteredNames = smartCastNames.filter(filter)
if (filteredNames.isNotEmpty()) {
val exits = collectAlwaysExitPoints(branch)
if (exits.isNotEmpty()) {
for (name in filteredNames) {
addPlaces(name, exits)
}
}
}
}
processBranchExits(thenSmartCastNames, elseBranch)
processBranchExits(elseSmartCastNames, thenBranch)
condition?.accept(this)
if (thenBranch != null && elseBranch != null) {
val thenCasts = potentialSmartCastPlaces(thenBranch, filter)
if (thenCasts.isNotEmpty()) {
val elseCasts = potentialSmartCastPlaces(elseBranch) { filter(it) && thenCasts.containsKey(it) }
if (elseCasts.isNotEmpty()) {
for ((name, places) in thenCasts) {
if (elseCasts.containsKey(name)) { // need filtering by cast names in else-branch
addPlaces(name, places)
}
}
for ((name, places) in elseCasts) { // already filtered by cast names in then-branch
addPlaces(name, places)
}
}
}
}
}
override fun visitForExpression(expression: KtForExpression) {
// analyze only the loop-range expression, do not enter the loop body
expression.loopRange?.accept(this)
}
override fun visitWhileExpression(expression: KtWhileExpression) {
val condition = expression.condition
// we need to enter the body only for "while(true)"
if (condition.isTrueConstant()) {
expression.acceptChildren(this)
} else {
condition?.accept(this)
}
}
//TODO: when
})
return map
}
private fun KtExpression.findMentionedName(filter: (SmartCastName) -> Boolean): SmartCastName? {
var foundMentionedName: SmartCastName? = null
val visitor = object : PsiRecursiveElementVisitor() {
override fun visitElement(element: PsiElement) {
if (foundMentionedName != null) return
if (element !is KtSimpleNameExpression) super.visitElement(element)
if (element !is KtExpression) return
element.smartCastExpressionName()?.takeIf(filter)?.let { foundMentionedName = it }
}
}
accept(visitor)
return foundMentionedName
}
/**
* Returns names of expressions that would possibly be smart cast
* in then (first component) and else (second component)
* branches of an if-statement with such condition
*/
private fun possiblySmartCastInCondition(condition: KtExpression?): Pair<Set<SmartCastName>, Set<SmartCastName>> {
val emptyResult = Pair(setOf<SmartCastName>(), setOf<SmartCastName>())
when (condition) {
is KtBinaryExpression -> {
val operation = condition.operationToken
val left = condition.left ?: return emptyResult
val right = condition.right ?: return emptyResult
fun smartCastInEq(): Pair<Set<SmartCastName>, Set<SmartCastName>> = when {
left.isNullLiteral() -> {
Pair(setOf(), right.smartCastExpressionName().singletonOrEmptySet())
}
right.isNullLiteral() -> {
Pair(setOf(), left.smartCastExpressionName().singletonOrEmptySet())
}
else -> {
val leftName = left.smartCastExpressionName()
val rightName = right.smartCastExpressionName()
val names = listOfNotNull(leftName, rightName).toSet()
Pair(names, setOf())
}
}
when (operation) {
KtTokens.EQEQ, KtTokens.EQEQEQ -> return smartCastInEq()
KtTokens.EXCLEQ, KtTokens.EXCLEQEQEQ -> return smartCastInEq().swap()
KtTokens.ANDAND -> {
val casts1 = possiblySmartCastInCondition(left)
val casts2 = possiblySmartCastInCondition(right)
return Pair(casts1.first.union(casts2.first), casts1.second.intersect(casts2.second))
}
KtTokens.OROR -> {
val casts1 = possiblySmartCastInCondition(left)
val casts2 = possiblySmartCastInCondition(right)
return Pair(casts1.first.intersect(casts2.first), casts1.second.union(casts2.second))
}
}
}
is KtIsExpression -> {
val cast = condition.leftHandSide.smartCastExpressionName().singletonOrEmptySet()
return if (condition.isNegated) Pair(setOf(), cast) else Pair(cast, setOf())
}
is KtPrefixExpression -> {
if (condition.operationToken == KtTokens.EXCL) {
val operand = condition.baseExpression ?: return emptyResult
return possiblySmartCastInCondition(operand).swap()
}
}
is KtParenthesizedExpression -> {
val operand = condition.expression ?: return emptyResult
return possiblySmartCastInCondition(operand)
}
}
return emptyResult
}
/**
* If it's possible that the given statement never passes the execution to the next statement (that is, always exits somewhere)
* then this function returns a collection of all places in code that are necessary to be kept to preserve this behaviour.
*/
private fun collectAlwaysExitPoints(statement: KtExpression?): Collection<KtExpression> {
val result = ArrayList<KtExpression>()
statement?.accept(object : ControlFlowVisitor() {
var insideLoopLevel: Int = 0
override fun visitReturnExpression(expression: KtReturnExpression) {
result.add(expression)
}
override fun visitThrowExpression(expression: KtThrowExpression) {
result.add(expression)
}
override fun visitIfExpression(expression: KtIfExpression) {
expression.condition?.accept(this)
val thenBranch = expression.then
val elseBranch = expression.`else`
if (thenBranch != null && elseBranch != null) { // if we have only one branch it makes no sense to search exits in it
val thenExits = collectAlwaysExitPoints(thenBranch)
if (thenExits.isNotEmpty()) {
val elseExits = collectAlwaysExitPoints(elseBranch)
if (elseExits.isNotEmpty()) {
result.addAll(thenExits)
result.addAll(elseExits)
}
}
}
}
override fun visitForExpression(loop: KtForExpression) {
loop.loopRange?.accept(this)
// do not make sense to search exits inside for as not necessary enter it at all
}
override fun visitWhileExpression(loop: KtWhileExpression) {
val condition = loop.condition ?: return
if (condition.isTrueConstant()) {
insideLoopLevel++
loop.body?.accept(this)
insideLoopLevel--
} else {
// do not make sense to search exits inside while-loop as not necessary enter it at all
condition.accept(this)
}
}
override fun visitDoWhileExpression(loop: KtDoWhileExpression) {
loop.condition?.accept(this)
insideLoopLevel++
loop.body?.accept(this)
insideLoopLevel--
}
override fun visitBreakExpression(expression: KtBreakExpression) {
if (insideLoopLevel == 0 || expression.getLabelName() != null) {
result.add(expression)
}
}
override fun visitContinueExpression(expression: KtContinueExpression) {
if (insideLoopLevel == 0 || expression.getLabelName() != null) {
result.add(expression)
}
}
override fun visitCallExpression(expression: KtCallExpression) {
val name = (expression.calleeExpression as? KtSimpleNameExpression)?.getReferencedName()
if (name != null && (name in globalProbablyNothingCallableNames.functionNames() || name in contextNothingFunctionNames)) {
result.add(expression)
}
super.visitCallExpression(expression)
}
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
val name = expression.getReferencedName()
if (name in globalProbablyNothingCallableNames.propertyNames() || name in contextNothingVariableNames) {
result.add(expression)
}
}
override fun visitBinaryExpression(expression: KtBinaryExpression) {
if (expression.operationToken == KtTokens.ELVIS) {
// do not search exits after "?:"
expression.left?.accept(this)
} else {
super.visitBinaryExpression(expression)
}
}
})
return result
}
/**
* Recursively visits code but does not enter constructs that may not affect smart casts/control flow
*/
private abstract class ControlFlowVisitor : KtVisitorVoid() {
override fun visitKtElement(element: KtElement) {
if (element.noControlFlowInside()) return
element.acceptChildren(this)
}
private fun KtElement.noControlFlowInside() = this is KtFunction || this is KtClass || this is KtClassBody
}
private data class SmartCastName(
private val receiverName: SmartCastName?,
private val selectorName: String? /* null means "this" (and receiverName should be null */
) {
init {
if (selectorName == null) {
assert(receiverName == null) { "selectorName is allowed to be null only when receiverName is also null (which means 'this')" }
}
}
override fun toString(): String = if (receiverName != null) "$receiverName.$selectorName" else selectorName ?: "this"
fun affectsNames(nameFilter: (String) -> Boolean): Boolean {
if (selectorName == null) return true
if (!nameFilter(selectorName)) return false
return receiverName == null || receiverName.affectsNames(nameFilter)
}
}
private fun KtExpression.smartCastExpressionName(): SmartCastName? {
return when (this) {
is KtSimpleNameExpression -> SmartCastName(null, this.getReferencedName())
is KtQualifiedExpression -> {
val selector = selectorExpression as? KtSimpleNameExpression ?: return null
val selectorName = selector.getReferencedName()
val receiver = receiverExpression
if (receiver is KtThisExpression) {
return SmartCastName(null, selectorName)
}
val receiverName = receiver.smartCastExpressionName() ?: return null
return SmartCastName(receiverName, selectorName)
}
is KtThisExpression -> SmartCastName(null, null)
else -> null
}
}
//TODO: declarations with special names (e.g. "get")
private class NameFilter : (String) -> Boolean {
private var names: MutableSet<String>? = HashSet()
override fun invoke(name: String) = names == null || name in names!!
val isEmpty: Boolean
get() = names?.isEmpty() ?: false
fun addUsedNames(statement: KtExpression) {
if (names != null) {
statement.forEachDescendantOfType<KtSimpleNameExpression>(canGoInside = { it !is KtBlockExpression }) {
names!!.add(it.getReferencedName())
}
}
}
fun addNamesFromFilter(filter: NameFilter) {
if (names == null) return
if (filter.names == null) {
names = null
} else {
names!!.addAll(filter.names!!)
}
}
fun addAllNames() {
names = null
}
}
private enum class MarkLevel {
NONE,
TAKE,
NEED_REFERENCE_RESOLVE,
NEED_COMPLETION
}
companion object {
fun findStatementToResolve(element: KtElement, declaration: KtDeclaration): KtExpression? {
return element.parentsWithSelf.takeWhile { it != declaration }.firstOrNull { it.isStatement() } as KtExpression?
}
private fun KtElement.forTopLevelBlocksInside(action: (KtBlockExpression) -> Unit) {
forEachDescendantOfType(canGoInside = { it !is KtBlockExpression }, action = action)
}
private fun KtExpression?.isNullLiteral() = this?.node?.elementType == KtNodeTypes.NULL
private fun KtExpression?.isTrueConstant() = this != null && node?.elementType == KtNodeTypes.BOOLEAN_CONSTANT && text == "true"
private fun <T : Any> T?.singletonOrEmptySet(): Set<T> = if (this != null) setOf(this) else setOf()
//TODO: review logic
private fun isValueNeeded(expression: KtExpression): Boolean = when (val parent = expression.parent) {
is KtBlockExpression -> expression == parent.lastStatement() && isValueNeeded(parent)
is KtContainerNode -> { //TODO - not quite correct
val pparent = parent.parent as? KtExpression
pparent != null && isValueNeeded(pparent)
}
is KtDeclarationWithBody -> {
if (expression == parent.bodyExpression)
!parent.hasBlockBody() && !parent.hasDeclaredReturnType()
else
true
}
is KtAnonymousInitializer -> false
else -> true
}
private fun KtBlockExpression.lastStatement(): KtExpression? =
lastChild?.siblings(forward = false)?.firstIsInstanceOrNull<KtExpression>()
private fun PsiElement.isStatement() = this is KtExpression && parent is KtBlockExpression
private fun KtTypeReference?.containsProbablyNothing() =
this?.typeElement?.anyDescendantOfType<KtUserType> { KotlinPsiHeuristics.isProbablyNothing(it) } ?: false
}
private inner class StatementMarks {
private val statementMarks = HashMap<KtExpression, MarkLevel>()
private val blockLevels = HashMap<KtBlockExpression, MarkLevel>()
fun mark(element: PsiElement, level: MarkLevel) {
var e = element
while (e != declaration) {
if (e.isStatement()) {
markStatement(e as KtExpression, level)
}
e = e.parent!!
}
}
private fun markStatement(statement: KtExpression, level: MarkLevel) {
val currentLevel = statementMark(statement)
if (currentLevel < level) {
statementMarks[statement] = level
val block = statement.parent as KtBlockExpression
val currentBlockLevel = blockLevels[block] ?: MarkLevel.NONE
if (currentBlockLevel < level) {
blockLevels[block] = level
}
}
}
fun statementMark(statement: KtExpression): MarkLevel = statementMarks[statement] ?: MarkLevel.NONE
fun allMarkedStatements(): Collection<KtExpression> = statementMarks.keys
fun lastMarkedStatement(block: KtBlockExpression, minLevel: MarkLevel): KtExpression? {
val level = blockLevels[block] ?: MarkLevel.NONE
if (level < minLevel) return null // optimization
return block.lastChild.siblings(forward = false)
.filterIsInstance<KtExpression>()
.first { statementMark(it) >= minLevel }
}
}
}
| plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/resolve/lazy/PartialBodyResolveFilter.kt | 1089575630 |
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.text.chars0
import kotlin.test.*
fun assertTrue(v: Boolean) = if (!v) throw AssertionError() else Unit
fun assertFalse(v: Boolean) = if (v) throw AssertionError() else Unit
fun assertEquals(a: Int, b: Int) { if (a != b) throw AssertionError() }
fun testIsSupplementaryCodePoint() {
assertFalse(Char.isSupplementaryCodePoint(-1))
for (c in 0..0xFFFF) {
assertFalse(Char.isSupplementaryCodePoint(c.toInt()))
}
for (c in 0xFFFF + 1..0x10FFFF) {
assertTrue(Char.isSupplementaryCodePoint(c))
}
assertFalse(Char.isSupplementaryCodePoint(0x10FFFF + 1))
}
fun testIsSurrogatePair() {
assertFalse(Char.isSurrogatePair('\u0000', '\u0000'))
assertFalse(Char.isSurrogatePair('\u0000', '\uDC00'))
assertTrue( Char.isSurrogatePair('\uD800', '\uDC00'))
assertTrue( Char.isSurrogatePair('\uD800', '\uDFFF'))
assertTrue( Char.isSurrogatePair('\uDBFF', '\uDFFF'))
assertFalse(Char.isSurrogatePair('\uDBFF', '\uF000'))
}
fun testToChars() {
assertTrue(charArrayOf('\uD800', '\uDC00').contentEquals(Char.toChars(0x010000)))
assertTrue(charArrayOf('\uD800', '\uDC01').contentEquals(Char.toChars(0x010001)))
assertTrue(charArrayOf('\uD801', '\uDC01').contentEquals(Char.toChars(0x010401)))
assertTrue(charArrayOf('\uDBFF', '\uDFFF').contentEquals(Char.toChars(0x10FFFF)))
try {
Char.toChars(Int.MAX_VALUE)
throw AssertionError()
} catch (e: IllegalArgumentException) {}
}
fun testToCodePoint() {
assertEquals(0x010000, Char.toCodePoint('\uD800', '\uDC00'))
assertEquals(0x010001, Char.toCodePoint('\uD800', '\uDC01'))
assertEquals(0x010401, Char.toCodePoint('\uD801', '\uDC01'))
assertEquals(0x10FFFF, Char.toCodePoint('\uDBFF', '\uDFFF'))
}
// TODO: Uncomment when such operations are supported for supplementary codepoints and the API is public.
fun testCase() {
/*
assertEquals('A'.toInt(), Char.toUpperCase('a'.toInt()))
assertEquals('A'.toInt(), Char.toUpperCase('A'.toInt()))
assertEquals('1'.toInt(), Char.toUpperCase('1'.toInt()))
assertEquals('a'.toInt(), Char.toLowerCase('A'.toInt()))
assertEquals('a'.toInt(), Char.toLowerCase('a'.toInt()))
assertEquals('1'.toInt(), Char.toLowerCase('1'.toInt()))
assertEquals(0x010400, Char.toUpperCase(0x010428))
assertEquals(0x010400, Char.toUpperCase(0x010400))
assertEquals(0x10FFFF, Char.toUpperCase(0x10FFFF))
assertEquals(0x110000, Char.toUpperCase(0x110000))
assertEquals(0x010428, Char.toLowerCase(0x010400))
assertEquals(0x010428, Char.toLowerCase(0x010428))
assertEquals(0x10FFFF, Char.toLowerCase(0x10FFFF))
assertEquals(0x110000, Char.toLowerCase(0x110000))
*/
}
fun testCategory() {
assertEquals('\n'.category.value, CharCategory.CONTROL.value)
assertEquals('1'.category.value, CharCategory.DECIMAL_DIGIT_NUMBER.value)
assertEquals(' '.category.value, CharCategory.SPACE_SEPARATOR.value)
assertEquals('a'.category.value, CharCategory.LOWERCASE_LETTER.value)
assertEquals('A'.category.value, CharCategory.UPPERCASE_LETTER.value)
assertEquals('<'.category.value, CharCategory.MATH_SYMBOL.value)
assertEquals(';'.category.value, CharCategory.OTHER_PUNCTUATION.value)
assertEquals('_'.category.value, CharCategory.CONNECTOR_PUNCTUATION.value)
assertEquals('$'.category.value, CharCategory.CURRENCY_SYMBOL.value)
assertEquals('\u2029'.category.value, CharCategory.PARAGRAPH_SEPARATOR.value)
assertTrue('\n' in CharCategory.CONTROL)
assertTrue('1' in CharCategory.DECIMAL_DIGIT_NUMBER)
assertTrue(' ' in CharCategory.SPACE_SEPARATOR)
assertTrue('a' in CharCategory.LOWERCASE_LETTER)
assertTrue('A' in CharCategory.UPPERCASE_LETTER)
assertTrue('<' in CharCategory.MATH_SYMBOL)
assertTrue(';' in CharCategory.OTHER_PUNCTUATION)
assertTrue('_' in CharCategory.CONNECTOR_PUNCTUATION)
assertTrue('$' in CharCategory.CURRENCY_SYMBOL)
assertTrue('\u2029' in CharCategory.PARAGRAPH_SEPARATOR)
try {
CharCategory.valueOf(-1)
throw AssertionError()
} catch (e: IllegalArgumentException) {}
try {
CharCategory.valueOf(31)
throw AssertionError()
} catch (e: IllegalArgumentException) {}
try {
CharCategory.valueOf(17)
throw AssertionError()
} catch (e: IllegalArgumentException) {}
}
@Test fun runTest() {
testIsSurrogatePair()
testToChars()
testToCodePoint()
testIsSupplementaryCodePoint()
testCase()
testCategory()
} | backend.native/tests/runtime/text/chars0.kt | 2511504296 |
// 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.tools.projectWizard.plugins.templates
import org.jetbrains.kotlin.tools.projectWizard.core.Context
import org.jetbrains.kotlin.tools.projectWizard.core.PluginSettingsOwner
import org.jetbrains.kotlin.tools.projectWizard.core.entity.PipelineTask
import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase
import org.jetbrains.kotlin.tools.projectWizard.templates.ConsoleJvmApplicationTemplate
class ConsoleJvmApplicationTemplatePlugin(context: Context) : TemplatePlugin(context) {
override val path = pluginPath
override val pipelineTasks: List<PipelineTask> = super.pipelineTasks + listOf(addTemplate)
companion object : PluginSettingsOwner() {
override val pluginPath = "template.consoleJvmApplicationTemplate"
val addTemplate by pipelineTask(GenerationPhase.PREPARE) {
withAction {
TemplatesPlugin.addTemplate.execute(ConsoleJvmApplicationTemplate)
}
}
}
} | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/plugins/templates/ConsoleJvmApplicationTemplatePlugin.kt | 3350163962 |
// 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.highlighter
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.EditorNotifications
import com.intellij.util.Alarm
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import java.util.concurrent.TimeUnit
/**
* Highlighting daemon is restarted when exception is thrown, if there is a recurred error
* (e.g. within a resolve) it could lead to infinite highlighting loop.
*
* Do not rethrow exception too often to disable HL for a while
*/
class KotlinHighlightingSuspender(private val project: Project) {
private val timeoutSeconds = Registry.intValue("kotlin.suspended.highlighting.timeout", 10)
private val lastThrownExceptionTimestampPerFile = mutableMapOf<VirtualFile, Long>()
private val suspendTimeoutMs = TimeUnit.SECONDS.toMillis(timeoutSeconds.toLong())
private val updateQueue = Alarm(Alarm.ThreadToUse.SWING_THREAD, KotlinPluginDisposable.getInstance(project))
/**
* @return true, when file is suspended for the 1st time (within a timeout window)
*/
fun suspend(file: VirtualFile): Boolean {
cleanup()
if (suspendTimeoutMs <= 0) return false
val timestamp = System.currentTimeMillis()
// daemon is restarted when exception is thrown
// if there is a recurred error (e.g. within a resolve) it could lead to infinite highlighting loop
// so, do not rethrow exception too often to disable HL for a while
val lastThrownExceptionTimestamp = synchronized(lastThrownExceptionTimestampPerFile) {
val lastThrownExceptionTimestamp = lastThrownExceptionTimestampPerFile[file] ?: run {
lastThrownExceptionTimestampPerFile[file] = timestamp
0L
}
lastThrownExceptionTimestamp
}
scheduleUpdate(file)
updateNotifications(file)
return timestamp - lastThrownExceptionTimestamp > suspendTimeoutMs
}
private fun scheduleUpdate(file: VirtualFile) {
updateQueue.apply { addRequest(Runnable { updateNotifications(file) }, suspendTimeoutMs + 1) }
}
fun unsuspend(file: VirtualFile) {
synchronized(lastThrownExceptionTimestampPerFile) {
lastThrownExceptionTimestampPerFile.remove(file)
}
cleanup()
updateNotifications(file)
}
fun isSuspended(file: VirtualFile): Boolean {
cleanup()
val timestamp = System.currentTimeMillis()
val lastThrownExceptionTimestamp = synchronized(lastThrownExceptionTimestampPerFile) {
lastThrownExceptionTimestampPerFile[file] ?: return false
}
return timestamp - lastThrownExceptionTimestamp < suspendTimeoutMs
}
private fun cleanup() {
val timestamp = System.currentTimeMillis()
val filesToUpdate = mutableListOf<VirtualFile>()
val filesToUpdateLater = mutableListOf<VirtualFile>()
synchronized(lastThrownExceptionTimestampPerFile) {
if (lastThrownExceptionTimestampPerFile.isEmpty()) return
val it = lastThrownExceptionTimestampPerFile.entries.iterator()
while (it.hasNext()) {
val next = it.next()
if (timestamp - next.value > suspendTimeoutMs) {
filesToUpdate += next.key
it.remove()
}
}
filesToUpdateLater.addAll(lastThrownExceptionTimestampPerFile.keys)
}
updateQueue.cancelAllRequests()
filesToUpdate.forEach(::updateNotifications)
filesToUpdateLater.forEach(::scheduleUpdate)
}
private fun updateNotifications(file: VirtualFile) {
EditorNotifications.getInstance(project).updateNotifications(file)
}
companion object {
fun getInstance(project: Project): KotlinHighlightingSuspender = project.service()
}
} | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/highlighter/KotlinHighlightingSuspender.kt | 519577070 |
import kotlinx.cinterop.*
import kotlin.test.*
import mangling2.*
fun main() {
val mangled = `Companion$`.Two
assertEquals(`Companion$`.Two, mangled)
}
| backend.native/tests/interop/basics/mangling2.kt | 1970621705 |
package klay.core
/**
* Stores settings in a key/value map. This will attempt to store persistently, but will fall back
* to an in-memory map. Use [.isPersisted] to check if the data are being persisted.
*/
interface Storage {
/**
* Represents a batch of edits to be applied to storage in one transaction. Individual edits are
* expensive on some platforms, and this batch interface allows multiple edits to be applied
* substantially more efficiently (more than an order of magnitude) on those platforms. If you're
* going to make hundreds or thousands of changes at once, use this mechanism.
*/
interface Batch {
/** Adds an update to the batch. */
fun setItem(key: String, data: String)
/** Adds an deletion to the batch. */
fun removeItem(key: String)
/** Commits the batch, applying all queued changes. Attempts to call [.setItem] or
* [.removeItem] after a call to this method will fail. */
fun commit()
}
/**
* Sets the value associated with the specified key to `data`.
* @param key identifies the value.
* *
* @param data the value associated with the key, which must not be null.
*/
fun setItem(key: String, data: String)
/**
* Removes the item in the Storage associated with the specified key.
* @param key identifies the value.
*/
fun removeItem(key: String)
/**
* Returns the item associated with `key`, or null if no item is associated with it.
* @param key identifies the value.
* *
* @return the value associated with the given key, or null.
*/
fun getItem(key: String): String?
/**
* Creates a [Batch] that can be used to effect multiple changes to storage in a single,
* more efficient, operation.
*/
fun startBatch(): Batch
/**
* Returns an object that can be used to iterate over all storage keys. *Note:* changes
* made to storage while iterating over the keys will not be reflected in the iteration, nor will
* they conflict with it.
*/
fun keys(): Iterable<String>
/**
* Returns true if storage data will be persistent across restarts.
*/
val isPersisted: Boolean
}
| src/main/kotlin/klay/core/Storage.kt | 3256872185 |
/*
* 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.compose.ui.text.android.style
import android.text.TextPaint
import android.text.style.MetricAffectingSpan
import androidx.compose.ui.text.android.InternalPlatformTextApi
/**
* Span that change font feature settings for font.
*
* @suppress
*/
@InternalPlatformTextApi
class FontFeatureSpan(val fontFeatureSettings: String) : MetricAffectingSpan() {
override fun updateMeasureState(textPaint: TextPaint) {
textPaint.fontFeatureSettings = fontFeatureSettings
}
override fun updateDrawState(textPaint: TextPaint) {
textPaint.fontFeatureSettings = fontFeatureSettings
}
}
| text/text/src/main/java/androidx/compose/ui/text/android/style/FontFeatureSpan.kt | 2421355683 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text.android
import android.text.Spanned
internal fun Spanned.hasSpan(clazz: Class<*>): Boolean {
return nextSpanTransition(-1 /* start */, length /* limit */, clazz) != length
}
internal fun Spanned.hasSpan(clazz: Class<*>, startInclusive: Int, endExclusive: Int): Boolean {
return nextSpanTransition(startInclusive - 1, endExclusive /* limit */, clazz) != endExclusive
} | text/text/src/main/java/androidx/compose/ui/text/android/SpannedExtensions.kt | 2486372272 |
/*
* 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.saveable.samples
import androidx.annotation.Sampled
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Sampled
@Composable
fun SimpleNavigationWithSaveableStateSample() {
@Composable
fun <T : Any> Navigation(
currentScreen: T,
modifier: Modifier = Modifier,
content: @Composable (T) -> Unit
) {
// create SaveableStateHolder.
val saveableStateHolder = rememberSaveableStateHolder()
Box(modifier) {
// Wrap the content representing the `currentScreen` inside `SaveableStateProvider`.
// Here you can also add a screen switch animation like Crossfade where during the
// animation multiple screens will be displayed at the same time.
saveableStateHolder.SaveableStateProvider(currentScreen) {
content(currentScreen)
}
}
}
Column {
var screen by rememberSaveable { mutableStateOf("screen1") }
Row(horizontalArrangement = Arrangement.SpaceEvenly) {
Button(onClick = { screen = "screen1" }) {
Text("Go to screen1")
}
Button(onClick = { screen = "screen2" }) {
Text("Go to screen2")
}
}
Navigation(screen, Modifier.fillMaxSize()) { currentScreen ->
if (currentScreen == "screen1") {
Screen1()
} else {
Screen2()
}
}
}
}
@Composable
fun Screen1() {
var counter by rememberSaveable { mutableStateOf(0) }
Button(onClick = { counter++ }) {
Text("Counter=$counter on Screen1")
}
}
@Composable
fun Screen2() {
Text("Screen2")
}
@Composable
fun Button(modifier: Modifier = Modifier, onClick: () -> Unit, content: @Composable () -> Unit) {
Box(
modifier
.clickable(onClick = onClick)
.background(Color(0xFF6200EE), RoundedCornerShape(4.dp))
.padding(horizontal = 16.dp, vertical = 8.dp)
) {
content()
}
} | compose/runtime/runtime-saveable/samples/src/main/java/androidx/compose/runtime/saveable/samples/SaveableStateHolderSamples.kt | 373940777 |
/*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.gradle.configuration
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.util.xmlb.annotations.OptionTag
import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration
@State(
name = "PackageSearchGradleConfiguration",
storages = [(Storage(PackageSearchGeneralConfiguration.StorageFileName))],
)
internal class PackageSearchGradleConfiguration : BaseState(), PersistentStateComponent<PackageSearchGradleConfiguration> {
companion object {
@JvmStatic
fun getInstance(project: Project) = project.service<PackageSearchGradleConfiguration>()
}
override fun getState(): PackageSearchGradleConfiguration = this
override fun loadState(state: PackageSearchGradleConfiguration) {
this.copyFrom(state)
}
@get:OptionTag("GRADLE_SCOPES")
var gradleScopes by string(PackageSearchGradleConfigurationDefaults.GradleScopes)
@get:OptionTag("GRADLE_SCOPES_DEFAULT")
var defaultGradleScope by string(PackageSearchGradleConfigurationDefaults.GradleDefaultScope)
@get:OptionTag("UPDATE_SCOPES_ON_USE")
var updateScopesOnUsage by property(true)
fun determineDefaultGradleScope(): String =
if (!defaultGradleScope.isNullOrEmpty()) {
defaultGradleScope!!
} else {
PackageSearchGradleConfigurationDefaults.GradleDefaultScope
}
fun addGradleScope(scope: String) {
val currentScopes = getGradleScopes()
if (!currentScopes.contains(scope)) {
gradleScopes = currentScopes.joinToString(",") + ",$scope"
this.incrementModificationCount()
}
}
fun getGradleScopes(): List<String> {
var scopes = gradleScopes.orEmpty().split(",", ";", "\n")
.map { it.trim() }
.filter { it.isNotEmpty() }
if (scopes.isEmpty()) {
scopes = PackageSearchGradleConfigurationDefaults.GradleScopes.split(",", ";", "\n")
.map { it.trim() }
.filter { it.isNotEmpty() }
}
return scopes
}
}
| plugins/package-search/gradle/src/com/jetbrains/packagesearch/intellij/plugin/gradle/configuration/PackageSearchGradleConfiguration.kt | 956940171 |
package training.featuresSuggester.suggesters
import com.intellij.psi.PsiElement
import training.featuresSuggester.FeatureSuggesterBundle
import training.featuresSuggester.NoSuggestion
import training.featuresSuggester.SuggesterSupport
import training.featuresSuggester.Suggestion
import training.featuresSuggester.actions.*
import training.util.WeakReferenceDelegator
class IntroduceVariableSuggester : AbstractFeatureSuggester() {
override val id: String = "Introduce variable"
override val suggestingActionDisplayName: String = FeatureSuggesterBundle.message("introduce.variable.name")
override val message = FeatureSuggesterBundle.message("introduce.variable.message")
override val suggestingActionId = "IntroduceVariable"
override val suggestingTipId = suggestingActionId
override val minSuggestingIntervalDays = 14
override val languages = listOf("JAVA", "kotlin", "Python", "JavaScript", "ECMAScript 6")
private class ExtractedExpressionData(var exprText: String, changedStatement: PsiElement) {
var changedStatement: PsiElement? by WeakReferenceDelegator(changedStatement)
val changedStatementText: String
var declaration: PsiElement? by WeakReferenceDelegator(null)
var variableEditingFinished: Boolean = false
init {
val text = changedStatement.text
changedStatementText = text.replaceFirst(exprText, "").trim()
exprText = exprText.trim()
}
fun getDeclarationText(): String? {
return declaration?.let {
if (it.isValid) it.text else null
}
}
}
private var extractedExprData: ExtractedExpressionData? = null
override fun getSuggestion(action: Action): Suggestion {
val language = action.language ?: return NoSuggestion
val langSupport = SuggesterSupport.getForLanguage(language) ?: return NoSuggestion
when (action) {
is BeforeEditorTextRemovedAction -> {
with(action) {
val deletedText = textFragment.text.takeIf { it.isNotBlank() }?.trim() ?: return NoSuggestion
val psiFile = this.psiFile ?: return NoSuggestion
val contentOffset = caretOffset + textFragment.text.indexOfFirst { it != ' ' && it != '\n' }
val curElement = psiFile.findElementAt(contentOffset) ?: return NoSuggestion
if (langSupport.isPartOfExpression(curElement)) {
val changedStatement =
langSupport.getTopmostStatementWithText(curElement, deletedText) ?: return NoSuggestion
extractedExprData = ExtractedExpressionData(textFragment.text, changedStatement)
}
}
}
is EditorCutAction -> {
val data = extractedExprData ?: return NoSuggestion
if (data.exprText != action.text.trim()) {
extractedExprData = null
}
}
is ChildReplacedAction -> {
if (extractedExprData == null) return NoSuggestion
with(action) {
when {
langSupport.isVariableDeclarationAdded(this) -> {
extractedExprData!!.declaration = newChild
}
newChild.text.trim() == extractedExprData!!.changedStatementText -> {
extractedExprData!!.changedStatement = newChild
}
langSupport.isVariableInserted(this) -> {
extractedExprData = null
return createSuggestion()
}
}
}
}
is ChildAddedAction -> {
if (extractedExprData == null) return NoSuggestion
with(action) {
if (langSupport.isVariableDeclarationAdded(this)) {
extractedExprData!!.declaration = newChild
}
else if (newChild.text.trim() == extractedExprData!!.changedStatementText) {
extractedExprData!!.changedStatement = newChild
}
else if (!extractedExprData!!.variableEditingFinished && isVariableEditingFinished()) {
extractedExprData!!.variableEditingFinished = true
}
}
}
is ChildrenChangedAction -> {
if (extractedExprData == null) return NoSuggestion
if (action.parent === extractedExprData!!.declaration &&
!extractedExprData!!.variableEditingFinished &&
isVariableEditingFinished()
) {
extractedExprData!!.variableEditingFinished = true
}
}
else -> NoSuggestion
}
return NoSuggestion
}
private fun SuggesterSupport.isVariableDeclarationAdded(action: ChildReplacedAction): Boolean {
return isExpressionStatement(action.oldChild) && isVariableDeclaration(action.newChild)
}
private fun SuggesterSupport.isVariableDeclarationAdded(action: ChildAddedAction): Boolean {
return isCodeBlock(action.parent) && isVariableDeclaration(action.newChild)
}
private fun isVariableEditingFinished(): Boolean {
if (extractedExprData == null) return false
with(extractedExprData!!) {
val declarationText = getDeclarationText() ?: return false
return declarationText.trim().endsWith(exprText)
}
}
private fun SuggesterSupport.isVariableInserted(action: ChildReplacedAction): Boolean {
if (extractedExprData == null) return false
with(extractedExprData!!) {
return variableEditingFinished
&& declaration.let { it != null && it.isValid && action.newChild.text == getVariableName(it) }
&& changedStatement === getTopmostStatementWithText(action.newChild, "")
}
}
}
| plugins/ide-features-trainer/src/training/featuresSuggester/suggesters/IntroduceVariableSuggester.kt | 605429324 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger.core
import com.sun.jdi.LocalVariable
import com.sun.jdi.Location
import com.sun.jdi.Method
import org.jetbrains.kotlin.idea.debugger.base.util.DexDebugFacility
import org.jetbrains.kotlin.idea.debugger.base.util.safeVariables
import org.jetbrains.kotlin.idea.debugger.core.DebuggerUtils.getBorders
// A pair of a [LocalVariable] with its starting [Location] and
// a stable [Comparable] implementation.
//
// [LocalVariable.compareTo] orders variables by location and slot.
// The location is unstable on dex VMs due to spilling and the slot
// depends on compiler internals. This class orders variables
// according to the attached location and name instead.
class VariableWithLocation(
val variable: LocalVariable,
val location: Location,
) : Comparable<VariableWithLocation> {
override fun compareTo(other: VariableWithLocation): Int =
location.compareTo(other.location).takeIf { it != 0 }
?: name.compareTo(other.name)
val name: String
get() = variable.name()
override fun toString(): String = "$name at $location"
}
// Returns a list of all [LocalVariable]s in the given methods with their starting
// location, ordered according to start location and variable name.
//
// The computed start locations take variable spilling into account on a dex VM.
// On a dex VM all variables are kept in registers and may have to be spilled
// during register allocation. This means that the same source level variable may
// correspond to several variables with different locations and slots.
// This method implements a heuristic to assign each visible variable to its
// actual starting location.
//
// ---
//
// This heuristic is not perfect. During register allocation we sometimes have
// to insert additional move instructions in the middle of a method, which can
// lead to large gaps in the scope of a local variable. Even if there is no additional
// spill code, the compiler is free to reorder blocks which can also create gaps
// in the variable live ranges. Unfortunately there is no way to detect this situation
// based on the local variable table and we will end up with the wrong variable order.
fun Method.sortedVariablesWithLocation(): List<VariableWithLocation> {
val allVariables = safeVariables()
?: return emptyList()
// On the JVM we can use the variable offsets directly.
if (!DexDebugFacility.isDex(virtualMachine())) {
return allVariables.mapNotNull { local ->
local.getBorders()?.let { VariableWithLocation(local, it.start) }
}.sorted()
}
// On dex, there are no separate slots for local variables. Instead, local variables
// are kept in registers and are subject to spilling. When a variable is spilled,
// its start offset is reset. In order to sort variables by introduction order,
// we need to identify spilled variables.
//
// The heuristic we use for this is to look for pairs of variables with the same
// name and type for which one begins exactly when the other ends.
val startOffsets = mutableMapOf<Long, MutableList<LocalVariable>>()
val replacements = mutableMapOf<LocalVariable, LocalVariable>()
for (variable in allVariables) {
val startOffset = variable.getBorders()?.start ?: continue
startOffsets.getOrPut(startOffset.codeIndex()) { mutableListOf() } += variable
}
for (variable in allVariables) {
val endOffset = variable.getBorders()?.endInclusive ?: continue
// Note that the endOffset is inclusive - it doesn't necessarily correspond to
// any bytecode index - so the variable ends exactly one index later.
val otherVariables = startOffsets[endOffset.codeIndex() + 1] ?: continue
for (other in otherVariables) {
if (variable.name() == other.name() && variable.signature() == other.signature()) {
replacements[other] = variable
break
}
}
}
return allVariables.mapNotNull { variable ->
var alias = variable
while (true) {
alias = replacements[alias] ?: break
}
replacements[variable] = alias
alias.getBorders()?.let {
VariableWithLocation(variable, it.start)
}
}.sorted()
}
// Given a list of variables returns a copy of the list without duplicate variable names,
// keeping only the last occurrence for each name.
//
// For Java, this kind of filtering is done in [StackFrame.visibleVariables], but for
// Kotlin this needs to be done separately for every (inline) stack frame.
fun filterRepeatedVariables(sortedVariables: List<LocalVariable>): List<LocalVariable> =
sortedVariables.associateBy { it.name() }.values.toList()
| plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/stackFrameUtils.kt | 3523088435 |
// 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.test
class Directives {
private val directives = mutableMapOf<String, MutableList<String>?>()
operator fun contains(key: String): Boolean {
return key in directives
}
operator fun get(key: String): String? {
return directives[key]?.single()
}
fun put(key: String, value: String?) {
if (value == null) {
directives[key] = null
} else {
directives.getOrPut(key, { arrayListOf() }).let {
it?.add(value) ?: error("Null value was already passed to $key via smth like // $key")
}
}
}
// Such values could be defined several times, e.g
// MY_DIRECTIVE: XXX
// MY_DIRECTIVE: YYY
// or
// MY_DIRECTIVE: XXX, YYY
fun listValues(name: String): List<String>? {
return directives[name]?.let { values ->
values.flatMap { InTextDirectivesUtils.splitValues(arrayListOf(), it) }
}
}
} | plugins/kotlin/tests-common/test/org/jetbrains/kotlin/idea/test/Directives.kt | 312923579 |
package org.jetbrains.completion.full.line
enum class ReferenceCorrectness {
UNDEFINED,
INCORRECT,
CORRECT, ;
fun isCorrect(): Boolean {
return this != INCORRECT
}
}
| plugins/full-line/core/src/org/jetbrains/completion/full/line/ReferenceCorrectness.kt | 14782591 |
// FIR_IDENTICAL
abstract class XXX {
abstract val a : Int get
}
| plugins/kotlin/idea/tests/testData/checker/regression/Jet67.kt | 3895410381 |
// 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.rename
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.refactoring.RefactoringBundle
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.core.surroundWith.KotlinSurrounderUtils
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.resolve.calls.tasks.isDynamic
class RenameDynamicMemberHandler : KotlinVariableInplaceRenameHandler() {
override fun isAvailable(element: PsiElement?, editor: Editor, file: PsiFile): Boolean {
val callee = PsiTreeUtil.findElementOfClassAtOffset(
file, editor.caretModel.offset, KtSimpleNameExpression::class.java, false
) ?: return false
val calleeDescriptor = callee.resolveToCall()?.resultingDescriptor ?: return false
return calleeDescriptor.isDynamic()
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?, dataContext: DataContext) {
super.invoke(project, editor, file, dataContext)
editor?.let {
KotlinSurrounderUtils.showErrorHint(
project,
it,
KotlinBundle.message("text.rename.not.applicable.to.dynamically.invoked.methods"),
RefactoringBundle.message("rename.title"),
null
)
}
}
override fun invoke(project: Project, elements: Array<out PsiElement>, dataContext: DataContext) {
// Do nothing: this method is called not from editor
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameDynamicMemberHandler.kt | 1629934010 |
// 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.quickfix.createFromUsage.createCallable
import com.intellij.psi.util.findParentOfType
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtForExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.util.OperatorNameConventions
object CreateNextFunctionActionFactory : CreateCallableMemberFromUsageFactory<KtForExpression>() {
override fun getElementOfInterest(diagnostic: Diagnostic): KtForExpression? {
return diagnostic.psiElement.findParentOfType(strict = false)
}
override fun createCallableInfo(element: KtForExpression, diagnostic: Diagnostic): CallableInfo? {
val diagnosticWithParameters = DiagnosticFactory.cast(diagnostic, Errors.NEXT_MISSING, Errors.NEXT_NONE_APPLICABLE)
val ownerType = TypeInfo(diagnosticWithParameters.a, Variance.IN_VARIANCE)
val variableExpr = element.loopParameter ?: element.destructuringDeclaration ?: return null
val returnType = TypeInfo(variableExpr as KtExpression, Variance.OUT_VARIANCE)
return FunctionInfo(
OperatorNameConventions.NEXT.asString(),
ownerType,
returnType,
modifierList = KtPsiFactory(element).createModifierList(KtTokens.OPERATOR_KEYWORD)
)
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateNextFunctionActionFactory.kt | 2149394416 |
// 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.nj2k.conversions
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.nj2k.RecursiveApplicableConversionBase
import org.jetbrains.kotlin.nj2k.equalsExpression
import org.jetbrains.kotlin.nj2k.symbols.deepestFqName
import org.jetbrains.kotlin.nj2k.tree.*
class EqualsOperatorConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
override fun applyToElement(element: JKTreeElement): JKTreeElement {
if (element !is JKQualifiedExpression) return recurse(element)
if (element.receiver is JKSuperExpression) return recurse(element)
val selector = element.selector as? JKCallExpression ?: return (element)
val argument = selector.arguments.arguments.singleOrNull() ?: return recurse(element)
if (selector.identifier.deepestFqName() == "java.lang.Object.equals") {
return recurse(
JKParenthesizedExpression(
equalsExpression(
element::receiver.detached(),
argument::value.detached(),
typeFactory
)
)
)
}
return recurse(element)
}
} | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/EqualsOperatorConversion.kt | 2573998904 |
// 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.jps.incremental
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.load.kotlin.JvmBytecodeBinaryVersion
import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmMetadataVersion
import java.io.File
import java.io.IOException
import java.nio.file.Path
import kotlin.io.path.*
/**
* Manages files with actual version [loadActual] and provides expected version [expected].
* Based on that actual and expected versions [CacheStatus] can be calculated.
* This can be done by constructing [CacheAttributesDiff] and calling [CacheAttributesDiff.status].
* Based on that status system may perform required actions (i.e. rebuild something, clearing caches, etc...).
*/
class CacheVersionManager(
private val versionFile: Path,
expectedOwnVersion: Int?
) : CacheAttributesManager<CacheVersion> {
override val expected: CacheVersion? =
if (expectedOwnVersion == null) null
else CacheVersion(expectedOwnVersion, JvmBytecodeBinaryVersion.INSTANCE, JvmMetadataVersion.INSTANCE)
override fun loadActual(): CacheVersion? =
if (versionFile.notExists()) null
else try {
CacheVersion(versionFile.readText().toInt())
} catch (e: NumberFormatException) {
null
} catch (e: IOException) {
null
}
override fun writeVersion(values: CacheVersion?) {
if (values == null) versionFile.deleteIfExists()
else {
versionFile.parent.createDirectories()
versionFile.writeText(values.intValue.toString())
}
}
@get:TestOnly
val versionFileForTesting: File
get() = versionFile.toFile()
}
fun CacheVersion(own: Int, bytecode: JvmBytecodeBinaryVersion, metadata: JvmMetadataVersion): CacheVersion {
require(own in 0 until Int.MAX_VALUE / 1000000)
require(bytecode.major in 0..9)
require(bytecode.minor in 0..9)
require(metadata.major in 0..9)
require(metadata.minor in 0..99)
return CacheVersion(
own * 1000000 +
bytecode.major * 10000 + bytecode.minor * 100 +
metadata.major * 1000 + metadata.minor
)
}
data class CacheVersion(val intValue: Int) {
val own: Int
get() = intValue / 1000000
val bytecode: JvmBytecodeBinaryVersion
get() = JvmBytecodeBinaryVersion(
intValue / 10000 % 10,
intValue / 100 % 10
)
val metadata: JvmMetadataVersion
get() = JvmMetadataVersion(
intValue / 1000 % 10,
intValue / 1 % 100
)
override fun toString(): String = "CacheVersion(caches: $own, bytecode: $bytecode, metadata: $metadata)"
}
| plugins/kotlin/jps/jps-plugin/src/org/jetbrains/kotlin/jps/incremental/CacheVersionManager.kt | 1862419954 |
package eu.kanade.tachiyomi.data.database.queries
import com.pushtorefresh.storio.sqlite.queries.DeleteQuery
import com.pushtorefresh.storio.sqlite.queries.Query
import eu.kanade.tachiyomi.data.database.DbProvider
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.database.models.MangaSync
import eu.kanade.tachiyomi.data.database.tables.MangaSyncTable
import eu.kanade.tachiyomi.data.mangasync.MangaSyncService
interface MangaSyncQueries : DbProvider {
fun getMangaSync(manga: Manga, sync: MangaSyncService) = db.get()
.`object`(MangaSync::class.java)
.withQuery(Query.builder()
.table(MangaSyncTable.TABLE)
.where("${MangaSyncTable.COL_MANGA_ID} = ? AND " +
"${MangaSyncTable.COL_SYNC_ID} = ?")
.whereArgs(manga.id, sync.id)
.build())
.prepare()
fun getMangasSync(manga: Manga) = db.get()
.listOfObjects(MangaSync::class.java)
.withQuery(Query.builder()
.table(MangaSyncTable.TABLE)
.where("${MangaSyncTable.COL_MANGA_ID} = ?")
.whereArgs(manga.id)
.build())
.prepare()
fun insertMangaSync(manga: MangaSync) = db.put().`object`(manga).prepare()
fun insertMangasSync(mangas: List<MangaSync>) = db.put().objects(mangas).prepare()
fun deleteMangaSync(manga: MangaSync) = db.delete().`object`(manga).prepare()
fun deleteMangaSyncForManga(manga: Manga) = db.delete()
.byQuery(DeleteQuery.builder()
.table(MangaSyncTable.TABLE)
.where("${MangaSyncTable.COL_MANGA_ID} = ?")
.whereArgs(manga.id)
.build())
.prepare()
} | app/src/main/java/eu/kanade/tachiyomi/data/database/queries/MangaSyncQueries.kt | 1900583271 |
package usage
fun use() = inline.A().f() | plugins/kotlin/jps/jps-plugin/tests/testData/incremental/withJava/other/inlineFunctionWithJvmNameInClass/usage.kt | 1551076080 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package training.learn.lesson
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import training.learn.course.Lesson
import training.util.trainerPluginConfigName
@State(name = "LessonStateBase", storages = [Storage(value = trainerPluginConfigName)])
private class LessonStateBase : PersistentStateComponent<LessonStateBase> {
override fun getState(): LessonStateBase = this
override fun loadState(persistedState: LessonStateBase) {
map = persistedState.map.mapKeys { it.key.toLowerCase() }.toMutableMap()
}
var map: MutableMap<String, LessonState> = mutableMapOf()
companion object {
internal val instance: LessonStateBase
get() = ApplicationManager.getApplication().getService(LessonStateBase::class.java)
}
}
internal object LessonStateManager {
fun setPassed(lesson: Lesson) {
LessonStateBase.instance.map[lesson.id.toLowerCase()] = LessonState.PASSED
}
fun resetPassedStatus() {
for (lesson in LessonStateBase.instance.map) {
lesson.setValue(LessonState.NOT_PASSED)
}
}
fun getStateFromBase(lessonId: String): LessonState =
LessonStateBase.instance.map.getOrPut(lessonId.toLowerCase()) { LessonState.NOT_PASSED }
}
| plugins/ide-features-trainer/src/training/learn/lesson/LessonStateBase.kt | 1282506239 |
/*
* Copyright 2010-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.
*/
@file:OptIn(ExperimentalStdlibApi::class)
import kotlin.native.internal.*
import kotlin.native.Platform
fun main() {
// Cleaner holds onto a finalization lambda. If it doesn't get executed,
// the memory will leak. Suppress memory leak checker to check for cleaners
// leak only.
Platform.isMemoryLeakCheckerActive = false
Platform.isCleanersLeakCheckerActive = true
// This cleaner will run, because with the checker active this cleaner
// will get collected, block scheduled and executed before cleaners are disabled.
createCleaner(42) {
println(it)
}
}
| backend.native/tests/runtime/basic/cleaner_in_main_with_checker.kt | 2307368298 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.