/*
 * Copyright 2017 Ali Moghnieh
 *
 * 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.blurengine.blur.modules.message

import com.blurengine.blur.session.BlurPlayer
import net.kyori.text.Component

interface Message {
    val messageNode: String
    val component: Component

    fun component(vararg args: Any?): Component

    fun send(blurPlayer: BlurPlayer, vararg args: Any?)
}

abstract class AbstractMessage(override val messageNode: String) : Message

Remove component(vararg args: Any?) in favour of Kotlin Extension format method.

/*
 * Copyright 2017 Ali Moghnieh
 *
 * 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.blurengine.blur.modules.message

import com.blurengine.blur.session.BlurPlayer
import net.kyori.text.Component

interface Message {
    val messageNode: String
    val component: Component

    fun send(blurPlayer: BlurPlayer, vararg args: Any?)
}

abstract class AbstractMessage(override val messageNode: String, override val component: Component) : Message


package mixit.ticket.model

enum class TicketType {
    SPEAKER,
    SPONSOR_STAND,
    SPONSOR_PARTY,
    SPONSOR_PARTNER,
    STAFF,
    MIXTEEN,
    ATTENDEE,
    VOLUNTEER,
    GUEST,
    COMPETITION_WINNER,
    FOOD,
    MEDIA,
    MIXETTE
}

Add a new ticket type

package mixit.ticket.model

enum class TicketType {
    SPEAKER,
    SPONSOR_STAND,
    SPONSOR_PARTY,
    SPONSOR_PARTNER,
    STAFF,
    MIXTEEN,
    ATTENDEE,
    VOLUNTEER,
    GUEST,
    GUEST_ONE_TALK,
    COMPETITION_WINNER,
    FOOD,
    MEDIA,
    MIXETTE
}


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

package android.support

import org.gradle.api.Project
import org.gradle.api.plugins.ExtraPropertiesExtension
import java.io.File

object SupportConfig {
    const val DEFAULT_MIN_SDK_VERSION = 14
    const val INSTRUMENTATION_RUNNER = "android.support.test.runner.AndroidJUnitRunner"
    const val BUILD_TOOLS_VERSION = "27.0.1"
    const val CURRENT_SDK_VERSION = 26

    fun getKeystore(project: Project): File {
        val supportRoot = (project.rootProject.property("ext") as ExtraPropertiesExtension)
                .get("supportRootFolder") as File
        return File(supportRoot, "development/keystore/debug.keystore")
    }

    fun getLintBaseline(project: Project): File {
        return File(project.projectDir, "/lint-baseline.xml")
    }
}

Move to using SDK 27 for jetpack branch.

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

package android.support

import org.gradle.api.Project
import org.gradle.api.plugins.ExtraPropertiesExtension
import java.io.File

object SupportConfig {
    const val DEFAULT_MIN_SDK_VERSION = 14
    const val INSTRUMENTATION_RUNNER = "android.support.test.runner.AndroidJUnitRunner"
    const val BUILD_TOOLS_VERSION = "27.0.1"
    const val CURRENT_SDK_VERSION = 27

    fun getKeystore(project: Project): File {
        val supportRoot = (project.rootProject.property("ext") as ExtraPropertiesExtension)
                .get("supportRootFolder") as File
        return File(supportRoot, "development/keystore/debug.keystore")
    }

    fun getLintBaseline(project: Project): File {
        return File(project.projectDir, "/lint-baseline.xml")
    }
}


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

package at.yawk.javap

import at.yawk.javap.model.Paste
import at.yawk.javap.model.ProcessingInput
import javax.inject.Inject

/**
 * @author yawkat
 */
class DefaultPaste @Inject constructor(sdkProvider: SdkProvider, processor: Processor) {
    val defaultPastes = sdkProvider.defaultSdkByLanguage.map {
        val code = when(it.key) {
            SdkLanguage.JAVA -> """import java.util.*;
import java.lang.*;
import java.lang.invoke.*;
import java.lang.reflect.*;
import java.io.*;

public class Main {
    public Main() {
        int i = 0;
        i++;
    }
}"""
            SdkLanguage.KOTLIN -> """import java.util.*

class Main() {
    init {
        var i = 0
        i++
    }
}"""
            SdkLanguage.SCALA -> """object Main {
    def test(i: Int) = i + 1
}"""
        }
        val input = ProcessingInput(code, it.value.name)
        Paste("default:${it.key}", "", input, processor.process(input))
    }
}

Remove a bunch of imports from the default java paste

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

package at.yawk.javap

import at.yawk.javap.model.Paste
import at.yawk.javap.model.ProcessingInput
import javax.inject.Inject

/**
 * @author yawkat
 */
class DefaultPaste @Inject constructor(sdkProvider: SdkProvider, processor: Processor) {
    val defaultPastes = sdkProvider.defaultSdkByLanguage.map {
        val code = when(it.key) {
            SdkLanguage.JAVA -> """import java.util.*;

public class Main {
    public Main() {
        int i = 0;
        i++;
    }
}"""
            SdkLanguage.KOTLIN -> """import java.util.*

class Main() {
    init {
        var i = 0
        i++
    }
}"""
            SdkLanguage.SCALA -> """object Main {
    def test(i: Int) = i + 1
}"""
        }
        val input = ProcessingInput(code, it.value.name)
        Paste("default:${it.key}", "", input, processor.process(input))
    }
}


package net.squanchy.support.time

import org.threeten.bp.format.DateTimeFormatter

fun createShortTimeFormatter(): DateTimeFormatter = DateTimeFormatter.ofPattern("h:mm a")

fun createShortDateFormatter(): DateTimeFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy")

fun createWeekDayAndDayFormatter(): DateTimeFormatter = DateTimeFormatter.ofPattern("EEE d")

Add locale to formatter creator functions

package net.squanchy.support.time

import org.threeten.bp.format.DateTimeFormatter
import java.util.Locale

fun createShortTimeFormatter(locale: Locale = Locale.getDefault()): DateTimeFormatter =
    DateTimeFormatter.ofPattern("h:mm a").withLocale(locale)

fun createShortDateFormatter(locale: Locale = Locale.getDefault()): DateTimeFormatter =
    DateTimeFormatter.ofPattern("MM/dd/yyyy").withLocale(locale)

fun createWeekDayAndDayFormatter(locale: Locale = Locale.getDefault()): DateTimeFormatter =
    DateTimeFormatter.ofPattern("EEE d").withLocale(locale)


/*
 * Copyright 2014-2018 Julien Guerinet
 *
 * 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.guerinet.mymartlet.util.room.converters

import com.guerinet.room.converter.BaseListConverter
import org.threeten.bp.DayOfWeek

/**
 * Room Converter for a list of [DayOfWeek]s
 * @author Julien Guerinet
 * @since 2.0.0
 */
class DayOfWeekListConverter : BaseListConverter<DayOfWeek>() {

    override fun objectToString(value: DayOfWeek): String = value.value.toString()

    override fun objectFromString(value: String): DayOfWeek = DayOfWeek.of(value.toInt())
}

Fix bug where an empty list of days would crash the reading from the DB

/*
 * Copyright 2014-2018 Julien Guerinet
 *
 * 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.guerinet.mymartlet.util.room.converters

import androidx.room.TypeConverter
import com.guerinet.room.converter.BaseListConverter
import org.threeten.bp.DayOfWeek

/**
 * Room Converter for a list of [DayOfWeek]s
 * @author Julien Guerinet
 * @since 2.0.0
 */
class DayOfWeekListConverter : BaseListConverter<DayOfWeek>() {

    /**
     * Overriding [fromString] here to never return a null value
     */
    @TypeConverter
    override fun fromString(value: String?): List<DayOfWeek>? = super.fromString(value) ?: listOf()

    override fun objectToString(value: DayOfWeek): String = value.value.toString()

    override fun objectFromString(value: String): DayOfWeek = DayOfWeek.of(value.toInt())
}


package se.barsk.park.mainui

import android.content.Context
import android.graphics.PorterDuff
import android.support.v4.content.ContextCompat
import android.view.View
import se.barsk.park.R
import se.barsk.park.datatypes.Car

/**
 * An interface for all lists of cars (parked cars and own cars)
 */
interface CarListEntry {
    fun showItem(car: Car, selected: Boolean = false, garageFull: Boolean = false)

    fun setAvatarColor(car: Car, context: Context, view: View) =
            setAvatarColor(getColorForCar(car, context), context, view)

    fun setAvatarColor(color: Int, context: Context, view: View) {
        val drawable = ContextCompat.getDrawable(context, R.drawable.circle_drawable)
        drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
        view.background = drawable
        view.setPadding(0, 0, 0, 0) // setting background resets padding, remove it again
    }

    fun getColorForCar(car: Car, context: Context): Int {
        val colors = context.resources.getIntArray(R.array.avatar_background_color)
        return colors[Math.abs(car.regNo.hashCode()) % colors.size]
    }
}

Fix oversized check mark when selecting cars

package se.barsk.park.mainui

import android.content.Context
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.support.v4.content.ContextCompat
import android.view.View
import se.barsk.park.R
import se.barsk.park.datatypes.Car

/**
 * An interface for all lists of cars (parked cars and own cars)
 */
interface CarListEntry {
    fun showItem(car: Car, selected: Boolean = false, garageFull: Boolean = false)

    fun setAvatarColor(car: Car, context: Context, view: View) =
            setAvatarColor(getColorForCar(car, context), context, view)

