package pl.mg6.likeornot.commons

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

Set initial list capacity to expected final size.

package pl.mg6.likeornot.commons

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


package backend.configuration

import backend.model.user.User
import org.springframework.security.core.userdetails.UserDetails

class CustomUserDetails(val user: User) : UserDetails {

    val id = user.core.id

    override fun getUsername() = user.email

    override fun isCredentialsNonExpired() = true

    override fun isAccountNonExpired() = true

    override fun isAccountNonLocked() = true

    override fun getAuthorities() = user.core.getAuthorities()

    override fun isEnabled() = !user.isBlocked

    override fun getPassword(): String? = user.passwordHash
}

Set customUserDetails.isEnabled() to true per default

package backend.configuration

import backend.model.user.User
import org.springframework.security.core.userdetails.UserDetails

class CustomUserDetails(val user: User) : UserDetails {

    val id = user.core.id

    override fun getUsername() = user.email

    override fun isCredentialsNonExpired() = true

    override fun isAccountNonExpired() = true

    override fun isAccountNonLocked() = true

    override fun getAuthorities() = user.core.getAuthorities()

    override fun isEnabled() = true

    override fun getPassword(): String? = user.passwordHash
}


/*
 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

// This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit.
package kotlinx.coroutines.experimental.guide.basic05s

import kotlinx.coroutines.experimental.*

fun main(args: Array<String>) = runBlocking<Unit> {
    launchDoWorld()
    println("Hello,")
}

// this is your first suspending function
suspend fun launchDoWorld() = currentScope {
        launch {
        println("World!")
    }
}

Fix bad code sample style


package com.satsumasoftware.timetable

import android.content.Context
import android.preference.PreferenceManager
import com.satsumasoftware.timetable.db.util.TimetableUtils
import com.satsumasoftware.timetable.framework.Timetable

class PrefUtils {

    companion object {

        const val PREF_CURRENT_TIMETABLE = "pref_current_timetable"

        @JvmStatic fun getCurrentTimetable(context: Context): Timetable? {
            val sp = PreferenceManager.getDefaultSharedPreferences(context)
            val timetableId = sp.getInt(PREF_CURRENT_TIMETABLE, -1)
            return if (timetableId == -1) {
                null
            } else {
                TimetableUtils.getTimetableWithId(context, timetableId)
            }
        }

        @JvmStatic fun setCurrentTimetable(context: Context, timetable: Timetable) {
            val sp = PreferenceManager.getDefaultSharedPreferences(context)
            sp.edit().putInt(PREF_CURRENT_TIMETABLE, timetable.id).apply()
        }

    }
}

Add functions to read/put values for pref_display_weeks_as_letters

package com.satsumasoftware.timetable

import android.content.Context
import android.preference.PreferenceManager
import com.satsumasoftware.timetable.db.util.TimetableUtils
import com.satsumasoftware.timetable.framework.Timetable

class PrefUtils {

    companion object {

        const val PREF_CURRENT_TIMETABLE = "pref_current_timetable"

        @JvmStatic fun getCurrentTimetable(context: Context): Timetable? {
            val sp = PreferenceManager.getDefaultSharedPreferences(context)
            val timetableId = sp.getInt(PREF_CURRENT_TIMETABLE, -1)
            return if (timetableId == -1) {
                null
            } else {
                TimetableUtils.getTimetableWithId(context, timetableId)
            }
        }

        @JvmStatic fun setCurrentTimetable(context: Context, timetable: Timetable) {
            val sp = PreferenceManager.getDefaultSharedPreferences(context)
            sp.edit().putInt(PREF_CURRENT_TIMETABLE, timetable.id).apply()
        }

        const val PREF_DISPLAY_WEEKS_AS_LETTERS = "pref_display_weeks_as_letters"

        @JvmStatic fun displayWeeksAsLetters(context: Context): Boolean {
            val sp = PreferenceManager.getDefaultSharedPreferences(context)
            return sp.getBoolean(PREF_DISPLAY_WEEKS_AS_LETTERS, false)
        }

        @JvmStatic fun setDisplayWeeksAsLetters(context: Context, boolean: Boolean) {
            val sp = PreferenceManager.getDefaultSharedPreferences(context)
            sp.edit().putBoolean(PREF_DISPLAY_WEEKS_AS_LETTERS, boolean).apply()
        }

    }
}


/*
 * Copyright 2020 Peter Kenji Yamanaka
 *
 * 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.pyamsoft.pydroid.arch

import androidx.annotation.CheckResult

/**
 * The UiController drives the events. It orchestrates events between the UiView and UiViewModel
 */
public interface UiController<C : UiControllerEvent> {

    /**
     * Respond to a published UiControllerEvent
     */
    public fun onControllerEvent(event: C)
}

/**
 * Create a new anonymous UiController
 *
 * For when a single Android component serves as multiple UiControllers
 */
@CheckResult
public inline fun <C : UiControllerEvent> newUiController(crossinline onEvent: (C) -> Unit): UiController<C> {
    return object : UiController<C> {
        override fun onControllerEvent(event: C) {
            return onEvent(event)
        }
    }
}

Use a singleton for empty controllers

/*
 * Copyright 2020 Peter Kenji Yamanaka
 *
 * 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.pyamsoft.pydroid.arch

import androidx.annotation.CheckResult

/**
 * The UiController drives the events. It orchestrates events between the UiView and UiViewModel
 */
public interface UiController<C : UiControllerEvent> {

    /**
     * Respond to a published UiControllerEvent
     */
    public fun onControllerEvent(event: C)
}

/**
 * Create a new anonymous UiController
 *
 * For when a single Android component serves as multiple UiControllers
 */
@CheckResult
public inline fun <C : UiControllerEvent> newUiController(crossinline onEvent: (C) -> Unit): UiController<C> {
    return object : UiController<C> {
        override fun onControllerEvent(event: C) {
            return onEvent(event)
        }
    }
}

private object UiControllers {

    /**
     * An empty Ui Controller singleton
     */
    val EMPTY = newUiController<UnitControllerEvent> { }

}

/**
 * Returns the no-op Empty Controller
 */
@CheckResult
public fun emptyController(): UiController<UnitControllerEvent> {
    return UiControllers.EMPTY
}


package com.elpassion.android.view

import android.app.Application
import android.test.ApplicationTestCase
import android.view.View

class ViewTest : ApplicationTestCase<Application>(Application::class.java) {

    fun testShouldSetViewVisibilityToVisible() {
        val view = View(context)
        view.visibility = View.INVISIBLE
        view.show()
        assertEquals(View.VISIBLE, view.visibility)
    }

    fun testShouldSetViewVisibilityToGone() {
        val view = View(context)
        view.hide()
        assertEquals(View.GONE, view.visibility)
    }
}

Add tests for isVisible and enable/disable functions

package com.elpassion.android.view

import android.app.Application
import android.test.ApplicationTestCase
import android.view.View
import junit.framework.Assert

class ViewTest : ApplicationTestCase<Application>(Application::class.java) {

    fun testShouldSetViewVisibilityToVisible() {
        val view = View(context)
        view.visibility = View.INVISIBLE
        view.show()
        assertEquals(View.VISIBLE, view.visibility)
    }

    fun testShouldSetViewVisibilityToGone() {
        val view = View(context)
        view.hide()
        assertEquals(View.GONE, view.visibility)
    }

    fun testShouldReturnThatViewIsVisibleWhenViewIsVisible() {
        val view = View(context)
        assertTrue(view.isVisible())
    }

    fun testShouldReturnThatViewIsInvisibleWhenIsGone() {
        val view = View(context)
        view.visibility = View.GONE
        assertFalse(view.isVisible())
    }

    fun testShouldReturnThatViewIsInvisibleWhenIsInvisible() {
        val view = View(context)
        view.visibility = View.INVISIBLE
        assertFalse(view.isVisible())
    }

    fun testShouldEnableDisabledView() {
        val view = View(context).apply { isEnabled = false }
        view.enable()
        assertTrue(view.isEnabled)
    }

    fun testShouldDisableEnabledView() {
        val view = View(context)
        view.disable()
        Assert.assertFalse(view.isEnabled)
    }
}


Add parser for J type instructions (aka jal)

package venus.riscv.insts.dsl.parsers

import venus.riscv.InstructionField
import venus.riscv.MachineCode
import venus.riscv.Program
import venus.riscv.insts.dsl.regNameToNumber

object JTypeParser : InstructionParser {
    override operator fun invoke(prog: Program, mcode: MachineCode, args: List<String>) {
        mcode[InstructionField.RD] = regNameToNumber(args[0])
        prog.addRelocation(args[1])
    }
}


package io.ktor.client.request

import io.ktor.http.*

/**
 * Gets the associated URL's host.
 */
var HttpRequestBuilder.host: String
    get() = url.host
    set(value) {
        url.host = value
    }

/**
 * Gets the associated URL's port.
 */
var HttpRequestBuilder.port: Int
    get() = url.port
    set(value) {
        url.port = value
    }

/**
 * Sets a single header of [key] with a specific [value] if the value is not null.
 */
fun HttpRequestBuilder.header(key: String, value: Any?): Unit =
    value?.let { headers.append(key, it.toString()) } ?: Unit

/**
 * Sets a single parameter of [key] with a specific [value] if the value is not null.
 */
fun HttpRequestBuilder.parameter(key: String, value: Any?): Unit =
    value?.let { url.parameters.append(key, it.toString()) } ?: Unit

/**
 * Sets the `Accept` header with a specific [contentType].
 */
fun HttpRequestBuilder.accept(contentType: ContentType): Unit =
    headers.append(HttpHeaders.Accept, contentType.toString())

Clarify usage of HttpRequestBuilder.parameter() function

package io.ktor.client.request

import io.ktor.http.*

/**
 * Gets the associated URL's host.
 */
var HttpRequestBuilder.host: String
    get() = url.host
    set(value) {
        url.host = value
    }

/**
 * Gets the associated URL's port.
 */
var HttpRequestBuilder.port: Int
    get() = url.port
    set(value) {
        url.port = value
    }

/**
 * Sets a single header of [key] with a specific [value] if the value is not null.
 */
fun HttpRequestBuilder.header(key: String, value: Any?): Unit =
    value?.let { headers.append(key, it.toString()) } ?: Unit

/**
 * Sets a single URL query parameter of [key] with a specific [value] if the value is not null. Can not be used to set
 * form parameters in the body.
 */
fun HttpRequestBuilder.parameter(key: String, value: Any?): Unit =
    value?.let { url.parameters.append(key, it.toString()) } ?: Unit

/**
 * Sets the `Accept` header with a specific [contentType].
 */
