package org.jlleitschuh.gradle.ktlint

import org.gradle.api.Action
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.tasks.util.PatternFilterable
import org.gradle.util.GradleVersion

typealias FilterApplier = (Action<PatternFilterable>) -> Unit

/**
 * The base Ktlint plugin that all other plugins are built on.
 */
open class KtlintBasePlugin : Plugin<Project> {
    internal lateinit var extension: KtlintExtension

    override fun apply(target: Project) {
        val filterTargetApplier: FilterApplier = {
            if (GradleVersion.current() >= GradleVersion.version("4.9")) {
                // API only added in Gradle 4.9
                target.tasks.withType(KtlintCheckTask::class.java).configureEach(it)
            } else {
                target.tasks.withType(KtlintCheckTask::class.java, it)
            }
        }

        extension = target.extensions.create(
            "ktlint",
            KtlintExtension::class.java,
            target.objects,
            filterTargetApplier
        )
    }
}

Change typealias visibility to internal.

package org.jlleitschuh.gradle.ktlint

import org.gradle.api.Action
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.tasks.util.PatternFilterable
import org.gradle.util.GradleVersion

internal typealias FilterApplier = (Action<PatternFilterable>) -> Unit

/**
 * The base Ktlint plugin that all other plugins are built on.
 */
open class KtlintBasePlugin : Plugin<Project> {
    internal lateinit var extension: KtlintExtension

    override fun apply(target: Project) {
        val filterTargetApplier: FilterApplier = {
            if (GradleVersion.current() >= GradleVersion.version("4.9")) {
                // API only added in Gradle 4.9
                target.tasks.withType(KtlintCheckTask::class.java).configureEach(it)
            } else {
                target.tasks.withType(KtlintCheckTask::class.java, it)
            }
        }

        extension = target.extensions.create(
            "ktlint",
            KtlintExtension::class.java,
            target.objects,
            filterTargetApplier
        )
    }
}


description = "JUnit Jupiter API"

dependencies {
	api("org.opentest4j:opentest4j:${Versions.ota4j}")
	api(project(":junit-platform-commons"))
	compileOnly("org.jetbrains.kotlin:kotlin-stdlib")
}

tasks.jar {
	manifest {
		attributes(
			"Automatic-Module-Name" to "org.junit.jupiter.api"
		)
	}
}

Introduce runtime dependency from Jupiter API to its Engine

description = "JUnit Jupiter API"

dependencies {
	api("org.opentest4j:opentest4j:${Versions.ota4j}")
	api(project(":junit-platform-commons"))
	compileOnly("org.jetbrains.kotlin:kotlin-stdlib")
	runtimeOnly(project(":junit-jupiter-engine"))
}

tasks.jar {
	manifest {
		attributes(
			"Automatic-Module-Name" to "org.junit.jupiter.api"
		)
	}
}


package com.fsck.k9.storage.migrations

import android.database.sqlite.SQLiteDatabase
import com.fsck.k9.mailstore.MigrationsHelper

internal class MigrationTo75(private val db: SQLiteDatabase, private val migrationsHelper: MigrationsHelper) {
    fun updateAccountWithSpecialFolderIds() {
        val account = migrationsHelper.account

        setSpecialFolderId(account.inboxFolder, account::setInboxFolderId)
        setSpecialFolderId("K9MAIL_INTERNAL_OUTBOX", account::setOutboxFolderId)
        setSpecialFolderId(account.draftsFolder, account::setDraftsFolderId)
        setSpecialFolderId(account.sentFolder, account::setSentFolderId)
        setSpecialFolderId(account.trashFolder, account::setTrashFolderId)
        setSpecialFolderId(account.archiveFolder, account::setArchiveFolderId)
        setSpecialFolderId(account.spamFolder, account::setSpamFolderId)
        setSpecialFolderId(account.autoExpandFolder, account::setAutoExpandFolderId)

        migrationsHelper.saveAccount()
    }

    private fun setSpecialFolderId(serverId: String?, setFolderId: (Long) -> Unit) {
        if (serverId == null) return

        db.query("folders", arrayOf("id"), "server_id = ?", arrayOf(serverId), null, null, null).use { cursor ->
            if (cursor.moveToFirst()) {
                val folderId = cursor.getLong(0)
                setFolderId(folderId)
            }
        }
    }
}

Reset folder server IDs in Account

package com.fsck.k9.storage.migrations

import android.database.sqlite.SQLiteDatabase
import com.fsck.k9.mailstore.MigrationsHelper

internal class MigrationTo75(private val db: SQLiteDatabase, private val migrationsHelper: MigrationsHelper) {
    fun updateAccountWithSpecialFolderIds() {
        val account = migrationsHelper.account

        setSpecialFolderId(account.inboxFolder, account::setInboxFolderId)
        setSpecialFolderId("K9MAIL_INTERNAL_OUTBOX", account::setOutboxFolderId)
        setSpecialFolderId(account.draftsFolder, account::setDraftsFolderId)
        setSpecialFolderId(account.sentFolder, account::setSentFolderId)
        setSpecialFolderId(account.trashFolder, account::setTrashFolderId)
        setSpecialFolderId(account.archiveFolder, account::setArchiveFolderId)
        setSpecialFolderId(account.spamFolder, account::setSpamFolderId)
        setSpecialFolderId(account.autoExpandFolder, account::setAutoExpandFolderId)

        account.inboxFolder = null
        account.draftsFolder = null
        account.sentFolder = null
        account.trashFolder = null
        account.archiveFolder = null
        account.spamFolder = null
        account.autoExpandFolder = null

        migrationsHelper.saveAccount()
    }

    private fun setSpecialFolderId(serverId: String?, setFolderId: (Long) -> Unit) {
        if (serverId == null) return

        db.query("folders", arrayOf("id"), "server_id = ?", arrayOf(serverId), null, null, null).use { cursor ->
            if (cursor.moveToFirst()) {
                val folderId = cursor.getLong(0)
                setFolderId(folderId)
            }
        }
    }
}


/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

buildscript {
    repositories {
        mavenLocal()
        google()
        mavenCentral()
    }
    dependencies {
        val kotlin_version: String by project
        classpath("com.android.tools.build:gradle:4.2.1")
        classpath("de.undercouch:gradle-download-task:4.1.1")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        maven {
            url = uri("$rootDir/node_modules/jsc-android/dist")
        }
        maven {
            // https://github.com/wix/Detox/blob/master/docs/Introduction.Android.md
            // All of Detox's artifacts are provided via the npm module
            url = uri("$rootDir/node_modules/detox/Detox-android")
        }
        mavenLocal()
        google()
        mavenCentral()
    }

    // used to override ndk path on CI
    if (System.getenv("LOCAL_ANDROID_NDK_VERSION") != null) {
        setProperty("ANDROID_NDK_VERSION", System.getenv("LOCAL_ANDROID_NDK_VERSION"))
        ext["ANDROID_NDK_PATH"] =  System.getenv("ANDROID_NDK")
    }
}

Fix builds without NDK path env set

/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

buildscript {
    repositories {
        mavenLocal()
        google()
        mavenCentral()
    }
    dependencies {
        val kotlin_version: String by project
        classpath("com.android.tools.build:gradle:4.2.1")
        classpath("de.undercouch:gradle-download-task:4.1.1")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        maven {
            url = uri("$rootDir/node_modules/jsc-android/dist")
        }
        maven {
            // https://github.com/wix/Detox/blob/master/docs/Introduction.Android.md
            // All of Detox's artifacts are provided via the npm module
            url = uri("$rootDir/node_modules/detox/Detox-android")
        }
        mavenLocal()
        google()
        mavenCentral()
    }

    // used to override ndk path/version from env variables on CI
    ext["ANDROID_NDK_PATH"] = null
    if (System.getenv("LOCAL_ANDROID_NDK_VERSION") != null) {
        setProperty("ANDROID_NDK_VERSION", System.getenv("LOCAL_ANDROID_NDK_VERSION"))
        ext["ANDROID_NDK_PATH"] =  System.getenv("ANDROID_NDK")
    }
}


package flavor.pie.kludge

import org.spongepowered.api.command.CommandResult
import org.spongepowered.api.command.CommandSource
import org.spongepowered.api.command.args.CommandContext
import org.spongepowered.api.command.spec.CommandExecutor
import org.spongepowered.api.command.spec.CommandSpec

val ((CommandSource, CommandContext) -> CommandResult).command: CommandExecutor get() = CommandExecutor { src, args -> this(src, args) }
fun CommandSpec.Builder.executor(executor: (CommandSource, CommandContext) -> CommandResult): CommandSpec.Builder = this.executor(executor.command)

Convert `command` into a function

package flavor.pie.kludge

import org.spongepowered.api.command.CommandResult
import org.spongepowered.api.command.CommandSource
import org.spongepowered.api.command.args.CommandContext
import org.spongepowered.api.command.spec.CommandExecutor
import org.spongepowered.api.command.spec.CommandSpec

fun ((CommandSource, CommandContext) -> CommandResult).command(): CommandExecutor = CommandExecutor(this)
fun CommandSpec.Builder.executor(executor: (CommandSource, CommandContext) -> CommandResult): CommandSpec.Builder = this.executor(executor.command())