    fun setAvatarColor(color: Int, context: Context, view: View) {
        val drawable = ContextCompat.getDrawable(context, R.drawable.circle_drawable)
        drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
        setBackgroundPreservePadding(view, drawable)
    }

    fun getColorForCar(car: Car, context: Context): Int {
        val colors = context.resources.getIntArray(R.array.avatar_background_color)
        return colors[Math.abs(car.regNo.hashCode()) % colors.size]
    }

    private fun setBackgroundPreservePadding(view: View, background: Drawable) {
        val pL = view.paddingLeft
        val pT = view.paddingTop
        val pR = view.paddingRight
        val pB = view.paddingBottom

        view.background = background
        view.setPadding(pL, pT, pR, pB)
    }
}


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

package org.jitsi.rtp.util

import org.jitsi.rtp.ByteArrayBuffer
import org.jitsi.rtp.extensions.bytearray.getInt

class SrtpUtils {
    companion object {
        fun getSrtcpIndex(packet: ByteArrayBuffer, authTagLen: Int): Int =
            packet.buffer.getInt(packet.length - (4 + authTagLen))
    }
}

Fix reading the SRTCP index.

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

package org.jitsi.rtp.util

import org.jitsi.rtp.ByteArrayBuffer
import org.jitsi.rtp.extensions.bytearray.getInt

class SrtpUtils {
    companion object {
        fun getSrtcpIndex(packet: ByteArrayBuffer, authTagLen: Int): Int =
            packet.buffer.getInt(packet.offset + packet.length - (4 + authTagLen))
    }
}


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

package io.sweers.catchup.util

import android.os.Build
import android.view.View

fun View.setLightStatusBar() {
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    var flags = systemUiVisibility
    // TODO noop if it's already set
    flags = flags or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
    systemUiVisibility = flags
  }
}

fun View.clearLightStatusBar() {
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    var flags = systemUiVisibility
    // TODO noop if it's already not set
    flags = flags and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv()
    systemUiVisibility = flags
  }
}

Add some View extensions for visibility

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

@file:Suppress("NOTHING_TO_INLINE")

package io.sweers.catchup.util

import android.os.Build
import android.view.View

fun View.setLightStatusBar() {
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    var flags = systemUiVisibility
    // TODO noop if it's already set
    flags = flags or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
    systemUiVisibility = flags
  }
}

fun View.clearLightStatusBar() {
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    var flags = systemUiVisibility
    // TODO noop if it's already not set
    flags = flags and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv()
    systemUiVisibility = flags
  }
}

inline fun View.isVisible() = visibility == View.VISIBLE
inline fun View.makeVisible() {
  visibility = View.VISIBLE
}

inline fun View.isGone() = visibility == View.GONE
inline fun View.makeGone() {
  visibility = View.GONE
}


package org.wikipedia.views

import android.annotation.SuppressLint
import android.content.Context
import android.view.View
import android.widget.LinearLayout
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import kotlinx.android.synthetic.main.view_dialog_title_with_image.view.*
import org.wikipedia.R

@SuppressLint("ViewConstructor")
class DialogTitleWithImage(
        context: Context,
        @StringRes titleRes: Int,
        @DrawableRes imageRes: Int,
        private val preserveImageAspect: Boolean
) : LinearLayout(context) {

    init {
        View.inflate(context, R.layout.view_dialog_title_with_image, this)
        orientation = VERTICAL
        title.setText(titleRes)
        image.setImageResource(imageRes)
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        super.onLayout(changed, l, t, r, b)
        if (image.drawable != null && preserveImageAspect) {
            val params = image.layoutParams as LayoutParams
            params.height = (image.drawable.intrinsicHeight.toDouble() / image.drawable.intrinsicWidth * image.width).toInt()
            image.layoutParams = params
        }
    }
}

Add line breaker on the last line


package com.agoda.sample

import android.content.Intent
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.widget.Button
import android.widget.ImageView

class TestActivity: AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)
    }

    override fun onResume() {
        super.onResume()
        findViewById<ImageView>(R.id.map).tag = "test_tag"

        findViewById<Button>(R.id.button).setOnClickListener {
            startActivity(Intent(this, RecyclerActivity::class.java))
        }

        findViewById<Button>(R.id.web_button).setOnClickListener {
            startActivity(Intent(this, WebAcitivty::class.java))
        }

        findViewById<Button>(R.id.snackbar_button).setOnClickListener {
            val snackbar = Snackbar.make(findViewById(android.R.id.content),
                    "This is snackbar!", Snackbar.LENGTH_LONG)

            snackbar.setAction("DISMISS") {
                snackbar.dismiss()
            }

            snackbar.show()
        }
    }
}

Add logging to seek bar

package com.agoda.sample

import android.content.Intent
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import android.widget.SeekBar

class TestActivity: AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)
    }

    override fun onResume() {
        super.onResume()
        findViewById<ImageView>(R.id.map).tag = "test_tag"

        findViewById<Button>(R.id.button).setOnClickListener {
            startActivity(Intent(this, RecyclerActivity::class.java))
        }

        findViewById<Button>(R.id.web_button).setOnClickListener {
            startActivity(Intent(this, WebAcitivty::class.java))
        }

        findViewById<Button>(R.id.snackbar_button).setOnClickListener {
            val snackbar = Snackbar.make(findViewById(android.R.id.content),
                    "This is snackbar!", Snackbar.LENGTH_LONG)

            snackbar.setAction("DISMISS") {
                snackbar.dismiss()
            }

            snackbar.show()
        }

        findViewById<SeekBar>(R.id.seek_bar).setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                Log.d("KAKAO", "SeekBar progress is: $progress")
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })
    }
}


package Kotlin101.Loops

fun main(args : Array<String>) {
    var presidents = array("jfk", "nixon", "carter")

    print("I love these presidents ")
    for (p in presidents) {
        print ("$p,")
    }

    println("")
    print("I loath these presidents ")
    var loop = presidents.size
    while (loop > 0) {
        loop--
        print("${presidents[loop]}, ")
    }

    println("")
    print("I puzzle these presidents ")
    var pool = presidents.size
    do {
        pool--
        print("${presidents[pool]}, ")
    }while(pool > 0)
}

Fix loop naming and for in indices

package Kotlin101.Loops

fun main(args : Array<String>) {
    var presidents = array("jfk", "nixon", "carter")

    print("I love these presidents ")
    for (p in presidents) {
        print ("$p, ")
    }

    println("")
    print("I voted for these presidents ")
    for (p in presidents.indices) {
        print ("${presidents[p]}, ")
    }

    println("")
    print("I loath these presidents ")
    var i = presidents.size
    while (i > 0) {
        i--
        print("${presidents[i]}, ")
    }

    println("")
    print("I puzzle these presidents ")
    var q = presidents.size
    do {
        q--
        print("${presidents[q]}, ")
    }while(q > 0)
}


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

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

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

Reduce the number of projects in the build scan performance test

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

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

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


package com.nibado.projects.advent.y2020

import com.nibado.projects.advent.*

object Day13 : Day {
    private val lines = resourceLines(2020, 13)
    private val timeStamp = lines.first().toInt()
    private val busIds = lines.last().split(",").toList()

    override fun part1(): Int = busIds.filterNot { it == "x" }.map { it.toInt() }
            .map { it to timeStamp - (timeStamp % it) + it }
            .minBy { it.second - timeStamp }!!
            .let { it.first * (it.second - timeStamp) }

    override fun part2(): Long {
        val busses = busIds.mapIndexed { i, id -> id to i }
                .filterNot { it.first == "x" }.map { (a, b) -> a.toInt() to b }

        var subList = busses.take(2)

        var time = 0L
        var increment = subList.first().first.toLong()

        while(true) {
            time += increment

            if(subList.all { (time + it.second) % it.first == 0L }) {
                if(subList.size == busses.size) {
                    break
                } else {
                    increment = subList.map { it.first.toLong() }.reduce { a, b -> a * b }
                    subList = busses.take(subList.size + 1)
                }
            }
        }

        return time
    }
}

Refactor Day 13 part 2

package com.nibado.projects.advent.y2020

import com.nibado.projects.advent.*

object Day13 : Day {
    private val lines = resourceLines(2020, 13)
    private val timeStamp = lines.first().toInt()
    private val busIds = lines.last().split(",").toList()

    override fun part1(): Int = busIds.filterNot { it == "x" }.map { it.toInt() }
            .map { it to timeStamp - (timeStamp % it) + it }
            .minBy { it.second - timeStamp }!!
            .let { it.first * (it.second - timeStamp) }

    override fun part2(): Long {
        val busses = busIds.mapIndexed { i, id -> id to i }
                .filterNot { it.first == "x" }.map { (a, b) -> a.toInt() to b }

        var time = 0L
        var increment = 1L

        for((id, i) in busses) {
            while((time + i) % id != 0L) {
                time += increment
            }
            increment *= id
        }

        return time
    }
}


package nl.rubensten.texifyidea.run.compiler

import com.intellij.openapi.project.Project
import nl.rubensten.texifyidea.run.BibtexRunConfiguration

/**
 * @author Thomas Schouten
 */
internal object BiberCompiler : Compiler<BibtexRunConfiguration> {

    override val displayName = "Biber"
    override val executableName = "biber"

