package io.ktor.client.features

import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.response.*
import io.ktor.content.*
import io.ktor.http.*
import io.ktor.util.*
import java.nio.charset.*

class HttpPlainText(private val defaultCharset: Charset) {
    suspend fun read(response: IncomingContent): String = response.readText(charset = defaultCharset)

    class Config {
        var defaultCharset: Charset = Charset.defaultCharset()

        fun build(): HttpPlainText = HttpPlainText(defaultCharset)
    }

    companion object Feature : HttpClientFeature<Config, HttpPlainText> {
        override val key = AttributeKey<HttpPlainText>("HttpPlainText")

        override fun prepare(block: Config.() -> Unit): HttpPlainText = Config().apply(block).build()

        override fun install(feature: HttpPlainText, scope: HttpClient) {
            scope.requestPipeline.intercept(HttpRequestPipeline.Render) { content ->
                if (content !is String) return@intercept
                val contentType = ContentType.Text.Plain.withCharset(feature.defaultCharset)
                proceedWith(TextContent(content, contentType))
            }

            scope.responsePipeline.intercept(HttpResponsePipeline.Parse) { (expectedType, response) ->
                if (expectedType != String::class) return@intercept
                if (response !is IncomingContent) return@intercept
                proceedWith(HttpResponseContainer(expectedType, feature.read(response)))
            }
        }
    }
}

Use response charset by default

package io.ktor.client.features

import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.response.*
import io.ktor.content.*
import io.ktor.http.*
import io.ktor.util.*
import java.nio.charset.*

class HttpPlainText(private val defaultCharset: Charset) {
    suspend fun read(response: IncomingContent): String = response.readText(charset = defaultCharset)

    class Config {
        var defaultCharset: Charset = Charset.defaultCharset()

        fun build(): HttpPlainText = HttpPlainText(defaultCharset)
    }

    companion object Feature : HttpClientFeature<Config, HttpPlainText> {
        override val key = AttributeKey<HttpPlainText>("HttpPlainText")

        override fun prepare(block: Config.() -> Unit): HttpPlainText = Config().apply(block).build()

        override fun install(feature: HttpPlainText, scope: HttpClient) {
            scope.requestPipeline.intercept(HttpRequestPipeline.Render) { content ->
                if (content !is String) return@intercept
                val contentType = ContentType.Text.Plain.withCharset(feature.defaultCharset)
                proceedWith(TextContent(content, contentType))
            }

            scope.responsePipeline.intercept(HttpResponsePipeline.Parse) { (expectedType, response) ->
                if (expectedType != String::class || response !is IncomingContent) return@intercept
                proceedWith(HttpResponseContainer(expectedType, feature.read(response)))
            }
        }
    }
}


package com.lapismc.minecraft.versioning

/**
 * Library inclusion rule for operating system checks.
 * @param os Operating system this rule applies to.
 * @param allowed Flag indicating whether the library should be included.
 */
class OSRule(val os: OSType, allowed: Boolean) : Rule(allowed) {
    /**
     * Checks whether this rule applies to the current system.
     * @return True if the rule should be considered, false otherwise.
     */
    override fun isApplicable(): Boolean = TODO()
}

Add logic to detect OS

package com.lapismc.minecraft.versioning

/**
 * Library inclusion rule for operating system checks.
 * @param os Operating system this rule applies to.
 * @param allowed Flag indicating whether the library should be included.
 */
class OSRule(val os: OSType, allowed: Boolean) : Rule(allowed) {
    companion object {
        /**
         * Name of the current operating system.
         */
        private val localOSName = System.getProperty("os.name").toLowerCase()

        /**
         * Checks whether the local system appears to be Windows.
         * @return True if the local OS is Windows, false otherwise.
         */
        fun isWindows() = localOSName.indexOf("win") >= 0

        /**
         * Checks whether the local system appears to be Mac OSX.
         * @return True if the local OS is Mac OSX, false otherwise.
         */
        fun isOSX() = localOSName.indexOf("mac") >= 0

        /**
         * Checks whether the local system appears to be Linux.
         * @return True if the local OS is Linux, false otherwise.
         */
        fun isLinux() = localOSName.indexOf("linux") >= 0
    }

    /**
     * Checks whether this rule applies to the current system.
     * @return True if the rule should be considered, false otherwise.
     */
    override fun isApplicable(): Boolean = when(os) {
        OSType.WINDOWS -> isWindows()
        OSType.OSX     -> isOSX()
        OSType.LINUX   -> isLinux()
    }
}


package Gradle_Util.buildTypes

import common.gradleWrapper
import jetbrains.buildServer.configs.kotlin.v2019_2.AbsoluteId
import jetbrains.buildServer.configs.kotlin.v2019_2.BuildType
import jetbrains.buildServer.configs.kotlin.v2019_2.CheckoutMode
import jetbrains.buildServer.configs.kotlin.v2019_2.Requirement
import jetbrains.buildServer.configs.kotlin.v2019_2.RequirementType

object WarmupEc2Agent : BuildType({
    uuid = "980bce31-2a3e-4563-9717-7c03e184f4a4"
    name = "Warmup EC2 Agent"
    id("Gradle_Util_WarmupEc2Agent")

    vcs {
        root(AbsoluteId("Gradle_Branches_GradlePersonalBranches"))
        checkoutMode = CheckoutMode.ON_AGENT
    }

    params {
        param("defaultBranchName", "master")
    }

    steps {
        gradleWrapper {
            name = "Resolve all dependencies"
            tasks = "resolveAllDependencies"
        }
    }

    requirements {
        requirement(Requirement(RequirementType.EQUALS, "teamcity.agent.name", "ec2-agent1"))
    }

})

Use build Java home for executing EC2 warmup build

package Gradle_Util.buildTypes

import common.gradleWrapper
import configurations.buildJavaHome
import jetbrains.buildServer.configs.kotlin.v2019_2.AbsoluteId
import jetbrains.buildServer.configs.kotlin.v2019_2.BuildType
import jetbrains.buildServer.configs.kotlin.v2019_2.CheckoutMode
import jetbrains.buildServer.configs.kotlin.v2019_2.Requirement
import jetbrains.buildServer.configs.kotlin.v2019_2.RequirementType

object WarmupEc2Agent : BuildType({
    uuid = "980bce31-2a3e-4563-9717-7c03e184f4a4"
    name = "Warmup EC2 Agent"
    id("Gradle_Util_WarmupEc2Agent")

    vcs {
        root(AbsoluteId("Gradle_Branches_GradlePersonalBranches"))
        checkoutMode = CheckoutMode.ON_AGENT
    }

    params {
        param("defaultBranchName", "master")
        param("env.JAVA_HOME", buildJavaHome())
    }

    steps {
        gradleWrapper {
            name = "Resolve all dependencies"
            tasks = "resolveAllDependencies"
        }
    }

    requirements {
        requirement(Requirement(RequirementType.EQUALS, "teamcity.agent.name", "ec2-agent1"))
    }

})


package com.cryart.sabbathschool.core.misc

import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import timber.log.Timber

object DateHelper {

    fun parseDate(date: String): DateTime? {
        return try {
            DateTimeFormat.forPattern(SSConstants.SS_DATE_FORMAT)
                .parseLocalDate(date).toDateTimeAtStartOfDay()
        } catch (ex: Exception) {
            Timber.e(ex)
            null
        }
    }

    fun formatDate(date: String, format: String = SSConstants.SS_DATE_FORMAT_OUTPUT_DAY): String {
        return try {
            DateTimeFormat.forPattern(format)
                .print(
                    DateTimeFormat.forPattern(SSConstants.SS_DATE_FORMAT)
                        .parseLocalDate(date)
                ).replaceFirstChar { it.uppercase() }
        } catch (ex: IllegalArgumentException) {
            Timber.e(ex)
            return ""
        }
    }
}

Add method to return today's date formatted

package com.cryart.sabbathschool.core.misc

import org.joda.time.DateTime
import org.joda.time.LocalDate
import org.joda.time.format.DateTimeFormat
import timber.log.Timber

object DateHelper {

    fun parseDate(date: String): DateTime? = try {
        DateTimeFormat.forPattern(SSConstants.SS_DATE_FORMAT)
            .parseLocalDate(date).toDateTimeAtStartOfDay()
    } catch (ex: Exception) {
        Timber.e(ex)
        null
    }

    fun formatDate(date: String, format: String = SSConstants.SS_DATE_FORMAT_OUTPUT_DAY): String = try {
        DateTimeFormat.forPattern(format)
            .print(
                DateTimeFormat.forPattern(SSConstants.SS_DATE_FORMAT)
                    .parseLocalDate(date)
            ).replaceFirstChar { it.uppercase() }
    } catch (ex: IllegalArgumentException) {
        Timber.e(ex)
        ""
    }

    fun today() = formatDate(LocalDate.now().toString(SSConstants.SS_DATE_FORMAT))
}


plugins {
	java
	id("com.github.johnrengelman.shadow") version "7.1.2"
}

group = "me.camdenorrb"
version = "1.1.0"

repositories {
	mavenCentral()
	maven("https://hub.spigotmc.org/nexus/content/repositories/public/") {
		name = "SpigotMC"
	}
}

dependencies {
	compileOnly("org.spigotmc:spigot-api:1.19-R0.1-SNAPSHOT")
}

Bump spigot-api from 1.19-R0.1-SNAPSHOT to 1.19.2-R0.1-SNAPSHOT

plugins {
	java
	id("com.github.johnrengelman.shadow") version "7.1.2"
}

group = "me.camdenorrb"
version = "1.1.0"

repositories {
	mavenCentral()
	maven("https://hub.spigotmc.org/nexus/content/repositories/public/") {
		name = "SpigotMC"
	}
}

dependencies {
	compileOnly("org.spigotmc:spigot-api:1.19.2-R0.1-SNAPSHOT")
}


Create a file to store and share the computeFt function

import machine.learning.Parameters
import machine.learning.Weights

/**
 * Compute the Ft layer using weights, vthreshold, returns and old_ft.
 * Given t, my need are :
 * - compute ft
 * - return the value and the sign
 *
 * @param givenT an Int. It's our index.
 * @param weight the weights of the neural net
 * @param ft the pair where first = the sign, second = the value, resulting of F_t
 * @param sizeWindow the number of considered items
 * @param returns the array of computed returns
 * @param parameters the parameters
 *
 * @return a pair of signum and value
 */
fun computeFt(givenT: Int, weight: Weights, ft:Array<Pair<Double,Double>>,
                      sizeWindow: Int, returns: DoubleArray, parameters: Parameters): Pair<Double, Double> {

    // this part doesn't depends on index
    var sum = weight.wMplusOne() * ft[givenT - 1].first + weight.vThreshold()

    // we get the useful weights and returns
    val usefulWeights: DoubleArray
    val usefulReturns: DoubleArray

    // if the t is smaller than our windows, we just take the t first elements
    // we sub 2 because the last weight is used with the F_{t-1}
    if (givenT < sizeWindow - 2) {
        // as said in the formal neural net layer :
        // w_{i,t} * r_{t-i}
        // so we need to reverse the returns array
        usefulWeights = weight.coefficients.sliceArray(0..givenT)
        usefulReturns = returns.sliceArray(0..givenT).reversedArray()

    } else {
        // we sub the (sizeWindow - 2) to always get the same number of elements than the weights
        // using the maxof(0, t-sizedwindow + 2) to avoid negative index
        // reverse the array for the same thing than above
        usefulWeights = weight.coefficients.sliceArray(0..(sizeWindow - 2))
        usefulReturns = returns.sliceArray(maxOf(0, givenT - sizeWindow + 2)..givenT).reversedArray()
    }

    // we zip the two array together and do the multiplication/sum
    for ((wi, ri) in usefulWeights.zip(usefulReturns)) {
        sum += wi * ri
    }

    // TODO: adding the x check not sure how.

    // we check the threshold
    // if it's greater than the threshold, we keep the result
    if (Math.abs(sum) > parameters.y) {
        return Pair(Math.signum(sum), sum)
    }
    // else we just do nothing
    return Pair(Math.signum(0.0), 0.0)
}


