/*
 * Copyright 2013-2013 Eugene Petrenko
 *
 * 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.jonnyzzz.teamcity.plugins.node.common

/**
 * @author Eugene Petrenko (eugene.petrenko@gmail.com)
 * Date: 16.08.13 21:42
 */
class NVMBean {
  val NVMUsed : String = "Use_NodeJS_Install_Runner"
  val NVMAvailable : String = "node.js.nvm"
  val NVMFeatureType: String = "jonnyzzz.nvm"
  val NVMVersion : String = "version"
  val NVMSource : String = "fromSource"
  val NVMURL : String = "fromURL"

  val NVM_ArchiveUrl : String = "https://github.com/nvm-sh/nvm/archive/v0.34.0.zip"
  //"https://github.com/nvm-sh/nvm/archive/master.zip"
}

Update default NVM to latest

/*
 * Copyright 2013-2013 Eugene Petrenko
 *
 * 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.jonnyzzz.teamcity.plugins.node.common

/**
 * @author Eugene Petrenko (eugene.petrenko@gmail.com)
 * Date: 16.08.13 21:42
 */
class NVMBean {
  val NVMUsed : String = "Use_NodeJS_Install_Runner"
  val NVMAvailable : String = "node.js.nvm"
  val NVMFeatureType: String = "jonnyzzz.nvm"
  val NVMVersion : String = "version"
  val NVMSource : String = "fromSource"
  val NVMURL : String = "fromURL"

  val NVM_ArchiveUrl : String = "https://github.com/nvm-sh/nvm/archive/v0.35.3.zip"
  //"https://github.com/nvm-sh/nvm/archive/master.zip"
}


plugins {
    `kotlin-dsl`
}

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

group = "gradlebuild"

dependencies {
    implementation("org.gradle.kotlin.kotlin-dsl:org.gradle.kotlin.kotlin-dsl.gradle.plugin:1.4.4")
    implementation("org.gradle.kotlin:gradle-kotlin-dsl-conventions:0.7.0")
}

Fix `kotlin-dsl` plugin version used in `build-logic-commons/code-quality`

plugins {
    `kotlin-dsl`
}

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

group = "gradlebuild"

dependencies {
    implementation("org.gradle.kotlin.kotlin-dsl:org.gradle.kotlin.kotlin-dsl.gradle.plugin:2.1.4")
    implementation("org.gradle.kotlin:gradle-kotlin-dsl-conventions:0.7.0")
}


Add tests for ParticleSystem creating x amount of particles based on deltaTime

package nl.dionsegijn.konfetti.core

import android.graphics.Rect
import nl.dionsegijn.konfetti.core.emitter.Emitter
import org.junit.Assert
import org.junit.Test
import org.mockito.ArgumentMatchers.anyInt
import org.mockito.Mockito

class PartySystemTest {

    @Test
    fun `Test creating particles every 50ms per frame`() {
        val party = Party(
            emitter = Emitter(100L).max(2)
        )
        val system = PartySystem(party, pixelDensity = 1f)

        Assert.assertTrue(system.enabled)
        Assert.assertFalse(system.isDoneEmitting())

        val rect = Mockito.mock(Rect::class.java)
        Mockito.`when`(rect.height()).thenReturn(100)
        Mockito.`when`(rect.contains(anyInt(), anyInt())).thenReturn(true)

        val render1 = system.render(0.05f, rect)
        Assert.assertEquals(1, render1.size)

        val render2 = system.render(0.06f, rect)
        Assert.assertEquals(2, render2.size)
    }

    @Test
    fun `Test creating Particles with high initial deltaTime`() {
        val party = Party(
            emitter = Emitter(100L).max(2)
        )
        val system = PartySystem(party, pixelDensity = 1f)

        Assert.assertTrue(system.enabled)
        Assert.assertFalse(system.isDoneEmitting())

        val rect = Mockito.mock(Rect::class.java)
        Mockito.`when`(rect.height()).thenReturn(100)
        Mockito.`when`(rect.contains(anyInt(), anyInt())).thenReturn(true)

        val particles = system.render(60f, rect)
        Assert.assertEquals(2, particles.size)
    }
}


package com.livinglifetechway.k4kotlin.core

import android.app.Activity
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager

/**
 * Hides the soft keyboard
 * @receiver Activity
 * @return a boolean value if the action was performed or not
 */
fun Activity.hideKeyboard(): Boolean {
    val view = currentFocus
    view?.let {
        val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        return inputMethodManager.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
    }
    return false
}

/**
 * Opens up the keyboard by focusing on the view
 * @receiver View
 */
fun View.showKeyboard() {
    val imm = this.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}

/**
 * Opens up the keyboard forcefully
 * @receiver Context
 */
fun Context.showKeyboard() {
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0)
}

Fix show keyboard method for the view to requestFocus first

package com.livinglifetechway.k4kotlin.core

import android.app.Activity
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager

/**
 * Hides the soft keyboard
 * @receiver Activity
 * @return a boolean value if the action was performed or not
 */
fun Activity.hideKeyboard(): Boolean {
    val view = currentFocus
    view?.let {
        val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        return inputMethodManager.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
    }
    return false
}

/**
 * Opens up the keyboard by focusing on the view
 * @receiver View
 */
fun View.showKeyboard() {
    val imm = this.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    this.requestFocus()
    imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}

/**
 * Opens up the keyboard forcefully
 * @receiver Context
 */
fun Context.showKeyboard() {
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0)
}


/*
 * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
 * that can be found in the LICENSE file.
 */

package kotlin.system

/**
 * Gets current system time in milliseconds since epoch
 */
@SymbolName("Kotlin_system_getTimeMillis")
public external fun getTimeMillis() : Long

/**
 * Gets current system time in nanoseconds since epoch
 */
@SymbolName("Kotlin_system_getTimeNanos")
public external fun getTimeNanos() : Long

/**
 * Gets current system time in microseconds since epoch
 */
@SymbolName("Kotlin_system_getTimeMicros")
public external fun getTimeMicros() : Long

/** Executes the given [block] and returns elapsed time in milliseconds. */
public inline fun measureTimeMillis(block: () -> Unit) : Long {
    val start = getTimeMillis()
    block()
    return getTimeMillis() - start
}

/** Executes the given [block] and returns elapsed time in microseconds (Kotlin/Native only). */
public inline fun measureTimeMicros(block: () -> Unit) : Long {
    val start = getTimeMicros()
    block()
    return getTimeMicros() - start
}

/** Executes the given [block] and returns elapsed time in nanoseconds. */
public inline fun measureNanoTime(block: () -> Unit) : Long {
    val start = getTimeNanos()
    block()
    return getTimeNanos() - start
}

Fix doc for system time getters

/*
 * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
 * that can be found in the LICENSE file.
 */

package kotlin.system

/**
 * Gets current system time in milliseconds since certain moment in the past,
 * only delta between two subsequent calls makes sense.
 */
@SymbolName("Kotlin_system_getTimeMillis")
public external fun getTimeMillis() : Long

/**
 * Gets current system time in nanoseconds since certain moment in the past,
 * only delta between two subsequent calls makes sense.
 */
@SymbolName("Kotlin_system_getTimeNanos")
public external fun getTimeNanos() : Long

/**
 * Gets current system time in microseconds since certain moment in the past,
 * only delta between two subsequent calls makes sense.
 */
@SymbolName("Kotlin_system_getTimeMicros")
public external fun getTimeMicros() : Long

/** Executes the given [block] and returns elapsed time in milliseconds. */
public inline fun measureTimeMillis(block: () -> Unit) : Long {
    val start = getTimeMillis()
    block()
    return getTimeMillis() - start
}

/** Executes the given [block] and returns elapsed time in microseconds (Kotlin/Native only). */
public inline fun measureTimeMicros(block: () -> Unit) : Long {
    val start = getTimeMicros()
    block()
    return getTimeMicros() - start
}

/** Executes the given [block] and returns elapsed time in nanoseconds. */
public inline fun measureNanoTime(block: () -> Unit) : Long {
    val start = getTimeNanos()
    block()
    return getTimeNanos() - start
}


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

import com.intellij.debugger.streams.trace.dsl.LambdaBody
import com.intellij.debugger.streams.trace.dsl.StatementFactory

/**
 * @author Vitaliy.Bibaev
 */
class JavaLambdaBody(statementFactory: StatementFactory, override val argName: String) : JavaCodeBlock(statementFactory), LambdaBody {
  override fun toCode(indent: Int): String = if (isExpression()) statements.first().toCode(0) else super.toCode(indent)

  fun isExpression(): Boolean = statements.size == 1
}

Use updated api of CodeBlockBase in LambdaBody

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

import com.intellij.debugger.streams.trace.dsl.LambdaBody
import com.intellij.debugger.streams.trace.dsl.StatementFactory

/**
 * @author Vitaliy.Bibaev
 */
class JavaLambdaBody(statementFactory: StatementFactory, override val argName: String) : JavaCodeBlock(statementFactory), LambdaBody {
  override fun toCode(indent: Int): String = if (isExpression()) getStatements().first().toCode() else super.toCode(indent)

  fun isExpression(): Boolean = size == 1
}


package androidx.build.gradle.gcpbuildcache

import org.gradle.caching.configuration.AbstractBuildCache

/**
 * Gradle Build Cache that uses GCP buckets as a backing for load and store
 * Gradle results.
 *
 * @param projectId The Google Cloud Platform project id, that can be used for billing.
 * @param bucketName The name of the bucket that is used to store all the gradle cache entries.
 * This essentially becomes the root of all cache entries.
 */
open class GcpBuildCache(
) : AbstractBuildCache() {
  lateinit var projectId: String
  lateinit var bucketName: String
}

Move the docs to the right place

package androidx.build.gradle.gcpbuildcache

import org.gradle.caching.configuration.AbstractBuildCache

/**
 * Gradle Build Cache that uses GCP buckets as a backing for load and store
 * Gradle results.
 */
open class GcpBuildCache(
) : AbstractBuildCache() {
  /**
   * The Google Cloud Platform project id, that can be used for billing.
   */
  lateinit var projectId: String

  /**
   * The name of the bucket that is used to store all the gradle cache entries.
   * This essentially becomes the root of all cache entries.
   */
  lateinit var bucketName: String
}


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

