package org.stepik.android.cache.course_list

import io.reactivex.Completable
import io.reactivex.Single
import org.stepic.droid.storage.dao.IDao
import org.stepik.android.cache.course_list.structure.DbStructureCourseListQuery
import org.stepik.android.data.course_list.model.CourseListQueryData
import org.stepik.android.data.course_list.source.CourseListQueryCacheDataSource
import org.stepik.android.domain.course_list.model.CourseListQuery
import javax.inject.Inject

class CourseListQueryCacheDataSourceImpl
@Inject
constructor(
    private val courseListQueryDataDao: IDao<CourseListQueryData>
) : CourseListQueryCacheDataSource {
    override fun getCourses(courseListQuery: CourseListQuery): Single<LongArray> =
        Single.fromCallable {
            courseListQueryDataDao
                .get(DbStructureCourseListQuery.Columns.ID, courseListQuery.toString())
                ?.courses
        }

    override fun saveCourses(courseListQuery: CourseListQuery, courses: LongArray): Completable =
        Completable.fromCallable {
            courseListQueryDataDao.insertOrReplace(CourseListQueryData(courseListQueryId = courseListQuery.toString(), courses = courses))
        }
}

Return empty LongArray when DB is empty

package org.stepik.android.cache.course_list

import io.reactivex.Completable
import io.reactivex.Single
import org.stepic.droid.storage.dao.IDao
import org.stepik.android.cache.course_list.structure.DbStructureCourseListQuery
import org.stepik.android.data.course_list.model.CourseListQueryData
import org.stepik.android.data.course_list.source.CourseListQueryCacheDataSource
import org.stepik.android.domain.course_list.model.CourseListQuery
import javax.inject.Inject

class CourseListQueryCacheDataSourceImpl
@Inject
constructor(
    private val courseListQueryDataDao: IDao<CourseListQueryData>
) : CourseListQueryCacheDataSource {
    override fun getCourses(courseListQuery: CourseListQuery): Single<LongArray> =
        Single.fromCallable {
            courseListQueryDataDao
                .get(DbStructureCourseListQuery.Columns.ID, courseListQuery.toString())
                ?.courses
                ?: LongArray(0)
        }

    override fun saveCourses(courseListQuery: CourseListQuery, courses: LongArray): Completable =
        Completable.fromCallable {
            courseListQueryDataDao.insertOrReplace(CourseListQueryData(courseListQueryId = courseListQuery.toString(), courses = courses))
        }
}


package com.example.redis

import org.junit.runner.RunWith
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.util.TestPropertyValues
import org.springframework.context.ApplicationContextInitializer
import org.springframework.context.ConfigurableApplicationContext
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit4.SpringRunner
import org.testcontainers.containers.GenericContainer

@RunWith(SpringRunner::class)
@SpringBootTest
@ContextConfiguration(initializers = [AbstractIntegrationTest.Initializer::class])
@AutoConfigureMockMvc
abstract class AbstractIntegrationTest {

    companion object {
        val redisContainer = GenericContainer<Nothing>("redis:3-alpine")
                .apply { withExposedPorts(6379) }
    }

    internal class Initializer : ApplicationContextInitializer<ConfigurableApplicationContext> {
        override fun initialize(configurableApplicationContext: ConfigurableApplicationContext) {
            redisContainer.start()

            TestPropertyValues.of(
                "spring.redis.host=${redisContainer.containerIpAddress}",
                "spring.redis.port=${redisContainer.firstMappedPort}"
            ).applyTo(configurableApplicationContext.environment)
        }
    }
}

Use host instead of containerIpAddress for Kotlin sample

package com.example.redis

import org.junit.runner.RunWith
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.util.TestPropertyValues
import org.springframework.context.ApplicationContextInitializer
import org.springframework.context.ConfigurableApplicationContext
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit4.SpringRunner
import org.testcontainers.containers.GenericContainer

@RunWith(SpringRunner::class)
@SpringBootTest
@ContextConfiguration(initializers = [AbstractIntegrationTest.Initializer::class])
@AutoConfigureMockMvc
abstract class AbstractIntegrationTest {

    companion object {
        val redisContainer = GenericContainer<Nothing>("redis:3-alpine")
                .apply { withExposedPorts(6379) }
    }

    internal class Initializer : ApplicationContextInitializer<ConfigurableApplicationContext> {
        override fun initialize(configurableApplicationContext: ConfigurableApplicationContext) {
            redisContainer.start()

            TestPropertyValues.of(
                "spring.redis.host=${redisContainer.host}",
                "spring.redis.port=${redisContainer.firstMappedPort}"
            ).applyTo(configurableApplicationContext.environment)
        }
    }
}


package com.louiscad.splittiessample.extensions

import android.view.View
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract

@ExperimentalContracts
inline fun <R> View.visibleInScope(finallyInvisible: Boolean = false, block: () -> R): R {
    contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
    return try {
        isVisible = true
        block()
    } finally {
        visibility = if (finallyInvisible) View.INVISIBLE else View.GONE
    }
}

@ExperimentalContracts
inline fun <R> View.goneInScope(block: () -> R): R {
    contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
    return try {
        isVisible = false
        block()
    } finally {
        isVisible = true
    }
}

@ExperimentalContracts
inline fun <R> View.invisibleInScope(block: () -> R): R {
    contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
    return try {
        isInvisible = true
        block()
    } finally {
        isInvisible = false
    }
}

Replace experimental annotation with UseExperimental

package com.louiscad.splittiessample.extensions

import android.view.View
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract

@UseExperimental(ExperimentalContracts::class)
inline fun <R> View.visibleInScope(finallyInvisible: Boolean = false, block: () -> R): R {
    contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
    return try {
        isVisible = true
        block()
    } finally {
        visibility = if (finallyInvisible) View.INVISIBLE else View.GONE
    }
}

@UseExperimental(ExperimentalContracts::class)
inline fun <R> View.goneInScope(block: () -> R): R {
    contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
    return try {
        isVisible = false
        block()
    } finally {
        isVisible = true
    }
}

@UseExperimental(ExperimentalContracts::class)
inline fun <R> View.invisibleInScope(block: () -> R): R {
    contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
    return try {
        isInvisible = true
        block()
    } finally {
        isInvisible = false
    }
}


Add test for discouraged use of def inspection

package nl.hannahsten.texifyidea.inspections.latex

import nl.hannahsten.texifyidea.inspections.TexifyInspectionTestBase

class LatexDiscouragedUseOfDefInspectionTest : TexifyInspectionTestBase(LatexDiscouragedUseOfDefInspection()) {
    fun `test warning for def`() = testHighlighting("""<warning descr="The use of TeX primitive \def is discouraged">\def</warning>\a1""")

    fun `test warning for let`() = testHighlighting("""<warning descr="The use of TeX primitive \let is discouraged">\let</warning>\a1""")

    fun `test quick fix def to newcommand`() = testNamedQuickFix(
            before = """\def\a1""",
            after = """\newcommand{\a}{1}""",
            numberOfFixes = 2,
            quickFixName = "Convert to \\newcommand"
    )

    fun `test quick fix def to renewcommand`() = testNamedQuickFix(
            before = """\def\a1""",
            after = """\renewcommand{\a}{1}""",
            numberOfFixes = 2,
            quickFixName = "Convert to \\renewcommand"
    )

    fun `test quick fix let to newcommand`() = testNamedQuickFix(
            before = """\let\a1""",
            after = """\newcommand{\a}{1}""",
            numberOfFixes = 2,
            quickFixName = "Convert to \\newcommand"
    )

    fun `test quick fix let to renewcommand`() = testNamedQuickFix(
            before = """\let\a1""",
            after = """\renewcommand{\a}{1}""",
            numberOfFixes = 2,
            quickFixName = "Convert to \\renewcommand"
    )
}


Create a function to set toolbar and status bar colors

package com.satsumasoftware.timetable

import android.app.Activity
import android.os.Build
import android.support.v4.content.ContextCompat
import android.support.v7.widget.Toolbar
import com.satsumasoftware.timetable.framework.Color

fun setBarColors(color: Color, activity: Activity, toolbar: Toolbar) {
    toolbar.setBackgroundColor(ContextCompat.getColor(activity, color.getPrimaryColorResId(activity)))
    if (Build.VERSION.SDK_INT >= 21) {
        activity.window.statusBarColor =
                ContextCompat.getColor(activity, color.getPrimaryDarkColorResId(activity))
    }
}


package org.jetbrains.ktor.application

import org.jetbrains.ktor.http.*
import java.io.*

/** Established connection with client, encapsulates request and response facilities
 */
public interface ApplicationRequest {
    public val application: Application

    public val requestLine: HttpRequestLine
    public val parameters: Map<String, List<String>>
    public val headers: Map<String, String>
    public val body : String

    public fun respond(handle: ApplicationResponse.() -> ApplicationRequestStatus): ApplicationRequestStatus
}

val ApplicationRequest.uri: String get() = requestLine.uri
val ApplicationRequest.method: String get() = requestLine.method
val ApplicationRequest.version: String get() = requestLine.version
fun ApplicationRequest.header(name: String): String? = headers[name]
fun ApplicationRequest.parameter(name: String): String? = headers[name]

public interface ApplicationResponse {
    public fun header(name: String, value: String): ApplicationResponse
    public fun status(code: Int): ApplicationResponse
    public fun content(text: String, encoding: String = "UTF-8"): ApplicationResponse
    public fun content(bytes: ByteArray): ApplicationResponse
    public fun contentStream(streamer: Writer.() -> Unit): ApplicationResponse

    public fun send(): ApplicationRequestStatus
    public fun sendRedirect(url: String): ApplicationRequestStatus
}

fun ApplicationResponse.header(name: String, value: Int): ApplicationResponse = header(name, value.toString())

Fix typo in (unused) extension function

package org.jetbrains.ktor.application

import org.jetbrains.ktor.http.*
import java.io.*

/** Established connection with client, encapsulates request and response facilities
 */
public interface ApplicationRequest {
    public val application: Application

    public val requestLine: HttpRequestLine
    public val parameters: Map<String, List<String>>
    public val headers: Map<String, String>
    public val body : String

    public fun respond(handle: ApplicationResponse.() -> ApplicationRequestStatus): ApplicationRequestStatus
}

val ApplicationRequest.uri: String get() = requestLine.uri
val ApplicationRequest.method: String get() = requestLine.method
val ApplicationRequest.version: String get() = requestLine.version
fun ApplicationRequest.header(name: String): String? = headers[name]
fun ApplicationRequest.parameter(name: String): String? = parameters[name]?.singleOrNull()