fun HttpRequestBuilder.accept(contentType: ContentType): Unit =
    headers.append(HttpHeaders.Accept, contentType.toString())


package io.mironov.smuggler.sample

import android.app.Activity
import android.os.Bundle
import io.mironov.smuggler.AutoParcelable

class SampleActivity : Activity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_sample)
  }
}

data class User(val firstName: String, val userName: String) : AutoParcelable
data class Message(val text: String, val user: User) : AutoParcelable
data class Chat(val title: String, val messages: List<Message>, val participants: List<User>) : AutoParcelable

Add simple parcelable implementation for reference

package io.mironov.smuggler.sample

import android.app.Activity
import android.os.Bundle
import android.os.Parcel
import android.os.Parcelable
import io.mironov.smuggler.AutoParcelable

class SampleActivity : Activity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_sample)
  }
}

data class User(val firstName: String, val lastName: String) : AutoParcelable {
  companion object CREATOR : Parcelable.Creator<User> {
    override fun newArray(size: Int): Array<out User?> {
      return arrayOfNulls(size)
    }

    override fun createFromParcel(parcel: Parcel): User {
      val firstName = parcel.readString()
      val lastName = parcel.readString()

      return User(firstName, lastName)
    }
  }

  override fun writeToParcel(parcel: Parcel, flags: Int) {
    parcel.writeString(firstName)
    parcel.writeString(lastName)
  }

  override fun describeContents(): Int {
    return 0
  }
}

data class Message(val text: String, val user: User) : AutoParcelable
data class Chat(val title: String, val messages: List<Message>, val participants: List<User>) : AutoParcelable


/*
 * 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.rtcp

import org.jitsi.rtp.NewRawPacket

class CompoundRtcpSplitter {
    companion object {
        // Get all the contained RTCP packets from compoundRtcpPacket.  Each
        // packet will have been given its own buffer.
        fun getAll(compoundRtcpPacket: NewRawPacket): List<RtcpPacket> {
            var bytesRemaining = compoundRtcpPacket.length - compoundRtcpPacket.offset
            var currOffset = compoundRtcpPacket.offset
            val rtcpPackets = mutableListOf<RtcpPacket>()
            while (bytesRemaining > RtcpHeader.SIZE_BYTES) {
                val rtcpPacket = RtcpPacket.parse(compoundRtcpPacket.buffer, currOffset)
                rtcpPackets.add(rtcpPacket.clone())
                currOffset += rtcpPacket.length
                bytesRemaining -= rtcpPacket.length
            }
            return rtcpPackets
        }
    }
}

Fix parsing compound RTCP when offset!=0.

/*
 * 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.rtcp

import org.jitsi.rtp.NewRawPacket

class CompoundRtcpSplitter {
    companion object {
        // Get all the contained RTCP packets from compoundRtcpPacket.  Each
        // packet will have been given its own buffer.
        fun getAll(compoundRtcpPacket: NewRawPacket): List<RtcpPacket> {
            var bytesRemaining = compoundRtcpPacket.length
            var currOffset = compoundRtcpPacket.offset
            val rtcpPackets = mutableListOf<RtcpPacket>()
            while (bytesRemaining > RtcpHeader.SIZE_BYTES) {
                val rtcpPacket = RtcpPacket.parse(compoundRtcpPacket.buffer, currOffset)
                rtcpPackets.add(rtcpPacket.clone())
                currOffset += rtcpPacket.length
                bytesRemaining -= rtcpPacket.length
            }
            return rtcpPackets
        }
    }
}


package com.doomspork.helloworld

import io.dropwizard.Configuration
import org.hibernate.validator.constraints.NotEmpty
import com.fasterxml.jackson.annotation.JsonProperty

data class HelloWorldConfiguration(JsonProperty NotEmpty var template: String,
                                   JsonProperty NotEmpty var defaultName: String = "Stranger") : Configuration()

Update jackson annotations to support multi-arg constructor

package com.doomspork.helloworld

import io.dropwizard.Configuration
import org.hibernate.validator.constraints.NotEmpty
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonCreator

data class HelloWorldConfiguration [JsonCreator] (JsonProperty("template") NotEmpty var template: String = "",
                                   JsonProperty("defaultName") NotEmpty var defaultName: String = "Stranger") : Configuration()


/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
 *
 * 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 com.kotlinnlp.simplednn.simplemath.ndarray

/**
 *
 */
class NDArrayMask(val dim1: Array<Int>, val dim2: Array<Int>) : Iterable<Indices> {

  init {
    require(dim1.size == dim2.size)
  }

  /**
   *
   */
  private inner class NDArrayMaskIterator : Iterator<Indices> {

    /**
     *
     */
    private var curIndex = 0

    /**
     *
     */
    override fun hasNext(): Boolean = curIndex < this@NDArrayMask.dim1.size

    /**
     *
     */
    override fun next(): Indices {

      val next = Pair(this@NDArrayMask.dim1[curIndex], this@NDArrayMask.dim2[curIndex])

      this.curIndex++

      return next
    }

  }

  /**
   *
   */
  override fun iterator(): Iterator<Indices> = this.NDArrayMaskIterator()
}

Add shape and size attributes

/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
 *
 * 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 com.kotlinnlp.simplednn.simplemath.ndarray

/**
 *
 */
class NDArrayMask(val dim1: Array<Int>, val dim2: Array<Int>, val shape: Shape) : Iterable<Indices> {

  init {
    require(dim1.size == dim2.size)
  }

  /**
   *
   */
  val size = dim1.size

  /**
   *
   */
  private inner class NDArrayMaskIterator : Iterator<Indices> {

    /**
     *
     */
    private var curIndex = 0

    /**
     *
     */
    override fun hasNext(): Boolean = curIndex < this@NDArrayMask.dim1.size

    /**
     *
     */
    override fun next(): Indices {

      val next = Pair(this@NDArrayMask.dim1[curIndex], this@NDArrayMask.dim2[curIndex])

      this.curIndex++

      return next
    }

  }

  /**
   *
   */
  override fun iterator(): Iterator<Indices> = this.NDArrayMaskIterator()
}


package net.squanchy.support.font

import android.graphics.Paint
import android.graphics.Typeface

class TypefaceDelegate(private val newTypeface: Typeface) {

    private companion object {
        @SuppressWarnings("MagicNumber")
        const val TEXT_SKEW_X = -.25f
        const val FALSE_FLAG = 0
    }

    fun applyTypefaceTo(paint: Paint) {
        val fakeStyle = fakeStyle(paint)

        if (bold(fakeStyle)) {
            paint.isFakeBoldText = true
        }
        if (italic(fakeStyle)) {
            paint.textSkewX = TEXT_SKEW_X
        }

        paint.typeface = newTypeface
    }

    private fun bold(fakeStyle: Int) = fakeStyle.and(Typeface.BOLD) != FALSE_FLAG

    private fun italic(fakeStyle: Int) = fakeStyle.and(Typeface.ITALIC) != FALSE_FLAG

    private fun fakeStyle(paint: Paint): Int {
        val oldStyle = paint.typeface?.style ?: 0
        return oldStyle.and(newTypeface.style.inv())
    }
}

Change naming to make the code easier to understand

package net.squanchy.support.font

import android.graphics.Paint
import android.graphics.Typeface

class TypefaceDelegate(private val newTypeface: Typeface) {

    private companion object {
        @SuppressWarnings("MagicNumber")
        const val TEXT_SKEW_X = -.25f
        const val FALSE_FLAG = 0
    }

    fun applyTypefaceTo(paint: Paint) {
        val previousStyle = computePreviousStyle(paint)

        if (isBold(previousStyle)) {
            paint.isFakeBoldText = true
        }
        if (isItalic(previousStyle)) {
            paint.textSkewX = TEXT_SKEW_X
        }

        paint.typeface = newTypeface
    }

    private fun isBold(fakeStyle: Int) = fakeStyle.and(Typeface.BOLD) != FALSE_FLAG

    private fun isItalic(fakeStyle: Int) = fakeStyle.and(Typeface.ITALIC) != FALSE_FLAG

    private fun computePreviousStyle(paint: Paint): Int {
        val oldStyle = paint.typeface?.style ?: 0
        return oldStyle.and(newTypeface.style.inv())
    }
}


package org.wordpress.aztec

import org.xml.sax.Attributes
import org.xml.sax.helpers.AttributesImpl

class AztecAttributes(attributes: Attributes = AttributesImpl()) : AttributesImpl(attributes) {

    fun setValue(key: String, value: String) {
        val index = getIndex(key)
        if (index == -1) {
            addAttribute("", key, key, "string", value)
        } else {
            setValue(index, value)
        }
    }

    fun isEmpty() : Boolean {
        return length == 0
    }

    fun hasAttribute(key: String) : Boolean {
        return getValue(key) == null
    }

    override fun toString(): String {
        val sb = StringBuilder()
        for (i in 0..this.length-1) {
            sb.append(this.getLocalName(i))
            sb.append("=\"")
            sb.append(this.getValue(i))
            sb.append("\" ")
        }
        return sb.trimEnd().toString()
    }
}

Add helper function for attribute removal

package org.wordpress.aztec

import org.xml.sax.Attributes
import org.xml.sax.helpers.AttributesImpl

class AztecAttributes(attributes: Attributes = AttributesImpl()) : AttributesImpl(attributes) {

    fun setValue(key: String, value: String) {
        val index = getIndex(key)
        if (index == -1) {
            addAttribute("", key, key, "string", value)
        } else {
            setValue(index, value)
        }
    }

    fun isEmpty() : Boolean {
        return length == 0
    }

    fun removeAttribute(key: String) {
        if (hasAttribute(key)) {
            val index = getIndex(key)
            removeAttribute(index)
        }
    }

    fun hasAttribute(key: String) : Boolean {
        return getValue(key) == null
    }

    override fun toString(): String {
        val sb = StringBuilder()
        for (i in 0..this.length-1) {
            sb.append(this.getLocalName(i))
            sb.append("=\"")
            sb.append(this.getValue(i))
            sb.append("\" ")
        }
        return sb.trimEnd().toString()
    }
}


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

import org.gradle.plugin.use.PluginDependenciesSpec
import org.gradle.plugin.use.PluginDependencySpec

/**
 * The `embedded-kotlin` plugin.
 *
 * Fetched from plugin repositories using the following plugin id:
 * `org.gradle.script.lang.kotlin.plugins.embedded-kotlin`.
 *
 * @see org.gradle.script.lang.kotlin.plugins.EmbeddedKotlinPlugin
 */
