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

import org.gradle.api.internal.project.ProjectInternal

import org.gradle.configuration.project.ProjectConfigureAction

import org.gradle.kotlin.dsl.resolver.kotlinBuildScriptModelTask
import org.gradle.kotlin.dsl.support.serviceOf

import org.gradle.tooling.provider.model.ToolingModelBuilderRegistry

class KotlinScriptingModelBuildersRegistrationAction : ProjectConfigureAction {

    override fun execute(project: ProjectInternal) {
        project.serviceOf<ToolingModelBuilderRegistry>().apply {
            register(KotlinBuildScriptModelBuilder)
            register(KotlinBuildScriptTemplateModelBuilder)
        }
        project.tasks.apply {
            register(kotlinBuildScriptModelTask) {
                it.group = "other"
            }
        }
    }
}

Revert "Set `prepareKotlinBuildScriptModel` task group explicitly"

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

import org.gradle.api.internal.project.ProjectInternal

import org.gradle.configuration.project.ProjectConfigureAction

import org.gradle.kotlin.dsl.resolver.kotlinBuildScriptModelTask
import org.gradle.kotlin.dsl.support.serviceOf

import org.gradle.tooling.provider.model.ToolingModelBuilderRegistry

class KotlinScriptingModelBuildersRegistrationAction : ProjectConfigureAction {

    override fun execute(project: ProjectInternal) {
        project.serviceOf<ToolingModelBuilderRegistry>().apply {
            register(KotlinBuildScriptModelBuilder)
            register(KotlinBuildScriptTemplateModelBuilder)
        }
        project.tasks.apply {
            register(kotlinBuildScriptModelTask)
        }
    }
}


/*
 * Minecraft Dev for IntelliJ
 *
 * https://minecraftdev.org
 *
 * Copyright (c) 2017 minecraft-dev
 *
 * MIT License
 */

package com.demonwav.mcdev.nbt.lang.colors

class NbttSyntaxHighlighterFactory : com.intellij.openapi.fileTypes.SyntaxHighlighterFactory() {
    override fun getSyntaxHighlighter(project: com.intellij.openapi.project.Project?, virtualFile: com.intellij.openapi.vfs.VirtualFile?) = NbttSyntaxHighlighter()
}

Fix lack of imports for some reason

/*
 * Minecraft Dev for IntelliJ
 *
 * https://minecraftdev.org
 *
 * Copyright (c) 2017 minecraft-dev
 *
 * MIT License
 */

package com.demonwav.mcdev.nbt.lang.colors

import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile

class NbttSyntaxHighlighterFactory : SyntaxHighlighterFactory() {
    override fun getSyntaxHighlighter(project: Project?, virtualFile: VirtualFile?) = NbttSyntaxHighlighter()
}


// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.completion.settings

import com.intellij.application.options.CodeCompletionOptionsCustomSection
import com.intellij.completion.StatsCollectorBundle
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.options.BoundConfigurable
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.layout.*

class MLRankingConfigurable(private val supportedLanguages: List<String>)
  : BoundConfigurable("ML Ranking") {
  private val settings = CompletionMLRankingSettings.getInstance()

  override fun createPanel(): DialogPanel {
    return panel {
      titledRow(StatsCollectorBundle.message("ml.completion.settings.group")) {
        row {
          val enableRanking = checkBox(StatsCollectorBundle.message("ml.completion.enable"), settings::isRankingEnabled,
                                       { settings.isRankingEnabled = it })
          for (language in supportedLanguages) {
            row {
              checkBox(language, { settings.isLanguageEnabled(language) }, { settings.setLanguageEnabled(language, it) })
                .enableIf(enableRanking.selected)
            }
          }
        }
        val registry = Registry.get("completion.stats.show.ml.ranking.diff")
        row {
          checkBox(StatsCollectorBundle.message("ml.completion.show.diff"),
                   { registry.asBoolean() },
                   { registry.setValue(it) })
        }
      }
    }
  }
}

Disable 'showing diff checkbox' if ranking is disabled

// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.completion.settings

import com.intellij.completion.StatsCollectorBundle
import com.intellij.openapi.options.BoundConfigurable
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.layout.*

class MLRankingConfigurable(private val supportedLanguages: List<String>)
  : BoundConfigurable("ML Ranking") {
  private val settings = CompletionMLRankingSettings.getInstance()

  override fun createPanel(): DialogPanel {
    return panel {
      var enableRankingCheckbox: CellBuilder<JBCheckBox>? = null
      titledRow(StatsCollectorBundle.message("ml.completion.settings.group")) {
        row {
          val enableRanking = checkBox(StatsCollectorBundle.message("ml.completion.enable"), settings::isRankingEnabled,
                                       { settings.isRankingEnabled = it })
          for (language in supportedLanguages) {
            row {
              checkBox(language, { settings.isLanguageEnabled(language) }, { settings.setLanguageEnabled(language, it) })
                .enableIf(enableRanking.selected)
            }
          }
          enableRankingCheckbox = enableRanking
        }
        val registry = Registry.get("completion.stats.show.ml.ranking.diff")
        row {
          enableRankingCheckbox?.let { enableRanking ->
            checkBox(StatsCollectorBundle.message("ml.completion.show.diff"),
                     { registry.asBoolean() },
                     { registry.setValue(it) }).enableIf(enableRanking.selected)
          }

        }
      }
    }
  }
}


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

plugins {
    id("com.android.library")
    kotlin("multiplatform")
    `maven-publish`
}

android {
    setDefaults()
    buildTypes.getByName("release").consumerProguardFiles("proguard-rules.pro")
}

kotlin {
    android()
    macos()
    ios()
    configure(targets) { configureMavenPublication() }
    setupSourceSets()
    sourceSets {
        commonMain.dependencies {
            api(splitties("experimental"))
            compileOnly(Libs.kotlinX.coroutines.coreCommon)
        }
        commonTest {
            dependencies {
                implementation(project(":test-helpers"))
            }
        }
        androidMain.dependencies {
            api(splitties("appctx"))

            api(Libs.kotlin.stdlibJdk7)
            compileOnly(Libs.kotlinX.coroutines.android)
        }
        nativeMain {
            dependencies {
                api(Libs.kotlinX.coroutines.coreNative)
            }
        }
        appleMain {
            dependencies {
                implementation(splitties("mainthread"))
            }
        }
        all {
            languageSettings.apply {
                useExperimentalAnnotation("kotlin.Experimental")
            }
        }
        commonTest {
            dependencies {
                implementation(kotlin("test-common"))
                implementation(kotlin("test-annotations-common"))
            }
        }
        androidTest {
            dependencies {
                implementation(Libs.kotlin.testJunit)
            }
        }
    }
}

afterEvaluate {
    publishing {
        setupAllPublications(project)
    }
}

Add AndroidX test runner dependency

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

plugins {
    id("com.android.library")
    kotlin("multiplatform")
    `maven-publish`
}

android {
    setDefaults()
    buildTypes.getByName("release").consumerProguardFiles("proguard-rules.pro")
}

kotlin {
    android()
    macos()
    ios()
    configure(targets) { configureMavenPublication() }
    setupSourceSets()
    sourceSets {
        commonMain.dependencies {
            api(splitties("experimental"))
            compileOnly(Libs.kotlinX.coroutines.coreCommon)
        }
        commonTest {
            dependencies {
                implementation(project(":test-helpers"))
            }
        }
        androidMain.dependencies {
            api(splitties("appctx"))

            api(Libs.kotlin.stdlibJdk7)
            compileOnly(Libs.kotlinX.coroutines.android)
        }
        nativeMain {
            dependencies {
                api(Libs.kotlinX.coroutines.coreNative)
            }
        }
        appleMain {
            dependencies {
                implementation(splitties("mainthread"))
            }
        }
        all {
            languageSettings.apply {
                useExperimentalAnnotation("kotlin.Experimental")
            }
        }
        commonTest {
            dependencies {
                implementation(kotlin("test-common"))
                implementation(kotlin("test-annotations-common"))
            }
        }
        androidTest {
            dependencies {
                implementation(Libs.kotlin.testJunit)
            }
        }
    }
}

dependencies {
    androidTestImplementation(Libs.androidX.test.runner)
}

afterEvaluate {
    publishing {
        setupAllPublications(project)
    }
}


package com.projectcitybuild.spigot.modules.ranks

import com.projectcitybuild.entities.models.Group

object RankMapper {

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

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

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

        return permissionGroups.toList()
    }

}

Add Trusted+ rank to mapping

package com.projectcitybuild.spigot.modules.ranks

import com.projectcitybuild.entities.models.Group

object RankMapper {

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

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

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

        return permissionGroups.toList()
    }

}


package v_builders

import util.TODO
import util.doc39
import v_builders.data.getProducts
import v_builders.htmlLibrary.*

fun getTitleColor() = "#b9c9fe"
fun getCellColor(row: Int, column: Int) = if ((row + column) %2 == 0) "#dce4ff" else "#eff2ff"

fun todoTask39(): Nothing = TODO(
    """
        Task 39.
        1) Fill the table with the proper values from products.
        2) Color the table like a chess board (using getTitleColor() and getCellColor() functions above).
        Pass a color as an argument to functions 'tr', 'td'.
        You can run the 'Html Demo' configuration in IntelliJ IDEA to see the rendered table.
    """,
    documentation = doc39()
)

fun renderProductTable(): String {
    return html {
        table {
            tr {
                td {
                    text("Product")
                }
                td {
                    text("Price")
                }
                td {
                    text("Popularity")
                }
            }
            val products = getProducts()
            todoTask39()
        }
    }.toString()
}

Complete koan 39 (HTML builders)

package v_builders

import util.TODO
import util.doc39
import v_builders.data.getProducts
import v_builders.htmlLibrary.*

fun getTitleColor() = "#b9c9fe"
fun getCellColor(row: Int, column: Int) = if ((row + column) %2 == 0) "#dce4ff" else "#eff2ff"

fun todoTask39(): Nothing = TODO(
    """
        Task 39.
        1) Fill the table with the proper values from products.
        2) Color the table like a chess board (using getTitleColor() and getCellColor() functions above).
        Pass a color as an argument to functions 'tr', 'td'.
        You can run the 'Html Demo' configuration in IntelliJ IDEA to see the rendered table.
    """,
    documentation = doc39()
)