public interface ApplicationResponse {
    public fun header(name: String, value: String): ApplicationResponse
    public fun status(code: Int): ApplicationResponse
    public fun content(text: String, encoding: String = "UTF-8"): ApplicationResponse
    public fun content(bytes: ByteArray): ApplicationResponse
    public fun contentStream(streamer: Writer.() -> Unit): ApplicationResponse

    public fun send(): ApplicationRequestStatus
    public fun sendRedirect(url: String): ApplicationRequestStatus
}

fun ApplicationResponse.header(name: String, value: Int): ApplicationResponse = header(name, value.toString())


// 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.execution.configurations

import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.registry.Registry
import java.io.File

/**
 * @author yole
 */
fun setupLowPriorityExecution(commandLine: GeneralCommandLine, executablePath: String) {
  if (!canRunLowPriority()) {
    commandLine.exePath = executablePath
  }
  else {
    if (SystemInfo.isWindows) {
      // TODO
    }
    else {
      commandLine.exePath = "/usr/bin/nice"
      commandLine.addParameter("-n")
      commandLine.addParameter("10")
      commandLine.addParameter(executablePath)
    }
  }
}

private fun canRunLowPriority(): Boolean {
  if (!Registry.`is`("ide.allow.low.priority.process")) {
    return false
  }
  if (SystemInfo.isWindows) {
    return false
  }
  else {
    if (!niceExists) return false
  }
  return true
}

private val niceExists by lazy { File("/usr/bin/nice").exists() }

Support low priority processes on Windows

// 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.execution.configurations

import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.registry.Registry
import java.io.File

/**
 * @author yole
 */
fun setupLowPriorityExecution(commandLine: GeneralCommandLine, executablePath: String) {
  if (!canRunLowPriority()) {
    commandLine.exePath = executablePath
  }
  else {
    if (SystemInfo.isWindows) {
      commandLine.exePath = "cmd"
      commandLine.addParameters("/c", "start", "/b", "/low", "/wait", GeneralCommandLine.inescapableQuote(""), executablePath)
    }
    else {
      commandLine.exePath = "/usr/bin/nice"
      commandLine.addParameters("-n", "10", executablePath)
    }
  }
}

private fun canRunLowPriority(): Boolean {
  if (!Registry.`is`("ide.allow.low.priority.process")) {
    return false
  }
  if (!SystemInfo.isWindows && !niceExists) {
    return false
  }
  return true
}

private val niceExists by lazy { File("/usr/bin/nice").exists() }


package common

import common.util.*

/**
 * The core model classes.
 * @author Eric Pabst (epabst@gmail.com)
 * Date: 6/9/16
 * Time: 6:27 AM
 */
data class ToDo(val name: String, val dueDateString: String? = null, val note: String? = null, val createDateString: String, val id: ID<ToDo>? = null) : ProtectedWithID<ToDo> {
    constructor(name: String, dueDate: ProviderDate? = null, note: String? = null, createDate: ProviderDate = PlatformProvider.instance.now(), id: ID<ToDo>? = null) :
            this(name, dueDate?.toIsoTimestampString(), note, createDate.toIsoTimestampString(), id)

    val dueDate: ProviderDate? get() = dueDateString?.let { PlatformProvider.instance.toDate(it) }

    val createDate: ProviderDate? get() = createDateString?.let { PlatformProvider.instance.toDate(it) }

    override fun getID(): ID<ToDo>? = id

    override fun withID(id: ID<ToDo>): ToDo = copy(id = id)

    override val protectedAccess: Access get() = Access(ProtectionLevel.DEVICE)

    override fun copy(newAccess: Access): ToDo = this

    /** Used by [UndoComponent.watch]. */
    override fun toString(): String = "'$name'"
}

Fix compilation warning with ToDo

package common

import common.util.*

/**
 * The core model classes.
 * @author Eric Pabst (epabst@gmail.com)
 * Date: 6/9/16
 * Time: 6:27 AM
 */
data class ToDo(val name: String, val dueDateString: String? = null, val note: String? = null, val createDateString: String, val id: ID<ToDo>? = null) : ProtectedWithID<ToDo> {
    constructor(name: String, dueDate: ProviderDate? = null, note: String? = null, createDate: ProviderDate = PlatformProvider.instance.now(), id: ID<ToDo>? = null) :
            this(name, dueDate?.toIsoTimestampString(), note, createDate.toIsoTimestampString(), id)

    val dueDate: ProviderDate? get() = dueDateString?.let { PlatformProvider.instance.toDate(it) }

    val createDate: ProviderDate? get() = PlatformProvider.instance.toDate(createDateString)

    override fun getID(): ID<ToDo>? = id

    override fun withID(id: ID<ToDo>): ToDo = copy(id = id)

    override val protectedAccess: Access get() = Access(ProtectionLevel.DEVICE)

    override fun copy(newAccess: Access): ToDo = this

    /** Used by [UndoComponent.watch]. */
    override fun toString(): String = "'$name'"
}


package org.purescript.psi.exports

import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.PsiReferenceBase
import org.purescript.psi.data.PSDataDeclaration

class ExportedDataMemberReference(exportedDataMember: PSExportedDataMember) : PsiReferenceBase<PSExportedDataMember>(
    exportedDataMember,
    exportedDataMember.properName.textRangeInParent,
    false
) {
    override fun getVariants(): Array<PsiNamedElement> =
        candidates.distinctBy { it.name }
            .toTypedArray()

    override fun resolve(): PsiElement? =
        candidates.firstOrNull { it.name == myElement.name }

    private val candidates: Array<out PsiNamedElement>
        get() = when (val declaration = myElement.exportedData?.reference?.resolve()) {
            is PSDataDeclaration -> declaration.dataConstructorList?.dataConstructors ?: emptyArray()
            else -> emptyArray()
        }

}

Make exported data member references resolve to newtype constructors

package org.purescript.psi.exports

import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.PsiReferenceBase
import org.purescript.psi.data.PSDataDeclaration
import org.purescript.psi.newtype.PSNewTypeDeclarationImpl

class ExportedDataMemberReference(exportedDataMember: PSExportedDataMember) : PsiReferenceBase<PSExportedDataMember>(
    exportedDataMember,
    exportedDataMember.properName.textRangeInParent,
    false
) {
    override fun getVariants(): Array<PsiNamedElement> =
        candidates.distinctBy { it.name }
            .toTypedArray()

    override fun resolve(): PsiElement? =
        candidates.firstOrNull { it.name == myElement.name }

    private val candidates: Array<out PsiNamedElement>
        get() = when (val declaration = myElement.exportedData?.reference?.resolve()) {
            is PSDataDeclaration -> declaration.dataConstructorList?.dataConstructors ?: emptyArray()
            is PSNewTypeDeclarationImpl -> arrayOf(declaration.newTypeConstructor)
            else -> emptyArray()
        }
}


package com.google.android.gms.dependencies

import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
import org.junit.runner.RunWith
import org.junit.runners.JUnit4

@RunWith(JUnit4::class)
class ArtifactDependencyManagerTest {

  @Rule @JvmField var thrown: ExpectedException = ExpectedException.none()

  @Test
  fun getDependencies_SimulateConcurrencyDependencyAccess() {
    // Modify the dependencies while to iterating a retrieved set of dependencies. Since the ArtifactDependencyManager
    // is thread-safe this shouldn't cause a problem.

    val manager = ArtifactDependencyManager()
    manager.addDependency(Dependency(ARTIFACT_A_100, ARTIFACT_B_100.getArtifact(), ARTIFACT_B_100.version))
    manager.addDependency(Dependency(ARTIFACT_A_100, ARTIFACT_B_200.getArtifact(), ARTIFACT_B_200.version))

    val iterator = manager.getDependencies(ARTIFACT_B_100.getArtifact()).iterator()
    iterator.next()
    // Add a dependency and iterate again to cause a concurrency issue if the returned collection is connected to the
    // original set of dependencies in a thread-unsafe way.
    manager.addDependency(Dependency(ARTIFACT_A_100, ARTIFACT_B_300.getArtifact(), "9.9.9"))
    iterator.next()
  }
}

Rename Kotlin test class to match file name.

package com.google.android.gms.dependencies

import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
import org.junit.runner.RunWith
import org.junit.runners.JUnit4

@RunWith(JUnit4::class)
class DataObjectsTest {

  @Rule @JvmField var thrown: ExpectedException = ExpectedException.none()

  @Test
  fun getDependencies_SimulateConcurrencyDependencyAccess() {
    // Modify the dependencies while to iterating a retrieved set of dependencies. Since the ArtifactDependencyManager
    // is thread-safe this shouldn't cause a problem.

    val manager = ArtifactDependencyManager()
    manager.addDependency(Dependency(ARTIFACT_A_100, ARTIFACT_B_100.getArtifact(), ARTIFACT_B_100.version))
    manager.addDependency(Dependency(ARTIFACT_A_100, ARTIFACT_B_200.getArtifact(), ARTIFACT_B_200.version))

    val iterator = manager.getDependencies(ARTIFACT_B_100.getArtifact()).iterator()
    iterator.next()
    // Add a dependency and iterate again to cause a concurrency issue if the returned collection is connected to the
    // original set of dependencies in a thread-unsafe way.
    manager.addDependency(Dependency(ARTIFACT_A_100, ARTIFACT_B_300.getArtifact(), "9.9.9"))
    iterator.next()
  }
}


package org.purescript.psi

import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameIdentifierOwner

class PSForeignValueDeclaration(node: ASTNode) : PSPsiElement(node),
    PsiNameIdentifierOwner {
    override fun setName(name: String): PsiElement? {
        return null
    }

    override fun getNameIdentifier(): PSIdentifierImpl? {
        return findChildByClass(PSIdentifierImpl::class.java)
    }

    override fun getName(): String? {
        return nameIdentifier?.name
    }
}

Implement documentation for foreign values

package org.purescript.psi

import com.intellij.lang.ASTNode
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.elementType
import org.purescript.features.DocCommentOwner
import org.purescript.parser.PSTokens

