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

import kotlinx.coroutines.experimental.IO
import kotlinx.coroutines.experimental.withContext
import splitties.preferences.Preferences
import splitties.uithread.isUiThread

/**
 * **Requires** you have the following dependency in your project:
 * `org.jetbrains.kotlinx:kotlinx-coroutines-android:0.25.3`
 */
abstract class SuspendPrefsAccessor<out Prefs : Preferences>(prefsConstructorRef: () -> Prefs) {
    suspend operator fun invoke(): Prefs {
        return if (prefDelegate.isInitialized()) prefs else withContext(IO) {
            check(!isUiThread) {
                "Instantiating SharedPreferences performs I/O, which is not allowed on UI thread."
            }
            prefs
        }
    }

    private val prefDelegate = lazy(prefsConstructorRef)
    private val prefs by prefDelegate
}

Remove no longer needed not UI thread check

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

import kotlinx.coroutines.experimental.IO
import kotlinx.coroutines.experimental.withContext
import splitties.preferences.Preferences

/**
 * **Requires** you have the following dependency in your project:
 * `org.jetbrains.kotlinx:kotlinx-coroutines-android:0.25.3`
 */
abstract class SuspendPrefsAccessor<out Prefs : Preferences>(prefsConstructorRef: () -> Prefs) {
    suspend operator fun invoke(): Prefs {
        return if (prefDelegate.isInitialized()) prefs else withContext(IO) { prefs }
    }

    private val prefDelegate = lazy(prefsConstructorRef)
    private val prefs by prefDelegate
}


package com.github.davinkevin.podcastserver.extension.java.net

import org.apache.commons.io.FilenameUtils
import java.net.URI

/**
 * Created by kevin on 12/07/2020
 */
fun URI.extension(): String = FilenameUtils
        .getExtension(this.toASCIIString())
        .let { if (it.isEmpty()) "jpg" else it.substringBeforeLast("?") }

Remove usage of apache commons for file extension extraction

package com.github.davinkevin.podcastserver.extension.java.net

import java.net.URI

/**
 * Created by kevin on 12/07/2020
 */
fun URI.extension(): String {
    val path = this.path

    if(!path.contains(".")) {
        return "jpg"
    }

    return path.substringAfterLast(".")
}


description = "${rootProject.description} (Bill of Materials)"

apply(from = "$rootDir/gradle/publishing.gradle.kts")

dependencies {
	constraints {
		val mavenizedProjects: List<Project> by rootProject.extra
		mavenizedProjects.sorted()
				.filter { it.name != "junit-platform-console-standalone" }
				.forEach { api("${it.group}:${it.name}:${it.version}") }
	}
}

the<PublishingExtension>().publications.named<MavenPublication>("maven") {
	from(components["javaLibraryPlatform"])
	pom {
		description.set("This Bill of Materials POM can be used to ease dependency management " +
				"when referencing multiple JUnit artifacts using Gradle or Maven.")
	}
}

Add sanity checks for BOM generation

description = "${rootProject.description} (Bill of Materials)"

apply(from = "$rootDir/gradle/publishing.gradle.kts")

dependencies {
	constraints {
		val mavenizedProjects: List<Project> by rootProject.extra
		mavenizedProjects.sorted()
				.filter { it.name != "junit-platform-console-standalone" }
				.forEach { api("${it.group}:${it.name}:${it.version}") }
	}
}

the<PublishingExtension>().publications.named<MavenPublication>("maven") {
	from(components["javaLibraryPlatform"])
	pom {
		description.set("This Bill of Materials POM can be used to ease dependency management " +
				"when referencing multiple JUnit artifacts using Gradle or Maven.")
	}
}

tasks.withType<GenerateMavenPom> {
	doLast {
		val xml = destination.readText()
		require (xml.indexOf("<dependencies>") == xml.lastIndexOf("<dependencies>")) {
			"BOM must contain exactly one <dependencies> element but contained multiple:\n$destination"
		}
		require(xml.contains("<dependencyManagement>")) {
			"BOM must contain a <dependencyManagement> element:\n$destination"
		}
	}
}


package com.jetbrains.rider.plugins.unity.run.configurations

import com.intellij.execution.configurations.ConfigurationType
import com.intellij.openapi.project.Project
import icons.UnityIcons
import com.jetbrains.rider.run.configurations.DotNetConfigurationFactoryBase

open class UnityAttachToEditorFactory(type: ConfigurationType)
    : DotNetConfigurationFactoryBase<UnityAttachToEditorRunConfiguration>(type) {

    override fun createTemplateConfiguration(project: Project) = UnityAttachToEditorRunConfiguration(project, this)
    override fun isConfigurationSingletonByDefault() = true
    override fun getName() = "Debug Unity Editor"
    override fun getIcon() = UnityIcons.RunConfigurations.AttachAndDebug

    // This value gets written to the config file. By default it defers to getName, which is what happened pre-2018.3.
    // Keep the "Unity Debug" value so that we can load configs created by earlier versions, and earlier versions can
    // load this config
    override fun getId() = "Unity Debug"
}

class UnityAttachToEditorAndPlayFactory(type: ConfigurationType)
    : DotNetConfigurationFactoryBase<UnityAttachToEditorRunConfiguration>(type) {

    override fun createTemplateConfiguration(project: Project) = UnityAttachToEditorRunConfiguration(project, this, true)
    override fun isConfigurationSingletonByDefault() = true
    override fun getName() = "Debug Unity Editor (play mode)"
    override fun getId() = "UNITY_ATTACH_AND_PLAY"
    override fun getIcon() = UnityIcons.RunConfigurations.AttachDebugAndPlay
}

Make run configs only available in Unity projects

package com.jetbrains.rider.plugins.unity.run.configurations

import com.intellij.execution.configurations.ConfigurationType
import com.intellij.openapi.project.Project
import com.jetbrains.rider.isUnityProject
import icons.UnityIcons
import com.jetbrains.rider.run.configurations.DotNetConfigurationFactoryBase

open class UnityAttachToEditorFactory(type: ConfigurationType)
    : DotNetConfigurationFactoryBase<UnityAttachToEditorRunConfiguration>(type) {

    override fun createTemplateConfiguration(project: Project) = UnityAttachToEditorRunConfiguration(project, this)
    override fun isConfigurationSingletonByDefault() = true
    override fun getName() = "Debug Unity Editor"
    override fun getIcon() = UnityIcons.RunConfigurations.AttachAndDebug
    override fun isApplicable(project: Project) = project.isUnityProject()

    // This value gets written to the config file. By default it defers to getName, which is what happened pre-2018.3.
    // Keep the "Unity Debug" value so that we can load configs created by earlier versions, and earlier versions can
    // load this config
    override fun getId() = "Unity Debug"
}

class UnityAttachToEditorAndPlayFactory(type: ConfigurationType)
    : DotNetConfigurationFactoryBase<UnityAttachToEditorRunConfiguration>(type) {

    override fun createTemplateConfiguration(project: Project) = UnityAttachToEditorRunConfiguration(project, this, true)
    override fun isConfigurationSingletonByDefault() = true
    override fun getName() = "Debug Unity Editor (play mode)"
    override fun getId() = "UNITY_ATTACH_AND_PLAY"
    override fun getIcon() = UnityIcons.RunConfigurations.AttachDebugAndPlay
    override fun isApplicable(project: Project) = project.isUnityProject()
}


plugins {
  id("org.metaborg.gradle.config.java-library")
  id("org.metaborg.gradle.config.junit-testing")
}

val spoofax2Version: String by ext
dependencies {
  api(platform("org.metaborg:parent:$spoofax2Version"))

  api("org.apache.commons:commons-vfs2")
  api("commons-io:commons-io")
  api("io.reactivex.rxjava3:rxjava")
  api("com.google.guava:guava")
  api("com.google.inject:guice")
  api("org.slf4j:slf4j-api")

  compileOnly("com.google.code.findbugs:jsr305")

  testCompileOnly("junit:junit")
  testCompileOnly("com.google.code.findbugs:jsr305")
  testRuntimeOnly("org.junit.vintage:junit-vintage-engine:5.1.0")
}

// Copy test resources into classes directory, to make them accessible as classloader resources at runtime.
val copyTestResourcesTask = tasks.create<Copy>("copyTestResources") {
  from("$projectDir/src/test/resources")
  into("$buildDir/classes/java/test")
}
tasks.getByName("processTestResources").dependsOn(copyTestResourcesTask)

Use JUnit 5 platform version

plugins {
  id("org.metaborg.gradle.config.java-library")
  id("org.metaborg.gradle.config.junit-testing")
}

val spoofax2Version: String by ext
dependencies {
  api(platform("org.metaborg:parent:$spoofax2Version"))

  api("org.apache.commons:commons-vfs2")
  api("commons-io:commons-io")
  api("io.reactivex.rxjava3:rxjava")
  api("com.google.guava:guava")
  api("com.google.inject:guice")
  api("org.slf4j:slf4j-api")

  compileOnly("com.google.code.findbugs:jsr305")

  testCompileOnly("junit:junit")
  testCompileOnly("com.google.code.findbugs:jsr305")
  testRuntimeOnly("org.junit.vintage:junit-vintage-engine")
}

// Copy test resources into classes directory, to make them accessible as classloader resources at runtime.
val copyTestResourcesTask = tasks.create<Copy>("copyTestResources") {
  from("$projectDir/src/test/resources")
  into("$buildDir/classes/java/test")
}
tasks.getByName("processTestResources").dependsOn(copyTestResourcesTask)


package jetbrains.buildServer.dotnet

import jetbrains.buildServer.tools.ToolTypeAdapter

class DotnetToolTypeAdapter : ToolTypeAdapter() {
    override fun getType(): String {
        return DotnetConstants.PACKAGE_TYPE
    }

    override fun getDisplayName(): String {
        return DotnetConstants.PACKAGE_TOOL_TYPE_NAME
    }

    override fun getDescription(): String? {
        return "Is used in the .NET runner for CLI integration."
    }

    override fun getShortDisplayName(): String {
        return DotnetConstants.PACKAGE_SHORT_TOOL_TYPE_NAME
    }

    override fun getTargetFileDisplayName(): String {
        return DotnetConstants.PACKAGE_TARGET_FILE_DISPLAY_NAME
    }

    override fun isSupportDownload(): Boolean {
        return true
    }

    override fun getToolSiteUrl(): String {
        return "https://github.com/JetBrains/TeamCity.MSBuild.Logger/"
    }

    override fun getToolLicenseUrl(): String {
        return "https://github.com/JetBrains/TeamCity.MSBuild.Logger/blob/master/LICENSE"
    }

    override fun getTeamCityHelpFile(): String {
        return "DotnetIntegration"
    }

    override fun getValidPackageDescription(): String? {
        return "Specify the path to a " + displayName + " (.nupkg).\n" +
                "
Download TeamCity.Dotnet.Integration.<VERSION>.nupkg from\n" +
                "www.nuget.org"
    }