inline val PluginDependenciesSpec.`embedded-kotlin`: PluginDependencySpec
    get() = id("org.gradle.script.lang.kotlin.plugins.embedded-kotlin") version gradleScriptKotlinVersion

Fix wrong package in kdoc for embedded-plugin accessor

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

import org.gradle.plugin.use.PluginDependenciesSpec
import org.gradle.plugin.use.PluginDependencySpec

/**
 * The `embedded-kotlin` plugin.
 *
 * Fetched from plugin repositories using the following plugin id:
 * `org.gradle.script.lang.kotlin.plugins.embedded-kotlin`.
 *
 * @see org.gradle.script.lang.kotlin.plugins.embedded.EmbeddedKotlinPlugin
 */
inline val PluginDependenciesSpec.`embedded-kotlin`: PluginDependencySpec
    get() = id("org.gradle.script.lang.kotlin.plugins.embedded-kotlin") version gradleScriptKotlinVersion


/*
 * Copyright 2021 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.benchmark.macro.perfetto

import perfetto.protos.Trace
import perfetto.protos.TracePacket
import perfetto.protos.UiState
import java.io.File

/**
 * Convenience for UiState construction with specified package
 */
@Suppress("FunctionName") // constructor convenience
internal fun UiState(
    timelineStart: Long?,
    timelineEnd: Long?,
    highlightPackage: String?
) = UiState(
    timeline_start_ts = timelineStart,
    timeline_end_ts = timelineEnd,
    highlight_process = highlightPackage?.run {
        UiState.HighlightProcess(cmdline = highlightPackage)
    }
)

internal fun File.appendUiState(state: UiState) {
    val trace = Trace.ADAPTER.decode(inputStream())
    val appendedTrace = Trace(packet = trace.packet + listOf(TracePacket(ui_state = state)))
    Trace.ADAPTER.encode(outputStream(), appendedTrace)
}

Append UI metadata to trace file directly, instead of load+append+write

/*
 * Copyright 2021 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.benchmark.macro.perfetto

import perfetto.protos.Trace
import perfetto.protos.TracePacket
import perfetto.protos.UiState
import java.io.File

/**
 * Convenience for UiState construction with specified package
 */
@Suppress("FunctionName") // constructor convenience
internal fun UiState(
    timelineStart: Long?,
    timelineEnd: Long?,
    highlightPackage: String?
) = UiState(
    timeline_start_ts = timelineStart,
    timeline_end_ts = timelineEnd,
    highlight_process = highlightPackage?.run {
        UiState.HighlightProcess(cmdline = highlightPackage)
    }
)

internal fun File.appendUiState(state: UiState) {
    val traceToAppend = Trace(packet = listOf(TracePacket(ui_state = state)))
    appendBytes(traceToAppend.encode())
}


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

package org.rust.cargo.toolchain

import com.intellij.execution.configurations.GeneralCommandLine
import org.rust.cargo.CargoConstants.ProjectLayout
import org.rust.openapiext.GeneralCommandLine
import java.io.File
import java.nio.file.Path

class Grcov(private val grcovExecutable: Path) {
    fun createCommandLine(workingDirectory: File, coverageFilePath: Path): GeneralCommandLine =
        GeneralCommandLine(grcovExecutable)
            .withWorkDirectory(workingDirectory)
            .withParameters(
                ProjectLayout.target,
                "-t", "lcov",
                "--branch",
                "--ignore-not-existing",
                "-o", coverageFilePath.toString()
            )
            .withCharset(Charsets.UTF_8)
}

Fix `Run with Coverage` on nightly channel

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

package org.rust.cargo.toolchain

import com.intellij.execution.configurations.GeneralCommandLine
import org.rust.cargo.CargoConstants.ProjectLayout
import org.rust.openapiext.GeneralCommandLine
import java.io.File
import java.nio.file.Path

class Grcov(private val grcovExecutable: Path) {
    fun createCommandLine(workingDirectory: File, coverageFilePath: Path): GeneralCommandLine =
        GeneralCommandLine(grcovExecutable)
            .withWorkDirectory(workingDirectory)
            .withParameters(
                ProjectLayout.target,
                "-t", "lcov",
                "--llvm",
                "--branch",
                "--ignore-not-existing",
                "-o", coverageFilePath.toString()
            )
            .withCharset(Charsets.UTF_8)
}


pluginManagement {
    repositories {
        gradlePluginPortal()
    }
    plugins {
        id("com.diffplug.eclipse.apt") version "3.37.1"
        id("com.diffplug.spotless") version "6.7.2"
        id("io.github.gradle-nexus.publish-plugin") version "1.1.0"
        id("net.researchgate.release") version "3.0.0"
        id("org.domaframework.doma.compile") version "2.0.0"
        kotlin("jvm") version "1.7.10"
        kotlin("kapt") version "1.7.10"
    }
}

rootProject.name = "doma"

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

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

Update plugin net.researchgate.release to v3.0.1

pluginManagement {
    repositories {
        gradlePluginPortal()
    }
    plugins {
        id("com.diffplug.eclipse.apt") version "3.37.1"
        id("com.diffplug.spotless") version "6.7.2"
        id("io.github.gradle-nexus.publish-plugin") version "1.1.0"
        id("net.researchgate.release") version "3.0.1"
        id("org.domaframework.doma.compile") version "2.0.0"
        kotlin("jvm") version "1.7.10"
        kotlin("kapt") version "1.7.10"
    }
}

rootProject.name = "doma"

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

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


package i_introduction._10_Object_Expressions

import util.TODO
import util.doc10
import java.util.*

fun todoTask10(): Nothing = TODO(
    """
        Task 10.
        Read about object expressions that play the same role in Kotlin as anonymous classes do in Java.

        Add an object expression that provides a comparator to sort a list in a descending order using java.util.Collections class.
        In Kotlin you use Kotlin library extensions instead of java.util.Collections,
        but this example is still a good demonstration of mixing Kotlin and Java code.
    """,
    documentation = doc10()
)

fun task10(): List<Int> {
    val arrayList = arrayListOf(1, 5, 2)
    Collections.sort(arrayList, object : Comparator<Int> {
        override fun compare(o1: Int?, o2: Int?): Int {
            return o2!!.compareTo(o1!!)
        }
    })
    return arrayList
}

Remove nullability on Comparator.compare arguments

package i_introduction._10_Object_Expressions

import util.TODO
import util.doc10
import java.util.*

fun todoTask10(): Nothing = TODO(
    """
        Task 10.
        Read about object expressions that play the same role in Kotlin as anonymous classes do in Java.

        Add an object expression that provides a comparator to sort a list in a descending order using java.util.Collections class.
        In Kotlin you use Kotlin library extensions instead of java.util.Collections,
        but this example is still a good demonstration of mixing Kotlin and Java code.
    """,
    documentation = doc10()
)

fun task10(): List<Int> {
    val arrayList = arrayListOf(1, 5, 2)
    Collections.sort(arrayList, object : Comparator<Int> {
        override fun compare(o1: Int, o2: Int): Int {
            return o2.compareTo(o1)
        }
    })
    return arrayList
}


package com.vimeo.networking2.config

import retrofit2.Retrofit

class RetrofitServicesCache(var retrofit: Retrofit) {

    /**
     * Cache of Retrofit API Services.  Objects created by calling getService().
     */
    private val cache = mutableMapOf<Class<*>, Any>()

    /**
     * Create and cache instance of the given Retrofit Service interface.
     */
    @Suppress("UNCHECKED_CAST")
    fun <T> getService(serviceClass: Class<T>): T {
        if (cache[serviceClass] == null) {
            cache[serviceClass] = retrofit.create(serviceClass) as Any
        }
        return cache[serviceClass] as T
    }

    /**
     * Empty service endpoint cache.
     */
    fun clear() {
        println("RetrofitServicesCache.clear")
        cache.clear()
    }

     fun logCache() {
         println("RetrofitServicesCache.logCache")
         println(cache)
    }

}

Add class doc for the retrofit services cache

package com.vimeo.networking2.config

import retrofit2.Retrofit

/**
 * As Retrofit services are created, they are cached in this class.
 */
class RetrofitServicesCache(var retrofit: Retrofit) {

    /**
     * Cache of Retrofit API Services.  Objects created by calling getService().
     */
    private val cache = mutableMapOf<Class<*>, Any>()

    /**
     * Create and cache instance of the given Retrofit Service interface.
     */
    @Suppress("UNCHECKED_CAST")
    fun <T> getService(serviceClass: Class<T>): T {
        if (cache[serviceClass] == null) {
            cache[serviceClass] = retrofit.create(serviceClass) as Any
        }
        return cache[serviceClass] as T
    }

    /**
     * Empty service endpoint cache.
     */
    fun clear() {
        cache.clear()
    }

}


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

import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmProductType
import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmProductVersion

data class W3CSpecificationsVersion(override val product: XpmProductType) : XpmProductVersion {
    // region XpmProductVersion

    override val id: String = "1.0"

    override val features: String = ""

    override fun compareTo(other: XpmProductVersion): Int = this.product.id.compareTo(other.product.id)

    override fun toString(): String = "${product.presentation.presentableText} $id"

    // endregion
}

Change the W3C Specifications product display name.

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

import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmProductType
import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmProductVersion

data class W3CSpecificationsVersion(override val product: XpmProductType) : XpmProductVersion {
    // region XpmProductVersion

    override val id: String = "1.0"

    override val features: String = ""

    override fun compareTo(other: XpmProductVersion): Int = this.product.id.compareTo(other.product.id)

    override fun toString(): String = "${product.presentation.presentableText} REC"

    // endregion
}


dependencies {
    implementation(project(":basics"))
    implementation(project(":cleanup"))
    implementation(project(":dependencyModules"))
    implementation(project(":packaging"))
    implementation(project(":moduleIdentity"))

    testImplementation("junit:junit")
}

Remove dependency that is not needed

dependencies {
    implementation(project(":basics"))
    implementation(project(":cleanup"))
    implementation(project(":dependencyModules"))
    implementation(project(":moduleIdentity"))

    testImplementation("junit:junit")
}


package com.elpassion.mainframerplugin.util

val toolFilename = "mainframer.sh"

fun getToolDownloadUrl(version: String) = "https://github.com/gojuno/mainframer/releases/download/v$version/mainframer.sh"

Remove .sh suffix from mainframer.sh.

package com.elpassion.mainframerplugin.util

val toolFilename = "mainframer"

fun getToolDownloadUrl(version: String) = "https://github.com/gojuno/mainframer/releases/download/v$version/$toolFilename"


package ru.dyatel.tsuschedule.utilities

import java.io.File
import java.net.URL