/*
 * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform
 * Copyright (C) 2003-2019 The IdeaVim authors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package org.jetbrains.plugins.ideavim.action.copy

import com.maddyhome.idea.vim.command.CommandState
import com.maddyhome.idea.vim.helper.StringHelper.parseKeys
import com.maddyhome.idea.vim.helper.VimBehaviourDiffers
import org.jetbrains.plugins.ideavim.VimTestCase

class PutTextAfterCursorActionTest : VimTestCase() {
  @VimBehaviourDiffers(originalVimAfter = """
        |Same length text 1
        |Same length text 2
        |Same length text 3
        |${c}Same length text 1
        |Same length text 2
  """)
  fun `test copy linear text using clipboard`() {
    doTest(parseKeys("Vj\"+y", "G\"+p"),
      """${c}Same length text 1
        |Same length text 2
        |Same length text 3
      """.trimMargin(),
      """Same length text 1
        |Same length text 2
        |Same length text 3
        |${c}Same length text 1
        |Same length text 2
        |
      """.trimMargin(),
      CommandState.Mode.COMMAND, CommandState.SubMode.NONE)
  }
}


@file:JvmName("Conductor")

package com.bluelinelabs.conductor

import android.app.Activity
import android.os.Bundle
import android.view.ViewGroup
import androidx.annotation.UiThread
import com.bluelinelabs.conductor.internal.LifecycleHandler
import com.bluelinelabs.conductor.internal.ensureMainThread

/**
 * Conductor will create a [Router] that has been initialized for your Activity and containing ViewGroup.
 * If an existing [Router] is already associated with this Activity/ViewGroup pair, either in memory
 * or in the savedInstanceState, that router will be used and rebound instead of creating a new one with
 * an empty backstack.
 *
 * @receiver The Activity that will host the [Router] being attached.
 * @param container The ViewGroup in which the [Router]'s [Controller] views will be hosted
 * @param savedInstanceState The savedInstanceState passed into the hosting Activity's onCreate method. Used
 * for restoring the Router's state if possible.
 * @return A fully configured [Router] instance for use with this Activity/ViewGroup pair.
 */
@UiThread
fun Activity.attachRouter(container: ViewGroup, savedInstanceState: Bundle?): Router {
  ensureMainThread()
  return LifecycleHandler.install(this)
    .getRouter(container, savedInstanceState)
    .also { it.rebindIfNeeded() }
}

Revert attachRouter as an extension

package com.bluelinelabs.conductor

import android.app.Activity
import android.os.Bundle
import android.view.ViewGroup
import androidx.annotation.UiThread
import com.bluelinelabs.conductor.internal.LifecycleHandler
import com.bluelinelabs.conductor.internal.ensureMainThread

/**
 * Conductor will create a [Router] that has been initialized for your Activity and containing ViewGroup.
 * If an existing [Router] is already associated with this Activity/ViewGroup pair, either in memory
 * or in the savedInstanceState, that router will be used and rebound instead of creating a new one with
 * an empty backstack.
 *
 * @param activity The Activity that will host the [Router] being attached.
 * @param container The ViewGroup in which the [Router]'s [Controller] views will be hosted
 * @param savedInstanceState The savedInstanceState passed into the hosting Activity's onCreate method. Used
 * for restoring the Router's state if possible.
 * @return A fully configured [Router] instance for use with this Activity/ViewGroup pair.
 */
@UiThread
object Conductor {

  @JvmStatic
  fun attachRouter(activity: Activity, container: ViewGroup, savedInstanceState: Bundle?): Router {
    ensureMainThread()
    return LifecycleHandler.install(activity)
      .getRouter(container, savedInstanceState)
      .also { it.rebindIfNeeded() }
  }
}


package com.hannesdorfmann.mosby.sample.kotlin

import android.util.Log
import com.hannesdorfmann.mosby.mvp.MvpBasePresenter
import com.hannesdorfmann.mosby.sample.kotlin.model.AsyncHeroesTask

/**
 * Presenter that loads list of heroes
 *
 * @author Hannes Dorfmann
 */
public class HeroesPresenter : MvpBasePresenter<HeroesView> () {

    val TAG = "HeroesPresenter"

    private var loaderTask: AsyncHeroesTask ? = null

    fun loadHeroes(pullToRefresh: Boolean) {

        Log.d(TAG, "loadHeroes({$pullToRefresh})")

        cancelIfRunning();

        // Show Loading
        getView()?.showLoading(pullToRefresh)

        // execute loading
        loaderTask = AsyncHeroesTask(
                pullToRefresh,
                { heroes, pullToRefresh ->
                    getView()?.setData(heroes)
                    getView()?.showContent()
                },
                { exception, pullToRefresh ->
                    getView()?.showError(exception, pullToRefresh)
                }
        )

        loaderTask?.execute()

    }

    fun cancelIfRunning() {

        // Cancel any previous one
        loaderTask?.cancel(true);
    }

    override fun detachView(retainInstance: Boolean) {
        super.detachView(retainInstance)

        val builder = StringBuilder("detachView({$retainInstance})")

        if (!retainInstance) {
            cancelIfRunning()
            builder.append(" --> cancel async task")
        }

        Log.d(TAG, builder.toString())
    }

}

Use kotlin properties instead of getter method

package com.hannesdorfmann.mosby.sample.kotlin

import android.util.Log
import com.hannesdorfmann.mosby.mvp.MvpBasePresenter
import com.hannesdorfmann.mosby.sample.kotlin.model.AsyncHeroesTask

/**
 * Presenter that loads list of heroes
 *
 * @author Hannes Dorfmann
 */
public class HeroesPresenter : MvpBasePresenter<HeroesView> () {

    val TAG = "HeroesPresenter"

    private var loaderTask: AsyncHeroesTask ? = null

    fun loadHeroes(pullToRefresh: Boolean) {

        Log.d(TAG, "loadHeroes({$pullToRefresh})")

        cancelIfRunning();

        // Show Loading
        view?.showLoading(pullToRefresh)

        // execute loading
        loaderTask = AsyncHeroesTask(
                pullToRefresh,
                { heroes, pullToRefresh ->
                    view?.setData(heroes)
                    view?.showContent()
                },
                { exception, pullToRefresh ->
                    view?.showError(exception, pullToRefresh)
                }
        )

        loaderTask?.execute()

    }

    fun cancelIfRunning() {

        // Cancel any previous one
        loaderTask?.cancel(true);
    }

    override fun detachView(retainInstance: Boolean) {
        super.detachView(retainInstance)

        val builder = StringBuilder("detachView({$retainInstance})")

        if (!retainInstance) {
            cancelIfRunning()
            builder.append(" --> cancel async task")
        }

        Log.d(TAG, builder.toString())
    }

}


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

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

plugins {
  id("java")
  kotlin("jvm")
  kotlin("kapt")
}

tasks.withType<KotlinCompile>().configureEach {
  kotlinOptions {
    allWarningsAsErrors = true
    jvmTarget = "1.8"
  }
}

dependencies {
  // Kotlin
  implementation(kotlin("stdlib", org.jetbrains.kotlin.config.KotlinCompilerVersion.VERSION))
  implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3")

  // Moshi
  api("com.squareup.moshi:moshi:1.9.2")
  api("com.squareup.moshi:moshi-adapters:1.9.2")
  kapt("com.squareup.moshi:moshi-kotlin-codegen:1.9.2")
}

Update Moshi libraries to their latest versions.

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

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

plugins {
  id("java")
  kotlin("jvm")
  kotlin("kapt")
}

tasks.withType<KotlinCompile>().configureEach {
  kotlinOptions {
    allWarningsAsErrors = true
    jvmTarget = "1.8"
  }
}

dependencies {
  // Kotlin
  implementation(kotlin("stdlib", org.jetbrains.kotlin.config.KotlinCompilerVersion.VERSION))
  implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3")

  // Moshi
  api("com.squareup.moshi:moshi:1.11.0")
  api("com.squareup.moshi:moshi-adapters:1.10.0")
  kapt("com.squareup.moshi:moshi-kotlin-codegen:1.11.0")
}


Add minecraft bridge command for bridging minecraft/discord

package me.mrkirby153.KirBot.net.command

import me.mrkirby153.KirBot.Bot
import me.mrkirby153.KirBot.net.NetworkMessage
import me.mrkirby153.KirBot.net.NetworkMessageHandler
import me.mrkirby153.KirBot.server.ServerRepository
import net.dv8tion.jda.core.EmbedBuilder
import java.awt.Color

class MinecraftBridge : NetworkMessageHandler {

    override val requireAuth = true

    override fun handle(message: NetworkMessage) {
        val bridgeMessage = ServerRepository.gson.fromJson(message.data, BridgeMessage::class.java)

        val guild = Bot.jda.getGuildById(message.guild) ?: return

       if(guild.textChannels.filter { it.id == bridgeMessage.channel }.count() < 1)
           return
        val channel = guild.getTextChannelById(bridgeMessage.channel)

        val embed = EmbedBuilder().run {
            setDescription(bridgeMessage.message)
            setColor(Color.WHITE)
            setAuthor(bridgeMessage.user, null, "https://minotar.net/helm/${bridgeMessage.user}")
            build()
        }
        channel.sendMessage(embed).queue()
    }
}

data class BridgeMessage(val channel: String, val user: String, val message: String)


package org.rust.lang.icons

import com.intellij.ide.IconProvider
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.RustStructDeclField
import org.rust.lang.core.psi.impl.*
import javax.swing.Icon

class RustIconProvider: IconProvider() {
    override fun getIcon(element: PsiElement, flags: Int): Icon? {
        return when (element) {
            is RustEnumItemImpl -> RustIcons.ENUM
            is RustStructItemImpl -> RustIcons.CLASS
            is RustStructDeclField -> RustIcons.FIELD
            is RustFnItemImpl -> RustIcons.FUNCTION
            is RustImplMethodImpl -> RustIcons.METHOD
            else -> null
        }
    }
}

Structure View: Add visibility icons to struct fields

package org.rust.lang.icons

import com.intellij.ide.IconProvider
import com.intellij.openapi.util.Iconable
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiUtil
import com.intellij.ui.RowIcon
import com.intellij.util.PlatformIcons
import com.intellij.util.VisibilityIcons
import com.intellij.util.ui.EmptyIcon
import org.rust.lang.core.psi.RustStructDeclField
import org.rust.lang.core.psi.impl.*
import javax.swing.Icon