    companion object {
        internal val Shared: ToolTypeAdapter = DotnetToolTypeAdapter()
    }
}

Update .NET Integration tool description

package jetbrains.buildServer.dotnet

import jetbrains.buildServer.tools.ToolTypeAdapter

class DotnetToolTypeAdapter : ToolTypeAdapter() {
    override fun getType(): String {
        return DotnetConstants.PACKAGE_TYPE
    }

    override fun getDisplayName(): String {
        return DotnetConstants.PACKAGE_TOOL_TYPE_NAME
    }

    override fun getDescription(): String? {
        return "Is used in .NET CLI build steps."
    }

    override fun getShortDisplayName(): String {
        return DotnetConstants.PACKAGE_SHORT_TOOL_TYPE_NAME
    }

    override fun getTargetFileDisplayName(): String {
        return DotnetConstants.PACKAGE_TARGET_FILE_DISPLAY_NAME
    }

    override fun isSupportDownload(): Boolean {
        return true
    }

    override fun getToolSiteUrl(): String {
        return "https://github.com/JetBrains/TeamCity.MSBuild.Logger/"
    }

    override fun getToolLicenseUrl(): String {
        return "https://github.com/JetBrains/TeamCity.MSBuild.Logger/blob/master/LICENSE"
    }

    override fun getValidPackageDescription(): String? {
        return "Specify the path to a " + displayName + " (.nupkg).\n" +
                "
Download TeamCity.Dotnet.Integration.<VERSION>.nupkg from\n" +
                "www.nuget.org"
    }

    companion object {
        internal val Shared: ToolTypeAdapter = DotnetToolTypeAdapter()
    }
}


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

package com.louiscad.splittiessample.extensions.coroutines

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.selects.select

suspend inline fun <T> raceOf(vararg racers: suspend CoroutineScope.() -> T): T = coroutineScope {
    @UseExperimental(ExperimentalCoroutinesApi::class)
    racers.map { async(start = CoroutineStart.UNDISPATCHED, block = it) }.race()
}

@PublishedApi
internal suspend fun <T> List<Deferred<T>>.race(): T = select {
    this@race.forEach {
        it.onAwait { result ->
            this@race.forEach { deferred -> deferred.cancel() }
            return@onAwait result
        }
    }
}

Simplify raceOf implementation and remove useless inline.

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

package com.louiscad.splittiessample.extensions.coroutines

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.selects.select

suspend fun <T> raceOf(vararg racers: suspend CoroutineScope.() -> T): T = coroutineScope {
    select<T> {
        @UseExperimental(ExperimentalCoroutinesApi::class)
        val racersAsyncList = racers.map { async(start = CoroutineStart.UNDISPATCHED, block = it) }
        racersAsyncList.forEach { racer ->
            racer.onAwait { resultOfWinner ->
                racersAsyncList.forEach { deferred -> deferred.cancel() }
                return@onAwait resultOfWinner
            }
        }
    }
}


package org.purescript.parser

import com.intellij.psi.tree.IElementType

abstract class Parsec {
    var name: String? = null
        get() {
            if (field == null) {
                field = calcName()
            }
            return field
        }
        private set
    var expectedName: Set<String>? = null
        get() {
            if (field == null) {
                field = calcExpectedName()
            }
            return field
        }
        private set
    private var canBeEmpty: Boolean? = null
    abstract fun parse(context: ParserContext): ParserInfo
    protected abstract fun calcName(): String
    protected abstract fun calcExpectedName(): Set<String>
    operator fun plus(other: Parsec) = Combinators.seq(this, other)
    fun then(next: Parsec) = this + next
    fun or(next: Parsec) = Combinators.choice(this, next)
    fun sepBy1(next: Parsec) = Combinators.sepBy1(this, next)
    fun `as`(node: IElementType) = SymbolicParsec(this, node)
    abstract fun canStartWith(type: IElementType): Boolean
    fun canBeEmpty(): Boolean {
        if (canBeEmpty == null) {
            canBeEmpty = calcCanBeEmpty()
        }
        return canBeEmpty!!
    }
    protected abstract fun calcCanBeEmpty(): Boolean
    fun sepBy(parsec: Parsec) = Combinators.sepBy(this, parsec)
}

Make as infix to simplify parser grammar

package org.purescript.parser

import com.intellij.psi.tree.IElementType

abstract class Parsec {
    var name: String? = null
        get() {
            if (field == null) {
                field = calcName()
            }
            return field
        }
        private set
    var expectedName: Set<String>? = null
        get() {
            if (field == null) {
                field = calcExpectedName()
            }
            return field
        }
        private set
    private var canBeEmpty: Boolean? = null
    abstract fun parse(context: ParserContext): ParserInfo
    protected abstract fun calcName(): String
    protected abstract fun calcExpectedName(): Set<String>
    operator fun plus(other: Parsec) = Combinators.seq(this, other)
    fun then(next: Parsec) = this + next
    fun or(next: Parsec) = Combinators.choice(this, next)
    fun sepBy1(next: Parsec) = Combinators.sepBy1(this, next)
    infix fun `as`(node: IElementType) = SymbolicParsec(this, node)
    abstract fun canStartWith(type: IElementType): Boolean
    fun canBeEmpty(): Boolean {
        if (canBeEmpty == null) {
            canBeEmpty = calcCanBeEmpty()
        }
        return canBeEmpty!!
    }
    protected abstract fun calcCanBeEmpty(): Boolean
    fun sepBy(parsec: Parsec) = Combinators.sepBy(this, parsec)
}


package net.squanchy.schedule.view

import android.support.v7.widget.RecyclerView

import net.squanchy.schedule.domain.view.Event

class EventViewHolder(itemView: EventItemView) : RecyclerView.ViewHolder(itemView) {

    fun updateWith(event: Event, listener: ScheduleViewPagerAdapter.OnEventClickedListener?) {
        (itemView as EventItemView).updateWith(event)
        itemView.setOnClickListener {
            listener?.onEventClicked(event)
        }
    }
}

Rewrite setOnClickListener on a single line


package com.agoda.kakao.delegate

import com.agoda.kakao.intercept.Interceptor

/**
 * Base delegate interface.
 *
 * Provides functionality of aggregating interceptors and invoking them on `check`
 * and `perform` invocations.
 *
 * @see Interceptor
 */
interface Delegate<T, C, P> {
    var interaction: T

    fun viewInterceptor(): Interceptor<T, C, P>?
    fun screenInterceptor(): Interceptor<T, C, P>?
    fun kakaoInterceptor(): Interceptor<T, C, P>?

    fun interceptCheck(assertion: C): Boolean {
        interceptors().forEach { interceptor ->
            interceptor.onAll?.let {
                it.second(interaction)
                if (it.first) return true
            }

            interceptor.onCheck?.let {
                it.second(interaction, assertion)
                if (it.first) return true
            }
        }

        return false
    }

    fun interceptPerform(action: P): Boolean {
        interceptors().forEach { interceptor ->
            interceptor.onAll?.let {
                it.second(interaction)
                if (it.first) return true
            }

            interceptor.onPerform?.let {
                it.second(interaction, action)
                if (it.first) return true
            }
        }

        return false
    }

    private fun interceptors(): List<Interceptor<T, C, P>> = mutableListOf<Interceptor<T, C, P>>().also { list ->
        viewInterceptor()?.let { list.add(it) }
        screenInterceptor()?.let { list.add(it) }
        kakaoInterceptor()?.let { list.add(it) }
    }
}

Remove return type form aggregation function

package com.agoda.kakao.delegate

import com.agoda.kakao.intercept.Interceptor

/**
 * Base delegate interface.
 *
 * Provides functionality of aggregating interceptors and invoking them on `check`
 * and `perform` invocations.
 *
 * @see Interceptor
 */
interface Delegate<T, C, P> {
    var interaction: T

    fun viewInterceptor(): Interceptor<T, C, P>?
    fun screenInterceptor(): Interceptor<T, C, P>?
    fun kakaoInterceptor(): Interceptor<T, C, P>?

    fun interceptCheck(assertion: C): Boolean {
        interceptors().forEach { interceptor ->
            interceptor.onAll?.let {
                it.second(interaction)
                if (it.first) return true
            }

            interceptor.onCheck?.let {
                it.second(interaction, assertion)
                if (it.first) return true
            }
        }

        return false
    }

    fun interceptPerform(action: P): Boolean {
        interceptors().forEach { interceptor ->
            interceptor.onAll?.let {
                it.second(interaction)
                if (it.first) return true
            }

            interceptor.onPerform?.let {
                it.second(interaction, action)
                if (it.first) return true
            }
        }

        return false
    }

    private fun interceptors() = mutableListOf<Interceptor<T, C, P>>().also { list ->
        viewInterceptor()?.let { list.add(it) }
        screenInterceptor()?.let { list.add(it) }
        kakaoInterceptor()?.let { list.add(it) }
    }
}


package com.github.shiraji

import git4idea.GitCommit
import java.math.BigInteger
import java.security.MessageDigest

fun String.toMd5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(this.toByteArray())).toString(16)

fun String.subtract(text: String) = this.replace(text, "")

fun GitCommit.getPullRequestNumber() = this.fullMessage.replace("Merge pull request #", "").split(" ").first().toInt()

Add extensions for GitCommit for finding squashed pull request commit

package com.github.shiraji

import git4idea.GitCommit
import java.math.BigInteger
import java.security.MessageDigest

fun String.toMd5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(this.toByteArray())).toString(16)

fun String.subtract(text: String) = this.replace(text, "")

fun GitCommit.getPullRequestNumber() = "Merge pull request #(\\d*)".toRegex().find(this.fullMessage)!!.groups[1]!!.value.toInt()

fun GitCommit.getPullRequestNumberFromSquashCommit() = ".*\\(#(\\d*)\\)".toRegex().find(this.fullMessage)!!.groups[1]!!.value.toInt()

fun GitCommit.isSquashPullRequestCommit() = ".*\\(#(\\d*)\\)".toRegex().containsMatchIn(this.fullMessage)


package iii_conventions

data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> {
    override fun compareTo(other: MyDate): Int {
        return when {
            year != other.year -> year - other.year
            month != other.month -> month - other.month
            dayOfMonth != other.dayOfMonth -> dayOfMonth - other.dayOfMonth
            else -> 0
        }
    }
}

operator fun MyDate.rangeTo(other: MyDate): DateRange = todoTask27()

enum class TimeInterval {
    DAY,
    WEEK,
    YEAR
}

class DateRange(val start: MyDate, val endInclusive: MyDate)

Update koan 25 (Comparison) in iii_conventions (the else -> 0 was redundant; can just compare the dayOfMonth after we know the year and month are equal)

package iii_conventions