fun URL.download(destination: File, timeout: Int, onProgressUpdate: (Int) -> Unit) {
    val connection = openConnection().apply {
        connectTimeout = timeout
        readTimeout = timeout
    }

    val length = connection.contentLength
    var downloaded = 0
    connection.getInputStream().buffered().use { input ->
        destination.outputStream().buffered().use { output ->
            val buffer = ByteArray(8192)
            var count: Int
            do {
                count = input.read(buffer)
                if (count == -1) break

                output.write(buffer, 0, count)

                downloaded += count
                onProgressUpdate(downloaded * 100 / length)
            } while (true)
        }
    }
}

Fix possible division by 0 in file downloading

package ru.dyatel.tsuschedule.utilities

import java.io.File
import java.net.URL

fun URL.download(destination: File, timeout: Int, onProgressUpdate: (Int) -> Unit) {
    val connection = openConnection().apply {
        connectTimeout = timeout
        readTimeout = timeout
    }

    connection.getInputStream().buffered().use { input ->
        destination.outputStream().buffered().use { output ->
            val buffer = ByteArray(8192)
            val length = connection.contentLength
            var downloaded = 0
            var count: Int
            do {
                count = input.read(buffer)
                if (count == -1) break

                output.write(buffer, 0, count)

                if (length > 0) {
                    downloaded += count
                    onProgressUpdate(downloaded * 100 / length)
                }
            } while (true)
        }
    }
}


Add test for package not installed inspection

package nl.hannahsten.texifyidea.inspections.latex

import io.mockk.every
import io.mockk.mockkObject
import io.mockk.mockkStatic
import nl.hannahsten.texifyidea.index.LatexDefinitionIndex
import nl.hannahsten.texifyidea.inspections.TexifyInspectionTestBase
import nl.hannahsten.texifyidea.run.latex.LatexDistribution
import nl.hannahsten.texifyidea.util.SystemEnvironment
import nl.hannahsten.texifyidea.util.TexLivePackages
import nl.hannahsten.texifyidea.util.runCommand

class LatexPackageNotInstalledInspectionTest : TexifyInspectionTestBase(LatexPackageNotInstalledInspection()) {
    fun `test no warnings when not using texlive`() {
        texliveWithTlmgr(texlive = false, tlmgr = false)

        testHighlighting("\\usepackage{amsmath}")
    }

    fun `test no warnings when tlmgr is not available`() {
        texliveWithTlmgr(texlive = true, tlmgr = false)

        testHighlighting("\\usepackage{amsmath}")
    }

    fun `test no warnings when package is installed`() {
        texliveWithTlmgr()

        mockkObject(TexLivePackages)
        every { TexLivePackages.packageList } returns mutableListOf("amsmath")

        testHighlighting("\\usepackage{amsmath}")
    }

    fun `test warning when package is not installed`() {
        texliveWithTlmgr()

        mockkObject(TexLivePackages)
        every { TexLivePackages.packageList } returns mutableListOf()

        // The package is not installed locally.
        mockkStatic("nl.hannahsten.texifyidea.util.StringsKt")
        every { "tlmgr search --file /amsmath.sty".runCommand() } returns ""

        testHighlighting("<warning descr=\"Package is not installed or \\ProvidesPackage is missing\">\\usepackage{amsmath}</warning>")
    }

    private fun texliveWithTlmgr(texlive: Boolean = true, tlmgr: Boolean = true) {
        mockkObject(LatexDistribution)
        every { LatexDistribution.isTexliveAvailable } returns texlive

        mockkObject(SystemEnvironment)
        every { SystemEnvironment.isTlmgrInstalled } returns tlmgr
    }
}


package com.github.kittinunf.fuel.util

data class TestConfiguration(
        /**
         * Forced timeout value for every request during test mode is enabled.
         * If set to null, the original timeout will be used.
         * If set to -1, there will be no timeout.
         */
        var timeout: Int? = null,
        /**
         * If set to true, it will block the thread for every request.
         */
        var blocking: Boolean = true)


package eu.kanade.tachiyomi.network

import android.content.Context
import java.io.File
import java.util.concurrent.TimeUnit
import okhttp3.Cache
import okhttp3.OkHttpClient

class NetworkHelper(context: Context) {

    private val cacheDir = File(context.cacheDir, "network_cache")

    private val cacheSize = 5L * 1024 * 1024 // 5 MiB

    val cookieManager = AndroidCookieJar()

    val client = OkHttpClient.Builder()
        .cookieJar(cookieManager)
        .cache(Cache(cacheDir, cacheSize))
        .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .build()

    val cloudflareClient = client.newBuilder()
        .addInterceptor(UserAgentInterceptor())
        .addInterceptor(CloudflareInterceptor(context))
        .build()
}

Add network header logging in debug builds

package eu.kanade.tachiyomi.network

import android.content.Context
import eu.kanade.tachiyomi.BuildConfig
import java.io.File
import java.util.concurrent.TimeUnit
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor

class NetworkHelper(context: Context) {

    private val cacheDir = File(context.cacheDir, "network_cache")

    private val cacheSize = 5L * 1024 * 1024 // 5 MiB

    val cookieManager = AndroidCookieJar()

    val client by lazy {
        val builder = OkHttpClient.Builder()
            .cookieJar(cookieManager)
            .cache(Cache(cacheDir, cacheSize))
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)

        if (BuildConfig.DEBUG) {
            val httpLoggingInterceptor = HttpLoggingInterceptor().apply {
                level = HttpLoggingInterceptor.Level.HEADERS
            }
            builder.addInterceptor(httpLoggingInterceptor)
        }

        builder.build()
    }

    val cloudflareClient = client.newBuilder()
        .addInterceptor(UserAgentInterceptor())
        .addInterceptor(CloudflareInterceptor(context))
        .build()
}


package lt.markmerkk.tickets

import lt.markmerkk.Tags
import lt.markmerkk.TicketStorage
import lt.markmerkk.entities.Ticket
import lt.markmerkk.entities.TicketUseHistory
import org.slf4j.LoggerFactory
import rx.Observable
import rx.Scheduler
import rx.Subscription

class RecentTicketLoader(
        private val listener: Listener,
        private val ticketStorage: TicketStorage,
        private val ioScheduler: Scheduler,
        private val uiScheduler: Scheduler
) {

    private var fetchSub: Subscription? = null

    fun onAttach() {}

    fun onDetach() {
        fetchSub?.unsubscribe()
    }

    fun fetch() {
        fetchSub?.unsubscribe()
        fetchSub = ticketStorage.fetchRecentTickets(6)
                .flatMapObservable { Observable.from(it) }
                .flatMapSingle { ticketUseHistory ->
                    ticketStorage.findTicketsByCode(ticketUseHistory.code.code)
                            .map { ticket -> ticket.firstOrNull() }
                            .map {
                                ticketUseHistory.appendDescription(
                                        description = it?.description ?: ""
                                )
                            }
                }
                .toList()
                .subscribeOn(ioScheduler)
                .observeOn(uiScheduler)
                .subscribe({ tickets ->
                    val sortedRecentTickets = tickets
                            .sortedBy { it.lastUsed }
                            .reversed()
                    listener.onRecentTickets(sortedRecentTickets)
                }, {
                    logger.warn("Error fetch tickets", it)
                })
    }

    interface Listener {
        fun onRecentTickets(tickets: List<TicketUseHistory>)
    }

    companion object {
        private val logger = LoggerFactory.getLogger(Tags.TICKETS)
    }
}

Expand last used ticket search

package lt.markmerkk.tickets

import lt.markmerkk.Tags
import lt.markmerkk.TicketStorage
import lt.markmerkk.entities.Ticket
import lt.markmerkk.entities.TicketUseHistory
import org.slf4j.LoggerFactory
import rx.Observable
import rx.Scheduler
import rx.Subscription

class RecentTicketLoader(
        private val listener: Listener,
        private val ticketStorage: TicketStorage,
        private val ioScheduler: Scheduler,
        private val uiScheduler: Scheduler
) {

    private var fetchSub: Subscription? = null

    fun onAttach() {}

    fun onDetach() {
        fetchSub?.unsubscribe()
    }

    fun fetch() {
        fetchSub?.unsubscribe()
        fetchSub = ticketStorage.fetchRecentTickets(20)
                .flatMapObservable { Observable.from(it) }
                .flatMapSingle { ticketUseHistory ->
                    ticketStorage.findTicketsByCode(ticketUseHistory.code.code)
                            .map { ticket -> ticket.firstOrNull() }
                            .map {
                                ticketUseHistory.appendDescription(
                                        description = it?.description ?: ""
                                )
                            }
                }
                .toList()
                .subscribeOn(ioScheduler)
                .observeOn(uiScheduler)
                .subscribe({ tickets ->
                    val sortedRecentTickets = tickets
                            .sortedBy { it.lastUsed }
                            .reversed()
                    listener.onRecentTickets(sortedRecentTickets)
                }, {
                    logger.warn("Error fetch tickets", it)
                })
    }

    interface Listener {
        fun onRecentTickets(tickets: List<TicketUseHistory>)
    }

    companion object {
        private val logger = LoggerFactory.getLogger(Tags.TICKETS)
    }
}


package de.paul_woitaschek.mediaplayer.internals

import android.annotation.TargetApi
import android.media.AudioFormat
import android.media.MediaFormat
import android.os.Build

@TargetApi(16)
internal fun MediaFormat.containsKeys(vararg keys: String): Boolean = keys.any { containsKey(it) }

internal fun Sonic.availableBytes() = numChannels * samplesAvailable() * 2

internal fun findFormatFromChannels(numChannels: Int) = when (numChannels) {
  1 -> AudioFormat.CHANNEL_OUT_MONO
  2 -> AudioFormat.CHANNEL_OUT_STEREO
  3 -> AudioFormat.CHANNEL_OUT_STEREO or AudioFormat.CHANNEL_OUT_FRONT_CENTER
  4 -> AudioFormat.CHANNEL_OUT_QUAD
  5 -> AudioFormat.CHANNEL_OUT_QUAD or AudioFormat.CHANNEL_OUT_FRONT_CENTER
  6 -> AudioFormat.CHANNEL_OUT_5POINT1
  7 -> AudioFormat.CHANNEL_OUT_5POINT1 or AudioFormat.CHANNEL_OUT_BACK_CENTER
  8 -> if (Build.VERSION.SDK_INT >= 23) {
    AudioFormat.CHANNEL_OUT_7POINT1_SURROUND;
  } else -1
  else -> -1 // Error
}

Make sure all tracks match, not any

package de.paul_woitaschek.mediaplayer.internals

import android.annotation.TargetApi
import android.media.AudioFormat
import android.media.MediaFormat
import android.os.Build