class PSForeignValueDeclaration(node: ASTNode) :
    PSPsiElement(node),
    PsiNameIdentifierOwner,
    DocCommentOwner
{
    override fun setName(name: String): PsiElement? {
        return null
    }

    override fun getNameIdentifier(): PSIdentifierImpl? {
        return findChildByClass(PSIdentifierImpl::class.java)
    }

    override fun getName(): String? {
        return nameIdentifier?.name
    }

    override val docComments: List<PsiComment>
        get() =
            generateSequence(prevSibling) { it.prevSibling }
                .dropWhile { it !is PsiComment && it !is DocCommentOwner }
                .takeWhile { it is PsiComment || it is PsiWhiteSpace }
                .filter { it.elementType == PSTokens.DOC_COMMENT}
                .filterIsInstance(PsiComment::class.java)
                .toList()
                .reversed()
}


Add coverage for using mixed kotlin versions in a build down to 1.2.20

/*
 * Copyright 2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gradle.kotlin.dsl.plugins.dsl

import org.gradle.kotlin.dsl.embeddedKotlinVersion
import org.gradle.kotlin.dsl.fixtures.AbstractPluginTest

import org.hamcrest.CoreMatchers.allOf
import org.hamcrest.CoreMatchers.containsString
import org.junit.Assert.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized

@RunWith(Parameterized::class)
class KotlinDslPluginGradlePluginCrossVersionSmokeTest(

    private
    val kotlinVersion: String

) : AbstractPluginTest() {

    companion object {

        @Parameterized.Parameters(name = "{0}")
        @JvmStatic
        fun testedKotlinVersions() = listOf(
            embeddedKotlinVersion,
            "1.2.20"
        )
    }

    @Test
    fun `kotlin-dsl plugin in buildSrc and production code using kotlin-gradle-plugin `() {

        withDefaultSettingsIn("buildSrc")
        withBuildScriptIn("buildSrc", """
            import org.jetbrains.kotlin.config.KotlinCompilerVersion

            plugins {
                `kotlin-dsl`
            }

            repositories {
                jcenter()
            }

            dependencies {
                implementation(kotlin("gradle-plugin", "$kotlinVersion"))
            }

            println("buildSrc build script classpath kotlin compiler version " + KotlinCompilerVersion.VERSION)
        """)
        withFile("buildSrc/src/main/kotlin/my-plugin.gradle.kts", """
            apply<org.jetbrains.kotlin.gradle.plugin.KotlinPlatformJvmPlugin>()
        """)

        withDefaultSettings()
        withBuildScript("""
            import org.jetbrains.kotlin.config.KotlinCompilerVersion

            plugins {
                `my-plugin`
            }

            repositories {
                jcenter()
            }

            dependencies {
                implementation(kotlin("stdlib"))
            }

            println("root build script classpath kotlin compiler version " + KotlinCompilerVersion.VERSION)
        """)
        withFile("src/main/kotlin/SomeSource.kt", "fun main(args: Array<String>) {}")

        buildWithPlugin("classes").apply {
            assertThat(
                output,
                allOf(
                    containsString("buildSrc build script classpath kotlin compiler version $embeddedKotlinVersion"),
                    containsString("root build script classpath kotlin compiler version $kotlinVersion")
                )
            )
        }
    }
}


package chat.willow.kale.irc.message.rfc1459.rpl

import chat.willow.kale.ICommand

typealias Rpl474MessageType = RplSourceTargetContent.Message

object Rpl474Message : ICommand {

    override val command = "474"

    object Parser : RplSourceTargetChannelContent.Parser(command)
    object Serialiser : RplSourceTargetChannelContent.Serialiser(command)

}

Add missing 474 type declaration

package chat.willow.kale.irc.message.rfc1459.rpl

import chat.willow.kale.ICommand

typealias Rpl474MessageType = RplSourceTargetChannelContent.Message

object Rpl474Message : ICommand {

    override val command = "474"

    object Parser : RplSourceTargetChannelContent.Parser(command)
    object Serialiser : RplSourceTargetChannelContent.Serialiser(command)

}


/*
 * Copyright 2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package gradlebuild

import gradlebuild.cleanup.extension.CleanupExtension
import gradlebuild.cleanup.services.DaemonTracker
import gradlebuild.cleanup.tasks.KillLeakingJavaProcesses

plugins {
    base
}

val trackerService = gradle.sharedServices.registerIfAbsent("daemonTracker", DaemonTracker::class) {
    parameters.gradleHomeDir.fileValue(gradle.gradleHomeDir)
    parameters.rootProjectDir.set(rootProject.layout.projectDirectory)
}
rootProject.extensions.create<CleanupExtension>("cleanup", trackerService)

val killExistingProcessesStartedByGradle by rootProject.tasks.registering(KillLeakingJavaProcesses::class) {
    tracker.set(trackerService)
}

rootProject.tasks.named("clean") {
    dependsOn(killExistingProcessesStartedByGradle)
}

Remove explicit rootProject references in root cleanup plugin

/*
 * Copyright 2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package gradlebuild

import gradlebuild.cleanup.extension.CleanupExtension
import gradlebuild.cleanup.services.DaemonTracker
import gradlebuild.cleanup.tasks.KillLeakingJavaProcesses

plugins {
    base
}

val trackerService = gradle.sharedServices.registerIfAbsent("daemonTracker", DaemonTracker::class) {
    parameters.gradleHomeDir.fileValue(gradle.gradleHomeDir)
    parameters.rootProjectDir.set(layout.projectDirectory)
}
extensions.create<CleanupExtension>("cleanup", trackerService)

val killExistingProcessesStartedByGradle by tasks.registering(KillLeakingJavaProcesses::class) {
    tracker.set(trackerService)
}

tasks.named("clean") {
    dependsOn(killExistingProcessesStartedByGradle)
}


package com.github.shiraji.databindinglayout.intentions

import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.lang.xml.XMLLanguage
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import com.intellij.psi.XmlElementFactory

class ConvertToDatabindingLayoutIntention : IntentionAction {

    val whiteList = listOf("manifest", "project", "component", "module")

    override fun getText() = "Convert to databinding layout"
    override fun getFamilyName() = "Convert to databinding layout"
    override fun startInWriteAction() = true

    override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean {
        val rootTag = file.getRootTag() ?: return false
        if (rootTag.isDatabindingRootTag()) return false
        return !whiteList.contains(rootTag.name)
    }

    override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
        val rootTag = file.getRootTag() ?: return
        val xmlnsAttribute = rootTag.attributes
                .filter { it.name.startsWith("xmlns:") }
        val attributeText = xmlnsAttribute
                .map { it.text }
                .joinToString(separator = " ")
        val factory = XmlElementFactory.getInstance(project)

        xmlnsAttribute.forEach { it.delete() }
        val layoutXmlTag = factory.createTagFromText("<layout $attributeText>${rootTag.text}</layout>", XMLLanguage.INSTANCE)
        rootTag.replace(layoutXmlTag)
    }
}

Rename constants and add more black list root tag

package com.github.shiraji.databindinglayout.intentions

import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.lang.xml.XMLLanguage
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import com.intellij.psi.XmlElementFactory

class ConvertToDatabindingLayoutIntention : IntentionAction {

    companion object {
        val BLACK_LIST = listOf("manifest", "project", "component", "module", "selector", "menu", "resources", "alpha")
    }

    override fun getText() = "Convert to databinding layout"
    override fun getFamilyName() = "Convert to databinding layout"
    override fun startInWriteAction() = true

    override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean {
        val rootTag = file.getRootTag() ?: return false
        if (rootTag.isDatabindingRootTag()) return false
        return !BLACK_LIST.contains(rootTag.name)
    }

    override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
        val rootTag = file.getRootTag() ?: return
        val xmlnsAttribute = rootTag.attributes
                .filter { it.name.startsWith("xmlns:") }
        val attributeText = xmlnsAttribute
                .map { it.text }
                .joinToString(separator = " ")
        val factory = XmlElementFactory.getInstance(project)

        xmlnsAttribute.forEach { it.delete() }
        val layoutXmlTag = factory.createTagFromText("<layout $attributeText>${rootTag.text}</layout>", XMLLanguage.INSTANCE)
        rootTag.replace(layoutXmlTag)
    }
}


Create an XDebugProcessStarter implementation for MarkLogic error logs.

/*
 * Copyright (C) 2017 Reece H. Dunn
 *
 * 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 uk.co.reecedunn.intellij.plugin.marklogic.debugger.stack.view

import com.intellij.lang.Language
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFileFactory
import com.intellij.util.LocalTimeCounter
import com.intellij.xdebugger.XDebugProcess
import com.intellij.xdebugger.XDebugProcessStarter
import com.intellij.xdebugger.XDebugSession
import com.intellij.xdebugger.XSourcePosition
import com.intellij.xdebugger.evaluation.EvaluationMode
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider
import com.intellij.xdebugger.frame.XExecutionStack

private class MarkLogicDebugEditorsProvider(private var mimeType: String): XDebuggerEditorsProvider() {
    override fun createDocument(project: Project, text: String, sourcePosition: XSourcePosition?, mode: EvaluationMode): Document {
        val type = fileType
        val psiFile = PsiFileFactory.getInstance(project).createFileFromText(
            "debug." + type.getDefaultExtension(),
            type,
            text,
            LocalTimeCounter.currentTime(),
            true)
        return PsiDocumentManager.getInstance(project).getDocument(psiFile)!!
    }

    override fun getFileType(): FileType {
        val lang = Language.findInstancesByMimeType(mimeType).first()
        return lang.associatedFileType as FileType
    }
}

private class MarkLogicErrorProcess(session: XDebugSession): XDebugProcess(session) {
    override fun getEditorsProvider(): XDebuggerEditorsProvider {
        return MarkLogicDebugEditorsProvider("application/xquery")
    }
}

class MarkLogicErrorProcessStarter(val error: XExecutionStack): XDebugProcessStarter() {
    override fun start(session: XDebugSession): XDebugProcess {
        return MarkLogicErrorProcess(session)
    }
}


package engineer.carrot.warren.warren.state

data class IrcState(val connection: ConnectionState, val parsing: ParsingState, val channels: ChannelsState)

data class ChannelsState(val joined: MutableMap<String, ChannelState>)

data class ChannelState(val name: String, val users: MutableSet<String>)

data class ConnectionState(val server: String, val port: Int, val nickname: String, val username: String)

data class ParsingState(val userPrefixes: UserPrefixesState, val channelModes: ChannelModesState, val channelTypes: ChannelTypesState)

data class UserPrefixesState(var prefixesToModes: Map<Char, Char>)

data class ChannelModesState(var typeA: Set<Char>, var typeB: Set<Char>, var typeC: Set<Char>, var typeD: Set<Char>)

data class ChannelTypesState(var types: Set<Char>)

Add connection lifecycle, channel topic to state

package engineer.carrot.warren.warren.state

data class IrcState(val connection: ConnectionState, val parsing: ParsingState, val channels: ChannelsState)

data class ChannelsState(val joined: MutableMap<String, ChannelState>)

data class ChannelState(val name: String, val users: MutableSet<String>, var topic: String? = null)

data class ConnectionState(val server: String, val port: Int, var nickname: String, val username: String, var lifecycle: LifecycleState)

enum class LifecycleState { CONNECTING, CONNECTED, DISCONNECTED }

data class ParsingState(val userPrefixes: UserPrefixesState, val channelModes: ChannelModesState, val channelTypes: ChannelTypesState)

data class UserPrefixesState(var prefixesToModes: Map<Char, Char>)

data class ChannelModesState(var typeA: Set<Char>, var typeB: Set<Char>, var typeC: Set<Char>, var typeD: Set<Char>)

data class ChannelTypesState(var types: Set<Char>)


package org.http4k.filter

import org.http4k.core.Filter
import org.http4k.core.Request
import org.http4k.core.Response
import java.time.Clock
import java.time.Duration
import java.time.Duration.between

object ResponseFilters {

    /**
     * Intercept the response after it is sent to the next service.
     */
    fun Tap(fn: (Response) -> Unit) = Filter {
        next ->
        {
            next(it).let {
                fn(it)
                it
            }
        }
    }

    fun ReportLatency(clock: Clock, recordFn: (Request, Response, Duration) -> Unit): Filter = Filter {
        next ->
        {
            val start = clock.instant()
            val response = next(it)

            recordFn(it, response, between(start, clock.instant()))
            response
        }
    }
}