class RustIconProvider: IconProvider() {
    override fun getIcon(element: PsiElement, flags: Int): Icon? {
        return when (element) {
            is RustEnumItemImpl -> RustIcons.ENUM
            is RustStructItemImpl -> RustIcons.CLASS
            is RustStructDeclField -> getStructDeclFieldIcon(element, flags)
            is RustFnItemImpl -> RustIcons.FUNCTION
            is RustImplMethodImpl -> RustIcons.METHOD
            else -> null
        }
    }

    private fun getStructDeclFieldIcon(element: RustStructDeclField, flags: Int): Icon? {
        if ((flags and Iconable.ICON_FLAG_VISIBILITY) == 0)
            return RustIcons.FIELD;

        val icon = RowIcon(RustIcons.FIELD, EmptyIcon.create(PlatformIcons.PUBLIC_ICON))
        val visibility = if (element.pub == null) PsiUtil.ACCESS_LEVEL_PRIVATE else PsiUtil.ACCESS_LEVEL_PUBLIC
        VisibilityIcons.setVisibilityIcon(visibility, icon);
        return icon;
    }
}


package org.purescript.psi

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

// PsiNamedElement is only here so that the editor can find the the
// Identifier when it is in a parameter
class PSIdentifierImpl(node: ASTNode) : PSPsiElement(node), ContainsIdentifier,
    PsiNamedElement {
    override fun getName(): String {
        return text
    }

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

    override val identifiers
        get() = mapOf<String?, PSIdentifierImpl>(Pair(this.name, this))
}

Convert short methods to expression syntax

package org.purescript.psi

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

// PsiNamedElement is only here so that the editor can find the the
// Identifier when it is in a parameter
class PSIdentifierImpl(node: ASTNode) : PSPsiElement(node), ContainsIdentifier,
    PsiNamedElement {
    override fun getName(): String = text

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

    override val identifiers
        get() = mapOf<String?, PSIdentifierImpl>(Pair(this.name, this))
}


Add security configuration and allows all requests

package backend

import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity

@Configuration
@EnableWebMvcSecurity
open class WebSecurityConfig : WebSecurityConfigurerAdapter() {

    // Add default security but for now allow all requests
    override fun configure(http: HttpSecurity) {
        http.authorizeRequests()
                .antMatchers("*").permitAll()
    }
}


package flavor.pie.kludge

import java.util.Optional

operator fun <T> Optional<T>?.not(): T? = this.unwrap()

val <T: Any> T?.optional: Optional<T> get() = Optional.ofNullable(this)

fun <T> Optional<T>?.unwrap(): T? = this?.orElse(null)

Convert `optional` into a function

package flavor.pie.kludge

import java.util.Optional

operator fun <T> Optional<T>?.not(): T? = this.unwrap()

fun <T: Any> T?.optional(): Optional<T> = Optional.ofNullable(this)

fun <T> Optional<T>?.unwrap(): T? = this?.orElse(null)


package com.elpassion.android.commons.espresso

import android.os.Bundle
import android.support.design.widget.TextInputEditText
import android.support.design.widget.TextInputLayout
import android.support.test.rule.ActivityTestRule
import android.widget.FrameLayout
import org.junit.Rule
import org.junit.Test

class TextInputEditTextHasHintAssertionTest {

    @JvmField @Rule
    val activityRule = ActivityTestRule(Activity::class.java)

    @Test
    fun shouldConfirmTextInputEditTextHasHint() {
        onId(anId).textInputEditTextHasHint(textId)
    }

    class Activity : android.app.Activity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(FrameLayout(this).apply {
                addView(TextInputLayout(this.context).apply {
                    addView(TextInputEditText(this.context).apply {
                        id = anId
                        hint = context.getString(textId)
                    })
                })
            })
        }
    }

    companion object {
        private val anId = 123
        private val textId = R.string.app_name
    }
}

Add test checking if assertion fails to match.

package com.elpassion.android.commons.espresso

import android.os.Bundle
import android.support.design.widget.TextInputEditText
import android.support.design.widget.TextInputLayout
import android.support.test.rule.ActivityTestRule
import android.widget.FrameLayout
import junit.framework.AssertionFailedError
import org.junit.Rule
import org.junit.Test

class TextInputEditTextHasHintAssertionTest {

    @JvmField @Rule
    val activityRule = ActivityTestRule(Activity::class.java)

    @Test
    fun shouldConfirmTextInputEditTextHasHint() {
        onId(anId).textInputEditTextHasHint(textId)
    }

    @Test(expected = AssertionFailedError::class)
    fun shouldFailToMatch() {
        onId(anId).textInputEditTextHasHint(R.string.abc_search_hint)
    }

    class Activity : android.app.Activity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(FrameLayout(this).apply {
                addView(TextInputLayout(this.context).apply {
                    addView(TextInputEditText(this.context).apply {
                        id = anId
                        hint = context.getString(textId)
                    })
                })
            })
        }
    }

    companion object {
        private val anId = 123
        private val textId = R.string.app_name
    }
}


package io.quarkus.hibernate.orm.panache.kotlin.runtime

import io.quarkus.hibernate.orm.panache.common.runtime.AbstractJpaOperations
import io.quarkus.runtime.annotations.Recorder

@Recorder
open class PanacheKotlinHibernateOrmRecorder {
    fun setEntityToPersistenceUnit(entityToPersistenceUnit: Map<String?, String?>?) {
        AbstractJpaOperations.setEntityToPersistenceUnit(entityToPersistenceUnit)
    }
}

Fix panache+kotlin named datasource issue

package io.quarkus.hibernate.orm.panache.kotlin.runtime

import io.quarkus.hibernate.orm.panache.common.runtime.AbstractJpaOperations
import io.quarkus.runtime.annotations.Recorder

@Recorder
open class PanacheKotlinHibernateOrmRecorder {
    open fun setEntityToPersistenceUnit(entityToPersistenceUnit: Map<String?, String?>?) {
        AbstractJpaOperations.setEntityToPersistenceUnit(entityToPersistenceUnit)
    }
}


fun main() {

    readLine() // ignore first input
    val str = readLine().orEmpty()

    var count = 0L
    val freqTable = buildFreqTable(str)

    // all singles
    for (freq in freqTable) count += triangleNumber(freq.second)

    // all "middle" cases
    for (i in 0 until freqTable.size - 2) {

        if (freqTable[i + 1].second == 1 && freqTable[i].first == freqTable[i + 2].first) {

            count += Math.min(freqTable[i].second, freqTable[i + 2].second)
        }
    }

    println(count)
}

private fun buildFreqTable(str: String): List<Pair<Char, Int>> {

    if (str.length == 1) return listOf(Pair(str[0], 1))

    val table = mutableListOf<Pair<Char, Int>>()
    var lastChar = str[0]
    var count = 1
    for (i in 1 until str.length) {

        if (str[i] == lastChar) count++
        else {
            table.add(Pair(lastChar, count))
            lastChar = str[i]
            count = 1
        }
    }

    table.add(Pair(lastChar, count))
    return table
}

private fun triangleNumber(n: Int) = (n * (n + 1L)) / 2L


package tornadofx.testapps

import javafx.animation.Animation
import javafx.animation.Interpolator
import javafx.scene.paint.Color
import tornadofx.*

class ShapeTransitionTest : App(Main::class) {
    class Main : View("Shape Transition Test") {
        var switch = true
        val nextFill get() = if (switch) c(1.0, 0.0, 0.0) else c(0.0, 0.0, 1.0)
        val nextStroke get() = if (switch) c(0.0, 0.0, 1.0) else c(1.0, 0.0, 0.0)
        override val root = stackpane {
            background = Color.BLACK.asBackground()
            val round = circle(radius = 100.0) {
                fill = nextFill
                stroke = nextStroke
                switch = !switch
                strokeWidth = 20.0
            }
            val orbit = circle(0.0, 0.0, 10.0) {
                animateFill(0.33.seconds, Color.ORANGE, Color.YELLOW) {
                    isAutoReverse = true
                    cycleCount = Animation.INDEFINITE
                }
            }.follow(3.seconds, round, Interpolator.LINEAR) { cycleCount = Animation.INDEFINITE }
            button("Click Me") {
                action {
                    isDisable = true
                    val startFill = round.fill as? Color ?: Color.BLACK
                    val endFill = nextFill
                    val startStroke = round.stroke as? Color ?: Color.BLACK
                    val endStroke = nextStroke
                    switch = !switch
                    listOf(
                            pause(0.75.seconds, play = false) { setOnFinished { orbit.rate = -orbit.rate } },
                            listOf(
                                    round.animateFill(0.25.seconds, startFill, endFill, play = false),
                                    round.animateStroke(0.25.seconds, startStroke, endStroke, play = false)
                            ).playParallel(false)
                    ).playSequential { setOnFinished { isDisable = false } }
                }
            }
        }
    }
}


/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

object AndroidComponents {
    const val VERSION = "92.0.20210721180104"
}

Update to Mozilla Android Components 92.0.20210730143121.

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

object AndroidComponents {
    const val VERSION = "92.0.20210730143121"
}


package org.wordpress.aztec.spans

import android.text.Editable
import org.wordpress.aztec.AztecAttributes
import org.wordpress.aztec.source.InlineCssStyleFormatter

interface IAztecAttributedSpan {
    var attributes: AztecAttributes

    /**
     * Parses and applies the HTML 'style' attribute.
     * @param output An [Editable] containing an [IAztecAttributedSpan] for processing.
     * @param start The index where the [IAztecAttributedSpan] starts inside the [text]
     */
    fun applyInlineStyleAttributes(output: Editable, start: Int, end: Int) {
        val attr = this.attributes
        if (attr.hasAttribute("style")) {
            InlineCssStyleFormatter.applyInlineStyleAttributes(output, attr, start, end)
        }
    }
}

Use a declared constant instead of "style" literal

package org.wordpress.aztec.spans

import android.text.Editable
import org.wordpress.aztec.AztecAttributes
import org.wordpress.aztec.source.InlineCssStyleFormatter

interface IAztecAttributedSpan {
    var attributes: AztecAttributes

    /**
     * Parses and applies the HTML 'style' attribute.
     * @param output An [Editable] containing an [IAztecAttributedSpan] for processing.
     * @param start The index where the [IAztecAttributedSpan] starts inside the [text]
     */
    fun applyInlineStyleAttributes(output: Editable, start: Int, end: Int) {
        val attr = this.attributes
        if (attr.hasAttribute(InlineCssStyleFormatter.STYLE_ATTRIBUTE)) {
            InlineCssStyleFormatter.applyInlineStyleAttributes(output, attr, start, end)
        }
    }
}


// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.tools

import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.CapturingProcessHandler
import com.jetbrains.python.PythonHelper
import com.jetbrains.python.sdk.PythonSdkUtil
import java.io.File
import kotlin.system.exitProcess

fun main() {
  val baseDir = getBaseDirValue()!!
  val pythons = System.getenv("PACK_STDLIB_FROM_PATH")

  try {
    for (python in File(pythons).listFiles()!!) {
      if (python.name.startsWith(".")) {
        continue
      }
      val sdkHome = python.absolutePath

      val executable = File(PythonSdkUtil.getPythonExecutable(sdkHome) ?: throw AssertionError("No python on $sdkHome"))
      println("Packing stdlib of $sdkHome")

      val cph = CapturingProcessHandler(GeneralCommandLine(executable.absolutePath, PythonHelper.GENERATOR3.asParamString(), "-u", baseDir))
      val output = cph.runProcess()
      println(output.stdout + output.stderr)
    }
  }
  finally {
    exitProcess(0)
  }
}