@TargetApi(16)
internal fun MediaFormat.containsKeys(vararg keys: String): Boolean = keys.all { containsKey(it) }

internal fun Sonic.availableBytes() = numChannels * samplesAvailable() * 2

internal fun findFormatFromChannels(numChannels: Int) = when (numChannels) {
  1 -> AudioFormat.CHANNEL_OUT_MONO
  2 -> AudioFormat.CHANNEL_OUT_STEREO
  3 -> AudioFormat.CHANNEL_OUT_STEREO or AudioFormat.CHANNEL_OUT_FRONT_CENTER
  4 -> AudioFormat.CHANNEL_OUT_QUAD
  5 -> AudioFormat.CHANNEL_OUT_QUAD or AudioFormat.CHANNEL_OUT_FRONT_CENTER
  6 -> AudioFormat.CHANNEL_OUT_5POINT1
  7 -> AudioFormat.CHANNEL_OUT_5POINT1 or AudioFormat.CHANNEL_OUT_BACK_CENTER
  8 -> if (Build.VERSION.SDK_INT >= 23) {
    AudioFormat.CHANNEL_OUT_7POINT1_SURROUND;
  } else -1
  else -> -1 // Error
}


package org.wikipedia.views

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import kotlinx.android.synthetic.main.view_image_detail_horizontal.view.*
import org.wikipedia.R
import org.wikipedia.util.StringUtil

class ImageDetailHorizontalView constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int) : LinearLayout(context, attrs, defStyle) {
    init {
        View.inflate(context, R.layout.view_image_detail_horizontal, this)
        if (attrs != null) {
            val array = getContext().obtainStyledAttributes(attrs, R.styleable.ImageDetailHorizontalView, defStyle, 0)
            titleText!!.text = array.getString(R.styleable.ImageDetailHorizontalView_title)
            setDetailText(array.getString(R.styleable.ImageDetailHorizontalView_detail))
            array.recycle()
        }
        orientation = HORIZONTAL
    }

    fun setDetailText(detail: String?) {
        if (!detail.isNullOrEmpty()) {
            detailText!!.text = StringUtil.removeHTMLTags(detail)
        }
    }
}

Fix crash when inflating view

package org.wikipedia.views

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import kotlinx.android.synthetic.main.view_image_detail_horizontal.view.*
import org.wikipedia.R
import org.wikipedia.util.StringUtil

class ImageDetailHorizontalView constructor(context: Context, attrs: AttributeSet? = null) : LinearLayout(context, attrs) {
    init {
        View.inflate(context, R.layout.view_image_detail_horizontal, this)
        if (attrs != null) {
            val array = getContext().obtainStyledAttributes(attrs, R.styleable.ImageDetailHorizontalView, 0, 0)
            titleText!!.text = array.getString(R.styleable.ImageDetailHorizontalView_title)
            setDetailText(array.getString(R.styleable.ImageDetailHorizontalView_detail))
            array.recycle()
        }
        orientation = HORIZONTAL
    }

    fun setDetailText(detail: String?) {
        if (!detail.isNullOrEmpty()) {
            detailText!!.text = StringUtil.removeHTMLTags(detail)
        }
    }
}


package org.purescript.ide.inspections

import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiReference
import org.purescript.PSLanguage
import org.purescript.psi.exports.PSExportedModule
import org.purescript.psi.exports.PSExportedValue
import org.purescript.psi.imports.PSImportDeclarationImpl

class PSUnresolvedReferenceInspection : LocalInspectionTool() {
    override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
        return object : PsiElementVisitor() {
            override fun visitElement(element: PsiElement) {
                super.visitElement(element)
                when (element) {
                    is PSExportedValue -> visitReference(element.reference)
                    is PSExportedModule -> visitModuleReference(element.reference)
                    is PSImportDeclarationImpl -> visitModuleReference(element.reference)
                }
            }

            private fun visitModuleReference(reference: PsiReference) {
                if (reference.canonicalText !in PSLanguage.BUILTIN_MODULES) {
                    visitReference(reference)
                }
            }

            private fun visitReference(reference: PsiReference) {
                if (reference.resolve() == null) {
                    holder.registerProblem(reference)
                }
            }
        }
    }
}

Implement inspections for unresolved expression constructors

package org.purescript.ide.inspections

import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiReference
import org.purescript.PSLanguage
import org.purescript.psi.exports.PSExportedModule
import org.purescript.psi.exports.PSExportedValue
import org.purescript.psi.expression.PSExpressionConstructor
import org.purescript.psi.imports.PSImportDeclarationImpl

class PSUnresolvedReferenceInspection : LocalInspectionTool() {
    override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
        return object : PsiElementVisitor() {
            override fun visitElement(element: PsiElement) {
                super.visitElement(element)
                when (element) {
                    is PSExportedValue -> visitReference(element.reference)
                    is PSExportedModule -> visitModuleReference(element.reference)
                    is PSImportDeclarationImpl -> visitModuleReference(element.reference)
                    is PSExpressionConstructor -> visitReference(element.reference)
                }
            }

            private fun visitModuleReference(reference: PsiReference) {
                if (reference.canonicalText !in PSLanguage.BUILTIN_MODULES) {
                    visitReference(reference)
                }
            }

            private fun visitReference(reference: PsiReference) {
                if (reference.resolve() == null) {
                    holder.registerProblem(reference)
                }
            }
        }
    }
}


package kotlinx.coroutines.test

import kotlinx.coroutines.CoroutineExceptionHandler
import java.util.*
import kotlin.coroutines.CoroutineContext

/**
 * Access uncaught coroutines exceptions captured during test execution.
 *
 * Note, tests executed via [runBlockingTest] or [TestCoroutineScope.runBlocking] will not trigger uncaught exception
 * handling and should use [Deferred.await] or [Job.getCancellationException] to test exceptions.
 */
interface ExceptionCaptor {
    /**
     * List of uncaught coroutine exceptions.
     *
     * During [cleanupTestCoroutines] the first element of this list will be rethrown if it is not empty.
     */
    val exceptions: MutableList<Throwable>

    /**
     * Call after the test completes.
     *
     * @throws Throwable the first uncaught exception, if there are any uncaught exceptions
     */
    fun cleanupTestCoroutines()
}

/**
 * An exception handler that can be used to capture uncaught exceptions in tests.
 */
class TestCoroutineExceptionHandler: ExceptionCaptor, CoroutineExceptionHandler {
    override fun handleException(context: CoroutineContext, exception: Throwable) {
        exceptions += exception
    }

    override val key = CoroutineExceptionHandler

    override val exceptions = LinkedList<Throwable>()

    override fun cleanupTestCoroutines() {
        val exception = exceptions.firstOrNull() ?: return
        throw exception
    }
}

Add thread saftey to exceptions

package kotlinx.coroutines.test

import kotlinx.coroutines.CoroutineExceptionHandler
import java.util.*
import kotlin.coroutines.CoroutineContext

/**
 * Access uncaught coroutines exceptions captured during test execution.
 *
 * Note, tests executed via [runBlockingTest] or [TestCoroutineScope.runBlocking] will not trigger uncaught exception
 * handling and should use [Deferred.await] or [Job.getCancellationException] to test exceptions.
 */
interface ExceptionCaptor {
    /**
     * List of uncaught coroutine exceptions.
     *
     * During [cleanupTestCoroutines] the first element of this list will be rethrown if it is not empty.
     */
    val exceptions: List<Throwable>

    /**
     * Call after the test completes.
     *
     * @throws Throwable the first uncaught exception, if there are any uncaught exceptions
     */
    fun cleanupTestCoroutines()
}

/**
 * An exception handler that can be used to capture uncaught exceptions in tests.
 */
class TestCoroutineExceptionHandler: ExceptionCaptor, CoroutineExceptionHandler {
    val lock = Object()

    override fun handleException(context: CoroutineContext, exception: Throwable) {
        synchronized(lock) {
            _exceptions += exception
        }
    }

    override val key = CoroutineExceptionHandler

    private val _exceptions = mutableListOf<Throwable>()

    override val exceptions
        get() = _exceptions.toList()

    override fun cleanupTestCoroutines() {
        synchronized(lock) {
            val exception = _exceptions.firstOrNull() ?: return
            throw exception
        }
    }
}


import org.gradle.api.plugins.JavaPlugin.TEST_IMPLEMENTATION_CONFIGURATION_NAME

plugins {
    id("via.build-logic")
}

allprojects {
    group = "com.viaversion"
    version = property("projectVersion") as String // from gradle.properties
    description = "Allow newer clients to join older server versions."
}

val platforms = setOf(
    projects.viaversionBukkit,
    projects.viaversionBungee,
    projects.viaversionFabric,
    projects.viaversionSponge,
    projects.viaversionVelocity
).map { it.dependencyProject }

val special = setOf(
    projects.viaversion,
    projects.viaversionApi,
    projects.adventure
).map { it.dependencyProject }

subprojects {
    when (this) {
        in platforms -> plugins.apply("via.platform-conventions")
        in special -> plugins.apply("via.base-conventions")
        else -> plugins.apply("via.standard-conventions")
    }

    dependencies {
        // Note: If manually starting tests doesn't work for you in IJ, change 'Gradle -> Run Tests Using' to 'IntelliJ IDEA'
        TEST_IMPLEMENTATION_CONFIGURATION_NAME(rootProject.libs.netty)
        TEST_IMPLEMENTATION_CONFIGURATION_NAME(rootProject.libs.guava)
        TEST_IMPLEMENTATION_CONFIGURATION_NAME(rootProject.libs.bundles.junit)
    }
}

Fix project root build/libs dir not being cleaned The base plugin is usually applied by the java plugin, but since that has been moved into the platforms, cleaning was no longer applied to the root dir (created and filled by the universal submodule).

import org.gradle.api.plugins.JavaPlugin.TEST_IMPLEMENTATION_CONFIGURATION_NAME

plugins {
    base
    id("via.build-logic")
}

allprojects {
    group = "com.viaversion"
    version = property("projectVersion") as String // from gradle.properties
    description = "Allow newer clients to join older server versions."
}

val platforms = setOf(
    projects.viaversionBukkit,
    projects.viaversionBungee,
    projects.viaversionFabric,
    projects.viaversionSponge,
    projects.viaversionVelocity
).map { it.dependencyProject }

val special = setOf(
    projects.viaversion,
    projects.viaversionApi,
    projects.adventure
).map { it.dependencyProject }