Add default system clock to ReportLatency

package org.http4k.filter

import org.http4k.core.Filter
import org.http4k.core.Request
import org.http4k.core.Response
import java.time.Clock
import java.time.Duration
import java.time.Duration.between

object ResponseFilters {

    /**
     * Intercept the response after it is sent to the next service.
     */
    fun Tap(fn: (Response) -> Unit) = Filter {
        next ->
        {
            next(it).let {
                fn(it)
                it
            }
        }
    }

    fun ReportLatency(clock: Clock = Clock.systemUTC(), recordFn: (Request, Response, Duration) -> Unit): Filter = Filter {
        next ->
        {
            val start = clock.instant()
            val response = next(it)

            recordFn(it, response, between(start, clock.instant()))
            response
        }
    }
}


/*
 * 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.ui.tooling.preview

import android.content.Context
import android.graphics.Typeface
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.annotation.RestrictTo
import androidx.ui.text.font.Font

/**
 * Layoutlib implementation for [Font.ResourceLoader]
 *
 * @hide
 */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
internal class LayoutlibFontResourceLoader(private val context: Context) : Font.ResourceLoader {
    @RequiresApi(Build.VERSION_CODES.O)
    override fun load(font: Font): Typeface {
        val resId = context.resources.getIdentifier(
            font.name.substringBefore("."),
            "font",
            context.packageName
        )

        return context.resources.getFont(resId)
    }
}

Remove RestrictTo from LayoutLib FontLoader

/*
 * 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.ui.tooling.preview

import android.content.Context
import android.graphics.Typeface
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.ui.text.font.Font

/**
 * Layoutlib implementation for [Font.ResourceLoader]
 */
internal class LayoutlibFontResourceLoader(private val context: Context) : Font.ResourceLoader {
    @RequiresApi(Build.VERSION_CODES.O)
    override fun load(font: Font): Typeface {
        val resId = context.resources.getIdentifier(
            font.name.substringBefore("."),
            "font",
            context.packageName
        )

        return context.resources.getFont(resId)
    }
}


package com.livefront.bridgesample.base

import android.os.Bundle
import android.support.v4.app.Fragment
import com.livefront.bridge.Bridge

abstract class BridgeBaseFragment : Fragment() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Bridge.restoreInstanceState(this, savedInstanceState)
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        Bridge.saveInstanceState(this, outState)
    }

    override fun onDestroy() {
        super.onDestroy()
        Bridge.clear(this)
    }
}

Add ability to disable Bridge clearing in onDestroy

package com.livefront.bridgesample.base

import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentStatePagerAdapter
import com.livefront.bridge.Bridge

abstract class BridgeBaseFragment : Fragment() {
    /**
     * Determines whether or not [Bridge.clear] will be called in [onDestroy]. This is enabled by
     * default but may be disabled in scenarios where Fragments are "recycled" (such as when using
     * a [FragmentStatePagerAdapter].
     */
    open val shouldClearOnDestroy: Boolean = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Bridge.restoreInstanceState(this, savedInstanceState)
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        Bridge.saveInstanceState(this, outState)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (shouldClearOnDestroy) Bridge.clear(this)
    }
}


package com.projectcitybuild.spigot.modules.ranks

import com.projectcitybuild.entities.models.Group

object RankMapper {

    fun mapGroupsToPermissionGroups(groups: List<Group>): List<String> {
        val permissionGroups = mutableSetOf<String>()

        // TODO: [@andy] use Config file instead of hardcoding these
        groups.forEach { group ->
            when (group.name) {
                "member" -> permissionGroups.add("Member")
                "donator" -> permissionGroups.add("Donator")
                "trusted" -> permissionGroups.add("Trusted")
                "trusted plus" -> permissionGroups.add("Trusted+")
                "moderator" -> permissionGroups.add("Moderator")
                "operator" -> permissionGroups.add("OP")
                "senior operator" -> permissionGroups.add("SOP")
                "administrator" -> permissionGroups.add("Admin")
            }
        }

        // User cannot be a Member if they're in any other group
        if (permissionGroups.contains("Member") && permissionGroups.size > 1) {
            permissionGroups.remove("Member")
        }

        return permissionGroups.toList()
    }

}

Change permission nodes to lowercase

package com.projectcitybuild.spigot.modules.ranks

import com.projectcitybuild.entities.models.Group

object RankMapper {

    fun mapGroupsToPermissionGroups(groups: List<Group>): List<String> {
        val permissionGroups = mutableSetOf<String>()

        // TODO: [@andy] use Config file instead of hardcoding these
        groups.forEach { group ->
            when (group.name) {
                "member" -> permissionGroups.add("member")
                "donator" -> permissionGroups.add("donator")
                "trusted" -> permissionGroups.add("trusted")
                "trusted plus" -> permissionGroups.add("trusted+")
                "moderator" -> permissionGroups.add("moderator")
                "operator" -> permissionGroups.add("op")
                "senior operator" -> permissionGroups.add("sop")
                "administrator" -> permissionGroups.add("admin")
            }
        }

        // User cannot be a Member if they're in any other group
        if (permissionGroups.contains("Member") && permissionGroups.size > 1) {
            permissionGroups.remove("Member")
        }

        return permissionGroups.toList()
    }

}


Add a promotion manager to handle promotion.

package org.nwapw.abacus.number

import org.nwapw.abacus.Abacus
import org.nwapw.abacus.plugin.NumberImplementation
import java.util.function.Function

class PromotionManager(val abacus: Abacus) {

    val computePaths = mutableMapOf<Pair<NumberImplementation, NumberImplementation>, PromotionPath?>()

    fun computePathBetween(from: NumberImplementation, to: NumberImplementation): PromotionPath? {
        val fromName = abacus.pluginManager.interfaceImplementationNameFor(from.implementation)
        val toName = abacus.pluginManager.interfaceImplementationNameFor(to.implementation)

        if(fromName == toName) return listOf(Function { it })

        if(from.promotionPaths.containsKey(toName))
            return listOf(from.promotionPaths[toName] ?: return null)
        return null
    }

    fun getPathBetween(from: NumberImplementation, to: NumberImplementation): PromotionPath? {
        return computePaths.computeIfAbsent(from to to, {
             computePathBetween(it.first, it.second)
        })
    }

    fun promote(vararg numbers: NumberInterface): Array<NumberInterface>? {
        val pluginManager = abacus.pluginManager
        val implementations = numbers.map { pluginManager.interfaceImplementationFor(it.javaClass) }
        val highestPriority = implementations.sortedBy { it.priority }.last()
        return numbers.map {
            if(it.javaClass == highestPriority.implementation) it
            else getPathBetween(pluginManager.interfaceImplementationFor(it.javaClass), highestPriority)
                    ?.promote(it) ?: return null
        }.toTypedArray()
    }

}


/*
 * Copyright 2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package common

enum class JvmCategory(
    override val vendor: JvmVendor,
    override val version: JvmVersion
) : Jvm {
    MIN_VERSION(JvmVendor.oracle, JvmVersion.java8),
    MAX_VERSION(JvmVendor.oracle, JvmVersion.java17),
    SANTA_TRACKER_SMOKE_TEST_VERSION(JvmVendor.openjdk, JvmVersion.java11),
    EXPERIMENTAL_VERSION(JvmVendor.oracle, JvmVersion.java18)
}

Change JDK vendor to adoptium

/*
 * Copyright 2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package common

enum class JvmCategory(
    override val vendor: JvmVendor,
    override val version: JvmVersion
) : Jvm {
    MIN_VERSION(JvmVendor.oracle, JvmVersion.java8),
    MAX_VERSION(JvmVendor.adoptiumopenjdk, JvmVersion.java17),
    SANTA_TRACKER_SMOKE_TEST_VERSION(JvmVendor.adoptiumopenjdk, JvmVersion.java11),
    EXPERIMENTAL_VERSION(JvmVendor.adoptiumopenjdk, JvmVersion.java18)
}


/*
 * Use of this source code is governed by the MIT license that can be
 * found in the LICENSE file.
 */

package org.rust.cargo.runconfig

import com.intellij.execution.ExecutionException
import com.intellij.execution.ExecutionManager
import com.intellij.execution.configurations.RunProfileState
import com.intellij.execution.configurations.RunnerSettings
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.runners.ProgramRunner
import com.intellij.execution.runners.executeState
import com.intellij.execution.ui.RunContentDescriptor
import java.util.function.Function

abstract class RsDefaultProgramRunnerBase : ProgramRunner<RunnerSettings> {

    @Throws(ExecutionException::class)
    final override fun execute(environment: ExecutionEnvironment) {
        val state = environment.state ?: return
        execute(environment, environment.callback, state)
    }