data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> {
    override fun compareTo(other: MyDate): Int {
        return when {
            year != other.year -> year - other.year
            month != other.month -> month - other.month
            else -> dayOfMonth - other.dayOfMonth
        }
    }
}

operator fun MyDate.rangeTo(other: MyDate): DateRange = todoTask27()

enum class TimeInterval {
    DAY,
    WEEK,
    YEAR
}

class DateRange(val start: MyDate, val endInclusive: MyDate)


package com.s13g.aoc.aoc2020

import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import java.util.*

/**
 * --- Day 15: Rambunctious Recitation ---
 * https://adventofcode.com/2020/day/15
 */
class Day15 : Solver {

  override fun solve(lines: List<String>): Result {
    val input = lines[0].split(',').map { it.toInt() }
    return Result("${solveUntil(2020, input)}", "${solveUntil(30000000, input)}")
  }

  private fun solveUntil(limit: Int, input: List<Int>): Int {
    val positions = input
        .withIndex()
        .associate { Pair(it.value, TreeSet<Int>(listOf(it.index))) }
        .toMutableMap()

    var lastNum = input.last()
    var chainSize = input.size
    while (chainSize < limit) {
      var age = 0
      if (lastNum in positions && positions[lastNum]!!.size > 1) {
        val posSorted = positions[lastNum]!!
        val iter = posSorted.descendingIterator()
        age = iter.next() - iter.next()
      }
      // If diff was found, age is > 0, else 0. Add it to the list of positions.
      if (age !in positions) positions[age] = TreeSet()
      positions[age]!!.add(chainSize)
      lastNum = age
      chainSize++
    }
    // Return the last number found.
    return lastNum
  }
}

Speed up solution. No need for a TreeSet, items are added in increasing order anyway.

package com.s13g.aoc.aoc2020

import com.s13g.aoc.Result
import com.s13g.aoc.Solver

/**
 * --- Day 15: Rambunctious Recitation ---
 * https://adventofcode.com/2020/day/15
 */
class Day15 : Solver {

  override fun solve(lines: List<String>): Result {
    val input = lines[0].split(',').map { it.toInt() }
    return Result("${solveUntil(2020, input)}", "${solveUntil(30000000, input)}")
  }

  private fun solveUntil(limit: Int, input: List<Int>): Int {
    val positions = input
        .withIndex()
        .associate { Pair(it.value, mutableListOf(it.index)) }
        .toMutableMap()

    var lastNum = input.last()
    var chainSize = input.size
    while (chainSize < limit) {
      var age = 0
      if (lastNum in positions && positions[lastNum]!!.size > 1) {
        val l = positions[lastNum]!!.size - 1
        age = positions[lastNum]!![l] - positions[lastNum]!![l - 1]
      }
      // If diff was found, age is > 0, else 0. Add it to the list of positions.
      if (age !in positions) positions[age] = mutableListOf()
      positions[age]!!.add(chainSize)
      lastNum = age
      chainSize++
    }
    // Return the last number found.
    return lastNum
  }
}


package com.jetbrains.rider.plugins.unity.ideaInterop.fileTypes.asmdef

import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.psi.PsiElement
import com.jetbrains.rdclient.hyperlinks.FrontendCtrlClickHost
import com.jetbrains.rider.actions.RiderActionCallStrategy
import com.jetbrains.rider.actions.RiderActionSupportPolicy
import com.jetbrains.rider.actions.RiderActions

class AsmDefActionCallPolicy : RiderActionSupportPolicy() {
    override fun getCallStrategy(psiElement: PsiElement, backendActionId: String): RiderActionCallStrategy  =
        when (backendActionId) {
            IdeActions.ACTION_RENAME,
            IdeActions.ACTION_FIND_USAGES,
            FrontendCtrlClickHost.backendActionId,
            RiderActions.GOTO_DECLARATION -> RiderActionCallStrategy.BACKEND_FIRST
            else -> RiderActionCallStrategy.FRONTEND_ONLY
        }

    override fun isAvailable(psiElement: PsiElement, backendActionId: String): Boolean {
        val viewProvider = psiElement.containingFile?.viewProvider ?: return false
        return viewProvider.fileType == AsmDefFileType
    }
}

Fix missing rename asmdef action in Rider

package com.jetbrains.rider.plugins.unity.ideaInterop.fileTypes.asmdef

import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.psi.PsiElement
import com.jetbrains.rdclient.hyperlinks.FrontendCtrlClickHost
import com.jetbrains.rider.actions.RiderActionCallStrategy
import com.jetbrains.rider.actions.RiderActionSupportPolicy
import com.jetbrains.rider.actions.RiderActions

class AsmDefActionCallPolicy : RiderActionSupportPolicy() {
    override fun getCallStrategy(psiElement: PsiElement, backendActionId: String): RiderActionCallStrategy  =
        // Note that this is backend action ID, which means it's the R# action ID, which may or may not be the same as
        // the IdeAction.
        when (backendActionId) {
            "Rename",
            IdeActions.ACTION_FIND_USAGES,
            FrontendCtrlClickHost.backendActionId,
            RiderActions.GOTO_DECLARATION -> RiderActionCallStrategy.BACKEND_FIRST
            else -> RiderActionCallStrategy.FRONTEND_ONLY
        }

    override fun isAvailable(psiElement: PsiElement, backendActionId: String): Boolean {
        val viewProvider = psiElement.containingFile?.viewProvider ?: return false
        return viewProvider.fileType == AsmDefFileType
    }
}


package ee.mcdimus.matewp.service

import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*

/**
 * @author Dmitri Maksimov
 */
class FileSystemService {

  companion object {
    private const val HOME = "HOME"
  }

  fun getHomeDirectory(): Path {
    val homeDirectoryPath = System.getenv()
        .getOrElse(HOME, { throw IllegalStateException("environment variable $HOME is no defined") })
    return Paths.get(homeDirectoryPath)
  }

  fun getImagesDirectory(): Path {
    val imagesDirectory = getHomeDirectory().resolve("Pictures/mate-wp")
    if (Files.notExists(imagesDirectory)) {
      return Files.createDirectories(imagesDirectory)
    }
    return imagesDirectory
  }

  fun getConfigsDirectory(): Path {
    val configsDirectory = getImagesDirectory().resolve("configs")
    if (Files.notExists(configsDirectory)) {
      return Files.createDirectories(configsDirectory)
    }
    return configsDirectory
  }

  fun saveProperties(propertiesPath: Path, propertyMap: Map<String, String>): Path {
    val properties = Properties()
    for ((key, value) in propertyMap) {
      properties.setProperty(key, value)
    }

    Files.newOutputStream(propertiesPath).use {
      properties.store(it, null)
    }

    return propertiesPath
  }

  fun loadProperties(propertiesPath: Path): Properties {
    val properties = Properties()
    Files.newInputStream(propertiesPath).use {
      properties.load(it)
    }
    return properties
  }

}

Use system property 'user.home' instead of environment variable HOME, which is available only on Linux.

package ee.mcdimus.matewp.service

import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*

/**
 * @author Dmitri Maksimov
 */
class FileSystemService {

  companion object {
    private const val USER_HOME = "user.home"
  }

  fun getHomeDirectory(): Path {
    val homeDirectoryPath = System.getProperty(USER_HOME)
            ?: throw IllegalStateException("system property $USER_HOME is not defined")

    return Paths.get(homeDirectoryPath)
  }

  fun getImagesDirectory(): Path {
    val imagesDirectory = getHomeDirectory().resolve("Pictures/mate-wp")
    if (Files.notExists(imagesDirectory)) {
      return Files.createDirectories(imagesDirectory)
    }
    return imagesDirectory
  }

  fun getConfigsDirectory(): Path {
    val configsDirectory = getImagesDirectory().resolve("configs")
    if (Files.notExists(configsDirectory)) {
      return Files.createDirectories(configsDirectory)
    }
    return configsDirectory
  }

  fun saveProperties(propertiesPath: Path, propertyMap: Map<String, String>): Path {
    val properties = Properties()
    for ((key, value) in propertyMap) {
      properties.setProperty(key, value)
    }

    Files.newOutputStream(propertiesPath).use {
      properties.store(it, null)
    }

    return propertiesPath
  }

  fun loadProperties(propertiesPath: Path): Properties {
    val properties = Properties()
    Files.newInputStream(propertiesPath).use {
      properties.load(it)
    }
    return properties
  }

}


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

package org.gradle.kotlin.dsl.support

import org.gradle.api.NamedDomainObjectCollection

import kotlin.reflect.KClass

fun illegalElementType(container: NamedDomainObjectCollection<*>, name: String, expectedType: KClass<*>, actualType: KClass<*>) =
    IllegalStateException(
        "Element '$name' of type '${actualType.java.name}' from container '$container' cannot be cast to '${expectedType.qualifiedName}'.")

internal
fun internalError(): Nothing =
    throw InternalError("This should not happen, please report at https://github.com/gradle/kotlin-dsl/issues/new")

Throw IllegalArgumentException instead of IllegalStateException

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

package org.gradle.kotlin.dsl.support

import org.gradle.api.NamedDomainObjectCollection

import kotlin.reflect.KClass

fun illegalElementType(container: NamedDomainObjectCollection<*>, name: String, expectedType: KClass<*>, actualType: KClass<*>) =
    IllegalArgumentException(
        "Element '$name' of type '${actualType.java.name}' from container '$container' cannot be cast to '${expectedType.qualifiedName}'.")

internal
fun internalError(): Nothing =
    throw InternalError("This should not happen, please report at https://github.com/gradle/kotlin-dsl/issues/new")


Define init script to use internal mirror for Gradle build

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

val gradleMirrorUrl = findMirrorUrls()["gradle"]
if (gradleMirrorUrl != null) {
    allprojects {
        buildscript {
            repositories {
                maven {
                    name = "gradle-mirror"
                    url = uri(gradleMirrorUrl)
                }
            }
        }
        repositories {
            maven {
                name = "gradle-mirror"
                url = uri(gradleMirrorUrl)
            }
        }
    }
}

fun findMirrorUrls(): Map<String, String> =
    System.getenv("REPO_MIRROR_URLS")?.split(',')?.associate { nameToUrl ->
        val (name, url) = nameToUrl.split(':', limit = 2)
        name to url
    } ?: emptyMap()


package org.jetbrains.ktor.http

/**
 * Represents request address information is used to make a call.
 * There are at least two possible instances: "local" is how we see request at the server application and
 * "actual" is what we can recover from proxy provided headers.
 */
interface RequestConnectionPoint {
    /**
     * Request scheme, for example "http" or "https"
     */
    val scheme: String

    val version: String

    /**
     * Request port, for example 80 or 443
     */
    val port: Int

    /**
     * Request host, useful for virtual hosts routing
     */
    val host: String

    /**
     * URI path with no host, port and no schema specification, but possibly with query
     */
    val uri: String

    /**
     * Request HTTP method
     */
    val method: HttpMethod