plugins {
    kotlin("multiplatform")
    `maven-publish`
    id("com.jfrog.bintray")
}

kotlin {
    jvm()
    js()
    configure(targets) { configureMavenPublication() }
    sourceSets {
        getByName("commonMain").dependencies {
            api(kotlin("stdlib-common"))
        }
        getByName("jvmMain").dependencies {
            api(kotlin("stdlib-jdk7"))
        }
        getByName("jsMain").dependencies {
            api(kotlin("stdlib-js"))
        }
    }
}

publishing {
    setupAllPublications(project)
}

bintray {
    setupPublicationsUpload(project, publishing)
}

Add iOS and macOS support for bitflags split

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

plugins {
    kotlin("multiplatform")
    `maven-publish`
    id("com.jfrog.bintray")
}

kotlin {
    jvm()
    js()
    macos()
    ios()
    configure(targets) { configureMavenPublication() }
    setupNativeSourceSets()
    sourceSets {
        getByName("commonMain").dependencies {
            api(kotlin("stdlib-common"))
        }
        getByName("jvmMain").dependencies {
            api(kotlin("stdlib-jdk7"))
        }
        getByName("jsMain").dependencies {
            api(kotlin("stdlib-js"))
        }
    }
}

publishing {
    setupAllPublications(project)
}

bintray {
    setupPublicationsUpload(project, publishing)
}


package io.gitlab.arturbosch.detekt.rules.bugs

import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import org.jetbrains.kotlin.psi.KtBinaryExpressionWithTypeRHS
import org.jetbrains.kotlin.psi.KtPsiUtil

/**
 * @author Ivan Balaksha
 */
class UnsafeCast(config: Config = Config.empty) : Rule(config) {
	override val issue: Issue = Issue("UnsafeCast",
			Severity.Defect,
			"Cast operator throws an exception if the cast is not possible")

	override fun visitBinaryWithTypeRHSExpression(expression: KtBinaryExpressionWithTypeRHS) {
		if (KtPsiUtil.isUnsafeCast(expression)) {
			report(CodeSmell(issue, Entity.from(expression)))
		}
	}
}

Add dot in the end of description

package io.gitlab.arturbosch.detekt.rules.bugs

import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import org.jetbrains.kotlin.psi.KtBinaryExpressionWithTypeRHS
import org.jetbrains.kotlin.psi.KtPsiUtil

/**
 * @author Ivan Balaksha
 */
class UnsafeCast(config: Config = Config.empty) : Rule(config) {
	override val issue: Issue = Issue("UnsafeCast",
			Severity.Defect,
			"Cast operator throws an exception if the cast is not possible.")

	override fun visitBinaryWithTypeRHSExpression(expression: KtBinaryExpressionWithTypeRHS) {
		if (KtPsiUtil.isUnsafeCast(expression)) {
			report(CodeSmell(issue, Entity.from(expression)))
		}
	}
}


Create the integration test of SparkServerHandler

package com.felipecosta.microservice.server

import com.felipecosta.microservice.server.frontcontroller.FrontCommand
import org.junit.Test
import java.net.HttpURLConnection
import java.net.URL
import kotlin.test.assertEquals

class SparkServerHandlerTest {

    @Test
    fun givenHandlerWhenGetItShouldAssertResponse() {
        val stubFrontCommand = object : FrontCommand() {
            override fun process() {
                render(text = "SparkServerHandler Integration Test")
            }
        }
        SparkServerHandler().apply {
            get(GetHandler(Path("/"), { stubFrontCommand }))
        }

        spark.Spark.awaitInitialization()

        val urlConnection = (URL("http://localhost:8080").openConnection() as HttpURLConnection).apply {
            readTimeout = 2000
            connectTimeout = 2000
            requestMethod = "GET"
        }
        val response = urlConnection.inputStream.reader().use { it.readText() }

        assertEquals("SparkServerHandler Integration Test", response)

        spark.Spark.stop()
    }
}


package com.github.bjoernpetersen.musicbot.api

import com.github.bjoernpetersen.musicbot.spi.plugin.Provider

data class Song(
    val id: String,
    val provider: NamedPlugin<Provider>,
    val title: String,
    val description: String,
    val duration: Int?,
    val albumArtUrl: String?)

Add defaults to nullable song props

package com.github.bjoernpetersen.musicbot.api

import com.github.bjoernpetersen.musicbot.spi.plugin.Provider

data class Song @JvmOverloads constructor(
    val id: String,
    val provider: NamedPlugin<Provider>,
    val title: String,
    val description: String,
    val duration: Int? = null,
    val albumArtUrl: String? = null)


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

import androidx.lifecycle.GenericLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import kotlinx.coroutines.*
import kotlin.coroutines.resume

/**
 * This function returns/resumes as soon as the state of this [Lifecycle] is at least the
 * passed [state].
 *
 * [Lifecycle.State.DESTROYED] is forbidden, to avoid leaks.
 */
@PotentialFutureAndroidXLifecycleKtxApi
@UseExperimental(ExperimentalCoroutinesApi::class)
suspend fun Lifecycle.awaitState(state: Lifecycle.State) {
    require(state != Lifecycle.State.DESTROYED) {
        "DESTROYED is a terminal state that is forbidden for awaitState(…), to avoid leaks."
    }
    if (currentState >= state) return // Fast path
    @UseExperimental(MainDispatcherPerformanceIssueWorkaround::class)
    withContext(Dispatchers.MainAndroid.immediate) {
        if (currentState == Lifecycle.State.DESTROYED) { // Fast path to cancellation
            cancel()
        } else suspendCancellableCoroutine<Unit> { c ->
            val observer = object : GenericLifecycleObserver {
                override fun onStateChanged(source: LifecycleOwner?, event: Lifecycle.Event) {
                    if (currentState >= state) {
                        removeObserver(this)
                        c.resume(Unit)
                    } else if (currentState == Lifecycle.State.DESTROYED) {
                        c.cancel()
                    }
                }
            }
            addObserver(observer)
            c.invokeOnCancellation { removeObserver(observer) }
        }
    }
}

Remove no longer needed experimental annotation

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

import androidx.lifecycle.GenericLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import kotlinx.coroutines.*
import kotlin.coroutines.resume

/**
 * This function returns/resumes as soon as the state of this [Lifecycle] is at least the
 * passed [state].
 *
 * [Lifecycle.State.DESTROYED] is forbidden, to avoid leaks.
 */
@PotentialFutureAndroidXLifecycleKtxApi
suspend fun Lifecycle.awaitState(state: Lifecycle.State) {
    require(state != Lifecycle.State.DESTROYED) {
        "DESTROYED is a terminal state that is forbidden for awaitState(…), to avoid leaks."
    }
    if (currentState >= state) return // Fast path
    @UseExperimental(MainDispatcherPerformanceIssueWorkaround::class)
    withContext(Dispatchers.MainAndroid.immediate) {
        if (currentState == Lifecycle.State.DESTROYED) { // Fast path to cancellation
            cancel()
        } else suspendCancellableCoroutine<Unit> { c ->
            val observer = object : GenericLifecycleObserver {
                override fun onStateChanged(source: LifecycleOwner?, event: Lifecycle.Event) {
                    if (currentState >= state) {
                        removeObserver(this)
                        c.resume(Unit)
                    } else if (currentState == Lifecycle.State.DESTROYED) {
                        c.cancel()
                    }
                }
            }
            addObserver(observer)
            c.invokeOnCancellation { removeObserver(observer) }
        }
    }
}


/*
 * Copyright (C) 2016-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.xquery.resolve.reference

import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReferenceBase
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathEQName

class XQueryEQNamePrefixReference(element: XPathEQName, range: TextRange) : PsiReferenceBase<XPathEQName>(element, range) {
    override fun resolve(): PsiElement? {
        return element.resolvePrefixNamespace().map { ns -> ns.namespacePrefix?.element }.firstOrNull()
    }

    override fun getVariants(): Array<Any> {
        return arrayOf()
    }
}

Use XsQNameValue.expand to implement EQName prefix resolution.

/*
 * Copyright (C) 2016-2018 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.xquery.resolve.reference

import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReferenceBase
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathEQName
import uk.co.reecedunn.intellij.plugin.xpath.model.XPathNamespaceDeclaration
import uk.co.reecedunn.intellij.plugin.xpath.model.XsQNameValue
import uk.co.reecedunn.intellij.plugin.xpath.model.expand

class XQueryEQNamePrefixReference(element: XPathEQName, range: TextRange) : PsiReferenceBase<XPathEQName>(element, range) {
    override fun resolve(): PsiElement? {
        val ns = (element as XsQNameValue).expand().firstOrNull()?.namespace?.element
        return (ns?.parent as? XPathNamespaceDeclaration)?.namespacePrefix?.element
    }

    override fun getVariants(): Array<Any> {
        return arrayOf()
    }
}


plugins {
    id("java-gradle-plugin")
    kotlin("jvm") version "1.2.50"
}

repositories {
    jcenter()
    google()
}

dependencies {
    implementation(kotlin("stdlib-jdk8"))
    implementation("com.android.tools.build:gradle:3.1.3")
    implementation("org.jetbrains.dokka:dokka-android-gradle-plugin:0.9.17")
}

gradlePlugin {
    plugins {
        create("androidArtifacts") {
            id = "guru.stefma.androidartifacts"
            implementationClass = "guru.stefma.androidartifacts.AndroidArtifactsPlugin"
        }
    }
}

Add maven-publish to publish the plugin to mavenLocal

plugins {
    id("java-gradle-plugin")
    kotlin("jvm") version "1.2.50"
    id("maven-publish")
}

repositories {
    jcenter()
    google()
}

dependencies {
    implementation(kotlin("stdlib-jdk8"))
    implementation("com.android.tools.build:gradle:3.1.3")
    implementation("org.jetbrains.dokka:dokka-android-gradle-plugin:0.9.17")
}

gradlePlugin {
    plugins {
        create("androidArtifacts") {
            id = "guru.stefma.androidartifacts"
            implementationClass = "guru.stefma.androidartifacts.AndroidArtifactsPlugin"
        }
    }
}

/**
 * For local development.
 * Just run
 * ````
 * ./gradlew publishPluginMavenPublicationToMavenLocal
 * ```
 * to publish this plugin to the local maven
 *
 * Can be used either via
 * ```
 *     plugins { id("guru.stefma.androidartifcts") }
 * ```
 * or with the old `buildscript` block
 * ```
 *     buildscript {
 *         repositories {
 *             google()
 *             jcenter()
 *             mavenLocal()
 *         }
 *         dependencies { classpath "guru.stefma.androidartifacts:androidartifacts:DEV" }
 *     }
 *
 *     apply<guru.stefma.androidartifacts.AndroidArtifactsPlugin>()
 * ```
 */