    protected open fun doExecute(state: RunProfileState, environment: ExecutionEnvironment): RunContentDescriptor? {
        return executeState(state, environment, this)
    }

    // BACKCOMPAT: 2019.3. merge it into [execute] method
    @Throws(ExecutionException::class)
    protected open fun execute(
        environment: ExecutionEnvironment,
        callback: ProgramRunner.Callback?,
        state: RunProfileState
    ) {
        @Suppress("UnstableApiUsage")
        ExecutionManager.getInstance(environment.project).startRunProfile(environment, Function {
            doExecute(it, environment)
        })
    }
}

Fix code coverage runner on 2020.1

/*
 * Use of this source code is governed by the MIT license that can be
 * found in the LICENSE file.
 */

package org.rust.cargo.runconfig

import com.intellij.execution.ExecutionException
import com.intellij.execution.ExecutionManager
import com.intellij.execution.configurations.RunProfileState
import com.intellij.execution.configurations.RunnerSettings
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.runners.ProgramRunner
import com.intellij.execution.runners.executeState
import com.intellij.execution.ui.RunContentDescriptor
import org.jetbrains.concurrency.resolvedPromise

abstract class RsDefaultProgramRunnerBase : ProgramRunner<RunnerSettings> {

    @Throws(ExecutionException::class)
    final override fun execute(environment: ExecutionEnvironment) {
        val state = environment.state ?: return
        execute(environment, environment.callback, state)
    }

    protected open fun doExecute(state: RunProfileState, environment: ExecutionEnvironment): RunContentDescriptor? {
        return executeState(state, environment, this)
    }

    // BACKCOMPAT: 2019.3. merge it into [execute] method
    @Throws(ExecutionException::class)
    protected open fun execute(
        environment: ExecutionEnvironment,
        callback: ProgramRunner.Callback?,
        state: RunProfileState
    ) {
        @Suppress("UnstableApiUsage")
        ExecutionManager.getInstance(environment.project).startRunProfile(environment) {
            resolvedPromise(doExecute(state, environment))
        }
    }
}


package com.tristanwiley.chatse.extensions

import android.widget.ImageView
import com.koushikdutta.ion.Ion

fun ImageView.loadUrl(url: String) {
    Ion.with(context).load(url).intoImageView(this)
}

Use Glide to load images instead Ion

package com.tristanwiley.chatse.extensions

import android.widget.ImageView
import com.bumptech.glide.Glide

fun ImageView.loadUrl(url: String) {
    Glide.with(this).load(url).into(this)
}


Implement a graph algorithms that finds reachable vertices

/*
 * Copyright 2016 Michael Rozumyanskiy
 *
 * 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 io.michaelrocks.lightsaber.processor.graph

fun <T> DirectedGraph<T>.findReachableVertices(fromVertex: T): Set<T> {
  val traversal = DepthFirstTraversal<T>()
  val delegate = AbstractMarkingTraversal.SimpleDelegate<T>()
  traversal.traverse(this, delegate, fromVertex)
  return delegate.getVisitedVertices()
}


Add showInScope extension functions for Dialog

/*
 * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
 */

package com.louiscad.splittiessample.extensions.dialog

import android.app.Dialog
import com.louiscad.splittiessample.extensions.coroutines.raceOf
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.selects.select
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

suspend fun <R> Dialog.showInScope(
    dismissValue: R,
    block: suspend () -> R
): R = try {
    raceOf({
        suspendCancellableCoroutine<R> { c ->
            setOnDismissListener { c.resume(dismissValue) }
            show()
        }
    }, {
        block()
    })
} finally {
    dismiss()
}

suspend fun <R> Dialog.showInScope(
    onDismiss: suspend () -> R,
    block: suspend () -> R
): R = try {
    coroutineScope {
        @UseExperimental(ExperimentalCoroutinesApi::class)
        val dismissJob = launch(start = CoroutineStart.UNDISPATCHED) {
            suspendCancellableCoroutine<Unit> { c ->
                setOnDismissListener { c.resume(Unit) }
                show()
            }
        }
        @UseExperimental(ExperimentalCoroutinesApi::class)
        val blockAsync = async(start = CoroutineStart.UNDISPATCHED) {
            block()
        }
        select<R> {
            blockAsync.onAwait { result ->
                dismissJob.cancel()
                result
            }
            dismissJob.onJoin {
                blockAsync.cancel()
                onDismiss()
            }
        }
    }
} finally {
    dismiss()
}

suspend fun Dialog.showInScope(
    block: suspend () -> Unit
): Unit = try {
    raceOf({
        suspendCancellableCoroutine<Unit> { c ->
            setOnDismissListener { c.resume(Unit) }
            show()
        }
    }, {
        block()
    })
} finally {
    dismiss()
}


/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, you can obtain one at http://mozilla.org/MPL/2.0/.
 * ------------------------------------------------------------------*/

package com.kotlinnlp.simplednn.core.layers.models.merge.distance

import com.kotlinnlp.simplednn.core.layers.LayerParameters
import com.kotlinnlp.simplednn.core.layers.helpers.ForwardHelper
import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
import java.lang.Math.abs
import kotlin.math.exp

/**
 * The helper which executes the forward on a [DistanceLayer].
 *
 * @property layer the layer in which the forward is executed
 */
class DistanceForwardHelper <InputNDArrayType : NDArray<InputNDArrayType>>(
    override val layer: DistanceLayer<InputNDArrayType>
) : ForwardHelper<InputNDArrayType>(layer){

  /**
   * Forward the input to the output calculating a score value d ∈ [0, 1]. d = exp(-||input1-input2||1)
   */
  override fun forward() {

    val diffVector : DenseNDArray = DenseNDArrayFactory.fromNDArray(this.layer.inputArray1.values)
    var sum = 0.0
    val outputScore = DoubleArray(1)

    diffVector.assignSub(this.layer.inputArray2.values)

    diffVector.toDoubleArray().forEach { element -> sum += abs(element) }
    outputScore[0] = exp(-sum)
    this.layer.outputArray.assignValues(DenseNDArrayFactory.arrayOf(outputScore))

  }

  /**
   * Forward the input to the output saving the contributions.
   * Not available for the Sum layer.
   *
   * @param layerContributions the structure in which to save the contributions during the calculations
   */
  override fun forward(layerContributions: LayerParameters<*>) {
    throw NotImplementedError("Forward with contributions not available for the Sum layer.")
  }
}


/*
 * Copyright 2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package gradlebuild

plugins {
    id("me.champeau.gradle.jmh")
}

configurations {
    jmhImplementation {
        extendsFrom(configurations.implementation.get())
    }
}

jmh {
    isIncludeTests = false
    resultFormat = "CSV"
}

Fix jmh in presence of composite build

/*
 * Copyright 2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package gradlebuild

plugins {
    id("me.champeau.gradle.jmh")
}

configurations {
    jmhImplementation {
        extendsFrom(configurations.implementation.get())
    }
    jmhRuntime {
        attributes {
            attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, objects.named(LibraryElements.JAR))
        }
    }
}

jmh {
    isIncludeTests = false
    resultFormat = "CSV"
}


/*
 * Use of this source code is governed by the MIT license that can be
 * found in the LICENSE file.
 */

package org.rust.cargo.runconfig.command

import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.execution.configurations.ConfigurationTypeBase
import com.intellij.execution.configurations.ConfigurationTypeUtil
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.openapi.project.Project
import com.intellij.util.PlatformUtils
import org.rust.ide.icons.RsIcons

class CargoCommandConfigurationType : ConfigurationTypeBase(
    "CargoCommandRunConfiguration",
    "Cargo Command",
    "Cargo command run configuration",
    RsIcons.RUST
) {
    init {
        addFactory(CargoConfigurationFactory(this))
    }

    val factory: ConfigurationFactory get() = configurationFactories.single()

    override fun getHelpTopic(): String? =
        // Only IDEA and CLion have special page about IntelliJ Rust in their help
        if (PlatformUtils.isIntelliJ() || PlatformUtils.isCLion()) "rundebugconfigs.cargocommand" else null

    companion object {
        fun getInstance(): CargoCommandConfigurationType =
            ConfigurationTypeUtil.findConfigurationType(CargoCommandConfigurationType::class.java)
    }
}

class CargoConfigurationFactory(type: CargoCommandConfigurationType) : ConfigurationFactory(type) {

    override fun getId(): String = ID

    override fun createTemplateConfiguration(project: Project): RunConfiguration {
        return CargoCommandConfiguration(project, "Cargo", this)
    }

    companion object {
        const val ID: String = "Cargo Command"
    }
}

Rename "Cargo Command" run configuration to "Cargo"

/*
 * Use of this source code is governed by the MIT license that can be
 * found in the LICENSE file.
 */

package org.rust.cargo.runconfig.command

import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.execution.configurations.ConfigurationTypeBase
import com.intellij.execution.configurations.ConfigurationTypeUtil
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.openapi.project.Project
import com.intellij.util.PlatformUtils
import org.rust.ide.icons.RsIcons

class CargoCommandConfigurationType : ConfigurationTypeBase(
    "CargoCommandRunConfiguration",
    "Cargo",
    "Cargo command run configuration",
    RsIcons.RUST
) {
    init {
        addFactory(CargoConfigurationFactory(this))
    }

    val factory: ConfigurationFactory get() = configurationFactories.single()

    override fun getHelpTopic(): String? =
        // Only IDEA and CLion have special page about IntelliJ Rust in their help
        if (PlatformUtils.isIntelliJ() || PlatformUtils.isCLion()) "rundebugconfigs.cargocommand" else null

    companion object {
        fun getInstance(): CargoCommandConfigurationType =
            ConfigurationTypeUtil.findConfigurationType(CargoCommandConfigurationType::class.java)
    }
}

class CargoConfigurationFactory(type: CargoCommandConfigurationType) : ConfigurationFactory(type) {

    override fun getId(): String = ID

    override fun createTemplateConfiguration(project: Project): RunConfiguration {
        return CargoCommandConfiguration(project, "Cargo", this)
    }

    companion object {
        const val ID: String = "Cargo Command"
    }
}


package rx.javafx.kt

import javafx.event.EventType
import javafx.scene.control.TableView
import javafx.scene.input.MouseEvent
import rx.observables.JavaFxObservable

//TableView Extensions
fun <S> TableView<S>.mouseEvents(mouseEventType: EventType<MouseEvent>) =
        JavaFxObservable.fromNodeEvents(this,mouseEventType)