    /**
     * Client address or host name (generally not resolved to name for performance reasons).
     * For [org.jetbrains.ktor.application.ApplicationRequest.local] instance could point to
     * a proxy our application running behind.
     * NEVER use it for user authentication as it can be easily falsified (user can simply set some HTTP headers
     * such as X-Forwarded-Host so you should NEVER rely on it in any security checks.
     * If you are going to use it to create a back-connection please do it with care as an offender can easily
     * use it to force you to connect to some host that is not intended to be connected to so that may cause
     * serious consequences.
     */
    val remoteHost: String
}

Add documentation to a `version` property

package org.jetbrains.ktor.http

/**
 * Represents request address information is used to make a call.
 * There are at least two possible instances: "local" is how we see request at the server application and
 * "actual" is what we can recover from proxy provided headers.
 */
interface RequestConnectionPoint {
    /**
     * Request scheme, for example "http" or "https"
     */
    val scheme: String

    /**
     * Protocol version string
     */
    val version: String

    /**
     * Request port, for example 80 or 443
     */
    val port: Int

    /**
     * Request host, useful for virtual hosts routing
     */
    val host: String

    /**
     * URI path with no host, port and no schema specification, but possibly with query
     */
    val uri: String

    /**
     * Request HTTP method
     */
    val method: HttpMethod

    /**
     * Client address or host name (generally not resolved to name for performance reasons).
     * For [org.jetbrains.ktor.application.ApplicationRequest.local] instance could point to
     * a proxy our application running behind.
     * NEVER use it for user authentication as it can be easily falsified (user can simply set some HTTP headers
     * such as X-Forwarded-Host so you should NEVER rely on it in any security checks.
     * If you are going to use it to create a back-connection please do it with care as an offender can easily
     * use it to force you to connect to some host that is not intended to be connected to so that may cause
     * serious consequences.
     */
    val remoteHost: String
}


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

package common

enum class JvmCategory(val vendor: JvmVendor, val version: JvmVersion) {
    MIN_VERSION(JvmVendor.oracle, JvmVersion.java8),
    MAX_VERSION(JvmVendor.openjdk, JvmVersion.java11),
    EXPERIMENTAL_VERSION(JvmVendor.openjdk, JvmVersion.java12)
}

Use Java 12 for TC build pipeline

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

package common

enum class JvmCategory(val vendor: JvmVendor, val version: JvmVersion) {
    MIN_VERSION(JvmVendor.oracle, JvmVersion.java8),
    MAX_VERSION(JvmVendor.openjdk, JvmVersion.java12),
    EXPERIMENTAL_VERSION(JvmVendor.openjdk, JvmVersion.java12)
}


package org.runestar.client.plugins.dev

import org.runestar.client.api.forms.RgbForm
import org.runestar.client.api.util.DisposablePlugin
import org.runestar.client.game.raw.CLIENT
import org.runestar.client.game.raw.access.XUnderlayDefinition
import org.runestar.client.plugins.spi.PluginSettings
import java.awt.Color

class GroundColor : DisposablePlugin<GroundColor.Settings>() {

    override val defaultSettings = Settings()

    override fun start() {
        CLIENT.underlayDefinition_cached.clear()
        add(XUnderlayDefinition.init.enter.subscribe {
            it.instance.rgb = settings.color.get().rgb
        })
    }

    override fun stop() {
        super.stop()
        CLIENT.underlayDefinition_cached.clear()
    }

    class Settings(
            val color: RgbForm = RgbForm(Color.WHITE)
    ) : PluginSettings()
}


package com.chibatching.kotpref

import android.annotation.TargetApi
import android.content.SharedPreferences
import android.os.Build
import com.chibatching.kotpref.pref.StringSetPref
import java.util.*

internal class KotprefPreferences(val preferences: SharedPreferences) : SharedPreferences by preferences {

    override fun edit(): SharedPreferences.Editor {
        return KotprefEditor(preferences.edit())
    }

    internal inner class KotprefEditor(val editor: SharedPreferences.Editor) : SharedPreferences.Editor by editor {

        private val prefStringSet: MutableMap<String, StringSetPref.PrefMutableSet> by lazy { HashMap<String, StringSetPref.PrefMutableSet>() }

        override fun apply() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                prefStringSet.keys.forEach { key ->
                    prefStringSet[key]?.let {
                        editor.putStringSet(key, it)
                        it.syncTransaction()
                    }
                }
                prefStringSet.clear()
            }
            editor.apply()
        }

        override fun commit(): Boolean {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                prefStringSet.forEach { key, set ->
                    editor.putStringSet(key, set)
                    set.syncTransaction()
                }
                prefStringSet.clear()
            }
            return editor.commit()
        }

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        internal fun putStringSet(key: String, prefSet: StringSetPref.PrefMutableSet): SharedPreferences.Editor {
            prefStringSet.put(key, prefSet)
            return this
        }
    }
}

Fix NoClassDefFoundError when using blockingBulk on API <= 6.0

package com.chibatching.kotpref

import android.annotation.TargetApi
import android.content.SharedPreferences
import android.os.Build
import com.chibatching.kotpref.pref.StringSetPref
import java.util.*

internal class KotprefPreferences(val preferences: SharedPreferences) : SharedPreferences by preferences {

    override fun edit(): SharedPreferences.Editor {
        return KotprefEditor(preferences.edit())
    }

    internal inner class KotprefEditor(val editor: SharedPreferences.Editor) : SharedPreferences.Editor by editor {

        private val prefStringSet: MutableMap<String, StringSetPref.PrefMutableSet> by lazy { HashMap<String, StringSetPref.PrefMutableSet>() }

        override fun apply() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                syncTransaction()
            }
            editor.apply()
        }

        override fun commit(): Boolean {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                syncTransaction()
            }
            return editor.commit()
        }

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        internal fun putStringSet(key: String, prefSet: StringSetPref.PrefMutableSet): SharedPreferences.Editor {
            prefStringSet.put(key, prefSet)
            return this
        }

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        private fun syncTransaction() {
            prefStringSet.keys.forEach { key ->
                prefStringSet[key]?.let {
                    editor.putStringSet(key, it)
                    it.syncTransaction()
                }
            }
            prefStringSet.clear()
        }
    }
}


Add clearIvyCache function for library writers convenience

package jupyter.kotlin

import java.io.File

fun clearIvyCache()= deleteCacheDir()
fun clearIvyCache(group: String) = deleteCacheDir(group)
fun clearIvyCache(group: String, artifact: String) = deleteCacheDir(group, artifact)
fun clearIvyCache(group: String, artifact: String, version: String) = deleteCacheDir(group, artifact, version)

private fun deleteCacheDir(group: String? = null, artifact: String? = null, version: String? = null) {
    val userHomeDir = File(System.getProperty("user.home"))
    val ivyCacheDir = userHomeDir.resolve(".ivy2/cache")

    fun File.deleteDir() {
        if (exists()) deleteRecursively()
    }

    var deleteDir = ivyCacheDir
    if (group == null) {
        deleteDir.deleteDir()
        return
    }

    deleteDir = deleteDir.resolve(group)
    if (artifact == null) {
        deleteDir.deleteDir()
        return
    }

    deleteDir = deleteDir.resolve(artifact)
    if (version == null) {
        deleteDir.deleteDir()
        return
    }

    val filesToDelete = listOf(
        "ivy-$version.xml",
        "ivy-$version.xml.original",
        "ivydata-$version.properties",
        "jars/$artifact-$version.jar"
    )
    filesToDelete.forEach {
        deleteDir.resolve(it).delete()
    }
}


package pl.mg6.likeornot

import android.os.Bundle
import android.support.v4.view.ViewPager
import android.support.v7.app.AppCompatActivity

class GridActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.grid_activity)
        getLikables(LikableApiProvider.get()).subscribe { it: List<Likable> ->
            val pager = findViewById(R.id.grid_pager) as ViewPager
            val gridItems = it.mapIndexed { index, likable -> index to likable }.groupBy { it.first / 9 }.map { it.value.map { it.second } }
            pager.adapter = GridPagerAdapter(gridItems)
        }
    }
}

Use bound callable references as Consumers.

package pl.mg6.likeornot

import android.os.Bundle
import android.support.v4.view.ViewPager
import android.support.v7.app.AppCompatActivity
import android.util.Log

class GridActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.grid_activity)
        getLikables(LikableApiProvider.get())
                .subscribe(this::showLikables, this::showError)
    }

    private fun showLikables(likables: List<Likable>) {
        val pager = findViewById(R.id.grid_pager) as ViewPager
        val gridItems = likables
                .mapIndexed { index, likable -> index to likable }
                .groupBy { it.first / 9 }
                .map { it.value.map { it.second } }
        pager.adapter = GridPagerAdapter(gridItems)
    }

    private fun showError(error: Throwable) {
        Log.e("tag", "", error)
    }
}


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

package com.facebook.litho

import com.facebook.litho.testing.testrunner.LithoTestRunner
import org.assertj.core.api.Java6Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith

/** Unit tests [Style]. */
@RunWith(LithoTestRunner::class)
class StyleTest {

  private class TestStyleItem(val name: String) : StyleItem {
    override fun DslScope.applyToProps(commonProps: CommonProps) = Unit
  }

  @Test
  fun style_styleItemAdded_getNewInstanceWithOldAndNewItems() {
    val style1 = Style + TestStyleItem("first")
    val style2 = style1 + TestStyleItem("second")

    assertThat(style1).isNotEqualTo(style2)
    assertThat(style1.toStringList()).containsExactly("first")
    assertThat(style2.toStringList()).containsExactly("first", "second")
  }

  @Test
  fun style_stylesAdded_getNewInstanceInRightOrder() {
    val style1 = Style + TestStyleItem("first1") + TestStyleItem("first2")
    val style2 = Style + TestStyleItem("second1") + TestStyleItem("second2")
    val combined = style1 + style2

    assertThat(style1.toStringList()).containsExactly("first1", "first2")
    assertThat(style2.toStringList()).containsExactly("second1", "second2")
    assertThat(combined.toStringList()).containsExactly("first1", "first2", "second1", "second2")
  }

  @Test
  fun style_stylesAndStyleItemsAdded_getNewStyleInRightOrder() {
    val style1 = Style + TestStyleItem("first")
    val style2 = Style + TestStyleItem("second")
    val combined = style1 + style2 + TestStyleItem("third")

    assertThat(combined.toStringList()).containsExactly("first", "second", "third")
  }

  private fun Style.toStringList(): List<String> {
    val list = mutableListOf<String>()
    forEach { list.add((it as TestStyleItem).name) }
    return list
  }
}


Add main/support-v4 uniformity test for Fragments

package org.jetbrains.android.anko.uniformity

import org.junit.Test
import java.io.File
import java.util.regex.Pattern

public class SupportFragmentUniformityTest {