    override fun getCommand(runConfig: BibtexRunConfiguration, project: Project): List<String>? {
        val command = mutableListOf<String>()

        command.apply {
            if (runConfig.compilerPath != null) {
                add(runConfig.compilerPath!!)
            }
            else add(executableName)

            // Biber can find auxiliary files, but the flag is different from bibtex
//            add("--output-directory=${runConfig.auxDir?.path ?: ""}")
            add("--output-directory=${runConfig.mainFile?.parent?.path ?: ""}")

            runConfig.compilerArguments?.let { addAll(it.split("""\s+""".toRegex())) }

            // todo replace this test
            add("../auxil/" + (runConfig.mainFile?.nameWithoutExtension ?: return null))
        }

        return command.toList()
    }
}

Fix biber flag to include resource file

package nl.rubensten.texifyidea.run.compiler

import com.intellij.openapi.project.Project
import nl.rubensten.texifyidea.run.BibtexRunConfiguration

/**
 * @author Thomas Schouten
 */
internal object BiberCompiler : Compiler<BibtexRunConfiguration> {

    override val displayName = "Biber"
    override val executableName = "biber"

    override fun getCommand(runConfig: BibtexRunConfiguration, project: Project): List<String>? {
        val command = mutableListOf<String>()

        command.apply {
            if (runConfig.compilerPath != null) {
                add(runConfig.compilerPath!!)
            }
            else add(executableName)

            // Biber can find auxiliary files, but the flag is different from bibtex.
            // The following flag assumes the command is executed in the directory where the .bcf control file is.
            // The extra directory added is the directory from which the path to the .bib resource file is searched as specified in the .bcf file.
            add("--input-directory=${runConfig.mainFile?.parent?.path ?: ""}")

            runConfig.compilerArguments?.let { addAll(it.split("""\s+""".toRegex())) }

            add(runConfig.mainFile?.nameWithoutExtension ?: return null)
        }

        return command.toList()
    }
}


package org.jetbrains.ktor.netty

import io.netty.channel.*
import io.netty.handler.codec.http.*
import org.jetbrains.ktor.application.*
import org.jetbrains.ktor.interception.*

class NettyApplicationRequestContext(override val application: Application,
                                     val context: ChannelHandlerContext,
                                     val httpRequest: FullHttpRequest) : ApplicationRequestContext {
    val httpResponse = DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK)

    override val close = Interceptable0<Unit> {
        context.writeAndFlush(httpResponse)
        context.close()
    }

    override val request: NettyApplicationRequest = NettyApplicationRequest(httpRequest)
    override val response: NettyApplicationResponse = NettyApplicationResponse(httpResponse)
}

Use chunked encoding if other kind of encoding or content-length was not specified.

package org.jetbrains.ktor.netty

import io.netty.channel.*
import io.netty.handler.codec.http.*
import org.jetbrains.ktor.application.*
import org.jetbrains.ktor.http.HttpHeaders
import org.jetbrains.ktor.interception.*

class NettyApplicationRequestContext(override val application: Application,
                                     val context: ChannelHandlerContext,
                                     val httpRequest: FullHttpRequest) : ApplicationRequestContext {
    val httpResponse = DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK)

    override val close = Interceptable0<Unit> {
        if (response.headers.get(HttpHeaders.TransferEncoding) == null
                && response.headers.get(HttpHeaders.ContentLength) == null) {
            response.headers.append(HttpHeaders.TransferEncoding, "chunked")
        }
        context.writeAndFlush(httpResponse)
        context.close()
    }

    override val request: NettyApplicationRequest = NettyApplicationRequest(httpRequest)
    override val response: NettyApplicationResponse = NettyApplicationResponse(httpResponse)
}


package com.androidmess.helix.discover.view

import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import com.androidmess.helix.R
import com.androidmess.helix.common.ui.recyclerview.RecyclerViewItemSizeCalculator
import com.androidmess.helix.common.ui.view.inflate
import com.androidmess.helix.databinding.DiscoverListItemBinding
import com.androidmess.helix.discover.model.data.DiscoverMovieViewModel

class DiscoverAdapter(private val itemSizeCalculator: RecyclerViewItemSizeCalculator)
    : RecyclerView.Adapter<DiscoverAdapter.ViewHolder>() {

    private val data: MutableList<DiscoverMovieViewModel> = ArrayList()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = parent.inflate(R.layout.discover_list_item, false)
        val viewParams = view.layoutParams
        viewParams.width = itemSizeCalculator.itemWidth
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(data[position])

    override fun getItemCount(): Int = data.size

    fun addData(movies: List<DiscoverMovieViewModel>) {
        data.addAll(movies)
        notifyDataSetChanged()
    }

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {

        private var binding: DiscoverListItemBinding = DiscoverListItemBinding.bind(view)

        fun bind(movieModel: DiscoverMovieViewModel) {
            binding.movie = movieModel
        }
    }
}

Fix issue with blinking list on infinite scroll data reload

package com.androidmess.helix.discover.view

import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import com.androidmess.helix.R
import com.androidmess.helix.common.ui.recyclerview.RecyclerViewItemSizeCalculator
import com.androidmess.helix.common.ui.view.inflate
import com.androidmess.helix.databinding.DiscoverListItemBinding
import com.androidmess.helix.discover.model.data.DiscoverMovieViewModel

class DiscoverAdapter(private val itemSizeCalculator: RecyclerViewItemSizeCalculator)
    : RecyclerView.Adapter<DiscoverAdapter.ViewHolder>() {

    private val data: MutableList<DiscoverMovieViewModel> = ArrayList()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = parent.inflate(R.layout.discover_list_item, false)
        val viewParams = view.layoutParams
        viewParams.width = itemSizeCalculator.itemWidth
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(data[position])

    override fun getItemCount(): Int = data.size

    fun addData(movies: List<DiscoverMovieViewModel>) {
        data.addAll(movies)
        notifyItemRangeInserted(data.size - 1, movies.size)
    }

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {

        private var binding: DiscoverListItemBinding = DiscoverListItemBinding.bind(view)

        fun bind(movieModel: DiscoverMovieViewModel) {
            binding.movie = movieModel
        }
    }
}


package org.purescript

import com.intellij.lang.Language

class PSLanguage : Language("Purescript", "text/purescript", "text/x-purescript", "application/x-purescript") {
    companion object {
        val INSTANCE = PSLanguage()

        /**
         * These modules are built into the purescript compiler,
         * and have no corresponding source files.
         *
         * See [https://pursuit.purescript.org/builtins/docs/Prim] for details.
         */
        val BUILTIN_MODULES = setOf(
            "Prim",
            "Prim.Boolean",
            "Prim.Coerce",
            "Prim.Ordering",
            "Prim.Row",
            "Prim.RowList",
            "Prim.Symbol",
            "Prim.TypeError",
        )

        /**
         * These types are built into the purescript compiles,
         * and are always available.
         *
         * See [https://pursuit.purescript.org/builtins/docs/Prim] for details.
         */
        val BUILTIN_TYPES = setOf(
            "Int",
            "Number",
            "String",
            "Char",
            "Boolean",
            "Array",
            "Type", // TODO Type is really a kind, not a type
            "Row", // TODO Row is really a kind, not a type
        )
    }
}

Add all declarations from Prim to BUILTIN_TYPES

package org.purescript

import com.intellij.lang.Language

class PSLanguage : Language("Purescript", "text/purescript", "text/x-purescript", "application/x-purescript") {
    companion object {
        val INSTANCE = PSLanguage()

        /**
         * These modules are built into the purescript compiler,
         * and have no corresponding source files.
         *
         * See [https://pursuit.purescript.org/builtins/docs/Prim] for details.
         */
        val BUILTIN_MODULES = setOf(
            "Prim",
            "Prim.Boolean",
            "Prim.Coerce",
            "Prim.Ordering",
            "Prim.Row",
            "Prim.RowList",
            "Prim.Symbol",
            "Prim.TypeError",
        )

        /**
         * These types are built into the purescript compiles,
         * and are always available.
         *
         * See [https://pursuit.purescript.org/builtins/docs/Prim] for details.
         */
        val BUILTIN_TYPES = setOf(
            "Function", // TODO Function is really a kind, not a type
            "Record", // TODO Record is really a kind, not a type
            "Partial", // TODO Partial is really a Class, not a type
            "Constraint", // TODO Constraint is really a kind, not a type
            "Symbol",
            "Int",
            "Number",
            "String",
            "Char",
            "Boolean",
            "Array",
            "Type", // TODO Type is really a kind, not a type
            "Row", // TODO Row is really a kind, not a type
        )
    }
}


package pl.mg6.likeornot

import android.content.Context
import io.reactivex.Single
import java.io.File

typealias LikableToStatus = Map<String, Status>

fun callLocalLikes(context: Context): Single<LikableToStatus> {
    val likesFile = File(context.filesDir, "likes")
    return if (likesFile.exists()) {
        Single.fromCallable { likesFile.readLines() }
                .map(::toUuidToStatusMap)
    } else {
        Single.just(emptyMap())
    }
}

private fun toUuidToStatusMap(lines: List<String>) = lines.associateBy(::extractUuid, ::extractStatus)

private fun extractUuid(line: String) = line.substringBefore(' ')

private fun extractStatus(line: String) = Status.valueOf(line.substringAfter(' '))

Handle all errors when getting likes from local storage.

package pl.mg6.likeornot

import android.content.Context
import io.reactivex.Single
import java.io.File

typealias LikableToStatus = Map<String, Status>

fun callLocalLikes(context: Context): Single<LikableToStatus> {
    val likesFile = File(context.filesDir, "likes")
    return Single.fromCallable { likesFile.readLines() }
            .map(::toUuidToStatusMap)
            .onErrorReturnItem(emptyMap())
}