fun <S> TableView<S>.mouseClicks() =
        JavaFxObservable.fromNodeEvents(this,MouseEvent.MOUSE_CLICKED)

Add mouseEvent streams to Node

package rx.javafx.kt

import javafx.event.EventType
import javafx.scene.Node
import javafx.scene.input.MouseEvent
import rx.observables.JavaFxObservable

fun <N: Node> N.mouseEvents(mouseEventType: EventType<MouseEvent>) =
        JavaFxObservable.fromNodeEvents(this,mouseEventType)

fun <N: Node> N.mouseClicks() =
        JavaFxObservable.fromNodeEvents(this,MouseEvent.MOUSE_CLICKED)


Add an AccountStore implementation that can be leveraged to use a fixed access token for all requests

package com.vimeo.networking2.account

import com.vimeo.networking2.VimeoAccount

/**
 * An [AccountStore] that always uses the same access token to access the API. By using this store and providing a fixed
 * token, you will not be able to log into a different account and will only be able to utilize the account associated
 * with this token. If you wish to support logging into a different account, utilize the default [InMemoryAccountStore]
 * or implement your own disk backed [AccountStore].
 *
 * @param accessToken The access token that will be used by the SDK.
 */
class FixedAccessTokenAccountStore(accessToken: String) : AccountStore {
    private val vimeoAccount = VimeoAccount(accessToken = accessToken)

    override fun loadAccount(): VimeoAccount = vimeoAccount

    override fun storeAccount(vimeoAccount: VimeoAccount) = Unit

    override fun removeAccount() = Unit
}


package org.klips.dsl

interface Asserter {

    val asserted: List<Fact>
    val retired: List<Fact>

    fun assert(vararg facts: Fact): Array<out Fact>
    fun retire(vararg facts: Fact): Array<out Fact>

    operator fun Fact.unaryPlus():Fact {
        assert(this)
        return this
    }

    operator fun Fact.unaryMinus():Fact {
        retire(this)
        return this
    }
}

Make unary plus/minus generic functions.

package org.klips.dsl

interface Asserter {

    val asserted: List<Fact>
    val retired: List<Fact>

    fun assert(vararg facts: Fact): Array<out Fact>
    fun retire(vararg facts: Fact): Array<out Fact>

    operator fun <T : Fact> T.unaryPlus() : T {
        assert(this)
        return this
    }

    operator fun <T : Fact> T.unaryMinus() : T {
        retire(this)
        return this
    }
}


buildscript {

    var kotlinVersion: String by extra
    var kotlinEAPRepo: String by extra

    kotlinVersion = "1.1.2-eap-44"
    kotlinEAPRepo = "https://dl.bintray.com/kotlin/kotlin-eap-1.1"

    repositories {
        gradleScriptKotlin()
    }
}

plugins {
    id("org.jetbrains.kotlin.jvm") version "1.1.1"
}

val kotlinVersion: String by extra
val kotlinEAPRepo: String by extra

repositories {
    gradleScriptKotlin()
    maven { setUrl(kotlinEAPRepo) }
}

dependencies {
    // compile(gradleScriptKotlinApi())
    compile(kotlinModule("stdlib-jre8", kotlinVersion))
}

Fix buildSrc kotlin compilation issue.

import org.gradle.api.tasks.Delete
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

buildscript {

    var kotlinVersion: String by extra
    var kotlinEAPRepo: String by extra

    kotlinVersion = "1.1.2-eap-44"
    kotlinEAPRepo = "https://dl.bintray.com/kotlin/kotlin-eap-1.1"

    repositories {
        gradleScriptKotlin()
    }
}

plugins {
    id("org.jetbrains.kotlin.jvm") version "1.1.1"
}

val kotlinVersion: String by extra
val kotlinEAPRepo: String by extra

/**
 * Cleaning buildSrc before compilation.
 */
afterEvaluate {
    val clean: Delete by tasks
    val compileKotlin: KotlinCompile by tasks
    compileKotlin.dependsOn(clean)
}

repositories {
    gradleScriptKotlin()
    maven { setUrl(kotlinEAPRepo) }
}

dependencies {
    // compile(gradleScriptKotlinApi())
    compile(kotlinModule("stdlib-jre8", kotlinVersion))
}


package com.example.billing.reocurringPayments

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.actuate.metrics.CounterService
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController

@RestController
class Controller {
    @Autowired
    private lateinit var paymentGateway: com.example.payments.Gateway

    @Autowired
    private lateinit var counter: CounterService

    @Autowired
    private lateinit var service: Service

    @RequestMapping(value = "/reocurringPayment", method = arrayOf(RequestMethod.POST))
    fun createReocurringPayment(@RequestBody data: Map<String, Any>): ResponseEntity<String> {
        val responseHeaders = HttpHeaders()
        responseHeaders.add("content-type", MediaType.APPLICATION_JSON.toString())

        service.thisMayFail()

        val response: ResponseEntity<String>
        if (paymentGateway.createReocurringPayment(data["amount"] as Int)) {
            counter.increment("billing.reocurringPayment.created")
            response = ResponseEntity("{\"errors\": []}", responseHeaders, HttpStatus.CREATED)
        } else {
            response = ResponseEntity("{\"errors\": [\"error1\", \"error2\"]}", responseHeaders, HttpStatus.BAD_REQUEST)
        }

        return response
    }
}

Use constructor injection so you can make instance variables vals

package com.example.billing.reocurringPayments

import com.example.payments.Gateway
import org.springframework.boot.actuate.metrics.CounterService
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
import javax.inject.Inject

@RestController
class Controller {
    private val paymentGateway: com.example.payments.Gateway

    private val counter: CounterService

    private val service: Service

    @Inject
    constructor(paymentGateway: Gateway, counterService: CounterService, service: Service) {
        this.paymentGateway = paymentGateway
        this.counter = counterService
        this.service = service
    }

    @RequestMapping(value = "/reocurringPayment", method = arrayOf(RequestMethod.POST))
    fun createReocurringPayment(@RequestBody data: Map<String, Any>): ResponseEntity<String> {
        val responseHeaders = HttpHeaders()
        responseHeaders.add("content-type", MediaType.APPLICATION_JSON.toString())

        service.thisMayFail()

        val response: ResponseEntity<String>
        if (paymentGateway.createReocurringPayment(data["amount"] as Int)) {
            counter.increment("billing.reocurringPayment.created")
            response = ResponseEntity("{\"errors\": []}", responseHeaders, HttpStatus.CREATED)
        } else {
            response = ResponseEntity("{\"errors\": [\"error1\", \"error2\"]}", responseHeaders, HttpStatus.BAD_REQUEST)
        }

        return response
    }
}


package net.perfectdreams.loritta.plugin.rosbife.commands

import net.perfectdreams.loritta.plugin.rosbife.RosbifePlugin
import net.perfectdreams.loritta.plugin.rosbife.commands.base.BasicSkewedImageCommand

class BobBurningPaperCommand(m: RosbifePlugin) : BasicSkewedImageCommand(
		m.loritta,
		listOf("bobburningpaper", "bobpaperfire", "bobfire", "bobpapelfogo", "bobfogo"),
		"commands.images.bobfire.description",
		"bobfire.png",
		Corners(
				21f, 373f,
				14f, 353f,
				48f, 334f,
				82f, 354f
		)
)

Fix BobBurningFireCommand not working at all

package net.perfectdreams.loritta.plugin.rosbife.commands

import net.perfectdreams.loritta.plugin.rosbife.RosbifePlugin
import net.perfectdreams.loritta.plugin.rosbife.commands.base.BasicSkewedImageCommand

class BobBurningPaperCommand(m: RosbifePlugin) : BasicSkewedImageCommand(
		m.loritta,
		listOf("bobburningpaper", "bobpaperfire", "bobfire", "bobpapelfogo", "bobfogo"),
		"commands.images.bobfire.description",
		"bobfire.png",
		listOf(
				Corners(
						21f, 373f,

						14f, 353f,

						48f, 334f,

						82f, 354f
				),
				Corners(
						24f, 32f,

						138f, 33f,

						137f, 177f,

						20f, 175f
				)
		)
)


package Kotlin101.Functions.LocalClass

fun main (Args : Array<String>){
    class AirForce(val name : String)

    val usa = AirForce("USA")
    val india = AirForce("India")

    println("${usa.name} and ${india.name}")
}


package test.text

import kotlin.test.*

class CharNativeTest {

    @Test
    fun lowercaseChar() {
        // large mapping
        assertEquals('\u0239', '\u0239'.lowercaseChar())
        assertEquals('\u2C65', '\u023A'.lowercaseChar())
        assertEquals('\u023C', '\u023B'.lowercaseChar())

        // large negative mapping
        assertEquals('\u2C7D', '\u2C7D'.lowercaseChar())
        assertEquals('\u023F', '\u2C7E'.lowercaseChar())
        assertEquals('\u0240', '\u2C7F'.lowercaseChar())

        // <Lu, Ll>
        assertEquals('\u2C81', '\u2C80'.lowercaseChar())
        assertEquals('\u2C81', '\u2C81'.lowercaseChar())
        assertEquals('\u2C83', '\u2C82'.lowercaseChar())
    }

    @Test
    fun uppercaseChar() {
        // large mapping
        assertEquals('\u029C', '\u029C'.uppercaseChar())
        assertEquals('\uA7B2', '\u029D'.uppercaseChar())
        assertEquals('\uA7B0', '\u029E'.uppercaseChar())
        assertEquals('\u029F', '\u029F'.uppercaseChar())

        // large negative mapping
        assertEquals('\uAB6F', '\uAB6F'.uppercaseChar())
        assertEquals('\u13A0', '\uAB70'.uppercaseChar())
        assertEquals('\u13EF', '\uABBF'.uppercaseChar())
        assertEquals('\uABC0', '\uABC0'.uppercaseChar())
    }

    @Test
    fun titlecaseChar() {
        // titlecaseChar == char && uppercaseChar != char
        assertEquals('\u10CF'.uppercaseChar(), '\u10CF'.titlecaseChar())
        for (char in '\u10D0'..'\u10FA') {
            assertEquals(char, char.titlecaseChar())
            assertNotEquals(char, char.uppercaseChar())
        }
        for (char in '\u10FB'..'\u10FC') {
            assertEquals(char, char.titlecaseChar())
            assertEquals(char, char.uppercaseChar())
        }
        for (char in '\u10FD'..'\u10FF') {
            assertEquals(char, char.titlecaseChar())
            assertNotEquals(char, char.uppercaseChar())
        }
        assertEquals('\u1100'.uppercaseChar(), '\u1100'.titlecaseChar())
    }