    private var failFlag: Boolean = false

    private fun String.replaceDoubledSpaces(): String {
        var ret = this
        while (true) {
            val new = ret.replace("  ", " ")
            if (new == ret) return new
            ret = new
        }
    }

    private fun getAllDeclarations(file: File, receiver: String, declarationType: String): List<Pair<String, String>> {
        val argsIncluded = declarationType == "fun"
        val args = if (argsIncluded) "\\((.*?)\\)" else ""
        val postfix = if (argsIncluded) "[ \n\r\t]*?[\\{\\=]" else ""
        val pattern = Pattern.compile("$declarationType $receiver.([A-Za-z0-9_]+)$args( *?\\: *?.+?)?$postfix", Pattern.DOTALL)
        val matcher = pattern.matcher(file.readText())

        val functions = arrayListOf<Pair<String, String>>()
        while (matcher.find()) {
            val arguments = if (!argsIncluded) "" else matcher.group(2)
                    .replace('\n', ' ').replace('\r', ' ').replace('\t', ' ').replaceDoubledSpaces().trim()
            functions.add(matcher.group(1) to arguments)
        }

        return functions
    }

    private fun compare(
            func1: List<Pair<String, String>>,
            func2: List<Pair<String, String>>,
            text: String,
            receiver: String,
            declarationName: String
    ) {
        for (func in func1) {
            if (!func2.any { it == func }) {
                System.err.println("There is no $declarationName for $text library: $receiver.${func.first}(${func.second})")
                failFlag = true
            }
        }
    }

    Test
    public fun supportFragmentFunctionsExistTest() {
        val receiver = "Fragment"

        val (mainFiles, supportFiles) = File("dsl/static/src")
                .listFiles { it.extension == "kt" } !!.partition { !it.name.contains("Support")}

        listOf("fun", "val", "var").forEach { declarationName ->
            val mainFunctions = mainFiles.flatMap { getAllDeclarations(it, receiver, declarationName) }
            val supportFunctions = supportFiles.flatMap { getAllDeclarations(it, receiver, declarationName) }

            compare(mainFunctions, supportFunctions, "support", receiver, declarationName)
            compare(supportFunctions, mainFunctions, "main", receiver, declarationName)
        }

        if (failFlag) throw RuntimeException("See messages above.")
    }

}


package mareklangiewicz.pl.uspek

import org.junit.Assert
import org.junit.Test

class TreeCollectionLoggerTest {

    @Test
    fun `should create single success node test tree`() {
        val logger = TreeCollectionLogger()
        val location = CodeLocation("test.kt", 1)
        logger(Report.Start("first test", location))
        logger(Report.Success(location))
        Assert.assertEquals(logger.testTree!!, TestTree(name = "first test", state = TestState.SUCCESS, location = location))
    }
}


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

package splitties.preferences

import kotlin.reflect.KProperty

/**
 * A Lazy delegate that keeps a reference to it's initializer and resets it's value if you set it's
 * value with it's current value.
 *
 * Note that this doesn't support nullable values.
 *
 * Example:
 * ```kotlin
 * var myMember by ResettableLazy { Editor(preferences) }
 * ...
 * myMember = myMember // This line resets myMember. Next access will call the initializer again.
 * ```
 */
internal class ResettableLazy<T : Any>(private val initializer: () -> T) {

    private var value: T? = null

    operator fun getValue(thisRef: Any?, prop: KProperty<*>): T {
        return value ?: initializer().apply { value = this }
    }

    operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: T) {
        check(this.value == value) { "New values aren't accepted to reset this delegated property" }
        invalidate()
    }

    fun invalidate() {
        value = null
    }
}

Fix misspellings it's -> its

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

package splitties.preferences

import kotlin.reflect.KProperty

/**
 * A Lazy delegate that keeps a reference to its initializer and resets its value if you set its
 * value with its current value.
 *
 * Note that this doesn't support nullable values.
 *
 * Example:
 * ```kotlin
 * var myMember by ResettableLazy { Editor(preferences) }
 * ...
 * myMember = myMember // This line resets myMember. Next access will call the initializer again.
 * ```
 */
internal class ResettableLazy<T : Any>(private val initializer: () -> T) {

    private var value: T? = null

    operator fun getValue(thisRef: Any?, prop: KProperty<*>): T {
        return value ?: initializer().apply { value = this }
    }

    operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: T) {
        check(this.value == value) { "New values aren't accepted to reset this delegated property" }
        invalidate()
    }

    fun invalidate() {
        value = null
    }
}


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

// region Query Types

data class QueryType(val mimeType: String, val defaultExtensions: Array<String>)

val XQueryType: QueryType = QueryType("application/xquery", arrayOf("xq", "xqy", "xquery", "xql", "xqu"))

val JavaScriptType: QueryType = QueryType("application/javascript", arrayOf("js", "sjs"))

val SQLType: QueryType = QueryType("application/sql", arrayOf("sql"))

val SPARQLQueryType: QueryType = QueryType("application/sparql-query", arrayOf("sparql", "rq"))

val SPARQLUpdateType: QueryType = QueryType("application/sparql-update", arrayOf("ru"))

// endregion

Create a MimeType base class for QueryType.

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

open class MimeType(val mimeType: String, val defaultExtensions: Array<String>)

// region Query Types

class QueryType(mimeType: String, defaultExtensions: Array<String>):
    MimeType(mimeType, defaultExtensions)

val XQueryType: QueryType = QueryType("application/xquery", arrayOf("xq", "xqy", "xquery", "xql", "xqu"))

val JavaScriptType: QueryType = QueryType("application/javascript", arrayOf("js", "sjs"))

val SQLType: QueryType = QueryType("application/sql", arrayOf("sql"))

val SPARQLQueryType: QueryType = QueryType("application/sparql-query", arrayOf("sparql", "rq"))

val SPARQLUpdateType: QueryType = QueryType("application/sparql-update", arrayOf("ru"))

// endregion


package main

/**
 * Created by allen on 7/28/16.
 */
import spark.Spark.*
import com.google.gson.Gson
import controllers.SqliteController
import models.User
import spark.ModelAndView
import spark.template.handlebars.HandlebarsTemplateEngine
import java.util.*

fun main(args : Array<String>) {
    port(3000)

    staticFiles.location("/public");

    //gzip everything
    after({req, res ->
        res.header("Content-Encoding", "gzip")
    })

    //used to parse and convert JSON
    val gson = Gson()
    val templateEngine = HandlebarsTemplateEngine()

//    SqliteController.selectAllAlbums()

    get("/", { req, res -> ModelAndView(hashMapOf(Pair("name", "Test")), "index.hbs")  }, templateEngine)
    get("/hello/:name", { req, res -> ModelAndView(hashMapOf(Pair("name", req.params(":name"))), "index.hbs")  }, templateEngine)
    get("/user/:first/:last/json", { req, res -> User(req.params(":first"), req.params(":last")) }, { gson.toJson(it) })

    get("/api/albums", { req, res -> SqliteController.selectAllAlbums() }, { gson.toJson(it) })
    get("/api/albums/:id/images", { req, res -> SqliteController.imagesForAlbum(req.params(":id")) }, { gson.toJson(it) })
}

Edit routes to allow matches with trailing slash

package main

/**
 * Created by allen on 7/28/16.
 */
import spark.Spark.*
import com.google.gson.Gson
import controllers.SqliteController
import models.User
import spark.ModelAndView
import spark.template.handlebars.HandlebarsTemplateEngine
import java.util.*

fun main(args : Array<String>) {
    port(3000)

    staticFiles.location("/public")

    //allow routes to match with trailing slash
    before({ req, res ->
        val path = req.pathInfo()
        if (path.endsWith("/")){
            res.redirect(path.substring(0, path.length - 1))
        }
    })

    //gzip everything
    after({req, res ->
        res.header("Content-Encoding", "gzip")
    })

    //used to parse and convert JSON
    val gson = Gson()
    val templateEngine = HandlebarsTemplateEngine()

//    SqliteController.selectAllAlbums()

    get("/", { req, res -> ModelAndView(hashMapOf(Pair("name", "Test")), "index.hbs")  }, templateEngine)
    get("/hello/:name", { req, res -> ModelAndView(hashMapOf(Pair("name", req.params(":name"))), "index.hbs")  }, templateEngine)
    get("/user/:first/:last/json", { req, res -> User(req.params(":first"), req.params(":last")) }, { gson.toJson(it) })

    get("/api/albums", { req, res -> SqliteController.selectAllAlbums() }, { gson.toJson(it) })
    get("/api/albums/:id/images", { req, res -> SqliteController.imagesForAlbum(req.params(":id")) }, { gson.toJson(it) })
}


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

buildscript {

    val pluginsExperiments by extra(
        "org.gradle.kotlin:gradle-kotlin-dsl-conventions:0.2.0"
    )

    dependencies {
        classpath(pluginsExperiments)
    }

    configure(listOf(repositories, project.repositories)) {
        gradlePluginPortal()
    }
}

plugins {
    `kotlin-dsl`
}

kotlinDslPluginOptions {
    experimentalWarning.set(false)
}

apply(plugin = "org.gradle.kotlin-dsl.ktlint-convention")

tasks.validateTaskProperties {
    failOnWarning = true
}

tasks.withType<KotlinCompile>().configureEach {
    kotlinOptions {
        freeCompilerArgs += listOf(
            "-Xjsr305=strict",
            "-Xskip-runtime-version-check",
            "-Xskip-metadata-version-check"
        )
    }
}

val pluginsExperiments: String by extra

dependencies {
    compile(pluginsExperiments)

    compileOnly(gradleKotlinDsl())

    compile(kotlin("gradle-plugin"))
    compile(kotlin("stdlib-jdk8"))
    compile(kotlin("reflect"))

    compile("com.gradle.publish:plugin-publish-plugin:0.10.0")
    compile("org.ow2.asm:asm:6.2.1")

    testCompile("junit:junit:4.12")
    testCompile(gradleTestKit())
}

Rename extra property to better reflect new meaning

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

buildscript {

    val kotlinDslConventions by extra("org.gradle.kotlin:gradle-kotlin-dsl-conventions:0.2.0")

    dependencies {
        classpath(kotlinDslConventions)
    }

    configure(listOf(repositories, project.repositories)) {
        gradlePluginPortal()
    }
}

plugins {
    `kotlin-dsl`
}

kotlinDslPluginOptions {
    experimentalWarning.set(false)
}

apply(plugin = "org.gradle.kotlin-dsl.ktlint-convention")

tasks.validateTaskProperties {
    failOnWarning = true
}

tasks.withType<KotlinCompile>().configureEach {
    kotlinOptions {
        freeCompilerArgs += listOf(
            "-Xjsr305=strict",
            "-Xskip-runtime-version-check",
            "-Xskip-metadata-version-check"
        )
    }
}

val kotlinDslConventions: String by extra