/*
 * Copyright (C) 2020 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.query.rest.debugger

import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.text.nullize
import uk.co.reecedunn.intellij.plugin.core.xml.XmlElement
import uk.co.reecedunn.intellij.plugin.intellij.xdebugger.frame.QueryStackFrame

class MarkLogicDebugFrame(frame: XmlElement, query: VirtualFile) : QueryStackFrame(query) {
    override val uri: String? = frame.child("dbg:uri")?.text()?.nullize()
    override val line: Int = frame.child("dbg:line")?.text()?.toIntOrNull() ?: 1
    override val column: Int = 1
}

Add the column number to thedebug stack frame.

/*
 * Copyright (C) 2020 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.query.rest.debugger

import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.text.nullize
import uk.co.reecedunn.intellij.plugin.core.xml.XmlElement
import uk.co.reecedunn.intellij.plugin.intellij.xdebugger.frame.QueryStackFrame

class MarkLogicDebugFrame(frame: XmlElement, query: VirtualFile) : QueryStackFrame(query) {
    override val uri: String? = frame.child("dbg:uri")?.text()?.nullize()
    override val line: Int = frame.child("dbg:line")?.text()?.toIntOrNull() ?: 1
    override val column: Int = frame.child("dbg:column")?.text()?.toIntOrNull() ?: 1
}


package de.maibornwolff.codecharta.importer.codemaat

import de.maibornwolff.codecharta.model.*
import java.util.*

class CSVRow(private val row: Array<String?>, private val header: CSVHeader, private val pathSeparator: Char) {

    init {
        if (row.size <= header.pathColumn) {
            throw IllegalArgumentException(
                    "Row " + Arrays.toString(row) + " has no column containing the file path. Should be in " + header.pathColumn + "th column.")
        }
    }

    fun getFileNameFromPath(path: String): String {
        return path.substring(path.lastIndexOf(pathSeparator) + 1)
    }

    fun asDependency(): Dependency {
        val entityPath = Path(attributes.get("entity")!!).edgesList.first()
        val coupledPath = Path(attributes.get("coupled")!!).edgesList.first()

        return Dependency(
                entityPath,
                getFileNameFromPath(entityPath),
                coupledPath,
                getFileNameFromPath(coupledPath),
                attributes.get("degree")!!.toInt(),
                attributes.get("average-revs")!!.toInt()
        )
    }

    private fun validAttributeOfRow(i: Int) =
            i < row.size && row[i] != null

    private val attributes =
            header.columnNumbers
                    .filter { validAttributeOfRow(it) }
                    .associateBy(
                            { header.getColumnName(it) },
                            { row[it]!! }
                    )
}

Update Prefix Path in dependencies

package de.maibornwolff.codecharta.importer.codemaat

import de.maibornwolff.codecharta.model.*
import java.util.*

class CSVRow(private val row: Array<String?>, private val header: CSVHeader, private val pathSeparator: Char) {

    init {
        if (row.size <= header.pathColumn) {
            throw IllegalArgumentException(
                    "Row " + Arrays.toString(row) + " has no column containing the file path. Should be in " + header.pathColumn + "th column.")
        }
    }

    fun getFileNameFromPath(path: String): String {
        return path.substring(path.lastIndexOf(pathSeparator) + 1)
    }

    fun asDependency(): Dependency {
        val rootNode = "/root/"
        val entityPath = rootNode + Path(attributes.get("entity")!!).edgesList.first()
        val coupledPath = rootNode + Path(attributes.get("coupled")!!).edgesList.first()

        return Dependency(
                entityPath,
                getFileNameFromPath(entityPath),
                coupledPath,
                getFileNameFromPath(coupledPath),
                attributes.get("degree")!!.toInt(),
                attributes.get("average-revs")!!.toInt()
        )
    }

    private fun validAttributeOfRow(i: Int) =
            i < row.size && row[i] != null

    private val attributes =
            header.columnNumbers
                    .filter { validAttributeOfRow(it) }
                    .associateBy(
                            { header.getColumnName(it) },
                            { row[it]!! }
                    )
}


Add Sherlock and the Valid String solution

// https://www.hackerrank.com/challenges/sherlock-and-valid-string/problem

fun main() {

    val string = readLine().orEmpty()
    println(if (isValid(string)) "YES" else "NO")
}

fun isValid(string: String): Boolean {

    if (string.length <= 3) return true

    val charFreq = IntArray('z' - 'a' + 1)
    for (char in string) charFreq[char - 'a']++

    val metaFreq = mutableMapOf<Int, Int>()
    for (frequency in charFreq) {
        if (frequency != 0) metaFreq[frequency] = metaFreq.getOrDefault(frequency, 0) + 1
    }

    return when (metaFreq.keys.size) {
        1 -> true
        2 -> {
            val (first, second) = metaFreq.keys.toList()
            if ((first == 1 && metaFreq[first] == 1) || (second == 1 && metaFreq[second] == 1)) true
            else Math.abs(first - second) == 1 && (metaFreq[first] == 1 || metaFreq[second] == 1)
        }
        else -> false
    }
}


package com.beust.kobalt.misc

fun benchmarkMillis(run: () -> Unit) : Long {
    val start = System.currentTimeMillis()
    run()
    return System.currentTimeMillis() - start
}

fun benchmarkSeconds(run: () -> Unit) = benchmarkMillis(run) / 1000

Return pairs for benchmark functions.

package com.beust.kobalt.misc

fun <T> benchmarkMillis(run: () -> T) : Pair<Long, T> {
    val start = System.currentTimeMillis()
    val result = run()
    return Pair(System.currentTimeMillis() - start, result)
}

fun <T> benchmarkSeconds(run: () -> T) : Pair<Long, T> {
    val result = benchmarkMillis(run)
    return Pair(result.first / 1000, result.second)
}


@file:Suppress("unused")

package org.purescript.parser

import com.intellij.lang.PsiBuilder
import com.intellij.psi.tree.IElementType

class ParserContext(private val builder: PsiBuilder) {
    private val recoverySet = HashMap<IElementType, Int?>()
    var isInAttempt = false
    private var inOptional = 0
    fun eof() = builder.eof()

    fun advance() = builder.advanceLexer()

    fun addUntilToken(token: IElementType) {
        var i = 0
        if (recoverySet.containsKey(token)) {
            i = recoverySet[token]!!
        }
        recoverySet[token] = i + 1
    }

    fun removeUntilToken(token: IElementType) {
        val i = recoverySet[token]!!
        if (i == 1) {
            recoverySet.remove(token)
        } else {
            recoverySet[token] = i - 1
        }
    }

    fun isUntilToken(token: IElementType) = recoverySet.containsKey(token)
    fun enterOptional() = inOptional++
    fun exitOptional() = inOptional--
    fun isInOptional() = inOptional > 0
    fun text() = builder.tokenText ?: ""
    fun peek() = builder.tokenType ?: PSTokens.EOF

    fun eat(type: IElementType): Boolean {
        if (builder.tokenType === type) {
            advance()
            return true
        }
        return false
    }

    fun start(): PsiBuilder.Marker = builder.mark()

    val position: Int
        get() = builder.currentOffset

    fun getText(start: Int, end: Int) =
        builder.originalText.subSequence(start, end).toString()
}

Remove methods and field that is not longer in use

@file:Suppress("unused")

package org.purescript.parser

import com.intellij.lang.PsiBuilder
import com.intellij.psi.tree.IElementType

class ParserContext(private val builder: PsiBuilder) {
    var isInAttempt = false
    private var inOptional = 0
    fun eof() = builder.eof()

    fun advance() = builder.advanceLexer()

    fun enterOptional() = inOptional++
    fun exitOptional() = inOptional--
    fun isInOptional() = inOptional > 0
    fun text() = builder.tokenText ?: ""
    fun peek() = builder.tokenType ?: PSTokens.EOF

    fun eat(type: IElementType): Boolean {
        if (builder.tokenType === type) {
            advance()
            return true
        }
        return false
    }

    fun start(): PsiBuilder.Marker = builder.mark()

    val position: Int
        get() = builder.currentOffset

    fun getText(start: Int, end: Int) =
        builder.originalText.subSequence(start, end).toString()
}


/*
 * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
 */

package io.ktor.client.tests.utils

import ch.qos.logback.classic.*
import io.ktor.client.tests.utils.tests.*
import io.ktor.server.engine.*
import io.ktor.server.jetty.*
import org.slf4j.*
import java.io.*
import java.util.concurrent.*

private const val DEFAULT_PORT: Int = 8080
private const val HTTP_PROXY_PORT: Int = 8082

internal fun startServer(): Closeable {
    val logger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME) as ch.qos.logback.classic.Logger
    logger.level = Level.WARN

    val server = embeddedServer(Jetty, DEFAULT_PORT) {
        tests()
        benchmarks()
    }.start()

    val proxyServer = TestTcpServer(HTTP_PROXY_PORT, ::proxyHandler)

    return Closeable {
        proxyServer.close()
        server.stop(0L, 0L, TimeUnit.MILLISECONDS)
    }
}

/**
 * Start server for tests.
 */
fun main() {
    startServer()
}

Use Netty as a default test server instead of Jetty (some issues like TCP half-close could be reproduced only on Netty).

/*
 * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
 */

package io.ktor.client.tests.utils

import ch.qos.logback.classic.*
import io.ktor.client.tests.utils.tests.*
import io.ktor.server.engine.*
import io.ktor.server.jetty.*
import io.ktor.server.netty.*
import org.slf4j.*
import java.io.*
import java.util.concurrent.*

private const val DEFAULT_PORT: Int = 8080
private const val HTTP_PROXY_PORT: Int = 8082

internal fun startServer(): Closeable {
    val logger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME) as ch.qos.logback.classic.Logger
    logger.level = Level.WARN

    val server = embeddedServer(Netty, DEFAULT_PORT) {
        tests()
        benchmarks()
    }.start()

    val proxyServer = TestTcpServer(HTTP_PROXY_PORT, ::proxyHandler)

    return Closeable {
        proxyServer.close()
        server.stop(0L, 0L, TimeUnit.MILLISECONDS)
    }
}

/**
 * Start server for tests.
 */
fun main() {
    startServer()
}


package com.pr0gramm.app.util

import android.net.Uri

object Affiliate {
    private val paramsHubTraffic = mapOf(
            "utm_source" to "paid",
            "utm_medium" to "hubtraffic",
            "utm_campaign" to "hubtraffic_pr0grammapp")

    private val reHubTraffic = "(?:pornhub|redtube|tube8|youporn|xtube|spankwire|keezmovies|extremetube)\\.com".toRegex()

    private fun hubTraffic(url: String): String {
        val uri = Uri.parse(url)

        val updated = uri.buildUpon().clearQuery()

        for (name in uri.queryParameterNames - paramsHubTraffic.keys) {
            val value = uri.getQueryParameter(name) ?: continue
            updated.appendQueryParameter(name, value)
        }

        for ((name, value) in paramsHubTraffic) {
            updated.appendQueryParameter(name, value)
        }

        return updated.build().toString()
    }

    fun get(url: String): String? {
        return when {
            reHubTraffic.containsMatchIn(url) -> hubTraffic(url)

            // no affiliate url
            else -> null
        }
    }
}

Fix hubtraffic by redirecting over a app.pr0gramm.com domain.

package com.pr0gramm.app.util

import android.util.Base64

object Affiliate {
    private val paramsHubTraffic = mapOf(
            "utm_source" to "paid",
            "utm_medium" to "hubtraffic",
            "utm_campaign" to "hubtraffic_pr0grammapp")

    private val reHubTraffic = "(?:pornhub|redtube|tube8|youporn|xtube|spankwire|keezmovies|extremetube)\\.com".toRegex()