group = "guru.stefma.androidartifacts"
version = "dev"


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

rootProject.name = "doma"

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

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

Update plugin com.diffplug.eclipse.apt to v3.36.1

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

rootProject.name = "doma"

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

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


package com.mercadopago.android.px.internal.features.payment_result.remedies

import com.mercadopago.android.px.internal.repository.UserSelectionRepository
import com.mercadopago.android.px.internal.viewmodel.mappers.Mapper
import com.mercadopago.android.px.model.PaymentData
import com.mercadopago.android.px.model.internal.remedies.PayerPaymentMethodRejected
import com.mercadopago.android.px.model.internal.remedies.RemediesBody

internal class RemediesBodyMapper(private val userSelectionRepository: UserSelectionRepository)
    : Mapper<PaymentData, RemediesBody>() {

    override fun map(data: PaymentData): RemediesBody {
        val securityCodeLocation = userSelectionRepository.card?.securityCodeLocation
        with(data) {
            val payerPaymentMethodRejected = PayerPaymentMethodRejected(payerCost?.installments,
                issuer?.name, token?.lastFourDigits, paymentMethod.id, paymentMethod.paymentTypeId,
                token?.securityCodeLength, securityCodeLocation, rawAmount)
            return RemediesBody(payerPaymentMethodRejected)
        }
    }
}

Fix sec code length null after invalid esc

package com.mercadopago.android.px.internal.features.payment_result.remedies

import com.mercadopago.android.px.internal.repository.UserSelectionRepository
import com.mercadopago.android.px.internal.viewmodel.mappers.Mapper
import com.mercadopago.android.px.model.PaymentData
import com.mercadopago.android.px.model.internal.remedies.PayerPaymentMethodRejected
import com.mercadopago.android.px.model.internal.remedies.RemediesBody

internal class RemediesBodyMapper(private val userSelectionRepository: UserSelectionRepository)
    : Mapper<PaymentData, RemediesBody>() {

    override fun map(data: PaymentData): RemediesBody {
        val (secCodeLocation, secCodeLength) = userSelectionRepository.card?.let{
            Pair(it.securityCodeLocation, it.securityCodeLength)
        } ?: Pair(null, null)
        with(data) {
            val payerPaymentMethodRejected = PayerPaymentMethodRejected(payerCost?.installments,
                issuer?.name, token?.lastFourDigits, paymentMethod.id, paymentMethod.paymentTypeId,
                secCodeLength, secCodeLocation, rawAmount)
            return RemediesBody(payerPaymentMethodRejected)
        }
    }
}


plugins {
	kotlin("jvm") version "1.6.21"
	id("com.github.johnrengelman.shadow") version "7.1.2"
}

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

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

dependencies {
	compileOnly("org.spigotmc:spigot-api:1.18.2-R0.1-SNAPSHOT")
	implementation(kotlin("stdlib-jdk8"))
}

tasks {
	shadowJar {
		relocate("org.jetbrains", "me.camdenorrb.opencast.libs.org.jetbrains")
		relocate("org.intellij", "me.camdenorrb.opencast.libs.org.intellij")
		relocate("com.google", "me.camdenorrb.opencast.libs.com.google")
		relocate("kotlin", "me.camdenorrb.opencast.libs.kotlin")
	}
}

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

plugins {
	kotlin("jvm") version "1.6.21"
	id("com.github.johnrengelman.shadow") version "7.1.2"
}

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

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

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

tasks {
	shadowJar {
		relocate("org.jetbrains", "me.camdenorrb.opencast.libs.org.jetbrains")
		relocate("org.intellij", "me.camdenorrb.opencast.libs.org.intellij")
		relocate("com.google", "me.camdenorrb.opencast.libs.com.google")
		relocate("kotlin", "me.camdenorrb.opencast.libs.kotlin")
	}
}


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

rootProject.name = "doma"

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

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

Update plugin com.diffplug.spotless to v6.7.2

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

rootProject.name = "doma"

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

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


description = "doma-slf4j"

dependencies {
    api("org.slf4j:slf4j-api:1.7.34")
    implementation(project(":doma-core"))
    testImplementation("ch.qos.logback:logback-classic:1.2.10")
}

Update dependency org.slf4j:slf4j-api to v1.7.35

description = "doma-slf4j"

dependencies {
    api("org.slf4j:slf4j-api:1.7.35")
    implementation(project(":doma-core"))
    testImplementation("ch.qos.logback:logback-classic:1.2.10")
}


dependencies {
    implementation(project(":build"))
    implementation(project(":configuration"))
    implementation(project(":kotlinDsl"))
    implementation(project(":versioning"))

    implementation("com.google.guava:guava")
    implementation("org.ow2.asm:asm:7.1")
    implementation("org.ow2.asm:asm-commons:7.1")
    implementation("com.google.code.gson:gson:2.7")

    testImplementation("org.junit.jupiter:junit-jupiter-api:5.1.0")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.1.0")
}

tasks.test {
    useJUnitPlatform()
}

gradlePlugin {
    plugins {
        register("minify") {
            id = "gradlebuild.minify"
            implementationClass = "org.gradle.gradlebuild.packaging.MinifyPlugin"
        }
        register("shadedJar") {
            id = "gradlebuild.shaded-jar"
            implementationClass = "org.gradle.gradlebuild.packaging.ShadedJarPlugin"
        }
        register("apiMetadata") {
            id = "gradlebuild.api-metadata"
            implementationClass = "org.gradle.gradlebuild.packaging.ApiMetadataPlugin"
        }
    }
}

Upgrade JUnit in buildSrc to latest

dependencies {
    implementation(project(":build"))
    implementation(project(":configuration"))
    implementation(project(":kotlinDsl"))
    implementation(project(":versioning"))

    implementation("com.google.guava:guava")
    implementation("org.ow2.asm:asm:7.1")
    implementation("org.ow2.asm:asm-commons:7.1")
    implementation("com.google.code.gson:gson:2.7")

    testImplementation("org.junit.jupiter:junit-jupiter-api:5.6.0")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.6.0")
}

tasks.test {
    useJUnitPlatform()
}

gradlePlugin {
    plugins {
        register("minify") {
            id = "gradlebuild.minify"
            implementationClass = "org.gradle.gradlebuild.packaging.MinifyPlugin"
        }
        register("shadedJar") {
            id = "gradlebuild.shaded-jar"
            implementationClass = "org.gradle.gradlebuild.packaging.ShadedJarPlugin"
        }
        register("apiMetadata") {
            id = "gradlebuild.api-metadata"
            implementationClass = "org.gradle.gradlebuild.packaging.ApiMetadataPlugin"
        }
    }
}


package org.jetbrains.dokka

public class JekyllFormatService(locationService: LocationService, signatureGenerator: SignatureGenerator)
: MarkdownFormatService(locationService, signatureGenerator) {

    override fun format(nodes: Iterable<DocumentationNode>, to: StringBuilder) {
        to.appendln("---")
        to.appendln("layout: post")
        to.appendln("title: ${nodes.first().name}")
        to.appendln("---")
        super<MarkdownFormatService>.format(nodes, to)
    }
}

Use html extension for jekyll so that links work

package org.jetbrains.dokka

public class JekyllFormatService(locationService: LocationService, signatureGenerator: SignatureGenerator)
: MarkdownFormatService(locationService, signatureGenerator) {
    override val extension: String = "html"
    override fun format(nodes: Iterable<DocumentationNode>, to: StringBuilder) {
        to.appendln("---")
        to.appendln("layout: post")
        to.appendln("title: ${nodes.first().name}")
        to.appendln("---")
        super<MarkdownFormatService>.format(nodes, to)
    }
}


fun main(args: Array<String>) {

    readLine() // Ignore first line (size of array)
    val array = readLine().orEmpty().trim().split(" ").map { num -> num.toInt() }.toMutableList()

    var qtySwaps = 0
    for (i in 0 until array.size) {
        var itSwaps = 0
        for (j in 0 until array.size - 1) {
            if (array[j] > array[j + 1]) {
                val aux = array[j]
                array[j] = array[j + 1]
                array[j + 1] = aux

                itSwaps++
            }
        }

        if (itSwaps == 0) break
        else qtySwaps += itSwaps
    }

    println("Array is sorted in $qtySwaps swaps.")
    println("First Element: ${array[0]}")
    println("Last Element: ${array.last()}")
}


package v_builders

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

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

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

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

Improve `getCellColor` naming of arguments

package v_builders

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

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

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

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


package org.mapdb.issues

import org.junit.Test
import org.mapdb.*

class Issue769_Map_putOnly{

    object valueSer: Serializer<String> {

        val ser = ArrayList<String>()
        val deser = ArrayList<String>()

        override fun serialize(out: DataOutput2, value: String) {
            ser += value
            out.writeUTF(value)
        }

        override fun deserialize(input: DataInput2, available: Int): String {
            val v = input.readUTF()
            deser += v
            return v
        }

    }

    @Test fun hashMap(){
        val m = DBMaker.memoryDB().make()
                .hashMap("map", Serializer.INTEGER, valueSer)
                .create()

        check(m)
    }

    @Test fun treeMap(){
        val m = DBMaker.memoryDB().make()
                .treeMap("map", Serializer.INTEGER, valueSer)
                .valuesOutsideNodesEnable()
                .create()

        check(m)
    }

    private fun check(m: MapExtra<Int, String>) {
        m.put(1, "one")
        valueSer.deser.clear()
        valueSer.ser.clear()
        m.putOnly(1, "two")

        assert(valueSer.ser == arrayListOf("two"))
        assert(valueSer.deser.isEmpty())
    }

}