fun renderProductTable(): String {
    return html {
        table {
            tr(color = getTitleColor()) {
                td {
                    text("Product")
                }
                td {
                    text("Price")
                }
                td {
                    text("Popularity")
                }
            }
            val products = getProducts()
            products.forEachIndexed { index, product ->
                tr {
                    td(color = getCellColor(1, 1)) {
                        text(product.description)
                    }
                    td(color = getCellColor(1, 2)) {
                        text(product.price)
                    }
                    td(color = getCellColor(1, 3)) {
                        text(product.popularity)
                    }
                }
            }
        }
    }.toString()
}


@file:JvmName("UserRepository")

package backend.model.user

import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.CrudRepository
import org.springframework.data.repository.query.Param

interface UserRepository : CrudRepository<UserCore, Long> {
    fun findByEmail(email: String): User

    fun findByActivationToken(token: String): User

    @Query("select case when count(e) > 0 then true else false end from UserCore e where e.email = ?1")
    fun existsByEmail(email: String): Boolean

    @Query("from UserCore u where u.firstname like concat('%',:search,'%') or u.lastname like concat('%',:search,'%') or u.email like concat('%',:search,'%')")
    fun searchByString(@Param("search") search: String): List<UserCore>
}

Add method to find all sponsors

@file:JvmName("UserRepository")

package backend.model.user

import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.CrudRepository
import org.springframework.data.repository.query.Param

interface UserRepository : CrudRepository<UserCore, Long> {
    fun findByEmail(email: String): User

    fun findByActivationToken(token: String): User

    @Query("select case when count(e) > 0 then true else false end from UserCore e where e.email = ?1")
    fun existsByEmail(email: String): Boolean

    @Query("from UserCore u where u.firstname like concat('%',:search,'%') or u.lastname like concat('%',:search,'%') or u.email like concat('%',:search,'%')")
    fun searchByString(@Param("search") search: String): List<UserCore>

    @Query("from Sponsor s")
    fun findAllSponsors(): Iterable<Sponsor>

}


package ch.rmy.android.http_shortcuts.extensions

import android.content.Context
import android.net.Uri
import ch.rmy.android.http_shortcuts.exceptions.ResponseTooLargeException
import ch.rmy.android.http_shortcuts.utils.SizeLimitedReader
import java.io.BufferedReader
import java.io.InputStreamReader

private const val BUFFER_SIZE = 16384

fun Uri.readIntoString(context: Context, limit: Long): String =
    InputStreamReader(context.contentResolver.openInputStream(this))
        .use { reader ->
            try {
                BufferedReader(SizeLimitedReader(reader, limit), BUFFER_SIZE)
                    .use(BufferedReader::readText)
            } catch (e: SizeLimitedReader.LimitReachedException) {
                throw ResponseTooLargeException(e.limit)
            }
        }

Handle correct exception for large responses

package ch.rmy.android.http_shortcuts.extensions

import android.content.Context
import android.net.Uri
import ch.rmy.android.http_shortcuts.utils.SizeLimitedReader
import java.io.BufferedReader
import java.io.InputStreamReader

private const val BUFFER_SIZE = 16384

fun Uri.readIntoString(context: Context, limit: Long): String =
    InputStreamReader(context.contentResolver.openInputStream(this))
        .use { reader ->
            BufferedReader(SizeLimitedReader(reader, limit), BUFFER_SIZE)
                .use(BufferedReader::readText)
        }


import build.kotlinVersion

plugins {
    `java-gradle-plugin`
}

apply {
    plugin("kotlin")
}

base {
    archivesBaseName = "gradle-script-kotlin-plugins"
}

dependencies {

    implementation(kotlin("stdlib"))
    implementation(kotlin("gradle-plugin"))

    testImplementation(project(":test-fixtures"))
}

tasks {
    "generateEmbeddedKotlinVersionResource" {
        val generatedResourcesDir = "$buildDir/generate-resources/main"
        val versionResourceFile = file("$generatedResourcesDir/embedded-kotlin-version.txt")

        inputs.property("embeddedKotlinVersion", kotlinVersion)
        outputs.file(versionResourceFile)

        val main by java.sourceSets
        main.resources.srcDir(generatedResourcesDir)

        val processResources by tasks
        processResources.dependsOn(this)

        doLast {
            versionResourceFile.parentFile.mkdirs()
            versionResourceFile.writeText(kotlinVersion)
        }
    }
    "test" {
        val customInstallation by rootProject.tasks
        dependsOn(customInstallation)
    }
}

// --- Plugin declaration ----------------------------------------------
val pluginId = "embedded-kotlin"

gradlePlugin {
    (plugins) {
        pluginId {
            id = pluginId
            implementationClass = "org.gradle.script.lang.kotlin.plugins.embedded.EmbeddedKotlinPlugin"
        }
    }
}

// --- Utility functions -----------------------------------------------
fun kotlin(module: String) = "org.jetbrains.kotlin:kotlin-$module:$kotlinVersion"

Add plugin publication to the portal

import build.kotlinVersion

plugins {
    `java-gradle-plugin`
    id("com.gradle.plugin-publish") version "0.9.7"
}

apply {
    plugin("kotlin")
}

base {
    archivesBaseName = "gradle-script-kotlin-plugins"
}

dependencies {

    implementation(kotlin("stdlib"))
    implementation(kotlin("gradle-plugin"))

    testImplementation(project(":test-fixtures"))
}

tasks {
    "generateEmbeddedKotlinVersionResource" {
        val generatedResourcesDir = "$buildDir/generate-resources/main"
        val versionResourceFile = file("$generatedResourcesDir/embedded-kotlin-version.txt")

        inputs.property("embeddedKotlinVersion", kotlinVersion)
        outputs.file(versionResourceFile)

        val main by java.sourceSets
        main.resources.srcDir(generatedResourcesDir)

        val processResources by tasks
        processResources.dependsOn(this)

        doLast {
            versionResourceFile.parentFile.mkdirs()
            versionResourceFile.writeText(kotlinVersion)
        }
    }
    "test" {
        val customInstallation by rootProject.tasks
        dependsOn(customInstallation)
    }
}

// --- Plugin declaration ----------------------------------------------
val pluginId = "embedded-kotlin"

gradlePlugin {
    (plugins) {
        pluginId {
            id = pluginId
            implementationClass = "org.gradle.script.lang.kotlin.plugins.embedded.EmbeddedKotlinPlugin"
        }
    }
}

pluginBundle {
    (plugins) {
        pluginId {
            id = pluginId
            displayName = "Embedded Kotlin Gradle Plugin"
        }
    }
}

// --- Utility functions -----------------------------------------------
fun kotlin(module: String) = "org.jetbrains.kotlin:kotlin-$module:$kotlinVersion"


package me.echeung.moemoekyun.client.network

import me.echeung.moemoekyun.util.system.NetworkUtil
import okhttp3.Interceptor
import okhttp3.OkHttpClient

object NetworkClient {

    private const val HEADER_CONTENT_TYPE = "Content-Type"
    private const val CONTENT_TYPE = "application/json"

    private const val HEADER_ACCEPT = "Accept"
    private const val ACCEPT = "application/vnd.listen.v4+json"

    private const val HEADER_USER_AGENT = "User-Agent"

    val client: OkHttpClient = OkHttpClient.Builder()
            .addNetworkInterceptor(object : Interceptor {
                override fun intercept(chain: Interceptor.Chain): okhttp3.Response {
                    val request = chain.request()

                    val newRequest = request.newBuilder()
                            .addHeader(HEADER_USER_AGENT, NetworkUtil.userAgent)
                            .addHeader(HEADER_CONTENT_TYPE, CONTENT_TYPE)
                            .addHeader(HEADER_ACCEPT, ACCEPT)
                            .build()

                    return chain.proceed(newRequest)
                }
            })
            .build()
}

Remove v4 accept request header

package me.echeung.moemoekyun.client.network

import me.echeung.moemoekyun.util.system.NetworkUtil
import okhttp3.Interceptor
import okhttp3.OkHttpClient

object NetworkClient {

    private const val HEADER_CONTENT_TYPE = "Content-Type"
    private const val CONTENT_TYPE = "application/json"

    private const val HEADER_USER_AGENT = "User-Agent"

    val client: OkHttpClient = OkHttpClient.Builder()
            .addNetworkInterceptor(object : Interceptor {
                override fun intercept(chain: Interceptor.Chain): okhttp3.Response {
                    val request = chain.request()

                    val newRequest = request.newBuilder()
                            .addHeader(HEADER_USER_AGENT, NetworkUtil.userAgent)
                            .addHeader(HEADER_CONTENT_TYPE, CONTENT_TYPE)
                            .build()

                    return chain.proceed(newRequest)
                }
            })
            .build()
}


/*
    The MIT License (MIT)

    FTL-Compiler Copyright (c) 2016 thoma

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
*/
package com.thomas.needham.ftl

import com.thomas.needham.ftl.Utils.CONSOLE_COLOUR_RED
import com.thomas.needham.ftl.Utils.CONSOLE_COLOUR_RESET
import com.thomas.needham.ftl.frontend.EnumCompilerWarnings
import com.thomas.needham.ftl.frontend.Span
import com.thomas.needham.ftl.Utils.CONSOLE_COLOUR_YELLOW
import com.thomas.needham.ftl.frontend.EnumCompilerErrors

object Logger {
    @JvmStatic fun printMessage(string: String) : Unit{
        println(string)
    }

    @JvmStatic fun printWarning(warningType: EnumCompilerWarnings.Warnings, span: Span) : Unit{
        println(CONSOLE_COLOUR_YELLOW + span.toString() + " " + warningType.message + CONSOLE_COLOUR_RESET)
    }

    @JvmStatic fun printError(errorType: EnumCompilerErrors.Errors, span: Span) : Unit{
        println(CONSOLE_COLOUR_RED + span.toString() + " " + errorType.message + CONSOLE_COLOUR_RESET)
    }
}


plugins {
    `java-library`
}

repositories {
    mavenCentral()
}

// tag::dependency-on-bom[]
dependencies {
    // import a BOM
    implementation("org.springframework.boot:spring-boot-dependencies:1.5.8.RELEASE")

    // define dependencies without versions
    implementation("com.google.code.gson:gson")
    implementation("dom4j:dom4j")
}
// end::dependency-on-bom[]

//Note: dom4j also brings in xml-apis as transitive dependency
task<Copy>("copyLibs") {
    from(configurations.compileClasspath)
    into("$buildDir/libs")
}