dependencies {
    compile(kotlinDslConventions)

    compileOnly(gradleKotlinDsl())

    compile(kotlin("gradle-plugin"))
    compile(kotlin("stdlib-jdk8"))
    compile(kotlin("reflect"))

    compile("com.gradle.publish:plugin-publish-plugin:0.10.0")
    compile("org.ow2.asm:asm:6.2.1")

    testCompile("junit:junit:4.12")
    testCompile(gradleTestKit())
}


package fr.masciulli.drinks.core.drinks

class DrinksRepository(private val remoteSource: DrinksSource) : DrinksSource {
    override fun getDrinks() = remoteSource.getDrinks()
    override fun getDrink(id: String) = remoteSource.getDrink(id)
}

Add cache to drinks repository

package fr.masciulli.drinks.core.drinks

import rx.Observable

class DrinksRepository(private val remoteSource: DrinksSource) : DrinksSource {
    private val cachedDrinks: MutableMap<String, Drink> = LinkedHashMap()
    private var cached = false

    override fun getDrinks(): Observable<List<Drink>> {
        if (cached) {
            return Observable.just(cachedDrinks.values.toList())
        }
        return remoteSource.getDrinks().doOnNext { cacheDrinks(it) }
    }

    override fun getDrink(id: String): Observable<Drink> {
        val cachedDrink = cachedDrinks[id]
        if (cachedDrink != null) {
            return Observable.just(cachedDrink)
        }
        return remoteSource.getDrink(id).doOnNext { cacheDrinks(listOf(it)) }
    }

    private fun cacheDrinks(drinks: List<Drink>) {
        cachedDrinks.clear()

        drinks.forEach {
            cachedDrinks[it.id] = it
        }
        cached = true
    }
}


package com.octo.mob.octomeuh.countdown.utils

import android.os.CountDownTimer

interface CountDownListener {
    fun onValueUpdated(countValueInSeconds: Long)

    fun onCountDownOver()
}

open class SecondCountDownTimer(val secondsToCount: Int, val countDownListener: CountDownListener) : CountDownTimer((secondsToCount * 1000).toLong(), 1000) {
    override fun onFinish() {
        countDownListener.onValueUpdated(0)
        countDownListener.onCountDownOver()
    }

    override fun onTick(millisUntilFinished: Long) {
        countDownListener.onValueUpdated(millisUntilFinished / 1000)
    }
}

Decrease contdown refresh interval in order to have a smoother display

package com.octo.mob.octomeuh.countdown.utils

import android.os.CountDownTimer

interface CountDownListener {
    fun onValueUpdated(countValueInSeconds: Long)

    fun onCountDownOver()
}

open class SecondCountDownTimer(secondsToCount: Int, val countDownListener: CountDownListener) :
                 CountDownTimer(secondsToCount.secondsToMillis(), NOTIFICATION_INTERVAL_IN_MILLIS) {

    companion object {
        private val NOTIFICATION_INTERVAL_IN_MILLIS = 500L
    }

    override fun onFinish() {
        countDownListener.onValueUpdated(0)
        countDownListener.onCountDownOver()
    }

    override fun onTick(millisUntilFinished: Long) {
        countDownListener.onValueUpdated(millisUntilFinished / 1000)
    }

}

private fun Int.secondsToMillis() : Long {
    return this * 1000L
}


package com.beust.kobalt

class SystemProperties {
    companion object {
        val javaBase =
                System.getenv("JAVA_HOME")
                ?: System.getProperty("java.home")
                ?: throw IllegalArgumentException("JAVA_HOME not defined")
        val javaVersion = System.getProperty("java.version")
        val homeDir = System.getProperty("user.home")
        val tmpDir = System.getProperty("java.io.tmpdir")
        val currentDir = System.getProperty("user.dir")
        val username = System.getProperty("user.name")
    }
}

Make sure JAVA_HOME points to the JDK and not the JRE.

package com.beust.kobalt

class SystemProperties {
    companion object {
        val javaBase : String
            get() {
                val jh = System.getenv("JAVA_HOME")
                    ?: System.getProperty("java.home")
                    ?: throw IllegalArgumentException("JAVA_HOME not defined")
                val result =
                    if (jh.toLowerCase().endsWith("jre")) jh.substring(0, jh.length - 4)
                    else jh
                return result
            }
        val javaVersion = System.getProperty("java.version")
        val homeDir = System.getProperty("user.home")
        val tmpDir = System.getProperty("java.io.tmpdir")
        val currentDir = System.getProperty("user.dir")
        val username = System.getProperty("user.name")
    }
}


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

sealed class MLFeatureValue

class BinaryValue private constructor(val value: Boolean) : MLFeatureValue() {
  companion object {
    val TRUE = BinaryValue(true)
    val FALSE = BinaryValue(false)

    fun of(value: Boolean): BinaryValue = if (value) TRUE else FALSE
  }

  override fun toString(): String {
    return if (value) "1" else "0"
  }
}

class FloatValue private constructor(val value: Double) : MLFeatureValue() {
  companion object {
    fun of(value: Double) = FloatValue(value)
    fun of(value: Int) = FloatValue(value.toDouble())
  }

  override fun toString(): String = value.toString()
}

class CategoricalValue<T : Enum<*>> private constructor(val value: T) : MLFeatureValue() {
  companion object {
    fun <T : Enum<*>> of(value: T) = CategoricalValue(value)
  }

  override fun toString(): String = value.toString()
}

Add @JvmStatic to simplify usages in scala

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

sealed class MLFeatureValue

class BinaryValue private constructor(val value: Boolean) : MLFeatureValue() {
  companion object {
    val TRUE = BinaryValue(true)
    val FALSE = BinaryValue(false)

    @JvmStatic
    fun of(value: Boolean): BinaryValue = if (value) TRUE else FALSE
  }

  override fun toString(): String {
    return if (value) "1" else "0"
  }
}

class FloatValue private constructor(val value: Double) : MLFeatureValue() {
  companion object {
    @JvmStatic
    fun of(value: Double) = FloatValue(value)

    @JvmStatic
    fun of(value: Int) = FloatValue(value.toDouble())
  }

  override fun toString(): String = value.toString()
}

class CategoricalValue<T : Enum<*>> private constructor(val value: T) : MLFeatureValue() {
  companion object {
    @JvmStatic
    fun <T : Enum<*>> of(value: T) = CategoricalValue(value)
  }

  override fun toString(): String = value.toString()
}


package eu.kanade.tachiyomi.util.system

import android.annotation.SuppressLint
import timber.log.Timber

object MiuiUtil {

    fun isMiui(): Boolean {
        return getSystemProperty("ro.miui.ui.version.name")?.isNotEmpty() ?: false
    }

    @SuppressLint("PrivateApi")
    fun isMiuiOptimizationDisabled(): Boolean {
        if ("0" == getSystemProperty("persist.sys.miui_optimization")) {
            return true
        }

        return try {
            Class.forName("android.miui.AppOpsUtils")
                .getDeclaredMethod("isXOptMode")
                .invoke(null) as Boolean
        } catch (e: Exception) {
            false
        }
    }

    @SuppressLint("PrivateApi")
    private fun getSystemProperty(key: String?): String? {
        return try {
            Class.forName("android.os.SystemProperties")
                .getDeclaredMethod("get", String::class.java)
                .invoke(null, key) as String
        } catch (e: Exception) {
            Timber.w(e, "Unable to use SystemProperties.get")
            null
        }
    }
}

Update detection of disabled MIUI Optimization

package eu.kanade.tachiyomi.util.system

import android.annotation.SuppressLint
import timber.log.Timber

object MiuiUtil {

    fun isMiui(): Boolean {
        return getSystemProperty("ro.miui.ui.version.name")?.isNotEmpty() ?: false
    }

    @SuppressLint("PrivateApi")
    fun isMiuiOptimizationDisabled(): Boolean {
        val sysProp = getSystemProperty("persist.sys.miui_optimization")
        if (sysProp == "0" || sysProp == "false") {
            return true
        }

        return try {
            Class.forName("android.miui.AppOpsUtils")
                .getDeclaredMethod("isXOptMode")
                .invoke(null) as Boolean
        } catch (e: Exception) {
            false
        }
    }

    @SuppressLint("PrivateApi")
    private fun getSystemProperty(key: String?): String? {
        return try {
            Class.forName("android.os.SystemProperties")
                .getDeclaredMethod("get", String::class.java)
                .invoke(null, key) as String
        } catch (e: Exception) {
            Timber.w(e, "Unable to use SystemProperties.get")
            null
        }
    }
}


Add worker to generate report using specific reporter.

package org.jlleitschuh.gradle.ktlint.worker

import com.pinterest.ktlint.core.ReporterProvider
import org.gradle.api.GradleException
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.MapProperty
import org.gradle.api.provider.Property
import org.gradle.workers.WorkAction
import org.gradle.workers.WorkParameters
import java.io.FileInputStream
import java.io.ObjectInputStream
import java.io.PrintStream

@Suppress("UnstableApiUsage")
internal abstract class GenerateReportsWorkAction : WorkAction<GenerateReportsWorkAction.GenerateReportsParameters> {

    override fun execute() {
        val discoveredErrors = loadErrors()
        val currentReporterId = parameters.reporterId.get()
        val reporterProvider = loadReporterProviders().find { it.id == currentReporterId }
            ?: throw GradleException("Could not find ReporterProvider \"$currentReporterId\"")

        PrintStream(
            parameters
                .reporterOutput
                .get()
                .asFile
        ).use { printStream ->
            val reporter = reporterProvider.get(printStream, parameters.reporterOptions.get())

            reporter.beforeAll()
            discoveredErrors.forEach { lintErrorResult ->
                val filePath = lintErrorResult.lintedFile.absolutePath
                reporter.before(filePath)
                lintErrorResult.lintErrors.forEach {
                    reporter.onLintError(filePath, it.first.lintError, it.second)
                }
                reporter.after(filePath)
            }
            reporter.afterAll()
        }
    }

    private fun loadReporterProviders(): List<ReporterProvider> =
        ObjectInputStream(FileInputStream(parameters.loadedReporterProviders.asFile.get()))
            .use {
                @Suppress("UNCHECKED_CAST")
                it.readObject() as List<SerializableReporterProvider>
            }
            .map { it.reporterProvider }

    private fun loadErrors(): List<LintErrorResult> =
        ObjectInputStream(FileInputStream(parameters.discoveredErrorsFile.asFile.get()))
            .use {
                @Suppress("UNCHECKED_CAST")
                it.readObject() as List<LintErrorResult>
            }

    internal interface GenerateReportsParameters : WorkParameters {
        val discoveredErrorsFile: RegularFileProperty
        val loadedReporterProviders: RegularFileProperty
        val reporterId: Property<String>
        val reporterOutput: RegularFileProperty
        val reporterOptions: MapProperty<String, String>
    }
}