Fix race condition in unit test

package org.mapdb.issues

import org.junit.Test
import org.mapdb.*

class Issue769_Map_putOnly : Serializer<String>{

    val ser = ArrayList<String>()
    val deser = ArrayList<String>()

    override fun serialize(out: DataOutput2, value: String) {
        ser += value
        out.writeUTF(value)
    }

    override fun deserialize(input: DataInput2, available: Int): String {
        val v = input.readUTF()
        deser += v
        return v
    }

    @Test fun hashMap(){
        val m = DBMaker.memoryDB().make()
                .hashMap("map", Serializer.INTEGER, this)
                .create()

        check(m)
    }

    @Test fun treeMap(){
        val m = DBMaker.memoryDB().make()
                .treeMap("map", Serializer.INTEGER, this)
                .valuesOutsideNodesEnable()
                .create()

        check(m)
    }

    private fun check(m: MapExtra<Int, String>) {
        m.put(1, "one")
        deser.clear()
        ser.clear()
        m.putOnly(1, "two")

        assert(ser == arrayListOf("two"))
        assert(deser.isEmpty())
    }

}


plugins {
    `java-library`
}

description = "Common test utilities for the add-ons."

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

val nanohttpdVersion = "2.3.1"
val jupiterVersion = "5.6.0"

dependencies {
    compileOnly("org.zaproxy:zap:2.9.0")

    api("org.hamcrest:hamcrest-library:1.3")
    api("org.junit.jupiter:junit-jupiter-api:$jupiterVersion")
    api("org.junit.jupiter:junit-jupiter-params:$jupiterVersion")
    runtimeOnly("org.junit.jupiter:junit-jupiter-engine:$jupiterVersion")
    api("org.mockito:mockito-junit-jupiter:3.1.0")

    api("org.nanohttpd:nanohttpd-webserver:$nanohttpdVersion")
    api("org.nanohttpd:nanohttpd-websocket:$nanohttpdVersion")
}

Upgrade test libraries to address test failures

plugins {
    `java-library`
}

description = "Common test utilities for the add-ons."

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

val nanohttpdVersion = "2.3.1"
val jupiterVersion = "5.7.0"

dependencies {
    compileOnly("org.zaproxy:zap:2.9.0")

    api("org.hamcrest:hamcrest-library:1.3")
    api("org.junit.jupiter:junit-jupiter-api:$jupiterVersion")
    api("org.junit.jupiter:junit-jupiter-params:$jupiterVersion")
    runtimeOnly("org.junit.jupiter:junit-jupiter-engine:$jupiterVersion")
    api("org.mockito:mockito-junit-jupiter:3.6.28")

    api("org.nanohttpd:nanohttpd-webserver:$nanohttpdVersion")
    api("org.nanohttpd:nanohttpd-websocket:$nanohttpdVersion")
}


package Gradle4_Check

import jetbrains.buildServer.configs.kotlin.v2018_1.project
import jetbrains.buildServer.configs.kotlin.v2018_1.version
import model_g4.CIBuildModel
import projects_g4.RootProject

/*
The settings script is an entry point for defining a single
TeamCity project. TeamCity looks for the 'settings.kts' file in a
project directory and runs it if it's found, so the script name
shouldn't be changed and its package should be the same as the
project's external id.

The script should contain a single call to the project() function
with a Project instance or an init function as an argument, you
can also specify both of them to refine the specified Project in
the init function.

VcsRoots, BuildTypes, and Templates of this project must be
registered inside project using the vcsRoot(), buildType(), and
template() methods respectively.

Subprojects can be defined either in their own settings.kts or by
calling the subProjects() method in this project.
*/

version = "2018.1"
project(RootProject(CIBuildModel(buildScanTags = listOf("Check"))))

Fix package name to Gradle_Check4

package Gradle_Check4

import jetbrains.buildServer.configs.kotlin.v2018_1.project
import jetbrains.buildServer.configs.kotlin.v2018_1.version
import model_g4.CIBuildModel
import projects_g4.RootProject

/*
The settings script is an entry point for defining a single
TeamCity project. TeamCity looks for the 'settings.kts' file in a
project directory and runs it if it's found, so the script name
shouldn't be changed and its package should be the same as the
project's external id.

The script should contain a single call to the project() function
with a Project instance or an init function as an argument, you
can also specify both of them to refine the specified Project in
the init function.

VcsRoots, BuildTypes, and Templates of this project must be
registered inside project using the vcsRoot(), buildType(), and
template() methods respectively.

Subprojects can be defined either in their own settings.kts or by
calling the subProjects() method in this project.
*/

version = "2018.1"
project(RootProject(CIBuildModel(buildScanTags = listOf("Check"))))


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

package configurations

import common.Branch

val triggerExcludes = """
        -:.idea
        -:.github
        -:.teamcity
        -:.teamcityTest
        -:subprojects/docs/src/docs/release
    """.trimIndent()

fun branchFilter(branch: Branch) = """
    +:$branch
""".trimIndent()

val allBranchesFilter = """
    +:*
    -:<default>
""".trimIndent()

Fix branch name case in triggers

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

package configurations

import common.Branch

val triggerExcludes = """
        -:.idea
        -:.github
        -:.teamcity
        -:.teamcityTest
        -:subprojects/docs/src/docs/release
    """.trimIndent()

fun branchFilter(branch: Branch) = """
    +:${branch.name.toLowerCase()}
""".trimIndent()

val allBranchesFilter = """
    +:*
    -:<default>
""".trimIndent()


package se.ltu.emapal.compute.util

import java.util.*

/**
 * Keeps track of time as an amount of milliseconds since the Unix 1970 epoch.
 *
 * This class represents the preferred way to store all times that are not directly presented to
 * human users, or where conditions make its use nonviable.
 */
class UnixTime private constructor(private val milliseconds: Long) {
    /** Converts time into [Calendar] object. */
    fun toCalendar() = Calendar.getInstance().apply {
        this.timeZone = TimeZone.getTimeZone("GMT")
        this.timeInMillis = toMilliseconds()
    }

    /** Converts time into [Date] object. */
    fun toDate() = Date(toMilliseconds())

    /** Converts time into the amount of milliseconds since the Unix 1970 epoch. */
    fun toMilliseconds(): Long = milliseconds

    override fun equals(other: Any?): Boolean{
        if (this === other) {
            return true
        }
        if (other?.javaClass != javaClass) {
            return false
        }

        other as UnixTime
        return milliseconds == other.milliseconds
    }

    override fun hashCode(): Int{
        return milliseconds.hashCode()
    }

    override fun toString(): String = toDate().toString()

    companion object {
        /** Gets current time. */
        fun now() = ofMilliseconds(System.currentTimeMillis())

        /** Creates new unix time object from given amount of milliseconds. */
        fun ofMilliseconds(milliseconds: Long) = UnixTime(milliseconds)
    }
}

Remove empty newline from UnixTim


import org.jetbrains.registerDokkaArtifactPublication

plugins {
    `maven-publish`
    id("com.jfrog.bintray")
}

dependencies {
    api("org.jetbrains:markdown:0.1.45")
    implementation(kotlin("reflect"))
    implementation("org.jsoup:jsoup:1.12.1")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.11.1")

    testImplementation(project(":testApi"))
    testImplementation(kotlin("test-junit"))
}

tasks {
    processResources {
        val dokka_version: String by project
        eachFile {
            if (name == "dokka-version.properties") {
                filter { line ->
                    line.replace("<dokka-version>", dokka_version)
                }
            }
        }
    }
}

registerDokkaArtifactPublication("dokkaCore") {
    artifactId = "dokka-core"
}

Declare `dokkaVersion` as input `processResources` task in :core

import org.jetbrains.dokkaVersion
import org.jetbrains.registerDokkaArtifactPublication

plugins {
    `maven-publish`
    id("com.jfrog.bintray")
}

dependencies {
    api("org.jetbrains:markdown:0.1.45")
    implementation(kotlin("reflect"))
    implementation("org.jsoup:jsoup:1.12.1")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.11.1")

    testImplementation(project(":testApi"))
    testImplementation(kotlin("test-junit"))
}

tasks {
    processResources {
        inputs.property("dokkaVersion", dokkaVersion)
        eachFile {
            if (name == "dokka-version.properties") {
                filter { line ->
                    line.replace("<dokka-version>", dokkaVersion)
                }
            }
        }
    }
}

registerDokkaArtifactPublication("dokkaCore") {
    artifactId = "dokka-core"
}


package org.paradise.ipaq.controllers

import org.paradise.ipaq.domain.ExperianAddress
import org.paradise.ipaq.domain.ExperianSearchResult
import org.paradise.ipaq.services.ExperianService
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController

/**
 * Created by terrence on 17/7/17.
 */
@RestController
class ipaqController(private val experianService: ExperianService) {