Fix managingTransitiveDependencies/constraintsFromBOM Kotlin DSL sample

plugins {
    `java-library`
}

repositories {
    mavenCentral()
}

// tag::dependency-on-bom[]
dependencies {
    // import a BOM
    implementation(dependencies.platform("org.springframework.boot:spring-boot-dependencies:1.5.8.RELEASE"))

    // define dependencies without versions
    implementation("com.google.code.gson:gson")
    implementation("dom4j:dom4j")
}
// end::dependency-on-bom[]

//Note: dom4j also brings in xml-apis as transitive dependency
task<Copy>("copyLibs") {
    from(configurations.compileClasspath)
    into("$buildDir/libs")
}


package com.beyondtechnicallycorrect.visitordetector.persistence

import android.content.Context
import com.google.gson.Gson
import timber.log.Timber
import java.io.*
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton

@Singleton
public class DevicePersistence @Inject constructor(
    @Named("applicationContext") val applicationContext: Context,
    val gson: Gson
) {
    fun getSavedDevices(): Devices {
        var devicesAsJson: String = ""
        BufferedReader(InputStreamReader(applicationContext.openFileInput("devices.json"), Charsets.UTF_8)).use {
            reader -> devicesAsJson = reader.readText()
        }
        Timber.v("Retrieved devices.json as %s", devicesAsJson)
        return gson.fromJson(devicesAsJson, Devices::class.java)
    }

    fun saveDevices(devices: Devices) {
        val devicesAsJson = gson.toJson(devices)
        Timber.v("Saving devices.json as %s", devicesAsJson)
        BufferedWriter(OutputStreamWriter(applicationContext.openFileOutput("devices.json", Context.MODE_PRIVATE), Charsets.UTF_8)).use {
            writer -> writer.write(devicesAsJson)
        }
    }
}

Fix app crash when no devices.json file

package com.beyondtechnicallycorrect.visitordetector.persistence

import android.content.Context
import com.google.gson.Gson
import timber.log.Timber
import java.io.*
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton

@Singleton
public class DevicePersistence @Inject constructor(
    @Named("applicationContext") val applicationContext: Context,
    val gson: Gson
) {
    fun getSavedDevices(): Devices {
        if (!applicationContext.getFileStreamPath("devices.json").exists()) {
            return Devices(visitorDevices = listOf(), homeDevices = listOf())
        }
        var devicesAsJson: String = ""
        BufferedReader(InputStreamReader(applicationContext.openFileInput("devices.json"), Charsets.UTF_8)).use {
            reader -> devicesAsJson = reader.readText()
        }
        Timber.v("Retrieved devices.json as %s", devicesAsJson)
        return gson.fromJson(devicesAsJson, Devices::class.java)
    }

    fun saveDevices(devices: Devices) {
        val devicesAsJson = gson.toJson(devices)
        Timber.v("Saving devices.json as %s", devicesAsJson)
        BufferedWriter(OutputStreamWriter(applicationContext.openFileOutput("devices.json", Context.MODE_PRIVATE), Charsets.UTF_8)).use {
            writer -> writer.write(devicesAsJson)
        }
    }
}


useLogger(CustomEventLogger())

class CustomEventLogger() : BuildAdapter(), TaskExecutionListener {

    override fun beforeExecute(task: Task) {
        println("[${task.name}]")
    }

    override fun afterExecute(task: Task, state: TaskState) {
        println()
    }

    override fun buildFinished(result: BuildResult) {
        println("build completed")
        result.failure?.printStackTrace()
    }
}

Fix Kotlin custom logger sample

useLogger(CustomEventLogger())

class CustomEventLogger() : BuildAdapter(), TaskExecutionListener {

    override fun beforeExecute(task: Task) {
        println("[${task.name}]")
    }

    override fun afterExecute(task: Task, state: TaskState) {
        println()
    }

    override fun buildFinished(result: BuildResult) {
        println("build completed")
        if (result.failure != null) {
            result.failure.printStackTrace()
        }
    }
}


package com.github.shiraji.findpullrequest.model

import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.project.Project

object FindPullRequestConfig {
    private const val DEBUG_MODE = "com.github.shiraji.findpullrequest.model.FindPullRequestConfig.DEBUG_MODE"
    private const val OPEN_COMMIT = "com.github.shiraji.findpullrequest.model.FindPullRequestConfig.OPEN_COMMIT"
    private const val JUMP_TO_FILE = "com.github.shiraji.findpullrequest.model.FindPullRequestConfig.JUMP_TO_FILE"
    private const val PROTOCOL = "com.github.shiraji.findpullrequest.model.FindPullRequestConfig.PROTOCOL"

    @JvmStatic
    fun isDebugMode(project: Project) = PropertiesComponent.getInstance(project).getBoolean(DEBUG_MODE, false)

    @JvmStatic
    fun setDebugMode(value: Boolean, project: Project) = PropertiesComponent.getInstance(project).setValue(DEBUG_MODE, value, false)

    @JvmStatic
    fun isJumpToFile(project: Project) = PropertiesComponent.getInstance(project).getBoolean(JUMP_TO_FILE, true)

    @JvmStatic
    fun setJumpToFile(value: Boolean, project: Project) = PropertiesComponent.getInstance(project).setValue(JUMP_TO_FILE, value, true)

    @JvmStatic
    fun getProtocol(project: Project) = PropertiesComponent.getInstance(project).getValue(PROTOCOL, "https://")

    @JvmStatic
    fun setProtocol(value: String, project: Project) = PropertiesComponent.getInstance(project).setValue(PROTOCOL, value, "https://")

}

Add DISABLE constant and remove unused constant

package com.github.shiraji.findpullrequest.model

import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.project.Project

object FindPullRequestConfig {
    private const val DISABLE = "com.github.shiraji.findpullrequest.model.FindPullRequestConfig.DISABLE"
    private const val DEBUG_MODE = "com.github.shiraji.findpullrequest.model.FindPullRequestConfig.DEBUG_MODE"
    private const val JUMP_TO_FILE = "com.github.shiraji.findpullrequest.model.FindPullRequestConfig.JUMP_TO_FILE"
    private const val PROTOCOL = "com.github.shiraji.findpullrequest.model.FindPullRequestConfig.PROTOCOL"

    @JvmStatic
    fun isDebugMode(project: Project) = PropertiesComponent.getInstance(project).getBoolean(DEBUG_MODE, false)

    @JvmStatic
    fun setDebugMode(value: Boolean, project: Project) = PropertiesComponent.getInstance(project).setValue(DEBUG_MODE, value, false)

    @JvmStatic
    fun isJumpToFile(project: Project) = PropertiesComponent.getInstance(project).getBoolean(JUMP_TO_FILE, true)

    @JvmStatic
    fun setJumpToFile(value: Boolean, project: Project) = PropertiesComponent.getInstance(project).setValue(JUMP_TO_FILE, value, true)

    @JvmStatic
    fun getProtocol(project: Project) = PropertiesComponent.getInstance(project).getValue(PROTOCOL, "https://")

    @JvmStatic
    fun setProtocol(value: String, project: Project) = PropertiesComponent.getInstance(project).setValue(PROTOCOL, value, "https://")

}


import org.jlleitschuh.gradle.ktlint.KtlintExtension
import org.jlleitschuh.gradle.ktlint.reporter.ReporterType

plugins {
    application
}

plugins.apply("org.jlleitschuh.gradle.ktlint")
apply {
    plugin("kotlin")
}

application {
    mainClassName = "org.jlleitschuh.gradle.ktlint.sample.kotlin.MainKt"
}

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

configure<KtlintExtension> {
    verbose.set(true)
    outputToConsole.set(true)
    ruleSets.set(listOf("../kotlin-rulesets-creating/build/libs/kotlin-rulesets-creating.jar"))
    reporters.set(setOf(ReporterType.CHECKSTYLE, ReporterType.JSON))
}

tasks.findByName("ktlintMainSourceSetCheck")?.dependsOn(":samples:kotlin-rulesets-creating:build")
tasks.findByName("ktlintTestSourceSetCheck")?.dependsOn(":samples:kotlin-rulesets-creating:build")

Fix check is failed in sample that uses ruleset.

import org.jlleitschuh.gradle.ktlint.KtlintExtension
import org.jlleitschuh.gradle.ktlint.reporter.ReporterType

plugins {
    application
}

plugins.apply("org.jlleitschuh.gradle.ktlint")
apply {
    plugin("kotlin")
}

application {
    mainClassName = "org.jlleitschuh.gradle.ktlint.sample.kotlin.MainKt"
}

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

configure<KtlintExtension> {
    verbose.set(true)
    outputToConsole.set(true)
    ruleSets.set(listOf("../kotlin-rulesets-creating/build/libs/kotlin-rulesets-creating.jar"))
    reporters.set(setOf(ReporterType.CHECKSTYLE, ReporterType.JSON))
}

tasks.findByName("ktlintMainSourceSetCheck")?.dependsOn(":samples:kotlin-rulesets-creating:build")
tasks.findByName("ktlintTestSourceSetCheck")?.dependsOn(":samples:kotlin-rulesets-creating:build")
tasks.findByName("ktlintKotlinScriptCheck")?.dependsOn(":samples:kotlin-rulesets-creating:build")


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

package androidx.fragment.lint

import com.android.tools.lint.client.api.IssueRegistry
import com.android.tools.lint.detector.api.CURRENT_API

/**
 * Issue Registry containing Fragment specific lint Issues.
 */
class FragmentIssueRegistry : IssueRegistry() {
    // tests are run with this version. We ensure that with ApiLintVersionsTest
    override val api = 6
    override val minApi = CURRENT_API
    override val issues get() = listOf(FragmentTagDetector.ISSUE)
}

Add Fragment LiveData check to IssueRegistry

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

package androidx.fragment.lint

import com.android.tools.lint.client.api.IssueRegistry
import com.android.tools.lint.detector.api.CURRENT_API

/**
 * Issue Registry containing Fragment specific lint Issues.
 */
class FragmentIssueRegistry : IssueRegistry() {
    // tests are run with this version. We ensure that with ApiLintVersionsTest
    override val api = 6
    override val minApi = CURRENT_API
    override val issues get() = listOf(
        FragmentLiveDataObserverDetector.ISSUE,
        FragmentTagDetector.ISSUE)
}


package ee.email

import ee.design.KotlinGenerator
import ee.lang.integ.eePath

fun main(args: Array<String>) {
    val generator = KotlinGenerator(model())
    generator.generate(eePath)
}