subprojects {
    when (this) {
        in platforms -> plugins.apply("via.platform-conventions")
        in special -> plugins.apply("via.base-conventions")
        else -> plugins.apply("via.standard-conventions")
    }

    dependencies {
        // Note: If manually starting tests doesn't work for you in IJ, change 'Gradle -> Run Tests Using' to 'IntelliJ IDEA'
        TEST_IMPLEMENTATION_CONFIGURATION_NAME(rootProject.libs.netty)
        TEST_IMPLEMENTATION_CONFIGURATION_NAME(rootProject.libs.guava)
        TEST_IMPLEMENTATION_CONFIGURATION_NAME(rootProject.libs.bundles.junit)
    }
}


plugins {
    id("com.android.library")
    kotlin("android")
    kotlin("kapt")
}

android {
    compileSdkVersion(Versions.compileSdkVersion)
    buildToolsVersion(Versions.buildToolsVersion)

    defaultConfig {
        minSdkVersion(Versions.minSdkVersion)
        targetSdkVersion(Versions.targetSdkVersion)
        versionCode = Versions.versionCode
        versionName = Versions.versionName

        testInstrumentationRunner = "android.support.test.runner.AndroidJUnitRunner"

    }

    buildTypes {
        getByName("debug") {
            isTestCoverageEnabled = true
        }
        create("debugMini") {
            initWith(getByName("debug"))
            matchingFallbacks = listOf("debug")
        }
        getByName("release") {
            isMinifyEnabled = false
            proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro")
        }
    }

    sourceSets {
        getByName("main").java.srcDirs("src/main/kotlin")
        getByName("test").java.srcDirs("src/test/kotlin")
        getByName("androidTest").java.srcDirs("src/androidTest/kotlin")
    }

}

dependencies {
    KotlinDependencies.values.forEach { implementation(it) }

    NetworkDependencies.values.forEach { implementation(it) }
}

val add_test_dependencies: groovy.lang.Closure<Any?> by extra
add_test_dependencies(project)

Add RxJava dependency to network module

plugins {
    id("com.android.library")
    kotlin("android")
    kotlin("kapt")
}

android {
    compileSdkVersion(Versions.compileSdkVersion)
    buildToolsVersion(Versions.buildToolsVersion)

    defaultConfig {
        minSdkVersion(Versions.minSdkVersion)
        targetSdkVersion(Versions.targetSdkVersion)
        versionCode = Versions.versionCode
        versionName = Versions.versionName

        testInstrumentationRunner = "android.support.test.runner.AndroidJUnitRunner"

    }

    buildTypes {
        getByName("debug") {
            isTestCoverageEnabled = true
        }
        create("debugMini") {
            initWith(getByName("debug"))
            matchingFallbacks = listOf("debug")
        }
        getByName("release") {
            isMinifyEnabled = false
            proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro")
        }
    }

    sourceSets {
        getByName("main").java.srcDirs("src/main/kotlin")
        getByName("test").java.srcDirs("src/test/kotlin")
        getByName("androidTest").java.srcDirs("src/androidTest/kotlin")
    }

}

dependencies {
    KotlinDependencies.values.forEach { implementation(it) }
    NetworkDependencies.values.forEach { implementation(it) }
    implementation(RxJavaDependencies.rxJava)
}

val add_test_dependencies: groovy.lang.Closure<Any?> by extra
add_test_dependencies(project)


package com.intellij.grazie.config

import com.intellij.util.xmlb.annotations.Property

data class CheckingContext(@Property val isCheckInCommitMessagesEnabled: Boolean = false,
                           @Property val isCheckInStringLiteralsEnabled: Boolean = false,
                           @Property val isCheckInCommentsEnabled: Boolean = false,
                           @Property val isCheckInDocumentationEnabled: Boolean = false)

Enable by default check in documentation and comments for enabled languages.

package com.intellij.grazie.config

import com.intellij.util.xmlb.annotations.Property

data class CheckingContext(@Property val isCheckInCommitMessagesEnabled: Boolean = false,
                           @Property val isCheckInStringLiteralsEnabled: Boolean = false,
                           @Property val isCheckInCommentsEnabled: Boolean = true,
                           @Property val isCheckInDocumentationEnabled: Boolean = true)


package io.ktor.client.engine.cio

import io.ktor.client.engine.*
import io.ktor.network.tls.*
import javax.net.ssl.*

class CIOEngineConfig : HttpClientEngineConfig() {
    val endpoint: EndpointConfig = EndpointConfig()
    val https: HttpsConfig = HttpsConfig()

    var maxConnectionsCount: Int = 1000
}

class EndpointConfig {
    var maxConnectionsPerRoute: Int = 100
    var keepAliveTime: Int = 5000
    var pipelineMaxSize: Int = 20

    var connectTimeout: Int = 5000
    var connectRetryAttempts: Int = 5
}

class HttpsConfig {
    var trustManager: X509TrustManager? = null
    var randomAlgorithm: String = "NativePRNGNonBlocking"
    var cipherSuites: List<CipherSuite> = CIOCipherSuites.SupportedSuites
}

Set default random algorithm from system provided

package io.ktor.client.engine.cio

import io.ktor.client.engine.*
import io.ktor.network.tls.*
import java.security.*
import javax.net.ssl.*

private val DEFAULT_RANDOM: String =
    SecureRandom.getInstanceStrong().algorithm.takeIf { it != "unknown" } ?: "NativePRNGNonBlocking"

class CIOEngineConfig : HttpClientEngineConfig() {
    val endpoint: EndpointConfig = EndpointConfig()
    val https: HttpsConfig = HttpsConfig()

    var maxConnectionsCount: Int = 1000
}

class EndpointConfig {
    var maxConnectionsPerRoute: Int = 100
    var keepAliveTime: Int = 5000
    var pipelineMaxSize: Int = 20

    var connectTimeout: Int = 5000
    var connectRetryAttempts: Int = 5
}

class HttpsConfig {
    var trustManager: X509TrustManager? = null
    var randomAlgorithm: String = DEFAULT_RANDOM
    var cipherSuites: List<CipherSuite> = CIOCipherSuites.SupportedSuites
}


/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
 *
 * 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 com.kotlinnlp.simplednn.core.arrays

import com.kotlinnlp.simplednn.core.functionalities.updatemethods.UpdaterSupportStructure
import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray
import java.io.Serializable

/**
 * The [UpdatableArray] is a wrapper of an [NDArray] extending it with an [updaterSupportStructure]
 *
 */
open class UpdatableArray<NDArrayType: NDArray<NDArrayType>>(open val values: NDArrayType) : Serializable {

  companion object {

    /**
     * Private val used to serialize the class (needed from [Serializable])
     */
    @Suppress("unused")
    private const val serialVersionUID: Long = 1L
  }

  /**
   * The updater support structure to be used in combination with [com.kotlinnlp.simplednn.core.functionalities.updatemethods]
   */
  var updaterSupportStructure: UpdaterSupportStructure? = null
}

Set updaterSupportStructure var as lateinit

/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
 *
 * 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 com.kotlinnlp.simplednn.core.arrays

import com.kotlinnlp.simplednn.core.functionalities.updatemethods.UpdaterSupportStructure
import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray
import java.io.Serializable

/**
 * The [UpdatableArray] is a wrapper of an [NDArray] extending it with an [updaterSupportStructure]
 *
 */
open class UpdatableArray<NDArrayType: NDArray<NDArrayType>>(open val values: NDArrayType) : Serializable {

  companion object {

    /**
     * Private val used to serialize the class (needed from [Serializable])
     */
    @Suppress("unused")
    private const val serialVersionUID: Long = 1L
  }

  /**
   * The updater support structure used by [com.kotlinnlp.simplednn.core.functionalities.updatemethods].
   */
  lateinit var updaterSupportStructure: UpdaterSupportStructure
}


package net.yuzumone.bergamio.util

import android.content.Context

class PreferenceUtil(context: Context) {

    private val filename = "net.yuzumone.bergamio.pref"
    private val preference = context.getSharedPreferences(filename, 0)
    private val TOKEN = "token"
    private val EXPIRE = "expire"

    var token: String
    get() = preference.getString(TOKEN, null)
    set(value) = preference.edit().putString(TOKEN, value).apply()

    val hasAvailableToken: Boolean
    get() {
        if (token == "" && expire == 0L) {
            return false
        }
        val now = System.currentTimeMillis() / 1000L
        return (now < expire) && (token != "")
    }

    var expire: Long
    get() = preference.getLong(EXPIRE, 0L)
    set(value) {
        val now = System.currentTimeMillis() / 1000L
        val tile = now + value
        preference.edit().putLong(EXPIRE, tile).apply()
    }
}

Change defValue to empty string

package net.yuzumone.bergamio.util

import android.content.Context

class PreferenceUtil(context: Context) {

    private val filename = "net.yuzumone.bergamio.pref"
    private val preference = context.getSharedPreferences(filename, 0)
    private val TOKEN = "token"
    private val EXPIRE = "expire"

    var token: String
    get() = preference.getString(TOKEN, "")
    set(value) = preference.edit().putString(TOKEN, value).apply()

    val hasAvailableToken: Boolean
    get() {
        if (token == "" && expire == 0L) {
            return false
        }
        val now = System.currentTimeMillis() / 1000L
        return (now < expire) && (token != "")
    }

    var expire: Long
    get() = preference.getLong(EXPIRE, 0L)
    set(value) {
        val now = System.currentTimeMillis() / 1000L
        val tile = now + value
        preference.edit().putLong(EXPIRE, tile).apply()
    }
}


package net.bjoernpetersen.musicbot.api.player

import nl.jqno.equalsverifier.EqualsVerifier
import org.junit.jupiter.api.Test

class SongTest {
    @Test
    fun equalsContract() {
        EqualsVerifier.forClass(Song::class.java)
            .withOnlyTheseFields("id", "provider")
            .verify()
    }
}


package de.markusfisch.android.binaryeye.app

import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator

fun Vibrator.vibrate() {
	if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
		@Suppress("DEPRECATION")
		this.vibrate(100)
	} else {
		this.vibrate(VibrationEffect.createOneShot(100, 10))
	}
}

Fix vibrating for Android O and higher

package de.markusfisch.android.binaryeye.app

import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator

private const val MILLISECONDS = 100L

fun Vibrator.vibrate() {
	if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
		@Suppress("DEPRECATION")
		this.vibrate(MILLISECONDS)
	} else {
		this.vibrate(VibrationEffect.createOneShot(
			MILLISECONDS,
			VibrationEffect.DEFAULT_AMPLITUDE)
		)
	}
}


package com.felipecosta.kotlinrxjavasample.di