    private fun hubTraffic(url: String): String {
        val encoded = Base64.encodeToString(url.toByteArray(), Base64.URL_SAFE)
        return "https://app.pr0gramm.com/redirect.html?u=$encoded"
    }

    fun get(url: String): String? {
        return when {
            reHubTraffic.containsMatchIn(url) -> hubTraffic(url)

            // no affiliate url
            else -> null
        }
    }
}


package com.beust.kobalt

import com.beust.kobalt.api.Kobalt
import com.beust.kobalt.api.Project
import com.beust.kobalt.api.annotation.Directive
import com.beust.kobalt.maven.DepFactory
import com.beust.kobalt.maven.IClasspathDependency
import com.beust.kobalt.misc.KobaltExecutors
import com.beust.kobalt.SystemProperties
import java.io.File

@Directive
fun homeDir(vararg dirs: String) : String = SystemProperties.homeDir +
        File.separator + dirs.toArrayList().join(File.separator)

@Directive
fun file(file: String) : String = IClasspathDependency.PREFIX_FILE + file

@Directive
fun plugins(vararg dependency : IClasspathDependency) {
    Plugins.dynamicPlugins.addAll(dependency)
}

@Directive
fun plugins(vararg dependencies : String) {
    val executor = Kobalt.INJECTOR.getInstance(KobaltExecutors::class.java)
            .newExecutor("BuildScript", 5)
    val factory = Kobalt.INJECTOR.getInstance(DepFactory::class.java)
    dependencies.forEach {
        Plugins.dynamicPlugins.add(factory.create(it, executor))
    }
}

@Directive
fun repos(vararg repos : String) {
    repos.forEach { Kobalt.addRepo(it) }
}

@Directive
fun glob(g: String) : IFileSpec.Glob = IFileSpec.Glob(g)

Use the misc executor (otherwise threads left hanging).

package com.beust.kobalt

import com.beust.kobalt.api.Kobalt
import com.beust.kobalt.api.Project
import com.beust.kobalt.api.annotation.Directive
import com.beust.kobalt.maven.DepFactory
import com.beust.kobalt.maven.IClasspathDependency
import com.beust.kobalt.misc.KobaltExecutors
import com.beust.kobalt.SystemProperties
import java.io.File

@Directive
fun homeDir(vararg dirs: String) : String = SystemProperties.homeDir +
        File.separator + dirs.toArrayList().join(File.separator)

@Directive
fun file(file: String) : String = IClasspathDependency.PREFIX_FILE + file

@Directive
fun plugins(vararg dependency : IClasspathDependency) {
    Plugins.dynamicPlugins.addAll(dependency)
}

@Directive
fun plugins(vararg dependencies : String) {
    val executor = Kobalt.INJECTOR.getInstance(KobaltExecutors::class.java).miscExecutor
    val factory = Kobalt.INJECTOR.getInstance(DepFactory::class.java)
    dependencies.forEach {
        Plugins.dynamicPlugins.add(factory.create(it, executor))
    }
}

@Directive
fun repos(vararg repos : String) {
    repos.forEach { Kobalt.addRepo(it) }
}

@Directive
fun glob(g: String) : IFileSpec.Glob = IFileSpec.Glob(g)


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

import com.intellij.debugger.streams.trace.TraceExpressionBuilder
import com.intellij.debugger.streams.wrapper.StreamChain

/**
 * @author Vitaliy.Bibaev
 */
class KotlinExpressionBuilder : TraceExpressionBuilder {
  override fun createTraceExpression(chain: StreamChain): String {
    return ""
  }
}


package org.logout.notifications.telegram.bot.processor

class HelpProcessor : Processor {
    override fun onMessage(arguments: Array<String>?) =
            listOf("/staima, /whatsup and a couple of secret aliases — the closest next event in near future\n" +
                    "/staima today — as much of today's schedule which will fit in 1000 characters. " +
                    "This is going to be changed soon to send the whole day's schedule.\n" +
                    "/staima -v — if you want to see abstracts for the upcoming events" +
                    "Anything else is just gets repeated back at you. Maybe. Or bot could suddenly acquire sentience and look back at you.")
}

class StartProcessor : Processor {
    override fun onMessage(arguments: Array<String>?) =
            listOf("Welcome to Infobip DevDays 2017. Send /staima to find out what are the " +
                    "nearest events or /help for more information.")
}

class DissentProcessor : Processor {
    override fun onMessage(arguments: Array<String>?) =
            listOf("Sad to hear you are not happy. Grab a coffee?")
}

Update help and announce new feature

package org.logout.notifications.telegram.bot.processor

class HelpProcessor : Processor {
    override fun onMessage(arguments: Array<String>?) =
            listOf("/staima, /whatsup and a couple of secret aliases — the closest next event in near future\n" +
                    "/staima today — as much of today's schedule which will fit in 1000 characters. " +
                    "This is going to be changed soon to send the whole day's schedule.\n" +
                    "/staima -v — if you want to see abstracts for the upcoming events.\n" +
                    "/staima now — if you want to see what's going on right now.\n" +
                    "Anything else is just gets repeated back at you. Maybe. Or bot could suddenly acquire sentience and look back at you.")
}

class StartProcessor : Processor {
    override fun onMessage(arguments: Array<String>?) =
            listOf("Welcome to Infobip DevDays 2017. Send /staima to find out what are the " +
                    "nearest events or /help for more information.")
}

class DissentProcessor : Processor {
    override fun onMessage(arguments: Array<String>?) =
            listOf("Sad to hear you are not happy. Grab a coffee?")
}


dependencies {
  implementation(projects.fluencyCore)

  implementation("software.amazon.awssdk:s3:2.17.223")
}

Bump s3 from 2.17.223 to 2.17.281

dependencies {
  implementation(projects.fluencyCore)

  implementation("software.amazon.awssdk:s3:2.17.281")
}


package com.reduks.reduks

data class StoreDSL<State> (
        var initialState: State? = null,
        var initialReducer: (State, Action<State>) -> State = { state, action -> action.action(state) },
        var enhancer: Enhancer<State>? = null
)

fun <State> Any.reduksStore(dsl: StoreDSL<State>.() -> Unit) : Store<State> {
    val storeDsl = StoreDSL<State>()
    storeDsl.dsl()
    if (storeDsl.initialState == null) throw Exception("You need to pass a default instance to create the store")
    return Store(
            storeDsl.initialState!!,
            storeDsl.initialReducer,
            storeDsl.enhancer
    )
}

Implement state default value in store dsl

package com.reduks.reduks

import com.reduks.reduks.error.ReduksException

data class StoreDSL<State> (
        var initialState: State?,
        var initialReducer: (State, Action<State>) -> State,
        var enhancer: Enhancer<State>?
) {
    companion object Provider {
        inline fun <reified State> get() : StoreDSL<State> {
            val state = try { State::class.java.newInstance() } catch (e: java.lang.Exception) { throw ReduksException("To create a default initial state, all state fields need to be initialized with a default value.") }
            return StoreDSL(
                    state,
                    { state, action -> action.action(state) },
                    null
            )
        }
    }
}

inline fun <reified State> Any.reduksStore(dsl: StoreDSL<State>.() -> Unit) : Store<State> {
    val storeDsl = StoreDSL.get<State>()
    storeDsl.dsl()
    if (storeDsl.initialState == null) throw ReduksException("You need to pass a default instance to create the store")
    return Store(
            storeDsl.initialState!!,
            storeDsl.initialReducer,
            storeDsl.enhancer
    )
}


object PluginVersions {
    val kotlin = "1.3.31"
    val ktlintPlugin = "7.2.0"
    val gradlePublishPlugin = "0.10.1"
    val androidPlugin = "3.3.0"
    val semver = "1.1.1"
    val gradleWrapper = "4.10.2"
    val junit5 = "5.4.0"
    val assertJ = "3.11.1"
}

Use latest plugin version on itself.

object PluginVersions {
    val kotlin = "1.3.31"
    val ktlintPlugin = "7.4.0"
    val gradlePublishPlugin = "0.10.1"
    val androidPlugin = "3.3.0"
    val semver = "1.1.1"
    val gradleWrapper = "4.10.2"
    val junit5 = "5.4.0"
    val assertJ = "3.11.1"
}


/*
 * 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.query.vars

object KeyValueVarsBuilder : VarsBuilder {
    private var isFirstItem = true

    override fun start(builder: StringBuilder) {
        builder.append('(')
        isFirstItem = true
    }

    override fun add(builder: StringBuilder, key: String, value: String) {
        if (isFirstItem) {
            isFirstItem = false
        } else {
            builder.append(", ")
        }

        builder.append("xs:QName(\"")
        builder.append(key)
        builder.append("\"), ")
        builder.append(value)
    }

    override fun end(builder: StringBuilder) {
        builder.append(')')
    }
}

Use string variable references when building the key-value vars strings.

/*
 * 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.query.vars

object KeyValueVarsBuilder : VarsBuilder {
    private var isFirstItem = true

    override fun start(builder: StringBuilder) {
        builder.append('(')
        isFirstItem = true
    }

    override fun add(builder: StringBuilder, key: String, value: String) {
        if (isFirstItem) {
            isFirstItem = false
        } else {
            builder.append(", ")
        }

        builder.append("xs:QName(\"$key\"), $value")
    }

    override fun end(builder: StringBuilder) {
        builder.append(')')
    }
}


package com.example.jankstats.compose

import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalView
import androidx.metrics.performance.PerformanceMetricsState

// [START rememberMetricsStateHolder]
/**
 * Retrieve MetricsStateHolder from compose and remember until the current view changes.
 */
@Composable
fun rememberMetricsStateHolder(): PerformanceMetricsState.MetricsStateHolder {
    val view = LocalView.current
    return remember(view) { PerformanceMetricsState.getForHierarchy(view) }
}
// [END rememberMetricsStateHolder]

Rename DAC tag for state holder

package com.example.jankstats.compose

import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalView
import androidx.metrics.performance.PerformanceMetricsState

// [START metrics_state_holder]
/**
 * Retrieve MetricsStateHolder from compose and remember until the current view changes.
 */
@Composable
fun rememberMetricsStateHolder(): PerformanceMetricsState.MetricsStateHolder {
    val view = LocalView.current
    return remember(view) { PerformanceMetricsState.getForHierarchy(view) }
}
// [END metrics_state_holder]


package com.fortify.fod.parser