Improve Generators to generate into same file

package ee.email

import ee.design.gen.DesingKotlinGenerator
import ee.lang.integ.eePath

fun main(args: Array<String>) {
    val generator = DesingKotlinGenerator(model())
    generator.generate(eePath)
}


package blue.aodev.animeultimetv.presentation.common

import android.content.Context
import android.support.v17.leanback.widget.ImageCardView
import blue.aodev.animeultimetv.R
import blue.aodev.animeultimetv.domain.model.Episode
import blue.aodev.animeultimetv.extensions.formatEpisodeDuration
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions

class EpisodeCardPresenter : BaseCardPresenter() {

    override fun initResources(context: Context) {
        val res = context.resources
        cardImageWidth = res.getDimensionPixelSize(R.dimen.episode_card_width)
        cardImageHeight = res.getDimensionPixelSize(R.dimen.episode_card_height)
    }

    override fun onBindViewHolder(viewHolder: ViewHolder, item: Any) {
        val context = viewHolder.view.context
        val episode = item as Episode
        val cardView = viewHolder.view as ImageCardView

        cardView.titleText = context.getString(R.string.episode_title, episode.number)
        cardView.contentText = context.formatEpisodeDuration(episode.duration)

        Glide.with(context)
                .load(episode.imageUrl)
                .apply(RequestOptions.centerCropTransform())
                .into(cardView.mainImageView)
    }
}

Fix the episode card presenter colors

package blue.aodev.animeultimetv.presentation.common

import android.content.Context
import android.support.v17.leanback.widget.ImageCardView
import blue.aodev.animeultimetv.R
import blue.aodev.animeultimetv.domain.model.Episode
import blue.aodev.animeultimetv.extensions.formatEpisodeDuration
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions

class EpisodeCardPresenter : BaseCardPresenter() {

    override fun initResources(context: Context) {
        super.initResources(context)

        val res = context.resources
        cardImageWidth = res.getDimensionPixelSize(R.dimen.episode_card_width)
        cardImageHeight = res.getDimensionPixelSize(R.dimen.episode_card_height)
    }

    override fun onBindViewHolder(viewHolder: ViewHolder, item: Any) {
        val context = viewHolder.view.context
        val episode = item as Episode
        val cardView = viewHolder.view as ImageCardView

        cardView.titleText = context.getString(R.string.episode_title, episode.number)
        cardView.contentText = context.formatEpisodeDuration(episode.duration)

        Glide.with(context)
                .load(episode.imageUrl)
                .apply(RequestOptions.centerCropTransform())
                .into(cardView.mainImageView)
    }
}


package org.purescript.parser

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

class PureParser : PsiParser, PSTokens, PSElements {
    override fun parse(root: IElementType, builder: PsiBuilder): ASTNode {
        // builder.setDebugMode(true);
        val context = ParserContext(builder)
        builder.setWhitespaceSkippedCallback({ type, start, end ->
            context.trackColumn()
        })
        val mark = context.start()
        context.whiteSpace()
        // Creating a new instance here allows hot swapping while debugging.
        val info = PureParsecParser().parseModule.parse(context)
        var nextType: IElementType? = null
        if (!context.eof()) {
            var errorMarker: PsiBuilder.Marker? = null
            while (!context.eof()) {
                if (context.position >= info.position && errorMarker == null) {
                    errorMarker = context.start()
                    nextType = builder.tokenType
                }
                context.advance()
            }
            if (errorMarker != null) {
                if (nextType != null) errorMarker.error("Unexpected $nextType. $info") else errorMarker.error(
                    info.toString()
                )
            }
        }
        mark.done(root)
        return builder.treeBuilt
    }
}

Simplify callback, and remove warnings

package org.purescript.parser

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

class PureParser : PsiParser, PSTokens, PSElements {
    override fun parse(root: IElementType, builder: PsiBuilder): ASTNode {
        // builder.setDebugMode(true);
        val context = ParserContext(builder)
        builder.setWhitespaceSkippedCallback { _, _, _ -> context.trackColumn() }
        val mark = context.start()
        context.whiteSpace()
        // Creating a new instance here allows hot swapping while debugging.
        val info = PureParsecParser().parseModule.parse(context)
        var nextType: IElementType? = null
        if (!context.eof()) {
            var errorMarker: PsiBuilder.Marker? = null
            while (!context.eof()) {
                if (context.position >= info.position && errorMarker == null) {
                    errorMarker = context.start()
                    nextType = builder.tokenType
                }
                context.advance()
            }
            if (errorMarker != null) {
                if (nextType != null) errorMarker.error("Unexpected $nextType. $info") else errorMarker.error(
                    info.toString()
                )
            }
        }
        mark.done(root)
        return builder.treeBuilt
    }
}


package ftl

import ftl.cli.RefreshCommand
import ftl.cli.RunCommand
import picocli.CommandLine

@CommandLine.Command(
        name = "flank.jar\n",
        synopsisHeading = "",
        subcommands = [
            RunCommand::class,
            RefreshCommand::class
        ]
)
object Main : Runnable {
    override fun run() {
        if (version) {
            println("v0.2")
        } else {
            CommandLine.usage(Main, System.out);
        }
    }

    @CommandLine.Option(names = ["-v", "--version"], description = ["Prints the version"])
    var version = false

    @Throws(Exception::class)
    @JvmStatic
    fun main(args: Array<String>) {
        val args2 = arrayOf("-v")
        CommandLine.run<Runnable>(Main, System.out, *args2)
    }
}

Remove arg override used for testing

package ftl

import ftl.cli.RefreshCommand
import ftl.cli.RunCommand
import picocli.CommandLine

@CommandLine.Command(
        name = "flank.jar\n",
        synopsisHeading = "",
        subcommands = [
            RunCommand::class,
            RefreshCommand::class
        ]
)
object Main : Runnable {
    override fun run() {
        if (version) {
            println("v0.2")
        } else {
            CommandLine.usage(Main, System.out);
        }
    }

    @CommandLine.Option(names = ["-v", "--version"], description = ["Prints the version"])
    var version = false

    @Throws(Exception::class)
    @JvmStatic
    fun main(args: Array<String>) {
        CommandLine.run<Runnable>(Main, System.out, *args)
    }
}


package edu.csh.chase.sprint

import com.squareup.okhttp.OkHttpClient
import com.squareup.okhttp.Request as OkRequest

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

    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()
    }

}

Work on the execution and callbacks of requests

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?) {
    }

}


/*
 *  Copyright (c) 2004-2022, University of Oslo
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *  Redistributions of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 *  Redistributions in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *  Neither the name of the HISP project nor the names of its contributors may
 *  be used to endorse or promote products derived from this software without
 *  specific prior written permission.
 *
 *  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.
 */
package org.hisp.dhis.android.testapp.trackedentity.search

import com.google.common.truth.Truth.assertThat
import org.hisp.dhis.android.core.utils.integration.mock.BaseMockIntegrationTestMetadataEnqueable
import org.hisp.dhis.android.core.utils.runner.D2JunitRunner
import org.junit.Test
import org.junit.runner.RunWith

@RunWith(D2JunitRunner::class)
class TrackedEntityInstanceQueryCollectionRepositoryMockEnqueableIntegrationShould :
    BaseMockIntegrationTestMetadataEnqueable() {

    @Test
    fun find_online_blocking() {
        dhis2MockServer.enqueueMockResponse("trackedentity/search_grid.json")

        val trackedEntityInstances = d2.trackedEntityModule().trackedEntityInstanceQuery()
            .onlineOnly()
            .blockingGet()

        assertThat(trackedEntityInstances.size).isEqualTo(2)
    }
}


Add test for validating current build version name

package ru.dyatel.tsuschedule

import org.junit.Test

class UpdaterTest {

    @Test fun testBuildVersionName() {
        Release("1.0.0", "").isNewerThanInstalled()
    }

}


repositories {
    mavenCentral()
}

tasks.register("showRepos") {
    doLast {
        println("All repos:")
        //TODO:kotlin-dsl remove filter once we're no longer on a kotlin eap
        println(repositories.map { it.name }.filter { it != "maven" })
    }
}

Remove TODO and simplify map - no longer on a kotlin eap.

repositories {
    mavenCentral()
}

tasks.register("showRepos") {
    doLast {
        println("All repos:")
        println(repositories.map { it.name })
    }
}


buildscript {
    extra["kotlinVersion"] = "1.1-M03"

    repositories {
        mavenLocal()
        maven { setUrl("https://repo.gradle.org/gradle/repo") }
        maven { setUrl("https://plugins.gradle.org/m2/") }
        mavenCentral()
    }

    dependencies {
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${extra["kotlinVersion"]}")
        classpath("com.github.rodm:gradle-teamcity-plugin:0.12-SNAPSHOT")
    }
}

group = "com.github.rodm.teamcity"
version = "1.0-SNAPSHOT"

extra["teamcityVersion"] = findProperty("teamcity.version") ?: "9.1"

Update example to use Kotlin version 1.1.0

buildscript {
    extra["kotlinVersion"] = "1.1.0"

    repositories {
        mavenLocal()
        maven { setUrl("https://repo.gradle.org/gradle/repo") }
        maven { setUrl("https://plugins.gradle.org/m2/") }
        mavenCentral()
    }

    dependencies {
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${extra["kotlinVersion"]}")
        classpath("com.github.rodm:gradle-teamcity-plugin:0.12-SNAPSHOT")
    }
}

group = "com.github.rodm.teamcity"
version = "1.0-SNAPSHOT"

extra["teamcityVersion"] = findProperty("teamcity.version") ?: "9.1"


package Gradle_Check_TestCoverageForkedJava9Linux.buildTypes

import jetbrains.buildServer.configs.kotlin.v10.BuildType

class Gradle_Check_TestCoverageForkedJava9Linux_1(bucket: String) : BuildType({
    template(Gradle_Check.buildTypes.Gradle_Check_TestCoverageForkedLinux)
    uuid = "Gradle_Check_TestCoverageForkedJava9Linux_$bucket"
    extId = "Gradle_Check_TestCoverageForkedJava9Linux_$bucket"
    name = "Test Coverage - Forked Java9 Linux ($bucket)"

    params {
        param("org.gradle.test.bucket", bucket)
        param("org.gradle.test.buildType", "platform")
        param("webhook.body", """
            {
            "text":" ${'$'}{buildResult} - *${'$'}{buildName}* <${'$'}{buildStatusUrl}|#${'$'}{buildNumber}> (triggered by ${'$'}{triggeredBy})"
            }
        """.trimIndent())
    }
})