import android.app.Application
import com.felipecosta.kotlinrxjavasample.data.CacheDataRepository
import com.felipecosta.kotlinrxjavasample.data.DataRepository
import com.felipecosta.kotlinrxjavasample.data.NetworkDataRepository
import com.felipecosta.kotlinrxjavasample.data.SimpleDiskCache
import dagger.Module
import dagger.Provides
import io.reactivex.Scheduler
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.io.File
import javax.inject.Singleton

@Module
class AppModule(private val application: Application) {

    @Singleton
    @Provides
    fun providesDiskCache(): SimpleDiskCache {
        val fileCache = File(application.filesDir, "disk_cache")
        return SimpleDiskCache.open(fileCache, 1, Integer.MAX_VALUE.toLong())
    }

    @Singleton
    @Provides
    fun providesDataRepository(cache: SimpleDiskCache): DataRepository {
        return CacheDataRepository(NetworkDataRepository(), cache)
    }
}

Use a cache directory for the disk cache

package com.felipecosta.kotlinrxjavasample.di

import android.app.Application
import com.felipecosta.kotlinrxjavasample.data.CacheDataRepository
import com.felipecosta.kotlinrxjavasample.data.DataRepository
import com.felipecosta.kotlinrxjavasample.data.NetworkDataRepository
import com.felipecosta.kotlinrxjavasample.data.SimpleDiskCache
import dagger.Module
import dagger.Provides
import io.reactivex.Scheduler
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.io.File
import javax.inject.Singleton

@Module
class AppModule(private val application: Application) {

    @Singleton
    @Provides
    fun providesDiskCache(): SimpleDiskCache {
        val fileCache = File(application.cacheDir, "disk_cache")
        return SimpleDiskCache.open(fileCache, 1, Integer.MAX_VALUE.toLong())
    }

    @Singleton
    @Provides
    fun providesDataRepository(cache: SimpleDiskCache): DataRepository {
        return CacheDataRepository(NetworkDataRepository(), cache)
    }
}


Add inline trace function which handles start/end calls.

/*
 * Copyright (C) 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 androidx.os

import android.os.Trace
import android.support.annotation.RequiresApi

/**
 * Wrap the specified `block` in calls to [Trace.beginSection] (with the supplied `sectionName`)
 * and [Trace.endSection].
 */
@RequiresApi(18)
inline fun <T> trace(sectionName: String, block: () -> T): T {
    Trace.beginSection(sectionName)
    try {
        return block()
    } finally {
        Trace.endSection()
    }
}


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

import com.intellij.diagnostic.PluginException
import com.intellij.openapi.extensions.PluginId

interface ActionStubBase {
  val id: String
  val pluginId: PluginId?
  val iconPath: String?
}

class ActionGroupStub(
  override val id: String,
  val actionClass: String,
  val classLoader: ClassLoader,
  override val pluginId: PluginId
) : DefaultActionGroup(), ActionStubBase {

  var popupDefinedInXml = false

  override var iconPath: String? = null

  fun initGroup(target: ActionGroup) {
    ActionStub.copyTemplatePresentation(templatePresentation, target.templatePresentation)
    val children = getChildren(null)
    if (children.isNotEmpty()) {
      val defaultActionGroup = target as? DefaultActionGroup
                               ?: throw PluginException(
                                 "Action group class must extend DefaultActionGroup for the group to accept children: $actionClass",
                                 pluginId)
      defaultActionGroup.addAll(children.toList())
    }
    if (popupDefinedInXml) {
      target.isPopup = isPopup
    }
  }
}

Copy shortcut from stub to actual action group (e.g. "Database tools" action group has a shortcut assigned)

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

import com.intellij.diagnostic.PluginException
import com.intellij.openapi.extensions.PluginId

interface ActionStubBase {
  val id: String
  val pluginId: PluginId?
  val iconPath: String?
}

class ActionGroupStub(
  override val id: String,
  val actionClass: String,
  val classLoader: ClassLoader,
  override val pluginId: PluginId
) : DefaultActionGroup(), ActionStubBase {

  var popupDefinedInXml = false

  override var iconPath: String? = null

  fun initGroup(target: ActionGroup) {
    ActionStub.copyTemplatePresentation(templatePresentation, target.templatePresentation)
    target.shortcutSet = shortcutSet
    val children = getChildren(null)
    if (children.isNotEmpty()) {
      val defaultActionGroup = target as? DefaultActionGroup
                               ?: throw PluginException(
                                 "Action group class must extend DefaultActionGroup for the group to accept children: $actionClass",
                                 pluginId)
      defaultActionGroup.addAll(children.toList())
    }
    if (popupDefinedInXml) {
      target.isPopup = isPopup
    }
  }
}


package fi.evident.apina.utils

import java.util.Locale

fun propertyNameForGetter(getterName: String): String =
    when {
        // Value/inline classes result in name suffixed with hash
        getterName.contains("-") -> propertyNameForSimpleGetter(getterName.substringBefore('-'))
        else -> propertyNameForSimpleGetter(getterName)
    }

private fun propertyNameForSimpleGetter(getterName: String): String =
    when {
        getterName.startsWith("get") -> getterName.removePrefix("get")
            .replaceFirstChar { it.lowercase(Locale.getDefault()) }
        getterName.startsWith("is") -> getterName.removePrefix("is")
            .replaceFirstChar { it.lowercase(Locale.getDefault()) }
        else -> error("not a valid name for getter $getterName")
    }

Revert removal of decapitalize, caused apina generation task to fail with gradle 6.8

package fi.evident.apina.utils

fun propertyNameForGetter(getterName: String): String =
    when {
        // Value/inline classes result in name suffixed with hash
        getterName.contains("-") -> propertyNameForSimpleGetter(getterName.substringBefore('-'))
        else -> propertyNameForSimpleGetter(getterName)
    }

private fun propertyNameForSimpleGetter(getterName: String): String =
    when {
        getterName.startsWith("get") -> getterName.removePrefix("get").decapitalize()
        getterName.startsWith("is") -> getterName.removePrefix("is").decapitalize()
        else -> error("not a valid name for getter $getterName")
    }


package de.techdev.pocket.api

/**
 * Basic exception for all API-related errors
 *
 * @author Alexander Hanschke
 */
class PocketException(message: String) : RuntimeException(message)


Add benchmark test for parsing bootstrap data

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

package com.google.samples.apps.iosched.benchmark

import androidx.benchmark.junit4.BenchmarkRule
import androidx.benchmark.junit4.measureRepeated
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.samples.apps.iosched.shared.data.BootstrapConferenceDataSource
import org.hamcrest.core.IsNot.not
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith

/**
 * Benchmark test for parsing offline data. To keep startup times optimized, this benchmark
 * test is used to monitor potential hot spots when the app first loads content.
 */
@RunWith(AndroidJUnit4::class)
class BootstrapConferenceDataSourceBenchmark {
    @get:Rule
    val benchmarkRule = BenchmarkRule()

    // Parsing JSON data can be quite time consuming. We have custom deserializers to improve the
    // performance. We parse this data when the app starts up which is a critical user path. This
    // benchmark is to ensure we maintain the level of quality around bootstrapping data to minimize
    // the app startup latency. Note that loadAndParseBootstrapData() also normalizes after it has
    // been parsed.
    @Test
    fun benchmark_json_parsing() = benchmarkRule.measureRepeated {
        BootstrapConferenceDataSource.loadAndParseBootstrapData()
    }
}


package cn.yiiguxing.plugin.translate.action

import cn.yiiguxing.plugin.translate.util.Plugin
import com.intellij.ide.AppLifecycleListener
import com.intellij.ide.plugins.DynamicPluginListener
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionStub
import com.intellij.openapi.actionSystem.Constraints
import com.intellij.openapi.actionSystem.impl.ActionManagerImpl

class TitleBarActionRegistrar : AppLifecycleListener, DynamicPluginListener {

    override fun appFrameCreated(commandLineArgs: MutableList<String>) {
        registerAction()
    }

    override fun pluginLoaded(pluginDescriptor: IdeaPluginDescriptor) {
        registerAction()
    }

    private fun registerAction() {
        val actionManager = ActionManager.getInstance() as ActionManagerImpl
        val action = actionManager.getAction(TRANSLATION_TITLE_BAR_ACTION_ID) ?: return
        val name = if (action is ActionStub) action.className else action.javaClass.name
        val group = actionManager.getParentGroup(TITLE_BAR_ACTION_GROUP_ID, name, Plugin.descriptor) ?: return
        actionManager.addToGroup(group, action, Constraints.FIRST)
    }

    companion object {
        private const val TRANSLATION_TITLE_BAR_ACTION_ID = "TranslationTitleBar"
        private const val TITLE_BAR_ACTION_GROUP_ID = "ExperimentalToolbarActions"
    }

}

Fix title bar action group ID not registered exception

package cn.yiiguxing.plugin.translate.action

import com.intellij.ide.AppLifecycleListener
import com.intellij.ide.plugins.DynamicPluginListener
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.Constraints
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.actionSystem.impl.ActionManagerImpl

class TitleBarActionRegistrar : AppLifecycleListener, DynamicPluginListener {

    override fun appFrameCreated(commandLineArgs: MutableList<String>) {
        registerAction()
    }

    override fun pluginLoaded(pluginDescriptor: IdeaPluginDescriptor) {
        registerAction()
    }

    private fun registerAction() {
        val actionManager = ActionManager.getInstance() as ActionManagerImpl
        val group = actionManager.getAction(TITLE_BAR_ACTION_GROUP_ID) as? DefaultActionGroup ?: return
        val action = actionManager.getAction(TRANSLATION_TITLE_BAR_ACTION_ID) ?: return
        actionManager.addToGroup(group, action, Constraints.FIRST)
    }

    companion object {
        private const val TRANSLATION_TITLE_BAR_ACTION_ID = "TranslationTitleBar"
        private const val TITLE_BAR_ACTION_GROUP_ID = "ExperimentalToolbarActions"
    }

}


package com.anthonycr.mezzanine.utils

import javax.annotation.processing.Messager
import javax.lang.model.element.Element
import javax.tools.Diagnostic.Kind

/**
 * Utils to communicate with the compiler.
 */
object MessagerUtils {

    lateinit var messager: Messager

    /**
     * Report an error to the compiler at the specified element.
     *
     * @param element the offending element.
     *
     * @param message the error message.
     */
    fun reportError(element: Element, message: String) =
            messager.printMessage(Kind.ERROR, message, element)

    /**
     * Log info to the compiler to provide context to the process.
     *
     * @param message the message to log.
     */
    fun reportInfo(message: String) = messager.printMessage(Kind.NOTE, "Mezzanine: $message")

}

Swap out use of messager for println until NOTE stops generating warning

package com.anthonycr.mezzanine.utils