Introduce separate env variable for packed python sdk libs

// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.tools

import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.CapturingProcessHandler
import com.jetbrains.python.PythonHelper
import com.jetbrains.python.sdk.PythonSdkUtil
import java.io.File
import kotlin.system.exitProcess

fun main() {
  val pythons = System.getenv("PACK_STDLIB_FROM")
  val baseDir = System.getenv("PACK_STDLIB_TO")
  if (!File(baseDir).exists()) {
    File(baseDir).mkdirs()
  }

  try {
    for (python in File(pythons).listFiles()!!) {
      if (python.name.startsWith(".")) {
        continue
      }
      val sdkHome = python.absolutePath

      val executable = File(PythonSdkUtil.getPythonExecutable(sdkHome) ?: throw AssertionError("No python on $sdkHome"))
      println("Packing stdlib of $sdkHome")

      val cph = CapturingProcessHandler(GeneralCommandLine(executable.absolutePath, PythonHelper.GENERATOR3.asParamString(), "-u", baseDir))
      val output = cph.runProcess()
      println(output.stdout + output.stderr)
    }
  }
  finally {
    exitProcess(0)
  }
}


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

package com.facebook.fresco.vito.ktx

import android.net.Uri
import android.view.View
import com.facebook.fresco.vito.options.ImageOptions
import com.facebook.fresco.vito.view.VitoView

object ViewExtensions {

  fun View.show(uri: Uri) = VitoView.show(uri, this)

  fun View.show(uri: Uri, callerContext: Any) = VitoView.show(uri, callerContext, this)

  fun View.show(uri: Uri, imageOptions: ImageOptions) = VitoView.show(uri, imageOptions, this)

  fun View.show(uri: Uri, imageOptions: ImageOptions, callerContext: Any) =
      VitoView.show(uri, imageOptions, callerContext, this)
}

Add Extension Function That Supports ImageListener

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

package com.facebook.fresco.vito.ktx

import android.net.Uri
import android.view.View
import com.facebook.fresco.vito.listener.ImageListener
import com.facebook.fresco.vito.options.ImageOptions
import com.facebook.fresco.vito.view.VitoView

object ViewExtensions {

  fun View.show(uri: Uri) = VitoView.show(uri, this)

  fun View.show(uri: Uri, callerContext: Any) = VitoView.show(uri, callerContext, this)

  fun View.show(uri: Uri, imageOptions: ImageOptions) = VitoView.show(uri, imageOptions, this)

  fun View.show(uri: Uri, imageOptions: ImageOptions, imageListener: ImageListener) =
      VitoView.show(uri, imageOptions, imageListener, null, this)

  fun View.show(uri: Uri, imageOptions: ImageOptions, callerContext: Any) =
      VitoView.show(uri, imageOptions, callerContext, this)
}


package com.kamer.orny.data.room.entity

import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey

@Entity(tableName = "app_settings")
data class AppSettingsEntity(
        @PrimaryKey val id: Int = 0,
        @ColumnInfo(name = "default_author_id") val defaultAuthorId: String
)

Add app settings foreign key

package com.kamer.orny.data.room.entity

import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.ForeignKey
import android.arch.persistence.room.PrimaryKey

@Entity(
        tableName = "app_settings",
        foreignKeys = arrayOf(
                ForeignKey(
                        entity = AuthorEntity::class,
                        parentColumns = arrayOf("id"),
                        childColumns = arrayOf("default_author_id"),
                        onDelete = ForeignKey.SET_NULL
                )
        )
)
data class AppSettingsEntity(
        @PrimaryKey val id: Int = 0,
        @ColumnInfo(name = "default_author_id") val defaultAuthorId: String?
)


Add urban command for looking up urbandictionary definitions

package me.mrkirby153.KirBot.command.executors.`fun`

import me.mrkirby153.KirBot.command.BaseCommand
import me.mrkirby153.KirBot.command.Command
import me.mrkirby153.KirBot.command.CommandException
import me.mrkirby153.KirBot.command.args.CommandContext
import me.mrkirby153.KirBot.utils.Context
import me.mrkirby153.KirBot.utils.HttpUtils
import okhttp3.Request
import org.json.JSONObject
import org.json.JSONTokener
import java.net.URLEncoder

@Command(name = "urban", arguments = ["<term:string...>"])
class CommandUrban : BaseCommand(false) {
    override fun execute(context: Context, cmdContext: CommandContext) {
        val query = cmdContext.get<String>("term")!!

        val req = Request.Builder().url(
                "http://api.urbandictionary.com/v0/define?term=${URLEncoder.encode(query,
                        "UTF-8")}").build()

        val resp = HttpUtils.CLIENT.newCall(req).execute()

        val body = resp.body() ?: throw CommandException("Body is missing")

        val json = JSONObject(JSONTokener(body.string()))

        val resultType = json.getString("result_type")
        if (resultType == "no_results")
            throw CommandException("No definition found for `$query`")

        context.channel.sendMessage("$query - " +
                (json.getJSONArray("list")[0] as JSONObject).getString("definition")).queue()
    }
}


package com.hotpodata.twistris.utils

import android.graphics.Canvas
import com.hotpodata.blocklib.view.GridBinderView

/**
 * Created by jdrotos on 1/2/16.
 */
object GridOfColorsBlockDrawer : GridBinderView.RedBlockDrawer() {
    override fun drawBlock(canvas: Canvas, data: Any) {
        if (data is Int) {
            canvas.drawColor(data)
        } else {
            super.drawBlock(canvas, data)
        }
    }
}

Apply blocklib updates to prevent hardware layer badness

package com.hotpodata.twistris.utils

import android.graphics.Canvas
import android.graphics.RectF
import com.hotpodata.blocklib.view.GridBinderView

/**
 * Created by jdrotos on 1/2/16.
 */
object GridOfColorsBlockDrawer : GridBinderView.RedBlockDrawer() {
    override fun drawBlock(canvas: Canvas, blockCoords: RectF, data: Any) {
        if (data is Int) {
            paint.color = data
            canvas.drawRect(blockCoords, paint)
        } else {
            super.drawBlock(canvas, blockCoords, data)
        }
    }
}


package eu.kanade.tachiyomi.data.preference

import eu.kanade.tachiyomi.R

const val UNMETERED_NETWORK = "wifi"
const val CHARGING = "ac"

/**
 * This class stores the values for the preferences in the application.
 */
object PreferenceValues {

    /* ktlint-disable experimental:enum-entry-name-case */

    // Keys are lowercase to match legacy string values
    enum class ThemeMode {
        light,
        dark,
        system,
    }

    /* ktlint-enable experimental:enum-entry-name-case */

    enum class AppTheme(val titleResId: Int?) {
        DEFAULT(R.string.theme_default),
        BLUE(R.string.theme_blue),
        GREEN_APPLE(R.string.theme_greenapple),
        MIDNIGHT_DUSK(R.string.theme_midnightdusk),
        STRAWBERRY_DAIQUIRI(R.string.theme_strawberrydaiquiri),
        YOTSUBA(R.string.theme_yotsuba),

        // Deprecated
        HOT_PINK(null),
    }

    enum class TappingInvertMode(val shouldInvertHorizontal: Boolean = false, val shouldInvertVertical: Boolean = false) {
        NONE,
        HORIZONTAL(shouldInvertHorizontal = true),
        VERTICAL(shouldInvertVertical = true),
        BOTH(shouldInvertHorizontal = true, shouldInvertVertical = true),
    }
}

Add DARK_BLUE enum value back to avoid crash

package eu.kanade.tachiyomi.data.preference

import eu.kanade.tachiyomi.R

const val UNMETERED_NETWORK = "wifi"
const val CHARGING = "ac"

/**
 * This class stores the values for the preferences in the application.
 */
object PreferenceValues {

    /* ktlint-disable experimental:enum-entry-name-case */

    // Keys are lowercase to match legacy string values
    enum class ThemeMode {
        light,
        dark,
        system,
    }

    /* ktlint-enable experimental:enum-entry-name-case */

    enum class AppTheme(val titleResId: Int?) {
        DEFAULT(R.string.theme_default),
        BLUE(R.string.theme_blue),
        GREEN_APPLE(R.string.theme_greenapple),
        MIDNIGHT_DUSK(R.string.theme_midnightdusk),
        STRAWBERRY_DAIQUIRI(R.string.theme_strawberrydaiquiri),
        YOTSUBA(R.string.theme_yotsuba),

        // Deprecated
        DARK_BLUE(null),
        HOT_PINK(null),
    }

    enum class TappingInvertMode(val shouldInvertHorizontal: Boolean = false, val shouldInvertVertical: Boolean = false) {
        NONE,
        HORIZONTAL(shouldInvertHorizontal = true),
        VERTICAL(shouldInvertVertical = true),
        BOTH(shouldInvertHorizontal = true, shouldInvertVertical = true),
    }
}


/*
 * 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.
 */
import org.gradle.testing.performance.generator.tasks.JvmProjectGeneratorTask

tasks.register<JvmProjectGeneratorTask>("largeJavaProjectWithBuildScanPlugin") {
    dependencyGraph.run {
        size = 200
        depth = 5
        useSnapshotVersions = false // snapshots should not have a build scan specific performance impact
    }

    buildSrcTemplate = "buildsrc-plugins"
    setProjects(100)
    sourceFiles = 200
    testSourceFiles = 50 // verbose tests are time consuming
    filesPerPackage = 5
    linesOfCodePerSourceFile = 150
    numberOfScriptPlugins = 30
    rootProjectTemplates = listOf("root")
    subProjectTemplates = listOf("project-with-source")
    templateArgs = mapOf(
        "fullTestLogging" to true,
        "failedTests" to true,
        "projectDependencies" to true,
        "manyPlugins" to true,
        "manyScripts" to true
    )
}

Revert build scan performance test template size change

/*
 * 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.
 */
import org.gradle.testing.performance.generator.tasks.JvmProjectGeneratorTask

tasks.register<JvmProjectGeneratorTask>("largeJavaProjectWithBuildScanPlugin") {
    dependencyGraph.run {
        size = 200
        depth = 5
        useSnapshotVersions = false // snapshots should not have a build scan specific performance impact
    }

    buildSrcTemplate = "buildsrc-plugins"
    setProjects(250)
    sourceFiles = 200
    testSourceFiles = 50 // verbose tests are time consuming
    filesPerPackage = 5
    linesOfCodePerSourceFile = 150
    numberOfScriptPlugins = 30
    rootProjectTemplates = listOf("root")
    subProjectTemplates = listOf("project-with-source")
    templateArgs = mapOf(
        "fullTestLogging" to true,
        "failedTests" to true,
        "projectDependencies" to true,
        "manyPlugins" to true,
        "manyScripts" to true
    )
}


package com.elpassion.intelijidea.task.edit

import com.elpassion.intelijidea.task.MFTaskData
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import javax.swing.JComponent
import javax.swing.JTextField

class MFBeforeRunTaskDialog(project: Project) : DialogWrapper(project), TaskEditForm {

    private val taskEditValidator = TaskEditValidator(this)
    val form = MFBeforeRunTaskForm(project)

    init {
        isModal = true
        init()
    }

    override fun createCenterPanel(): JComponent {
        return form.panel
    }