package com.reduks.reduks.combine_reducers

import com.reduks.reduks.Action

/**
 * Created by bloder on 18/02/18.
 */

class CombineReducers<State>(private val reducers: Array<out (State, Action<State>) -> State>) {

    fun combine() : (State, Action<State>) -> State = fun (initialState: State, action: Action<State>) : State {
        var state: State = initialState
        reducers.forEach {
            val currentState = it(state, action)
            state = if (currentState != state) currentState else state
        }
        return state
    }
}

fun <State> Any.combineReducers(vararg reducers: (State, Action<State>) -> State) : (State, Action<State>) -> State = CombineReducers(reducers).combine()

Decrease combine reducers solution size with fold

package com.reduks.reduks.combine_reducers

import com.reduks.reduks.Action

/**
 * Created by bloder on 18/02/18.
 */

class CombineReducers<State>(private val reducers: Array<out (State, Action<State>) -> State>) {

    fun combine() : (State, Action<State>) -> State = fun (initialState: State, action: Action<State>) : State = reducers.fold(initialState) { acc, reducer ->
        val currentState = reducer(acc, action)
        if (currentState != acc) currentState else acc
    }
}

fun <State> Any.combineReducers(vararg reducers: (State, Action<State>) -> State) : (State, Action<State>) -> State = CombineReducers(reducers).combine()


package chat.rocket.android.chatdetails.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import chat.rocket.android.chatdetails.domain.ChatDetails
import chat.rocket.android.db.ChatRoomDao

class ChatDetailsViewModel(private val chatRoomDao: ChatRoomDao): ViewModel() {

    fun getDetails(chatRoomId: String): LiveData<ChatDetails> {
        return Transformations.switchMap(chatRoomDao.get(chatRoomId)) { room ->
            val entity = room.chatRoom
            val data: MutableLiveData<ChatDetails> = MutableLiveData()

            data.value = ChatDetails(
                entity.name,
                entity.fullname,
                entity.type,
                entity.topic,
                entity.announcement,
                entity.description
            )

            return@switchMap data
        }
    }
}

Fix a null pointer exeption.

package chat.rocket.android.chatdetails.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import chat.rocket.android.chatdetails.domain.ChatDetails
import chat.rocket.android.db.ChatRoomDao

class ChatDetailsViewModel(private val chatRoomDao: ChatRoomDao) : ViewModel() {

    fun getDetails(chatRoomId: String): LiveData<ChatDetails> {
        return Transformations.switchMap(chatRoomDao.get(chatRoomId)) { room ->
            return@switchMap MutableLiveData<ChatDetails>().apply {
                room?.chatRoom?.run {
                    value = ChatDetails(
                        name,
                        fullname,
                        type,
                        topic,
                        announcement,
                        description
                    )
                }
            }
        }
    }
}


package org.runestar.client.plugins.std.debug

import org.runestar.client.game.api.Widget
import org.runestar.client.game.api.live.LiveCanvas
import org.runestar.client.game.api.live.Mouse
import org.runestar.client.game.api.live.Widgets
import org.runestar.client.plugins.PluginSettings
import org.runestar.client.utils.DisposablePlugin
import org.runestar.general.fonts.RUNESCAPE_CHAT_FONT
import java.awt.Color

class WidgetDebug : DisposablePlugin<PluginSettings>() {

    override val defaultSettings = PluginSettings()

    override fun start() {
        super.start()

        add(LiveCanvas.repaints.subscribe { g ->
            g.color = Color.WHITE
            g.font = RUNESCAPE_CHAT_FONT
            val mouse = Mouse.location
            val mouseWidget = Widgets.flat
                    .filter {
                        val s = it.shape
                        s != null && mouse in s
                    }
                    .minBy { it.width + it.height } ?: return@subscribe
            g.draw(mouseWidget.shape)
            val hierarchy = ArrayList<Widget>()
            var w: Widget? = mouseWidget
            while (w != null) {
                hierarchy.add(w)
                w = w.ancestor
            }
            val hierarchyString = hierarchy.joinToString(" > ") { it.idString() }
            g.drawString(hierarchyString, 30, 40)
        })
    }

    private fun Widget.idString(): String {
        var s = "${parentId.group}.${parentId.parent}"
        if (this is Widget.Child) {
            s += ":$childId"
        }
        return s
    }
}


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

package com.example.owl.ui.utils

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.drawWithContent
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.VerticalGradient

/**
 * A [Modifier] which draws a vertical gradient
 */
fun Modifier.scrim(colors: List<Color>): Modifier = composed {
    var height by remember { mutableStateOf(0f) }
    val gradient = remember(colors, height) {
        VerticalGradient(
            colors = colors,
            startY = 0f,
            endY = height
        )
    }
    drawWithContent {
        drawContent()
        height = size.height
        drawRect(brush = gradient)
    }
}

Update scrim to use `drawWithCache`

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

package com.example.owl.ui.utils

import androidx.compose.ui.Modifier
import androidx.compose.ui.drawWithCache
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.VerticalGradient

/**
 * A [Modifier] which draws a vertical gradient
 */
fun Modifier.scrim(colors: List<Color>): Modifier = drawWithCache {
    // Use drawWithCache modifier to create and cache the gradient when size is known or changes.
    val gradient = VerticalGradient(
        colors = colors,
        startY = 0f,
        endY = size.height
    )
    onDraw {
        drawRect(brush = gradient)
    }
}


dependencies {
    api(project(":vok-framework"))
    api(project(":vok-db"))
    api(project(":vok-util-vaadin"))

    testImplementation("com.github.mvysny.dynatest:dynatest-engine:${properties["dynatest_version"]}")
    testImplementation("org.slf4j:slf4j-simple:${properties["slf4j_version"]}")
    testImplementation("com.h2database:h2:${properties["h2_version"]}")
    testImplementation("com.zaxxer:HikariCP:${properties["hikaricp_version"]}")
    testImplementation("com.github.mvysny.kaributesting:karibu-testing-v10:${properties["kaributesting_version"]}")
}

kotlin {
    explicitApi()
}

val configureBintray = ext["configureBintray"] as (artifactId: String, description: String) -> Unit
configureBintray("vok-framework-v10-vokdb", "VOK: Vaadin 10 Flow with VOK-DB persistence")

Fix vok-framework-vokdb maven artifact name

dependencies {
    api(project(":vok-framework"))
    api(project(":vok-db"))
    api(project(":vok-util-vaadin"))

    testImplementation("com.github.mvysny.dynatest:dynatest-engine:${properties["dynatest_version"]}")
    testImplementation("org.slf4j:slf4j-simple:${properties["slf4j_version"]}")
    testImplementation("com.h2database:h2:${properties["h2_version"]}")
    testImplementation("com.zaxxer:HikariCP:${properties["hikaricp_version"]}")
    testImplementation("com.github.mvysny.kaributesting:karibu-testing-v10:${properties["kaributesting_version"]}")
}

kotlin {
    explicitApi()
}

val configureBintray = ext["configureBintray"] as (artifactId: String, description: String) -> Unit
configureBintray("vok-framework-vokdb", "VOK: Vaadin 10 Flow with VOK-DB persistence")


package net.grandcentrix.thirtyinch.kotlin

import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import net.grandcentrix.thirtyinch.TiPresenter
import net.grandcentrix.thirtyinch.TiView
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4

@RunWith(JUnit4::class)
class TiPresenterTest {

    interface View : TiView {

        fun aViewMethod()

    }

    class TestPresenter : TiPresenter<View>()

    private val mockView = mock<View>()

    @Test
    fun `test sendToViewKotlin should view as this and call it`() = with(TestPresenter()) {
        val tiTestPresenter = test()
        tiTestPresenter.create()
        tiTestPresenter.attachView(mockView)

        deliverToView { aViewMethod() }

        verify(mockView).aViewMethod()
    }
}

Add test for deliverToView without view

package net.grandcentrix.thirtyinch.kotlin

import com.nhaarman.mockito_kotlin.*
import net.grandcentrix.thirtyinch.TiPresenter
import net.grandcentrix.thirtyinch.TiView
import org.junit.*
import org.junit.runner.*
import org.junit.runners.*

@RunWith(JUnit4::class)
class TiPresenterTest {

    interface View : TiView {
        fun aViewMethod()
    }

    class TestPresenter : TiPresenter<View>()

    private val mockView = mock<View>()

    @Test
    fun `test deliverToView should view as this and call it`() = with(TestPresenter()) {
        val tiTestPresenter = test()
        tiTestPresenter.attachView(mockView)

        deliverToView { aViewMethod() }

        verify(mockView).aViewMethod()
    }

    @Test
    fun `test deliverToView without attached view`() = with(TestPresenter()) {
        val tiTestPresenter = test()
        deliverToView { aViewMethod() }
        verify(mockView, never()).aViewMethod()

        tiTestPresenter.attachView(mockView)
        verify(mockView).aViewMethod()
    }
}


Add test for path clash without `package` directive

package locationProvider

import org.jetbrains.dokka.plugability.DokkaContext
import org.jetbrains.dokka.base.resolvers.local.DefaultLocationProvider
import org.jetbrains.dokka.testApi.testRunner.AbstractCoreTest
import org.junit.Assert.assertNotEquals
import org.junit.Test

class DefaultLocationProviderTest: AbstractCoreTest() {
    @Test
    fun `#644 same directory for module and package`() {
        val configuration = dokkaConfiguration {
            passes {
                pass {
                    sourceRoots = listOf("src/")
                }
            }
        }

        testInline(
            """
            |/src/main/kotlin/basic/Test.kt
            |
            |class Test {
            |   val x = 1
            |}
        """.trimMargin(),
            configuration
        ) {
            var context: DokkaContext? = null
            pluginsSetupStage = {
                context = it
            }

            pagesGenerationStage = { module ->
                val lp = DefaultLocationProvider(module, context!!)
                assertNotEquals(lp.resolve(module.children.single()).removePrefix("/"), lp.resolve(module))
            }
        }
    }
}


package me.samthompson.bubbleactions_sample

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import me.samthompson.bubbleactions.BubbleActions

/**
 * Created by sam on 11/28/15.
 */
public class KotlinActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kotlin)

        val textView = findViewById(R.id.text_view);
        textView.setOnLongClickListener {
            BubbleActions.on(textView)
                    .addAction("Star", R.drawable.bubble_star, {
                        Toast.makeText(textView.context, "Star pressed!", Toast.LENGTH_SHORT).show()
                    })
                    .addAction("Share", R.drawable.bubble_share, {
                        Toast.makeText(textView.context, "Share pressed!", Toast.LENGTH_SHORT).show()
                    })
                    .addAction("Hide", R.drawable.bubble_hide, {
                        Toast.makeText(textView.context, "Hide pressed!", Toast.LENGTH_SHORT).show()
                    })
                    .show()
            true
        }
    }

}