class BsiToken {
    var tenantId: Int = 0
    var tenantCode: String? = null
    var projectVersionId: Int = 0
    var payloadType: String? = null
    var assessmentTypeId: Int = 0
    var technologyStack: String? = null
    var languageLevel = ""
    var endpoint: String? = null
}

Rename endpoint to apiUri and default it to AMS portal

package com.fortify.fod.parser

class BsiToken {
    var tenantId: Int = 0
    var tenantCode: String? = null
    var projectVersionId: Int = 0
    var payloadType: String? = null
    var assessmentTypeId: Int = 0
    var technologyStack: String? = null
    var languageLevel = ""
    var apiUri: String = "https://api.ams.fortify.com"
}


Create an XpmFunctionReference data class implementation.

/*
 * Copyright (C) 2020 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.xpm.function.impl

import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue
import uk.co.reecedunn.intellij.plugin.xpm.function.XpmFunctionReference

data class XpmFunctionReferenceImpl(
    override val functionName: XsQNameValue,
    override val arity: Int
) : XpmFunctionReference


/*
 * Copyright 2020, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import io.spine.gradle.internal.Deps

/*
    This Smoke Tests module holds a TestMethodFactory that is used in model-compiler-test module.
*/

plugins {
    java
}

dependencies {
    implementation(Deps.gen.javaPoet)
}

Add dependency on the `tools-api`.

/*
 * Copyright 2020, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import io.spine.gradle.internal.Deps

/*
    This Smoke Tests module holds a TestMethodFactory that is used in model-compiler-test module.
*/

plugins {
    java
}

val spineVersion: String by extra

dependencies {
    implementation(Deps.gen.javaPoet)
    implementation("io.spine.tools:tools-api:$spineVersion")
}


package util

import common.Os
import jetbrains.buildServer.configs.kotlin.v2019_2.Project

object UtilProject : Project({
    id("Util")
    name = "Util"

    buildType(RerunFlakyTest(Os.LINUX))
    buildType(RerunFlakyTest(Os.WINDOWS))
    buildType(RerunFlakyTest(Os.MACOS))
    buildType(WarmupEc2Agent)
})

Add Gradle Enterprise key to Utils project

package util

import common.Os
import jetbrains.buildServer.configs.kotlin.v2019_2.Project

object UtilProject : Project({
    id("Util")
    name = "Util"

    buildType(RerunFlakyTest(Os.LINUX))
    buildType(RerunFlakyTest(Os.WINDOWS))
    buildType(RerunFlakyTest(Os.MACOS))
    buildType(WarmupEc2Agent)

    params {
        param("env.GRADLE_ENTERPRISE_ACCESS_KEY", "%ge.gradle.org.access.key%")
    }
})


package net.devromik.bw

import net.devromik.bw.Color.values

/**
 * @author Shulnyaev Roman
 */
enum class Color(val index: Int) {
    BLACK(0),
    WHITE(1),
    GRAY(2);
}

val COLOR_COUNT = values().size

fun colorByIndex(index: Int) = Color.values().firstOrNull { it.index == index }

Optimize getting a color by an index

package net.devromik.bw

import net.devromik.bw.Color.*

/**
 * @author Shulnyaev Roman
 */
enum class Color(val index: Int) {
    BLACK(0),
    WHITE(1),
    GRAY(2);
}

val COLOR_COUNT = values().size

fun colorByIndex(index: Int) =
    when (index) {
        BLACK.index -> BLACK
        WHITE.index -> WHITE
        GRAY.index -> GRAY
        else -> throw IllegalArgumentException("$index is not a color index")
    }


package codesample.kotlin.jwtexample.security.config

import codesample.kotlin.jwtexample.security.AuthExceptionsEntry
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.http.SessionCreationPolicy

@Configuration
@EnableWebSecurity
class SecurityConfig (val authExceptionsEntry: AuthExceptionsEntry)
    : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http
                // Route all auth exceptions to this class. See it's comment for more info
                .exceptionHandling().authenticationEntryPoint(authExceptionsEntry)
                .and()

                // Do not store any session info. We are going to authenticate each request with JWT token
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()

                .authorizeRequests()

                .antMatchers("/h2-console/**/**").permitAll()
                .antMatchers("/auth/**").permitAll()
                .anyRequest().authenticated()
    }
}

Fix h2-console being blocked by spring-security

package codesample.kotlin.jwtexample.security.config

import codesample.kotlin.jwtexample.security.AuthExceptionsEntry
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.builders.WebSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.http.SessionCreationPolicy

@Configuration
@EnableWebSecurity
class SecurityConfig (val authExceptionsEntry: AuthExceptionsEntry)
    : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http
                // Route all auth exceptions to this class. See it's comment for more info
                .exceptionHandling().authenticationEntryPoint(authExceptionsEntry)
                .and()

                // Do not store any session info. We are going to authenticate each request with JWT token
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()

                .authorizeRequests()

                .antMatchers("/auth/**").permitAll()
                .anyRequest().authenticated()
    }

    override fun configure(web: WebSecurity) {
        web
                .ignoring().antMatchers("/h2-console/**/**")
    }
}


package com.github.kmizu.kotbinator

inline fun <T> block(body: () -> T): T {
    return body()
}

Define map method for nullable-type

package com.github.kmizu.kotbinator

inline fun <T> block(body: () -> T): T {
    return body()
}

inline fun <T, U> T?.map(f: (T) -> U): U? = block {
    when(this) {
        null -> null
        else -> f(this)
    }
}

fun foo() {
    val x: String? = "FOO"
    val y: Int? = x.map { x -> 1 }
}


package configurations

import jetbrains.buildServer.configs.kotlin.v10.BuildType
import model.CIBuildModel
import model.OS
import model.TestCoverage
import model.TestType

class FunctionalTest(model: CIBuildModel, testCoverage : TestCoverage, subProject: String = "") : BuildType({
    uuid = testCoverage.asConfigurationId(model, subProject)
    extId = uuid
    name = testCoverage.asName() + if (!subProject.isEmpty()) " ($subProject)" else ""
    val testTask = testCoverage.testType.name + "Test" + if (!subProject.isEmpty()) subProject.capitalize() else ""
    val quickTest = testCoverage.testType == TestType.quick
    applyDefaults(model, this, testTask, subProject = subProject, requiresDistribution = !quickTest,
            runsOnWindows = testCoverage.os == OS.windows, timeout = if (quickTest) 60 else 180)

    params {
        param("env.JAVA_HOME", "%${testCoverage.os}.${testCoverage.version}.${testCoverage.vendor}.64bit%")
        if (testCoverage.os == OS.linux) {
            param("env.JAVA_9", "%linux.java9.oracle.64bit%")
            param("env.ANDROID_HOME", "/opt/android/sdk")
        }
    }
})

Call build types on subprojects instead of using specific tasks

package configurations

import jetbrains.buildServer.configs.kotlin.v10.BuildType
import model.CIBuildModel
import model.OS
import model.TestCoverage
import model.TestType

class FunctionalTest(model: CIBuildModel, testCoverage : TestCoverage, subProject: String = "") : BuildType({
    uuid = testCoverage.asConfigurationId(model, subProject)
    extId = uuid
    name = testCoverage.asName() + if (!subProject.isEmpty()) " ($subProject)" else ""
    val testTask = if (!subProject.isEmpty()) subProject + ":" else "" + testCoverage.testType.name + "Test"
    val quickTest = testCoverage.testType == TestType.quick
    applyDefaults(model, this, testTask, subProject = subProject, requiresDistribution = !quickTest,
            runsOnWindows = testCoverage.os == OS.windows, timeout = if (quickTest) 60 else 180)

    params {
        param("env.JAVA_HOME", "%${testCoverage.os}.${testCoverage.version}.${testCoverage.vendor}.64bit%")
        if (testCoverage.os == OS.linux) {
            param("env.JAVA_9", "%linux.java9.oracle.64bit%")
            param("env.ANDROID_HOME", "/opt/android/sdk")
        }
    }
})


package adrygraph.simplelauncher

import adrygraph.simplelauncher.settings.ui.ColorPickerDialog
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.ViewGroup

class MainActivity : AppCompatActivity(), ColorPickerDialog.OnColorChangedListener {

    private var mRootView : ViewGroup? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mRootView = findViewById(R.id.activityMainRootViewCL)!!
    }

    override fun onBackPressed() {
        displayColorPicker()
    }

    private fun displayColorPicker() {
        ColorPickerDialog(this@MainActivity, this@MainActivity)
                .show()
    }

    override fun colorChanged(color: Int) {
        setBackground(color)
    }

    private fun setBackground(color : Int) {
        mRootView!!.setBackgroundColor(color)
    }
}

Apply background from prefs on app start

package adrygraph.simplelauncher

import adrygraph.simplelauncher.settings.ui.ColorPickerDialog
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.ViewGroup

class MainActivity : AppCompatActivity(), ColorPickerDialog.OnColorChangedListener {

    private var mRootView : ViewGroup? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mRootView = findViewById(R.id.activityMainRootViewCL)!!
        setBackground(AppData.getBackgroundColorInPref())
    }

    override fun onBackPressed() {
        displayColorPicker()
    }

    private fun displayColorPicker() {
        ColorPickerDialog(this@MainActivity, this@MainActivity)
                .show()
    }

    override fun colorChanged(color: Int) {
        setBackground(color)
    }

    private fun setBackground(color : Int) {
        mRootView!!.setBackgroundColor(color)
    }
}


/*
 * Java GPX Library (@__identifier__@).
 * Copyright (c) @__year__@ Franz Wilhelmstötter
 *
 * 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.
 *
 * Author:
 *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
 */

/**
 * @author Franz Wilhelmstötter
 * @since 2.1
 * @version 2.1
 */
plugins {
	`java-gradle-plugin`
	`kotlin-dsl`
}

repositories {
	mavenLocal()
	gradlePluginPortal()
}

configure<JavaPluginConvention> {
	sourceCompatibility = JavaVersion.VERSION_11
	targetCompatibility = JavaVersion.VERSION_11
}

Fix deprecation warning in build script.

/*
 * Java GPX Library (@__identifier__@).
 * Copyright (c) @__year__@ Franz Wilhelmstötter
 *
 * 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.
 *
 * Author:
 *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
 */

/**
 * @author Franz Wilhelmstötter
 * @since 2.1
 * @version 2.1
 */
plugins {
	`java-gradle-plugin`
	`kotlin-dsl`
}

repositories {
	mavenLocal()
	gradlePluginPortal()
}