    override fun doValidate(): ValidationInfo? {
        return taskEditValidator.doValidate()
    }

    override fun taskField(): JTextField {
        return form.taskField
    }

    override fun buildCommandField(): JTextField {
        return form.buildCommandField
    }

    override fun mainframerToolField(): TextFieldWithBrowseButton {
        return form.mainframerToolField
    }

    fun restoreMainframerTask(data: MFTaskData) {
        form.mainframerToolField.text = data.mainframerPath
        form.buildCommandField.text = data.buildCommand
        form.taskField.text = data.taskName
    }

    fun createMFTaskDataFromForms() = MFTaskData(
            mainframerPath = form.mainframerToolField.text,
            buildCommand = form.buildCommandField.text,
            taskName = form.taskField.text)
}

Convert methods bodies to expression

package com.elpassion.intelijidea.task.edit

import com.elpassion.intelijidea.task.MFTaskData
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import javax.swing.JComponent
import javax.swing.JTextField

class MFBeforeRunTaskDialog(project: Project) : DialogWrapper(project), TaskEditForm {

    private val taskEditValidator = TaskEditValidator(this)
    val form = MFBeforeRunTaskForm(project)

    init {
        isModal = true
        init()
    }

    override fun createCenterPanel(): JComponent = form.panel

    override fun doValidate(): ValidationInfo? = taskEditValidator.doValidate()

    override fun taskField(): JTextField = form.taskField

    override fun buildCommandField(): JTextField = form.buildCommandField

    override fun mainframerToolField(): TextFieldWithBrowseButton = form.mainframerToolField

    fun restoreMainframerTask(data: MFTaskData) {
        form.mainframerToolField.text = data.mainframerPath
        form.buildCommandField.text = data.buildCommand
        form.taskField.text = data.taskName
    }

    fun createMFTaskDataFromForms() = MFTaskData(
            mainframerPath = form.mainframerToolField.text,
            buildCommand = form.buildCommandField.text,
            taskName = form.taskField.text)
}


package com.example.billing

import com.example.billing.reocurringPayments.Service
import com.example.payments.Gateway
import com.example.payments.RecurlyGateway
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

@Configuration
// This class must not be final (final is the default in Kotlin)
// or Spring Boot is not happy.
open class Configuration {
    @Bean
    // This method must be overrideable (not overrideable is the default in Kotlin)
    // or Spring Boot is not happy.
    open fun paymentGateway(): Gateway = RecurlyGateway()

    @Bean
    // This method must be overrideable (not overrideable is the default in Kotlin)
    // or Spring Boot is not happy.
    open fun serviceThatMayFail(): Service = Service()
}

Leverage the type inference in Kotlin to eliminate some typing

package com.example.billing

import com.example.billing.reocurringPayments.Service
import com.example.payments.RecurlyGateway
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

@Configuration
// This class must not be final (final is the default in Kotlin)
// or Spring Boot is not happy.
open class Configuration {
    @Bean
    // This method must be overrideable (not overrideable is the default in Kotlin)
    // or Spring Boot is not happy.
    open fun paymentGateway() = RecurlyGateway()

    @Bean
    // This method must be overrideable (not overrideable is the default in Kotlin)
    // or Spring Boot is not happy.
    open fun serviceThatMayFail() = Service()
}


package io.ktor.http

internal actual fun allStatusCodes(): List<HttpStatusCode> = listOf(
    HttpStatusCode.Continue,
    HttpStatusCode.SwitchingProtocols,
    HttpStatusCode.Processing,
    HttpStatusCode.OK,
    HttpStatusCode.Created,
    HttpStatusCode.Accepted,
    HttpStatusCode.NonAuthoritativeInformation,
    HttpStatusCode.NoContent,
    HttpStatusCode.ResetContent,
    HttpStatusCode.PartialContent,
    HttpStatusCode.MultipleChoices,
    HttpStatusCode.MovedPermanently,
    HttpStatusCode.Found,
    HttpStatusCode.SeeOther,
    HttpStatusCode.NotModified,
    HttpStatusCode.UseProxy,
    HttpStatusCode.SwitchProxy,
    HttpStatusCode.TemporaryRedirect,
    HttpStatusCode.PermanentRedirect,
    HttpStatusCode.BadRequest,
    HttpStatusCode.Unauthorized,
    HttpStatusCode.PaymentRequired,
    HttpStatusCode.Forbidden,
    HttpStatusCode.NotFound,
    HttpStatusCode.MethodNotAllowed,
    HttpStatusCode.NotAcceptable,
    HttpStatusCode.ProxyAuthenticationRequired,
    HttpStatusCode.RequestTimeout,
    HttpStatusCode.Conflict,
    HttpStatusCode.Gone,
    HttpStatusCode.LengthRequired,
    HttpStatusCode.PreconditionFailed,
    HttpStatusCode.PayloadTooLarge,
    HttpStatusCode.RequestURITooLong,
    HttpStatusCode.UnsupportedMediaType,
    HttpStatusCode.RequestedRangeNotSatisfiable,
    HttpStatusCode.ExceptionFailed,
    HttpStatusCode.UpgradeRequired,
    HttpStatusCode.TooManyRequests,
    HttpStatusCode.RequestHeaderFieldTooLarge,
    HttpStatusCode.InternalServerError,
    HttpStatusCode.NotImplemented,
    HttpStatusCode.BadGateway,
    HttpStatusCode.ServiceUnavailable,
    HttpStatusCode.GatewayTimeout,
    HttpStatusCode.VersionNotSupported,
    HttpStatusCode.VariantAlsoNegotiates
)

Fix HTTP 417 status message (attempt 3)

package io.ktor.http

internal actual fun allStatusCodes(): List<HttpStatusCode> = listOf(
    HttpStatusCode.Continue,
    HttpStatusCode.SwitchingProtocols,
    HttpStatusCode.Processing,
    HttpStatusCode.OK,
    HttpStatusCode.Created,
    HttpStatusCode.Accepted,
    HttpStatusCode.NonAuthoritativeInformation,
    HttpStatusCode.NoContent,
    HttpStatusCode.ResetContent,
    HttpStatusCode.PartialContent,
    HttpStatusCode.MultipleChoices,
    HttpStatusCode.MovedPermanently,
    HttpStatusCode.Found,
    HttpStatusCode.SeeOther,
    HttpStatusCode.NotModified,
    HttpStatusCode.UseProxy,
    HttpStatusCode.SwitchProxy,
    HttpStatusCode.TemporaryRedirect,
    HttpStatusCode.PermanentRedirect,
    HttpStatusCode.BadRequest,
    HttpStatusCode.Unauthorized,
    HttpStatusCode.PaymentRequired,
    HttpStatusCode.Forbidden,
    HttpStatusCode.NotFound,
    HttpStatusCode.MethodNotAllowed,
    HttpStatusCode.NotAcceptable,
    HttpStatusCode.ProxyAuthenticationRequired,
    HttpStatusCode.RequestTimeout,
    HttpStatusCode.Conflict,
    HttpStatusCode.Gone,
    HttpStatusCode.LengthRequired,
    HttpStatusCode.PreconditionFailed,
    HttpStatusCode.PayloadTooLarge,
    HttpStatusCode.RequestURITooLong,
    HttpStatusCode.UnsupportedMediaType,
    HttpStatusCode.RequestedRangeNotSatisfiable,
    HttpStatusCode.ExpectationFailed,
    HttpStatusCode.UpgradeRequired,
    HttpStatusCode.TooManyRequests,
    HttpStatusCode.RequestHeaderFieldTooLarge,
    HttpStatusCode.InternalServerError,
    HttpStatusCode.NotImplemented,
    HttpStatusCode.BadGateway,
    HttpStatusCode.ServiceUnavailable,
    HttpStatusCode.GatewayTimeout,
    HttpStatusCode.VersionNotSupported,
    HttpStatusCode.VariantAlsoNegotiates
)


package org.jetbrains.plugins.ideavim.propertybased

import com.intellij.ide.IdeEventQueue
import com.intellij.openapi.editor.Editor
import com.intellij.testFramework.PlatformTestUtil
import com.maddyhome.idea.vim.command.CommandState
import com.maddyhome.idea.vim.helper.StringHelper
import com.maddyhome.idea.vim.helper.StringHelper.parseKeys
import com.maddyhome.idea.vim.key.CommandNode
import org.jetbrains.jetCheck.Generator
import org.jetbrains.jetCheck.ImperativeCommand
import org.jetbrains.jetCheck.PropertyChecker
import org.jetbrains.plugins.ideavim.VimTestCase

class YankDeletePropertyTest : VimPropertyTest() {
  fun testYankDelete() {
    PropertyChecker.checkScenarios {
      ImperativeCommand { env ->
        val editor = configureByText(loremText)
        try {
          moveCaretToRandomPlace(env, editor)
          env.executeCommands(Generator.sampledFrom(YankDeleteActions(editor)))
        } finally {
          reset(editor)
        }
      }
    }
  }
}

private class YankDeleteActions(private val editor: Editor) : ImperativeCommand {
  override fun performCommand(env: ImperativeCommand.Environment) {
    val key = env.generateValue(Generator.sampledFrom(keysList), null)

    env.logMessage("Use command: $key")
    VimTestCase.typeText(parseKeys(key), editor, editor.project)

    IdeEventQueue.getInstance().flushQueue()
    PlatformTestUtil.dispatchAllInvocationEventsInIdeEventQueue()
  }
}

private val keysList =
  arrayListOf("v", "V", "<C-V>", "h", "j", "k", "l", "w", "e", "b", "y", "Y", "_", "d", "D", "c", "C", "p", "P")


package eu.kanade.tachiyomi.data.preference

import androidx.preference.PreferenceDataStore

class EmptyPreferenceDataStore : PreferenceDataStore() {

    override fun getBoolean(key: String?, defValue: Boolean): Boolean {
        return false
    }

    override fun putBoolean(key: String?, value: Boolean) {
    }

    override fun getInt(key: String?, defValue: Int): Int {
        return 0
    }

    override fun putInt(key: String?, value: Int) {
    }

    override fun getLong(key: String?, defValue: Long): Long {
        return 0
    }

    override fun putLong(key: String?, value: Long) {
    }

    override fun getFloat(key: String?, defValue: Float): Float {
        return 0f
    }

    override fun putFloat(key: String?, value: Float) {
    }

    override fun getString(key: String?, defValue: String?): String? {
        return null
    }

    override fun putString(key: String?, value: String?) {
    }

    override fun getStringSet(key: String?, defValues: Set<String>?): Set<String>? {
        return null
    }

    override fun putStringSet(key: String?, values: Set<String>?) {
    }
}

Fix MultiSelectListPreference crash in extensions

package eu.kanade.tachiyomi.data.preference

import androidx.preference.PreferenceDataStore

class EmptyPreferenceDataStore : PreferenceDataStore() {

    override fun getBoolean(key: String?, defValue: Boolean): Boolean {
        return false
    }

    override fun putBoolean(key: String?, value: Boolean) {
    }

    override fun getInt(key: String?, defValue: Int): Int {
        return 0
    }

    override fun putInt(key: String?, value: Int) {
    }

    override fun getLong(key: String?, defValue: Long): Long {
        return 0
    }

    override fun putLong(key: String?, value: Long) {
    }

    override fun getFloat(key: String?, defValue: Float): Float {
        return 0f
    }