private fun toUuidToStatusMap(lines: List<String>) = lines.associateBy(::extractUuid, ::extractStatus)

private fun extractUuid(line: String) = line.substringBefore(' ')

private fun extractStatus(line: String) = Status.valueOf(line.substringAfter(' '))


package org.wordpress.aztec.spans

import android.content.Context
import android.graphics.drawable.Drawable

class AztecCommentSpan(context: Context, drawable: Drawable, override var nestingLevel: Int) :
        AztecDynamicImageSpan(context, drawable), AztecFullWidthImageSpan {
    companion object {
        private val HTML_MORE: String = "more"
        private val HTML_PAGE: String = "nextpage"
    }

    enum class Comment constructor(val html: String) {
        MORE(HTML_MORE),
        PAGE(HTML_PAGE)
    }
}

Fix comment drawable bounds when adding it from toolbar

package org.wordpress.aztec.spans

import android.content.Context
import android.graphics.drawable.Drawable
import org.wordpress.aztec.AztecText

class AztecCommentSpan @JvmOverloads constructor(context: Context, drawable: Drawable, override var nestingLevel: Int, editor: AztecText? = null) :
        AztecDynamicImageSpan(context, drawable), AztecFullWidthImageSpan {

    init {
        textView = editor
    }

    companion object {
        private val HTML_MORE: String = "more"
        private val HTML_PAGE: String = "nextpage"
    }

    enum class Comment constructor(val html: String) {
        MORE(HTML_MORE),
        PAGE(HTML_PAGE)
    }
}


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

import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.mozilla.experiments.nimbus.internal.NimbusException

class NimbusSetupTest {
    @Test
    fun `WHEN error is reportable THEN return true`() {
        val error = NimbusException.IOException("IOException")

        assertTrue(error.isReportableError())
    }

    @Test
    fun `WHEN error is non-reportable THEN return false`() {
        val error1 = NimbusException.ResponseException("ResponseException")
        val error2 = NimbusException.RequestException("RequestException")

        assertFalse(error1.isReportableError())
        assertFalse(error2.isReportableError())
    }
}

Fix naming of generated exception

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

import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.mozilla.experiments.nimbus.internal.NimbusException

class NimbusSetupTest {
    @Test
    fun `WHEN error is reportable THEN return true`() {
        val error = NimbusException.IoException("IOException")

        assertTrue(error.isReportableError())
    }

    @Test
    fun `WHEN error is non-reportable THEN return false`() {
        val error1 = NimbusException.ResponseException("ResponseException")
        val error2 = NimbusException.RequestException("RequestException")

        assertFalse(error1.isReportableError())
        assertFalse(error2.isReportableError())
    }
}


package com.vimeo.networking2

import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.annotations.Internal

/**
 * Live chat configuration data.
 */
@Internal
@JsonClass(generateAdapter = true)
data class LiveChatConfiguration(

    /**
     * The live chat Firebase API key.
     */
    @Internal
    @Json(name = "api_key")
    val apiKey: String? = null,

    /**
     * The live chat Firebase app ID.
     */
    @Internal
    @Json(name = "api_id")
    val appId: String? = null,

    /**
     * The live chat Firebase authentication domain.
     */
    @Internal
    @Json(name = "auth_domain")
    val authDomain: String? = null,

    /**
     * The live chat Firebase database URL.
     */
    @Internal
    @Json(name = "database_url")
    val databaseUrl: String? = null,

    /**
     * The live chat Firebase messaging sender ID.
     */
    @Internal
    @Json(name = "messaging_sender_id")
    val messagingSenderId: String? = null,

    /**
     * The live chat Firebase project ID.
     */
    @Internal
    @Json(name = "project_id")
    val projectId: String? = null,

    /**
     * The live chat Firebase storage bucket.
     */
    @Internal
    @Json(name = "storage_bucket")
    val storageBucket: String? = null

)

Fix app id field name in live chat configuration

package com.vimeo.networking2

import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.annotations.Internal

/**
 * Live chat configuration data.
 */
@Internal
@JsonClass(generateAdapter = true)
data class LiveChatConfiguration(

    /**
     * The live chat Firebase API key.
     */
    @Internal
    @Json(name = "api_key")
    val apiKey: String? = null,

    /**
     * The live chat Firebase app ID.
     */
    @Internal
    @Json(name = "app_id")
    val appId: String? = null,

    /**
     * The live chat Firebase authentication domain.
     */
    @Internal
    @Json(name = "auth_domain")
    val authDomain: String? = null,

    /**
     * The live chat Firebase database URL.
     */
    @Internal
    @Json(name = "database_url")
    val databaseUrl: String? = null,

    /**
     * The live chat Firebase messaging sender ID.
     */
    @Internal
    @Json(name = "messaging_sender_id")
    val messagingSenderId: String? = null,

    /**
     * The live chat Firebase project ID.
     */
    @Internal
    @Json(name = "project_id")
    val projectId: String? = null,

    /**
     * The live chat Firebase storage bucket.
     */
    @Internal
    @Json(name = "storage_bucket")
    val storageBucket: String? = null

)


package info.nightscout.androidaps.queue.commands

import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin
import info.nightscout.androidaps.plugins.pump.omnipod.OmnipodPumpPlugin
import info.nightscout.androidaps.queue.Callback
import javax.inject.Inject

class CommandStartPump(
    injector: HasAndroidInjector,
    callback: Callback?
) : Command(injector, CommandType.START_PUMP, callback) {

    @Inject lateinit var activePlugin: ActivePluginProvider
    @Inject lateinit var profileFunction: ProfileFunction

    override fun execute() {
        val pump = activePlugin.activePump
        if (pump is LocalInsightPlugin) {
            val result = pump.startPump()
            callback?.result(result)?.run()
        } else if (pump is OmnipodPumpPlugin) {
            // When using CommandQueue.setProfile, it refuses to set the profile is the same as the current profile
            // However we need to set the current profile to resume delivery in case the Pod is suspended
            if (profileFunction.getProfile() != null) {
                pump.setNewBasalProfile(profileFunction.getProfile())
            }
        }
    }

    override fun status(): String = "START PUMP"
}

Remove unresolved Omnipod import after merge

package info.nightscout.androidaps.queue.commands

import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin
import info.nightscout.androidaps.queue.Callback
import javax.inject.Inject

class CommandStartPump(
    injector: HasAndroidInjector,
    callback: Callback?
) : Command(injector, CommandType.START_PUMP, callback) {

    @Inject lateinit var activePlugin: ActivePluginProvider
    @Inject lateinit var profileFunction: ProfileFunction

    override fun execute() {
        val pump = activePlugin.activePump
        if (pump is LocalInsightPlugin) {
            val result = pump.startPump()
            callback?.result(result)?.run()
        } else if (pump.pumpDescription.pumpType == PumpType.Insulet_Omnipod) {
            // When using CommandQueue.setProfile, it refuses to set the profile is the same as the current profile
            // However we need to set the current profile to resume delivery in case the Pod is suspended
            if (profileFunction.getProfile() != null) {
                pump.setNewBasalProfile(profileFunction.getProfile())
            }
        }
    }

    override fun status(): String = "START PUMP"
}


package mil.nga.giat.mage.form.field

import android.util.Patterns
import mil.nga.giat.mage.form.FormField

class EmailFieldState(definition: FormField<String>) :
  FieldState<String, FieldValue.Text>(
    definition,
    validator = ::isValid,
    errorFor = ::errorMessage,
    hasValue = ::hasValue
  )

private fun errorMessage(definition: FormField<String>, value: FieldValue.Text?): String {
  return if (value?.text.isNullOrBlank()) {
    "Please enter a value"
  } else {
    "Invalid email address"
  }
}

private fun isValid(definition: FormField<String>, value: FieldValue.Text?): Boolean {
  return if (!definition.required && !hasValue(value)) {
    true
  } else if (definition.required || value?.text?.isBlank() == true) {
    false
  } else value != null && Patterns.EMAIL_ADDRESS.matcher(value.text).matches()
}

private fun hasValue(value: FieldValue.Text?): Boolean {
  return value?.text?.isNotEmpty() == true
}

Fix validation on email field

package mil.nga.giat.mage.form.field

import android.util.Patterns
import mil.nga.giat.mage.form.FormField

class EmailFieldState(definition: FormField<String>) :
  FieldState<String, FieldValue.Text>(
    definition,
    validator = ::isValid,
    errorFor = ::errorMessage,
    hasValue = ::hasValue
  )

private fun errorMessage(definition: FormField<String>, value: FieldValue.Text?): String {
  return if (value?.text.isNullOrBlank()) {
    "Please enter a value"
  } else {
    "Invalid email address"
  }
}

private fun isValid(definition: FormField<String>, value: FieldValue.Text?): Boolean {
  return if (!definition.required && !hasValue(value)) {
    true
  } else if (definition.required && value?.text?.isBlank() == true) {
    false
  } else value != null && Patterns.EMAIL_ADDRESS.matcher(value.text).matches()
}

private fun hasValue(value: FieldValue.Text?): Boolean {
  return value?.text?.isNotEmpty() == true
}


package io.ktor.client

import io.ktor.client.engine.*
import java.util.*

/**
 * Constructs an asynchronous [HttpClient] using optional [block] for configuring this client.
 *
 * The [HttpClientEngine] is selected from the dependencies.
 * https://ktor.io/clients/http-client/engines.html
 */
actual fun HttpClient(
    block: HttpClientConfig<*>.() -> Unit
): HttpClient = HttpClient(FACTORY, block)