configure<JavaPluginExtension> {
	sourceCompatibility = JavaVersion.VERSION_11
	targetCompatibility = JavaVersion.VERSION_11
}


plugins {
    `java-library`
}

java {
    sourceCompatibility = JavaVersion.VERSION_11
    targetCompatibility = JavaVersion.VERSION_11
}

version = "0"

tasks {

    javadoc {
        (options as StandardJavadocDocletOptions).addStringOption("-module", "de.sormuras.bach.doc.minimal")
        (options as StandardJavadocDocletOptions).addStringOption("-patch-module", "de.sormuras.bach.doc.minimal=src/main/java")
    }

    val sourcesJar by creating(Jar::class) {
        dependsOn(JavaPlugin.CLASSES_TASK_NAME)
        classifier = "sources"
        from(sourceSets["main"].allJava)
    }

    val javadocJar by creating(Jar::class) {
        dependsOn(JavaPlugin.JAVADOC_TASK_NAME)
        classifier = "javadoc"
        from(javadoc)
    }

    artifacts {
        add("archives", sourcesJar)
        add("archives", javadocJar)
    }
}

Make Gradle sample more minimal

plugins {
    `java-library`
}

java {
    sourceCompatibility = JavaVersion.VERSION_11
    targetCompatibility = JavaVersion.VERSION_11
    withSourcesJar()
    withJavadocJar()
}

version = "0"

tasks.javadoc {
    (options as StandardJavadocDocletOptions).apply {
        addStringOption("-module", "de.sormuras.bach.doc.minimal")
        addStringOption("-patch-module", "de.sormuras.bach.doc.minimal=src/main/java")
    }
}


package fr.masciulli.drinks.drink

import fr.masciulli.drinks.BaseViewModel
import fr.masciulli.drinks.core.drinks.Drink
import fr.masciulli.drinks.core.drinks.DrinksSource
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.BehaviorSubject

class DrinkViewModel(
        private val drinksSource: DrinksSource,
        private val drinkId: String
) : BaseViewModel {
    private var drinkDisposable: Disposable? = null

    var drink: BehaviorSubject<Drink> = BehaviorSubject.create()
    var error: BehaviorSubject<Throwable> = BehaviorSubject.create()
    val shareDrink: BehaviorSubject<Drink> = BehaviorSubject.create()

    override fun start() {
        drinkDisposable = drinksSource.getDrink(drinkId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        { drinkLoaded(it) },
                        { errorLoadingDrink(it) }
                )
    }

    private fun drinkLoaded(drink: Drink) {
        this.drink.onNext(drink)
    }

    private fun errorLoadingDrink(throwable: Throwable) {
        error.onNext(throwable)
    }

    fun openShareDrink() {
        drink.value?.let { shareDrink.onNext(it) }
    }

    override fun stop() {
        drinkDisposable?.dispose()
    }
}

Set view model feeds immutable

package fr.masciulli.drinks.drink

import fr.masciulli.drinks.BaseViewModel
import fr.masciulli.drinks.core.drinks.Drink
import fr.masciulli.drinks.core.drinks.DrinksSource
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.BehaviorSubject

class DrinkViewModel(
        private val drinksSource: DrinksSource,
        private val drinkId: String
) : BaseViewModel {
    private var drinkDisposable: Disposable? = null

    val drink: BehaviorSubject<Drink> = BehaviorSubject.create()
    val error: BehaviorSubject<Throwable> = BehaviorSubject.create()
    val shareDrink: BehaviorSubject<Drink> = BehaviorSubject.create()

    override fun start() {
        drinkDisposable = drinksSource.getDrink(drinkId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        { drinkLoaded(it) },
                        { errorLoadingDrink(it) }
                )
    }

    private fun drinkLoaded(drink: Drink) {
        this.drink.onNext(drink)
    }

    private fun errorLoadingDrink(throwable: Throwable) {
        error.onNext(throwable)
    }

    fun openShareDrink() {
        drink.value?.let { shareDrink.onNext(it) }
    }

    override fun stop() {
        drinkDisposable?.dispose()
    }
}


package backend.controller

import backend.model.event.EventService
import backend.model.misc.Coords
import backend.view.EventView
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.*
import java.time.LocalDateTime
import java.time.ZoneOffset
import kotlin.collections.map

@RestController
@RequestMapping("/event")
class EventController {

    val eventService: EventService

    @Autowired
    constructor(eventService: EventService) {
        this.eventService = eventService
    }