    override fun putFloat(key: String?, value: Float) {
    }

    override fun getString(key: String?, defValue: String?): String? {
        return null
    }

    override fun putString(key: String?, value: String?) {
    }

    override fun getStringSet(key: String?, defValues: Set<String>?): Set<String>? {
        return emptySet()
    }

    override fun putStringSet(key: String?, values: Set<String>?) {
    }
}


package com.ridi.books.helper.text

import java.util.Calendar

fun Long.elapsedTimeString(): String {
    var elapsed = System.currentTimeMillis() - this
    val second = 1000
    val minute = second * 60
    val hour = minute * 60
    val day = (hour * 24).toLong()
    val week = day * 7
    val suffix: String

    if (elapsed / week > 3) {
        val cal = Calendar.getInstance()
        cal.timeInMillis = this
        return "${cal.get(Calendar.YEAR)}.${cal.get(Calendar.MONDAY) + 1}.${cal.get(Calendar.DAY_OF_MONTH)}"
    } else if (elapsed / week > 0) {
        suffix = "주 전"
        elapsed /= week
    } else if (elapsed / day > 0) {
        suffix = "일 전"
        elapsed /= day
    } else if (elapsed / hour > 0) {
        suffix = "시간 전"
        elapsed /= hour
    } else if (elapsed / minute > 0) {
        suffix = "분 전"
        elapsed /= minute
    } else if (elapsed / second > 10) {
        suffix = "초 전"
        elapsed /= second
    } else {
        return "방금 전"
    }

    return "$elapsed$suffix"
}

Update elapsedTimeString - add ‘tooMuchElasped’ parameter that returned if more than 3 weeks have elapsed

package com.ridi.books.helper.text

fun Long.elapsedTimeString(tooMuchElapsed: String): String {
    var elapsed = System.currentTimeMillis() - this
    val second = 1000
    val minute = second * 60
    val hour = minute * 60
    val day = (hour * 24).toLong()
    val week = day * 7
    val suffix: String

    if (elapsed / week > 3) {
        return tooMuchElapsed
    } else if (elapsed / week > 0) {
        suffix = "주 전"
        elapsed /= week
    } else if (elapsed / day > 0) {
        suffix = "일 전"
        elapsed /= day
    } else if (elapsed / hour > 0) {
        suffix = "시간 전"
        elapsed /= hour
    } else if (elapsed / minute > 0) {
        suffix = "분 전"
        elapsed /= minute
    } else if (elapsed / second > 10) {
        suffix = "초 전"
        elapsed /= second
    } else {
        return "방금 전"
    }

    return "$elapsed$suffix"
}


package org.runestar.client.plugins.dev

import com.google.common.collect.Iterables
import org.runestar.client.game.api.live.LiveCanvas
import org.runestar.client.game.api.live.Npcs
import org.runestar.client.game.api.live.Players
import org.runestar.client.game.api.live.Projectiles
import org.runestar.client.plugins.spi.PluginSettings
import org.runestar.client.utils.DisposablePlugin
import java.awt.Color

class BoundingBoxTest : DisposablePlugin<PluginSettings>() {

    override val defaultSettings = PluginSettings()

    override fun start() {
        add(LiveCanvas.repaints.subscribe { g ->
            g.color = Color.WHITE

            val actors = Iterables.concat(Npcs, Players)
            actors.forEach { actor ->
                val m = actor.model ?: return@forEach
                m.drawBoundingBox(g)
            }

            Projectiles.forEach { p ->
                val m = p.model ?: return@forEach
                m.drawBoundingBox(g)
            }
        })
    }
}

Update bounding boxes dev plugin for all models

package org.runestar.client.plugins.dev

import com.google.common.collect.Iterables
import org.runestar.client.game.api.live.*
import org.runestar.client.plugins.spi.PluginSettings
import org.runestar.client.utils.DisposablePlugin
import java.awt.Color

class BoundingBoxTest : DisposablePlugin<PluginSettings>() {

    override val defaultSettings = PluginSettings()

    override fun start() {
        add(LiveCanvas.repaints.subscribe { g ->

            g.color = Color.WHITE
            val actors = Iterables.concat(Players, Npcs)
            actors.forEach {
                val m = it.model ?: return@forEach
                m.drawBoundingBox(g)
            }

            g.color = Color.ORANGE
            GroundItems.onPlane(Game.plane).forEach {
                val m = it.model ?: return@forEach
                m.drawBoundingBox(g)
            }

            g.color = Color.YELLOW
            Projectiles.forEach {
                val m = it.model ?: return@forEach
                m.drawBoundingBox(g)
            }

            g.color = Color.CYAN
            SceneObjects.Interactable.onPlane(Game.plane).forEach {
                val m = it.model ?: return@forEach
                m.drawBoundingBox(g)
            }

            g.color = Color.RED
            SceneObjects.Floor.onPlane(Game.plane).forEach {
                val m = it.model ?: return@forEach
                m.drawBoundingBox(g)
            }

            g.color = Color.BLUE
            SceneObjects.Wall.onPlane(Game.plane).forEach {
                it.models.forEach {
                    it.drawBoundingBox(g)
                }
            }

            g.color = Color.GREEN
            SceneObjects.Boundary.onPlane(Game.plane).forEach {
                it.models.forEach {
                    it.drawBoundingBox(g)
                }
            }
        })
    }
}


package jetbrains.buildServer.agent

import jetbrains.buildServer.agent.impl.OSTypeDetector
import jetbrains.buildServer.util.OSType
import jetbrains.buildServer.util.StringUtil
import java.io.File

class EnvironmentImpl(private val _fileSystemService: FileSystemService) : Environment {
    override fun tryGetVariable(name: String): String? {
        return System.getenv(name)
    }

    override val paths: Sequence<File>
        get() =
            tryGetVariable(PathEnvironmentVariableName)?.let {
                return StringUtil.splitHonorQuotes(it, File.pathSeparatorChar)
                        .asSequence()
                        .map { File(it) }
                        .filter { _fileSystemService.isExists(it) }
            } ?: emptySequence()

    override val os: OSType
        get() = OSDetector.detect() ?: OSType.UNIX

    companion object {
        private const val PathEnvironmentVariableName = "PATH"
        private val OSDetector = OSTypeDetector()
    }
}

Make .NET CLI more robust in finding dotnet core installation

package jetbrains.buildServer.agent

import jetbrains.buildServer.agent.impl.OSTypeDetector
import jetbrains.buildServer.util.OSType
import jetbrains.buildServer.util.StringUtil
import java.io.File

class EnvironmentImpl(private val _fileSystemService: FileSystemService) : Environment {
    override fun tryGetVariable(name: String): String? {
        return System.getenv(name)
    }

    override val paths: Sequence<File>
        get() =
            (tryGetVariable(PathEnvironmentVariableName)?.let { path ->
                StringUtil.splitHonorQuotes(path, File.pathSeparatorChar)
                        .asSequence()
                        .map { File(it) }
                        .filter { _fileSystemService.isExists(it) }
            } ?: emptySequence()) + getHintPaths()

    override val os: OSType
        get() = OSDetector.detect() ?: OSType.UNIX

    /**
     * Provides a well known paths for tools on each platform.
     */
    private fun getHintPaths(): Sequence<File> = sequence {
        when (os) {
            OSType.MAC -> yield(File("/usr/local/share/dotnet"))
            OSType.UNIX -> yield(File("/usr/share/dotnet"))
            OSType.WINDOWS -> yield(File("C:\\Program Files\\dotnet"))
        }
    }

    companion object {
        private const val PathEnvironmentVariableName = "PATH"
        private val OSDetector = OSTypeDetector()
    }
}


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

package io.michaelrocks.lightsaber.processor.graph

import java.util.*

fun <T> DirectedGraph<T>.findCycles(): Collection<Collection<T>> {
  val gray = HashSet<T>()
  val cycles = HashSet<Collection<T>>()
  val cycle = ArrayList<T>()

  traverseDepthFirst(
      beforeAdjacent = { vertex ->
        cycle.add(vertex)

        if (!gray.add(vertex)) {
          cycles.add(cycle.toList())
        }
      },
      afterAdjacent = { vertex ->
        gray.remove(vertex)
        cycle.removeAt(cycle.lastIndex)
      }
  )

  return cycles
}

Revert to a working cycle search algorithm

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

package io.michaelrocks.lightsaber.processor.graph

import java.util.*

fun <T> DirectedGraph<T>.findCycles(): Collection<Collection<T>> {
  val colors = HashMap<T, VertexColor>()
  val cycles = HashSet<Collection<T>>()

  fun traverse(vertex: T, cycle: MutableList<T>) {
    val color = colors[vertex]
    if (color == VertexColor.BLACK) {
      return
    }

    try {
      cycle.add(vertex)

      if (color == VertexColor.GRAY) {
        val cycleStartIndex = cycle.indexOf(vertex)
        cycles.add(cycle.subList(cycleStartIndex, cycle.size).toList())
        return
      }

      colors.put(vertex, VertexColor.GRAY)
      getAdjacentVertices(vertex)?.forEach { traverse(it, cycle) }
      colors.put(vertex, VertexColor.BLACK)
    } finally {
      cycle.removeAt(cycle.lastIndex)
    }
  }

  vertices.forEach { traverse(it, ArrayList()) }
  return cycles
}

private enum class VertexColor {
  GRAY, BLACK
}


package com.visiolink.app

import groovy.lang.Closure
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit

fun String.execute(dir: File? = null): String {
    val cmdArgs = split(" ")

    val process = ProcessBuilder(cmdArgs)
            .directory(dir)
            .redirectOutput(ProcessBuilder.Redirect.PIPE)
            .redirectError(ProcessBuilder.Redirect.PIPE)
            .start()

    return with(process) {
        waitFor(10, TimeUnit.SECONDS)
        inputStream.bufferedReader().readText()
    }
}

fun String.print(): String {
    println(this)
    return this
}

fun dateFormat(pattern: String,
               locale: Locale = Locale.getDefault(),
               block: SimpleDateFormat.() -> Unit = {}): SimpleDateFormat
        = SimpleDateFormat(pattern, locale).apply(block)

fun <T> closure(block: () -> T) = object : Closure<T>(null) {
    fun doCall(vararg args: Any?): T {
        return block.invoke()
    }
}

Make String extension functions internal

package com.visiolink.app

import groovy.lang.Closure
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit

internal fun String.execute(dir: File? = null): String {
    val cmdArgs = split(" ")

    val process = ProcessBuilder(cmdArgs)
            .directory(dir)
            .redirectOutput(ProcessBuilder.Redirect.PIPE)
            .redirectError(ProcessBuilder.Redirect.PIPE)
            .start()

    return with(process) {
        waitFor(10, TimeUnit.SECONDS)
        inputStream.bufferedReader().readText()
    }
}

internal fun String.print(): String {
    println(this)
    return this
}

fun dateFormat(pattern: String,
               locale: Locale = Locale.getDefault(),
               block: SimpleDateFormat.() -> Unit = {}): SimpleDateFormat
        = SimpleDateFormat(pattern, locale).apply(block)

fun <T> closure(block: () -> T) = object : Closure<T>(null) {
    fun doCall(vararg args: Any?): T {
        return block.invoke()
    }
}


package com.handstandsam.shoppingapp.cart