interface HttpClientEngineContainer {
    val factory: HttpClientEngineFactory<*>
}

/**
 * Workaround for dummy android [ClassLoader].
 */
private val engines: List<HttpClientEngineContainer> = HttpClientEngineContainer::class.java.let {
    ServiceLoader.load(it, it.classLoader).toList()
}

private val FACTORY = engines.firstOrNull()?.factory
    ?: error("Failed to find HttpClientEngineContainer in classpath via ServiceLoader")

Improve HTTP client engine container documentation

package io.ktor.client

import io.ktor.client.engine.*
import java.util.*

/**
 * Constructs an asynchronous [HttpClient] using optional [block] for configuring this client.
 *
 * The [HttpClientEngine] is selected from the dependencies using [ServiceLoader].
 * The first found implementation that provides [HttpClientEngineContainer] service implementation is used.
 * An exception is thrown if no implementations found.
 *
 * See https://ktor.io/clients/http-client/engines.html
 */
actual fun HttpClient(
    block: HttpClientConfig<*>.() -> Unit
): HttpClient = HttpClient(FACTORY, block)

/**
 * A container is searched across dependencies using [ServiceLoader] to find client implementations.
 * An implementation of this interface provides HTTP client [factory] and only used
 * to find the default client engine
 * when [HttpClient] function is called with no particular client implementation specified
 *
 * @property factory that produces HTTP client instances
 */
interface HttpClientEngineContainer {
    val factory: HttpClientEngineFactory<*>
}

/**
 * Workaround for dummy android [ClassLoader].
 */
private val engines: List<HttpClientEngineContainer> = HttpClientEngineContainer::class.java.let {
    ServiceLoader.load(it, it.classLoader).toList()
}

private val FACTORY = engines.firstOrNull()?.factory
    ?: error(
        "Failed to find HTTP client engine implementation in the classpath: consider adding client engine dependency. " +
            "See https://ktor.io/clients/http-client/engines.html"
    )


package com.emberjs.utils

import com.intellij.openapi.vfs.VirtualFile

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

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

fun Iterable<VirtualFile>.findAppFolder() =
        find { it.name == "app" && it.isDirectory }

Remove obsolete findAppFolder() extension method


package com.github.tslamic.dn

import android.content.Context
import android.content.SharedPreferences
import android.database.sqlite.SQLiteDatabase
import java.io.File
import java.io.InputStream
import java.io.OutputStream

class DatabaseImpl(val context: Context) : Database {
  val prefs: SharedPreferences = context.getSharedPreferences("__dn__", Context.MODE_PRIVATE)
  val database: File = context.getDatabasePath("dn.db")
  val version: Long = 2L

  override fun copyFromAssets() {
    val key = "version"
    if (!database.isValid() || version != prefs.getLong(key, 0)) {
      val src = context.assets.open("dn.db")
      copy(src, database.outputStream(), key, version)
    }
  }

  override fun instance(): SQLiteDatabase? {
    if (database.isValid()) {
      return SQLiteDatabase.openDatabase(database.absolutePath, null, SQLiteDatabase.OPEN_READONLY)
    }
    return null
  }

  private fun copy(src: InputStream, dst: OutputStream, key: String, version: Long) {
    src.use { s ->
      dst.use { d ->
        if (s.copyTo(d) > 0) {
          prefs.edit().putLong(key, version).apply()
        }
      }
    }
  }

  private fun File.isValid(): Boolean {
    return this.exists() && this.length() > 0
  }
}

Check and create db dir if necessary

package com.github.tslamic.dn

import android.content.Context
import android.content.SharedPreferences
import android.database.sqlite.SQLiteDatabase
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream

class DatabaseImpl(val context: Context) : Database {
  val prefs: SharedPreferences = context.getSharedPreferences("__dn__", Context.MODE_PRIVATE)
  val database: File = context.getDatabasePath("dn.db")
  val version: Long = 2L

  override fun copyFromAssets() {
    val key = "version"
    if (!database.isValid() || version != prefs.getLong(key, 0)) {
      if (!database.parentFile.exists() && !database.parentFile.mkdir()) {
        throw IOException("Couldn't create db dir")
      }
      val src = context.assets.open("dn.db")
      copy(src, database.outputStream(), key, version)
    }
  }

  override fun instance(): SQLiteDatabase? {
    if (database.isValid()) {
      return SQLiteDatabase.openDatabase(database.absolutePath, null, SQLiteDatabase.OPEN_READONLY)
    }
    return null
  }

  private fun copy(src: InputStream, dst: OutputStream, key: String, version: Long) {
    src.use { s ->
      dst.use { d ->
        if (s.copyTo(d) > 0) {
          prefs.edit().putLong(key, version).apply()
        }
      }
    }
  }

  private fun File.isValid(): Boolean {
    return this.exists() && this.length() > 0
  }
}


plugins {
  id("adventure.parent-build-logic")
}

group = "net.kyori"
version = "4.9.1"
description = "A user-interface library for Minecraft: Java Edition."

Prepare for further development on 4.10.0

plugins {
  id("adventure.parent-build-logic")
}

group = "net.kyori"
version = "4.10.0-SNAPSHOT"
description = "A user-interface library for Minecraft: Java Edition."


package com.s13g.aoc.aoc2020

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

/**
 * --- Day 1: Report Repair ---
 * https://adventofcode.com/2020/day/1
 */
class Day1 : Solver {
  override fun solve(lines: List<String>): Result {
    val (resultA, resultB) = run(lines.map { it.toLong() })
    return Result("$resultA", "$resultB")
  }

  private fun run(input: List<Long>): Array<Long> {
    val result = arrayOf(0L, 0L)
    for (i in input.indices) {
      for (j in i + 1 until input.size) {
        (result[0] == 0L).let { if (it) result[0] = test(listOf(input[i], input[j])) }
        for (k in j + 1 until input.size) {
          (result[1] == 0L).let { if (it) result[1] = test(listOf(input[i], input[j], input[k])) }
        }
      }
    }
    return result
  }

  private fun test(items: List<Long>) = if (items.sum() == 2020L) items.mul() else 0
}

Replace let if more normal if statement.

package com.s13g.aoc.aoc2020

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

/**
 * --- Day 1: Report Repair ---
 * https://adventofcode.com/2020/day/1
 */
class Day1 : Solver {
  override fun solve(lines: List<String>): Result {
    val (resultA, resultB) = run(lines.map { it.toLong() })
    return Result("$resultA", "$resultB")
  }

  private fun run(input: List<Long>): Array<Long> {
    val result = arrayOf(0L, 0L)
    for (i in input.indices) {
      for (j in i + 1 until input.size) {
        if (result[0] == 0L) result[0] = test(listOf(input[i], input[j]))
        for (k in j + 1 until input.size) {
          if (result[1] == 0L) result[1] = test(listOf(input[i], input[j], input[k]))
        }
      }
    }
    return result
  }

  private fun test(items: List<Long>) = if (items.sum() == 2020L) items.mul() else 0
}


Add unit tests for the ManageCarsActivity

package se.barsk.park

import android.support.design.widget.FloatingActionButton
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.TextView
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.robolectric.Robolectric
import se.barsk.park.datatypes.MockCarCollection
import se.barsk.park.managecars.ManageCarsActivity

class ManageCarsActivityTest : RobolectricTest() {
    private lateinit var activity: ManageCarsActivity

    @Before
    fun setUp() {
        activity = Robolectric.buildActivity(ManageCarsActivity::class.java).create().start().resume().visible().get()
    }

    @Test
    fun fabIsVisibleTest() {
        val fab = activity.findViewById<FloatingActionButton>(R.id.manage_cards_fab)
        assertEquals(View.VISIBLE, fab.visibility)
    }

    @Test
    fun carListShownWithCarsTest() {
        val manageCarsRecyclerView = activity.findViewById<RecyclerView>(R.id.manage_cars_recyclerview)
        val placeholderView = activity.findViewById<TextView>(R.id.manage_cars_placeholder)
        assertEquals(false, ParkApp.carCollection.getCars().isEmpty())
        assertEquals(View.VISIBLE, manageCarsRecyclerView.visibility)
        assertEquals(View.GONE, placeholderView.visibility)
    }

    @Test
    fun placeholderShownWithNoCarsTest() {
        ParkApp.carCollection = MockCarCollection(0)
        val activity = Robolectric.buildActivity(ManageCarsActivity::class.java).create().start().resume().visible().get()
        val manageCarsRecyclerView = activity.findViewById<RecyclerView>(R.id.manage_cars_recyclerview)
        val placeholderView = activity.findViewById<TextView>(R.id.manage_cars_placeholder)
        assertEquals(true, ParkApp.carCollection.getCars().isEmpty())
        assertEquals(View.GONE, manageCarsRecyclerView.visibility)
        assertEquals(View.VISIBLE, placeholderView.visibility)
    }

    @Test
    fun hideFabWhenClickingItTest() {
        val fab = activity.findViewById<FloatingActionButton>(R.id.manage_cards_fab)
        fab.performClick()
        assertEquals(View.GONE, fab.visibility)
    }
}


package com.pr0gramm.app

import android.content.Context
import android.support.multidex.MultiDex

class DebugApplicationClass : ApplicationClass() {
    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }
}

Enable StrictMode early on debug.

package com.pr0gramm.app

import android.content.Context
import android.os.StrictMode
import android.support.multidex.MultiDex

class DebugApplicationClass : ApplicationClass() {
    init {
        StrictMode.enableDefaults()
    }

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }
}


Add a new core class to deal with the Result forwarding