Fix JAVA_HOME setting for Java9 test coverage

package Gradle_Check_TestCoverageForkedJava9Linux.buildTypes

import jetbrains.buildServer.configs.kotlin.v10.BuildType

class Gradle_Check_TestCoverageForkedJava9Linux_1(bucket: String) : BuildType({
    template(Gradle_Check.buildTypes.Gradle_Check_TestCoverageForkedLinux)
    uuid = "Gradle_Check_TestCoverageForkedJava9Linux_$bucket"
    extId = "Gradle_Check_TestCoverageForkedJava9Linux_$bucket"
    name = "Test Coverage - Forked Java9 Linux ($bucket)"

    params {
        param("env.JAVA_HOME", "%linux.java9.oracle.64bit%")
        param("org.gradle.test.bucket", bucket)
        param("org.gradle.test.buildType", "platform")
        param("webhook.body", """
            {
            "text":" ${'$'}{buildResult} - *${'$'}{buildName}* <${'$'}{buildStatusUrl}|#${'$'}{buildNumber}> (triggered by ${'$'}{triggeredBy})"
            }
        """.trimIndent())
    }
})


package com.vimeo.networking2.requests

import com.vimeo.networking2.VimeoAccount
import retrofit2.Call
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.Header
import retrofit2.http.POST

/**
 * All the authentication endpoints.
 */
interface AuthService {

    /**
     * Get an access token by providing the client id and client secret along with grant
     * and scope types.
     *
     * @param authHeader It is created from the client id and client secret.
     * @param grantType  Determines whether you have access to public or private data.
     * @param scope      Determines what you want to access to in the Vimeo API.
     *
     * @return A [VimeoAccount] that has an access token.
     *
     */
    @FormUrlEncoded
    @POST("oauth/authorize/client")
    fun authorizeWithClientCredentialsGrant(@Header("Authorization") authHeader: String,
                                            @Field("grant_type") grantType: String,
                                            @Field("scope") scope: String
    ): Call<VimeoAccount>

}

Fix for formatting in auth service

package com.vimeo.networking2.requests

import com.vimeo.networking2.VimeoAccount
import retrofit2.Call
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.Header
import retrofit2.http.POST

/**
 * All the authentication endpoints.
 */
interface AuthService {

    /**
     * Get an access token by providing the client id and client secret along with grant
     * and scope types.
     *
     * @param authHeader It is created from the client id and client secret.
     * @param grantType  Determines whether you have access to public or private data.
     * @param scope      Determines what you want to access to in the Vimeo API.
     *
     * @return A [VimeoAccount] that has an access token.
     *
     */
    @FormUrlEncoded
    @POST("oauth/authorize/client")
    fun authorizeWithClientCredentialsGrant(
        @Header("Authorization") authHeader: String,
        @Field("grant_type") grantType: String,
        @Field("scope") scope: String
    ): Call<VimeoAccount>

}


package com.sksamuel.kt.koin

import io.kotest.assertions.throwables.shouldThrowAny
import io.kotest.core.spec.style.ShouldSpec
import org.koin.dsl.module
import org.koin.test.check.checkModules

class CheckModulesTest : ShouldSpec({

   should("Enable check modules") {
      checkModules {
         modules(koinModule)
      }
   }

   should("Throw exception if module is incomplete") {
      shouldThrowAny {
         checkModules {
            modules(incompleteModule)
         }
      }
   }

})

private val incompleteModule = module {
   single { RepoUser(get()) }
}

private class RepoUser(
   private val repo: Repo
)

// Not defined in Koin
private class Repo


package nl.hannahsten.texifyidea.inspections.latex.redundancy

import nl.hannahsten.texifyidea.file.LatexFileType
import nl.hannahsten.texifyidea.inspections.TexifyInspectionTestBase

class LatexDuplicateDefinitionInspectionTest : TexifyInspectionTestBase(LatexDuplicateDefinitionInspection()) {

    fun testWarning() {
        myFixture.configureByText(
            LatexFileType,
            """
            <error descr="Command '\cmdtwo' is defined multiple times">\newcommand{\cmdtwo}{a}</error>
            <error descr="Command '\cmdtwo' is defined multiple times">\newcommand{\cmdtwo}{a}</error>

            \providecommand{\test}{}
            <error descr="Command '\test' is defined multiple times">\newcommand{\test}{}</error>
            """.trimIndent()
        )
        myFixture.checkHighlighting()
    }

    fun testNoWarning() {
        myFixture.configureByText(
            LatexFileType,
            """
            \providecommand{\cmd}{a}
            \renewcommand{\cmd}{a}

            \providecommand{\provided}{}
            """.trimIndent()
        )
        myFixture.checkHighlighting()
    }
}

Add test to verify the issue is solved and remove a part of another test that is now not supported as true positive anymore

package nl.hannahsten.texifyidea.inspections.latex.redundancy

import nl.hannahsten.texifyidea.file.LatexFileType
import nl.hannahsten.texifyidea.inspections.TexifyInspectionTestBase

class LatexDuplicateDefinitionInspectionTest : TexifyInspectionTestBase(LatexDuplicateDefinitionInspection()) {

    fun testWarning() {
        myFixture.configureByText(
            LatexFileType,
            """
            <error descr="Command '\cmdtwo' is defined multiple times">\newcommand{\cmdtwo}{a}</error>
            <error descr="Command '\cmdtwo' is defined multiple times">\newcommand{\cmdtwo}{a}</error>
            """.trimIndent()
        )
        myFixture.checkHighlighting()
    }

    fun testNoWarning() {
        myFixture.configureByText(
            LatexFileType,
            """
            \providecommand{\cmd}{a}
            \renewcommand{\cmd}{a}

            \providecommand{\provided}{}
            """.trimIndent()
        )
        myFixture.checkHighlighting()
    }

    fun testNewcommand() {
        myFixture.configureByText(
            LatexFileType,
            """
            \newcommand{\foo}{}
            \renewcommand{\foo}{}
            """.trimIndent()
        )
        myFixture.checkHighlighting()
    }
}


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

package org.rust.toml

import com.intellij.notification.NotificationType
import org.rust.ide.notifications.showBalloonWithoutProject
import org.toml.lang.psi.*
import kotlin.reflect.KProperty

fun tomlPluginIsAbiCompatible(): Boolean {
    try {
        load<TomlKey>()
        load<TomlValue>()

        load(TomlKeyValue::key)
        load(TomlKeyValue::value)

        load(TomlTable::entries)
        load(TomlTable::header)

        load(TomlArrayTable::entries)
        load(TomlArrayTable::header)

        load(TomlTableHeader::names)
        load(TomlKeyValueOwner::entries)
    } catch (e: LinkageError) {
        showBalloonWithoutProject(
            "Incompatible TOML plugin version, code completion for Cargo.toml is not available.",
            NotificationType.WARNING
        )
        return false
    }
    return true
}

private inline fun <reified T : Any> load(): String = T::class.java.name
private fun load(p: KProperty<*>): String = p.name

Make sure notification is shown at most once

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

package org.rust.toml

import com.intellij.notification.NotificationType
import org.rust.ide.notifications.showBalloonWithoutProject
import org.toml.lang.psi.*
import kotlin.reflect.KProperty

fun tomlPluginIsAbiCompatible(): Boolean = computeOnce

private val computeOnce: Boolean by lazy {
    try {
        load<TomlKey>()
        load<TomlValue>()

        load(TomlKeyValue::key)
        load(TomlKeyValue::value)

        load(TomlTable::entries)
        load(TomlTable::header)

        load(TomlArrayTable::entries)
        load(TomlArrayTable::header)

        load(TomlTableHeader::names)
        load(TomlKeyValueOwner::entries)
        true
    } catch (e: LinkageError) {
        showBalloonWithoutProject(
            "Incompatible TOML plugin version, code completion for Cargo.toml is not available.",
            NotificationType.WARNING
        )
        false
    }
}

private inline fun <reified T : Any> load(): String = T::class.java.name
private fun load(p: KProperty<*>): String = p.name


package io.ktor.client.features.websocket

import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.http.websocket.*
import io.ktor.util.*
import java.util.*

private const val WEBSOCKET_VERSION = "13"
private const val NONCE_SIZE = 24

class WebSocketContent: ClientUpgradeContent() {

    private val nonce: String = buildString {
        val bytes = ByteArray(NONCE_SIZE)
        random.nextBytes(bytes)
        append(encodeBase64(bytes))
    }

    override val headers: Headers = HeadersBuilder().apply {
        append(HttpHeaders.Upgrade, "websocket")
        append(HttpHeaders.Connection, "upgrade")

        append(HttpHeaders.SecWebSocketKey, nonce)
        append(HttpHeaders.SecWebSocketVersion, WEBSOCKET_VERSION)
    }.build()

    override fun verify(headers: Headers) {
        val serverAccept = headers[HttpHeaders.SecWebSocketAccept]
                ?: error("Server should specify header ${HttpHeaders.SecWebSocketAccept}")

        val expectedAccept = websocketServerAccept(nonce)
        check(expectedAccept == serverAccept) {
            "Failed to verify server accept header. Expected: $expectedAccept, received: $serverAccept"
        }
    }

    companion object {
        private val random = Random()
    }
}

Fix client websocket nonce size

package io.ktor.client.features.websocket

import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.http.websocket.*
import io.ktor.util.*
import java.util.*

private const val WEBSOCKET_VERSION = "13"
private const val NONCE_SIZE = 16

class WebSocketContent: ClientUpgradeContent() {

    private val nonce: String = buildString {
        val bytes = ByteArray(NONCE_SIZE)
        random.nextBytes(bytes)
        append(encodeBase64(bytes))
    }

    override val headers: Headers = HeadersBuilder().apply {
        append(HttpHeaders.Upgrade, "websocket")
        append(HttpHeaders.Connection, "upgrade")

        append(HttpHeaders.SecWebSocketKey, nonce)
        append(HttpHeaders.SecWebSocketVersion, WEBSOCKET_VERSION)
    }.build()

    override fun verify(headers: Headers) {
        val serverAccept = headers[HttpHeaders.SecWebSocketAccept]
                ?: error("Server should specify header ${HttpHeaders.SecWebSocketAccept}")

        val expectedAccept = websocketServerAccept(nonce)
        check(expectedAccept == serverAccept) {
            "Failed to verify server accept header. Expected: $expectedAccept, received: $serverAccept"
        }
    }