import com.handstandsam.shoppingapp.models.ItemWithQuantity
import kotlinx.coroutines.channels.ConflatedBroadcastChannel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow

/**
 * In memory implementation of our [ShoppingCartDao]
 */
class InMemoryShoppingCartDao : ShoppingCartDao {

    private val itemsInCart: MutableMap<String, ItemWithQuantity> = mutableMapOf()

    private val channel = ConflatedBroadcastChannel(listOf<ItemWithQuantity>())

    override suspend fun findByLabel(label: String): ItemWithQuantity? {
        return itemsInCart[label]
    }

    override suspend fun upsert(itemWithQuantity: ItemWithQuantity) {
        itemsInCart[itemWithQuantity.item.label] = itemWithQuantity
        sendUpdateChannel()
    }

    override suspend fun remove(itemWithQuantity: ItemWithQuantity) {
        itemsInCart.remove(itemWithQuantity.item.label)
        sendUpdateChannel()
    }

    override suspend fun empty() {
        itemsInCart.clear()
        sendUpdateChannel()
    }

    override val allItems: Flow<List<ItemWithQuantity>>
        get() = channel.asFlow()

    private suspend fun sendUpdateChannel() {
        channel.send(
            itemsInCart.values.toList()
                .sortedBy { it.item.label }
        )
    }

}

Make it more clear how we are sending updates to the channel.

package com.handstandsam.shoppingapp.cart

import com.handstandsam.shoppingapp.models.ItemWithQuantity
import kotlinx.coroutines.channels.ConflatedBroadcastChannel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow

/**
 * In memory implementation of our [ShoppingCartDao]
 */
class InMemoryShoppingCartDao : ShoppingCartDao {

    private val itemsInCart: MutableMap<String, ItemWithQuantity> = mutableMapOf()

    private val channel = ConflatedBroadcastChannel(listOf<ItemWithQuantity>())

    override suspend fun findByLabel(label: String): ItemWithQuantity? {
        return itemsInCart[label]
    }

    override suspend fun upsert(itemWithQuantity: ItemWithQuantity) {
        itemsInCart[itemWithQuantity.item.label] = itemWithQuantity
        channel.send(itemsInCart.asSortedList())
    }

    override suspend fun remove(itemWithQuantity: ItemWithQuantity) {
        itemsInCart.remove(itemWithQuantity.item.label)
        channel.send(itemsInCart.asSortedList())
    }

    override suspend fun empty() {
        itemsInCart.clear()
        channel.send(itemsInCart.asSortedList())
    }

    override val allItems: Flow<List<ItemWithQuantity>>
        get() = channel.asFlow()

    private fun MutableMap<String, ItemWithQuantity>.asSortedList(): List<ItemWithQuantity> {
        return values.toList()
            .sortedBy { it.item.label }
    }

}


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

package org.rust.ide.annotator

import org.rust.ide.lineMarkers.RsLineMarkerProviderTestBase

/**
 * Tests for Trait Method Implementation Line Marker
 */
class RsTraitMethodImplLineMarkerProviderTest : RsLineMarkerProviderTestBase() {

    fun `test impl`() = doTestByText("""
        trait Foo {         // - Has implementations
            fn foo(&self);
            fn bar(&self) {
                self.foo();
            }
        }
        struct Bar {} // - Has implementations
        impl Foo for Bar {
            fn foo(&self) { // - Implements method in `Foo`
            }
            fn bar(&self) { // - Overrides method in `Foo`
            }
        }
    """)

    fun `test icon position`() = doTestByText("""
        trait
        Foo // - Has implementations
        {
            fn
            foo
            (&self);

            type
            T1
            ;

            const
            C1
            : u32;
        }
        struct
        Bar // - Has implementations
        {}
        impl Foo for Bar {
            ///
            /// Documentation
            ///
            #[warn(non_camel_case_types)]
            fn
            foo // - Implements method in `Foo`
            (&self) {
            }

            type
            T1
            = ();

            const
            C1
            : u32 = 1;
        }
    """)
}

Extend line marker related tests for "const" and "type"

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

package org.rust.ide.annotator

import org.rust.ide.lineMarkers.RsLineMarkerProviderTestBase

/**
 * Tests for Trait Method Implementation Line Marker
 */
class RsTraitMethodImplLineMarkerProviderTest : RsLineMarkerProviderTestBase() {

    fun `test impl`() = doTestByText("""
        trait Foo {         // - Has implementations
            fn foo(&self);
            fn bar(&self) {
                self.foo();
            }
            type T1;
            type T2 = ();
            const C1: u32;
            const C2: u32 = 1;
        }
        struct Bar {} // - Has implementations
        impl Foo for Bar {
            fn foo(&self) { // - Implements method in `Foo`
            }
            fn bar(&self) { // - Overrides method in `Foo`
            }
            type T1 = ();
            type T2 = ();
            const C1: u32 = 1;
            const C2: u32 = 1;
        }
    """)

    fun `test icon position`() = doTestByText("""
        trait
        Foo // - Has implementations
        {
            fn
            foo
            (&self);

            type
            T1
            ;

            const
            C1
            : u32;
        }
        struct
        Bar // - Has implementations
        {}
        impl Foo for Bar {
            ///
            /// Documentation
            ///
            #[warn(non_camel_case_types)]
            fn
            foo // - Implements method in `Foo`
            (&self) {
            }

            type
            T1
            = ();

            const
            C1
            : u32 = 1;
        }
    """)
}


package jp.toastkid.yobidashi.planning_poker

import android.databinding.DataBindingUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup

import jp.toastkid.yobidashi.R
import jp.toastkid.yobidashi.databinding.CardItemBinding

/**
 * RecyclerView's adapter.

 * @author toastkidjp
 */
internal class Adapter : RecyclerView.Adapter<CardViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardViewHolder {
        return CardViewHolder(
                DataBindingUtil.inflate<CardItemBinding>(
                        LayoutInflater.from(parent.context),
                        R.layout.card_item,
                        parent,
                        false
                )
        )
    }

    override fun onBindViewHolder(holder: CardViewHolder, position: Int) {
        val text = Suite.values()[position % Suite.values().size].text()
        holder.setText(text)
        holder.itemView.setOnClickListener { v -> holder.open() }
    }

    override fun getItemCount(): Int {
        return MAXIMUM_SIZE
    }

    companion object {

        /** Maximum size.  */
        private val MAXIMUM_SIZE = Suite.values().size * 20

        /** Medium.  */
        private val MEDIUM = MAXIMUM_SIZE / 2

        fun medium(): Int {
            return MEDIUM
        }
    }
}

Clean up Planning Poker's adapter.

package jp.toastkid.yobidashi.planning_poker

import android.databinding.DataBindingUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup

import jp.toastkid.yobidashi.R
import jp.toastkid.yobidashi.databinding.CardItemBinding

/**
 * RecyclerView's adapter.
 *
 * @author toastkidjp
 */
internal class Adapter : RecyclerView.Adapter<CardViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardViewHolder {
        return CardViewHolder(
                DataBindingUtil.inflate<CardItemBinding>(
                        LayoutInflater.from(parent.context),
                        R.layout.card_item,
                        parent,
                        false
                )
        )
    }

    override fun onBindViewHolder(holder: CardViewHolder, position: Int) {
        val text = Suite.values()[position % Suite.values().size].text()
        holder.setText(text)
        holder.itemView.setOnClickListener { v -> holder.open() }
    }

    override fun getItemCount(): Int = MAXIMUM_SIZE

    companion object {

        /**
         * Maximum size.
         */
        private val MAXIMUM_SIZE = Suite.values().size * 20

        /**
         * Medium.
         */
        private val MEDIUM = MAXIMUM_SIZE / 2

        /**
         * Return medium number.
         */
        fun medium(): Int = MEDIUM
    }
}


package io.github.vyo.twig

import nl.komponents.kovenant.async
import kotlin.concurrent.currentThread

/**
 * Created by Manuel Weidmann on 24.11.2015.
 */

class Logger(caller: Any) {

    val caller: Any = caller

    var threshold: Level = Level.DEBUG

    companion object root {
        var threshold: Level = Level.INFO
    }

    fun log(message: String, level: Level) {
        if (level < threshold || level < root.threshold) return
        val thread: Thread = currentThread
        async {
            println("{${ escape("thread") }:${ escape(thread) }" +
                    "${escape("time")}:${escape(System.currentTimeMillis())}," +
                    "${escape("level")}:${escape(level.toInt())}," +
                    "${ escape("name") }:${ escape(caller) }, " +
                    "${escape("message")}:${escape(message)}}")
        }
    }

    private fun escape(string: Any): String {
        return "\"${string.toString()}\""
    }

    fun trace(message: String) {
        log(message, Level.TRACE)
    }

    fun debug(message: String) {
        log(message, Level.DEBUG)
    }

    fun info(message: String) {
        log(message, Level.INFO)
    }

    fun warn(message: String) {
        log(message, Level.WARN)
    }

    fun error(message: String) {
        log(message, Level.ERROR)
    }

    fun fatal(message: String) {
        log(message, Level.FATAL)
    }
}

Set default log level to INFO

package io.github.vyo.twig

import nl.komponents.kovenant.async
import kotlin.concurrent.currentThread

/**
 * Created by Manuel Weidmann on 24.11.2015.
 */

class Logger(caller: Any) {

    val caller: Any = caller

    var threshold: Level = Level.INFO

    companion object root {
        var threshold: Level = Level.INFO
    }

    fun log(message: String, level: Level) {
        if (level < threshold || level < root.threshold) return
        val thread: Thread = currentThread
        async {
            println("{${ escape("thread") }:${ escape(thread) }" +
                    "${escape("time")}:${escape(System.currentTimeMillis())}," +
                    "${escape("level")}:${escape(level.toInt())}," +
                    "${ escape("name") }:${ escape(caller) }, " +
                    "${escape("message")}:${escape(message)}}")
        }
    }

    private fun escape(string: Any): String {
        return "\"${string.toString()}\""
    }

    fun trace(message: String) {
        log(message, Level.TRACE)
    }

    fun debug(message: String) {
        log(message, Level.DEBUG)
    }

    fun info(message: String) {
        log(message, Level.INFO)
    }

    fun warn(message: String) {
        log(message, Level.WARN)
    }

    fun error(message: String) {
        log(message, Level.ERROR)
    }

    fun fatal(message: String) {
        log(message, Level.FATAL)
    }
}


package br.com.bloder.migration

import br.com.bloder.migration.internal.InternalMigration

/**
 * Class to abstract realm migration
 */
class Migration : InternalMigration {

    /**
     * Represents what will change in a migration version
     */
    override fun up() {}

    /**
     * Represents what will be discarded when that migration version
     * does not exist anymore
     */
    override fun down() {}
}

Set dynamic realm object as param in migration

package br.com.bloder.migration

import br.com.bloder.migration.internal.InternalMigration
import io.realm.DynamicRealm

/**
 * Class to abstract realm migration
 */
open class Migration : InternalMigration {

    /**
     * Represents what will change in a migration version
     */
    override fun up(realm: DynamicRealm?) {}

    /**
     * Represents what will be discarded when that migration version
     * does not exist anymore
     */
    override fun down(realm: DynamicRealm?) {}
}


/*
 * This is an init script for internal usage at Gradle Inc.
 */