package org.firezenk.kartographer.library.core

class Results(val core: Core) {

    private lateinit var observer: (Any?) -> Unit

    fun <T> sendResult(requestCode: Int, data: T?) {
        core.current()?.let {
            if (it.forResult == requestCode) {
                observer(data)
            } else {
                core.log?.d("Current route: $it, is not subscribed for the request code: $requestCode")
            }
        } ?: core.log?.d("There is no route to send results")
    }

    fun subscribeForResult(resultCallback: (Any?) -> Unit) {
        observer = resultCallback
    }
}


package org.http4k.client

import org.http4k.server.Http4kServer
import org.http4k.server.ServerConfig
import org.http4k.server.asServer
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach

abstract class AbstractHttpClientContract(private val serverConfig: (Int) -> ServerConfig) {

    private lateinit var server: Http4kServer

    val port: Int
        get() = server.port()

    @BeforeEach
    fun before() {
        server = ServerForClientContract.asServer(serverConfig(0)).start()
    }

    protected fun testImageBytes() = this::class.java.getResourceAsStream("/test.png").readBytes()

    @AfterEach
    fun after() {
        server.stop()
    }
}

Debug client contract in IntelliJ only

package org.http4k.client

import org.http4k.core.Filter
import org.http4k.core.NoOp
import org.http4k.core.then
import org.http4k.filter.DebuggingFilters
import org.http4k.filter.inIntelliJOnly
import org.http4k.server.Http4kServer
import org.http4k.server.ServerConfig
import org.http4k.server.asServer
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach

abstract class AbstractHttpClientContract(private val serverConfig: (Int) -> ServerConfig) {

    private lateinit var server: Http4kServer

    val port: Int
        get() = server.port()

    @BeforeEach
    fun before() {
        server = Filter.NoOp
            .then(DebuggingFilters.PrintRequestAndResponse().inIntelliJOnly())
            .then(ServerForClientContract)
            .asServer(serverConfig(0)).start()
    }

    protected fun testImageBytes() = this::class.java.getResourceAsStream("/test.png").readBytes()

    @AfterEach
    fun after() {
        server.stop()
    }
}


/*
 * Copyright 2017 Nicholas Bilyk
 *
 * 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.acornui.core

import com.acornui.core.time.time
import com.acornui.string.toRadix
import kotlin.math.abs

object UidUtil {

	/**
	 * Returns a unique id.
	 */
	fun createUid(): String {
		return abs(time.nowMs().toInt()).toRadix(36) + (Math.random() * Int.MAX_VALUE).toInt().toRadix(36)
	}

}

Fix reference to JVM random code in common

/*
 * Copyright 2017 Nicholas Bilyk
 *
 * 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.acornui.core

import com.acornui.core.time.time
import com.acornui.string.toRadix
import kotlin.math.abs
import kotlin.random.Random

object UidUtil {

	/**
	 * Returns a unique id.
	 */
	fun createUid(): String {
		return abs(time.nowMs().toInt()).toRadix(36) + (Random.nextDouble() * Int.MAX_VALUE).toInt().toRadix(36)
	}

}


package net.squanchy.service.firebase.injection

import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.FirebaseFirestoreSettings
import dagger.Module
import dagger.Provides
import net.squanchy.injection.ApplicationLifecycle
import net.squanchy.service.firebase.FirebaseAuthService
import net.squanchy.service.firebase.FirestoreDbService
import net.squanchy.service.repository.AuthService

@Module
class FirestoreModule {

    @Provides
    internal fun firebaseAuth(): FirebaseAuth = FirebaseAuth.getInstance()

    @Provides
    internal fun firebaseFirestoreSettings(): FirebaseFirestoreSettings {
        return FirebaseFirestoreSettings.Builder()
            .setPersistenceEnabled(true)
            .setTimestampsInSnapshotsEnabled(true)
            .build()
    }

    @Provides
    internal fun firebaseFirestore(settings: FirebaseFirestoreSettings): FirebaseFirestore {
        val firebaseFirestore = FirebaseFirestore.getInstance()
        firebaseFirestore.firestoreSettings = settings
        return firebaseFirestore
    }

    @Provides
    @ApplicationLifecycle
    internal fun firestoreDbService(database: FirebaseFirestore): FirestoreDbService = FirestoreDbService(database)

    @ApplicationLifecycle
    @Provides
    internal fun firebaseAuthService(firebaseAuth: FirebaseAuth): AuthService = FirebaseAuthService(firebaseAuth)
}

Use remote config to allow disabling persistence

package net.squanchy.service.firebase.injection

import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.FirebaseFirestoreSettings
import dagger.Module
import dagger.Provides
import net.squanchy.injection.ApplicationLifecycle
import net.squanchy.remoteconfig.RemoteConfig
import net.squanchy.service.firebase.FirebaseAuthService
import net.squanchy.service.firebase.FirestoreDbService
import net.squanchy.service.repository.AuthService

@Module
class FirestoreModule {

    @Provides
    internal fun firebaseAuth(): FirebaseAuth = FirebaseAuth.getInstance()

    @Provides
    internal fun firebaseFirestoreSettings(remoteConfig: RemoteConfig): FirebaseFirestoreSettings {
        val persistenceEnabled = !remoteConfig.getBoolean(KEY_PERSISTENCE_DISABLED)

        return FirebaseFirestoreSettings.Builder()
            .setPersistenceEnabled(persistenceEnabled)
            .setTimestampsInSnapshotsEnabled(true)
            .build()
    }

    @Provides
    internal fun firebaseFirestore(settings: FirebaseFirestoreSettings): FirebaseFirestore {
        val firebaseFirestore = FirebaseFirestore.getInstance()
        firebaseFirestore.firestoreSettings = settings
        return firebaseFirestore
    }

    @Provides
    @ApplicationLifecycle
    internal fun firestoreDbService(database: FirebaseFirestore): FirestoreDbService = FirestoreDbService(database)

    @ApplicationLifecycle
    @Provides
    internal fun firebaseAuthService(firebaseAuth: FirebaseAuth): AuthService = FirebaseAuthService(firebaseAuth)
}

private const val KEY_PERSISTENCE_DISABLED = "firestore_persistence_disabled"


package org.gradle.gradlebuild

import org.gradle.api.JavaVersion
import org.gradle.internal.os.OperatingSystem

object BuildEnvironment {
    val isCiServer = "CI" in System.getenv()
    val gradleKotlinDslVersion = "1.0-rc-6"
    val jvm = org.gradle.internal.jvm.Jvm.current()
    val javaVersion = JavaVersion.current()
    val isWindows = OperatingSystem.current().isWindows
    val agentNum: Int
        get() {
            if (System.getenv().containsKey("USERNAME")) {
                val agentNumEnv = System.getenv("USERNAME").replaceFirst("tcagent", "")
                if (Regex("""\d+""").containsMatchIn(agentNumEnv)) {
                    return agentNumEnv.toInt()
                }
            }
            return 1
        }
}

Upgrade Kotlin DSL to 1.0-rc-7

package org.gradle.gradlebuild

import org.gradle.api.JavaVersion
import org.gradle.internal.os.OperatingSystem

object BuildEnvironment {
    val isCiServer = "CI" in System.getenv()
    val gradleKotlinDslVersion = "1.0-rc-7"
    val jvm = org.gradle.internal.jvm.Jvm.current()
    val javaVersion = JavaVersion.current()
    val isWindows = OperatingSystem.current().isWindows
    val agentNum: Int
        get() {
            if (System.getenv().containsKey("USERNAME")) {
                val agentNumEnv = System.getenv("USERNAME").replaceFirst("tcagent", "")
                if (Regex("""\d+""").containsMatchIn(agentNumEnv)) {
                    return agentNumEnv.toInt()
                }
            }
            return 1
        }
}


/**
 * Copyright 2019 Carl-Philipp Harmant
 *
 *
 * 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 fr.cph.chicago.core.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.RelativeLayout
import butterknife.BindView
import butterknife.ButterKnife
import fr.cph.chicago.R

/**
 * BusArrivalError activity that can be thrown from anywhere in the app
 *
 * @author Carl-Philipp Harmant
 * @version 1
 */
class ErrorActivity : Activity() {

    @BindView(R.id.retryButton)
    lateinit var button: Button
    @BindView(R.id.failureLayout)
    lateinit var failure: RelativeLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.error)
        ButterKnife.bind(this)

        failure.visibility = View.VISIBLE
        button.setOnClickListener {
            val intent = Intent(this@ErrorActivity, BaseActivity::class.java)
            finish()
            startActivity(intent)
        }
    }
}

Remove butterknife from error activity

/**
 * Copyright 2019 Carl-Philipp Harmant
 *
 *
 * 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 fr.cph.chicago.core.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import fr.cph.chicago.R
import kotlinx.android.synthetic.main.error.failureLayout
import kotlinx.android.synthetic.main.error.retryButton

/**
 * BusArrivalError activity that can be thrown from anywhere in the app
 *
 * @author Carl-Philipp Harmant
 * @version 1
 */
class ErrorActivity : Activity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.error)
        failureLayout.visibility = View.VISIBLE
        retryButton.setOnClickListener {
            val intent = Intent(this@ErrorActivity, BaseActivity::class.java)
            finish()
            startActivity(intent)
        }
    }
}


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

package Gradle_Promotion.buildTypes

import common.Os
import common.requiresOs
import jetbrains.buildServer.configs.kotlin.v2019_2.BuildType
import jetbrains.buildServer.configs.kotlin.v2019_2.CheckoutMode
import jetbrains.buildServer.configs.kotlin.v2019_2.vcs.GitVcsRoot