    @Test
    fun lowercase() {
        // LATIN CAPITAL LETTER I WITH DOT ABOVE
        assertEquals("\u0069\u0307", '\u0130'.lowercase())
    }

    fun titlecase() {
        // titlecase = titlecaseChar = char != uppercaseChar
        assertEquals('\u10F0'.titlecaseChar().toString(), '\u10F0'.titlecase())
        assertEquals('\u10F0', '\u10F0'.titlecaseChar())
        assertNotEquals('\u10F0', '\u10F0'.uppercaseChar())
    }
}


package jp.itohiro.intellij.simpleplugin

import com.intellij.lexer.Lexer
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.HighlighterColors
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase
import com.intellij.psi.TokenType
import com.intellij.psi.tree.IElementType
import jp.itohiro.intellij.simpleplugin.psi.SimpleTypes

public class SimpleSyntaxHighlighter: SyntaxHighlighterBase() {
    override fun getTokenHighlights(tokenType: IElementType?): Array<out TextAttributesKey> {
        throw UnsupportedOperationException()
    }

    override fun getHighlightingLexer(): Lexer {
        throw UnsupportedOperationException()
    }
    //    companion object {
//        public val SEPARATOR = createTextAttributesKey("SIMPLE_SEPARATOR", DefaultLanguageHighlighterColors.OPERATION_SIGN);
//        public val KEY = createTextAttributesKey("SIMPLE_KEY", DefaultLanguageHighlighterColors.KEYWORD);
//        public val VALUE = createTextAttributesKey("SIMPLE_VALUE", DefaultLanguageHighlighterColors.STRING);
//        public val COMMENT = createTextAttributesKey("SIMPLE_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT);
//        public val BAD_CHARACTER = createTextAttributesKey("SIMPLE_BAD_CHARACTER", HighlighterColors.BAD_CHARACTER);
//
//        private val BAD_CHAR_KEYS = arrayOf(BAD_CHARACTER);
//        private val SEPARATOR_KEYS = arrayOf(SEPARATOR);
//        private val KEY_KEYS = arrayOf(KEY);
//        private val VALUE_KEYS = arrayOf(VALUE);
//        private val COMMENT_KEYS = arrayOf(COMMENT);
//        private val EMPTY_KEYS = Array<TextAttributesKey>()
//    }
//
//    override fun getTokenHighlights(tokenType: IElementType?): Array<out TextAttributesKey> {
//        if (tokenType == SimpleTypes.SEPARATOR) {
//            return SEPARATOR_KEYS;
//        } else if (tokenType == SimpleTypes.KEY) {
//            return KEY_KEYS;
//        } else if (tokenType == SimpleTypes.VALUE) {
//            return VALUE_KEYS;
//        } else if (tokenType == SimpleTypes.COMMENT) {
//            return COMMENT_KEYS;
//        } else if (tokenType == TokenType.BAD_CHARACTER) {
//            return BAD_CHAR_KEYS;
//        } else {
//            return EMPTY_KEYS;
//        }
//    }
//
//    override fun getHighlightingLexer(): Lexer {
//        return SimpleLexerAdapter()
//    }
}


package com.rimmer.yttrium

/*
 * Contains generic error types used within the server.
 * These errors are caught by the router and transformed into http responses.
 */

/** This is mapped to 404 and should be thrown whenever something that was requested doesn't exist. */
class NotFoundException : Exception("not_found")

/** This is mapped to 403 and should be thrown whenever a session has insufficient permissions for an operation. */
class UnauthorizedException : Exception("no_permission")

/** This is mapped to 400 and should be thrown whenever a request tries to do something that's impossible in that context. */
class InvalidStateException(cause: String): Exception(cause)

/** This is mapped to the provided http code and should be thrown for errors that don't fit any other exception. */
class HttpException(val errorCode: Int, cause: String): Exception(cause)

Support custom messages for UnauthorizedException

package com.rimmer.yttrium

/*
 * Contains generic error types used within the server.
 * These errors are caught by the router and transformed into http responses.
 */

/** This is mapped to 404 and should be thrown whenever something that was requested doesn't exist. */
class NotFoundException : Exception("not_found")

/** This is mapped to 403 and should be thrown whenever a session has insufficient permissions for an operation. */
class UnauthorizedException(text: String = "invalid_token") : Exception(text)

/** This is mapped to 400 and should be thrown whenever a request tries to do something that's impossible in that context. */
class InvalidStateException(cause: String): Exception(cause)

/** This is mapped to the provided http code and should be thrown for errors that don't fit any other exception. */
class HttpException(val errorCode: Int, cause: String): Exception(cause)


/*
 * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
 */

package splitties.coroutines

import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.channels.SendChannel

/**
 * [SendChannel.offer] that returns `false` when this [SendChannel.isClosedForSend], instead of
 * throwing.
 *
 * [SendChannel.offer] throws when the channel is closed. In race conditions, especially when using
 * multithreaded dispatchers, that can lead to uncaught exceptions as offer is often called from
 * non suspending functions that don't catch the default [CancellationException] or any other
 * exception that might be the cause of the closing of the channel.
 */
fun <E> SendChannel<E>.offerCatching(element: E): Boolean {
    return runCatching { offer(element) }.getOrDefault(false)
}

Add link to relevant issue

/*
 * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
 */

package splitties.coroutines

import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.channels.SendChannel

/**
 * [SendChannel.offer] that returns `false` when this [SendChannel.isClosedForSend], instead of
 * throwing.
 *
 * [SendChannel.offer] throws when the channel is closed. In race conditions, especially when using
 * multithreaded dispatchers, that can lead to uncaught exceptions as offer is often called from
 * non suspending functions that don't catch the default [CancellationException] or any other
 * exception that might be the cause of the closing of the channel.
 *
 * See this issue: [https://github.com/Kotlin/kotlinx.coroutines/issues/974](https://github.com/Kotlin/kotlinx.coroutines/issues/974)
 */
fun <E> SendChannel<E>.offerCatching(element: E): Boolean {
    return runCatching { offer(element) }.getOrDefault(false)
}


package com.sedsoftware.yaptalker.presentation.features.news

import com.arellomobile.mvp.viewstate.strategy.AddToEndSingleStrategy
import com.arellomobile.mvp.viewstate.strategy.AddToEndStrategy
import com.arellomobile.mvp.viewstate.strategy.SingleStateStrategy
import com.arellomobile.mvp.viewstate.strategy.SkipStrategy
import com.arellomobile.mvp.viewstate.strategy.StateStrategyType
import com.sedsoftware.yaptalker.presentation.base.BaseView
import com.sedsoftware.yaptalker.presentation.model.YapEntity

@StateStrategyType(AddToEndSingleStrategy::class)
interface NewsView : BaseView {

  @StateStrategyType(AddToEndStrategy::class)
  fun appendNewsItem(entity: YapEntity)

  @StateStrategyType(SingleStateStrategy::class)
  fun clearNewsList()

  @StateStrategyType(SkipStrategy::class)
  fun updateCurrentUiState()

  fun showFab()

  fun hideFab()
}

Fix fab visibility funcs strategy

package com.sedsoftware.yaptalker.presentation.features.news

import com.arellomobile.mvp.viewstate.strategy.AddToEndStrategy
import com.arellomobile.mvp.viewstate.strategy.SingleStateStrategy
import com.arellomobile.mvp.viewstate.strategy.SkipStrategy
import com.arellomobile.mvp.viewstate.strategy.StateStrategyType
import com.sedsoftware.yaptalker.presentation.base.BaseView
import com.sedsoftware.yaptalker.presentation.model.YapEntity

@StateStrategyType(SkipStrategy::class)
interface NewsView : BaseView {

  @StateStrategyType(AddToEndStrategy::class)
  fun appendNewsItem(entity: YapEntity)

  @StateStrategyType(SingleStateStrategy::class)
  fun clearNewsList()

  fun updateCurrentUiState()

  fun showFab()

  fun hideFab()
}


package nl.dionsegijn.steppertouchdemo.recyclerview

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.xwray.groupie.GroupieAdapter
import kotlinx.android.synthetic.main.fragment_recycler_view.recyclerView
import nl.dionsegijn.steppertouchdemo.R
import nl.dionsegijn.steppertouchdemo.recyclerview.items.StepperTouchItem
import nl.dionsegijn.steppertouchdemo.recyclerview.items.TextItem

class RecyclerViewFragment : Fragment() {

    private val adapter = GroupieAdapter()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_recycler_view, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        recyclerView.adapter = this.adapter
        recyclerView.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)

        adapter.addAll(listOf(
            TextItem("First item"),
            TextItem("Second item"),
            StepperTouchItem(),
            TextItem("Fourth item"),
            TextItem("Fifth item"),
            StepperTouchItem(),
            TextItem("Seventh item"),
            TextItem("Eight item"),
            TextItem("Ninth item"),
            TextItem("Tenth item"),
            TextItem("Eleven item"),
            TextItem("Twelve item"),
            StepperTouchItem(),
            TextItem("Thirteen item"),
            TextItem("Fourteen item"),
        ))
        adapter.notifyDataSetChanged()
    }
}

Add 100 items to the list

package nl.dionsegijn.steppertouchdemo.recyclerview

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.xwray.groupie.GroupieAdapter
import kotlinx.android.synthetic.main.fragment_recycler_view.recyclerView
import nl.dionsegijn.steppertouch.StepperTouch
import nl.dionsegijn.steppertouchdemo.R
import nl.dionsegijn.steppertouchdemo.recyclerview.items.StepperTouchItem
import nl.dionsegijn.steppertouchdemo.recyclerview.items.TextItem

class RecyclerViewFragment : Fragment() {

    private val adapter = GroupieAdapter()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_recycler_view, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        recyclerView.adapter = this.adapter
        recyclerView.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)

        val list = (1..100).map {
            if (it % 5 == 0) StepperTouchItem() else TextItem("Item #$it")
        }

        adapter.addAll(list)
        adapter.notifyDataSetChanged()
    }
}


package nl.hannahsten.texifyidea.inspections.latex

import nl.hannahsten.texifyidea.file.LatexFileType
import nl.hannahsten.texifyidea.inspections.TexifyInspectionTestBase
import org.junit.Test
import java.nio.file.Path
import java.nio.file.Paths