    @ResponseStatus(HttpStatus.CREATED)
    @RequestMapping(
            value = "/",
            method = arrayOf(RequestMethod.POST),
            produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
    fun createEvent(@RequestBody body: EventView): EventView {

        val event = eventService.createEvent(
                title = body.title!!,
                date = LocalDateTime.ofEpochSecond(body.date!!, 0, ZoneOffset.UTC),
                city = body.city!!,
                duration = body.duration,
                startingLocation = Coords(body.startingLocation!!.latitude!!, body.startingLocation!!.longitude!!))

        return EventView(event)
    }

    @RequestMapping(
            value = "/",
            method = arrayOf(RequestMethod.GET),
            produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
    fun getAllEvents(): Iterable<EventView> {
        return eventService.findAll().map { EventView(it) }
    }
}

Validate Body of API Request for creating events

package backend.controller

import backend.model.event.EventService
import backend.model.misc.Coords
import backend.view.EventView
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.*
import java.time.LocalDateTime
import java.time.ZoneOffset
import javax.validation.Valid
import kotlin.collections.map

@RestController
@RequestMapping("/event")
class EventController {

    val eventService: EventService

    @Autowired
    constructor(eventService: EventService) {
        this.eventService = eventService
    }

    @ResponseStatus(HttpStatus.CREATED)
    @RequestMapping(
            value = "/",
            method = arrayOf(RequestMethod.POST),
            produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
    fun createEvent(@Valid @RequestBody body: EventView): EventView {

        val event = eventService.createEvent(
                title = body.title!!,
                date = LocalDateTime.ofEpochSecond(body.date!!, 0, ZoneOffset.UTC),
                city = body.city!!,
                duration = body.duration,
                startingLocation = Coords(body.startingLocation!!.latitude!!, body.startingLocation!!.longitude!!))

        return EventView(event)
    }

    @RequestMapping(
            value = "/",
            method = arrayOf(RequestMethod.GET),
            produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
    fun getAllEvents(): Iterable<EventView> {
        return eventService.findAll().map { EventView(it) }
    }
}


package org.jetbrains.ktor.cio

import java.io.*
import java.nio.*

interface Channel : Closeable

interface ReadChannel : Channel {
    suspend fun read(dst: ByteBuffer): Int
}

interface WriteChannel : Channel {
    suspend fun write(src: ByteBuffer)
    suspend fun flush()
}

interface RandomAccessReadChannel : ReadChannel {
    val position: Long
    val size: Long

    suspend fun seek(position: Long)
}

suspend fun ReadChannel.copyTo(out: WriteChannel, bufferPool: ByteBufferPool = NoPool, bufferSize: Int = 8192): Int {
    val bufferTicket = bufferPool.allocate(bufferSize)
    val buffer = bufferTicket.buffer
    var bytes = 0
    try {
        while (read(buffer).also { bytes += it } != -1) {
            buffer.flip()
            out.write(buffer)
            buffer.clear()
        }
    } finally {
        bufferPool.release(bufferTicket)
    }
    return bytes + 1 // compensate for -1 as EOF
}

open class ChannelIOException(message: String, exception: Exception) : Exception(message, exception)
class ChannelWriteException(message: String = "Cannot write to a channel", exception: Exception) : ChannelIOException(message, exception)
class ChannelReadException(message: String = "Cannot read from a channel", exception: Exception) : ChannelIOException(message, exception)

Change supertype for ChannelIOException so it is IOException now

package org.jetbrains.ktor.cio

import java.io.*
import java.nio.*

interface Channel : Closeable

interface ReadChannel : Channel {
    suspend fun read(dst: ByteBuffer): Int
}

interface WriteChannel : Channel {
    suspend fun write(src: ByteBuffer)
    suspend fun flush()
}

interface RandomAccessReadChannel : ReadChannel {
    val position: Long
    val size: Long

    suspend fun seek(position: Long)
}

suspend fun ReadChannel.copyTo(out: WriteChannel, bufferPool: ByteBufferPool = NoPool, bufferSize: Int = 8192): Int {
    val bufferTicket = bufferPool.allocate(bufferSize)
    val buffer = bufferTicket.buffer
    var bytes = 0
    try {
        while (read(buffer).also { bytes += it } != -1) {
            buffer.flip()
            out.write(buffer)
            buffer.clear()
        }
    } finally {
        bufferPool.release(bufferTicket)
    }
    return bytes + 1 // compensate for -1 as EOF
}

open class ChannelIOException(message: String, exception: Exception) : IOException(message, exception)
class ChannelWriteException(message: String = "Cannot write to a channel", exception: Exception) : ChannelIOException(message, exception)
class ChannelReadException(message: String = "Cannot read from a channel", exception: Exception) : ChannelIOException(message, exception)


/*
 * 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.java16),
    SANTA_TRACKER_SMOKE_TEST_VERSION(JvmVendor.oracle, JvmVersion.java11),
    EXPERIMENTAL_VERSION(JvmVendor.oracle, JvmVersion.java17)
}

Fix vendor for Santa Tracker smoke test jvm

/*
 * 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.java16),
    SANTA_TRACKER_SMOKE_TEST_VERSION(JvmVendor.openjdk, JvmVersion.java11),
    EXPERIMENTAL_VERSION(JvmVendor.oracle, JvmVersion.java17)
}


package org.purescript.psi

import com.intellij.lang.ASTNode

class PSExportList(node: ASTNode) : PSPsiElement(node)

Add exported items to export lists

package org.purescript.psi

import com.intellij.lang.ASTNode

class PSExportList(node: ASTNode) : PSPsiElement(node) {
    val exportedItems = findChildrenByClass(PSExportedItem::class.java)
}


Add simple test for spreadsheet builder DSL

package com.github.fwilhe.incell

import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test

internal class SheetTest {
    @Test
    fun spreadsheetBuilder() {
        val expected = Sheet(listOf(Column("constant value", { 1.11 }))).row(0)
        val sheet = spreadsheet { column("constant value", { 1.11 }) }.row(0)
        assertEquals(expected, sheet)
    }
}


object PluginVersions {
    val kotlin = "1.3.31"
    val ktlintPlugin = "7.4.0"
    val gradlePublishPlugin = "0.10.1"
    val androidPlugin = "3.4.0"
    val semver = "1.1.1"
    val gradleWrapper = "5.4"
    val junit5 = "5.4.0"
    val assertJ = "3.11.1"
}

Apply latest version of plugin on itself.

object PluginVersions {
    val kotlin = "1.3.31"
    val ktlintPlugin = "8.0.0"
    val gradlePublishPlugin = "0.10.1"
    val androidPlugin = "3.4.0"
    val semver = "1.1.1"
    val gradleWrapper = "5.4"
    val junit5 = "5.4.0"
    val assertJ = "3.11.1"
}


package io.ktor.utils.io.tests

import io.ktor.utils.io.charsets.*
import io.ktor.utils.io.core.*
import kotlin.test.*

private const val TEXT = "test\u00f0."
private val BYTES = byteArrayOf(0x74, 0x65, 0x73, 0x74, 0xf0.toByte(), 0x2e)

class ISOTest {
    @Test
    fun testEncode() {
        val bytes = Charsets.ISO_8859_1.newEncoder().encode(TEXT).readBytes()
        assertTrue {
            bytes.contentEquals(BYTES)
        }
    }

    @Test
    fun testEncodeUnmappable() {
        assertFailsWith<MalformedInputException> {
            Charsets.ISO_8859_1.newEncoder().encode("\u0422")
        }
    }

    @Test
    fun testDecode() {
        val pkt = ByteReadPacket(BYTES)
        val result = Charsets.ISO_8859_1.newDecoder().decode(pkt)
        assertEquals(TEXT, result)
    }
}

Disable ISO-8859-1 tests in js

package io.ktor.utils.io.tests

import io.ktor.utils.io.charsets.*
import io.ktor.utils.io.core.*
import kotlin.test.*

private const val TEXT = "test\u00f0."
private val BYTES = byteArrayOf(0x74, 0x65, 0x73, 0x74, 0xf0.toByte(), 0x2e)

class ISOTest {
    @Ignore
    @Test
    fun testEncode() {
        val bytes = Charsets.ISO_8859_1.newEncoder().encode(TEXT).readBytes()
        assertTrue {
            bytes.contentEquals(BYTES)
        }
    }

    @Ignore
    @Test
    fun testEncodeUnmappable() {
        assertFailsWith<MalformedInputException> {
            Charsets.ISO_8859_1.newEncoder().encode("\u0422")
        }
    }

    @Ignore
    @Test
    fun testDecode() {
        val pkt = ByteReadPacket(BYTES)
        val result = Charsets.ISO_8859_1.newDecoder().decode(pkt)
        assertEquals(TEXT, result)
    }
}


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

@file:Suppress("PackageDirectoryMismatch")

import org.gradle.api.Project
import org.gradle.kotlin.dsl.extra
import java.util.Properties

object ProjectVersions {
    const val androidBuildTools = "28.0.3"
    const val androidSdk = 28
}

val Project.thisLibraryVersion: String
    get() {
        val key = "splitties.version"
        return rootProject.extra.properties.getOrElse(key) {
            Properties().also {
                it.load(rootProject.file("libraries_version.properties").reader())
            }.getProperty(key).also { value ->
                rootProject.extra.properties[key] = value // Cache it in root project's extra properties.
            }
        } as String
    }

val Project.isDevVersion get() = thisLibraryVersion.contains("-dev-")

Raise compile and target SDK to 29

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

@file:Suppress("PackageDirectoryMismatch")

import org.gradle.api.Project
import org.gradle.kotlin.dsl.extra
import java.util.Properties

object ProjectVersions {
    const val androidBuildTools = "29.0.2"
    const val androidSdk = 29
}

val Project.thisLibraryVersion: String
    get() {
        val key = "splitties.version"
        return rootProject.extra.properties.getOrElse(key) {
            Properties().also {
                it.load(rootProject.file("libraries_version.properties").reader())
            }.getProperty(key).also { value ->
                rootProject.extra.properties[key] = value // Cache it in root project's extra properties.
            }
        } as String
    }

val Project.isDevVersion get() = thisLibraryVersion.contains("-dev-")


package io.polymorphicpanda.kspec

import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import io.polymorphicpanda.kspec.runner.KSpecRunner
import io.polymorphicpanda.kspec.runner.RunNotifier
import io.polymorphicpanda.kspec.support.setupSpec
import org.junit.Test

/**
 * @author Ranie Jade Ramiso
 */
class SharedExampleTest {
    @Test
    fun testSubjectUniqueForEachExample() {

        var subject1: Throwable? = null
        var subject2: Throwable? = null

        val shared = sharedExample<Throwable> {
            it("an example") {
                subject1 = subject
            }

            it("another example") {
                subject2 = subject
            }
        }

        val spec = setupSpec {
            describe(RuntimeException::class) {
                subject { RuntimeException() }
                itBehavesLike(shared)
            }
        }

        val notifier = RunNotifier()
        val runner = KSpecRunner(spec)
        runner.run(notifier)

        assertThat(subject1 !== subject2, equalTo(true))
    }
}


import org.gradle.api.tasks.GradleBuild

fun isProjectDir(candidate: File) =
    candidate.isDirectory && File(candidate, "settings.gradle").exists()

fun isCompatibleWithJDK(candidate: File) =
    candidate.name.endsWith("kotlin-1.0") && JavaVersion.current() < JavaVersion.VERSION_1_9

val subProjectTasks = rootDir
    .listFiles()
    .filter { isProjectDir(it) }
    .filter { isCompatibleWithJDK(it) }
    .map { subProjectDir ->
    task<GradleBuild>("prepare-${subProjectDir.name}") {
        setDir(subProjectDir)
    }
}

setDefaultTasks(subProjectTasks.map { it.name })

Fix indentation in fixtures build file


package org.jetbrains.ktor.netty

import io.netty.channel.*
import kotlin.coroutines.experimental.*

suspend fun ChannelFuture.suspendAwait() {
    if (isDone) return

    suspendCoroutine<Unit> { continuation ->
        addListener { f ->
            try {
                f.get()
                continuation.resume(Unit)
            } catch (t: Throwable) {
                continuation.resumeWithException(t)
            }
        }
    }
}

Fix exception handling in awaiting for a channel future

package org.jetbrains.ktor.netty

import io.netty.channel.*
import kotlin.coroutines.experimental.*

suspend fun ChannelFuture.suspendAwait() {
    if (isDone) return

    suspendCoroutine<Unit> { continuation ->
        addListener { f ->
            try {
                f.get()
            } catch (t: Throwable) {
                continuation.resumeWithException(t)
                return@addListener
            }
            continuation.resume(Unit)
        }
    }
}


package org.jetbrains.dokka.tests

import org.jetbrains.dokka.DocumentationNode
import org.jetbrains.dokka.FileGenerator
import org.jetbrains.dokka.FormatService
import org.jetbrains.dokka.relativeToRoot
import org.junit.Before
import org.junit.Rule
import org.junit.rules.TemporaryFolder

abstract class FileGeneratorTestCase {
    abstract val formatService: FormatService

    @get:Rule
    var folder = TemporaryFolder()

    val fileGenerator = FileGenerator(folder.apply { create() }.root)

    @Before
    fun bindGenerator() {
        fileGenerator.formatService = formatService
    }

    fun buildPagesAndReadInto(nodes: List<DocumentationNode>, sb: StringBuilder) = with(fileGenerator) {
        buildPages(nodes)
        val byLocations = nodes.groupBy { location(it) }
        byLocations.forEach { (loc, _) ->
            if (byLocations.size > 1) {
                sb.appendln("<!-- File: ${relativeToRoot(loc)} -->")
            }
            sb.append(loc.file.readText())
        }
    }
}

Append line before file path in testData

package org.jetbrains.dokka.tests

import org.jetbrains.dokka.DocumentationNode
import org.jetbrains.dokka.FileGenerator
import org.jetbrains.dokka.FormatService
import org.jetbrains.dokka.relativeToRoot
import org.junit.Before
import org.junit.Rule
import org.junit.rules.TemporaryFolder

abstract class FileGeneratorTestCase {
    abstract val formatService: FormatService

    @get:Rule
    var folder = TemporaryFolder()

    val fileGenerator = FileGenerator(folder.apply { create() }.root)

    @Before
    fun bindGenerator() {
        fileGenerator.formatService = formatService
    }

    fun buildPagesAndReadInto(nodes: List<DocumentationNode>, sb: StringBuilder) = with(fileGenerator) {
        buildPages(nodes)
        val byLocations = nodes.groupBy { location(it) }
        byLocations.forEach { (loc, _) ->
            if (byLocations.size > 1) {
                if (sb.isNotBlank() && !sb.endsWith('\n')) {
                    sb.appendln()
                }
                sb.appendln("<!-- File: ${relativeToRoot(loc)} -->")
            }
            sb.append(loc.file.readText())
        }
    }
}


package edu.csh.chase.sprint

import com.squareup.okhttp
import com.squareup.okhttp.Call
import com.squareup.okhttp.Callback
import com.squareup.okhttp.OkHttpClient
import com.squareup.okhttp.Response
import java.io.IOException
import com.squareup.okhttp.Request as OkRequest
import com.squareup.okhttp.Response as OkResponse

class RequestProcessor(val request: Request, private val client: OkHttpClient, val successListener: SprintSuccess?,
                       val failureListener: SprintFailure?) : Callback {

    var currentCall: Call? = null

    private fun buildOkRequest(): OkRequest {
        val builder = OkRequest.Builder()
        //TODO make sure the URL is still valid if the urlParams is null
        builder.url(request.url + request.urlParams?.toString())
        when (request.requestType) {
            RequestType.Get -> builder.get()
            RequestType.Post -> builder.post(request.body)
        }
        request.headers?.forEach { builder.addHeader(it.name, it.value) }
        return builder.build()
    }

    fun executeRequest() {
        val okRequest = buildOkRequest()
        currentCall = client.newCall(okRequest)
        currentCall!!.enqueue(this)
    }

    fun cancelRequest() {
        currentCall?.cancel()
        currentCall = null
    }

    override fun onFailure(request: okhttp.Request?, e: IOException?) {
    }

    override fun onResponse(response: Response?) {
    }

}

Work on response handling from the OkRequest

package edu.csh.chase.sprint

import com.squareup.okhttp
import com.squareup.okhttp.Call
import com.squareup.okhttp.Callback
import com.squareup.okhttp.OkHttpClient
import java.io.IOException
import com.squareup.okhttp.Request as OkRequest
import com.squareup.okhttp.Response as OkResponse

class RequestProcessor(val request: Request, private val client: OkHttpClient, val successListener: SprintSuccess?,
                       val failureListener: SprintFailure?) : Callback {

    var currentCall: Call? = null

    private fun buildOkRequest(): OkRequest {
        val builder = OkRequest.Builder()
        //TODO make sure the URL is still valid if the urlParams is null
        builder.url(request.url + request.urlParams?.toString())
        when (request.requestType) {
            RequestType.Get -> builder.get()
            RequestType.Post -> builder.post(request.body)
        }
        request.headers?.forEach { builder.addHeader(it.name, it.value) }
        return builder.build()
    }

    fun executeRequest() {
        val okRequest = buildOkRequest()
        currentCall = client.newCall(okRequest)
        currentCall!!.enqueue(this)
    }

    fun cancelRequest() {
        currentCall?.cancel()
        currentCall = null
    }

    override fun onFailure(request: okhttp.Request?, e: IOException?) {

    }

    override fun onResponse(response: OkResponse) {
        val statusCode = response.code()
        val body = response.body()
        val headers = response.headers()
    }

}


object Android {
    const val VERSION_CODE = 64
    const val VERSION_NAME = "1.12"
    const val APP_NAME = "de.devisnik.android.mine"

    const val MIN_SDK = 23
    const val TARGET_SDK = 31
    const val COMPILE_SDK = 31

    const val BUILD_TOOLS = "32.0.0"
}

Increment version to 65, 1.13

object Android {
    const val VERSION_CODE = 65
    const val VERSION_NAME = "1.13"
    const val APP_NAME = "de.devisnik.android.mine"

    const val MIN_SDK = 23
    const val TARGET_SDK = 31
    const val COMPILE_SDK = 31

    const val BUILD_TOOLS = "32.0.0"
}


package com.emberjs.utils

import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtilCore.findModuleForFile
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.patterns.PsiElementPattern
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiFilter
import java.util.*

val PsiElement.originalVirtualFile: VirtualFile?
    get() = containingFile.originalFile.virtualFile

val PsiElement.module: Module?
    get() = originalVirtualFile.let { findModuleForFile(it!!, project) }

val PsiElement.emberRoot: VirtualFile?
    get() = module?.emberRoot

val PsiElement.parents: Iterable<PsiElement>
    get() = object : Iterable<PsiElement> {
        override fun iterator(): Iterator<PsiElement> {
            var file = this@parents

            return object : Iterator<PsiElement> {
                override fun hasNext() = file.parent != null
                override fun next(): PsiElement {
                    file = file.parent
                    return file
                }
            }
        }
    }

fun <T : PsiElement> PsiElement.collect(filter: PsiFilter<T>) =
        ArrayList<T>().apply { accept(filter.createVisitor(this)) }

inline fun <reified T : PsiElement> PsiElementPattern.Capture<T>.toFilter() = object : PsiFilter<T>(T::class.java) {
    override fun accept(element: T) = this@toFilter.accepts(element)
}

Apply the suggested change from dwickern's review

package com.emberjs.utils

import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtilCore.findModuleForFile
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.patterns.PsiElementPattern
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiFilter
import java.util.*

val PsiElement.originalVirtualFile: VirtualFile?
    get() = containingFile.originalFile.virtualFile

val PsiElement.module: Module?
    get() = originalVirtualFile?.let { findModuleForFile(it, project) }

val PsiElement.emberRoot: VirtualFile?
    get() = module?.emberRoot

val PsiElement.parents: Iterable<PsiElement>
    get() = object : Iterable<PsiElement> {
        override fun iterator(): Iterator<PsiElement> {
            var file = this@parents

            return object : Iterator<PsiElement> {
                override fun hasNext() = file.parent != null
                override fun next(): PsiElement {
                    file = file.parent
                    return file
                }
            }
        }
    }

fun <T : PsiElement> PsiElement.collect(filter: PsiFilter<T>) =
        ArrayList<T>().apply { accept(filter.createVisitor(this)) }

inline fun <reified T : PsiElement> PsiElementPattern.Capture<T>.toFilter() = object : PsiFilter<T>(T::class.java) {
    override fun accept(element: T) = this@toFilter.accepts(element)
}


package com.satsumasoftware.timetable.framework

import java.util.*

class Assignment(val id: Int, val title: String, val detail: String, val dueDate: Date)

Use org.threeten.bp.LocalDate instead of java.util.Date

package com.satsumasoftware.timetable.framework

import org.threeten.bp.LocalDate

class Assignment(val id: Int, val title: String, val detail: String, val dueDate: LocalDate)


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

package org.toml.lang

import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.util.io.ByteSequence
import com.intellij.openapi.vfs.VirtualFile
import org.toml.lang.psi.TomlFileType

class TomlFileTypeDetector : FileTypeRegistry.FileTypeDetector {
    override fun getVersion(): Int = 1

    override fun detect(file: VirtualFile, firstBytes: ByteSequence, firstCharsIfText: CharSequence?): FileType? =
        if (file.name == "config" && file.parent?.name == ".cargo") TomlFileType else null
}

Use performance optimizations provided by FileTypeDetector API not to slow down IDEs using TOML plugin

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

package org.toml.lang

import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.util.io.ByteSequence
import com.intellij.openapi.vfs.VirtualFile
import org.toml.lang.psi.TomlFileType

class TomlFileTypeDetector : FileTypeRegistry.FileTypeDetector {
    override fun getVersion() = 1

    override fun detect(file: VirtualFile, firstBytes: ByteSequence, firstCharsIfText: CharSequence?): FileType? =
        if (file.name == "config" && file.parent?.name == ".cargo") TomlFileType else null

    override fun getDetectedFileTypes() = listOf(TomlFileType)

    override fun getDesiredContentPrefixLength() = 0
}


pluginManagement {
    repositories {
        gradlePluginPortal()
    }
    plugins {
        id("com.diffplug.eclipse.apt") version "3.34.1"
        id("com.diffplug.spotless") version "6.1.0"
        id("io.github.gradle-nexus.publish-plugin") version "1.1.0"
        id("net.researchgate.release") version "2.8.1"
        id("org.seasar.doma.compile") version "1.1.0"
        kotlin("jvm") version "1.6.10"
        kotlin("kapt") version "1.6.10"
    }
}

rootProject.name = "doma"

include("doma-core")
include("doma-kotlin")
include("doma-mock")
include("doma-processor")
include("doma-slf4j")

include("integration-test-common")
include("integration-test-java")
include("integration-test-java-latest")
include("integration-test-kotlin")

Update plugin com.diffplug.spotless to v6.1.2

pluginManagement {
    repositories {
        gradlePluginPortal()
    }
    plugins {
        id("com.diffplug.eclipse.apt") version "3.34.1"
        id("com.diffplug.spotless") version "6.1.2"
        id("io.github.gradle-nexus.publish-plugin") version "1.1.0"
        id("net.researchgate.release") version "2.8.1"
        id("org.seasar.doma.compile") version "1.1.0"
        kotlin("jvm") version "1.6.10"
        kotlin("kapt") version "1.6.10"
    }
}

rootProject.name = "doma"

include("doma-core")
include("doma-kotlin")
include("doma-mock")
include("doma-processor")
include("doma-slf4j")

include("integration-test-common")
include("integration-test-java")
include("integration-test-java-latest")
include("integration-test-kotlin")


/*
 * 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.
 */
import org.gradle.gradlebuild.unittestandcompile.ModuleType

plugins {
    `java-library`
     gradlebuild.classycle
}

description = "Tools to take immutable, comparable snapshots of files and other things"

dependencies {
    implementation(project(":baseServices"))
    implementation(project(":native"))
    implementation(project(":messaging"))
    implementation(project(":coreApi"))
    implementation(project(":files"))
    implementation(project(":persistentCache"))
    implementation(project(":modelCore"))

    implementation(library("guava"))
    implementation(library("jsr305"))
    implementation(library("inject"))

    testImplementation(project(":processServices"))
    testImplementation(project(":resources"))
    testImplementation(library("ant"))
}

gradlebuildJava {
    moduleType = ModuleType.CORE
}

testFixtures {
    from(":baseServices")
    from(":files")
    from(":messaging")
    from(":core")
    from(":coreApi")
}

Remove dependency snapshots -> files

/*
 * 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.
 */
import org.gradle.gradlebuild.unittestandcompile.ModuleType

plugins {
    `java-library`
     gradlebuild.classycle
}

description = "Tools to take immutable, comparable snapshots of files and other things"

dependencies {
    implementation(project(":baseServices"))
    implementation(project(":native"))
    implementation(project(":messaging"))
    implementation(project(":coreApi"))
    implementation(project(":persistentCache"))
    implementation(project(":modelCore"))

    implementation(library("guava"))
    implementation(library("jsr305"))
    implementation(library("inject"))

    testImplementation(project(":processServices"))
    testImplementation(project(":resources"))
    testImplementation(library("ant"))
}

gradlebuildJava {
    moduleType = ModuleType.CORE
}

testFixtures {
    from(":baseServices")
    from(":files")
    from(":messaging")
    from(":core")
    from(":coreApi")
}


package net.squanchy.notification

import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import net.squanchy.schedule.domain.view.Event
import net.squanchy.service.firebase.FirebaseAuthService
import net.squanchy.service.repository.EventRepository
import java.util.Collections
import java.util.Comparator

internal class NotificationService(private val authService: FirebaseAuthService, private val eventRepository: EventRepository) {

    fun sortedFavourites(): Observable<List<Event>> {
        return authService.ifUserSignedInThenObservableFrom { userId ->
            eventRepository.events(userId)
                    .map { events -> events.filter { it.favorited } }
                    .map { events ->
                        Collections.sort(events, byStartDate())
                        events
                    }
                    .take(1)
                    .subscribeOn(Schedulers.io())
        }
    }

    private fun byStartDate(): Comparator<Event> {
        return kotlin.Comparator { event, otherEvent -> event.startTime.compareTo(otherEvent.startTime) }
    }
}

Use sortedBy instead of comparatorˆ

package net.squanchy.notification

import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import net.squanchy.schedule.domain.view.Event
import net.squanchy.service.firebase.FirebaseAuthService
import net.squanchy.service.repository.EventRepository

internal class NotificationService(private val authService: FirebaseAuthService, private val eventRepository: EventRepository) {

    fun sortedFavourites(): Observable<List<Event>> {
        return authService.ifUserSignedInThenObservableFrom { userId ->
            eventRepository.events(userId)
                    .map { it.filter { it.favorited } }
                    .map { it.sortedBy { it.startTime } }
                    .take(1)
                    .subscribeOn(Schedulers.io())
        }
    }

}


Add type aliases for Kotlin and a simple extension function.

@file:JvmName("NumberUtils")
package org.nwapw.abacus.number

typealias PromotionFunction = java.util.function.Function<NumberInterface, NumberInterface>
typealias PromotionPath = List<PromotionFunction>
typealias NumberClass = Class<NumberInterface>

fun PromotionPath.promote(from: NumberInterface): NumberInterface {
    return fold(from, { current, function -> function.apply(current) })
}


package Kotlin101.Objects.Delegation

//This is a neat little feature being able to automatically assign an object to handle any trait

fun main(args : Array<String>) {
    var me = BruceWayne(Batman(), RichyRich())
    me.inWater()
    print("Is awesomely rich? " + me.isAwesomelyRich())
}

trait Superpower {
    fun inWater()
    fun onAir()
    fun onSoil()
}

trait Wealth {
    fun isAwesomelyRich () : Boolean
}

public class Batman() : Superpower{
    class object {
        fun create() = Batman()
    }

    override fun inWater(){
        println("Ack, cannot swim")
    }

    override fun onAir(){
        println("Requires vehicle")
    }

    override fun onSoil(){
        println("Awesome")
    }

    fun isFun() : Boolean{
        return false
    }
}

public class RichyRich : Wealth{
    override fun isAwesomelyRich(): Boolean {
        return true
    }
}

public class BruceWayne(a : Batman, b : RichyRich) : Superpower by a, Wealth by b


Implement notification to suggest using Run Dashboard

// 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.
@file: JvmName("SuggestUsingRunDashBoardUtil")
package com.intellij.execution

import com.intellij.execution.configurations.ConfigurationType
import com.intellij.execution.dashboard.RunDashboardManager
import com.intellij.icons.AllIcons
import com.intellij.notification.*
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.project.Project

/**
* If Run Dashboard is not configured for [configurationTypes], show [Notification] allowing to enable dashboard for those configurations.
**/
fun promptUserToUseRunDashboard(project: Project, configurationTypes: Collection<ConfigurationType>) {
  ApplicationManager.getApplication().invokeLater {
    val currentTypes = RunDashboardManager.getInstance(project).types
    val typesToAdd = configurationTypes.filter {
      it.id !in currentTypes
    }
    if (typesToAdd.isNotEmpty()) {
      Notifications.Bus.notify(SuggestDashboardNotification(project, typesToAdd.toSet()), project)
    }
  }
}

private const val suggestRunDashboardId = "Suggest Run Dashboard"

private class SuggestDashboardNotification(
  private val project: Project,
  private val types: Set<ConfigurationType>
) : Notification(
  suggestRunDashboardId,
  AllIcons.General.Run,
  "Use Run Dashboard?",
  null,
  "Run Dashboard is convenient for viewing results of multiple run configuration at once. " +
  "Add the following configuration types to Run Dashboard:
" +
  types.joinToString(prefix = "", postfix = "", separator = "
") { it.configurationTypeDescription } + "
?",
  NotificationType.INFORMATION,
  { _, _ -> }
) {
  init {
    addAction(NotificationAction.create("Yes") { _ ->
      ApplicationManager.getApplication().invokeLater {
        runWriteAction {
          val runDashboardManager = RunDashboardManager.getInstance(project)
          runDashboardManager.types = runDashboardManager.types + types.map { it.id }
        }
      }
      expire()
    })
    addAction(NotificationAction.create("Not this time") { _ ->
      expire()
    })
    addAction(NotificationAction.create("Do not ask again") { _ ->
      NotificationsConfiguration.getNotificationsConfiguration().changeSettings(
        suggestRunDashboardId, NotificationDisplayType.NONE, true, false
      )
      expire()
    })
  }
}


package net.kenro.ji.jin.purescript.icons

import com.intellij.openapi.util.IconLoader

interface PSIcons {
    companion object {
        val FILE = IconLoader.getIcon("/icons/pure.png")
    }
}

Remove deprecation warning by adding class as argument to getIcon

package net.kenro.ji.jin.purescript.icons

import com.intellij.openapi.util.IconLoader

interface PSIcons {
    companion object {
        val FILE = IconLoader.getIcon("/icons/pure.png", PSIcons::class.java)
    }
}


package net.moltendorf.bukkit.intellidoors.settings

import net.moltendorf.bukkit.intellidoors.log

private const val SETTINGS_VERSION = 5

fun upgradeSettings(settings: GlobalSettings) {
  var versions = 0

  for (i in settings.version..SETTINGS_VERSION) {
    upgrade[i]?.invoke(settings) ?: continue

    ++versions
  }

  settings.version = SETTINGS_VERSION

  if (versions > 0) {
    val plural = if (versions > 1) "s" else ""

    log.warning("Your config is $versions version$plural out of date. New values have been inferred.")
    log.warning("It is recommended to back up your config and delete it so the latest can be generated.")
  }
}

val upgrade = mapOf(
  Pair(5, fun(settings: GlobalSettings) {
    val ironTrapdoor = settings["iron-trapdoor"] ?: return

    // The settings loader needs refactoring badly so we'll just hack this in.
    ironTrapdoor.pair.interact = ironTrapdoor.single.interact
  })
)

Fix warning about config version being wrong

package net.moltendorf.bukkit.intellidoors.settings

import net.moltendorf.bukkit.intellidoors.log

private const val SETTINGS_VERSION = 5

fun upgradeSettings(settings: GlobalSettings) {
  if (settings.version < SETTINGS_VERSION) {
    var versions = 0

    for (i in settings.version + 1..SETTINGS_VERSION) {
      upgrade[i]?.invoke(settings) ?: continue

      ++versions
    }

    settings.version = SETTINGS_VERSION

    if (versions > 0) {
      val plural = if (versions > 1) "s" else ""

      log.warning("Your config is $versions version$plural out of date. New values have been inferred.")
      log.warning("It is recommended to back up your config and delete it so the latest can be generated.")
    }
  }
}

val upgrade = mapOf(
  Pair(5, fun(settings: GlobalSettings) {
    val ironTrapdoor = settings["iron-trapdoor"] ?: return

    // The settings loader needs refactoring badly so we'll just hack this in.
    ironTrapdoor.pair.interact = ironTrapdoor.single.interact
  })
)


package org.amshove.kluent.tests.backtickassertions

import org.amshove.kluent.`should throw`
import org.jetbrains.spek.api.Spek
import kotlin.test.assertFails

class ShouldThrowTests : Spek({
    given("the should throw method") {
        on("expecting the thrown exception") {
            it("should pass") {
                val func = { throw IndexOutOfBoundsException() }
                func `should throw` IndexOutOfBoundsException::class
            }
        }
        on("expection another exception") {
            it("should fail") {
                val func = { throw IndexOutOfBoundsException() }
                assertFails({ func `should throw` IllegalArgumentException::class })
            }
        }
    }
})

Add BacktickAssertion Test for should throw

package org.amshove.kluent.tests.backtickassertions

import org.amshove.kluent.`should throw`
import org.jetbrains.spek.api.Spek
import java.util.*
import kotlin.test.assertFails

class ShouldThrowTests : Spek({
    given("the should throw method") {
        on("expecting the thrown exception") {
            it("should pass") {
                val func = { throw IndexOutOfBoundsException() }
                func `should throw` IndexOutOfBoundsException::class
            }
        }
        on("expection another exception") {
            it("should fail") {
                val func = { throw IndexOutOfBoundsException() }
                assertFails({ func `should throw` IllegalArgumentException::class })
            }
        }
        on("trying to get an out of indexed item in an empty list") {
            val funcWithReturn = { ArrayList<String>().get(-1) }
            it("should pass a failing test") {
                funcWithReturn `should throw` ArrayIndexOutOfBoundsException::class
            }
        }
    }
})


package org.stepic.droid.configuration

object RemoteConfig {
    const val PREFIX = "remote_config_"

    const val MIN_DELAY_RATE_DIALOG_SEC = "min_delay_rate_dialog_sec"
    const val SHOW_STREAK_DIALOG_AFTER_LOGIN = "show_streak_dialog_after_login"
    const val ADAPTIVE_COURSES = "adaptive_courses_android"
    const val ADAPTIVE_BACKEND_URL = "adaptive_backend_url"
    const val IS_LOCAL_SUBMISSIONS_ENABLED = "is_local_submissions_enabled"
    const val SEARCH_QUERY_PARAMS_ANDROID = "search_query_params_android"
    const val IS_NEW_HOME_SCREEN_ENABLED = "is_new_home_screen_enabled"
    const val PERSONALIZED_ONBOARDING_COURSE_LISTS = "personalized_onboarding_course_lists"
    const val IS_COURSE_REVENUE_AVAILABLE_ANDROID = "is_course_revenue_available_android"
    const val PURCHASE_FLOW_ANDROID = "purchase_flow_android"

    // TODO APPS-3443: Remove after finishing feature
    const val PURCHASE_FLOW_ANDROID_TESTING_FLAG = true
}

Disable purchase flow testing flag

package org.stepic.droid.configuration

object RemoteConfig {
    const val PREFIX = "remote_config_"

    const val MIN_DELAY_RATE_DIALOG_SEC = "min_delay_rate_dialog_sec"
    const val SHOW_STREAK_DIALOG_AFTER_LOGIN = "show_streak_dialog_after_login"
    const val ADAPTIVE_COURSES = "adaptive_courses_android"
    const val ADAPTIVE_BACKEND_URL = "adaptive_backend_url"
    const val IS_LOCAL_SUBMISSIONS_ENABLED = "is_local_submissions_enabled"
    const val SEARCH_QUERY_PARAMS_ANDROID = "search_query_params_android"
    const val IS_NEW_HOME_SCREEN_ENABLED = "is_new_home_screen_enabled"
    const val PERSONALIZED_ONBOARDING_COURSE_LISTS = "personalized_onboarding_course_lists"
    const val IS_COURSE_REVENUE_AVAILABLE_ANDROID = "is_course_revenue_available_android"
    const val PURCHASE_FLOW_ANDROID = "purchase_flow_android"

    // TODO APPS-3443: Remove after finishing feature
    const val PURCHASE_FLOW_ANDROID_TESTING_FLAG = false
}