abstract class BasePromotionBuildType(vcsRoot: GitVcsRoot, cleanCheckout: Boolean = true) : BuildType() {
    init {
        vcs {
            root(vcsRoot)

            checkoutMode = CheckoutMode.ON_AGENT
            this.cleanCheckout = cleanCheckout
            showDependenciesChanges = true
        }

        requirements {
            requiresOs(Os.linux)
        }
    }
}

Add ge.gradle.org credentials to promotion jobs

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

package Gradle_Promotion.buildTypes

import common.Os
import common.requiresOs
import jetbrains.buildServer.configs.kotlin.v2019_2.BuildType
import jetbrains.buildServer.configs.kotlin.v2019_2.CheckoutMode
import jetbrains.buildServer.configs.kotlin.v2019_2.ParameterDisplay
import jetbrains.buildServer.configs.kotlin.v2019_2.vcs.GitVcsRoot

abstract class BasePromotionBuildType(vcsRoot: GitVcsRoot, cleanCheckout: Boolean = true) : BuildType() {
    init {
        vcs {
            root(vcsRoot)

            checkoutMode = CheckoutMode.ON_AGENT
            this.cleanCheckout = cleanCheckout
            showDependenciesChanges = true
        }

        requirements {
            requiresOs(Os.linux)
        }

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


package org.rust.ide.annotator

import com.intellij.testFramework.LightProjectDescriptor
import org.junit.experimental.categories.Category
import org.rust.Performance
import org.rust.lang.RustTestCaseBase

@Category(Performance::class)
class RustHighlightingPerformanceTest : RustTestCaseBase() {
    override val dataPath = "org/rust/ide/annotator/fixtures/performance"

    override fun getProjectDescriptor(): LightProjectDescriptor = WithStdlibRustProjectDescriptor()

    fun testHighlightingWithStdlib() {
        myFixture.copyDirectoryToProject("", "")

        myFixture.configureFromTempProjectFile("main.rs")

        val elapsed = myFixture.checkHighlighting()
        reportTeamCityMetric(name, elapsed)
    }

}

Reset `RustImplIndex` on every test run

package org.rust.ide.annotator

import com.intellij.psi.stubs.StubUpdatingIndex
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.util.indexing.FileBasedIndex
import org.junit.experimental.categories.Category
import org.rust.Performance
import org.rust.lang.RustTestCaseBase

@Category(Performance::class)
class RustHighlightingPerformanceTest : RustTestCaseBase() {
    override val dataPath = "org/rust/ide/annotator/fixtures/performance"

    override fun setUp() {
        super.setUp()

        FileBasedIndex.getInstance().requestRebuild(StubUpdatingIndex.INDEX_ID)
    }

    override fun getProjectDescriptor(): LightProjectDescriptor = WithStdlibRustProjectDescriptor()

    fun testHighlightingWithStdlib() {
        myFixture.copyDirectoryToProject("", "")

        myFixture.configureFromTempProjectFile("main.rs")

        val elapsed = myFixture.checkHighlighting()
        reportTeamCityMetric(name, elapsed)
    }

}


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

package org.wfanet.measurement.common.testing

import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement

/**
 * [TestRule] that ensures that the given [AutoCloseable] resource is closed after statement
 * evaluation.
 *
 * This can replace [ExternalResource][org.junit.rules.ExternalResource], which does not guarantee
 * that [after][org.junit.rules.ExternalResource.after] is invoked if
 * [before][org.junit.rules.ExternalResource.before] throws an exception.
 */
open class CloseableResource<T : AutoCloseable>(lazyResource: () -> T) : TestRule {
  protected val resource by lazy { lazyResource() }

  override fun apply(base: Statement, description: Description) = object : Statement() {
    override fun evaluate() {
      try {
        resource.use {
          before()
          base.evaluate()
        }
      } finally {
        after()
      }
    }
  }

  open fun before() {}

  open fun after() {}
}

Initialize properties on construction in Spanner testing AutoCloseables.

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

package org.wfanet.measurement.common.testing

import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement

/**
 * [TestRule] that ensures that the given [AutoCloseable] resource is closed after statement
 * evaluation.
 *
 * This can replace [ExternalResource][org.junit.rules.ExternalResource], which does not guarantee
 * that [after][org.junit.rules.ExternalResource.after] is invoked if
 * [before][org.junit.rules.ExternalResource.before] throws an exception.
 */
open class CloseableResource<T : AutoCloseable>(private val createResource: () -> T) : TestRule {
  protected lateinit var resource: T
    private set

  override fun apply(base: Statement, description: Description) = object : Statement() {
    override fun evaluate() {
      check(!::resource.isInitialized)

      resource = createResource()
      resource.use { base.evaluate() }
    }
  }
}


package com.beust.kobalt.app

import com.beust.kobalt.Args
import com.beust.kobalt.internal.ActorUtils
import com.beust.kobalt.internal.PluginInfo
import com.beust.kobalt.misc.log
import com.google.inject.Inject
import java.io.File
import java.io.FileOutputStream

/**
 * Invoked with --init. Generate a new project.
 */
public class ProjectGenerator @Inject constructor(val pluginInfo: PluginInfo){
    companion object {
        /**
         * Turns a dot property into a proper Kotlin identifier, e.g. common.version -> commonVersion
         */
        fun toIdentifier(key: String): String {
            fun upperFirst(s: String) = if (s.isBlank()) s else s.substring(0, 1).toUpperCase() + s.substring(1)

            return key.split('.').mapIndexed( { index, value -> if (index == 0) value else upperFirst(value) })
                    .joinToString("")
        }
    }

    fun run(args: Args) {
        val contributor = ActorUtils.selectAffinityActor(pluginInfo.initContributors, File("."))
        if (contributor != null) {
            contributor.generateBuildFile(FileOutputStream(File(args.buildFile)))
            log(1, "Created ${args.buildFile}")
        } else {
            log(1, "Couldn't identify project, not generating any build file")
        }
    }
}

Create the directory for --init.

package com.beust.kobalt.app

import com.beust.kobalt.Args
import com.beust.kobalt.internal.ActorUtils
import com.beust.kobalt.internal.PluginInfo
import com.beust.kobalt.misc.log
import com.google.inject.Inject
import java.io.File
import java.io.FileOutputStream

/**
 * Invoked with --init. Generate a new project.
 */
public class ProjectGenerator @Inject constructor(val pluginInfo: PluginInfo){
    companion object {
        /**
         * Turns a dot property into a proper Kotlin identifier, e.g. common.version -> commonVersion
         */
        fun toIdentifier(key: String): String {
            fun upperFirst(s: String) = if (s.isBlank()) s else s.substring(0, 1).toUpperCase() + s.substring(1)

            return key.split('.').mapIndexed( { index, value -> if (index == 0) value else upperFirst(value) })
                    .joinToString("")
        }
    }

    fun run(args: Args) {
        val contributor = ActorUtils.selectAffinityActor(pluginInfo.initContributors, File("."))
        File(args.buildFile).parentFile.mkdirs()
        if (contributor != null) {
            contributor.generateBuildFile(FileOutputStream(File(args.buildFile)))
            log(1, "Created ${args.buildFile}")
        } else {
            log(1, "Couldn't identify project, not generating any build file")
        }
    }
}


import java.io.File

println("Let's migrate this Android project from support libraries to AndroidX.")
val dir = File(".")
val androidXClassMappingCsvFile = File(dir, "androidx-class-mapping.csv")
val expectedNumberOfModules = 43
val ignoredRootDirNames = listOf("build", "buildSrc", "gradle", "projectFilesBackup")

val moduleDirectories: List<File> = dir.listFiles { file: File ->
    file.isDirectory &&
            !file.name.startsWith('.') &&
            file.name !in ignoredRootDirNames &&
            file.listFiles { it: File -> it.isDirectory && it.name == "src" }.size == 1
}!!.sortedBy { it.name }
check(moduleDirectories.size == expectedNumberOfModules)

val supportedExtensions = listOf("kt", "java", "xml")
fun File.findSourceFiles(): List<File> = listFiles { file: File ->
    file.extension in supportedExtensions
}.asList() + listFiles { file: File ->
    file.isDirectory
}.flatMap { it.findSourceFiles() }

val srcDirectories = moduleDirectories.map { File(it, "src") }
val sourceFiles = srcDirectories.flatMap { it.findSourceFiles() }
println("There's ${sourceFiles.size} source files that may need migration")
val supportLibsToAndroidXMappings = androidXClassMappingCsvFile.readLines().drop(1).map { line ->
    val (supportLibClassName, androidXClassName) = line.split(",").also { check(it.size == 2) }
    check(supportLibClassName.isLegalClassName()) { "Illegal entry in csv: $supportLibClassName" }
    check(androidXClassName.isLegalClassName()) { "Illegal entry in csv: $androidXClassName" }
    supportLibClassName to androidXClassName
}
println("CSV file ok.")

fun String.simpleNameFromFullyQualified(): String = substring(indexOfFirst { it.isUpperCase() })
fun String.packageNameFromClassName(): String = substring(0, indexOfFirst { it.isUpperCase() })
fun String.isLegalClassName() = first().isJavaIdentifierStart() && all {
    it.isJavaIdentifierPart() || it == '.'
}

fun File.migrateToAndroidX() {
    check(extension in supportedExtensions)
    val sourceCode = readText()
    var editedSourceCode = sourceCode
    print("Migrating file named \"$name\" with full name: \"$absolutePath\"… ")
    supportLibsToAndroidXMappings.forEach { (supportLibClassName, androidXClassName) ->
        editedSourceCode = editedSourceCode.replace(supportLibClassName, androidXClassName)
    }
    print("Overwriting file… ")
    writeText(editedSourceCode)
    println("Done. ✅")
}

println("Starting batch migration")
sourceFiles.forEach {
    it.migrateToAndroidX()
}
println("AndroidX migration complete!")
println("You now just need to update the dependencies, if not already done.")


package com.github.inikolaev.vertx.web.kotlin

import io.vertx.core.http.HttpServerResponse
import io.vertx.core.json.JsonArray
import io.vertx.core.json.JsonObject

fun HttpServerResponse.endJson(json: JsonObject) = this.end(json.encode())
fun HttpServerResponse.endJson(json: JsonArray) = this.end(json.encode())

Make endJson to encode any object to JSON

package com.github.inikolaev.vertx.web.kotlin

import io.vertx.core.http.HttpServerResponse
import io.vertx.core.json.Json
import io.vertx.core.json.JsonArray
import io.vertx.core.json.JsonObject

fun HttpServerResponse.endJson(json: JsonObject) = this.end(json.encode())
fun HttpServerResponse.endJson(json: JsonArray) = this.end(json.encode())
fun HttpServerResponse.endJson(entity: Any) = this.end(Json.encode(entity))


package circlet.auth

import circlet.platform.api.oauth.*
import circlet.platform.workspaces.*
import io.ktor.application.*
import io.ktor.request.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.server.engine.*
import io.ktor.server.jetty.*
import libraries.coroutines.extra.*
import libraries.klogging.*
import runtime.utils.*
import java.awt.*
import java.net.*
import java.util.concurrent.*
import kotlin.coroutines.*

val log = KLoggers.logger()

suspend fun accessTokenInteractive(lifetime: Lifetime, config: WorkspaceConfiguration): OAuthTokenResponse {

    val port = selectFreePort()
    val codeFlow = CodeFlowConfig(config, "http://localhost:$port/auth")

    return suspendCancellableCoroutine { cnt ->

        val server = try {
            embeddedServer(Jetty, port, "localhost") {
                routing {
                    get("auth") {
                        val token = codeFlow.handleCodeFlowRedirect(call.request.uri)
                        call.respondText("<script>close()</script>", io.ktor.http.ContentType("text", "html"))
                        cnt.resume(token)
                    }
                }
            }.start(wait = false)
        }
        catch (th: Throwable) {
            log.error(th, "Can't start server at: ${codeFlow.redirectUri}")
            throw th
        }

        lifetime.add {
            server.stop(100, 5000, TimeUnit.MILLISECONDS)
        }

        val uri = URI(codeFlow.codeFlowURL())
        Desktop.getDesktop().browse(uri)
    }
}

Revert "replace suspendCoroutine with suspendCancellableCoroutine"

package circlet.auth

import circlet.platform.api.oauth.*
import circlet.platform.workspaces.*
import io.ktor.application.*
import io.ktor.request.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.server.engine.*
import io.ktor.server.jetty.*
import libraries.coroutines.extra.*
import libraries.klogging.*
import runtime.utils.*
import java.awt.*
import java.net.*
import java.util.concurrent.*
import kotlin.coroutines.*

val log = KLoggers.logger()

suspend fun accessTokenInteractive(lifetime: Lifetime, config: WorkspaceConfiguration): OAuthTokenResponse {

    val port = selectFreePort()
    val codeFlow = CodeFlowConfig(config, "http://localhost:$port/auth")

    return suspendCoroutine { cnt ->

        val server = try {
            embeddedServer(Jetty, port, "localhost") {
                routing {
                    get("auth") {
                        val token = codeFlow.handleCodeFlowRedirect(call.request.uri)
                        call.respondText("<script>close()</script>", io.ktor.http.ContentType("text", "html"))
                        cnt.resume(token)
                    }
                }
            }.start(wait = false)
        }
        catch (th: Throwable) {
            log.error(th, "Can't start server at: ${codeFlow.redirectUri}")
            throw th
        }

        lifetime.add {
            server.stop(100, 5000, TimeUnit.MILLISECONDS)
        }

        val uri = URI(codeFlow.codeFlowURL())
        Desktop.getDesktop().browse(uri)
    }
}


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

package androidx.ui.res

import android.os.Build
import androidx.annotation.ColorRes
import androidx.compose.Composable
import androidx.ui.core.ContextAmbient
import androidx.ui.graphics.Color

/**
 * Load a string resource.
 *
 * @param id the resource identifier
 * @return the color associated with the resource
 */
@Composable
fun colorResource(@ColorRes id: Int): Color {
    val context = ContextAmbient.current
    return if (Build.VERSION.SDK_INT >= 23) {
        Color(context.resources.getColor(id, context.theme))
    } else {
        @Suppress("DEPRECATION")
        Color(context.resources.getColor(id))
    }
}

Fix documentation error in ColorResource

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

package androidx.ui.res

import android.os.Build
import androidx.annotation.ColorRes
import androidx.compose.Composable
import androidx.ui.core.ContextAmbient
import androidx.ui.graphics.Color

/**
 * Load a color resource.
 *
 * @param id the resource identifier
 * @return the color associated with the resource
 */
@Composable
fun colorResource(@ColorRes id: Int): Color {
    val context = ContextAmbient.current
    return if (Build.VERSION.SDK_INT >= 23) {
        Color(context.resources.getColor(id, context.theme))
    } else {
        @Suppress("DEPRECATION")
        Color(context.resources.getColor(id))
    }
}


package org.team2471.frc.lib.util

import edu.wpi.first.wpilibj.Timer

/**
 * Executes the given block and returns elapsed time in seconds.
 */
fun measureTimeFPGA(body: () -> Unit): Double {
    val start = Timer.getFPGATimestamp()
    body()
    return Timer.getFPGATimestamp() - start
}

fun Double.deadband(tolerance: Double) = if(Math.abs(this) < tolerance) {
    0.0
} else {
    this * (1+tolerance) - tolerance // scale
}

Update meanlib to fix deadband scaling

package org.team2471.frc.lib.util

import edu.wpi.first.wpilibj.Timer

/**
 * Executes the given block and returns elapsed time in seconds.
 */
fun measureTimeFPGA(body: () -> Unit): Double {
    val start = Timer.getFPGATimestamp()
    body()
    return Timer.getFPGATimestamp() - start
}

fun Double.deadband(tolerance: Double) = if(Math.abs(this) < tolerance) {
    0.0
} else {
    this
}


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

package app.tivi.ui.widget

import android.content.Context
import android.support.v7.widget.Toolbar
import android.util.AttributeSet
import app.tivi.R
import app.tivi.extensions.resolveColor

class TintingToolbar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = R.attr.toolbarStyle
) : Toolbar(context, attrs, defStyleAttr) {

    var iconTint: Int = context.theme.resolveColor(android.R.attr.colorControlNormal)
        set(value) {
            navigationIcon = navigationIcon?.let {
                it.setTint(value)
                it.mutate()
            }
            overflowIcon = overflowIcon?.let {
                it.setTint(value)
                it.mutate()
            }
        }
}

Fix Toolbar tinting animation on release build

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

package app.tivi.ui.widget

import android.content.Context
import android.support.annotation.Keep
import android.support.v7.widget.Toolbar
import android.util.AttributeSet
import app.tivi.R
import app.tivi.extensions.resolveColor

class TintingToolbar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = R.attr.toolbarStyle
) : Toolbar(context, attrs, defStyleAttr) {
    @get:Keep
    @set:Keep
    var iconTint: Int = context.theme.resolveColor(android.R.attr.colorControlNormal)
        set(value) {
            if (value != field) {
                navigationIcon = navigationIcon?.let {
                    it.setTint(value)
                    it.mutate()
                }
                overflowIcon = overflowIcon?.let {
                    it.setTint(value)
                    it.mutate()
                }
            }
            field = value
        }
}