    companion object {
        private val random = Random()
    }
}


package org.purescript.psi

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

class PSValueDeclaration(node: ASTNode) : PSPsiElement(node),
    PsiNameIdentifierOwner {
    override fun getName(): String {
        return findChildByClass(PSIdentifierImpl::class.java)!!
            .name
    }

    override fun setName(name: String): PsiElement? {
        return null
    }

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

    val varBindersInParameters: Map<String, PSVarBinderImpl>
        get() {
            return collectDescendantsOfType<PSVarBinderImpl>()
                .asSequence()
                .filterNotNull()
                .map { Pair(it.name, it) }
                .toMap()
        }
}

Add presentation for value declaration

package org.purescript.psi

import com.intellij.lang.ASTNode
import com.intellij.navigation.ItemPresentation
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.psi.util.collectDescendantsOfType
import javax.swing.Icon

class PSValueDeclaration(node: ASTNode) : PSPsiElement(node),
    PsiNameIdentifierOwner {
    override fun getName(): String {
        return findChildByClass(PSIdentifierImpl::class.java)!!
            .name
    }

    override fun getPresentation(): ItemPresentation {
        val name = this.name
        val fileName = this.containingFile.name
        return object : ItemPresentation {
            override fun getPresentableText(): String {
                return name
            }

            override fun getLocationString(): String {
                return fileName
            }

            override fun getIcon(unused: Boolean): Icon? {
                return null
            }
        }
    }

    override fun setName(name: String): PsiElement? {
        return null
    }

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

    val varBindersInParameters: Map<String, PSVarBinderImpl>
        get() {
            return collectDescendantsOfType<PSVarBinderImpl>()
                .asSequence()
                .filterNotNull()
                .map { Pair(it.name, it) }
                .toMap()
        }
}


package Kotlin101.Strings

fun main(args : Array<String>) {
    var plato1 = "Wise men speak because they have something to say; Fools because they have to say something."

    //This is a single line string
    println("I love ancient philosophy.")

    //Use triple quote """ to go multi line. This also means that you can use double quote " freely in the string.
    //This demonstrate template expression. Pretty neat huh. You can use ${ } to show any arbitrary expression
    println("""My favorite quote is by '$plato1' although at ${plato1.length} characters long, it is not compact.
He is also a skeptic on love "${platoOnLove()}. He is wrong, love is as simple as 1 + 1 = ${1 + 1 }."
            """)
}

fun platoOnLove(): String{
    return "Love is a serious mental disease."
}

Add comment to continue to Variables.kt

package Kotlin101.Strings

fun main(args : Array<String>) {
    var plato1 = "Wise men speak because they have something to say; Fools because they have to say something."

    //This is a single line string
    println("I love ancient philosophy.")

    //Use triple quote """ to go multi line. This also means that you can use double quote " freely in the string.
    //This demonstrate template expression. Pretty neat huh. You can use ${ } to show any arbitrary expression
    println("""My favorite quote is by '$plato1' although at ${plato1.length} characters long, it is not compact.
He is also a skeptic on love "${platoOnLove()}. He is wrong, love is as simple as 1 + 1 = ${1 + 1 }."
            """)
}

fun platoOnLove(): String{
    return "Love is a serious mental disease."
}

/* what's next? try Variables.kt to learn about immutable/mutable variable declarations */


object PluginVersions {
    val kotlin = "1.3.50"
    val ktlintPlugin = "9.0.0"
    val gradlePublishPlugin = "0.10.1"
    val androidPlugin = "3.5.0"
    val semver = "1.1.1"
    val gradleWrapper = "5.6.2"
    val junit5 = "5.4.0"
    val assertJ = "3.11.1"
}

Apply latest released plugin version on itself.

object PluginVersions {
    val kotlin = "1.3.50"
    val ktlintPlugin = "9.1.1"
    val gradlePublishPlugin = "0.10.1"
    val androidPlugin = "3.5.0"
    val semver = "1.1.1"
    val gradleWrapper = "5.6.2"
    val junit5 = "5.4.0"
    val assertJ = "3.11.1"
}


package venus.riscv

fun userStringToInt(s: String): Int {
    if (isCharacterLiteral(s)) {
        return characterLiteralToInt(s)
    }
    val radix = when (s.take(2)) {
        "0x" -> 16
        "0b" -> 2
        else -> return s.toLong().toInt()
    }
    return s.drop(2).toLong(radix).toInt()
}

private fun isCharacterLiteral(s: String) =
        s.first() == '\'' && s.last() == '\''

private fun characterLiteralToInt(s: String): Int {
    val stripSingleQuotes = s.drop(1).dropLast(1)
    if (stripSingleQuotes == "\\'") return '\''.toInt()
    if (stripSingleQuotes == "\"") return '"'.toInt()

    val jsonString = "\"$stripSingleQuotes\""
    try {
        val parsed = JSON.parse<String>(jsonString)
        if (parsed.isEmpty()) throw NumberFormatException("character literal $s is empty")
        if (parsed.length > 1) throw NumberFormatException("character literal $s too long")
        return parsed[0].toInt()
    } catch (e: Throwable) {
        throw NumberFormatException("could not parse character literal $s")
    }
}

Fix to allow negative signs for hex/binary immediates

package venus.riscv

fun userStringToInt(s: String): Int {
    if (isCharacterLiteral(s)) {
        return characterLiteralToInt(s)
    }

    val radix = when {
        s.startsWith("0x") -> 16
        s.startsWith("0b") -> 2
        s.drop(1).startsWith("0x") -> 16
        s.drop(1).startsWith("0b") -> 2
        else -> return s.toLong().toInt()
    }

    val skipSign = when (s.first()) {
        '+', '-' -> 1
        else -> 0
    }

    val noRadixString = s.take(skipSign) + s.drop(skipSign + 2)
    return noRadixString.toLong(radix).toInt()
}

private fun isCharacterLiteral(s: String) =
        s.first() == '\'' && s.last() == '\''

private fun characterLiteralToInt(s: String): Int {
    val stripSingleQuotes = s.drop(1).dropLast(1)
    if (stripSingleQuotes == "\\'") return '\''.toInt()
    if (stripSingleQuotes == "\"") return '"'.toInt()

    val jsonString = "\"$stripSingleQuotes\""
    try {
        val parsed = JSON.parse<String>(jsonString)
        if (parsed.isEmpty()) throw NumberFormatException("character literal $s is empty")
        if (parsed.length > 1) throw NumberFormatException("character literal $s too long")
        return parsed[0].toInt()
    } catch (e: Throwable) {
        throw NumberFormatException("could not parse character literal $s")
    }
}


package net.binggl.mydms.features.upload

import FixtureHelpers
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import net.binggl.mydms.features.upload.models.UploadItem
import org.junit.Assert
import org.junit.Test
import java.text.SimpleDateFormat

class UploadModelTest {

    @Test
    fun serializeToJson(): Unit {
        val uploadItem = UploadItem("id", "test", "mime", simpleDateFormat.parse("01.01.2018"))
        val expected = MAPPER.writeValueAsString(MAPPER.readValue(FixtureHelpers.fixture("fixtures/UploadItem.json"), UploadItem::class.java))
        Assert.assertEquals(expected, MAPPER.writeValueAsString(uploadItem))
    }

    @Test
    fun deserializeFromJson(): Unit {
        val uploadItem = UploadItem("id", "test", "mime", simpleDateFormat.parse("01.01.2018"))
        Assert.assertEquals(MAPPER.readValue(FixtureHelpers.fixture("fixtures/UploadItem.json"), UploadItem::class.java), uploadItem)
    }

    companion object {
        // https://github.com/FasterXML/jackson-module-kotlin
        private val MAPPER = jacksonObjectMapper()
        private val simpleDateFormat = SimpleDateFormat("dd.MM.yyyy")
    }
}

Use jodatime to parse dates.

package net.binggl.mydms.features.upload

import FixtureHelpers
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import net.binggl.mydms.features.upload.models.UploadItem
import org.joda.time.format.DateTimeFormat
import org.junit.Assert
import org.junit.Test
import java.text.SimpleDateFormat

class UploadModelTest {

    @Test
    fun serializeToJson(): Unit {
        val uploadItem = UploadItem("id", "test", "mime", fmt.parseDateTime("20180101").toDate())
        val expected = MAPPER.writeValueAsString(MAPPER.readValue(FixtureHelpers.fixture("fixtures/UploadItem.json"), UploadItem::class.java))
        Assert.assertEquals(expected, MAPPER.writeValueAsString(uploadItem))
    }

    @Test
    fun deserializeFromJson(): Unit {
        val uploadItem = UploadItem("id", "test", "mime", fmt.parseDateTime("20180101").toDate())
        Assert.assertEquals(MAPPER.readValue(FixtureHelpers.fixture("fixtures/UploadItem.json"), UploadItem::class.java), uploadItem)
    }

    companion object {
        // https://github.com/FasterXML/jackson-module-kotlin
        private val MAPPER = jacksonObjectMapper()
        private val fmt = DateTimeFormat.forPattern("yyyyMMdd")
    }
}


package me.scana.okgradle.data

import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.ResponseBody.Companion.toResponseBody

class TestInterceptor : Interceptor {

    var recentRequest: Request? = null
    private var response: Response = buildResponse("".toResponseBody("text/plain".toMediaType()))

    override fun intercept(chain: Interceptor.Chain): Response {
        recentRequest = chain.request()
        return response
    }

    fun returnsJson(json: String) {
        val body = ResponseBody.create(
                "application/json".toMediaType(),
                json
        )
        response = buildResponse(body)
    }

    private fun buildResponse(body: ResponseBody): Response {
        return Response.Builder()
                .code(200)
                .body(body)
                .protocol(Protocol.HTTP_2)
                .message("")
                .request(Request.Builder().url("http://url.com").build())
                .build()
    }
}

class MockOkHttpClient {

    private val testInterceptor = TestInterceptor()
    private val okHttpClient = OkHttpClient.Builder()
            .addInterceptor(testInterceptor)
            .build()

    fun returnsJson(json: String) {
        testInterceptor.returnsJson(json)
    }

    fun instance() = okHttpClient

    fun recentRequest(): Request? = testInterceptor.recentRequest

}

Migrate method call to OkHttps extension function call

package me.scana.okgradle.data