Remove semicolon and unnecessary qualifier

package me.samthompson.bubbleactions_sample

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import me.samthompson.bubbleactions.BubbleActions

/**
 * Created by sam on 11/28/15.
 */
class KotlinActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kotlin)

        val textView = findViewById(R.id.text_view)
        textView.setOnLongClickListener {
            BubbleActions.on(textView)
                    .addAction("Star", R.drawable.bubble_star, {
                        Toast.makeText(textView.context, "Star pressed!", Toast.LENGTH_SHORT).show()
                    })
                    .addAction("Share", R.drawable.bubble_share, {
                        Toast.makeText(textView.context, "Share pressed!", Toast.LENGTH_SHORT).show()
                    })
                    .addAction("Hide", R.drawable.bubble_hide, {
                        Toast.makeText(textView.context, "Hide pressed!", Toast.LENGTH_SHORT).show()
                    })
                    .show()
            true
        }
    }

}


package com.jetbrains.rider.plugins.unity.run.configurations

import com.intellij.execution.configurations.ConfigurationTypeBase
import icons.UnityIcons

// We need to keep "UNITY_DEBUG_RUN_CONFIGURATION" for backwards compatibility - a user can run a newer EAP side by side
// with 2018.1 and still load the standard attach/debug run config. The new attach/debug/play config will still come up
// as "Unknown", but we can't help that
class UnityDebugConfigurationType : ConfigurationTypeBase(id,
    "Attach to Unity Editor", "Attach to Unity process and debug",
    UnityIcons.RunConfigurations.AttachToUnityParentConfiguration) {

    val attachToEditorFactory = UnityAttachToEditorFactory(this)
    val attachToEditorAndPlayFactory = UnityAttachToEditorAndPlayFactory(this)

    init {
        addFactory(attachToEditorFactory)
        addFactory(attachToEditorAndPlayFactory)
    }

    companion object {
        val id = "UNITY_DEBUG_RUN_CONFIGURATION"
    }
}

Make Unity run configs dumb aware

package com.jetbrains.rider.plugins.unity.run.configurations

import com.intellij.execution.configurations.ConfigurationTypeBase
import com.intellij.openapi.project.DumbAware
import icons.UnityIcons

class UnityDebugConfigurationType : ConfigurationTypeBase(id,
    "Attach to Unity Editor", "Attach to Unity process and debug",
    UnityIcons.RunConfigurations.AttachToUnityParentConfiguration), DumbAware {

    val attachToEditorFactory = UnityAttachToEditorFactory(this)
    val attachToEditorAndPlayFactory = UnityAttachToEditorAndPlayFactory(this)

    init {
        addFactory(attachToEditorFactory)
        addFactory(attachToEditorAndPlayFactory)
    }

    companion object {
        // Note that this value is incorrect. The JavaDoc states that the ID should be camel cased without dashes or
        // underscores, etc. But it's used as the key for persisting run configuration settings, and so shouldn't ever
        // be changed. Too late now.
        const val id = "UNITY_DEBUG_RUN_CONFIGURATION"
    }
}


package pink.madis.agptweeter

import java.nio.charset.StandardCharsets.UTF_8
import java.io.IOException

fun isNewRemoteVersion(remoteVersion: Version, local: Fetcher): Boolean {
  val localVersion = local.latestVersion() ?: return true // no local, so definitely later
  return remoteVersion > localVersion
}

fun checkAndTweet(artifactSource: ArtifactSource, cache: Store, db: Store, tweet: (String)->Unit) {
  println("Checking for new versions of ${artifactSource.prettyName}")

  val remote = artifactSource.fetcher

  val remoteVersion = remote.latestVersion() ?: throw IOException("Did not get a proper remote version")

  println("Latest remote version is ${remoteVersion.orig}")

  // hit cache first, because the most common case is that we're not hitting anything
  if (!isNewRemoteVersion(remoteVersion, StoreFetcher(cache, artifactSource.key))) {
    println("Local cache already has version, no tweet")
    return
  }
  if (!isNewRemoteVersion(remoteVersion, StoreFetcher(db, artifactSource.key))) {
    println("DynamoDB already has this version, no tweet")
    return
  }

  tweet("${artifactSource.prettyName} ${remoteVersion.orig} is out!")

  // update cache and db
  cache.write(artifactSource.key, remoteVersion.orig.toByteArray(UTF_8))
  db.write(artifactSource.key, remoteVersion.orig.toByteArray(UTF_8))
}

Update local cache after miss

package pink.madis.agptweeter

import java.nio.charset.StandardCharsets.UTF_8
import java.io.IOException

fun isNewRemoteVersion(remoteVersion: Version, local: Fetcher): Boolean {
  val localVersion = local.latestVersion() ?: return true // no local, so definitely later
  return remoteVersion > localVersion
}

fun checkAndTweet(artifactSource: ArtifactSource, cache: Store, db: Store, tweet: (String)->Unit) {
  println("Checking for new versions of ${artifactSource.prettyName}")

  val remote = artifactSource.fetcher

  val remoteVersion = remote.latestVersion() ?: throw IOException("Did not get a proper remote version")

  println("Latest remote version is ${remoteVersion.orig}")

  // hit cache first, because the most common case is that we're not hitting anything
  if (!isNewRemoteVersion(remoteVersion, StoreFetcher(cache, artifactSource.key))) {
    println("Local cache already has version, no tweet")
    return
  }
  if (!isNewRemoteVersion(remoteVersion, StoreFetcher(db, artifactSource.key))) {
    println("DynamoDB already has this version, no tweet")
    // update local cache too so that we don't hit dynamodb for the next run
    cache.write(artifactSource.key, remoteVersion.orig.toByteArray(UTF_8))
    return
  }

  val tweetContents = "${artifactSource.prettyName} ${remoteVersion.orig} is out!"
  println("Tweet: $tweetContents")
  tweet(tweetContents)

  // we've definitely tweeted now, update both cache and db
  cache.write(artifactSource.key, remoteVersion.orig.toByteArray(UTF_8))
  db.write(artifactSource.key, remoteVersion.orig.toByteArray(UTF_8))
}


package com.masahirosaito.spigot.homes.tests

enum class Permission(val permission: String) {

    HOME_DEFAULT("homes.command"),
    HOME_NAME("homes.command.name"),
    HOME_PLAYER("homes.command.player"),
    HOME_PLAYER_NAME("homes.command.player.name"),

    HOME_SET("homes.command.set"),
    HOME_SET_NAME("homes.command.set.name"),

    HOME_DELETE("homes.command.delete"),
    HOME_DELETE_NAME("homes.command.delete.name"),

    HOME_INVITE("homes.command.invite"),
    HOME_INVITE_NAME("homes.command.invite.name")
}

Add two permissions for private command

package com.masahirosaito.spigot.homes.tests

enum class Permission(val permission: String) {

    HOME_DEFAULT("homes.command"),
    HOME_NAME("homes.command.name"),
    HOME_PLAYER("homes.command.player"),
    HOME_PLAYER_NAME("homes.command.player.name"),

    HOME_SET("homes.command.set"),
    HOME_SET_NAME("homes.command.set.name"),

    HOME_DELETE("homes.command.delete"),
    HOME_DELETE_NAME("homes.command.delete.name"),

    HOME_INVITE("homes.command.invite"),
    HOME_INVITE_NAME("homes.command.invite.name"),

    HOME_PRIVATE("homes.command.private"),
    HOME_PRIVATE_NAME("homes.command.private.name")
}


package pl.droidsonroids.droidsmap.feature.office.mvp

import pl.droidsonroids.droidsmap.base.DataObserverAdapter
import pl.droidsonroids.droidsmap.feature.office.business_logic.OfficeFeatureBoundary
import pl.droidsonroids.droidsmap.model.Coordinates

class OfficePresenter private constructor(
        private val view: OfficeMvpView<OfficeUiModel>,
        private val officeFeatureBoundary : OfficeFeatureBoundary) {

    fun onRequestOffice() = officeFeatureBoundary.requestOffice(OfficeDataObserver())

    fun onRoomClicked(coordinates: Coordinates) = officeFeatureBoundary.changeToRoomPerspective()

    private fun updateUi(uiModel: OfficeUiModel) {
        view.setMapPanningConstraints(uiModel)
        view.focusMapOnOfficeLocation(uiModel)
        view.displayOfficeRooms(uiModel)
    }

    companion object {
        fun create(view: OfficeMvpView<OfficeUiModel>, officeFeatureBoundary: OfficeFeatureBoundary)
                = OfficePresenter(view, officeFeatureBoundary)
    }

    inner class OfficeDataObserver : DataObserverAdapter<OfficeUiModel>() {
        override fun onNext(model: OfficeUiModel) {
            updateUi(model)
        }

        override fun onError(e: Throwable) {
            TODO("NYI") // implement data fetch error
        }
    }
}

Implement view animates camera to room perspective

package pl.droidsonroids.droidsmap.feature.office.mvp

import pl.droidsonroids.droidsmap.base.DataObserverAdapter
import pl.droidsonroids.droidsmap.feature.office.business_logic.OfficeFeatureBoundary
import pl.droidsonroids.droidsmap.model.Coordinates

class OfficePresenter private constructor(
        private val view: OfficeMvpView<OfficeUiModel>,
        private val officeFeatureBoundary : OfficeFeatureBoundary) {

    fun onRequestOffice() = officeFeatureBoundary.requestOffice(OfficeDataObserver())

    fun onRoomClicked(coordinates: Coordinates) {
        officeFeatureBoundary.changeToRoomPerspective()
        view.animateCameraToClickedRoom()
    }

    private fun updateUi(uiModel: OfficeUiModel) {
        view.setMapPanningConstraints(uiModel)
        view.focusMapOnOfficeLocation(uiModel)
        view.displayOfficeRooms(uiModel)
    }

    companion object {
        fun create(view: OfficeMvpView<OfficeUiModel>, officeFeatureBoundary: OfficeFeatureBoundary)
                = OfficePresenter(view, officeFeatureBoundary)
    }

    inner class OfficeDataObserver : DataObserverAdapter<OfficeUiModel>() {
        override fun onNext(model: OfficeUiModel) {
            updateUi(model)
        }

        override fun onError(e: Throwable) {
            TODO("NYI") // implement data fetch error
        }
    }
}


package pl.mg6.likeornot.commons

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

Use subList instead of creating new List objects for chunks.

package pl.mg6.likeornot.commons

fun <T> List<T>.batch(chunkSize: Int): List<List<T>> {
    require(chunkSize > 0) { "chunkSize must be greater than 0" }
    val chunksCount = (size + chunkSize - 1) / chunkSize
    val chunkedList = ArrayList<List<T>>(chunksCount)
    for (i in 0 until size step chunkSize) {
        chunkedList.add(subList(i, minOf(i + chunkSize, size)))
    }
    return chunkedList
}