/*
 * Copyright 2019 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.
 */

plugins {
    application
}

extra["pomName"] = "Prefab"
extra["pomDescription"] = "The main Prefab program."

dependencies {
    implementation("com.github.ajalt:clikt:2.2.0")
    testImplementation("io.mockk:mockk:1.9.3")

    implementation(project(":api"))
    implementation(project(":cmake-plugin"))
    implementation(project(":ndk-build-plugin"))
}

application {
    // Define the main class for the application.
    mainClassName = "com.google.prefab.cli.AppKt"
}

tasks.withType<Jar> {
    manifest {
        attributes["Main-Class"] = application.mainClassName
    }
}

Make the CLI a fat jar.

/*
 * Copyright 2019 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.
 */

plugins {
    application
}

extra["pomName"] = "Prefab"
extra["pomDescription"] = "The main Prefab program."

dependencies {
    implementation("com.github.ajalt:clikt:2.2.0")
    testImplementation("io.mockk:mockk:1.9.3")

    implementation(project(":api"))
    implementation(project(":cmake-plugin"))
    implementation(project(":ndk-build-plugin"))
}

application {
    // Define the main class for the application.
    mainClassName = "com.google.prefab.cli.AppKt"
}

tasks.withType<Jar> {
    manifest {
        attributes["Main-Class"] = application.mainClassName
    }

    from(configurations.runtimeClasspath.get().map {
        if (it.isDirectory) it else zipTree(
            it
        )
    })
}