import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.ResponseBody.Companion.toResponseBody

class TestInterceptor : Interceptor {

    var recentRequest: Request? = null
    private var response: Response = buildResponse("".toResponseBody("text/plain".toMediaType()))

    override fun intercept(chain: Interceptor.Chain): Response {
        recentRequest = chain.request()
        return response
    }

    fun returnsJson(json: String) {
        val body = json.toResponseBody("application/json".toMediaType())
        response = buildResponse(body)
    }

    private fun buildResponse(body: ResponseBody): Response {
        return Response.Builder()
                .code(200)
                .body(body)
                .protocol(Protocol.HTTP_2)
                .message("")
                .request(Request.Builder().url("http://url.com").build())
                .build()
    }
}

class MockOkHttpClient {

    private val testInterceptor = TestInterceptor()
    private val okHttpClient = OkHttpClient.Builder()
            .addInterceptor(testInterceptor)
            .build()

    fun returnsJson(json: String) {
        testInterceptor.returnsJson(json)
    }

    fun instance() = okHttpClient

    fun recentRequest(): Request? = testInterceptor.recentRequest

}


package pl.mg6.likeornot.view

import android.content.Context
import android.support.v4.view.ViewPager
import android.util.AttributeSet

class SquareViewPager : ViewPager {

    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(measuredWidth, measuredWidth)
    }
}

Fix how sqaure view measures its height.

package pl.mg6.likeornot.view

import android.content.Context
import android.support.v4.view.ViewPager
import android.util.AttributeSet

class SquareViewPager : ViewPager {

    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val width = MeasureSpec.getSize(widthMeasureSpec)
        val newHeightMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY)
        super.onMeasure(widthMeasureSpec, newHeightMeasureSpec)
    }
}


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

@file:Suppress("NOTHING_TO_INLINE")

package splitties.uithread

import android.os.Looper

@PublishedApi internal inline val currentThread: Thread get() = Thread.currentThread()

/** This main looper cache avoids synchronization overhead when accessed repeatedly. */
@JvmField val mainLooper: Looper = Looper.getMainLooper()!!
@JvmField val mainThread: Thread = mainLooper.thread

val isUiThread inline get() = mainThread === Thread.currentThread()

/**
 * Passes if run on the [mainThread] (aka. UI thread), throws an [IllegalStateException] otherwise.
 */
inline fun checkUiThread() = check(isUiThread) {
    "This should only be called on the UI thread! Current: $currentThread"
}

Add uiThread inline proxy to mainThread property

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

@file:Suppress("NOTHING_TO_INLINE")

package splitties.uithread

import android.os.Looper

@PublishedApi internal inline val currentThread: Thread get() = Thread.currentThread()

/** This main looper cache avoids synchronization overhead when accessed repeatedly. */
@JvmField val mainLooper: Looper = Looper.getMainLooper()!!
@JvmField val mainThread: Thread = mainLooper.thread
inline val uiThread get() = mainThread

val isUiThread inline get() = mainThread === Thread.currentThread()

/**
 * Passes if run on the [mainThread] (aka. UI thread), throws an [IllegalStateException] otherwise.
 */
inline fun checkUiThread() = check(isUiThread) {
    "This should only be called on the UI thread! Current: $currentThread"
}


package Kotlin101.Functions.Cascades

fun main (Args : Array<String>){
    /* This call utilizes extension function and infix call */
    var superman = Superman() with {
        name = "Lux Luthor"
        punch()
        kick()
    }
}

public fun <T>T.with(operations : T.() -> Unit) : T {
    this.operations()
    return this
}

public class Superman() {
    var name : String = "Clark Kent"

    public fun punch() : Unit = println("$name punches")
    public fun fly() : Unit = println("$name flies")
    public fun kick() : Unit = println("$name kicks")
}

Add sub object creation in with example

package Kotlin101.Functions.Cascades

fun main (Args : Array<String>){
    /* This call utilizes extension function and infix call. It is handy to deal with pesky Java object initializations */
    var superman = Superman() with {
        name = "Lux Luthor"
        punch()
        kick()
        sidekick = Spiderman() with {
            special()
        }
    }
}

public fun <T>T.with(operations : T.() -> Unit) : T {
    this.operations()
    return this
}

public class Superman() {
    var name : String = "Clark Kent"
    var sidekick : Sidekick = Robin()

    public fun punch() : Unit = println("$name punches")
    public fun fly() : Unit = println("$name flies")
    public fun kick() : Unit = println("$name kicks")
}

trait Sidekick {
    public abstract fun special()
}

public class Spiderman() : Sidekick {
    var name : String = "Peter Parker"
    override fun special() = println("$name webs")
}

public class Robin() : Sidekick {
    var name : String = "Robin"
    override fun special() = println("$name is useless")
}


plugins {
    id("gradlebuild.distribution.api-java")
}

gradlebuildJava.usedInWorkers()

dependencies {
    implementation(project(":cli"))

    implementation(project(":base-annotations"))
    implementation(libs.commonsLang)
}

Add description to :build-option project

plugins {
    id("gradlebuild.distribution.api-java")
}

description = "The Gradle build option parser."

gradlebuildJava.usedInWorkers()

dependencies {
    implementation(project(":cli"))

    implementation(project(":base-annotations"))
    implementation(libs.commonsLang)
}


pluginManagement {
    plugins {
        id("org.jetbrains.kotlin.jvm") version "1.5.21"
        id("com.gradle.plugin-publish") version "0.15.0"
        `java-gradle-plugin`
        `maven-publish`
        id("org.jlleitschuh.gradle.ktlint") version "10.2.0"
        id("com.github.johnrengelman.shadow") version "7.0.0"
        id("com.github.breadmoirai.github-release") version "2.2.10"
    }
}

enableFeaturePreview("VERSION_CATALOGS")

plugins {
    `gradle-enterprise`
}

gradleEnterprise {
    buildScan {
        termsOfServiceUrl = "https://gradle.com/terms-of-service"
        termsOfServiceAgree = "yes"

        publishAlways()
    }
}

rootProject.name = "ktlint-gradle"
rootProject.buildFileName = "build.gradle.kts"

Use the latest version of plugin on itself

pluginManagement {
    plugins {
        id("org.jetbrains.kotlin.jvm") version "1.5.21"
        id("com.gradle.plugin-publish") version "0.15.0"
        `java-gradle-plugin`
        `maven-publish`
        id("org.jlleitschuh.gradle.ktlint") version "10.2.1"
        id("com.github.johnrengelman.shadow") version "7.0.0"
        id("com.github.breadmoirai.github-release") version "2.2.10"
    }
}

enableFeaturePreview("VERSION_CATALOGS")

plugins {
    `gradle-enterprise`
}

gradleEnterprise {
    buildScan {
        termsOfServiceUrl = "https://gradle.com/terms-of-service"
        termsOfServiceAgree = "yes"

        publishAlways()
    }
}

rootProject.name = "ktlint-gradle"
rootProject.buildFileName = "build.gradle.kts"


/*
 * Copyright 2018 Google, Inc.
 *
 * 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 me.banes.chris.tivi

import android.content.Context
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.module.AppGlideModule
import com.bumptech.glide.request.RequestOptions

@GlideModule
class TiviAppGlideModule : AppGlideModule() {
    override fun applyOptions(context: Context, builder: GlideBuilder) {
        builder.setDefaultRequestOptions(
                RequestOptions().format(DecodeFormat.PREFER_ARGB_8888)
        )
    }
}

Disable HARDWARE bitmaps in Glide for now

/*
 * Copyright 2018 Google, Inc.
 *
 * 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 me.banes.chris.tivi

import android.content.Context
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.module.AppGlideModule
import com.bumptech.glide.request.RequestOptions

@GlideModule
class TiviAppGlideModule : AppGlideModule() {
    override fun applyOptions(context: Context, builder: GlideBuilder) {
        builder.setDefaultRequestOptions(
                RequestOptions().disallowHardwareConfig()
        )
    }
}


package configurations

import jetbrains.buildServer.configs.kotlin.v10.BuildStep
import jetbrains.buildServer.configs.kotlin.v10.BuildType
import jetbrains.buildServer.configs.kotlin.v10.buildSteps.gradle
import jetbrains.buildServer.configs.kotlin.v10.buildSteps.script
import model.CIBuildModel

object ColonyCompatibility : BuildType({
    uuid = "${CIBuildModel.projectPrefix}ColonyCompatibility"
    extId = uuid
    name = "Colony Compatibility"
    description = "Check Gradle against latest development version of Colony"

    applyDefaultSettings(this, vcsRoot = "Colony_ColonyMaster")

    params {
        param("env.JAVA_HOME", "%linux.java8.oracle.64bit%")
    }

    steps {
        gradle {
            name = "GRADLE_RUNNER"
            tasks = "clean :gradle-test:test"
            gradleParams = gradleParameters.joinToString(separator = " ")
            useGradleWrapper = true
        }
        script {
            name = "CHECK_CLEAN_M2"
            executionMode = BuildStep.ExecutionMode.ALWAYS
            scriptContent = m2CleanScriptLinux
        }
    }

    applyDefaultDependencies(this, true)
})

Remove build scan init from Colony Comp build

package configurations

import jetbrains.buildServer.configs.kotlin.v10.BuildStep
import jetbrains.buildServer.configs.kotlin.v10.BuildType
import jetbrains.buildServer.configs.kotlin.v10.buildSteps.gradle
import jetbrains.buildServer.configs.kotlin.v10.buildSteps.script
import model.CIBuildModel

object ColonyCompatibility : BuildType({
    uuid = "${CIBuildModel.projectPrefix}ColonyCompatibility"
    extId = uuid
    name = "Colony Compatibility"
    description = "Check Gradle against latest development version of Colony"

    applyDefaultSettings(this, vcsRoot = "Colony_ColonyMaster")

    params {
        param("env.JAVA_HOME", "%linux.java8.oracle.64bit%")
    }

    steps {
        gradle {
            name = "GRADLE_RUNNER"
            tasks = "clean :gradle-test:test"
            gradleParams = gradleParameters.joinToString(separator = " ").replace("-I ./gradle/buildScanInit.gradle","")
            useGradleWrapper = true
        }
        script {
            name = "CHECK_CLEAN_M2"
            executionMode = BuildStep.ExecutionMode.ALWAYS
            scriptContent = m2CleanScriptLinux
        }
    }

    applyDefaultDependencies(this, true)
})


package org.wordpress.aztec

/**
 * Describes styles that could be applied to text
 */