import javax.annotation.processing.Messager
import javax.lang.model.element.Element
import javax.tools.Diagnostic.Kind

/**
 * Utils to communicate with the compiler.
 */
object MessagerUtils {

    lateinit var messager: Messager

    /**
     * Report an error to the compiler at the specified element.
     *
     * @param element the offending element.
     *
     * @param message the error message.
     */
    fun reportError(element: Element, message: String) =
            messager.printMessage(Kind.ERROR, message, element)

    /**
     * Log info to the compiler to provide context to the process.
     *
     * @param message the message to log.
     */
    fun reportInfo(message: String) = println("Mezzanine: $message")

}


package org.jetbrains.kotlin.konan.library

import org.jetbrains.kotlin.konan.KonanVersion
import org.jetbrains.kotlin.konan.parseKonanVersion
import org.jetbrains.kotlin.konan.KonanAbiVersion
import org.jetbrains.kotlin.konan.properties.Properties
import org.jetbrains.kotlin.konan.parseKonanAbiVersion

data class KonanLibraryVersioning(
    val libraryVersion: String?,
    val compilerVersion: KonanVersion?,
    val abiVersion: KonanAbiVersion?
)

fun Properties.writeKonanLibraryVersioning(versions: KonanLibraryVersioning) {
    versions.abiVersion ?. let { this.setProperty(KLIB_PROPERTY_ABI_VERSION, it.toString()) }
    versions.libraryVersion ?. let { this.setProperty(KLIB_PROPERTY_LIBRARY_VERSION, it) }
    versions.compilerVersion ?. let { this.setProperty(KLIB_PROPERTY_COMPILER_VERSION, "${versions.compilerVersion}") }
}

fun Properties.readKonanLibraryVersioning(): KonanLibraryVersioning {
    val abiVersion = this.getProperty(KLIB_PROPERTY_ABI_VERSION)?.parseKonanAbiVersion()
    val libraryVersion = this.getProperty(KLIB_PROPERTY_LIBRARY_VERSION)
    val compilerVersion = this.getProperty(KLIB_PROPERTY_COMPILER_VERSION)?.parseKonanVersion()

    return KonanLibraryVersioning(abiVersion = abiVersion, libraryVersion = libraryVersion, compilerVersion = compilerVersion)
}

Print out the complete KonanVersion to klib manifest.

package org.jetbrains.kotlin.konan.library

import org.jetbrains.kotlin.konan.KonanVersion
import org.jetbrains.kotlin.konan.parseKonanVersion
import org.jetbrains.kotlin.konan.KonanAbiVersion
import org.jetbrains.kotlin.konan.properties.Properties
import org.jetbrains.kotlin.konan.parseKonanAbiVersion

data class KonanLibraryVersioning(
    val libraryVersion: String?,
    val compilerVersion: KonanVersion?,
    val abiVersion: KonanAbiVersion?
)

fun Properties.writeKonanLibraryVersioning(versions: KonanLibraryVersioning) {
    versions.abiVersion ?. let { this.setProperty(KLIB_PROPERTY_ABI_VERSION, it.toString()) }
    versions.libraryVersion ?. let { this.setProperty(KLIB_PROPERTY_LIBRARY_VERSION, it) }
    versions.compilerVersion ?. let { this.setProperty(KLIB_PROPERTY_COMPILER_VERSION, "${versions.compilerVersion.toString(true, true)}") }
}

fun Properties.readKonanLibraryVersioning(): KonanLibraryVersioning {
    val abiVersion = this.getProperty(KLIB_PROPERTY_ABI_VERSION)?.parseKonanAbiVersion()
    val libraryVersion = this.getProperty(KLIB_PROPERTY_LIBRARY_VERSION)
    val compilerVersion = this.getProperty(KLIB_PROPERTY_COMPILER_VERSION)?.parseKonanVersion()

    return KonanLibraryVersioning(abiVersion = abiVersion, libraryVersion = libraryVersion, compilerVersion = compilerVersion)
}


package jp.toastkid.yobidashi.notification.widget

import android.app.Notification
import android.content.Context
import android.support.v4.app.NotificationCompat
import android.support.v4.app.NotificationManagerCompat

import jp.toastkid.yobidashi.R

/**
 * Notification widget's launcher.

 * @author toastkidjp
 */
object NotificationWidget {

    /** Notification ID.  */
    private val ID = 1

    /**
     * Show notification widget.
     * @param context
     */
    fun show(context: Context) {
        val notification = makeNotification(context)
        NotificationManagerCompat.from(context).notify(ID, notification)
    }

    private fun makeNotification(context: Context): Notification {
        return NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.ic_search_white)
                .setCustomContentView(RemoteViewsFactory.make(context))
                .setOngoing(true)
                .setAutoCancel(false)
                .build()
    }

    /**
     * Hide notification widget.
     * @param context
     */
    fun hide(context: Context) {
        NotificationManagerCompat.from(context).cancel(ID)
    }

    /**
     * Refresh.
     * @param context
     */
    fun refresh(context: Context) {
        val manager = NotificationManagerCompat.from(context)
        manager.cancel(ID)
        manager.notify(ID, makeNotification(context))
    }
}

Clean up notification widget's code.

package jp.toastkid.yobidashi.notification.widget

import android.app.Notification
import android.content.Context
import android.support.v4.app.NotificationCompat
import android.support.v4.app.NotificationManagerCompat

import jp.toastkid.yobidashi.R

/**
 * Notification widget's launcher.
 *
 * @author toastkidjp
 */
object NotificationWidget {

    /**
     * Notification ID.
     */
    private val ID = 1

    /**
     * Show notification widget.
     * @param context
     */
    fun show(context: Context) {
        NotificationManagerCompat
                .from(context)
                .notify(ID, makeNotification(context))
    }

    /**
     * Make notification widget.
     *
     * @param context
     */
    private fun makeNotification(context: Context): Notification {
        return NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.ic_search_white)
                .setCustomContentView(RemoteViewsFactory.make(context))
                .setOngoing(true)
                .setAutoCancel(false)
                .build()
    }

    /**
     * Hide notification widget.
     * @param context
     */
    fun hide(context: Context) {
        NotificationManagerCompat
                .from(context)
                .cancel(ID)
    }

    /**
     * Refresh.
     * @param context
     */
    fun refresh(context: Context) {
        val manager = NotificationManagerCompat.from(context)
        manager.cancel(ID)
        manager.notify(ID, makeNotification(context))
    }
}


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

import com.intellij.psi.xml.XmlAttribute
import com.intellij.psi.xml.XmlAttributeValue
import com.intellij.psi.xml.XmlTag

val XmlAttributeValue.attribute: XmlAttribute?
    get() = parent as? XmlAttribute

val XmlAttribute.schemaType: String?
    get() = (descriptor?.declaration as? XmlTag)?.getAttributeValue("type")

Support resolving relaxng schemma types.

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

import com.intellij.psi.xml.XmlAttribute
import com.intellij.psi.xml.XmlAttributeValue
import com.intellij.psi.xml.XmlTag

val XmlAttributeValue.attribute: XmlAttribute?
    get() = parent as? XmlAttribute

val XmlAttribute.schemaType: String?
    get() {
        val tag = descriptor?.declaration as? XmlTag
        return when (tag?.namespace) {
            "http://www.w3.org/2001/XMLSchema" -> tag.getAttributeValue("type")
            "http://relaxng.org/ns/structure/1.0" -> tag.subTags.mapNotNull {
                when (it.localName) {
                    "data" -> it.getAttributeValue("type")
                    "ref" -> it.getAttributeValue("name")
                    else -> null
                }
            }.firstOrNull()
            else -> null
        }
    }


package chat.rocket.android.chatroom.viewmodel

import android.content.Context
import chat.rocket.android.helper.MessageParser
import chat.rocket.android.server.domain.MessagesRepository
import chat.rocket.core.TokenRepository
import chat.rocket.core.model.Message
import chat.rocket.core.model.Value
import javax.inject.Inject

class MessageViewModelMapper @Inject constructor(private val context: Context,
                                                 private val tokenRepository: TokenRepository,
                                                 private val messageParser: MessageParser,
                                                 private val messagesRepository: MessagesRepository) {

    suspend fun mapToViewModel(message: Message, settings: Map<String, Value<Any>>?) =
            MessageViewModel(context, tokenRepository.get(), message, settings, messageParser, messagesRepository)

    suspend fun mapToViewModelList(messageList: List<Message>, settings: Map<String, Value<Any>>?): List<MessageViewModel> {
        return messageList.map { MessageViewModel(context, tokenRepository.get(), it, settings, messageParser, messagesRepository) }
    }
}

Set suspendable fun to use CommonPool

package chat.rocket.android.chatroom.viewmodel

import android.content.Context
import chat.rocket.android.helper.MessageParser
import chat.rocket.android.server.domain.MessagesRepository
import chat.rocket.core.TokenRepository
import chat.rocket.core.model.Message
import chat.rocket.core.model.Value
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.launch
import javax.inject.Inject

class MessageViewModelMapper @Inject constructor(private val context: Context,
                                                 private val tokenRepository: TokenRepository,
                                                 private val messageParser: MessageParser,
                                                 private val messagesRepository: MessagesRepository) {

    suspend fun mapToViewModel(message: Message, settings: Map<String, Value<Any>>?) = launch(CommonPool) {
        MessageViewModel(this@MessageViewModelMapper.context, tokenRepository.get(), message, settings, messageParser, messagesRepository)
    }

    suspend fun mapToViewModelList(messageList: List<Message>, settings: Map<String, Value<Any>>?): List<MessageViewModel> {
        return messageList.map { MessageViewModel(context, tokenRepository.get(), it, settings, messageParser, messagesRepository) }
    }
}


package org.wordpress.aztec.plugins.visual2html

import android.text.SpannableStringBuilder
import org.wordpress.aztec.plugins.IAztecPlugin

interface ISpanPreprocessor : IAztecPlugin {
    fun beforeSpansProcessed(spannable: SpannableStringBuilder)
}

Add a warning comment to the span preprocessor plugin interface

package org.wordpress.aztec.plugins.visual2html

import android.text.SpannableStringBuilder
import org.wordpress.aztec.plugins.IAztecPlugin

interface ISpanPreprocessor : IAztecPlugin {
    /**
     * Called before the spannable is processed by [org.wordpress.aztec.AztecParser] during span-to-HTML parsing.
     *
     * Warning: This callback should be read-only. The content should not be modified as it can be called by
     * the edit history handler, which would alter the content before the actual parsing.
     */
    fun beforeSpansProcessed(spannable: SpannableStringBuilder)
}