class LatexAbsolutePathInspectionTest : TexifyInspectionTestBase(LatexAbsolutePathInspection()) {
    var absoluteWorkingPath: String

    init {
        val currentRelativePath: Path = Paths.get("")
        absoluteWorkingPath = currentRelativePath.toAbsolutePath().toString()
    }

    @Test
    fun testNotSupportedAbsolutePath() {
        myFixture.configureByText(LatexFileType, """<error>\include{$absoluteWorkingPath/test/resources/completion/path/testfile.tex}</error>""")
        myFixture.checkHighlighting()
    }
}

Fix absolute path inspection test

package nl.hannahsten.texifyidea.inspections.latex

import nl.hannahsten.texifyidea.file.LatexFileType
import nl.hannahsten.texifyidea.inspections.TexifyInspectionTestBase
import org.junit.Test
import java.nio.file.Path
import java.nio.file.Paths

class LatexAbsolutePathInspectionTest : TexifyInspectionTestBase(LatexAbsolutePathInspection()) {
    var absoluteWorkingPath: String

    init {
        val currentRelativePath: Path = Paths.get("")
        absoluteWorkingPath = currentRelativePath.toAbsolutePath().toString()
    }

    @Test
    fun testNotSupportedAbsolutePath() {
        myFixture.configureByText(LatexFileType, """\include{<error descr="No absolute path allowed here">$absoluteWorkingPath/test/resources/completion/path/testfile.tex</error>}""")
        myFixture.checkHighlighting()
    }

    @Test
    fun testNotSupportedAbsolutePathAsSecondParameter() {
        myFixture.configureByText(LatexFileType, """\import{/absolute/path/to/}{<error descr="No absolute path allowed here">$absoluteWorkingPath/test/resources/completion/path/testfile.tex</error>}""")
        myFixture.checkHighlighting()
    }
}


package pl.mg6.likeornot.commons

fun <T> List<T>.batch(chunkSize: Int): List<List<T>> {
    if (chunkSize <= 0) {
        throw IllegalArgumentException("chunkSize must be greater than 0")
    }
    val list = mutableListOf<MutableList<T>>()
    for (i in 0 until size) {
        if (i % chunkSize == 0) {
            list.add(ArrayList(chunkSize))
        }
        list.last().add(get(i))
    }
    return list
}

Set initial list of lists capacity to expected final size.

package pl.mg6.likeornot.commons

fun <T> List<T>.batch(chunkSize: Int): List<List<T>> {
    if (chunkSize <= 0) {
        throw IllegalArgumentException("chunkSize must be greater than 0")
    }
    val capacity = (size + chunkSize - 1) / chunkSize
    val list = ArrayList<ArrayList<T>>(capacity)
    for (i in 0 until size) {
        if (i % chunkSize == 0) {
            list.add(ArrayList(chunkSize))
        }
        list.last().add(get(i))
    }
    return list
}


package org.kethereum.methodsignatures.model

data class TextMethodSignature(val signature: String) {
    val functionName by lazy { signature.substringBefore("(").trim() }

    val parameters by lazy { signature.substringAfter("(").substringBefore(")").split(",").map { it.trim() } }

    // see https://solidity.readthedocs.io/en/develop/abi-spec.htm
    val normalizedParameters by lazy {
        parameters.map {
            when (it) {
                "uint" -> "uint256"
                "int" -> "int256"
                "fixed" -> "fixed128x18"
                "ufixed" -> "ufixed128x18"
                else -> it
            }
        }
    }

    private val normalizedParametersString by lazy { normalizedParameters.joinToString(",")}

    val normalizedSignature by lazy { "$functionName($normalizedParametersString)" }
}

Add mapping from byte to bytes1

package org.kethereum.methodsignatures.model

data class TextMethodSignature(val signature: String) {
    val functionName by lazy { signature.substringBefore("(").trim() }

    val parameters by lazy { signature.substringAfter("(").substringBefore(")").split(",").map { it.trim() } }

    // see https://solidity.readthedocs.io/en/develop/abi-spec.htm
    val normalizedParameters by lazy {
        parameters.map {
            when (it) {
                "uint" -> "uint256"
                "int" -> "int256"
                "fixed" -> "fixed128x18"
                "ufixed" -> "ufixed128x18"
                "byte" -> "bytes1"
                else -> it
            }
        }
    }

    private val normalizedParametersString by lazy { normalizedParameters.joinToString(",")}

    val normalizedSignature by lazy { "$functionName($normalizedParametersString)" }
}


package com.codegy.aerlink.connection

import java.util.*

data class Command(val serviceUUID: UUID, val characteristicUUID: UUID, val packet: ByteArray? = null) {

    var isWriteCommand: Boolean = packet != null
    private var retryCount = 0
    var importance = IMPORTANCE_NORMAL
    var successBlock: (() -> Unit)? = null
    var failureBlock: (() -> Unit)? = null

    fun completeWithSuccess() {
        successBlock?.invoke()
    }

    fun completeWithFailure() {
        failureBlock?.invoke()
    }

    fun shouldRetryAgain(): Boolean {
        if (retryCount >= importance) {
            return false
        }

        if (importance <= IMPORTANCE_MAX) {
            retryCount++
        }

        return true
    }

    override fun equals(other: Any?): Boolean {
        if (other == null || other !is Command) {
            return false
        }

        return serviceUUID == other.serviceUUID &&
                characteristicUUID == other.characteristicUUID &&
                Arrays.equals(packet, other.packet)
    }

    override fun hashCode(): Int {
        return Objects.hash(serviceUUID, characteristicUUID, packet)
    }

    companion object {
        const val IMPORTANCE_MIN = 1
        const val IMPORTANCE_NORMAL = 3
        const val IMPORTANCE_MAX = 500
    }
}

Add command importance to the constructor

package com.codegy.aerlink.connection

import java.util.*

data class Command(val serviceUUID: UUID, val characteristicUUID: UUID, val packet: ByteArray? = null, var importance: Int = IMPORTANCE_NORMAL) {

    var isWriteCommand: Boolean = packet != null
    private var retryCount = 0
    var successBlock: (() -> Unit)? = null
    var failureBlock: (() -> Unit)? = null

    fun completeWithSuccess() {
        successBlock?.invoke()
    }

    fun completeWithFailure() {
        failureBlock?.invoke()
    }

    fun shouldRetryAgain(): Boolean {
        if (retryCount >= importance) {
            return false
        }

        if (importance <= IMPORTANCE_MAX) {
            retryCount++
        }

        return true
    }

    override fun equals(other: Any?): Boolean {
        if (other == null || other !is Command) {
            return false
        }

        return serviceUUID == other.serviceUUID &&
                characteristicUUID == other.characteristicUUID &&
                Arrays.equals(packet, other.packet)
    }

    override fun hashCode(): Int {
        return Objects.hash(serviceUUID, characteristicUUID, packet)
    }

    companion object {
        const val IMPORTANCE_MIN = 1
        const val IMPORTANCE_NORMAL = 3
        const val IMPORTANCE_MAX = 500
    }
}


package mixit

import com.samskivert.mustache.Mustache
import com.samskivert.mustache.Mustache.TemplateLoader
import mixit.web.SimpleEscapers
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean

@SpringBootApplication
@EnableConfigurationProperties(MixitProperties::class)
class MixitApplication {

    @Bean
    fun mustacheCompiler(templateLoader: TemplateLoader): Mustache.Compiler =
            Mustache.compiler().withEscaper(SimpleEscapers().HTML).withLoader(templateLoader)
}

fun main(args: Array<String>) {
    runApplication<MixitApplication>(*args)
}

Patch to be able to display talks

package mixit

import com.samskivert.mustache.Mustache
import com.samskivert.mustache.Mustache.TemplateLoader
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean

@SpringBootApplication
@EnableConfigurationProperties(MixitProperties::class)
class MixitApplication {

    @Bean
    fun mustacheCompiler(templateLoader: TemplateLoader): Mustache.Compiler =
            //Mustache.compiler().withEscaper(SimpleEscapers().HTML).withLoader(templateLoader)
            // TODO Find a way to disable HTML escaping before enabling user authentication
            Mustache.compiler().escapeHTML(false).withLoader(templateLoader)
}

fun main(args: Array<String>) {
    runApplication<MixitApplication>(*args)
}


Add Fraudulent Activity Notifications solution

fun main() {

    val (_, days) = readLine().orEmpty().trim().split(" ").map(String::toInt)
    val expenditures = readLine().orEmpty().trim().split(" ").map(String::toInt).toTypedArray()
    fraudulentActivityNotifications(days, expenditures)
}

fun fraudulentActivityNotifications(days: Int, expenditures: Array<Int>) {

    val countArray = IntArray(200)
    var qty = 0

    // initialize
    for (i in 0 until days) {
        countArray[expenditures[i]]++
    }

    for (i in days until expenditures.size) {

        if (expenditures[i] >= median(days, countArray)) qty++
        countArray[expenditures[i - days]]--
        countArray[expenditures[i]]++
    }

    println(qty)
}

fun median(days: Int, countArray: IntArray): Int {

    var count = 0
    val even = days % 2 == 0
    val medianIdx = days / 2
    var foundFirst = false
    var median = 0
    for (countIdx in 0 until countArray.size) {

        count += countArray[countIdx]
        if (!even) {
            if (count > medianIdx) {

                median = countIdx * 2
                break
            }
        } else {
            if (count == medianIdx) {

                median = countIdx
                foundFirst = true
            } else if (count >= medianIdx) {

                if (foundFirst) median += countIdx
                else median = countIdx * 2
                break
            }
        }
    }

    return median
}


/*
 * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
 * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
 */

package kotlin.time

import kotlin.system.*

@SinceKotlin("1.3")
@ExperimentalTime
public actual object MonoClock : AbstractLongClock(unit = DurationUnit.NANOSECONDS), Clock { // TODO: interface should not be required here
    override fun read(): Long = getTimeNanos()
    override fun toString(): String = "Clock(nanoTime)"
}

Rename Clock to TimeSource, ClockMark to TimeMark

/*
 * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
 * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
 */

package kotlin.time

import kotlin.system.*

@SinceKotlin("1.3")
@ExperimentalTime
internal actual object MonotonicTimeSource : AbstractLongTimeSource(unit = DurationUnit.NANOSECONDS), TimeSource { // TODO: interface should not be required here
    override fun read(): Long = getTimeNanos()
    override fun toString(): String = "TimeSource(nanoTime)"
}