if (!gradle.startParameter.systemPropertiesArgs.containsKey("disableScanPlugin")) {
    rootProject {
        pluginManager.withPlugin("com.gradle.build-scan") {
            extensions["buildScan"].withGroovyBuilder {
                if (gradle.startParameter.taskNames in listOf(listOf("verifyTestFilesCleanup"), listOf("killExistingProcessesStartedByGradle"))) {
                    "publishOnFailure"()
                } else {
                    "publishAlways"()
                }
                setProperty("server", "https://e.grdev.net")
            }
        }
    }
}

Create build scan only when tagging fails

/*
 * This is an init script for internal usage at Gradle Inc.
 */
val tasksWithBuildScansOnFailure = listOf("verifyTestFilesCleanup", "killExistingProcessesStartedByGradle", "tagBuild").map { listOf(it)}

if (!gradle.startParameter.systemPropertiesArgs.containsKey("disableScanPlugin")) {
    rootProject {
        pluginManager.withPlugin("com.gradle.build-scan") {
            extensions["buildScan"].withGroovyBuilder {
                if (gradle.startParameter.taskNames in tasksWithBuildScansOnFailure) {
                    "publishOnFailure"()
                } else {
                    "publishAlways"()
                }
                setProperty("server", "https://e.grdev.net")
            }
        }
    }
}


package io.github.vyo.twig

import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.shouldEqual

/**
 * Created by Manuel Weidmann on 28.11.2015.
 */
class LoggerSpec : Spek() {
    init {
        given("nothing") {
            on("initialisation") {
                it("should setup root logger log threshold") {
                    shouldEqual(Level.INFO, Logger.root.threshold)
                }
            }
            on("invocation") {
                it("should be able to log messages as 'root'") {
                    Logger.root.info("logging test $this")
                }
            }
        }

    }
}


Add example with use case of addPropText

package sandbox.view

import com.almasb.fxgl.app.GameApplication
import com.almasb.fxgl.app.GameSettings
import com.almasb.fxgl.dsl.FXGL
import com.almasb.fxgl.dsl.getGameScene
import javafx.scene.paint.Color

class PropertyMapTest : GameApplication() {

    override fun initSettings(settings: GameSettings) {
        settings.width = 800
        settings.height = 600
        settings.title = "PropertyMap value display sample"
    }

    override fun initUI() {
        getGameScene().setBackgroundColor(Color.BLACK)
        FXGL.getWorldProperties().setValue("String property", "string value")
        FXGL.getWorldProperties().setValue("Integer property", 100)
        FXGL.getWorldProperties().setValue("Double property", 1001.1001)
        FXGL.getWorldProperties().setValue("Boolean property", true)
        FXGL.getWorldProperties().setValue("Object property", this)

        FXGL.addPropText("String property", 10.0, 20.0)
        FXGL.addPropText("Integer property", 10.0, 40.0)
        FXGL.addPropText("Double property", 10.0, 60.0)
        FXGL.addPropText("Boolean property", 10.0, 80.0)
        FXGL.addPropText("Object property", 10.0, 100.0)

    }

    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            launch(PropertyMapTest::class.java, args)
        }
    }
}


package com.sedsoftware.yaptalker.data.model

import android.os.Parcel
import android.os.Parcelable
import pl.droidsonroids.jspoon.annotation.Selector

class ForumPage() : Parcelable {
  @Selector("a[href~=.*/forum\\d+/].title")
  lateinit var forumTitle: String
  @Selector("a[href~=.*/forum\\d+/].title", attr = "href", defValue = "0")
  lateinit var forumId: String
  @Selector("a[title~=Страница: \\d+]", attr = "title", defValue = "0")
  lateinit var totalPages: String
  @Selector("table tr + tr")
  lateinit var topics: List<Topic>

  constructor(parcel: Parcel) : this() {
    forumTitle = parcel.readString()
    forumId = parcel.readString()
    totalPages = parcel.readString()
    topics = parcel.createTypedArrayList(Topic)
  }

  override fun writeToParcel(parcel: Parcel, flags: Int) {
    parcel.writeString(forumTitle)
    parcel.writeString(forumId)
    parcel.writeString(totalPages)
    parcel.writeTypedList(topics)
  }

  override fun describeContents() = 0

  companion object CREATOR : Parcelable.Creator<ForumPage> {
    override fun createFromParcel(parcel: Parcel): ForumPage = ForumPage(parcel)
    override fun newArray(size: Int): Array<ForumPage?> = arrayOfNulls(size)
  }
}

class Topic() : Parcelable {
  @Selector("a.subtitle") lateinit var title: String
  @Selector("a.subtitle", attr = "href") lateinit var link: String
  @Selector("td.row2 > a") lateinit var author: String
  @Selector("td.row2 > a", attr = "href") lateinit var authorLink: String
  @Selector("div.rating-short-value") lateinit var rating: String
  @Selector("td.row4:matchesOwn(\\d+)") lateinit var answers: String
  @Selector("td.row2 > .desc", format = "([0-9\\.]+ - [0-9:]+)") lateinit var lastPostDate: String
  @Selector("span.desc a ~ a") lateinit var lastPostAuthor: String

  constructor(parcel: Parcel) : this() {
    title = parcel.readString()
    link = parcel.readString()
    author = parcel.readString()
    authorLink = parcel.readString()
    rating = parcel.readString()
    answers = parcel.readString()
    lastPostDate = parcel.readString()
    lastPostAuthor = parcel.readString()
  }

  override fun writeToParcel(parcel: Parcel, flags: Int) {
    parcel.writeString(title)
    parcel.writeString(link)
    parcel.writeString(author)
    parcel.writeString(authorLink)
    parcel.writeString(rating)
    parcel.writeString(answers)
    parcel.writeString(lastPostDate)
    parcel.writeString(lastPostAuthor)
  }

  override fun describeContents() = 0

  companion object CREATOR : Parcelable.Creator<Topic> {
    override fun createFromParcel(parcel: Parcel): Topic = Topic(parcel)
    override fun newArray(size: Int): Array<Topic?> = arrayOfNulls(size)
  }
}


package com.veyndan.paper.reddit.api.reddit.network.interceptor

import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response

class UserAgentInterceptor(userAgentHeaderValue: String) : Interceptor {

    companion object {

        private const val USER_AGENT_HEADER_NAME = "User-Agent"
    }

    private val userAgentHeaderValue: String = checkNotNull(userAgentHeaderValue)

    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest: Request = chain.request()
        val requestWithUserAgent: Request = originalRequest.newBuilder()
                .header(USER_AGENT_HEADER_NAME, userAgentHeaderValue)
                .build()
        return chain.proceed(requestWithUserAgent)
    }
}

Use Kotlin nullability type system

package com.veyndan.paper.reddit.api.reddit.network.interceptor

import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response

class UserAgentInterceptor(private val userAgentHeaderValue: String) : Interceptor {

    companion object {

        private const val USER_AGENT_HEADER_NAME = "User-Agent"
    }

    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest: Request = chain.request()
        val requestWithUserAgent: Request = originalRequest.newBuilder()
                .header(USER_AGENT_HEADER_NAME, userAgentHeaderValue)
                .build()
        return chain.proceed(requestWithUserAgent)
    }
}


plugins {
    id("com.neva.fork")
    id("com.cognifide.aem.common")
}

description = "Example"
defaultTasks("develop")

aem {
    tasks {
        sequence("develop", {
            description = "Builds and deploys AEM application, cleans environment then runs integration and functional tests"
        }) {
            dependsOrdered(
                    ":aem:instanceSatisfy",
                    ":aem:assembly:full:packageDeploy",
                    ":aem:environmentClean",
                    ":aem:environmentCheck",
                    ":test:integration:test",
                    ":test:functional:test",
                    ":test:performance:test"
            )
        }
    }
}

apply(from = "gradle/fork.gradle.kts")
apply(from = "gradle/common.gradle.kts")

Update develop task description to mention performance testing

plugins {
    id("com.neva.fork")
    id("com.cognifide.aem.common")
}

description = "Example"
defaultTasks("develop")

aem {
    tasks {
        sequence("develop", {
            description = "Builds and deploys AEM application, cleans environment then runs integration, functional and performance tests"
        }) {
            dependsOrdered(
                    ":aem:instanceSatisfy",
                    ":aem:assembly:full:packageDeploy",
                    ":aem:environmentClean",
                    ":aem:environmentCheck",
                    ":test:integration:test",
                    ":test:functional:test",
                    ":test:performance:test"
            )
        }
    }
}

apply(from = "gradle/fork.gradle.kts")
apply(from = "gradle/common.gradle.kts")


package org.purescript.psi.declaration

import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameIdentifierOwner
import org.purescript.psi.PSPsiElement
import org.purescript.psi.name.PSOperatorName

class PSFixityDeclaration(node: ASTNode) : PSPsiElement(node), PsiNameIdentifierOwner {
    private val operatorName get() =
        findNotNullChildByClass(PSOperatorName::class.java)

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

    override fun getNameIdentifier(): PsiElement {
        return operatorName;
    }

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

Fix navigation location for fixity declaration

package org.purescript.psi.declaration

import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameIdentifierOwner
import org.purescript.psi.PSPsiElement
import org.purescript.psi.name.PSOperatorName

class PSFixityDeclaration(node: ASTNode) : PSPsiElement(node), PsiNameIdentifierOwner {
    private val operatorName get() =
        findNotNullChildByClass(PSOperatorName::class.java)

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

    override fun getTextOffset(): Int = nameIdentifier.textOffset

    override fun getNameIdentifier(): PsiElement {
        return operatorName;
    }

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


package org.wordpress.aztec.plugins.wpcomments.spans

import android.text.TextPaint
import android.text.style.CharacterStyle

class GutenbergCommentSpan(var content: String) : CharacterStyle() {
    override fun updateDrawState(tp: TextPaint) {
    }
}

Make Gutenberg comment span a block span to properly handle newlines

package org.wordpress.aztec.plugins.wpcomments.spans

import android.text.Layout
import org.wordpress.aztec.AztecAttributes
import org.wordpress.aztec.spans.IAztecBlockSpan

class GutenbergCommentSpan(
        override val startTag: String,
        override var nestingLevel: Int,
        override var attributes: AztecAttributes = AztecAttributes()
) : IAztecBlockSpan {
    override val TAG: String = "wp:"
    override var align: Layout.Alignment? = null
    override var startBeforeCollapse: Int = -1
    override var endBeforeBleed: Int = -1

    private var _endTag: String = super.endTag
    override var endTag: String
        get() = _endTag
        set(value) {
            _endTag = value
        }
}


Add extension functions for ClassVisitor

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

package io.michaelrocks.lightsaber.processor.commons

import io.michaelrocks.lightsaber.processor.descriptors.MethodDescriptor
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.Opcodes
import org.objectweb.asm.Type

fun ClassVisitor.newMethod(access: Int, method: MethodDescriptor, body: GeneratorAdapter.() -> Unit) {
  GeneratorAdapter(this, access, method).apply {
    visitCode()
    body()
    returnValue()
    endMethod()
  }
}

fun ClassVisitor.newDefaultConstructor(access: Int = Opcodes.ACC_PUBLIC, superType: Type = Types.OBJECT_TYPE) {
  newMethod(access, MethodDescriptor.forDefaultConstructor()) {
    loadThis()
    invokeConstructor(superType, MethodDescriptor.forDefaultConstructor())
  }
}