    @RequestMapping(value = "/Search", method = arrayOf(RequestMethod.GET), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
    fun search(@RequestParam(value = "query") query: String? = null,
               @RequestParam(value = "country") country: String? = null,
               @RequestParam(value = "take", defaultValue = "10") take: Int): ResponseEntity<ExperianSearchResult> {

        return experianService.search(query, country, take)
    }

    @RequestMapping(value = "/format", method = arrayOf(RequestMethod.GET), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
    fun format(@RequestParam(value = "country") country: String? = null,
               @RequestParam(value = "id") id: String? = null): ResponseEntity<ExperianAddress> {

        return experianService.format(country, id)
    }

}

Refactor controller injected object as immutable object

package org.paradise.ipaq.controllers

import org.paradise.ipaq.domain.ExperianAddress
import org.paradise.ipaq.domain.ExperianSearchResult
import org.paradise.ipaq.services.ExperianService
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController

/**
 * Created by terrence on 17/7/17.
 */
@RestController
class ipaqController(val experianService: ExperianService) {

    @RequestMapping(value = "/Search", method = arrayOf(RequestMethod.GET), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
    fun search(@RequestParam(value = "query") query: String? = null,
               @RequestParam(value = "country") country: String? = null,
               @RequestParam(value = "take", defaultValue = "10") take: Int): ResponseEntity<ExperianSearchResult> {

        return experianService.search(query, country, take)
    }

    @RequestMapping(value = "/format", method = arrayOf(RequestMethod.GET), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
    fun format(@RequestParam(value = "country") country: String? = null,
               @RequestParam(value = "id") id: String? = null): ResponseEntity<ExperianAddress> {

        return experianService.format(country, id)
    }

}


package se.barsk.park.datatypes

/**
 * A mock implementation of the CarCollection with a hard coded list of cars to
 * get well defined data and stable data. It does not persist any changes to storage.
 */
class MockCarCollection : CarCollection() {
    override fun readCarsFromStorage(): MutableList<OwnCar> {
        val car1 = OwnCar("ALP 110", "Margaretha")
        val car2 = OwnCar("MLB 803", "Margaretha")
        return mutableListOf(car1, car2)
    }

    override fun persistRemoval(ownCar: OwnCar) = Unit
    override fun persistUpdate(ownCar: OwnCar, position: Int) = Unit

    /**
     * Method intended to only be run by unit tests. Replaces the entire content
     * of the car collection with the given list of cars. Used to bypass persistent
     * storage
     */
    fun replaceContent(newCars: MutableList<OwnCar>) {
        ownCars.clear()
        ownCars.addAll(newCars)
    }
}

Make number of cars configurable in the mock car collection

package se.barsk.park.datatypes

/**
 * A mock implementation of the CarCollection with a hard coded list of cars to
 * get well defined data and stable data. It does not persist any changes to storage.
 */
class MockCarCollection(var numCars: Int = 2) : CarCollection() {
    override fun readCarsFromStorage(): MutableList<OwnCar> {
        val car1 = OwnCar("ALP 110", "Margaretha")
        val car2 = OwnCar("MLB 803", "Margaretha")
        return listOf(car1, car2).subList(0, numCars).toMutableList()
    }

    override fun persistRemoval(ownCar: OwnCar) = Unit
    override fun persistUpdate(ownCar: OwnCar, position: Int) = Unit

    /**
     * Method intended to only be run by unit tests. Replaces the entire content
     * of the car collection with the given list of cars. Used to bypass persistent
     * storage
     */
    fun replaceContent(newCars: MutableList<OwnCar>) {
        ownCars.clear()
        ownCars.addAll(newCars)
    }
}


package tv.fanart.bot

import kotlinx.coroutines.*
import org.koin.core.KoinComponent
import org.koin.core.inject
import tv.fanart.config.ConfigRepo
import java.lang.Runnable
import java.util.*

class FanartBot : KoinComponent {

    private val configurationClient by inject<ConfigRepo>()

    private val mainJob = SupervisorJob()
    private val mainContext = Dispatchers.Main + mainJob

    suspend fun start() = coroutineScope {
        configurationClient.updateConfig?.let { updateConfig ->
            launch(mainContext) {
                val updateBot = UpdateBot(updateConfig)
                while (true) {
                    updateBot.update(Date(updateConfig.lastUpdate))?.let {
                        configurationClient.updateConfig(updateConfig.copy(lastUpdate = it.time))
                    }
                    delay(updateConfig.delay)
                }
            }
        }

        // TODO Spawn off translation bot
        launch(mainContext) {
        }

        Runtime.getRuntime().addShutdownHook(Thread(Runnable {
            runBlocking {
                mainJob.cancelAndJoin()
            }
        }))

        yield()
    }
}

Add translation config launch strategy

package tv.fanart.bot

import kotlinx.coroutines.*
import org.koin.core.KoinComponent
import org.koin.core.inject
import tv.fanart.config.ConfigRepo
import java.lang.Runnable
import java.util.*

class FanartBot : KoinComponent {

    private val configurationClient by inject<ConfigRepo>()

    private val mainJob = SupervisorJob()
    private val mainContext = Dispatchers.Main + mainJob

    suspend fun start() = coroutineScope {
        configurationClient.updateConfig?.let { updateConfig ->
            launch(mainContext) {
                val updateBot = UpdateBot(updateConfig)
                while (true) {
                    updateBot.update(Date(updateConfig.lastUpdate))?.let {
                        configurationClient.updateConfig(updateConfig.copy(lastUpdate = it.time))
                    }
                    delay(updateConfig.delay)
                }
            }
        }

        configurationClient.translationConfig?.let {
            launch(mainContext) {
            }
        }

        Runtime.getRuntime().addShutdownHook(Thread(Runnable {
            runBlocking {
                mainJob.cancelAndJoin()
            }
        }))

        yield()
    }
}


rootProject.name = "SpongeAPI"

pluginManagement {
    repositories {
        mavenLocal()
        mavenCentral()
        gradlePluginPortal()
        maven("https://repo-new.spongepowered.org/repository/maven-public")
        maven("https://repo.spongepowered.org/maven")
    }
    resolutionStrategy {
        eachPlugin {
            if (requested.id.id.startsWith("org.spongepowered.gradle.")) {
                val version = requested.version ?: "0.11.7-SNAPSHOT"
                useModule("org.spongepowered:SpongeGradle:$version")
            }
            if (requested.id.id.startsWith("net.minecrell.licenser")) {
                val vresion = requested.version ?: "0.4.1"
                useModule("net.minecrell.licenser:licenser:$version")
            }
        }
    }
}

Fix resolving the licenser plugin.

rootProject.name = "SpongeAPI"

pluginManagement {
    repositories {
        mavenLocal()
        mavenCentral()
        gradlePluginPortal()
        maven("https://repo-new.spongepowered.org/repository/maven-public")
        maven("https://repo.spongepowered.org/maven")
    }
    resolutionStrategy {
        eachPlugin {
            if (requested.id.id.startsWith("org.spongepowered.gradle.")) {
                val version = requested.version ?: "0.11.7-SNAPSHOT"
                useModule("org.spongepowered:SpongeGradle:$version")
            }
            if (requested.id.id == "net.minecrell.licenser") {
                val version = requested.version ?: "0.4.1"
                useModule("gradle.plugin.net.minecrell:licenser:$version")
            }
        }
    }
}


package ee.schkola.fx

import ee.lang.TypedComposite
import ee.lang.fx.ModelApp
import ee.lang.fx.view.ExplorerModel
import ee.lang.initObjectTrees
import ee.schkola.Schkola
import ee.system.dev.BuildToolFactory
import ee.system.dev.Gradle
import ee.system.dev.Maven
import ee.system.task.SystemTaskRegistry
import ee.task.PathResolver
import ee.task.TaskRepository
import java.nio.file.Paths

open class SchkolaDesignApp() : ModelApp(ExplorerModel("SchkolaDesign", listOf("Component" to Schkola.initObjectTrees(true))) {
    it is TypedComposite<*>
}, taskRepository())
/*
{
    companion object {
        @JvmStatic fun main(args: Array<String>) {
            Application.launch(SchkolaDesignApp::class.java)
        }
    }
}
*/

private fun taskRepository(): TaskRepository {
    val ret = TaskRepository()
    val home = Paths.get("Schkola")
    val pathResolver = PathResolver(home, hashMapOf("SkolaModel" to "src"))
    val maven = Maven(home = home.resolve("maven"), plugins = arrayListOf("eclipse"),
            defaultProfiles = listOf(),
            defaultParams = hashMapOf())
    val gradle = Gradle(home = home.resolve("gradle"))
    val buildToolFactory = BuildToolFactory(maven, gradle)
    val systemTaskRegistry = SystemTaskRegistry(pathResolver, buildToolFactory)
    systemTaskRegistry.register(ret)
    return ret
}

Rework to use Map for child object, in order to simplify derive/copy of DSL objects

package ee.schkola.fx

import ee.lang.MultiHolder
import ee.lang.fx.ModelApp
import ee.lang.fx.view.ExplorerModel
import ee.lang.initObjectTrees
import ee.schkola.Schkola
import ee.system.dev.BuildToolFactory
import ee.system.dev.Gradle
import ee.system.dev.Maven
import ee.system.task.SystemTaskRegistry
import ee.task.PathResolver
import ee.task.TaskRepository
import java.nio.file.Paths

open class SchkolaDesignApp() : ModelApp(ExplorerModel("SchkolaDesign", listOf("Component" to Schkola.initObjectTrees(true))) {
    it is MultiHolder<*>
}, taskRepository())
/*
{
    companion object {
        @JvmStatic fun main(args: Array<String>) {
            Application.launch(SchkolaDesignApp::class.java)
        }
    }
}
*/

private fun taskRepository(): TaskRepository {
    val ret = TaskRepository()
    val home = Paths.get("Schkola")
    val pathResolver = PathResolver(home, hashMapOf("SkolaModel" to "src"))
    val maven = Maven(home = home.resolve("maven"), plugins = arrayListOf("eclipse"),
            defaultProfiles = listOf(),
            defaultParams = hashMapOf())
    val gradle = Gradle(home = home.resolve("gradle"))
    val buildToolFactory = BuildToolFactory(maven, gradle)
    val systemTaskRegistry = SystemTaskRegistry(pathResolver, buildToolFactory)
    systemTaskRegistry.register(ret)
    return ret
}


package guru.stefma.androidartifacts

import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.publish.maven.MavenPublication

class JavaArtifactsPlugin : Plugin<Project> {

    override fun apply(project: Project) {
        val extension = project.createJavaArtifactsExtension()
        project.applyMavenPublishPlugin()
        val publicationTasks = project.tasks.createListAvailablePublicationTask()
        val publicationName = "maven"
        project.tasks.createJavaArtifactsTask(publicationName)
        publicationTasks.publicationNames += publicationName
        createPublication(extension, project, publicationName, publicationTasks)
    }

    private fun Project.createJavaArtifactsExtension() =
            extensions.create("javaArtifact", ArtifactsExtension::class.java)

    private fun createPublication(
            extension: ArtifactsExtension,
            project: Project,
            publicationName: String,
            publicationTasks: ListGeneratedPublicationTasks
    ) {
        publicationTasks.publicationNames += publicationName
        project.publishingExtension.publications.create(publicationName, MavenPublication::class.java) {
            it.from(project.components.getByName("java"))
            // Publish sources only if set to true
            if (extension.sources) it.addJavaSourcesArtifact(project, "maven")
            // Publish javadoc only if set to true
            if (extension.javadoc) {
                it.addJavaJavadocArtifact(project, "maven")
            }

            it.setupMetadata(project, extension)
        }
    }

}

Move creating of in afterEvalutaion listener

package guru.stefma.androidartifacts

import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.publish.maven.MavenPublication

class JavaArtifactsPlugin : Plugin<Project> {

    override fun apply(project: Project) {
        val extension = project.createJavaArtifactsExtension()
        project.applyMavenPublishPlugin()
        val publicationTasks = project.tasks.createListAvailablePublicationTask()
        val publicationName = "maven"
        project.tasks.createJavaArtifactsTask(publicationName)
        publicationTasks.publicationNames += publicationName
        // TODO: Think if we can do that better lazy somehow
        // see https://docs.gradle.org/current/userguide/lazy_configuration.html
        project.afterEvaluate {
            createPublication(extension, project, publicationName, publicationTasks)
        }
    }

    private fun Project.createJavaArtifactsExtension() =
            extensions.create("javaArtifact", ArtifactsExtension::class.java)

    private fun createPublication(
            extension: ArtifactsExtension,
            project: Project,
            publicationName: String,
            publicationTasks: ListGeneratedPublicationTasks
    ) {
        publicationTasks.publicationNames += publicationName
        project.publishingExtension.publications.create(publicationName, MavenPublication::class.java) {
            it.from(project.components.getByName("java"))
            // Publish sources only if set to true
            if (extension.sources) it.addJavaSourcesArtifact(project, "maven")
            // Publish javadoc only if set to true
            if (extension.javadoc) {
                it.addJavaJavadocArtifact(project, "maven")
            }

            it.setupMetadata(project, extension)
        }
    }

}


package io.particle.mesh.ui.setup

import androidx.fragment.app.FragmentActivity
import com.squareup.phrase.Phrase
import io.particle.android.sdk.cloud.ParticleCloudSDK
import io.particle.mesh.setup.BarcodeData.CompleteBarcodeData
import io.particle.mesh.setup.flow.FlowRunnerUiListener
import io.particle.mesh.ui.R
import kotlinx.android.synthetic.main.fragment_scan_commissioner_code.*
import mu.KotlinLogging

class ScanCommissionerCodeFragment :  ScanIntroBaseFragment() {

    override val layoutId: Int = R.layout.fragment_scan_commissioner_code

    private val log = KotlinLogging.logger {}

    override fun onFragmentReady(activity: FragmentActivity, flowUiListener: FlowRunnerUiListener) {
        super.onFragmentReady(activity, flowUiListener)
        val productName = getUserFacingTypeName()

        textView.text = Phrase.from(view, R.string.p_scancommissionercode_tip_content)
            .put("product_type", productName)
            .format()

        setup_header_text.text = Phrase.from(view, R.string.pair_assisting_device_with_your_phone)
            .put("product_type", productName)
            .format()

        assistantText.text = Phrase.from(view, R.string.p_pairassistingdevice_subheader_1)
            .put("product_type", productName)
            .format()
    }

    override fun onBarcodeUpdated(barcodeData: CompleteBarcodeData?) {
        log.info { "onBarcodeUpdated(COMMISH): $barcodeData" }
        flowScopes.onWorker {
            flowUiListener?.commissioner?.updateBarcode(barcodeData!!, ParticleCloudSDK.getCloud())
        }
    }

}

Remove unnecessary code for formatting these strings now that they're static

package io.particle.mesh.ui.setup

import androidx.fragment.app.FragmentActivity
import com.squareup.phrase.Phrase
import io.particle.android.sdk.cloud.ParticleCloudSDK
import io.particle.mesh.setup.BarcodeData.CompleteBarcodeData
import io.particle.mesh.setup.flow.FlowRunnerUiListener
import io.particle.mesh.ui.R
import kotlinx.android.synthetic.main.fragment_scan_commissioner_code.*
import mu.KotlinLogging

class ScanCommissionerCodeFragment :  ScanIntroBaseFragment() {

    override val layoutId: Int = R.layout.fragment_scan_commissioner_code

    private val log = KotlinLogging.logger {}

    override fun onFragmentReady(activity: FragmentActivity, flowUiListener: FlowRunnerUiListener) {
        super.onFragmentReady(activity, flowUiListener)
        val productName = getUserFacingTypeName()
        assistantText.text = Phrase.from(view, R.string.p_pairassistingdevice_subheader_1)
            .put("product_type", productName)
            .format()
    }

    override fun onBarcodeUpdated(barcodeData: CompleteBarcodeData?) {
        log.info { "onBarcodeUpdated(COMMISH): $barcodeData" }
        flowScopes.onWorker {
            flowUiListener?.commissioner?.updateBarcode(barcodeData!!, ParticleCloudSDK.getCloud())
        }
    }

}


import org.gradle.gradlebuild.test.integrationtests.IntegrationTest
import org.gradle.gradlebuild.testing.integrationtests.cleanup.WhenNotEmpty
import org.gradle.gradlebuild.unittestandcompile.ModuleType

plugins {
    gradlebuild.classycle
}

repositories {
    mavenLocal()
}

dependencies {
    integTestCompile(library("groovy"))
    integTestCompile(library("ant"))
    integTestCompile(testLibrary("jsoup"))
    integTestCompile(testLibrary("sampleCheck")) {
        exclude(group = "org.codehaus.groovy", module = "groovy-all")
        exclude(module = "slf4j-simple")
    }

    val allTestRuntimeDependencies: DependencySet by rootProject.extra
    allTestRuntimeDependencies.forEach {
        integTestRuntime(it)
    }

    crossVersionTestCompile(project(":scala"))
    crossVersionTestCompile(project(":ide"))
    crossVersionTestCompile(project(":codeQuality"))
    crossVersionTestCompile(project(":signing"))

    allTestRuntimeDependencies.forEach {
        crossVersionTestRuntime(it)
    }
}

gradlebuildJava {
    moduleType = ModuleType.INTERNAL
}

testFixtures {
    from(":diagnostics", "integTest")
    from(":platformNative", "integTest")
}

val integTestTasks: DomainObjectCollection<IntegrationTest> by extra
integTestTasks.configureEach {
    libsRepository.required = true
}

testFilesCleanup {
    policy.set(WhenNotEmpty.REPORT)
}

Remove usage of `mavenLocal()` from `:integTest`

import org.gradle.gradlebuild.test.integrationtests.IntegrationTest
import org.gradle.gradlebuild.testing.integrationtests.cleanup.WhenNotEmpty
import org.gradle.gradlebuild.unittestandcompile.ModuleType

plugins {
    gradlebuild.classycle
}

dependencies {
    integTestCompile(library("groovy"))
    integTestCompile(library("ant"))
    integTestCompile(testLibrary("jsoup"))
    integTestCompile(testLibrary("sampleCheck")) {
        exclude(group = "org.codehaus.groovy", module = "groovy-all")
        exclude(module = "slf4j-simple")
    }

    val allTestRuntimeDependencies: DependencySet by rootProject.extra
    allTestRuntimeDependencies.forEach {
        integTestRuntime(it)
    }

    crossVersionTestCompile(project(":scala"))
    crossVersionTestCompile(project(":ide"))
    crossVersionTestCompile(project(":codeQuality"))
    crossVersionTestCompile(project(":signing"))

    allTestRuntimeDependencies.forEach {
        crossVersionTestRuntime(it)
    }
}

gradlebuildJava {
    moduleType = ModuleType.INTERNAL
}

testFixtures {
    from(":diagnostics", "integTest")
    from(":platformNative", "integTest")
}

val integTestTasks: DomainObjectCollection<IntegrationTest> by extra
integTestTasks.configureEach {
    libsRepository.required = true
}

testFilesCleanup {
    policy.set(WhenNotEmpty.REPORT)
}


package com.vimeo.networking2

/**
 * Based on CAPABILITY_PLATFORM_CONFIGS_OTA_FEATURES.
 */
data class FeaturesConfiguration(

    /**
     * The Chromecast receiver app ID.
     */
    val chromecastAppId: String?,

    /**
     * Is Comscore enabled for iOS?
     */
    val comscore: Boolean?,

    /**
     * Does the user reside within a GDPR-compliant country?
     */
    val gdprEnabled: Boolean?

)

Add play tracking enabled field to feature config

package com.vimeo.networking2

/**
 * Based on CAPABILITY_PLATFORM_CONFIGS_OTA_FEATURES.
 */
data class FeaturesConfiguration(

    /**
     * The Chromecast receiver app ID.
     */
    val chromecastAppId: String?,

    /**
     * Is Comscore enabled?
     */
    val comscore: Boolean?,

    /**
     * Does the user reside within a GDPR-compliant country?
     */
    val gdprEnabled: Boolean?,

    /**
     * Is play tracking enabled?
     */
    val playTracking: Boolean?

)


/*
 * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
 * that can be found in the LICENSE file.
 */

package test

import kotlin.test.*

public actual fun assertTypeEquals(expected: Any?, actual: Any?) {
    if (expected != null && actual != null) {
        assertEquals(expected::class, actual::class)
    } else {
        assertTrue(expected == null && actual == null)
    }
}

internal actual fun String.removeLeadingPlusOnJava6(): String = this

Fix assertTypeEquals to check subtypes

/*
 * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
 * that can be found in the LICENSE file.
 */

package test

import kotlin.test.*

public actual fun assertTypeEquals(expected: Any?, actual: Any?) {
    if (expected != null && actual != null) {
        assertTrue(expected::class.isInstance(actual) || actual::class.isInstance(expected),
                "Expected: $expected,  Actual: $actual")
    } else {
        assertTrue(expected == null && actual == null)
    }
}

internal actual fun String.removeLeadingPlusOnJava6(): String = this


package me.elsiff.morefish.fishing

import me.elsiff.morefish.announcement.PlayerAnnouncement
import me.elsiff.morefish.fishing.catchhandler.CatchHandler
import me.elsiff.morefish.fishing.condition.FishCondition
import org.bukkit.inventory.ItemStack
import kotlin.math.floor
import kotlin.random.Random

/**
 * Created by elsiff on 2018-12-20.
 */
data class FishType(
    val name: String,
    val rarity: FishRarity,
    val displayName: String,
    val lengthMin: Double,
    val lengthMax: Double,
    val icon: ItemStack,
    val catchHandlers: List<CatchHandler>,
    val catchAnnouncement: PlayerAnnouncement,
    val conditions: Set<FishCondition> = emptySet(),
    val hasNotFishItemFormat: Boolean = false,
    val noDisplay: Boolean = false,
    val hasCatchFirework: Boolean = false,
    val additionalPrice: Double = 0.0
) {
    fun generateFish(): Fish {
        check(lengthMin <= lengthMax) { "Max-length must not be smaller than min-length" }

        val length = lengthMin + Random.nextDouble() * (lengthMax - lengthMin)
        return Fish(this, floor(length * 10) / 10)
    }
}

Change the way to calculate length on generating fish

package me.elsiff.morefish.fishing

import me.elsiff.morefish.announcement.PlayerAnnouncement
import me.elsiff.morefish.fishing.catchhandler.CatchHandler
import me.elsiff.morefish.fishing.condition.FishCondition
import org.bukkit.inventory.ItemStack
import kotlin.math.floor
import kotlin.math.max
import kotlin.math.min
import kotlin.random.Random

/**
 * Created by elsiff on 2018-12-20.
 */
data class FishType(
    val name: String,
    val rarity: FishRarity,
    val displayName: String,
    val lengthMin: Double,
    val lengthMax: Double,
    val icon: ItemStack,
    val catchHandlers: List<CatchHandler>,
    val catchAnnouncement: PlayerAnnouncement,
    val conditions: Set<FishCondition> = emptySet(),
    val hasNotFishItemFormat: Boolean = false,
    val noDisplay: Boolean = false,
    val hasCatchFirework: Boolean = false,
    val additionalPrice: Double = 0.0
) {
    fun generateFish(): Fish {
        check(lengthMin <= lengthMax) { "Max-length must not be smaller than min-length" }

        val rawLength = lengthMin + Random.nextDouble() * (lengthMax - lengthMin)
        val length = clamp(floorToTwoDecimalPlaces(rawLength), lengthMin, lengthMax)
        return Fish(this, length)
    }

    private fun clamp(value: Double, min: Double, max: Double): Double =
        max(min(value, max), min)

    private fun floorToTwoDecimalPlaces(value: Double): Double =
        floor(value * 10) / 10
}


// Require Java 10 or higher
val javaVersion = JavaVersion.current()
require(javaVersion.isJava10Compatible) {
	"The JUnit 5 build requires Java 10 or higher. Currently executing with Java ${javaVersion.majorVersion}."
}

rootProject.name = "junit5"

include("documentation")
include("junit-jupiter-api")
include("junit-jupiter-engine")
include("junit-jupiter-migrationsupport")
include("junit-jupiter-params")
include("junit-platform-commons")
include("junit-platform-commons-java-9")
include("junit-platform-console")
include("junit-platform-console-standalone")
include("junit-platform-engine")
include("junit-platform-launcher")
include("junit-platform-runner")
include("junit-platform-suite-api")
include("junit-platform-surefire-provider")
include("junit-vintage-engine")
include("platform-tests")
include("platform-tooling-support-tests")
include("junit-bom")

// check that every subproject has a custom build file
// based on the project name
rootProject.children.forEach { project ->
	project.buildFileName = "${project.name}.gradle"
	require(project.buildFile.isFile)
}

enableFeaturePreview("STABLE_PUBLISHING")

Enable use of Kotlin DSL for subproject build scripts

// Require Java 10 or higher
val javaVersion = JavaVersion.current()
require(javaVersion.isJava10Compatible) {
	"The JUnit 5 build requires Java 10 or higher. Currently executing with Java ${javaVersion.majorVersion}."
}

rootProject.name = "junit5"

include("documentation")
include("junit-jupiter-api")
include("junit-jupiter-engine")
include("junit-jupiter-migrationsupport")
include("junit-jupiter-params")
include("junit-platform-commons")
include("junit-platform-commons-java-9")
include("junit-platform-console")
include("junit-platform-console-standalone")
include("junit-platform-engine")
include("junit-platform-launcher")
include("junit-platform-runner")
include("junit-platform-suite-api")
include("junit-platform-surefire-provider")
include("junit-vintage-engine")
include("platform-tests")
include("platform-tooling-support-tests")
include("junit-bom")

// check that every subproject has a custom build file
// based on the project name
rootProject.children.forEach { project ->
	project.buildFileName = "${project.name}.gradle"
	if (!project.buildFile.isFile) {
		project.buildFileName = "${project.name}.gradle.kts"
	}
	require(project.buildFile.isFile) {
		"${project.buildFile} must exist"
	}
}

enableFeaturePreview("STABLE_PUBLISHING")


package org.wordpress.aztec.spans

import android.text.style.StrikethroughSpan
import org.wordpress.aztec.AztecAttributes

class AztecStrikethroughSpan(tag: String = "del",
                             override var attributes: AztecAttributes = AztecAttributes())
    : StrikethroughSpan(), IAztecInlineSpan {
    override val TAG = tag
}

Update Aztec to use default strikethrough tag of <s> instead of <del>

package org.wordpress.aztec.spans

import android.text.style.StrikethroughSpan
import org.wordpress.aztec.AztecAttributes

class AztecStrikethroughSpan(tag: String = "s",
                             override var attributes: AztecAttributes = AztecAttributes())
    : StrikethroughSpan(), IAztecInlineSpan {
    override val TAG = tag
}


Create converter for Point model to/from gms model

/*
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     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.google.android.ground.ui.map

import android.location.Location
import com.google.android.gms.maps.model.LatLng
import com.google.android.ground.model.geometry.Coordinate
import com.google.android.ground.model.geometry.Point

fun LatLng.toPoint(): Point = Point(Coordinate(latitude, longitude))

fun Point.toLatLng(): LatLng = LatLng(coordinate.x, coordinate.y)

fun Location.toPoint(): Point = Point(Coordinate(latitude, longitude))


import org.jetbrains.dokka.gradle.DokkaTask

plugins {
    kotlin("multiplatform")
    id("org.jetbrains.dokka")
}

apply(from = "../template.root.gradle.kts")

kotlin {
    jvm()
    linuxX64("linux")
    macosX64("macos")
    sourceSets {
        named("commonMain") {
            dependencies {
                implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.8-1.4.0-rc")
            }
        }
    }
}

tasks.withType<DokkaTask> {
    dokkaSourceSets {
        create("commonMain")
        create("jvmMain")
        create("linuxMain")
        create("macosMain")
    }
}

Add js target back to Multiplatform0GradleIntegrationTest

import org.jetbrains.dokka.gradle.DokkaTask

plugins {
    kotlin("multiplatform")
    id("org.jetbrains.dokka")
}

apply(from = "../template.root.gradle.kts")

kotlin {
    jvm()
    linuxX64("linux")
    macosX64("macos")
    js()
    sourceSets {
        named("commonMain") {
            dependencies {
                implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.8-1.4.0-rc")
            }
        }
    }
}

tasks.withType<DokkaTask> {
    dokkaSourceSets {
        create("commonMain")
        create("jvmMain")
        create("linuxMain")
        create("macosMain")
        create("jsMain")
    }
}


package org.jetbrains.kotlin.r4a

import com.intellij.codeInsight.completion.CompletionContributor
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.lexer.KtTokens.LT
import org.jetbrains.kotlin.lexer.KtTokens.RBRACE
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.psi.KtxAttribute
import org.jetbrains.kotlin.psi.KtxElement

class R4aCompletionContributor : CompletionContributor() {
    override fun invokeAutoPopup(position: PsiElement, typeChar: Char): Boolean {
        // TODO(lmr): how can we "auto-close" on </ characters?
        if (typeChar == '<' && position.parent is KtBlockExpression) {
            // if the user types a bracket inside of a block, there is a high probability that they are
            // starting a ktx tag
            return true
        }
        if (typeChar == ' ' && position.parent is KtxElement) {
            // we are in a Ktx element about to type an attribute
            return true
        }
        if (typeChar == ' ' && position.parent is KtReferenceExpression && position.parent.prevSibling.node.elementType == LT) {
            // we have hit space after the tagname of a ktx open tag
            return true
        }
        if (typeChar == ' ' && position.parent is KtxAttribute && position.node.elementType == RBRACE) {
            // we have hit space after the closing brace of a ktx attribute
            return true
        }
        return super.invokeAutoPopup(position, typeChar)
    }
}

Fix NPE in Completion Contributor

package org.jetbrains.kotlin.r4a

import com.intellij.codeInsight.completion.CompletionContributor
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.lexer.KtTokens.LT
import org.jetbrains.kotlin.lexer.KtTokens.RBRACE
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.psi.KtxAttribute
import org.jetbrains.kotlin.psi.KtxElement

class R4aCompletionContributor : CompletionContributor() {
    override fun invokeAutoPopup(position: PsiElement, typeChar: Char): Boolean {
        // TODO(lmr): how can we "auto-close" on </ characters?
        if (typeChar == '<' && position.parent is KtBlockExpression) {
            // if the user types a bracket inside of a block, there is a high probability that they are
            // starting a ktx tag
            return true
        }
        if (typeChar == ' ' && position.parent is KtxElement) {
            // we are in a Ktx element about to type an attribute
            return true
        }
        if (typeChar == ' ' && position.parent is KtReferenceExpression && position.parent?.prevSibling?.node?.elementType == LT) {
            // we have hit space after the tagname of a ktx open tag
            return true
        }
        if (typeChar == ' ' && position.parent is KtxAttribute && position.node?.elementType == RBRACE) {
            // we have hit space after the closing brace of a ktx attribute
            return true
        }
        return super.invokeAutoPopup(position, typeChar)
    }
}


plugins {
   id("us.ihmc.ihmc-build")
}

ihmc {
   group = "us.ihmc"
   version = "0.1.0"
   vcsUrl = "https://your.vcs/url"
   openSource = false

   configureDependencyResolution()
   configurePublications()
}

println "hello"

mainDependencies {

}

testDependencies {

}

Fix bug in test project.

plugins {
   id("us.ihmc.ihmc-build")
}

ihmc {
   group = "us.ihmc"
   version = "0.1.0"
   vcsUrl = "https://your.vcs/url"
   openSource = false

   configureDependencyResolution()
   configurePublications()
}

println("hello")

mainDependencies {

}

testDependencies {

}


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

import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.lexer.KtToken

enum class WizardType(val wizardTypeName: String, val fileBodyFormat: String = "") {
    NONE("Source"),
    CLASS("Class", buildFileBody(KtTokens.CLASS_KEYWORD)),
    INTERFACE("Interface", buildFileBody(KtTokens.INTERFACE_KEYWORD)),
    OBJECT("Object", buildFileBody(KtTokens.OBJECT_KEYWORD)),
    ENUM("Enum", buildFileBody(KtTokens.ENUM_KEYWORD))
}

private val NOT_EMPTY_BODY_FORMAT = "%s {\n}"

private fun buildFileBody(modifier: KtToken): String = "$modifier $NOT_EMPTY_BODY_FORMAT"

Fix creation of enum class by wizard

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

import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.lexer.KtToken

enum class WizardType(val wizardTypeName: String, val fileBodyFormat: String = "") {
    NONE("Source"),
    CLASS("Class", buildFileBody(KtTokens.CLASS_KEYWORD)),
    INTERFACE("Interface", buildFileBody(KtTokens.INTERFACE_KEYWORD)),
    OBJECT("Object", buildFileBody(KtTokens.OBJECT_KEYWORD)),
    ENUM("Enum", buildFileBody(KtTokens.ENUM_KEYWORD, KtTokens.CLASS_KEYWORD))
}

private val NOT_EMPTY_BODY_FORMAT = "%s {\n}"

private fun buildFileBody(vararg modifiers: KtToken): String =
        "${modifiers.joinToString(separator = " ")} $NOT_EMPTY_BODY_FORMAT"


buildscript {
    dependencies {
        classpath("com.android.tools.build:gradle:2.3.1")
        classpath(kotlin("gradle-plugin"))
    }
    repositories {
        jcenter()
    }
}

apply {
    plugin("com.android.application")
    plugin("kotlin-android")
}

android {
    buildToolsVersion("25.0.0")
    compileSdkVersion(23)

    defaultConfig {
        minSdkVersion(15)
        targetSdkVersion(23)

        applicationId = "com.example.kotlingradle"
        versionCode = 1
        versionName = "1.0"
    }

    buildTypes {
        getByName("release") {
            isMinifyEnabled = false
            proguardFiles("proguard-rules.pro")
        }
    }
}

dependencies {
    compile("com.android.support:appcompat-v7:23.4.0")
    compile("com.android.support.constraint:constraint-layout:1.0.0-alpha8")
    compile(kotlin("stdlib"))
}

repositories {
    jcenter()
}

Upgrade Android tools to 2.3.3

buildscript {
    dependencies {
        classpath("com.android.tools.build:gradle:2.3.3")
        classpath(kotlin("gradle-plugin"))
    }
    repositories {
        jcenter()
    }
}

apply {
    plugin("com.android.application")
    plugin("kotlin-android")
}

android {
    buildToolsVersion("25.0.0")
    compileSdkVersion(23)

    defaultConfig {
        minSdkVersion(15)
        targetSdkVersion(23)

        applicationId = "com.example.kotlingradle"
        versionCode = 1
        versionName = "1.0"
    }

    buildTypes {
        getByName("release") {
            isMinifyEnabled = false
            proguardFiles("proguard-rules.pro")
        }
    }
}

dependencies {
    compile("com.android.support:appcompat-v7:23.4.0")
    compile("com.android.support.constraint:constraint-layout:1.0.0-alpha8")
    compile(kotlin("stdlib"))
}

repositories {
    jcenter()
}


/*
 * Copyright (c) Meta Platforms, Inc. and 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.
 */

inline fun ComponentScope.Spinner(
    options: List<String>,
    selectedOption: String,
    @LayoutRes itemLayout: Int = android.R.layout.simple_dropdown_item_1line,
    selectedTextSize: Dimen = 16.sp,
    @ColorInt selectedTextColor: Int = 0xDE000000.toInt(),
    caret: Drawable? = null,
    noinline onItemSelected: (ItemSelectedEvent) -> Unit
): Spinner =
    Spinner.create(context)
        .options(options)
        .selectedOption(selectedOption)
        .itemLayout(itemLayout)
        .selectedTextColor(selectedTextColor)
        .selectedTextSizePx(selectedTextSize.toPixels().toFloat())
        .caret(caret)
        .itemSelectedEventHandler(eventHandler(onItemSelected))
        .build()

Make all IG wrappers use ResourcesScope instead of ComponentScope

/*
 * Copyright (c) Meta Platforms, Inc. and 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.
 */

inline fun ResourcesScope.Spinner(
    options: List<String>,
    selectedOption: String,
    @LayoutRes itemLayout: Int = android.R.layout.simple_dropdown_item_1line,
    selectedTextSize: Dimen = 16.sp,
    @ColorInt selectedTextColor: Int = 0xDE000000.toInt(),
    caret: Drawable? = null,
    noinline onItemSelected: (ItemSelectedEvent) -> Unit
): Spinner =
    Spinner.create(context)
        .options(options)
        .selectedOption(selectedOption)
        .itemLayout(itemLayout)
        .selectedTextColor(selectedTextColor)
        .selectedTextSizePx(selectedTextSize.toPixels().toFloat())
        .caret(caret)
        .itemSelectedEventHandler(eventHandler(onItemSelected))
        .build()


package org.stepik.android.view.course.mapper

import android.content.Context
import org.stepic.droid.R
import javax.inject.Inject

class DisplayPriceMapper
@Inject
constructor(
    private val context: Context
) {
    companion object {
        private const val RUB_FORMAT = "RUB"
        private const val USD_FORMAT = "USD"
    }
    fun mapToDisplayPrice(currencyCode: String, price: String): String =
        when (currencyCode) {
            RUB_FORMAT ->
                context.getString(R.string.rub_format, price.substringBefore('.'))
            USD_FORMAT ->
                context.getString(R.string.usd_format, price)
            else ->
                "$price $currencyCode"
        }
}

Trim trailing zeroes in display prices

package org.stepik.android.view.course.mapper

import android.content.Context
import org.stepic.droid.R
import javax.inject.Inject

class DisplayPriceMapper
@Inject
constructor(
    private val context: Context
) {
    companion object {
        private const val RUB_FORMAT = "RUB"
        private const val USD_FORMAT = "USD"

        private const val RUB_SUFFIX = ".00"
    }
    fun mapToDisplayPrice(currencyCode: String, price: String): String =
        when (currencyCode) {
            RUB_FORMAT ->
                context.getString(R.string.rub_format, price.removeSuffix(RUB_SUFFIX))
            USD_FORMAT ->
                context.getString(R.string.usd_format, price)
            else ->
                "$price $currencyCode"
        }
}


package com.github.jackparisi.droidbox.binding

import android.databinding.BindingAdapter
import android.graphics.Rect
import android.util.Base64
import android.view.MotionEvent
import android.view.View
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import android.widget.ImageView
import com.bumptech.glide.Glide

/**
 * Created by Giacomo Parisi on 02/07/2017.
 * https://github.com/JackParisi
 */

@BindingAdapter("visibleOrGone")
fun bindVisibleOrGone(v: View, visible: Boolean) {
    v.visibility = if (visible) View.VISIBLE else View.GONE
}

@BindingAdapter("visibleOrInvisible")
fun bindVisibleOrInvisible(v: View, visible: Boolean) {
    v.visibility = if (visible) View.VISIBLE else View.INVISIBLE
}

Add docs for viewAdapter + methods refactor

package com.github.jackparisi.droidbox.binding

import android.databinding.BindingAdapter
import android.view.View

/**
 * Created by Giacomo Parisi on 02/07/2017.
 * https://github.com/JackParisi
 */

/**
 * Update the visibility of te view status VISIBLE/GONE based on boolean value
 *
 * @param view The view that need the visibility update
 * @param visible Set it to true for VISIBLE status or false for GONE status
 */
@BindingAdapter("visibleOrGone")
fun bindVisibleOrGone(view: View, visible: Boolean) {
    view.visibility = if (visible) View.VISIBLE else View.GONE
}

/**
 *
 * Update the visibility of te view status VISIBLE/INVISIBLE based on boolean value
 *
 * @param view The view that need the visibility update
 * @param visible Set it to true for VISIBLE status or false for INVISIBLE status
 */
@BindingAdapter("visibleOrInvisible")
fun bindVisibleOrInvisible(view: View, visible: Boolean) {
    view.visibility = if (visible) View.VISIBLE else View.INVISIBLE
}


package com.chimbori.crux.common

import java.lang.Character.isLetter

internal fun String.countMatches(substring: String): Int {
  var count = 0
  val indexOf = indexOf(substring)
  if (indexOf >= 0) {
    count++
    count += substring(indexOf + substring.length).countMatches(substring)
  }
  return count
}

/** Remove more than two spaces or newlines */
internal fun String.removeWhiteSpace() = replace("\\s+".toRegex(), " ").trim { it <= ' ' }

internal fun String.countLetters() = count { isLetter(it) }

internal fun String.nullIfBlank(): String? = ifBlank { null }

internal fun String.cleanTitle() = if (lastIndexOf("|") > length / 2) {
  substring(0, indexOf("|")).trim()
} else {
  removeWhiteSpace()
}

Make `String.nullIfBlank()` public, to allow callers to use it themselves.

package com.chimbori.crux.common

import java.lang.Character.isLetter

internal fun String.countMatches(substring: String): Int {
  var count = 0
  val indexOf = indexOf(substring)
  if (indexOf >= 0) {
    count++
    count += substring(indexOf + substring.length).countMatches(substring)
  }
  return count
}

/** Remove more than two spaces or newlines */
internal fun String.removeWhiteSpace() = replace("\\s+".toRegex(), " ").trim { it <= ' ' }

internal fun String.countLetters() = count { isLetter(it) }

public fun String.nullIfBlank(): String? = ifBlank { null }

internal fun String.cleanTitle() = if (lastIndexOf("|") > length / 2) {
  substring(0, indexOf("|")).trim()
} else {
  removeWhiteSpace()
}