enum class TextFormat {
    FORMAT_BOLD,
    FORMAT_ITALIC,
    FORMAT_UNDERLINED,
    FORMAT_STRIKETHROUGH,
    FORMAT_BULLET,
    FORMAT_QUOTE,
    FORMAT_LINK
}

Add headers to text format

package org.wordpress.aztec

/**
 * Describes styles that could be applied to text
 */
enum class TextFormat {
    FORMAT_HEADER_1,
    FORMAT_HEADER_2,
    FORMAT_HEADER_3,
    FORMAT_HEADER_4,
    FORMAT_HEADER_5,
    FORMAT_HEADER_6,
    FORMAT_BOLD,
    FORMAT_ITALIC,
    FORMAT_UNDERLINED,
    FORMAT_STRIKETHROUGH,
    FORMAT_BULLET,
    FORMAT_QUOTE,
    FORMAT_LINK
}


package com.acornui.skins

import com.acornui.component.UiComponent
import com.acornui.component.createOrReuseAttachment
import com.acornui.component.style.addStyleRule
import com.acornui.component.text.charStyle
import com.acornui.core.di.inject
import com.acornui.core.graphic.Window

/**
 * Watches the window for scale changes, updating the character style.
 */
class WindowScalingAttachment(val target: UiComponent) {

	private val textScaling = charStyle()
	private val window = target.inject(Window)

	init {
		window.scaleChanged.add { _, _ ->
			updateWindowScaling()
		}
		updateWindowScaling()
		target.addStyleRule(textScaling)
	}

	private fun updateWindowScaling() {
		textScaling.apply {
			val window = target.inject(Window)
			scaleX = window.scaleX
			scaleY = window.scaleY
		}
	}

	companion object {
		fun attach(target: UiComponent) {
			target.createOrReuseAttachment(WindowScalingAttachment) { WindowScalingAttachment(target) }
		}
	}
}

Fix Scaling attachment not re-applying when changing skin

package com.acornui.skins

import com.acornui.component.UiComponent
import com.acornui.component.createOrReuseAttachment
import com.acornui.component.style.AlwaysFilter
import com.acornui.component.style.StyleRule
import com.acornui.component.text.charStyle
import com.acornui.core.Disposable
import com.acornui.core.di.inject
import com.acornui.core.graphic.Window
import com.acornui.function.as2

/**
 * Watches the window for scale changes, updating the character style.
 */
class WindowScalingAttachment(val target: UiComponent) : Disposable {

	private val textScaling = charStyle()
	private val textScalingRule = StyleRule(textScaling, AlwaysFilter)
	private val window = target.inject(Window)

	init {
		window.scaleChanged.add(::updateWindowScaling.as2)
		updateWindowScaling()
	}

	private fun updateWindowScaling() {
		textScaling.apply {
			val window = target.inject(Window)
			scaleX = window.scaleX
			scaleY = window.scaleY
		}
	}

	fun apply() {
		if (!target.styleRules.contains(textScalingRule))
			target.styleRules.add(textScalingRule)
	}

	override fun dispose() {
		window.scaleChanged.remove(::updateWindowScaling.as2)
		target.styleRules.remove(textScalingRule)

	}

	companion object {

		fun attach(target: UiComponent) {
			val scalingAttachment = target.createOrReuseAttachment(WindowScalingAttachment) { WindowScalingAttachment(target) }
			scalingAttachment.apply()
		}
	}
}


package nl.hannahsten.texifyidea.inspections.latex

import nl.hannahsten.texifyidea.inspections.TexifyInspectionTestBase

class LatexDiacriticIJInspectionTest : TexifyInspectionTestBase(LatexDiacriticIJInspection()) {
    fun `test warning`() = testHighlighting("""<warning>\^i</warning>""")

    fun `test no warning`() = testHighlighting("""\^{\i}""")

    fun `test quick fix i`() = testQuickFix(
            before = """\^i""",
            after = """\^{\i}"""
    )

    fun `test quick fix j`() = testQuickFix(
            before = """\^j""",
            after = """\^{\j}"""
    )

    fun `test quick fix i in math mode`() = testQuickFix(
            before = """$\^i$""",
            after = """$\^\imath$"""
    )

    fun `test quick fix j in math mode`() = testQuickFix(
            before = """$\^j$""",
            after = """$\^\jmath$"""
    )
}


package io.gitlab.arturbosch.tinbo.plugins

import io.gitlab.arturbosch.tinbo.config.TinboConfig
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.config.BeanDefinition
import org.springframework.context.ApplicationContext
import org.springframework.context.support.GenericApplicationContext
import org.springframework.stereotype.Component

/**
 * @author Artur Bosch
 */
@Component
class TinboContext @Autowired constructor(val context: ApplicationContext,
										  val tinboConfig: TinboConfig) {

	private val _helpers = lazy { context.getBeansOfType(PluginHelper::class.java).values }

	@PluginSupport
	fun pluginHelpers() = _helpers.value

	@PluginSupport
	fun registerBeanDefinition(name: String, bean: BeanDefinition) {
		(context as GenericApplicationContext).defaultListableBeanFactory
				.registerBeanDefinition(name, bean)
	}

	@PluginSupport
	fun registerSingleton(name: String, obj: Any) {
		(context as GenericApplicationContext).beanFactory.registerSingleton(name, obj)
	}

	@PluginSupport
	inline fun <reified T : Any> beanOf(): T {
		return context.getBean(T::class.java)
	}

	@PluginSupport
	inline fun <reified T : Any> beansOf(): MutableMap<String, T> {
		return context.getBeansOfType(T::class.java)
	}
}

Add non inlined beanOf and beansOf functions to context for better java interop

package io.gitlab.arturbosch.tinbo.plugins

import io.gitlab.arturbosch.tinbo.config.TinboConfig
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.config.BeanDefinition
import org.springframework.context.ApplicationContext
import org.springframework.context.support.GenericApplicationContext
import org.springframework.stereotype.Component

/**
 * @author Artur Bosch
 */
@Component
class TinboContext @Autowired constructor(val context: ApplicationContext,
										  val tinboConfig: TinboConfig) {

	private val _helpers = lazy { context.getBeansOfType(PluginHelper::class.java).values }

	@PluginSupport
	fun pluginHelpers() = _helpers.value

	@PluginSupport
	fun registerBeanDefinition(name: String, bean: BeanDefinition) {
		(context as GenericApplicationContext).defaultListableBeanFactory
				.registerBeanDefinition(name, bean)
	}

	@PluginSupport
	fun registerSingleton(name: String, obj: Any) {
		(context as GenericApplicationContext).beanFactory.registerSingleton(name, obj)
	}

	@PluginSupport
	fun <T> beanOf(clazz: Class<T>): T = context.getBean(clazz)

	@PluginSupport
	inline fun <reified T : Any> beanOf(): T = beanOf(T::class.java)

	@PluginSupport
	fun <T> beansOf(clazz: Class<T>): MutableMap<String, T> = context.getBeansOfType(clazz)

	@PluginSupport
	inline fun <reified T : Any> beansOf(): MutableMap<String, T> = beansOf(T::class.java)
}


plugins {
    id("gradlebuild.distribution.api-java")
}

dependencies {
    api(project(":base-services")) // leaks BuildOperationNotificationListener on API

    implementation(libs.jsr305)
    implementation(libs.inject)
    implementation(project(":logging"))
    implementation(project(":core-api"))
    implementation(project(":core"))
    implementation(project(":launcher"))
    implementation(project(":snapshots"))

    integTestImplementation(project(":internal-testing"))
    integTestImplementation(project(":internal-integ-testing"))

    // Dependencies of the integ test fixtures
    integTestImplementation(project(":build-option"))
    integTestImplementation(project(":messaging"))
    integTestImplementation(project(":persistent-cache"))
    integTestImplementation(project(":native"))
    integTestImplementation(libs.guava)

    integTestDistributionRuntimeOnly(project(":distributions-full"))
}

Upgrade 'enterprise' to Groovy 3

plugins {
    id("gradlebuild.distribution.api-java")
}

dependencies {
    api(project(":base-services")) // leaks BuildOperationNotificationListener on API

    implementation(libs.jsr305)
    implementation(libs.inject)
    implementation(libs.groovyJson)
    implementation(project(":logging"))
    implementation(project(":core-api"))
    implementation(project(":core"))
    implementation(project(":launcher"))
    implementation(project(":snapshots"))

    integTestImplementation(project(":internal-testing"))
    integTestImplementation(project(":internal-integ-testing"))

    // Dependencies of the integ test fixtures
    integTestImplementation(project(":build-option"))
    integTestImplementation(project(":messaging"))
    integTestImplementation(project(":persistent-cache"))
    integTestImplementation(project(":native"))
    integTestImplementation(libs.guava)

    integTestDistributionRuntimeOnly(project(":distributions-full"))
}


package org.firezenk.kartographer.library.core

import org.junit.Assert.*

/**
 * Created by Jorge Garrido Oval, aka firezenk on 14/01/18.
 * Project: Kartographer
 */
class CoreTest {

}

Add a basic Core test

package org.firezenk.kartographer.library.core

import org.firezenk.kartographer.library.Logger
import org.firezenk.kartographer.library.core.util.TargetRoute
import org.firezenk.kartographer.library.dsl.route
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test

/**
 * Created by Jorge Garrido Oval, aka firezenk on 14/01/18.
 * Project: Kartographer
 */
class CoreTest {

    lateinit var core: Core
    lateinit var move: Move

    @Before fun setup() {
        core = Core(Any(), Logger())
        move = Move(core)
    }

    @Test fun `given a history with one route on default path, the current route is correct`() {
        val route = route {
            target = TargetRoute::class
            path = Core.ROOT_NODE
            anchor = Any()
        }
        move.routeTo(route)

        val currentRoute = core.current<Any>()

        assertEquals(route, currentRoute)
    }

    @Test fun `given a history with one route on default path, the current route payload is correct`() {
        val route = route {
            target = TargetRoute::class
            path = Core.ROOT_NODE
            params = mapOf("param1" to 1, "param2" to "hi!")
            anchor = Any()
        }
        move.routeTo(route)

        val currentParam1 = core.payload<Int>("param1")
        val currentParam2 = core.payload<String>("param2")

        assertEquals(currentParam1, 1)
        assertEquals(currentParam2, "hi!")
    }
}