content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
/* * Copyright (c) 2019 Spotify AB. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.spotify.heroic.aggregation.simple import com.spotify.heroic.metric.MetricCollection import java.util.function.Supplier data class FilterableMetrics<T>( val data: T? = null, val metricSupplier: Supplier<MetricCollection>? = null )
aggregation/simple/src/main/java/com/spotify/heroic/aggregation/simple/FilterableMetrics.kt
642421812
// NAME: SomethingBase // TARGET_FILE_NAME: extractToExistingFile.1.kt class <caret>Something { // INFO: {checked: "true"} var independent = 1 }
plugins/kotlin/idea/tests/testData/refactoring/extractSuperclass/extractToExistingFile.kt
998363674
package katas.kotlin.trigram import org.junit.Assert.assertTrue import org.junit.Test import java.io.File import java.util.* /** * Code kata http://codekata.com/kata/kata14-tom-swift-under-the-milkwood/ * Plain text books from http://www.gutenberg.org/wiki/Main_Page */ class TrigramTest { @Test fun `process couple books and generate text based on trigrams from all of them`() { val load = { fileName: String -> File("src/katas/kotlin/trigram/$fileName").readLines() } val words = (load("53970-0.txt") + load("18440-0.txt") + load("39702-0.txt")) .map { it.trim().replace(Regex("[_#—]"), "") } .filter { it.isNotEmpty() } .flatMap { it.split(Regex("\\s+")) } val data = words.windowed(3).fold(HashMap<Pair<String, String>, MutableList<String>>()) { map, trigram -> val key = Pair(trigram[0], trigram[1]) map.putIfAbsent(key, ArrayList()) map[key]!!.add(trigram[2]) map } //data.values.take(100).forEach { printed(it) } val random = Random(123) val entryPoint = data.keys.drop(random.nextInt(data.size)).first() val pairs = generateSequence(entryPoint) { val nextWords = data[it] if (nextWords == null || nextWords.isEmpty()) null else Pair(it.second, nextWords[random.nextInt(nextWords.size)]) } val text = pairs.take(2000).map { it.first }.joinToString(" ") println(text) assertTrue(text.startsWith( "example, there is more fairly representative than such images ever are, but a means of the climate admirable. " + "The productions of the battalion of the velocity of Light as the sequel will shew." )) } }
kotlin/src/katas/kotlin/trigram/Trigram.kt
3190475431
fun foo() { for (i in 1..<caret>10) { } }
plugins/kotlin/idea/tests/testData/wordSelection/ForRange/0.kt
2349122257
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]> * Copyright (c) contributors * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.jonathanxd.kores import com.github.jonathanxd.kores.base.* import com.github.jonathanxd.kores.inspect.InstructionsInspect import com.github.jonathanxd.kores.type.`is` import com.github.jonathanxd.kores.type.getCommonSuperType import com.github.jonathanxd.iutils.container.primitivecontainers.BooleanContainer import java.lang.reflect.Type import java.util.* import java.util.function.Consumer import java.util.stream.Stream /** * Abstract [Instruction] iterable. * * @see ArrayInstructions * @see MutableInstructions */ abstract class Instructions : Iterable<Instruction>, KoresPart { /** * Size of source. */ abstract val size: Int /** * True if is empty, false otherwise. */ val isEmpty: Boolean get() = this.size == 0 /** * True if is not empty, false otherwise. */ val isNotEmpty: Boolean get() = !this.isEmpty /** * Gets element at index [index]. * * @throws IndexOutOfBoundsException If the [index] is either negative or greater than [size]. */ operator fun get(index: Int): Instruction { if (index < 0 || index >= this.size) throw IndexOutOfBoundsException("Index: $index. Size: $size") return this.getAtIndex(index) } /** * Gets element at index [index]. This method should only be called if the index * is in the bounds. */ protected abstract fun getAtIndex(index: Int): Instruction /** * Returns true if this [Instructions] contains [o]. */ abstract operator fun contains(o: Any): Boolean /** * Returns true if this [Instructions] contains all elements of [c]. */ open fun containsAll(c: Collection<*>): Boolean { return c.all { this.contains(it) } } /** * Adds [other] to this [Instructions]. */ abstract operator fun plus(other: Instruction): Instructions /** * Removes [other] from this [Instructions]. */ abstract operator fun minus(other: Instruction): Instructions /** * Adds all [Instruction] of [other] to this [Instructions] */ abstract operator fun plus(other: Iterable<Instruction>): Instructions /** * Removes all [Instruction] of [other] from this [Instructions] */ abstract operator fun minus(other: Iterable<Instruction>): Instructions /** * Returns the index of [o] in this [Instructions]. */ abstract fun indexOf(o: Any): Int /** * Returns the last index of [o] in this [Instructions]. */ abstract fun lastIndexOf(o: Any): Int /** * For each all elements of this [Instructions]. */ abstract override fun forEach(action: Consumer<in Instruction>) /** * Creates an array of [Instruction] of all elements of this [Instructions]. */ abstract fun toArray(): Array<Instruction> /** * Creates a [Spliterator] from elements of this [Instructions]. */ abstract override fun spliterator(): Spliterator<Instruction> /** * Creates an [Iterator] that iterates elements of this [Instructions]. */ abstract override fun iterator(): Iterator<Instruction> /** * Creates a view of this [Instructions] from index [fromIndex] to index [toIndex], * changes to this [Instructions] is reflected in current [Instructions]. */ abstract fun subSource(fromIndex: Int, toIndex: Int): Instructions /** * Creates a immutable [Instructions] with elements of this [Instructions]. */ open fun toImmutable(): Instructions = ArrayInstructions(this.toArray()) /** * Creates a mutable [Instructions] with elements of this [Instructions]. */ open fun toMutable(): MutableInstructions = ListInstructions(this) /** * Creates a [ListIterator] that iterates this [Instructions]. */ abstract fun listIterator(): ListIterator<Instruction> /** * Creates a [ListIterator] that iterates this [Instructions] and starts at [index]. */ abstract fun listIterator(index: Int): ListIterator<Instruction> /** * Creates a [Stream] of this [Instructions]. */ abstract fun stream(): Stream<Instruction> /** * Creates a parallel [Stream] of this [Instructions] (which may or may not be parallel). */ abstract fun parallelStream(): Stream<Instruction> override fun toString(): String = if (this.isEmpty) "Instructions[]" else "Instructions[...]" /** * Factory methods to create immutable [Instructions]. */ companion object { private val EMPTY = emptyArray<Instruction>() private val EMPTY_INSTRUCTIONS = ArrayInstructions(EMPTY) /** * Returns a empty immutable [Instructions]. */ @JvmStatic fun empty(): Instructions { return Instructions.EMPTY_INSTRUCTIONS } /** * Creates a immutable [Instructions] with all elements of [parts]. */ @JvmStatic fun fromArray(parts: Array<Instruction>): Instructions { return ArrayInstructions(parts.clone()) } /** * Creates a immutable [Instructions] with a single [part]. */ @JvmStatic fun fromPart(part: Instruction): Instructions { return ArrayInstructions(arrayOf(part)) } /** * Creates a immutable [Instructions] with all elements of vararg [parts]. */ @JvmStatic fun fromVarArgs(vararg parts: Instruction): Instructions { return ArrayInstructions(Array(parts.size, { parts[it] })) } /** * Creates a immutable [Instructions] from elements of [iterable]. */ @Suppress("UNCHECKED_CAST") @JvmStatic fun fromIterable(iterable: Iterable<Instruction>): Instructions { if (iterable is Collection<Instruction>) { return if (iterable.isEmpty()) { empty() } else { ArrayInstructions(iterable.toTypedArray()) } } return ArrayInstructions(iterable.toList().toTypedArray()) } /** * Creates a immutable [Instructions] from elements of generic [iterable]. */ @Suppress("UNCHECKED_CAST") @JvmStatic fun fromGenericIterable(iterable: Iterable<*>): Instructions { if (iterable is Collection<*>) { return if (iterable.isEmpty()) { empty() } else { ArrayInstructions((iterable as Collection<Instruction>).toTypedArray()) } } return ArrayInstructions((iterable as Iterable<Instruction>).toList().toTypedArray()) } /** * Creates a immutable [Instructions] with all elements of [Instructions] of [iterable]. */ @Suppress("UNCHECKED_CAST") @JvmStatic fun fromInstructionsIterable(iterable: Iterable<Instructions>): Instructions { if (iterable is Collection<Instructions>) { return if (iterable.isEmpty()) { empty() } else { ArrayInstructions(iterable.flatMap { it }.toTypedArray()) } } return ArrayInstructions(iterable.flatMap { it }.toTypedArray()) } } } /** * Insert element `toInsert` in `source` after element determined by `predicate` or at end of source if not found. * @param predicate Predicate to determine element * @param toInsert Element to insert after element determined by `predicate` * @return `source` */ fun Instructions.insertAfterOrEnd( predicate: (Instruction) -> Boolean, toInsert: Instructions ): MutableInstructions { val any = BooleanContainer.of(false) val result = this.insertAfter({ codePart -> if (predicate(codePart)) { any.toTrue() return@insertAfter true } false }, toInsert) if (!any.get()) { result.addAll(toInsert) } return result } /** * Insert element `toInsert` in `source` before element determined by `predicate` or at end of source if not found. * * @param predicate Predicate to determine element * @param toInsert Element to insert after element determined by `predicate` * @return `source` */ fun Instructions.insertBeforeOrEnd( predicate: (Instruction) -> Boolean, toInsert: Instructions ): MutableInstructions { val any = BooleanContainer.of(false) val result = this.insertBefore({ codePart -> if (predicate(codePart)) { any.toTrue() true } else false }, toInsert) if (!any.get()) { result.addAll(toInsert) } return result } /** * Insert element `toInsert` in `source` after element determined by `predicate` or at start of source if not found. * @param predicate Predicate to determine element * @param toInsert Element to insert after element determined by `predicate` * @return `source` */ fun Instructions.insertAfterOrStart( predicate: (Instruction) -> Boolean, toInsert: Instructions ): MutableInstructions { val any = BooleanContainer.of(false) val result = this.insertAfter({ codePart -> if (predicate(codePart)) { any.toTrue() return@insertAfter true } false }, toInsert) if (!any.get()) { result.addAll(0, toInsert) } return result } /** * Insert element `toInsert` in `source` before element determined by `predicate` or at start of source if not found. * * @param predicate Predicate to determine element * @param toInsert Element to insert after element determined by `predicate` * @return `source` */ fun Instructions.insertBeforeOrStart( predicate: (Instruction) -> Boolean, toInsert: Instructions ): MutableInstructions { val any = BooleanContainer.of(false) val result = this.insertBefore({ codePart -> if (predicate(codePart)) { any.toTrue() true } else false }, toInsert) if (!any.get()) { result.addAll(0, toInsert) } return result } /** * Insert element `toInsert` in `source` after element determined by `predicate` * * @param predicate Predicate to determine element * @param toInsert Element to insert after element determined by `predicate` * @return `source` */ fun Instructions.insertAfter( predicate: (Instruction) -> Boolean, toInsert: Instructions ): MutableInstructions { val any = BooleanContainer.of(false) return this.visit({ part, location, codeParts -> if (any.get()) return@visit if (location == Location.AFTER) { if (predicate(part)) { codeParts.addAll(toInsert) any.set(true) } } }) } /** * Insert element `toInsert` in `source` before element determined by `predicate` * * @param predicate Predicate to determine element * @param toInsert Element to insert before element determined by `predicate` * @return `source` */ fun Instructions.insertBefore( predicate: (Instruction) -> Boolean, toInsert: Instructions ): MutableInstructions { val any = BooleanContainer.of(false) return this.visit({ part, location, codeParts -> if (any.get()) return@visit if (location == Location.BEFORE) { if (predicate(part)) { codeParts.addAll(toInsert) any.set(true) } } }) } /** * Visit Code Source elements. * * This method create a new [Instructions] and add all elements from `codeSource` * before and after visits each [KoresPart] of `codeSource`. * * When visiting process finish, it will clear `codeSource` and add all elements from new * [Instructions] * * @param consumer Consumer * @return Result source. */ fun Instructions.visit(consumer: (Instruction, Location, MutableInstructions) -> Unit): MutableInstructions { val returnSource = ListInstructions() for (codePart in this) { consumeIfExists( codePart, { codePart0 -> consumer(codePart0, Location.BEFORE, returnSource) }) returnSource.add(codePart) consumeIfExists( codePart, { codePart0 -> consumer(codePart0, Location.AFTER, returnSource) }) } return returnSource } private fun consumeIfExists(part: Instruction, sourceConsumer: (Instruction) -> Unit) { if (part is BodyHolder) { for (codePart in part.body) { consumeIfExists(codePart, sourceConsumer) } } else { sourceConsumer(part) } } /** * Find an element in a code source. (Highly recommended to use [InstructionsInspect] instead of this. * * @param predicate Predicate. * @param function Mapper. * @param U Mapped return type. * @return List of mapped parts. */ fun <U> Instructions.find( predicate: (Instruction) -> Boolean, function: (Instruction) -> U ): List<U> { val list = ArrayList<U>() for (codePart in this) { if (codePart is Instructions) { list.addAll(this.find(predicate, function)) } else { if (predicate(codePart)) { list.add(function(codePart)) } } } return list } /** * Tries to determine which type this [Instructions] collection leaves on stack or returns, * if this `source` leaves two different types (ex, [String] and [List]), the returned type is * [Any], if source leaves two different primitive types, or an object type and a primitive, `null` is returned. * * This function does not check if a value of the returned [Type] will be always leaved in stack because this does * not do flow analysis, example of scenario that this function returns a type that may not be leaved: * * ``` * if (a) { * "Hello" * } else {} * ``` * * This function will return [String], but this expression does not leave [String] in stack in all cases. */ /** * Returns the type that this [Instructions] leaves on stack. * * This function analyzes the last instruction of [Instructions] and infer the type of value leaved on stack. * * Examples: * * For * * ``` * if (a == 9) { * "x" * } else { * "b" * } * ``` * This returns [String] * * For * * ``` * if (a == 9) { * "x" * } else { * Integer.valueOf(0) * } * ``` * * This returns [Object] * * but for: * * ``` * if (a == 9) { * "x" * } else { * } * ``` * * This returns `null`. */ fun Instructions.getLeaveType(): Type? { return this.lastOrNull()?.safeForComparison?.getLeaveType() } /** * Returns the type leaved in stack by this [Instruction] */ fun Instruction.getLeaveType(): Type? { when (this) { is MethodInvocation -> { if (this.target.safeForComparison is New) { return (this.target.safeForComparison as New).localization } else { val rtype = this.spec.typeSpec.returnType if (!rtype.`is`(Types.VOID)) { return rtype } } } is Access -> { when (this) { Access.SUPER -> return Alias.SUPER Access.THIS -> return Alias.THIS } } is IfStatement -> { val bType = this.body.getLeaveType() val eType = this.elseStatement.getLeaveType() return if (bType != null && eType != null) { if (bType.`is`(eType)) bType else getCommonSuperType(bType, eType) } else { null } } is TryStatementBase -> { val btype = this.body.getLeaveType() val types = this.catchStatements.map { it.body.getLeaveType() } val ftype = this.finallyStatement.getLeaveType() return if (btype != null && ftype != null && types.isNotEmpty() && types.all { it != null }) { if (ftype.`is`(btype) && types.filterNotNull().all { it.`is`(btype) }) { btype } else { types.filterNotNull().fold(getCommonSuperType(ftype, btype)) { a, b -> if (a == null) null else getCommonSuperType(a, b) } } } else { null } } is SwitchStatement -> { val types = this.cases.map { it.body.getLeaveType() } return if (types.isNotEmpty() && types.all { it != null }) { types.reduce { acc, type -> if (acc == null || type == null) null else getCommonSuperType(acc, type) } } else { null } } is LocalCode -> return null is BodyHolder -> return this.body.getLeaveType() is Typed -> return this.type } return null } /** * Location to insert element. */ enum class Location { /** * Insert before. */ BEFORE, /** * Insert after. */ AFTER }
src/main/kotlin/com/github/jonathanxd/kores/Instructions.kt
809032021
do return 1 while (true)
plugins/kotlin/j2k/old/tests/testData/fileOrElement/doWhileStatement/whileWithReturn.kt
1873291930
/* * wac-core * Copyright (C) 2016 Martijn Heil * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package tk.martijn_heil.wac_core.craft.vessel interface HasRudder { var heading: Int }
src/main/kotlin/tk/martijn_heil/wac_core/craft/vessel/HasRudder.kt
2867014351
package evoasm.x64 import kasm.x64.* import org.junit.jupiter.api.Test import kasm.x64.GpRegister64.* import kasm.x64.XmmRegister.* import kasm.x64.YmmRegister.* import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.CsvSource import org.junit.jupiter.params.provider.ValueSource import kotlin.test.assertEquals import kotlin.test.assertNotEquals internal class InterpreterTest { private fun <T> operandRegisters(size: Int, registers: List<T>) : List<List<T>> { return List(size){ listOf(registers[it]) } } @ParameterizedTest @ValueSource(strings = ["false", "true"]) fun runAllInstructions(compressOpcodes: Boolean) { val programInput = LongProgramSetInput(1, 2) programInput[0, 0] = 0x1L programInput[0, 1] = 0x2L val defaultOptions = InterpreterOptions.DEFAULT val instructionCount = defaultOptions.instructions.size println(defaultOptions.instructions.size) val options = InterpreterOptions(instructions = defaultOptions.instructions.take(instructionCount), compressOpcodes = compressOpcodes, moveInstructions = defaultOptions.moveInstructions, xmmOperandRegisters = operandRegisters(4, Interpreter.XMM_REGISTERS), ymmOperandRegisters = operandRegisters(4, Interpreter.YMM_REGISTERS), mmOperandRegisters = operandRegisters(3, Interpreter.MM_REGISTERS), gp64OperandRegisters = operandRegisters(3, Interpreter.GP_REGISTERS), gp32OperandRegisters = operandRegisters(3, Interpreter.GP_REGISTERS.map{it.subRegister32}), gp16OperandRegisters = operandRegisters(3, Interpreter.GP_REGISTERS.map{it.subRegister16}), gp8OperandRegisters = operandRegisters(3, Interpreter.GP_REGISTERS.map{it.subRegister8}), unsafe = false ) println(options.instructions.last()) val programSet = ProgramSet(1000, options.instructions.size) val programSetOutput = LongProgramSetOutput(programSet.programCount, programInput) val interpreter = Interpreter(programSet, programInput, programSetOutput, options = options) for(i in 0 until programSet.programCount) { for (j in 0 until programSet.programSize) { programSet[i, j] = interpreter.getOpcode(j) } } val measurements = interpreter.runAndMeasure() println(measurements) println(interpreter.statistics) println("Output: ${programSetOutput[0, 0]}") } @ParameterizedTest @ValueSource(strings = ["false", "true"]) fun addLong(compressOpcodes: Boolean) { val programSize = 5_500_000 val expectedOutput = programSize.toLong() val programInput = LongProgramSetInput(1, 2) programInput[0, 0] = 0x0L programInput[0, 1] = 0x1L //val options = InterpreterOptions.DEFAULT val options = InterpreterOptions(instructions = InstructionGroup.ARITHMETIC_GP64_INSTRUCTIONS.instructions, compressOpcodes = compressOpcodes, moveInstructions = emptyList(), gp64OperandRegisters = operandRegisters(3, Interpreter.GP_REGISTERS), unsafe = false) val programSet = ProgramSet(1, programSize) val programSetOutput = LongProgramSetOutput(programSet.programCount, programInput) val interpreter = Interpreter(programSet, programInput, programSetOutput, options = options) for (j in 0 until programSet.programSize) { programSet[0, j] = interpreter.getOpcode(AddRm64R64, RAX, RBX)!! } run { val output = programSetOutput.getLong(0, 0) assertNotEquals(expectedOutput, output) } val measurements = interpreter.runAndMeasure() println(measurements) run { val output = programSetOutput.getLong(0, 0) assertEquals(expectedOutput, output) } } // @TestFactory // fun addSubLong(): List<DynamicTest> { // return listOf(false, true).flatMap { compressOpcodes -> // listOf(InterpreterOptions.defaultInstructions,InstructionGroup.ARITHMETIC_GP64_INSTRUCTIONS.instructions).map { instructions -> // dynamicTest(listOf(compressOpcodes).toString()) { // addSubLong(compressOpcodes, instructions) // } // } // } // } enum class TestInstructionGroup { ALL_INSTRUCTIONS { override val instructions: List<Instruction> get() = InstructionGroup.all }, ARITHMETIC_GP64_INSTRUCTIONS { override val instructions: List<Instruction> get() = InstructionGroup.ARITHMETIC_GP64_INSTRUCTIONS.instructions } ; abstract val instructions : List<Instruction> } @ParameterizedTest @CsvSource( "false, ALL_INSTRUCTIONS", "true, ALL_INSTRUCTIONS", "false, ARITHMETIC_GP64_INSTRUCTIONS", "true, ARITHMETIC_GP64_INSTRUCTIONS" ) fun addSubLong(compressOpcodes: Boolean, instructionGroup: TestInstructionGroup) { val programSize = 10_000 val expectedOutput = programSize.toLong() val programInput = LongProgramSetInput(1, 2) programInput[0, 0] = 0x0L programInput[0, 1] = 0x1L val options = InterpreterOptions(instructions = instructionGroup.instructions, compressOpcodes = compressOpcodes, xmmOperandRegisters = operandRegisters(4, Interpreter.XMM_REGISTERS), ymmOperandRegisters = operandRegisters(4, Interpreter.YMM_REGISTERS), mmOperandRegisters = operandRegisters(3, Interpreter.MM_REGISTERS), gp64OperandRegisters = operandRegisters(3, Interpreter.GP_REGISTERS), gp32OperandRegisters = operandRegisters(3, Interpreter.GP_REGISTERS.map{it.subRegister32}), gp16OperandRegisters = operandRegisters(3, Interpreter.GP_REGISTERS.map{it.subRegister16}), gp8OperandRegisters = operandRegisters(3, Interpreter.GP_REGISTERS.map{it.subRegister8}), unsafe = false ) val programSet = ProgramSet(2, programSize) val programSetOutput = LongProgramSetOutput(programSet.programCount, programInput) val interpreter = Interpreter(programSet, programInput, programSetOutput, options = options) for (i in 0 until programSet.programSize) { programSet[0, i] = interpreter.getOpcode(AddRm64R64, RAX, RBX)!! } for (i in 0 until programSet.programSize) { programSet[1, i] = interpreter.getOpcode(SubRm64R64, RAX, RBX)!! } run { val output = programSetOutput.getLong(0, 0) assertNotEquals(expectedOutput, output) } val measurements = interpreter.runAndMeasure() println(measurements) run { assertEquals(expectedOutput, programSetOutput.getLong(0, 0)) assertEquals(-expectedOutput, programSetOutput.getLong(1, 0)) } } @Test fun addSubByteVector() { val programSize = 10 val programInput = ByteVectorProgramSetInput(1, 3, VectorSize.BITS_256) val elementCount = programInput.vectorSize.byteSize val expectedOutput = Array(elementCount) { ((it % 4) * programSize / 2).toByte() } programInput[0, 0] = Array(elementCount){0.toByte()} programInput[0, 1] = Array(elementCount){0.toByte()} programInput[0, 2] = Array(elementCount){(it % 4).toByte()} val options = InterpreterOptions(instructions = InstructionGroup.ARITHMETIC_B_AVX_YMM_INSTRUCTIONS.instructions, moveInstructions = listOf(VmovdqaYmmYmmm256), unsafe = false) val programSet = ProgramSet(2, programSize) val programSetOutput = ByteVectorProgramSetOutput(programSet.programCount, programInput, VectorSize.BITS_256) val interpreter = Interpreter(programSet, programInput, programSetOutput, options = options) val interpreterMoveInstruction = interpreter.getOpcode(VmovdqaYmmYmmm256, YMM1, YMM0)!! for (i in 0 until programSet.programSize step 2) { programSet[0, i] = interpreter.getOpcode(VpaddbYmmYmmYmmm256, YMM0, YMM1, YMM2)!! programSet[0, i + 1] = interpreterMoveInstruction } for (i in 0 until programSet.programSize step 2) { programSet[1, i] = interpreter.getOpcode(VpsubbYmmYmmYmmm256, YMM0, YMM1, YMM2)!! programSet[1, i + 1] = interpreterMoveInstruction } run { val output = programSetOutput[0, 0] assertNotEquals(expectedOutput, output) } val measurements = interpreter.runAndMeasure() println(measurements) run { assertEquals(expectedOutput.toList(), programSetOutput[0, 0].toList()) assertEquals(expectedOutput.map{(-it).toByte()}, programSetOutput.get(1, 0).toList()) } } @Test fun addSubIntVector() { val programSize = 10_000_000 val programInput = IntVectorProgramSetInput(1, 3, VectorSize.BITS_256) val elementCount = programInput.vectorSize.byteSize / Int.SIZE_BYTES val expectedOutput = Array(elementCount) { ((it % 4) * programSize / 2) } programInput[0, 0] = Array(elementCount){ 0 } programInput[0, 1] = Array(elementCount){ 0 } programInput[0, 2] = Array(elementCount){ (it % 4) } val options = InterpreterOptions(instructions = InstructionGroup.ARITHMETIC_D_AVX_YMM_INSTRUCTIONS.instructions, moveInstructions = listOf(VmovdqaYmmYmmm256), unsafe = false) val programSet = ProgramSet(2, programSize) val programSetOutput = IntVectorProgramSetOutput(programSet.programCount, programInput, VectorSize.BITS_256) val interpreter = Interpreter(programSet, programInput, programSetOutput, options = options) val interpreterMoveInstruction = interpreter.getOpcode(VmovdqaYmmYmmm256, YMM1, YMM0)!! for (i in 0 until programSet.programSize step 2) { programSet[0, i] = interpreter.getOpcode(VpadddYmmYmmYmmm256, YMM0, YMM1, YMM2)!! programSet[0, i + 1] = interpreterMoveInstruction } for (i in 0 until programSet.programSize step 2) { programSet[1, i] = interpreter.getOpcode(VpsubdYmmYmmYmmm256, YMM0, YMM1, YMM2)!! programSet[1, i + 1] = interpreterMoveInstruction } run { val output = programSetOutput[0, 0] assertNotEquals(expectedOutput, output) } val measurements = interpreter.runAndMeasure() println(measurements) run { assertEquals(expectedOutput.toList(), programSetOutput[0, 0].toList()) assertEquals(expectedOutput.map{ (-it) }, programSetOutput.get(1, 0).toList()) } } @Test fun addSubFloatVector() { val programSize = 1000 val programInput = FloatVectorProgramSetInput(1, 3, VectorSize.BITS_256) val elementCount = programInput.vectorSize.byteSize / 4 val expectedOutput = Array(elementCount) { ((it % 4) * programSize / 2).toFloat() } programInput[0, 0] = Array(elementCount){0.toFloat()} programInput[0, 1] = Array(elementCount){0.toFloat()} programInput[0, 2] = Array(elementCount){(it % 4).toFloat()} val options = InterpreterOptions(instructions = InstructionGroup.ARITHMETIC_PS_AVX_YMM_INSTRUCTIONS.instructions, moveInstructions = listOf(VmovapsYmmYmmm256), unsafe = false) val programSet = ProgramSet(2, programSize) val programSetOutput = FloatVectorProgramSetOutput(programSet.programCount, programInput, VectorSize.BITS_256) val interpreter = Interpreter(programSet, programInput, programSetOutput, options = options) val interpreterMoveInstruction = interpreter.getOpcode(VmovapsYmmYmmm256, YMM1, YMM0)!! val addOpcode = interpreter.getOpcode(VaddpsYmmYmmYmmm256, YMM0, YMM1, YMM2)!! val subOpcode = interpreter.getOpcode(VsubpsYmmYmmYmmm256, YMM0, YMM1, YMM2)!! for (i in 0 until programSet.programSize step 2) { programSet[0, i] = addOpcode programSet[0, i + 1] = interpreterMoveInstruction } for (i in 0 until programSet.programSize step 2) { programSet[1, i] = subOpcode programSet[1, i + 1] = interpreterMoveInstruction } run { val output = programSetOutput[0, 0] assertNotEquals(expectedOutput, output) } val measurements = interpreter.runAndMeasure() println(measurements) run { assertEquals(expectedOutput.toList(), programSetOutput[0, 0].toList()) assertEquals(expectedOutput.map{(-it + 0f).toFloat()}, programSetOutput.get(1, 0).toList()) } } @Test fun addDouble() { val programSize = 100_000 val expectedOutput = programSize.toDouble() val programInput = DoubleProgramSetInput(1, 2) programInput[0, 0] = 0.0 programInput[0, 1] = 1.0 val options = InterpreterOptions(instructions = InstructionGroup.ARITHMETIC_SD_SSE_XMM_INSTRUCTIONS.instructions, moveInstructions = listOf(), unsafe = false) val programSet = ProgramSet(2, programSize) val programSetOutput = DoubleProgramSetOutput(programSet.programCount, programInput) val interpreter = Interpreter(programSet, programInput, programSetOutput, options = options) val opcode = interpreter.getOpcode(AddsdXmm0To63Xmmm64, XMM0, XMM1)!! for (j in 0 until programSet.programSize) { programSet[0, j] = opcode } run { val output = programSetOutput.getDouble(0, 0) assertNotEquals(expectedOutput, output) } val measurements = interpreter.runAndMeasure() println(measurements) run { assertEquals(expectedOutput, programSetOutput[0, 0]) } } @Test fun addSubDoubleWithMultipleInputs() { val programSize = 100_000 val factor = 4.0; val expectedOutput = programSize.toDouble() val programInput = DoubleProgramSetInput(2, 2) programInput[0, 0] = 0.0 programInput[0, 1] = 1.0 programInput[1, 0] = 0.0 programInput[1, 1] = factor val options = InterpreterOptions(instructions = InstructionGroup.ARITHMETIC_SD_SSE_XMM_INSTRUCTIONS.instructions, moveInstructions = listOf(), unsafe = false) val programSet = ProgramSet(2, programSize) val programSetOutput = DoubleProgramSetOutput(programSet.programCount, programInput) val interpreter = Interpreter(programSet, programInput, programSetOutput, options = options) println("OUTPUT SIZE ${programSetOutput.size}") val addOpcode = interpreter.getOpcode(AddsdXmm0To63Xmmm64, XMM0, XMM1)!! val subOpcode = interpreter.getOpcode(SubsdXmm0To63Xmmm64, XMM0, XMM1)!! for (j in 0 until programSet.programSize) { programSet[0, j] = addOpcode } for (j in 0 until programSet.programSize) { programSet[1, j] = subOpcode } run { val output = programSetOutput.getDouble(0, 0) assertNotEquals(expectedOutput, output) } run { val output = programSetOutput.getDouble(1, 0) assertNotEquals(expectedOutput, -output) } val measurements = interpreter.runAndMeasure() println(measurements) run { assertEquals(expectedOutput, programSetOutput[0, 0]) assertEquals(expectedOutput * factor, programSetOutput[0, 1]) } run { assertEquals(-expectedOutput, programSetOutput[1, 0]) assertEquals(-expectedOutput * factor, programSetOutput[1, 1]) } } }
test/evoasm/x64/InterpreterTest.kt
3243541857
package jp.juggler.subwaytooter import androidx.test.platform.app.InstrumentationRegistry import androidx.test.runner.AndroidJUnit4 import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith // Android instrumentation test は run configuration を編集しないと Empty tests とかいうエラーになります @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext Assert.assertEquals("jp.juggler.subwaytooter", appContext.packageName) } }
app/src/androidTest/java/jp/juggler/subwaytooter/ExampleInstrumentedTest.kt
1846475824
package com.seancheey.resources import java.io.* /** * Created by Seancheey on 02/06/2017. * GitHub: https://github.com/Seancheey */ object Resources { val components_json: String get() = getResourceString("dat/components.json")!! val errorImageInStream: InputStream get() = getResourceInStream("dat/error.png")!! val noRobotImageInStream: InputStream get() = getResourceInStream("dat/norobot.png") ?: errorImageInStream val arrowImageInStream: InputStream get() = getResourceInStream("dat/arrow.png") ?: errorImageInStream val titleImageInStream: InputStream get() = getResourceInStream("dat/title.png") ?: errorImageInStream val transparentImageInStream: InputStream get() = getResourceInStream("dat/transparent.png") ?: errorImageInStream fun getResourceString(path: String): String? { try { val buffReader = BufferedReader(InputStreamReader(getResourceInStream(path)) as Reader) val strBuilder = StringBuilder() while (true) { val line = buffReader.readLine() ?: break strBuilder.append("$line\n") } return strBuilder.toString() } catch (e: IOException) { return null } } fun getResourceInStream(path: String): InputStream? = javaClass.getResourceAsStream(path) }
src/com/seancheey/resources/Resources.kt
1850281485
package com.seancheey.game import com.seancheey.game.model.Node import java.io.Serializable /** * Created by Seancheey on 05/06/2017. * GitHub: https://github.com/Seancheey */ class ActionTree(private val actions: MutableMap<Int, Action>) : Serializable { constructor(vararg pairs: Pair<Int, Action>) : this(mutableMapOf(*pairs)) fun putAction(action: Action, type: Int): Unit { actions[type] = action } fun executeAll(node: Node) { val toDelete = arrayListOf<Int>() for ((key, action) in actions.entries) { if (!action.discard) { action.execute(node) } else { toDelete.add(key) } } for (del in toDelete) { actions.remove(del) } } }
src/com/seancheey/game/ActionTree.kt
203716350
package com.mgaetan89.showsrage.extension.preferences import android.content.SharedPreferences import android.support.test.InstrumentationRegistry import android.support.test.rule.ActivityTestRule import android.support.test.runner.AndroidJUnit4 import com.mgaetan89.showsrage.TestActivity import com.mgaetan89.showsrage.extension.Fields import com.mgaetan89.showsrage.extension.getPreferences import com.mgaetan89.showsrage.extension.getServerPassword import org.assertj.core.api.Assertions.assertThat import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class SharedPreferencesExtension_GetServerPasswordTest { @JvmField @Rule val activityRule = ActivityTestRule(TestActivity::class.java, false, false) private lateinit var preference: SharedPreferences @Before fun before() { this.preference = InstrumentationRegistry.getTargetContext().getPreferences() } @Test fun getServerPassword() { this.preference.edit().putString(Fields.SERVER_PASSWORD.field, "serverPassword").apply() val serverPassword = this.preference.getServerPassword() assertThat(serverPassword).isEqualTo("serverPassword") } @Test fun getServerPassword_Empty() { this.preference.edit().putString(Fields.SERVER_PASSWORD.field, "").apply() val serverPassword = this.preference.getServerPassword() assertThat(serverPassword).isEmpty() } @Test fun getServerPassword_Missing() { assertThat(this.preference.contains(Fields.SERVER_PASSWORD.field)).isFalse() val serverPassword = this.preference.getServerPassword() assertThat(serverPassword).isNull() } @Test fun getServerPassword_Null() { this.preference.edit().putString(Fields.SERVER_PASSWORD.field, null).apply() val serverPassword = this.preference.getServerPassword() assertThat(serverPassword).isNull() } @After fun after() { this.preference.edit().clear().apply() } }
app/src/androidTest/kotlin/com/mgaetan89/showsrage/extension/preferences/SharedPreferencesExtension_GetServerPasswordTest.kt
384530962
package xyz.sachil.essence.activity import android.os.Bundle import android.widget.Toast import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupWithNavController import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import xyz.sachil.essence.R import xyz.sachil.essence.databinding.ActivityMainBinding import xyz.sachil.essence.vm.MainViewModel class MainActivity : AppCompatActivity() { companion object { private const val TAG = "MainActivity" } private var isReadyToExit = false private val viewModel: MainViewModel by viewModels() private lateinit var viewBinding: ActivityMainBinding private val fragments = setOf( R.id.menu_navigation_essence, R.id.menu_navigation_article, R.id.menu_navigation_weekly_popular, R.id.menu_navigation_girl, R.id.menu_navigation_settings ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initViews() } //再按一次退出 override fun onBackPressed() { if (isReadyToExit) { super.onBackPressed() } else { isReadyToExit = true lifecycleScope.launch(Dispatchers.IO) { delay(3500) isReadyToExit = false } Toast.makeText(this, R.string.exit_app_help_toast, Toast.LENGTH_LONG).show() } } private fun initViews() { //使用viewBinding代替kotlin-android-extensions插件和findViewById方法 viewBinding = ActivityMainBinding.inflate(layoutInflater) setContentView(viewBinding.root) setSupportActionBar(viewBinding.toolBar) supportActionBar?.setDisplayShowTitleEnabled(false) val navHostFragment = supportFragmentManager.findFragmentById(R.id.fragmentContainer) as NavHostFragment val navController = navHostFragment.navController // val navigator = FixedFragmentNavigator(this,supportFragmentManager,navHostFragment.id) // navController.navigatorProvider.addNavigator(navigator) // navController.setGraph(R.navigation.navigation_main) val appBarConfiguration = AppBarConfiguration.Builder(fragments).build() viewBinding.toolBar.setupWithNavController( navController, appBarConfiguration ) viewBinding.bottomNavigation.setupWithNavController(navController) } }
app/src/main/java/xyz/sachil/essence/activity/MainActivity.kt
2477715266
package top.zbeboy.isy.web.data.school import org.springframework.stereotype.Controller import org.springframework.ui.ModelMap import org.springframework.util.ObjectUtils import org.springframework.util.StringUtils import org.springframework.validation.BindingResult import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.ResponseBody import top.zbeboy.isy.domain.tables.pojos.School import top.zbeboy.isy.service.data.SchoolService import top.zbeboy.isy.web.common.MethodControllerCommon import top.zbeboy.isy.web.util.AjaxUtils import top.zbeboy.isy.web.util.DataTablesUtils import top.zbeboy.isy.web.util.SmallPropsUtils import top.zbeboy.isy.web.vo.data.school.SchoolVo import java.util.* import javax.annotation.Resource import javax.servlet.http.HttpServletRequest import javax.validation.Valid /** * Created by zbeboy 2017-12-01 . **/ @Controller open class SchoolController { @Resource open lateinit var schoolService: SchoolService @Resource open lateinit var methodControllerCommon: MethodControllerCommon /** * 获取全部学校 * * @return 全部学校 json */ @RequestMapping(value = ["/user/schools"], method = [(RequestMethod.GET)]) @ResponseBody fun schools(): AjaxUtils<School> { val ajaxUtils = AjaxUtils.of<School>() val schools = ArrayList<School>() val isDel: Byte = 0 val school = School(0, "请选择学校", isDel) schools.add(school) val schoolRecords = schoolService.findByIsDel(isDel) schoolRecords.mapTo(schools) { School(it.schoolId, it.schoolName, it.schoolIsDel) } return ajaxUtils.success().msg("获取学校数据成功!").listData(schools) } /** * 学校数据 * * @return 学校数据页面 */ @RequestMapping(value = ["/web/menu/data/school"], method = [(RequestMethod.GET)]) fun schoolData(): String { return "web/data/school/school_data::#page-wrapper" } /** * datatables ajax查询数据 * * @param request 请求 * @return datatables数据 */ @RequestMapping(value = ["/web/data/school/data"], method = [(RequestMethod.GET)]) @ResponseBody fun schoolDatas(request: HttpServletRequest): DataTablesUtils<School> { // 前台数据标题 注:要和前台标题顺序一致,获取order用 val headers = ArrayList<String>() headers.add("select") headers.add("school_id") headers.add("school_name") headers.add("school_is_del") headers.add("operator") val dataTablesUtils = DataTablesUtils<School>(request, headers) val records = schoolService.findAllByPage(dataTablesUtils) var schools: List<School> = ArrayList() if (!ObjectUtils.isEmpty(records) && records.isNotEmpty) { schools = records.into(School::class.java) } dataTablesUtils.data = schools dataTablesUtils.setiTotalRecords(schoolService.countAll().toLong()) dataTablesUtils.setiTotalDisplayRecords(schoolService.countByCondition(dataTablesUtils).toLong()) return dataTablesUtils } /** * 学校数据添加 * * @return 添加页面 */ @RequestMapping(value = ["/web/data/school/add"], method = [(RequestMethod.GET)]) fun schoolAdd(): String { return "web/data/school/school_add::#page-wrapper" } /** * 学校数据编辑 * * @param id 学校id * @param modelMap 页面对象 * @return 编辑页面 */ @RequestMapping(value = ["/web/data/school/edit"], method = [(RequestMethod.GET)]) fun schoolEdit(@RequestParam("id") id: Int, modelMap: ModelMap): String { val school = schoolService.findById(id) return if (!ObjectUtils.isEmpty(school)) { modelMap.addAttribute("school", school) "web/data/school/school_edit::#page-wrapper" } else methodControllerCommon.showTip(modelMap, "未查询到相关学校信息") } /** * 保存时检验学校名是否重复 * * @param name 学校名 * @return true 合格 false 不合格 */ @RequestMapping(value = ["/web/data/school/save/valid"], method = [(RequestMethod.POST)]) @ResponseBody fun saveValid(@RequestParam("schoolName") name: String): AjaxUtils<*> { val schoolName = StringUtils.trimWhitespace(name) if (StringUtils.hasLength(schoolName)) { val schools = schoolService.findBySchoolName(schoolName) return if (ObjectUtils.isEmpty(schools)) { AjaxUtils.of<Any>().success().msg("学校名不存在") } else { AjaxUtils.of<Any>().fail().msg("学校名已存在") } } return AjaxUtils.of<Any>().fail().msg("学校名不能为空") } /** * 保存学校信息 * * @param schoolVo 学校 * @param bindingResult 检验 * @return true 保存成功 false 保存失败 */ @RequestMapping(value = ["/web/data/school/save"], method = [(RequestMethod.POST)]) @ResponseBody fun schoolSave(@Valid schoolVo: SchoolVo, bindingResult: BindingResult): AjaxUtils<*> { if (!bindingResult.hasErrors()) { val school = School() var isDel: Byte? = 0 if (null != schoolVo.schoolIsDel && schoolVo.schoolIsDel == 1.toByte()) { isDel = 1 } school.schoolIsDel = isDel school.schoolName = StringUtils.trimWhitespace(schoolVo.schoolName!!) schoolService.save(school) return AjaxUtils.of<Any>().success().msg("保存成功") } return AjaxUtils.of<Any>().fail().msg("填写信息错误,请检查") } /** * 检验编辑时学校名重复 * * @param id 学校id * @param name 学校名 * @return true 合格 false 不合格 */ @RequestMapping(value = ["/web/data/school/update/valid"], method = [(RequestMethod.POST)]) @ResponseBody fun updateValid(@RequestParam("schoolId") id: Int, @RequestParam("schoolName") name: String): AjaxUtils<*> { val schoolName = StringUtils.trimWhitespace(name) val schoolRecords = schoolService.findBySchoolNameNeSchoolId(schoolName, id) return if (schoolRecords.isEmpty()) { AjaxUtils.of<Any>().success().msg("学校名不重复") } else AjaxUtils.of<Any>().fail().msg("学校名重复") } /** * 保存学校更改 * * @param schoolVo 学校 * @param bindingResult 检验 * @return true 更改成功 false 更改失败 */ @RequestMapping(value = ["/web/data/school/update"], method = [(RequestMethod.POST)]) @ResponseBody fun schoolUpdate(@Valid schoolVo: SchoolVo, bindingResult: BindingResult): AjaxUtils<*> { if (!bindingResult.hasErrors() && !ObjectUtils.isEmpty(schoolVo.schoolId)) { val school = schoolService.findById(schoolVo.schoolId!!) if (!ObjectUtils.isEmpty(school)) { var isDel: Byte? = 0 if (!ObjectUtils.isEmpty(schoolVo.schoolIsDel) && schoolVo.schoolIsDel == 1.toByte()) { isDel = 1 } school.schoolIsDel = isDel school.schoolName = StringUtils.trimWhitespace(schoolVo.schoolName!!) schoolService.update(school) return AjaxUtils.of<Any>().success().msg("更改成功") } } return AjaxUtils.of<Any>().fail().msg("更改失败") } /** * 批量更改学校状态 * * @param schoolIds 学校ids * @param isDel is_del * @return true注销成功 */ @RequestMapping(value = ["/web/data/school/update/del"], method = [(RequestMethod.POST)]) @ResponseBody fun schoolUpdateDel(schoolIds: String, isDel: Byte?): AjaxUtils<*> { if (StringUtils.hasLength(schoolIds) && SmallPropsUtils.StringIdsIsNumber(schoolIds)) { schoolService.updateIsDel(SmallPropsUtils.StringIdsToList(schoolIds), isDel) return AjaxUtils.of<Any>().success().msg("更改学校状态成功") } return AjaxUtils.of<Any>().fail().msg("更改学校状态失败") } }
src/main/java/top/zbeboy/isy/web/data/school/SchoolController.kt
3492473019
package com.elpassion.mainframerplugin.common inline fun <reified T : Exception> assertThrows(function: () -> Unit): Exception { try { function.invoke() throw AssertionError("The specified function didn't throw an exception. ") } catch (ex: Exception) { when { T::class.java.isAssignableFrom(ex.javaClass) -> return ex else -> throw AssertionError("Expected ${T::class.simpleName} not thrown. Catched ${ex.javaClass.name}") } } }
src/test/kotlin/com/elpassion/mainframerplugin/common/assertThrows.kt
3559788803
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.actions import com.intellij.openapi.vcs.changes.actions.BaseCommitExecutorAction import git4idea.checkin.GitCommitAndPushExecutor class GitCommitAndPushExecutorAction : BaseCommitExecutorAction() { override val executorId: String = GitCommitAndPushExecutor.ID }
plugins/git4idea/src/git4idea/actions/GitCommitAndPushExecutorAction.kt
690404354
package de.ph1b.audiobook.mvp import android.os.Bundle import androidx.annotation.CallSuper import de.ph1b.audiobook.misc.checkMainThread import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import timber.log.Timber abstract class Presenter<V : Any> { val view: V get() { checkMainThread() return internalView!! } val attached: Boolean get() { checkMainThread() return internalView != null } private var internalView: V? = null private val compositeDisposable = CompositeDisposable() @CallSuper open fun onRestore(savedState: Bundle) { checkMainThread() } fun attach(view: V) { Timber.i("attach $view") checkMainThread() check(internalView == null) { "$internalView already bound." } internalView = view onAttach(view) } fun detach() { Timber.i("detach $internalView") checkMainThread() compositeDisposable.clear() internalView = null } @CallSuper open fun onSave(state: Bundle) { checkMainThread() } open fun onAttach(view: V) {} fun Disposable.disposeOnDetach() { checkMainThread() if (internalView == null) { dispose() } else compositeDisposable.add(this) } }
app/src/main/java/de/ph1b/audiobook/mvp/Presenter.kt
1751418429
package org.runestar.client.api.web.hiscore enum class HiscoreCategory(val label: String) { OVERALL("Overall"), ATTACK("Attack"), DEFENCE("Defence"), STRENGTH("Strength"), HITPOINTS("Hitpoints"), RANGED("Ranged"), PRAYER("Prayer"), MAGIC("Magic"), COOKING("Cooking"), WOODCUTTING("Woodcutting"), FLETCHING("Fletching"), FISHING("Fishing"), FIREMAKING("Firemaking"), CRAFTING("Crafting"), SMITHING("Smithing"), MINING("Mining"), HERBLORE("Herblore"), AGILITY("Agility"), THIEVING("Thieving"), SLAYER("Slayer"), FARMING("Farming"), RUNECRAFT("Runecraft"), HUNTER("Hunter"), CONSTRUCTION("Construction"), LEAGUE_POINTS("League Points"), BOUNTY_HUNTER_HUNTER("Bounty Hunter - Hunter"), BOUNTY_HUNTER_ROGUE("Bounty Hunter - Rogue"), CLUE_SCROLL_ALL("Clue Scrolls (all)"), CLUE_SCROLL_BEGINNER("Clue Scrolls (beginner)"), CLUE_SCROLL_EASY("Clue Scrolls (easy)"), CLUE_SCROLL_MEDIUM("Clue Scrolls (medium)"), CLUE_SCROLL_HARD("Clue Scrolls (hard)"), CLUE_SCROLL_ELITE("Clue Scrolls (elite)"), CLUE_SCROLL_MASTER("Clue Scrolls (master)"), LAST_MAN_STANDING("Last Man Standing"), ABYSSAL_SIRE("Abyssal Sire"), ALCHEMICAL_HYDRA("Alchemical Hydra"), BARROWS_CHESTS("Barrows Chests"), BRYOPHYTA("Bryophyta"), CALLISTO("Callisto"), CERBERUS("Cerberus"), CHAMBERS_OF_XERIC("Chambers of Xeric"), CHAMBERS_OF_XERIC_CHALLENGE_MODE("Chambers of Xeric: Challenge Mode"), CHAOS_ELEMENTAL("Chaos Elemental"), CHAOS_FANATIC("Chaos Fanatic"), COMMANDER_ZILYANA("Commander Zilyana"), CORPOREAL_BEAST("Corporeal Beast"), CRAZY_ARCHAEOLOGIST("Crazy Archaeologist"), DAGANNOTH_PRIME("Dagannoth Prime"), DAGANNOTH_REX("Dagannoth Rex"), DAGANNOTH_SUPREME("Dagannoth Supreme"), DERANGED_ARCHAEOLOGIST("Deranged Archaeologist"), GENERAL_GRAARDOR("General Graardor"), GIANT_MOLE("Giant Mole"), GROTESQUE_GUARDIANS("Grotesque Guardians"), HESPORI("Hespori"), KALPHITE_QUEEN("Kalphite Queen"), KING_BLACK_DRAGON("King Black Dragon"), KRAKEN("Kraken"), KREEARRA("Kree'Arra"), KRIL_TSUTSAROTH("K'ril Tsutsaroth"), MIMIC("Mimic"), NIGHTMARE("Nightmare"), OBOR("Obor"), SARACHNIS("Sarachnis"), SCORPIA("Scorpia"), SKOTIZO("Skotizo"), THE_GAUNTLET("The Gauntlet"), THE_CORRUPTED_GAUNTLET("The Corrupted Gauntlet"), THEATRE_OF_BLOOD("Theatre of Blood"), THERMONUCLEAR_SMOKE_DEVIL("Thermonuclear Smoke Devil"), TZKAL_ZUK("TzKal-Zuk"), TZTOK_JAD("TzTok-Jad"), VENENATIS("Venenatis"), VETION("Vet'ion"), VORKATH("Vorkath"), WINTERTODT("Wintertodt"), ZALCANO("Zalcano"), ZULRAH("Zulrah"), ; }
api/src/main/java/org/runestar/client/api/web/hiscore/HiscoreCategory.kt
620769148
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.causeway.client.kroviz.snapshots.simpleapp1_16_0 import org.apache.causeway.client.kroviz.snapshots.Response object ACTIONS_CREATE : Response() { override val url = "http://localhost:8080/restful/services/simple.SimpleObjectMenu/actions/create" override val str = """{ "id": "create", "memberType": "action", "links": [ { "rel": "self", "href": "http://localhost:8080/restful/services/simple.SimpleObjectMenu/actions/create", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-action\"" }, { "rel": "up", "href": "http://localhost:8080/restful/services/simple.SimpleObjectMenu", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"", "title": "Simple Objects" }, { "rel": "urn:org.restfulobjects:rels/invokeaction=\"create\"", "href": "http://localhost:8080/restful/services/simple.SimpleObjectMenu/actions/create/invoke", "method": "POST", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-action\"", "arguments": { "name": { "value": null } } }, { "rel": "describedby", "href": "http://localhost:8080/restful/domain-types/simple.SimpleObjectMenu/actions/create", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/action-description\"" } ], "extensions": { "actionType": "user", "actionSemantics": "nonIdempotent" }, "parameters": { "name": { "num": 0, "id": "name", "name": "Name", "description": "" } } }""" }
incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/simpleapp1_16_0/ACTIONS_CREATE.kt
175643378
package org.intellij.markdown.flavours.gfm import org.intellij.markdown.MarkdownTokenTypes import org.intellij.markdown.flavours.commonmark.CommonMarkMarkerProcessor import org.intellij.markdown.parser.LookaheadText import org.intellij.markdown.parser.MarkerProcessor import org.intellij.markdown.parser.MarkerProcessorFactory import org.intellij.markdown.parser.ProductionHolder import org.intellij.markdown.parser.constraints.MarkdownConstraints import org.intellij.markdown.parser.sequentialparsers.SequentialParser public class GFMMarkerProcessor(productionHolder: ProductionHolder, constraintsBase: MarkdownConstraints) : CommonMarkMarkerProcessor(productionHolder, constraintsBase) { override fun populateConstraintsTokens(pos: LookaheadText.Position, constraints: MarkdownConstraints, productionHolder: ProductionHolder) { if (constraints !is GFMConstraints || !constraints.hasCheckbox()) { super.populateConstraintsTokens(pos, constraints, productionHolder) return } val line = pos.currentLine var offset = pos.offsetInCurrentLine while (offset < line.length() && line[offset] != '[') { offset++ } if (offset == line.length()) { super.populateConstraintsTokens(pos, constraints, productionHolder) return } val type = when (constraints.getLastType()) { '>' -> MarkdownTokenTypes.BLOCK_QUOTE '.', ')' -> MarkdownTokenTypes.LIST_NUMBER else -> MarkdownTokenTypes.LIST_BULLET } val middleOffset = pos.offset - pos.offsetInCurrentLine + offset val endOffset = Math.min(pos.offset - pos.offsetInCurrentLine + constraints.getCharsEaten(pos.currentLine), pos.nextLineOrEofOffset) productionHolder.addProduction(listOf( SequentialParser.Node(pos.offset..middleOffset, type), SequentialParser.Node(middleOffset..endOffset, GFMTokenTypes.CHECK_BOX) )) } public object Factory : MarkerProcessorFactory { override fun createMarkerProcessor(productionHolder: ProductionHolder): MarkerProcessor<*> { return GFMMarkerProcessor(productionHolder, GFMConstraints.BASE) } } }
src/org/intellij/markdown/flavours/gfm/GFMMarkerProcessor.kt
2294660495
package com.apollographql.apollo3.compiler import com.apollographql.apollo3.annotations.ApolloExperimental import com.apollographql.apollo3.ast.Schema import com.apollographql.apollo3.compiler.introspection.toSchema import com.google.common.truth.Truth.assertThat import okio.Buffer import java.io.File @OptIn(ApolloExperimental::class) internal object TestUtils { internal fun shouldUpdateTestFixtures(): Boolean { return when (System.getProperty("updateTestFixtures")?.trim()) { "on", "true", "1" -> true else -> false } } internal fun shouldUpdateMeasurements(): Boolean { return when (System.getProperty("updateTestFixtures")?.trim()) { "on", "true", "1" -> true else -> false } } internal fun checkTestFixture(actual: File, expected: File) { val actualText = actual.readText() val expectedText = expected.readText() if (actualText != expectedText) { if (shouldUpdateTestFixtures()) { expected.writeText(actualText) } else { throw Exception("""generatedFile content doesn't match the expectedFile content. |If you changed the compiler recently, you need to update the testFixtures. |Run the tests with `-DupdateTestFixtures=true` to do so. |diff ${expected.path} ${actual.path}""".trimMargin()) } } } /** * This allows to run a specific test from the command line by using something like: * * ./gradlew :apollo-compiler:test -testFilter="fragments_with_type_condition" --tests '*Codegen*' */ fun testFilterMatches(value: String): Boolean { val testFilter = System.getProperty("testFilter") ?: return true return Regex(testFilter).containsMatchIn(value) } fun testParametersForGraphQLFilesIn(path: String): Collection<Array<Any>> { return File(path) .walk() .toList() .filter { it.isFile } .filter { it.extension == "graphql" } .filter { testFilterMatches(it.name) } .sortedBy { it.name } .map { arrayOf(it.nameWithoutExtension, it) } } private fun File.replaceExtension(newExtension: String): File { return File(parentFile, "$nameWithoutExtension.$newExtension") } private fun findSchema(dir: File): Schema? { return listOf("graphqls", "sdl", "json").map { File(dir, "schema.$it") } .firstOrNull { it.exists() } ?.let { it.toSchema() } } /** * run the block and checks the result against the .expected file * * @param block: the callback to produce the result. [checkExpected] will try to find a schema * for [graphQLFile] by either looking for a schema with the same name or testing the first * schema.[json|sdl|graphqls] in the hierarchy */ fun checkExpected(graphQLFile: File, block: (Schema?) -> String) { var parent = graphQLFile.parentFile // We're in src/test/validation/operation/... // There's a schema at src/test/validation/schema.json if we go past that, stop var schema: Schema? = null while (parent.name != "test") { schema = findSchema(parent) if (schema != null) { break } parent = parent.parentFile } check (schema != null) { "Cannot find a schema for $graphQLFile" } val actual = block(schema) val expectedFile = File(graphQLFile.parent, graphQLFile.nameWithoutExtension + ".expected") val expected = try { expectedFile.readText() } catch (e: Exception) { null } if (shouldUpdateTestFixtures()) { expectedFile.writeText(actual) } else { assertThat(actual).isEqualTo(expected) } } } internal fun String.buffer() = Buffer().writeUtf8(this)
apollo-compiler/src/test/kotlin/com/apollographql/apollo3/compiler/TestUtils.kt
1327761394
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.intentions import com.intellij.codeInsight.CodeInsightBundle import com.intellij.codeInsight.FileModificationService import com.intellij.codeInsight.generation.OverrideImplementUtil import com.intellij.codeInsight.intention.impl.BaseIntentionAction import com.intellij.ide.util.PsiClassListCellRenderer import com.intellij.ide.util.PsiClassRenderingInfo import com.intellij.ide.util.PsiElementListCellRenderer import com.intellij.java.JavaBundle import com.intellij.openapi.application.runReadAction import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.ui.popup.IPopupChooserBuilder import com.intellij.openapi.ui.popup.PopupChooserBuilder import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.ui.components.JBList import com.intellij.util.IncorrectOperationException import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.asJava.toLightMethods import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.core.overrideImplement.BodyType import org.jetbrains.kotlin.idea.core.overrideImplement.GenerateMembersHandler import org.jetbrains.kotlin.idea.core.overrideImplement.OverrideMemberChooserObject import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress import org.jetbrains.kotlin.idea.refactoring.isAbstract import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors import org.jetbrains.kotlin.idea.util.application.executeCommand import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.getTypeSubstitution import org.jetbrains.kotlin.idea.util.substitute import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.util.findCallableMemberBySignature import javax.swing.ListSelectionModel abstract class ImplementAbstractMemberIntentionBase : SelfTargetingRangeIntention<KtNamedDeclaration>( KtNamedDeclaration::class.java, KotlinBundle.lazyMessage("implement.abstract.member") ) { companion object { private val LOG = Logger.getInstance("#${ImplementAbstractMemberIntentionBase::class.java.canonicalName}") } protected fun findExistingImplementation( subClass: ClassDescriptor, superMember: CallableMemberDescriptor ): CallableMemberDescriptor? { val superClass = superMember.containingDeclaration as? ClassDescriptor ?: return null val substitution = getTypeSubstitution(superClass.defaultType, subClass.defaultType).orEmpty() val signatureInSubClass = superMember.substitute(substitution) as? CallableMemberDescriptor ?: return null val subMember = subClass.findCallableMemberBySignature(signatureInSubClass) return if (subMember?.kind?.isReal == true) subMember else null } protected abstract fun acceptSubClass(subClassDescriptor: ClassDescriptor, memberDescriptor: CallableMemberDescriptor): Boolean private fun findClassesToProcess(member: KtNamedDeclaration): Sequence<PsiElement> { val baseClass = member.containingClassOrObject as? KtClass ?: return emptySequence() val memberDescriptor = member.resolveToDescriptorIfAny() as? CallableMemberDescriptor ?: return emptySequence() fun acceptSubClass(subClass: PsiElement): Boolean { if (!BaseIntentionAction.canModify(subClass)) return false val classDescriptor = when (subClass) { is KtLightClass -> subClass.kotlinOrigin?.resolveToDescriptorIfAny() is KtEnumEntry -> subClass.resolveToDescriptorIfAny() is PsiClass -> subClass.getJavaClassDescriptor() else -> null } ?: return false return acceptSubClass(classDescriptor, memberDescriptor) } if (baseClass.isEnum()) { return baseClass.declarations .asSequence() .filterIsInstance<KtEnumEntry>() .filter(::acceptSubClass) } return HierarchySearchRequest(baseClass, baseClass.useScope, false) .searchInheritors() .asSequence() .filter(::acceptSubClass) } protected abstract fun computeText(element: KtNamedDeclaration): (() -> String)? override fun applicabilityRange(element: KtNamedDeclaration): TextRange? { if (!element.isAbstract()) return null setTextGetter(computeText(element) ?: return null) if (!findClassesToProcess(element).any()) return null return element.nameIdentifier?.textRange } protected abstract val preferConstructorParameters: Boolean private fun implementInKotlinClass(editor: Editor?, member: KtNamedDeclaration, targetClass: KtClassOrObject) { val subClassDescriptor = targetClass.resolveToDescriptorIfAny() ?: return val superMemberDescriptor = member.resolveToDescriptorIfAny() as? CallableMemberDescriptor ?: return val superClassDescriptor = superMemberDescriptor.containingDeclaration as? ClassDescriptor ?: return val substitution = getTypeSubstitution(superClassDescriptor.defaultType, subClassDescriptor.defaultType).orEmpty() val descriptorToImplement = superMemberDescriptor.substitute(substitution) as CallableMemberDescriptor val chooserObject = OverrideMemberChooserObject.create( member.project, descriptorToImplement, descriptorToImplement, BodyType.FromTemplate, preferConstructorParameters ) GenerateMembersHandler.generateMembers(editor, targetClass, listOf(chooserObject), false) } private fun implementInJavaClass(member: KtNamedDeclaration, targetClass: PsiClass) { member.toLightMethods().forEach { OverrideImplementUtil.overrideOrImplement(targetClass, it) } } private fun implementInClass(member: KtNamedDeclaration, targetClasses: List<PsiElement>) { val project = member.project project.executeCommand<Unit>(JavaBundle.message("intention.implement.abstract.method.command.name")) { if (!FileModificationService.getInstance().preparePsiElementsForWrite(targetClasses)) return@executeCommand runWriteAction<Unit> { for (targetClass in targetClasses) { try { val descriptor = OpenFileDescriptor(project, targetClass.containingFile.virtualFile) val targetEditor = FileEditorManager.getInstance(project).openTextEditor(descriptor, true)!! when (targetClass) { is KtLightClass -> targetClass.kotlinOrigin?.let { implementInKotlinClass(targetEditor, member, it) } is KtEnumEntry -> implementInKotlinClass(targetEditor, member, targetClass) is PsiClass -> implementInJavaClass(member, targetClass) } } catch (e: IncorrectOperationException) { LOG.error(e) } } } } } private class ClassRenderer : PsiElementListCellRenderer<PsiElement>() { private val psiClassRenderer = PsiClassListCellRenderer() override fun getComparator(): Comparator<PsiElement> { val baseComparator = psiClassRenderer.comparator return Comparator { o1, o2 -> when { o1 is KtEnumEntry && o2 is KtEnumEntry -> o1.name!!.compareTo(o2.name!!) o1 is KtEnumEntry -> -1 o2 is KtEnumEntry -> 1 o1 is PsiClass && o2 is PsiClass -> baseComparator.compare(o1, o2) else -> 0 } } } override fun getElementText(element: PsiElement?): String? { return when (element) { is KtEnumEntry -> element.name is PsiClass -> psiClassRenderer.getElementText(element) else -> null } } override fun getContainerText(element: PsiElement?, name: String?): String? { return when (element) { is KtEnumEntry -> element.containingClassOrObject?.fqName?.asString() is PsiClass -> PsiClassRenderingInfo.getContainerTextStatic(element) else -> null } } } override fun startInWriteAction(): Boolean = false override fun checkFile(file: PsiFile): Boolean { return true } override fun preparePsiElementForWriteIfNeeded(target: KtNamedDeclaration): Boolean { return true } override fun applyTo(element: KtNamedDeclaration, editor: Editor?) { if (editor == null) throw IllegalArgumentException("This intention requires an editor") val project = element.project val classesToProcess = project.runSynchronouslyWithProgress( JavaBundle.message("intention.implement.abstract.method.searching.for.descendants.progress"), true ) { runReadAction { findClassesToProcess(element).toList() } } ?: return if (classesToProcess.isEmpty()) return classesToProcess.singleOrNull()?.let { return implementInClass(element, listOf(it)) } val renderer = ClassRenderer() val sortedClasses = classesToProcess.sortedWith(renderer.comparator) if (isUnitTestMode()) return implementInClass(element, sortedClasses) val list = JBList(sortedClasses).apply { selectionMode = ListSelectionModel.MULTIPLE_INTERVAL_SELECTION cellRenderer = renderer } val builder = PopupChooserBuilder<PsiElement>(list) renderer.installSpeedSearch(builder as IPopupChooserBuilder<*>) builder .setTitle(CodeInsightBundle.message("intention.implement.abstract.method.class.chooser.title")) .setItemChoosenCallback { val index = list.selectedIndex if (index < 0) return@setItemChoosenCallback @Suppress("UNCHECKED_CAST") implementInClass(element, list.selectedValues.toList() as List<KtClassOrObject>) } .createPopup() .showInBestPositionFor(editor) } } class ImplementAbstractMemberIntention : ImplementAbstractMemberIntentionBase() { override fun computeText(element: KtNamedDeclaration): (() -> String)? = when (element) { is KtProperty -> KotlinBundle.lazyMessage("implement.abstract.property") is KtNamedFunction -> KotlinBundle.lazyMessage("implement.abstract.function") else -> null } override fun acceptSubClass(subClassDescriptor: ClassDescriptor, memberDescriptor: CallableMemberDescriptor): Boolean { return subClassDescriptor.kind != ClassKind.INTERFACE && findExistingImplementation(subClassDescriptor, memberDescriptor) == null } override val preferConstructorParameters: Boolean get() = false } class ImplementAbstractMemberAsConstructorParameterIntention : ImplementAbstractMemberIntentionBase() { override fun computeText(element: KtNamedDeclaration): (() -> String)? { if (element !is KtProperty) return null return KotlinBundle.lazyMessage("implement.as.constructor.parameter") } override fun acceptSubClass(subClassDescriptor: ClassDescriptor, memberDescriptor: CallableMemberDescriptor): Boolean { val kind = subClassDescriptor.kind return (kind == ClassKind.CLASS || kind == ClassKind.ENUM_CLASS) && subClassDescriptor !is JavaClassDescriptor && findExistingImplementation(subClassDescriptor, memberDescriptor) == null } override val preferConstructorParameters: Boolean get() = true override fun applicabilityRange(element: KtNamedDeclaration): TextRange? { if (element !is KtProperty) return null return super.applicabilityRange(element) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ImplementAbstractMemberIntention.kt
584312080
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.github.pullrequest.ui.timeline import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestCommitShort class GHPRTimelineGroupedCommits : GHPRTimelineGroupedItems<GHPullRequestCommitShort>()
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/timeline/GHPRTimelineGroupedCommits.kt
35948207
package com.nononsenseapps.feeder.ui.compose.text import androidx.compose.runtime.Composable import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.VerbatimTtsAnnotation class AnnotatedParagraphStringBuilder { // Private for a reason private val builder: AnnotatedString.Builder = AnnotatedString.Builder() private val poppedComposableStyles = mutableListOf<ComposableStyleWithStartEnd>() val composableStyles = mutableListOf<ComposableStyleWithStartEnd>() val lastTwoChars: MutableList<Char> = mutableListOf() val length: Int get() = builder.length val endsWithWhitespace: Boolean get() { if (lastTwoChars.isEmpty()) { return true } lastTwoChars.peekLatest()?.let { latest -> // Non-breaking space (160) is not caught by trim or whitespace identification if (latest.isWhitespace() || latest.code == 160) { return true } } return false } fun pushVerbatimTtsAnnotation(verbatim: String) = builder.pushTtsAnnotation(VerbatimTtsAnnotation(verbatim)) fun pushStyle(style: SpanStyle): Int = builder.pushStyle(style = style) fun pop(index: Int) = builder.pop(index) fun pushStringAnnotation(tag: String, annotation: String): Int = builder.pushStringAnnotation(tag = tag, annotation = annotation) fun pushComposableStyle( style: @Composable () -> SpanStyle ): Int { composableStyles.add( ComposableStyleWithStartEnd( style = style, start = builder.length ) ) return composableStyles.lastIndex } fun popComposableStyle( index: Int ) { poppedComposableStyles.add( composableStyles.removeAt(index).copy(end = builder.length) ) } fun append(text: String) { if (text.count() >= 2) { lastTwoChars.pushMaxTwo(text.secondToLast()) } if (text.isNotEmpty()) { lastTwoChars.pushMaxTwo(text.last()) } builder.append(text) } fun append(char: Char) { lastTwoChars.pushMaxTwo(char) builder.append(char) } @Composable fun toComposableAnnotatedString(): AnnotatedString { for (composableStyle in poppedComposableStyles) { builder.addStyle( style = composableStyle.style(), start = composableStyle.start, end = composableStyle.end ) } for (composableStyle in composableStyles) { builder.addStyle( style = composableStyle.style(), start = composableStyle.start, end = builder.length ) } return builder.toAnnotatedString() } fun toAnnotatedString(): AnnotatedString { return builder.toAnnotatedString() } } fun AnnotatedParagraphStringBuilder.isEmpty() = lastTwoChars.isEmpty() fun AnnotatedParagraphStringBuilder.isNotEmpty() = lastTwoChars.isNotEmpty() fun AnnotatedParagraphStringBuilder.ensureDoubleNewline() { when { lastTwoChars.isEmpty() -> { // Nothing to do } length == 1 && lastTwoChars.peekLatest()?.isWhitespace() == true -> { // Nothing to do } length == 2 && lastTwoChars.peekLatest()?.isWhitespace() == true && lastTwoChars.peekSecondLatest()?.isWhitespace() == true -> { // Nothing to do } lastTwoChars.peekLatest() == '\n' && lastTwoChars.peekSecondLatest() == '\n' -> { // Nothing to do } lastTwoChars.peekLatest() == '\n' -> { append('\n') } else -> { append("\n\n") } } } private fun AnnotatedParagraphStringBuilder.ensureSingleNewline() { when { lastTwoChars.isEmpty() -> { // Nothing to do } length == 1 && lastTwoChars.peekLatest()?.isWhitespace() == true -> { // Nothing to do } lastTwoChars.peekLatest() == '\n' -> { // Nothing to do } else -> { append('\n') } } } private fun CharSequence.secondToLast(): Char { if (count() < 2) { throw NoSuchElementException("List has less than two items.") } return this[lastIndex - 1] } private fun <T> MutableList<T>.pushMaxTwo(item: T) { this.add(0, item) if (count() > 2) { this.removeLast() } } private fun <T> List<T>.peekLatest(): T? { return this.firstOrNull() } private fun <T> List<T>.peekSecondLatest(): T? { if (count() < 2) { return null } return this[1] } data class ComposableStyleWithStartEnd( val style: @Composable () -> SpanStyle, val start: Int, val end: Int = -1 )
app/src/main/java/com/nononsenseapps/feeder/ui/compose/text/AnnotatedString.kt
2241668488
package org.stepic.droid.storage.dao import android.content.ContentValues import android.database.Cursor import com.google.gson.Gson import org.stepic.droid.storage.operations.DatabaseOperations import org.stepic.droid.storage.structure.DbStructureCourse import org.stepic.droid.util.* import org.stepik.android.cache.video.dao.VideoDao import org.stepik.android.model.Course import org.stepik.android.model.Video import javax.inject.Inject class CourseDaoImpl @Inject constructor( databaseOperations: DatabaseOperations, private val videoDao: VideoDao, private val gson: Gson ) : DaoBase<Course>(databaseOperations) { public override fun getDbName() = DbStructureCourse.TABLE_NAME public override fun getDefaultPrimaryColumn() = DbStructureCourse.Columns.ID public override fun getDefaultPrimaryValue(persistentObject: Course) = persistentObject.id.toString() public override fun parsePersistentObject(cursor: Cursor): Course = Course( id = cursor.getLong(DbStructureCourse.Columns.ID), title = cursor.getString(DbStructureCourse.Columns.TITLE), description = cursor.getString(DbStructureCourse.Columns.DESCRIPTION), cover = cursor.getString(DbStructureCourse.Columns.COVER), acquiredSkills = DbParseHelper.parseStringToStringList(cursor.getString(DbStructureCourse.Columns.ACQUIRED_SKILLS)), certificate = cursor.getString(DbStructureCourse.Columns.CERTIFICATE), requirements = cursor.getString(DbStructureCourse.Columns.REQUIREMENTS), summary = cursor.getString(DbStructureCourse.Columns.SUMMARY), workload = cursor.getString(DbStructureCourse.Columns.WORKLOAD), intro = cursor.getString(DbStructureCourse.Columns.INTRO), introVideo = Video(id = cursor.getLong(DbStructureCourse.Columns.INTRO_VIDEO_ID)), language = cursor.getString(DbStructureCourse.Columns.LANGUAGE), announcements = DbParseHelper.parseStringToLongList(cursor.getString(DbStructureCourse.Columns.ANNOUNCEMENTS)), authors = DbParseHelper.parseStringToLongList(cursor.getString(DbStructureCourse.Columns.AUTHORS)), instructors = DbParseHelper.parseStringToLongList(cursor.getString(DbStructureCourse.Columns.INSTRUCTORS)), sections = DbParseHelper.parseStringToLongList(cursor.getString(DbStructureCourse.Columns.SECTIONS)), previewLesson = cursor.getLong(DbStructureCourse.Columns.PREVIEW_LESSON), previewUnit = cursor.getLong(DbStructureCourse.Columns.PREVIEW_UNIT), courseFormat = cursor.getString(DbStructureCourse.Columns.COURSE_FORMAT), targetAudience = cursor.getString(DbStructureCourse.Columns.TARGET_AUDIENCE), certificateFooter = cursor.getString(DbStructureCourse.Columns.CERTIFICATE_FOOTER), certificateCoverOrg = cursor.getString(DbStructureCourse.Columns.CERTIFICATE_COVER_ORG), totalUnits = cursor.getLong(DbStructureCourse.Columns.TOTAL_UNITS), enrollment = cursor.getLong(DbStructureCourse.Columns.ENROLLMENT), progress = cursor.getString(DbStructureCourse.Columns.PROGRESS), owner = cursor.getLong(DbStructureCourse.Columns.OWNER), readiness = cursor.getDouble(DbStructureCourse.Columns.READINESS), isContest = cursor.getBoolean(DbStructureCourse.Columns.IS_CONTEST), isFeatured = cursor.getBoolean(DbStructureCourse.Columns.IS_FEATURED), isActive = cursor.getBoolean(DbStructureCourse.Columns.IS_ACTIVE), isPublic = cursor.getBoolean(DbStructureCourse.Columns.IS_PUBLIC), isArchived = cursor.getBoolean(DbStructureCourse.Columns.IS_ARCHIVED), isFavorite = cursor.getBoolean(DbStructureCourse.Columns.IS_FAVORITE), isProctored = cursor.getBoolean(DbStructureCourse.Columns.IS_PROCTORED), isInWishlist = cursor.getBoolean(DbStructureCourse.Columns.IS_IN_WISHLIST), isEnabled = cursor.getBoolean(DbStructureCourse.Columns.IS_ENABLED), certificateDistinctionThreshold = cursor.getLong(DbStructureCourse.Columns.CERTIFICATE_DISTINCTION_THRESHOLD), certificateRegularThreshold = cursor.getLong(DbStructureCourse.Columns.CERTIFICATE_REGULAR_THRESHOLD), certificateLink = cursor.getString(DbStructureCourse.Columns.CERTIFICATE_LINK), isCertificateAutoIssued = cursor.getBoolean(DbStructureCourse.Columns.IS_CERTIFICATE_AUTO_ISSUED), isCertificateIssued = cursor.getBoolean(DbStructureCourse.Columns.IS_CERTIFICATE_ISSUED), withCertificate = cursor.getBoolean(DbStructureCourse.Columns.WITH_CERTIFICATE), lastDeadline = cursor.getString(DbStructureCourse.Columns.LAST_DEADLINE), beginDate = cursor.getString(DbStructureCourse.Columns.BEGIN_DATE), endDate = cursor.getString(DbStructureCourse.Columns.END_DATE), slug = cursor.getString(DbStructureCourse.Columns.SLUG), scheduleLink = cursor.getString(DbStructureCourse.Columns.SCHEDULE_LINK), scheduleLongLink = cursor.getString(DbStructureCourse.Columns.SCHEDULE_LONG_LINK), scheduleType = cursor.getString(DbStructureCourse.Columns.SCHEDULE_TYPE), lastStepId = cursor.getString(DbStructureCourse.Columns.LAST_STEP), learnersCount = cursor.getLong(DbStructureCourse.Columns.LEARNERS_COUNT), reviewSummary = cursor.getLong(DbStructureCourse.Columns.REVIEW_SUMMARY), timeToComplete = cursor.getLong(DbStructureCourse.Columns.TIME_TO_COMPLETE), courseOptions = cursor.getString(DbStructureCourse.Columns.OPTIONS)?.toObject(gson), actions = cursor.getString(DbStructureCourse.Columns.ACTIONS)?.toObject(gson), isPaid = cursor.getBoolean(DbStructureCourse.Columns.IS_PAID), price = cursor.getString(DbStructureCourse.Columns.PRICE), currencyCode = cursor.getString(DbStructureCourse.Columns.CURRENCY_CODE), displayPrice = cursor.getString(DbStructureCourse.Columns.DISPLAY_PRICE), priceTier = cursor.getString(DbStructureCourse.Columns.PRICE_TIER), defaultPromoCodeName = cursor.getString(DbStructureCourse.Columns.DEFAULT_PROMO_CODE_NAME), defaultPromoCodePrice = cursor.getString(DbStructureCourse.Columns.DEFAULT_PROMO_CODE_PRICE), defaultPromoCodeDiscount = cursor.getString(DbStructureCourse.Columns.DEFAULT_PROMO_CODE_DISCOUNT), defaultPromoCodeExpireDate = cursor.getDate(DbStructureCourse.Columns.DEFAULT_PROMO_CODE_EXPIRE_DATE) ) public override fun getContentValues(course: Course): ContentValues { val values = ContentValues() values.put(DbStructureCourse.Columns.ID, course.id) values.put(DbStructureCourse.Columns.TITLE, course.title) values.put(DbStructureCourse.Columns.DESCRIPTION, course.description) values.put(DbStructureCourse.Columns.COVER, course.cover) values.put(DbStructureCourse.Columns.ACQUIRED_SKILLS, DbParseHelper.parseStringArrayToString(course.acquiredSkills?.toTypedArray())) values.put(DbStructureCourse.Columns.CERTIFICATE, course.certificate) values.put(DbStructureCourse.Columns.REQUIREMENTS, course.requirements) values.put(DbStructureCourse.Columns.SUMMARY, course.summary) values.put(DbStructureCourse.Columns.WORKLOAD, course.workload) values.put(DbStructureCourse.Columns.INTRO, course.intro) values.put(DbStructureCourse.Columns.INTRO_VIDEO_ID, course.introVideo?.id ?: -1) // todo add complete course entity and remove this hack values.put(DbStructureCourse.Columns.LANGUAGE, course.language) values.put(DbStructureCourse.Columns.ANNOUNCEMENTS, DbParseHelper.parseLongListToString(course.announcements)) values.put(DbStructureCourse.Columns.AUTHORS, DbParseHelper.parseLongListToString(course.authors)) values.put(DbStructureCourse.Columns.INSTRUCTORS, DbParseHelper.parseLongListToString(course.instructors)) values.put(DbStructureCourse.Columns.SECTIONS, DbParseHelper.parseLongListToString(course.sections)) values.put(DbStructureCourse.Columns.PREVIEW_LESSON, course.previewLesson) values.put(DbStructureCourse.Columns.PREVIEW_UNIT, course.previewUnit) values.put(DbStructureCourse.Columns.COURSE_FORMAT, course.courseFormat) values.put(DbStructureCourse.Columns.TARGET_AUDIENCE, course.targetAudience) values.put(DbStructureCourse.Columns.CERTIFICATE_FOOTER, course.certificateFooter) values.put(DbStructureCourse.Columns.CERTIFICATE_COVER_ORG, course.certificateCoverOrg) values.put(DbStructureCourse.Columns.TOTAL_UNITS, course.totalUnits) values.put(DbStructureCourse.Columns.ENROLLMENT, course.enrollment) values.put(DbStructureCourse.Columns.PROGRESS, course.progress) values.put(DbStructureCourse.Columns.OWNER, course.owner) values.put(DbStructureCourse.Columns.READINESS, course.readiness) values.put(DbStructureCourse.Columns.IS_CONTEST, course.isContest) values.put(DbStructureCourse.Columns.IS_FEATURED, course.isFeatured) values.put(DbStructureCourse.Columns.IS_ACTIVE, course.isActive) values.put(DbStructureCourse.Columns.IS_PUBLIC, course.isPublic) values.put(DbStructureCourse.Columns.IS_ARCHIVED, course.isArchived) values.put(DbStructureCourse.Columns.IS_FAVORITE, course.isFavorite) values.put(DbStructureCourse.Columns.IS_PROCTORED, course.isProctored) values.put(DbStructureCourse.Columns.IS_IN_WISHLIST, course.isInWishlist) values.put(DbStructureCourse.Columns.IS_ENABLED, course.isEnabled) values.put(DbStructureCourse.Columns.CERTIFICATE_DISTINCTION_THRESHOLD, course.certificateDistinctionThreshold) values.put(DbStructureCourse.Columns.CERTIFICATE_REGULAR_THRESHOLD, course.certificateRegularThreshold) values.put(DbStructureCourse.Columns.CERTIFICATE_LINK, course.certificateLink) values.put(DbStructureCourse.Columns.IS_CERTIFICATE_AUTO_ISSUED, course.isCertificateAutoIssued) values.put(DbStructureCourse.Columns.IS_CERTIFICATE_ISSUED, course.isCertificateIssued) values.put(DbStructureCourse.Columns.WITH_CERTIFICATE, course.withCertificate) values.put(DbStructureCourse.Columns.LAST_DEADLINE, course.lastDeadline) values.put(DbStructureCourse.Columns.BEGIN_DATE, course.beginDate) values.put(DbStructureCourse.Columns.END_DATE, course.endDate) values.put(DbStructureCourse.Columns.SLUG, course.slug) values.put(DbStructureCourse.Columns.SCHEDULE_LINK, course.scheduleLink) values.put(DbStructureCourse.Columns.SCHEDULE_LONG_LINK, course.scheduleLongLink) values.put(DbStructureCourse.Columns.SCHEDULE_TYPE, course.scheduleType) values.put(DbStructureCourse.Columns.LAST_STEP, course.lastStepId) values.put(DbStructureCourse.Columns.LEARNERS_COUNT, course.learnersCount) values.put(DbStructureCourse.Columns.REVIEW_SUMMARY, course.reviewSummary) values.put(DbStructureCourse.Columns.TIME_TO_COMPLETE, course.timeToComplete) values.put(DbStructureCourse.Columns.OPTIONS, course.courseOptions?.let(gson::toJson)) values.put(DbStructureCourse.Columns.ACTIONS, course.actions?.let(gson::toJson)) values.put(DbStructureCourse.Columns.IS_PAID, course.isPaid) values.put(DbStructureCourse.Columns.PRICE, course.price) values.put(DbStructureCourse.Columns.CURRENCY_CODE, course.currencyCode) values.put(DbStructureCourse.Columns.DISPLAY_PRICE, course.displayPrice) values.put(DbStructureCourse.Columns.PRICE_TIER, course.priceTier) values.put(DbStructureCourse.Columns.DEFAULT_PROMO_CODE_NAME, course.defaultPromoCodeName) values.put(DbStructureCourse.Columns.DEFAULT_PROMO_CODE_PRICE, course.defaultPromoCodePrice) values.put(DbStructureCourse.Columns.DEFAULT_PROMO_CODE_DISCOUNT, course.defaultPromoCodeDiscount) values.put(DbStructureCourse.Columns.DEFAULT_PROMO_CODE_EXPIRE_DATE, course.defaultPromoCodeExpireDate?.time ?: -1) return values } override fun populateNestedObjects(course: Course): Course = course.apply { introVideo = videoDao.get(course.introVideo?.id ?: -1) // less overhead vs immutability } override fun storeNestedObjects(persistentObject: Course) { persistentObject.introVideo?.let(videoDao::replace) } }
app/src/main/java/org/stepic/droid/storage/dao/CourseDaoImpl.kt
1627290270
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.index.actions import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageType import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsContexts.NotificationContent import com.intellij.openapi.util.ThrowableComputable import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.openapi.util.text.HtmlChunk import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier import com.intellij.vcsUtil.VcsFileUtil import git4idea.GitContentRevision import git4idea.index.ui.GitFileStatusNode import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager import java.util.* class GitAddAction : StagingAreaOperationAction(GitAddOperation) class GitResetAction : StagingAreaOperationAction(GitResetOperation) class GitRevertAction : StagingAreaOperationAction(GitRevertOperation) abstract class StagingAreaOperationAction(private val operation: StagingAreaOperation) : GitFileStatusNodeAction(operation.actionText, Presentation.NULL_STRING, operation.icon) { override fun matches(statusNode: GitFileStatusNode): Boolean = operation.matches(statusNode) override fun perform(project: Project, nodes: List<GitFileStatusNode>) = performStageOperation(project, nodes, operation) } fun performStageOperation(project: Project, nodes: List<GitFileStatusNode>, operation: StagingAreaOperation) { FileDocumentManager.getInstance().saveAllDocuments() runProcess(project, operation.progressTitle, true) { val repositoryManager = GitRepositoryManager.getInstance(project) val submodulesByRoot = mutableMapOf<GitRepository, MutableList<GitFileStatusNode>>() val pathsByRoot = mutableMapOf<GitRepository, MutableList<GitFileStatusNode>>() for (node in nodes) { val filePath = node.filePath val submodule = GitContentRevision.getRepositoryIfSubmodule(project, filePath) if (submodule != null) { val list = submodulesByRoot.computeIfAbsent(submodule.parent) { ArrayList() } list.add(node) } else { val repo = repositoryManager.getRepositoryForFileQuick(filePath) if (repo != null) { val list = pathsByRoot.computeIfAbsent(repo) { ArrayList() } list.add(node) } } } val exceptions = mutableListOf<VcsException>() pathsByRoot.forEach { (repo, nodes) -> try { operation.processPaths(project, repo.root, nodes) VcsFileUtil.markFilesDirty(project, nodes.map { it.filePath }) } catch (ex: VcsException) { exceptions.add(ex) } } submodulesByRoot.forEach { (repo, submodules) -> try { operation.processPaths(project, repo.root, submodules) VcsFileUtil.markFilesDirty(project, submodules.mapNotNull { it.filePath.parentPath }) } catch (ex: VcsException) { exceptions.add(ex) } } if (exceptions.isNotEmpty()) { showErrorMessage(project, operation.errorMessage, exceptions) } } } fun <T> runProcess(project: Project, @NlsContexts.ProgressTitle title: String, canBeCancelled: Boolean, process: () -> T): T { return ProgressManager.getInstance().runProcessWithProgressSynchronously(ThrowableComputable { process() }, title, canBeCancelled, project) } private fun showErrorMessage(project: Project, @NotificationContent messageTitle: String, exceptions: Collection<Exception>) { val message = HtmlBuilder().append(HtmlChunk.text("$messageTitle:").bold()) .br() .appendWithSeparators(HtmlChunk.br(), exceptions.map { HtmlChunk.text(it.localizedMessage) }) VcsBalloonProblemNotifier.showOverVersionControlView(project, message.toString(), MessageType.ERROR) }
plugins/git4idea/src/git4idea/index/actions/StagingAreaOperationAction.kt
296720747
// Copyright 2000-2021 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.ide.util import com.fasterxml.jackson.databind.ObjectMapper import com.intellij.internal.statistic.eventLog.EventLogConfiguration import com.intellij.internal.statistic.local.ActionSummary import com.intellij.internal.statistic.local.ActionsLocalSummary import com.intellij.internal.statistic.utils.StatisticsUploadAssistant import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import com.intellij.util.PlatformUtils import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.io.HttpRequests import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap import java.util.concurrent.ScheduledFuture import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicReference private val LOG = logger<TipsOrderUtil>() private const val RANDOM_SHUFFLE_ALGORITHM = "default_shuffle" private const val TIPS_SERVER_URL = "https://feature-recommendation.analytics.aws.intellij.net/tips/v1" internal data class RecommendationDescription(val algorithm: String, val tips: List<TipAndTrickBean>, val version: String?) @Service internal class TipsOrderUtil { private class RecommendationsStartupActivity : StartupActivity.Background { private val scheduledFuture = AtomicReference<ScheduledFuture<*>>() override fun runActivity(project: Project) { val app = ApplicationManager.getApplication() if (!app.isEAP || app.isHeadlessEnvironment || !StatisticsUploadAssistant.isSendAllowed()) { return } scheduledFuture.getAndSet(AppExecutorUtil.getAppScheduledExecutorService().schedule(Runnable { try { sync() } finally { scheduledFuture.getAndSet(AppExecutorUtil.getAppScheduledExecutorService().schedule(Runnable(::sync), 3, TimeUnit.HOURS)) ?.cancel(false) } }, 5, TimeUnit.MILLISECONDS)) ?.cancel(false) } } companion object { @JvmStatic private fun sync() { LOG.assertTrue(!ApplicationManager.getApplication().isDispatchThread) LOG.debug { "Fetching tips order from the server: ${TIPS_SERVER_URL}" } val allTips = TipAndTrickBean.EP_NAME.iterable.map { it.fileName } val actionsSummary = service<ActionsLocalSummary>().getActionsStats() val startTimestamp = System.currentTimeMillis() HttpRequests.post(TIPS_SERVER_URL, HttpRequests.JSON_CONTENT_TYPE) .connect(HttpRequests.RequestProcessor { request -> val bucket = EventLogConfiguration.bucket val tipsRequest = TipsRequest(allTips, actionsSummary, PlatformUtils.getPlatformPrefix(), bucket) val objectMapper = ObjectMapper() request.write(objectMapper.writeValueAsBytes(tipsRequest)) val recommendation = objectMapper.readValue(request.readString(), ServerRecommendation::class.java) LOG.debug { val duration = System.currentTimeMillis() - startTimestamp val algorithmInfo = "${recommendation.usedAlgorithm}:${recommendation.version}" "Server recommendation made. Algorithm: $algorithmInfo. Duration: ${duration}" } service<TipsOrderUtil>().serverRecommendation = recommendation }, null, LOG) } } @Volatile private var serverRecommendation: ServerRecommendation? = null /** * Reorders tips to show the most useful ones in the beginning * * @return object that contains sorted tips and describes approach of how the tips are sorted */ fun sort(tips: List<TipAndTrickBean>): RecommendationDescription { // temporarily suggest random order if we cannot estimate quality return serverRecommendation?.reorder(tips) ?: RecommendationDescription(RANDOM_SHUFFLE_ALGORITHM, tips.shuffled(), null) } } private data class TipsRequest( val tips: List<String>, val usageInfo: Map<String, ActionSummary>, val ideName: String, // product code val bucket: Int ) private class ServerRecommendation { @JvmField var showingOrder = emptyList<String>() @JvmField var usedAlgorithm = "unknown" @JvmField var version: String? = null fun reorder(tips: List<TipAndTrickBean>): RecommendationDescription? { val tipToIndex = Object2IntOpenHashMap<String>(showingOrder.size) showingOrder.forEachIndexed { index, tipFile -> tipToIndex.put(tipFile, index) } for (tip in tips) { if (!tipToIndex.containsKey(tip.fileName)) { LOG.error("Unknown tips file: ${tip.fileName}") return null } } return RecommendationDescription(usedAlgorithm, tips.sortedBy { tipToIndex.getInt(it.fileName) }, version) } }
platform/platform-impl/src/com/intellij/ide/util/TipsOrderUtil.kt
2998654291
package graphics.scenery.tests.examples.advanced import bdv.util.AxisOrder import org.joml.Vector3f import graphics.scenery.* import graphics.scenery.backends.Renderer import graphics.scenery.controls.OpenVRHMD import graphics.scenery.controls.TrackedDeviceType import graphics.scenery.controls.TrackerRole import graphics.scenery.numerics.Random import graphics.scenery.attribute.material.Material import graphics.scenery.controls.behaviours.Grabable import graphics.scenery.controls.behaviours.VRGrab import graphics.scenery.volumes.SlicingPlane import graphics.scenery.volumes.TransferFunction import graphics.scenery.volumes.Volume import ij.IJ import ij.ImagePlus import net.imglib2.img.Img import net.imglib2.img.display.imagej.ImageJFunctions import net.imglib2.type.numeric.integer.UnsignedShortType import org.scijava.ui.behaviour.ClickBehaviour import tpietzsch.example2.VolumeViewerOptions import kotlin.concurrent.thread import kotlin.system.exitProcess /** * Example for usage of VR controllers. Demonstrates the use of custom key bindings on the * HMD, and the use of intersection testing with scene elements. * * @author Ulrik Günther <[email protected]> */ class VRVolumeCroppingExample : SceneryBase(VRVolumeCroppingExample::class.java.simpleName, windowWidth = 1920, windowHeight = 1200) { private lateinit var hmd: OpenVRHMD private lateinit var boxes: List<Node> private lateinit var hullbox: Box private lateinit var volume: Volume override fun init() { hmd = OpenVRHMD(useCompositor = true) if(!hmd.initializedAndWorking()) { logger.error("This demo is intended to show the use of OpenVR controllers, but no OpenVR-compatible HMD could be initialized.") exitProcess(1) } hub.add(SceneryElement.HMDInput, hmd) VRGrab.createAndSet(scene,hmd, listOf(OpenVRHMD.OpenVRButton.Side), listOf(TrackerRole.RightHand)) renderer = hub.add(Renderer.createRenderer(hub, applicationName, scene, windowWidth, windowHeight)) renderer?.toggleVR() val cam: Camera = DetachedHeadCamera(hmd) cam.spatial { position = Vector3f(0.0f, 0.0f, 0.0f) } cam.perspectiveCamera(50.0f, windowWidth, windowHeight) scene.addChild(cam) val imp: ImagePlus = IJ.openImage("https://imagej.nih.gov/ij/images/t1-head.zip") val img: Img<UnsignedShortType> = ImageJFunctions.wrapShort(imp) volume = Volume.fromRAI(img, UnsignedShortType(), AxisOrder.DEFAULT, "T1 head", hub, VolumeViewerOptions()) volume.transferFunction = TransferFunction.ramp(0.001f, 0.5f, 0.3f) volume.spatial { scale = Vector3f(0.5f,-0.5f,0.5f) position = Vector3f(0f,1f,-1f) } scene.addChild(volume) val croppingHandle = Box(Vector3f(0.2f,0.01f,0.2f)) croppingHandle.spatial{ position = Vector3f(0f,1f,-0.5f) } croppingHandle.addAttribute(Grabable::class.java, Grabable()) scene.addChild(croppingHandle) val croppingPlane = SlicingPlane() croppingPlane.addTargetVolume(volume) volume.slicingMode = Volume.SlicingMode.Cropping croppingHandle.addChild(croppingPlane) (0..5).map { val light = PointLight(radius = 15.0f) light.emissionColor = Random.random3DVectorFromRange(0.0f, 1.0f) light.spatial { position = Random.random3DVectorFromRange(-5.0f, 5.0f) } light.intensity = 1.0f light }.forEach { scene.addChild(it) } hullbox = Box(Vector3f(20.0f, 20.0f, 20.0f), insideNormals = true) hullbox.material { ambient = Vector3f(0.6f, 0.6f, 0.6f) diffuse = Vector3f(0.4f, 0.4f, 0.4f) specular = Vector3f(0.0f, 0.0f, 0.0f) cullingMode = Material.CullingMode.Front } scene.addChild(hullbox) thread { while(!running) { Thread.sleep(200) } hmd.events.onDeviceConnect.add { hmd, device, timestamp -> if(device.type == TrackedDeviceType.Controller) { logger.info("Got device ${device.name} at $timestamp") device.model?.let { controller -> // This attaches the model of the controller to the controller's transforms // from the OpenVR/SteamVR system. hmd.attachToNode(device, controller, cam) } } } } } override fun inputSetup() { super.inputSetup() // We first grab the default movement actions from scenery's input handler, // and re-bind them on the right-hand controller's trackpad or joystick. inputHandler?.let { handler -> hashMapOf( "move_forward" to OpenVRHMD.keyBinding(TrackerRole.RightHand, OpenVRHMD.OpenVRButton.Up), "move_back" to OpenVRHMD.keyBinding(TrackerRole.RightHand, OpenVRHMD.OpenVRButton.Down), "move_left" to OpenVRHMD.keyBinding(TrackerRole.RightHand, OpenVRHMD.OpenVRButton.Left), "move_right" to OpenVRHMD.keyBinding(TrackerRole.RightHand, OpenVRHMD.OpenVRButton.Right) ).forEach { (name, key) -> handler.getBehaviour(name)?.let { b -> logger.info("Adding behaviour $name bound to $key to HMD") hmd.addBehaviour(name, b) hmd.addKeyBinding(name, key) } } } // Finally, add a behaviour to toggle the scene's shell hmd.addBehaviour("toggle_shell", ClickBehaviour { _, _ -> hullbox.visible = !hullbox.visible logger.info("Hull visible: ${hullbox.visible}") }) //... and bind that to the A button on the left-hand controller. hmd.addKeyBinding("toggle_shell", TrackerRole.LeftHand, OpenVRHMD.OpenVRButton.A) // slicing mode toggle hmd.addBehaviour("toggleSlicing", ClickBehaviour{ _, _ -> val current = volume.slicingMode.id val next = (current + 1 ) % Volume.SlicingMode.values().size volume.slicingMode = Volume.SlicingMode.values()[next] }) hmd.addKeyBinding("toggleSlicing",TrackerRole.RightHand,OpenVRHMD.OpenVRButton.A) } companion object { @JvmStatic fun main(args: Array<String>) { VRVolumeCroppingExample().main() } } }
src/test/kotlin/graphics/scenery/tests/examples/advanced/VRVolumeCroppingExample.kt
3308182083
package de.langerhans.discord.gitbot import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.stereotype.Component /** * Created by maxke on 07.08.2016. * Main config */ @Component @ConfigurationProperties(prefix = "bot") open class BotConfig() { lateinit var discordtoken: String lateinit var targetChannel: String } @Component @ConfigurationProperties(prefix = "github") open class GithubConfig() { lateinit var secret: String }
src/main/kotlin/de/langerhans/discord/gitbot/Config.kt
4125045316
package com.richodemus.chronicler.server.core import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.times import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.Before import org.junit.Test internal class ChronicleTest { private val id = "uuid" private val data = "interesting data" private var eventListenerMock: EventCreationListener? = null private var eventPersisterMock: EventPersister? = null private var target: Chronicle? = null @Before fun setUp() { eventListenerMock = mock<EventCreationListener> {} eventPersisterMock = mock<EventPersister> { on { readEvents() } doReturn listOf<Event>().iterator() } target = Chronicle(eventListenerMock(), eventPersisterMock()) } private fun eventListenerMock() = eventListenerMock!! private fun eventPersisterMock() = eventPersisterMock!! private fun target() = target!! @Test fun `New Chronicle should be empty`() { val result = target().getEvents() assertThat(result).hasSize(0) } @Test fun `New Chronicle should be at page zero`() { val result = target().page assertThat(result).isEqualTo(0L) } @Test fun `A Chronicle with one event should return one event`() { val target = target() target.addEvent(Event(id, "type", 1L, "")) assertThat(target.getEvents()).hasSize(1) } @Test fun `Should send newly created event to listener`() { val target = target() val event = Event(id, "type", 1L, "") target.addEvent(event) verify(eventListenerMock()).onEvent(eq(event)) } @Test fun `Should send newly created event to persister`() { val target = target() val event = Event(id, "type", 1L, "") target.addEvent(event) verify(eventPersisterMock()).persist(eq(event)) } @Test fun `Should read events from persistence`() { val events = listOf(Event("one", "type", 1L, ""), Event("two", "type", 2L, "")) whenever(eventPersisterMock().readEvents()).thenReturn(events.iterator()) target = Chronicle(eventListenerMock(), eventPersisterMock()) assertThat(target().getEvents()).containsExactly(*events.toTypedArray()) } @Test fun `Should read event ids from persistence`() { val events = listOf(Event("one", "type", 1L, ""), Event("two", "type", 2L, "")) whenever(eventPersisterMock().readEvents()).thenReturn(events.iterator()) target = Chronicle(eventListenerMock(), eventPersisterMock()) assertThat(target().getIds()).containsExactly(*events.map { it.id }.toTypedArray()) } @Test fun `A Chronicle with one event should be at page one`() { val target = target() target.addEvent(Event(id, "type", 1L, "")) assertThat(target.page).isEqualTo(1L) } @Test fun `Add pageless Event to empty Chronicle`() { val target = target() target.addEvent(Event(id, "type", null, data)) val result = target.getEvents().single() assertThat(result.id).isEqualTo(id) assertThat(result.page).isEqualTo(1L) assertThat(result.data).isEqualTo(data) } @Test fun `Add Event to first page of empty Chronicle`() { val target = target() target.addEvent(Event(id, "type", 1L, data)) val result = target.getEvents().single() assertThat(result.id).isEqualTo(id) assertThat(result.page).isEqualTo(1L) assertThat(result.data).isEqualTo(data) } @Test fun `Adding event at the wrong page should throw exception`() { val target = target() assertThatThrownBy { target.addEvent(Event(id, "type", 2L, "")) }.isInstanceOf(WrongPageException::class.java) } @Test fun `Should not insert duplicate Event`() { val target = target() target.addEvent(Event(id, "type", null, "original data")) target.addEvent(Event(id, "type", null, "second data")) val result = target.getEvents() assertThat(result).hasSize(1) assertThat(result.single().data).isEqualTo("original data") } @Test fun `Should not send duplicate event to listener`() { val target = target() target.addEvent(Event(id, "type", null, "original data")) target.addEvent(Event(id, "type", null, "second data")) verify(eventListenerMock(), times(1)).onEvent(any()) } }
server/core/src/test/kotlin/com/richodemus/chronicler/server/core/ChronicleTest.kt
2240327528
/* * Copyright 2019 New Vector Ltd * * 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.matrix.androidsdk.rest.model.identityserver import com.google.gson.annotations.SerializedName data class IdentityServerRegisterResponse( @JvmField @SerializedName("access_token") @Deprecated("The spec is `token`, but we used `access_token` for a Sydent release") val accessToken: String? = null, @JvmField @SerializedName("token") val token: String? = null ) { // XXX: The spec is `token`, but we used `access_token` for a Sydent release. val identityServerAccessToken: String? get() = token ?: accessToken }
matrix-sdk/src/main/java/org/matrix/androidsdk/rest/model/identityserver/IdentityServerRegisterResponse.kt
2958980339
package com.richodemus.chronicler.server.core import org.slf4j.LoggerFactory import java.time.Duration import kotlin.system.measureTimeMillis class EventLoader(val persister: EventPersister) { private val logger = LoggerFactory.getLogger(javaClass) fun getEvents(): List<Event> { logger.info("Loading events...") val count = persister.getNumberOfEvents() logger.info("There are $count events") val events = mutableListOf<Event>() val time = measureTimeMillis { val eventIterator = persister.readEvents() eventIterator.forEach { events.add(it) } } val duration = Duration.ofMillis(time) val durationString = String.format("%d minutes and %d seconds", (duration.seconds % 3600) / 60, (duration.seconds % 60)) logger.info("Loaded ${events.size} events in $durationString") return events } }
server/core/src/main/kotlin/com/richodemus/chronicler/server/core/EventLoader.kt
2371521744
// 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 org.jetbrains.plugins.github.pullrequest.ui.timeline import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestState import org.jetbrains.plugins.github.api.data.pullrequest.timeline.GHPRTimelineEvent class GHPRTimelineMergedStateEvents(initialState: GHPRTimelineEvent.State) : GHPRTimelineMergedEvents<GHPRTimelineEvent.State>(), GHPRTimelineEvent.State { private val inferredOriginalState: GHPullRequestState = when (initialState.newState) { GHPullRequestState.CLOSED -> GHPullRequestState.OPEN GHPullRequestState.MERGED -> GHPullRequestState.OPEN GHPullRequestState.OPEN -> GHPullRequestState.CLOSED } override var newState: GHPullRequestState = initialState.newState private set override fun addNonMergedEvent(event: GHPRTimelineEvent.State) { newState = event.newState } override fun hasAnyChanges(): Boolean = newState != inferredOriginalState }
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/timeline/GHPRTimelineMergedStateEvents.kt
1293019217
package com.yeungeek.avsample.activities.opengl.tutorial.oes.renderer import android.opengl.GLSurfaceView import javax.microedition.khronos.egl.EGLConfig import javax.microedition.khronos.opengles.GL10 class Camera2SurfaceRenderer : GLSurfaceView.Renderer { override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) { TODO("Not yet implemented") } override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) { TODO("Not yet implemented") } override fun onDrawFrame(gl: GL10?) { TODO("Not yet implemented") } }
AVSample/app/src/main/java/com/yeungeek/avsample/activities/opengl/tutorial/oes/renderer/Camera2SurfaceRenderer.kt
3738063806
package slatekit.entities.features import slatekit.common.data.DataAction import slatekit.common.data.Value import kotlin.reflect.KProperty import slatekit.entities.Entity import slatekit.entities.core.EntityOps import slatekit.entities.EntityOptions import slatekit.meta.Reflector import slatekit.meta.kClass import slatekit.query.Update import slatekit.results.Try import slatekit.results.builders.Tries interface Updates<TId, T> : EntityOps<TId, T> where TId : kotlin.Comparable<TId>, T : Entity<TId> { /** * directly modifies an entity without any additional processing/hooks/etc * @param entity * @return */ suspend fun modify(entity: T): Boolean { return repo().update(entity) } /** * directly modifies an entity without any additional processing/hooks/etc * @param entity * @return */ suspend fun patch(id:TId, values:List<Value>): Int { return repo().patchById(id, values) } /** * creates the entity in the data store with additional processing based on the options supplied * @param entity : The entity to save * @param options: Settings to determine whether to apply metadata, and notify via Hooks */ suspend fun update(entity: T, options: EntityOptions): Pair<Boolean, T> { // Massage val entityFinal = when (options.applyMetadata) { true -> applyFieldData(DataAction.Update, entity) false -> entity } // Update val success = modify(entityFinal) return Pair(success, entityFinal) } /** * updates the entity in the data store and sends an event if there is support for Hooks * @param entity * @return */ suspend fun update(entity: T): Boolean { val finalEntity = applyFieldData(DataAction.Update, entity) val success = repo().update(finalEntity) return success } /** * updates the entity in the data-store with error-handling * @param entity * @return */ suspend fun updateAsTry(entity: T): Try<Boolean> { return Tries.of { update(entity) } } /** * updates the entity field in the datastore * @param id: id of the entity * @param field: the name of the field * @param value: the value to set on the field * @return */ suspend fun update(id: TId, field: String, value: String) { val item = repo().getById(id) item?.let { entity -> Reflector.setFieldValue(entity.kClass, entity, field, value) update(entity) } } /** * updates items using the query */ suspend fun updateByQuery(builder: Update): Int { return repo().patchByQuery(builder) } /** * updates items based on the field name * @param prop: The property reference * @param value: The value to check for * @return */ suspend fun patchByField(prop: KProperty<*>, value: Any): Int { return repo().patchByField(prop.name, value) } /** * updates items based on the field name * @param prop: The property reference * @param value: The value to check for * @return */ suspend fun patchByFields(prop: KProperty<*>, oldValue: Any?, newValue:Any?): Int { return repo().patchByValue(prop.name, oldValue, newValue) } /** * updates items using the query */ suspend fun patch(builder: Update.() -> Unit): Int { return repo().patch(builder) } suspend fun update(): Update = repo().patch() }
src/lib/kotlin/slatekit-entities/src/main/kotlin/slatekit/entities/features/Updates.kt
2311813925
// 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.jetbrains.python.codeInsight.mlcompletion import com.intellij.codeInsight.completion.CompletionLocation import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementPresentation import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiComment import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.elementType import com.jetbrains.python.PyTokenTypes import com.jetbrains.python.psi.* import com.jetbrains.python.sdk.PythonSdkUtil object PyCompletionFeatures { fun isDictKey(element: LookupElement): Boolean { val presentation = LookupElementPresentation.renderElement(element) return ("dict key" == presentation.typeText) } fun isTheSameFile(element: LookupElement, location: CompletionLocation): Boolean { val psiFile = location.completionParameters.originalFile val elementPsiFile = element.psiElement?.containingFile ?: return false return psiFile == elementPsiFile } fun isTakesParameterSelf(element: LookupElement): Boolean { val presentation = LookupElementPresentation.renderElement(element) return presentation.tailText == "(self)" } enum class ElementNameUnderscoreType {NO_UNDERSCORE, TWO_START_END, TWO_START, ONE_START} fun getElementNameUnderscoreType(name: String): ElementNameUnderscoreType { return when { name.startsWith("__") && name.endsWith("__") -> ElementNameUnderscoreType.TWO_START_END name.startsWith("__") -> ElementNameUnderscoreType.TWO_START name.startsWith("_") -> ElementNameUnderscoreType.ONE_START else -> ElementNameUnderscoreType.NO_UNDERSCORE } } fun isPsiElementIsPyFile(element: LookupElement) = element.psiElement is PyFile fun isPsiElementIsPsiDirectory(element: LookupElement) = element.psiElement is PsiDirectory data class ElementModuleCompletionFeatures(val isFromStdLib: Boolean, val canFindModule: Boolean) fun getElementModuleCompletionFeatures(element: LookupElement): ElementModuleCompletionFeatures? { val psiElement = element.psiElement ?: return null var vFile: VirtualFile? = null var sdk: Sdk? = null val containingFile = psiElement.containingFile if (psiElement is PsiDirectory) { vFile = psiElement.virtualFile sdk = PythonSdkUtil.findPythonSdk(psiElement) } else if (containingFile != null) { vFile = containingFile.virtualFile sdk = PythonSdkUtil.findPythonSdk(containingFile) } if (vFile != null) { val isFromStdLib = PythonSdkUtil.isStdLib(vFile, sdk) val canFindModule = ModuleUtilCore.findModuleForFile(vFile, psiElement.project) != null return ElementModuleCompletionFeatures(isFromStdLib, canFindModule) } return null } fun isInCondition(locationPsi: PsiElement): Boolean { if (isAfterColon(locationPsi)) return false val condition = PsiTreeUtil.getParentOfType(locationPsi, PyConditionalStatementPart::class.java, true, PyArgumentList::class.java, PyStatementList::class.java) return condition != null } fun isAfterIfStatementWithoutElseBranch(locationPsi: PsiElement): Boolean { val prevKeywords = getPrevKeywordsIdsInTheSameColumn(locationPsi, 1) if (prevKeywords.isEmpty()) return false val ifKwId = PyMlCompletionHelpers.getKeywordId("if") val elifKwId = PyMlCompletionHelpers.getKeywordId("elif") return prevKeywords[0] == ifKwId || prevKeywords[0] == elifKwId } fun isInForStatement(locationPsi: PsiElement): Boolean { if (isAfterColon(locationPsi)) return false val parent = PsiTreeUtil.getParentOfType(locationPsi, PyForPart::class.java, true, PyStatementList::class.java) return parent != null } fun getPrevNeighboursKeywordIds(locationPsi: PsiElement, maxPrevKeywords: Int = 2): ArrayList<Int> { val res = ArrayList<Int>() var cur: PsiElement? = locationPsi while (cur != null) { cur = PsiTreeUtil.prevVisibleLeaf(cur)?: break val keywordId = PyMlCompletionHelpers.getKeywordId(cur.text) ?: break res.add(keywordId) if (res.size >= maxPrevKeywords) break } return res } fun getPrevKeywordsIdsInTheSameLine(locationPsi: PsiElement, maxPrevKeywords: Int = 2): ArrayList<Int> { val res = ArrayList<Int>() var cur: PsiElement? = locationPsi while (cur != null) { cur = PsiTreeUtil.prevLeaf(cur)?: break if (cur is PsiWhiteSpace && cur.textContains('\n')) break val keywordId = PyMlCompletionHelpers.getKeywordId(cur.text) ?: continue res.add(keywordId) if (res.size >= maxPrevKeywords) break } return res } fun getPrevKeywordsIdsInTheSameColumn(locationPsi: PsiElement, maxPrevKeywords: Int = 2): ArrayList<Int> { val maxSteps = 1000 fun getIndent(element: PsiElement) = element.text.split('\n').last().length fun isIndentElement(element: PsiElement) = element is PsiWhiteSpace && element.textContains('\n') fun isInDocstring(element: PsiElement) = element.parent is StringLiteralExpression val res = ArrayList<Int>() val whitespaceElem = PsiTreeUtil.prevLeaf(locationPsi) ?: return res if (!whitespaceElem.text.contains('\n')) return res val caretIndent = getIndent(whitespaceElem) var stepsCounter = 0 var cur: PsiElement? = whitespaceElem while (cur != null) { stepsCounter++ if (stepsCounter > maxSteps) break cur = PsiTreeUtil.prevLeaf(cur)?: break val prev = PsiTreeUtil.prevLeaf(cur)?: break if (cur is PsiComment || isInDocstring(cur)) continue if (!isIndentElement(prev)) continue val prevIndent = getIndent(prev) if (prevIndent < caretIndent) break if (prevIndent > caretIndent) continue val keywordId = PyMlCompletionHelpers.getKeywordId(cur.text) ?: break res.add(keywordId) if (res.size >= maxPrevKeywords) break cur = prev } return res } fun getNumberOfOccurrencesInScope(kind: PyCompletionMlElementKind, locationPsi: PsiElement, lookupString: String): Int? { when (kind) { in arrayOf(PyCompletionMlElementKind.FUNCTION, PyCompletionMlElementKind.TYPE_OR_CLASS, PyCompletionMlElementKind.FROM_TARGET) -> { val statementList = PsiTreeUtil.getParentOfType(locationPsi, PyStatementList::class.java, PyFile::class.java) ?: return null val children = PsiTreeUtil.collectElementsOfType(statementList, PyReferenceExpression::class.java) return children.count { it.textOffset < locationPsi.textOffset && it.textMatches(lookupString) } } PyCompletionMlElementKind.NAMED_ARG -> { val psiArgList = PsiTreeUtil.getParentOfType(locationPsi, PyArgumentList::class.java) ?: return null val children = PsiTreeUtil.getChildrenOfType(psiArgList, PyKeywordArgument::class.java) ?: return null return children.map { it.firstChild }.count { lookupString == "${it.text}=" } } PyCompletionMlElementKind.PACKAGE_OR_MODULE -> { val imports = PsiTreeUtil.collectElementsOfType(locationPsi.containingFile, PyImportElement::class.java) return imports.count { imp -> val refExpr = imp.importReferenceExpression refExpr != null && refExpr.textMatches(lookupString) } } else -> { return null } } } fun getBuiltinPopularityFeature(lookupString: String, isBuiltins: Boolean): Int? = if (isBuiltins) PyMlCompletionHelpers.builtinsPopularity[lookupString] else null fun getKeywordId(lookupString: String): Int? = PyMlCompletionHelpers.getKeywordId(lookupString) fun getPyLookupElementInfo(element: LookupElement): PyCompletionMlElementInfo? = element.getUserData(PyCompletionMlElementInfo.key) fun getNumberOfQualifiersInExpresionFeature(element: PsiElement): Int { if (element !is PyQualifiedExpression) return 1 return element.asQualifiedName()?.components?.size ?: 1 } private fun isAfterColon(locationPsi: PsiElement): Boolean { val prevVisibleLeaf = PsiTreeUtil.prevVisibleLeaf(locationPsi) return (prevVisibleLeaf != null && prevVisibleLeaf.elementType == PyTokenTypes.COLON) } }
python/src/com/jetbrains/python/codeInsight/mlcompletion/PyCompletionFeatures.kt
2277761663
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.vrem.wifianalyzer.wifi.filter.adapter import com.vrem.annotation.OpenClass import com.vrem.wifianalyzer.settings.Settings @OpenClass abstract class BasicFilterAdapter<T>(open var selections: Set<T>) { fun selections(selections: Array<T>) { this.selections = selections.toSet() } abstract fun isActive(): Boolean abstract fun reset() abstract fun save(settings: Settings) }
app/src/main/kotlin/com/vrem/wifianalyzer/wifi/filter/adapter/BasicFilterAdapter.kt
2067813789
package com.byoutline.kickmaterial.features.projectdetails import android.content.Context import android.content.Intent import android.media.MediaPlayer import android.net.Uri import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.text.TextUtils import android.view.Window import android.view.WindowManager import android.widget.VideoView import com.byoutline.kickmaterial.R import com.byoutline.kickmaterial.databinding.ActivityVideoBinding import com.byoutline.kickmaterial.model.ProjectDetails import com.byoutline.secretsauce.databinding.bindContentView import com.byoutline.secretsauce.utils.LogUtils /** * Displays fullscreen video. Since it has neither fragments nor toolbar we do not extend * [com.byoutline.kickmaterial.utils.AutoHideToolbarActivity] */ class VideoActivity : AppCompatActivity() { lateinit var videoView: VideoView public override fun onCreate(savedInstanceState: Bundle?) { requestWindowFeature(Window.FEATURE_NO_TITLE) window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN) super.onCreate(savedInstanceState) val binding: ActivityVideoBinding = bindContentView(R.layout.activity_video) videoView = binding.videoView if (savedInstanceState == null) { setDataFromArgs() } } private fun setDataFromArgs() { val intent = intent if (intent == null) { LogUtils.LOGE(TAG, "Null intent") // NOI18E return } val args = intent.extras if (args == null) { LogUtils.LOGE(TAG, "Null args") // NOI18E return } val videoUrl = args.getString(BUNDLE_VIDEO_URL) val altVideoUrl = args.getString(BUNDLE_ALT_VIDEO_URL) val webviewUrl = args.getString(BUNDLE_WEBVIEW_URL) val uri = Uri.parse(videoUrl) videoView.setMediaController(VideoController(this, webviewUrl)) videoView.setVideoURI(uri) videoView.setOnErrorListener(object : MediaPlayer.OnErrorListener { internal var tryAltVideo = !TextUtils.isEmpty(altVideoUrl) override fun onError(mediaPlayer: MediaPlayer, i: Int, i1: Int): Boolean { if (tryAltVideo) { tryAltVideo = false videoView.setVideoURI(Uri.parse(altVideoUrl)) videoView.start() return true } return false } }) videoView.setOnCompletionListener { finish() } videoView.requestFocus() } override fun onStart() { super.onStart() videoView.start() } companion object { const val BUNDLE_VIDEO_URL = "bundle_video_url" const val BUNDLE_ALT_VIDEO_URL = "bundle_alt_video_url" const val BUNDLE_WEBVIEW_URL = "bundle_web_view_url" private val TAG = LogUtils.makeLogTag(VideoActivity::class.java) fun showActivity(context: Context, projectDetails: ProjectDetails) { showActivity(context, projectDetails.videoUrl, projectDetails.altVideoUrl, projectDetails.pledgeUrl) } fun showActivity(context: Context, videoUrl: String, altVideoUrl: String, webviewUrl: String) { val intent = Intent(context, VideoActivity::class.java).apply { putExtra(BUNDLE_VIDEO_URL, videoUrl) putExtra(BUNDLE_ALT_VIDEO_URL, altVideoUrl) putExtra(BUNDLE_WEBVIEW_URL, webviewUrl) } context.startActivity(intent) } } }
app/src/main/java/com/byoutline/kickmaterial/features/projectdetails/VideoActivity.kt
3310131189
// FILE: 1.kt package test inline fun log(lazyMessage: () -> Any?) { lazyMessage() } // FILE: 2.kt import test.* inline fun getOrCreate( z : Boolean = false, s: () -> String ) { log { s() } } fun box(): String { var z = "fail" getOrCreate { z = "OK"; z } return z }
backend.native/tests/external/codegen/boxInline/defaultValues/kt11479.kt
642214179
package me.consuegra.algorithms import me.consuegra.datastructure.KListNode import me.consuegra.datastructure.KStack /** * Implement a function to check if a linked list is a palindrome */ class KPalindromeLinkedList { fun <T> isPalindromeSolution1(input: KListNode<T>?) : Boolean { return input?.let { it == KReverseLinkedList().reverseOption1(input) } ?: false } fun <T> isPalindromeSolution2(input: KListNode<T>?) : Boolean { val stack = KStack<T>() var slow = input var fast = input while (fast != null && fast.next != null) { slow?.data?.let { stack.push(it) } slow = slow?.next fast = fast.next?.next } if (fast != null) { slow = slow?.next } while (slow != null) { if (stack.pop() != slow.data) { return false } slow = slow.next } return true } }
src/main/kotlin/me/consuegra/algorithms/KPalindromeLinkedList.kt
1867261615
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT import kotlin.reflect.full.createType import kotlin.reflect.KClass import kotlin.reflect.KTypeProjection import kotlin.test.assertEquals class A<T1> { inner class B<T2, T3> { inner class C<T4> } class D } fun foo(): A<Int>.B<Double, Float>.C<Long> = null!! fun box(): String { fun KClass<*>.inv() = KTypeProjection.invariant(this.createType()) val type = A.B.C::class.createType(listOf(Long::class.inv(), Double::class.inv(), Float::class.inv(), Int::class.inv())) assertEquals("A<kotlin.Int>.B<kotlin.Double, kotlin.Float>.C<kotlin.Long>", type.toString()) assertEquals("A.D", A.D::class.createType().toString()) return "OK" }
backend.native/tests/external/codegen/box/reflection/types/createType/innerGeneric.kt
680731651
package abi44_0_0.expo.modules.battery import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.BatteryManager import android.os.Bundle import android.util.Log import abi44_0_0.expo.modules.core.interfaces.services.EventEmitter class BatteryLevelReceiver(private val eventEmitter: EventEmitter?) : BroadcastReceiver() { private val BATTERY_LEVEL_EVENT_NAME = "Expo.batteryLevelDidChange" private fun onBatteryLevelChange(BatteryLevel: Float) { eventEmitter?.emit( BATTERY_LEVEL_EVENT_NAME, Bundle().apply { putFloat("batteryLevel", BatteryLevel) } ) } override fun onReceive(context: Context, intent: Intent) { val batteryIntent = context.applicationContext.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) if (batteryIntent == null) { Log.e("Battery", "ACTION_BATTERY_CHANGED unavailable. Events wont be received") return } val level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) val scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1) val batteryLevel: Float = if (level != -1 && scale != -1) { level / scale.toFloat() } else { -1f } onBatteryLevelChange(batteryLevel) } }
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/battery/BatteryLevelReceiver.kt
383353159
/* * This file is part of MythicDrops, licensed under the MIT License. * * Copyright (C) 2020 Richard Harrah * * Permission is hereby granted, free of charge, * to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.tealcube.minecraft.bukkit.mythicdrops.api.socketing import com.tealcube.minecraft.bukkit.mythicdrops.getNonNullString import org.bukkit.configuration.ConfigurationSection class PermissiveSocketCommand(configurationSection: ConfigurationSection) : SocketCommand("") { init { runner = SocketCommandRunner.fromName(configurationSection.getNonNullString("runner")) command = configurationSection.getNonNullString("command") permissions = configurationSection.getStringList("permissions") } }
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/api/socketing/PermissiveSocketCommand.kt
634928802
@file:JvmName("Foo") @JvmOverloads fun <caret>foo(x: Int = 0, y: Double = 0.0, z: String = "0", n: Int = 2) { }
plugins/kotlin/idea/tests/testData/refactoring/changeSignature/JvmOverloadedAddDefault3After.kt
2408830132
interface Z { open fun foo(a: Int, b: Int) } open class A { open fun foo(<caret>a: Int, b: Int) { println(a) } } open class B: A(), Z { override fun foo(a: Int, b: Int) { } } class C: A() { override fun foo(a: Int, b: Int) { } } class D: B(), Z { override fun foo(a: Int, b: Int) { } }
plugins/kotlin/idea/tests/testData/refactoring/safeDelete/deleteValueParameter/kotlinValueParameterWithJava/hierarchyWithUnsafeUsages2.kt
776104491
class Chain fun complicate(chain: Chain) { val vra = (fu<caret>n(chain: Chain, fn: Chain.() -> Chain): Chain { return chain.fn() })(chain){ this.also { println(it) } } }
plugins/kotlin/idea/tests/testData/refactoring/inline/anonymousFunction/lambdaWithReceiverAsParameter3.kt
1305363161
// SUGGESTED_NAMES: s, getX // PARAM_DESCRIPTOR: value-parameter a: kotlin.Int defined in foo // PARAM_TYPES: kotlin.Int fun foo(a: Int): String { val x = "+cd$a:${a + 1}efg" val y = "+cd$a${a + 1}efg" return "ab<selection>cd$a:${a + 1}ef</selection>" }
plugins/kotlin/idea/tests/testData/refactoring/extractFunction/stringTemplates/multipleEntriesWithPrefix.kt
3985619323
// "Create class 'Foo'" "true" fun test() = <caret>Foo<kotlin.String, Int>(2, "2")
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/callExpression/typeArguments/noReceiverLongName.kt
3700495306
package test actual object Obj
plugins/kotlin/idea/tests/testData/navigation/implementations/multiModule/expectObject/jvm/jvm.kt
4137676697
package org.jetbrains.plugins.notebooks.visualization.outputs import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.extensions.ExtensionPointName import org.jetbrains.plugins.notebooks.visualization.NotebookCellLines /** Merely a marker for data that can be represented via some Swing component. */ interface NotebookOutputDataKey { /** Get content that can be used for building diff for outputs. */ fun getContentForDiffing(): Any } interface NotebookOutputDataKeyExtractor { /** * Seeks somewhere for some data to be represented below [interval]. * * @return * `null` if the factory can never extract any data from the [interval] of the [editor]. * An empty list if the factory managed to extract some information, and it literally means there's nothing to be shown. * A non-empty list if some data can be shown. */ fun extract(editor: EditorImpl, interval: NotebookCellLines.Interval): List<NotebookOutputDataKey>? companion object { @JvmField val EP_NAME: ExtensionPointName<NotebookOutputDataKeyExtractor> = ExtensionPointName.create("org.jetbrains.plugins.notebooks.editor.outputs.notebookOutputDataKeyExtractor") } }
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/outputs/NotebookOutputDataKeyExtractor.kt
2498134238
// Copyright 2000-2021 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.workspaceModel.ide.impl.legacyBridge.module import com.intellij.openapi.module.UnloadedModuleDescription import com.intellij.openapi.vfs.pointers.VirtualFilePointer import com.intellij.util.containers.Interner import com.intellij.workspaceModel.ide.impl.VirtualFileUrlBridge import com.intellij.workspaceModel.storage.bridgeEntities.ModuleDependencyItem import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity class UnloadedModuleDescriptionBridge private constructor( private val name: String, private val dependencyModuleNames: List<String>, private val contentRoots: List<VirtualFilePointer>, private val groupPath: List<String> ) : UnloadedModuleDescription { override fun getName(): String = name override fun getDependencyModuleNames(): List<String> = dependencyModuleNames override fun getContentRoots(): List<VirtualFilePointer> = contentRoots override fun getGroupPath(): List<String> = groupPath companion object { fun createDescriptions(entities: List<ModuleEntity>): List<UnloadedModuleDescription> { val interner = Interner.createStringInterner() return entities.map { entity -> create(entity, interner) } } fun createDescription(entity: ModuleEntity): UnloadedModuleDescription = create(entity, Interner.createStringInterner()) private fun create(entity: ModuleEntity, interner: Interner<String>): UnloadedModuleDescriptionBridge { val contentRoots = entity.contentRoots.sortedBy { contentEntry -> contentEntry.url.url } .mapTo(ArrayList()) { contentEntry -> contentEntry.url as VirtualFileUrlBridge } val dependencyModuleNames = entity.dependencies.filterIsInstance(ModuleDependencyItem.Exportable.ModuleDependency::class.java) .map { moduleDependency -> interner.intern(moduleDependency.module.name) } return UnloadedModuleDescriptionBridge(entity.name, dependencyModuleNames, contentRoots, entity.groupPath?.path ?: emptyList()) } } }
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/UnloadedModuleDescriptionBridge.kt
3565912083
fun foo(): String = "" fun bar() { <caret> } // ELEMENT: foo // CHAR: .
plugins/kotlin/completion/tests/testData/handlers/charFilter/DotAfterFun1.kt
660455512
package de.fabmax.kool.platform import de.fabmax.kool.pipeline.TexFormat import de.fabmax.kool.pipeline.TextureData2d import de.fabmax.kool.util.* import kotlinx.coroutines.runBlocking import java.awt.Color import java.awt.Graphics2D import java.awt.GraphicsEnvironment import java.awt.RenderingHints import java.awt.image.BufferedImage import java.awt.image.DataBufferInt import java.io.ByteArrayInputStream import java.io.IOException import kotlin.math.ceil import kotlin.math.round /** * @author fabmax */ private typealias AwtFont = java.awt.Font internal class FontMapGenerator(val maxWidth: Int, val maxHeight: Int, val ctx: Lwjgl3Context) { private val canvas = BufferedImage(maxWidth, maxHeight, BufferedImage.TYPE_INT_ARGB) private val clearColor = Color(0, 0, 0, 0) private val availableFamilies: Set<String> private val customFonts = mutableMapOf<String, AwtFont>() init { val families: MutableSet<String> = mutableSetOf() val ge = GraphicsEnvironment.getLocalGraphicsEnvironment() for (family in ge.availableFontFamilyNames) { families.add(family) } availableFamilies = families } internal fun loadCustomFonts(props: Lwjgl3Context.InitProps, assetMgr: JvmAssetManager) { props.customFonts.forEach { (family, path) -> try { val inStream = runBlocking { ByteArrayInputStream(assetMgr.loadAsset(path)!!.toArray()) } val ttfFont = AwtFont.createFont(AwtFont.TRUETYPE_FONT, inStream) customFonts[family] = ttfFont logD { "Loaded custom font: $family" } } catch (e: IOException) { logE { "Failed loading font $family: $e" } e.printStackTrace() } } } fun createFontMapData(font: AtlasFont, fontScale: Float, outMetrics: MutableMap<Char, CharMetrics>): TextureData2d { val g = canvas.graphics as Graphics2D g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON) // clear canvas g.background = clearColor g.clearRect(0, 0, maxWidth, maxHeight) var style = AwtFont.PLAIN if (font.style and AtlasFont.BOLD != 0) { style = AwtFont.BOLD } if (font.style and AtlasFont.ITALIC != 0) { style += AwtFont.ITALIC } var customFont: AwtFont? = null var family = AwtFont.SANS_SERIF val fams = font.family.split(",") for (fam in fams) { val f = fam.trim().replace("\"", "") if (f in customFonts.keys) { customFont = customFonts[f] break } else if (f == "sans-serif") { family = AwtFont.SANS_SERIF break } else if (f == "monospaced") { family = AwtFont.MONOSPACED break } else if (f in availableFamilies) { family = f break } } val size = round(font.sizePts * fontScale) val awtFont = customFont?.deriveFont(font.style, size) ?: AwtFont(family, style, size.toInt()) // theoretically we could specify an accurate font weight, however this does not have any effect for all fonts I tried //awtFont = awtFont.deriveFont(mapOf<TextAttribute, Any>(TextAttribute.WEIGHT to TextAttribute.WEIGHT_EXTRA_LIGHT)) g.font = awtFont g.color = Color.BLACK outMetrics.clear() val texHeight = makeMap(font, size, g, outMetrics) val buffer = getCanvasAlphaData(maxWidth, texHeight) logD { "Generated font map for (${font}, scale=${fontScale})" } //ImageIO.write(canvas, "png", File("${g.font.family}-${g.font.size}.png")) return TextureData2d(buffer, maxWidth, texHeight, TexFormat.R) } private fun getCanvasAlphaData(width: Int, height: Int): Uint8Buffer { val imgBuf = canvas.data.dataBuffer as DataBufferInt val pixels = imgBuf.bankData[0] val buffer = createUint8Buffer(width * height) for (i in 0 until width * height) { buffer.put((pixels[i] shr 24).toByte()) } buffer.flip() return buffer } private fun makeMap(font: AtlasFont, size: Float, g: Graphics2D, outMetrics: MutableMap<Char, CharMetrics>): Int { val fm = g.fontMetrics // unfortunately java font metrics don't provide methods to determine the precise pixel bounds of individual // characters and some characters (e.g. 'j', 'f') extend further to left / right than the given char width // therefore we need to add generous padding to avoid artefacts val isItalic = font.style == AtlasFont.ITALIC val padLeft = ceil(if (isItalic) size / 2f else size / 5f).toInt() val padRight = ceil(if (isItalic) size / 2f else size / 10f).toInt() val padTop = 0 val padBottom = 0 val ascent = if (font.ascentEm == 0f) (fm.ascent + fm.leading) else ceil(font.ascentEm * size).toInt() val descent = if (font.descentEm == 0f) fm.descent else ceil(font.descentEm * size).toInt() val height = if (font.heightEm == 0f) fm.height else ceil(font.heightEm * size).toInt() // first pixel is opaque g.fillRect(0, 0, 1, 1) var x = 1 var y = ascent for (c in font.chars) { val charW = fm.charWidth(c) val paddedWidth = charW + padLeft + padRight if (x + paddedWidth > maxWidth) { x = 0 y += height + padBottom + padTop if (y + descent > maxHeight) { logE { "Unable to render full font map: Maximum texture size exceeded" } break } } val metrics = CharMetrics() metrics.width = paddedWidth.toFloat() metrics.height = (height + padBottom + padTop).toFloat() metrics.xOffset = padLeft.toFloat() metrics.yBaseline = ascent.toFloat() metrics.advance = charW.toFloat() metrics.uvMin.set( x.toFloat(), (y - ascent - padTop).toFloat() ) metrics.uvMax.set( (x + paddedWidth).toFloat(), (y - ascent + padBottom + height).toFloat() ) outMetrics[c] = metrics g.drawString("$c", x + padLeft, y) x += paddedWidth } val texW = maxWidth val texH = nextPow2(y + descent) for (cm in outMetrics.values) { cm.uvMin.x /= texW cm.uvMin.y /= texH cm.uvMax.x /= texW cm.uvMax.y /= texH } return texH } private fun nextPow2(value: Int): Int { var pow2 = 16 while (pow2 < value && pow2 < maxHeight) { pow2 = pow2 shl 1 } return pow2 } }
kool-core/src/jvmMain/kotlin/de/fabmax/kool/platform/FontMapGenerator.kt
2747932701
package info.nightscout.androidaps.danars.comm import android.content.Context import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Config import info.nightscout.androidaps.danars.DanaRSPlugin import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) @PrepareForTest(ConstraintChecker::class, DetailedBolusInfoStorage::class) class DanaRS_Packet_Bolus_Set_Step_Bolus_StartTest : DanaRSTestBase() { @Mock lateinit var constraintChecker: ConstraintChecker @Mock lateinit var commandQueue: CommandQueueProvider @Mock lateinit var context: Context @Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage private lateinit var danaRSPlugin: DanaRSPlugin private val packetInjector = HasAndroidInjector { AndroidInjector { if (it is DanaRS_Packet_Bolus_Set_Step_Bolus_Start) { it.aapsLogger = aapsLogger it.danaPump = danaPump it.constraintChecker = constraintChecker } } } @Test fun runTest() { val packet = DanaRS_Packet_Bolus_Set_Step_Bolus_Start(packetInjector) // test params val testparams = packet.requestParams Assert.assertEquals(0.toByte(), testparams[0]) Assert.assertEquals(0.toByte(), testparams[2]) // test message decoding packet.handleMessage(byteArrayOf(0.toByte(), 0.toByte(), 0.toByte())) Assert.assertEquals(false, packet.failed) packet.handleMessage(byteArrayOf(1.toByte(), 1.toByte(), 1.toByte(), 1.toByte(), 1.toByte(), 1.toByte(), 1.toByte(), 1.toByte())) Assert.assertEquals(true, packet.failed) Assert.assertEquals("BOLUS__SET_STEP_BOLUS_START", packet.friendlyName) } @Before fun mock() { danaRSPlugin = DanaRSPlugin(HasAndroidInjector { AndroidInjector { Unit } }, aapsLogger, rxBus, context, resourceHelper, constraintChecker, profileFunction, activePluginProvider, sp, commandQueue, danaPump, detailedBolusInfoStorage, fabricPrivacy, dateUtil) Mockito.`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0)) } }
app/src/test/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StartTest.kt
1150895860
package eu.corvus.essentials.core.mvc import android.os.Bundle import android.support.v4.app.Fragment import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView /** * Created by Vlad Cazacu on 17.03.2017. */ abstract class BaseFragment : Fragment(), ModelView { private lateinit var rootView: View open val controller: BaseController<out ModelView>? = null abstract val viewId: Int override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { if(viewId == 0) rootView = TextView(context).apply { layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) gravity = Gravity.CENTER text = "View not setup" } else rootView = inflater.inflate(viewId, container, false) return rootView } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) controller?.attach(this) } override fun onResume() { super.onResume() controller?.onRestore() } override fun onPause() { super.onPause() onStart() } override fun onDestroyView() { super.onDestroyView() controller?.dettach() } override fun onDestroy() { super.onDestroy() controller?.dettach() } }
app/src/main/java/eu/corvus/essentials/core/mvc/BaseFragment.kt
1089938353
// WITH_RUNTIME // PROBLEM: none fun test() { <caret>System.err.print("foo") }
plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceJavaStaticMethodWithKotlinAnalog/io/notApplicablePrint.kt
369170076
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea import com.intellij.ProjectTopics import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.ReadAction import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootEvent import com.intellij.openapi.roots.ModuleRootListener import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.updateSettings.impl.UpdateChecker.excludedFromUpdateCheckPlugins import com.intellij.util.concurrency.AppExecutorUtil import org.jetbrains.kotlin.diagnostics.DiagnosticFactory import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinPluginCompatibilityVerifier.checkCompatibility import org.jetbrains.kotlin.idea.configuration.ui.notifications.notifyKotlinStyleUpdateIfNeeded import org.jetbrains.kotlin.idea.reporter.KotlinReportSubmitter.Companion.setupReportingFromRelease import org.jetbrains.kotlin.idea.search.containsKotlinFile import org.jetbrains.kotlin.js.resolve.diagnostics.ErrorsJs import org.jetbrains.kotlin.resolve.jvm.KotlinJavaPsiFacade import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm import org.jetbrains.kotlin.resolve.konan.diagnostics.ErrorsNative import java.util.concurrent.Callable internal class PluginStartupActivity : StartupActivity.Background { override fun runActivity(project: Project) { val startupService = PluginStartupService.getInstance(project) startupService.register() project.messageBus.connect(startupService).subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener { override fun rootsChanged(event: ModuleRootEvent) { KotlinJavaPsiFacade.getInstance(project).clearPackageCaches() } }) initializeDiagnostics() excludedFromUpdateCheckPlugins.add("org.jetbrains.kotlin") checkCompatibility() setupReportingFromRelease() //todo[Sedunov]: wait for fix in platform to avoid misunderstood from Java newbies (also ConfigureKotlinInTempDirTest) //KotlinSdkType.Companion.setUpIfNeeded(); ReadAction.nonBlocking(Callable { project.containsKotlinFile() }) .inSmartMode(project) .expireWith(startupService) .finishOnUiThread(ModalityState.any()) { hasKotlinFiles -> if (!hasKotlinFiles) return@finishOnUiThread if (!ApplicationManager.getApplication().isHeadlessEnvironment) { notifyKotlinStyleUpdateIfNeeded(project) } val daemonCodeAnalyzer = DaemonCodeAnalyzerImpl.getInstanceEx(project) as DaemonCodeAnalyzerImpl daemonCodeAnalyzer.serializeCodeInsightPasses(true) } .submit(AppExecutorUtil.getAppExecutorService()) } companion object { /* Concurrent access to Errors may lead to the class loading dead lock because of non-trivial initialization in Errors. As a work-around, all Error classes are initialized beforehand. It doesn't matter what exact diagnostic factories are used here. */ private fun initializeDiagnostics() { consumeFactory(Errors.DEPRECATION) consumeFactory(ErrorsJvm.ACCIDENTAL_OVERRIDE) consumeFactory(ErrorsJs.CALL_FROM_UMD_MUST_BE_JS_MODULE_AND_JS_NON_MODULE) consumeFactory(ErrorsNative.INCOMPATIBLE_THROWS_INHERITED) } private inline fun consumeFactory(factory: DiagnosticFactory<*>) { factory.javaClass } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/PluginStartupActivity.kt
3462936555
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtClass // OPTIONS: derivedClasses interface Z: A { } object O1: A() object O2: Z
plugins/kotlin/idea/tests/testData/findUsages/kotlin/findClassUsages/kotlinClassDerivedObjects.1.kt
3259595776
// WITH_RUNTIME fun fn(index : Int, list: List<()->Unit>) { when { index in list.indices -> <selection>list[index]</selection>() } }
plugins/kotlin/idea/tests/testData/refactoring/introduceVariable/ComplexCallee.kt
2125844295
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.quickfix.QuickFixUtil import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isNullExpression import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.error.ErrorUtils import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.typeUtil.makeNullable import java.util.* open class ChangeVariableTypeFix(element: KtCallableDeclaration, type: KotlinType) : KotlinQuickFixAction<KtCallableDeclaration>(element) { private val typeContainsError = ErrorUtils.containsErrorType(type) private val typePresentation = IdeDescriptorRenderers.SOURCE_CODE_TYPES_WITH_SHORT_NAMES.renderType(type) private val typeSourceCode = IdeDescriptorRenderers.SOURCE_CODE_TYPES.renderType(type) open fun variablePresentation(): String? { val element = element!! val name = element.name return if (name != null) { val container = element.unsafeResolveToDescriptor().containingDeclaration as? ClassDescriptor val containerName = container?.name?.takeUnless { it.isSpecial }?.asString() if (containerName != null) "'$containerName.$name'" else "'$name'" } else { null } } override fun getText(): String { if (element == null) return "" val variablePresentation = variablePresentation() return if (variablePresentation != null) { KotlinBundle.message("change.type.of.0.to.1", variablePresentation, typePresentation) } else { KotlinBundle.message("change.type.to.0", typePresentation) } } class OnType(element: KtCallableDeclaration, type: KotlinType) : ChangeVariableTypeFix(element, type), HighPriorityAction { override fun variablePresentation() = null } class ForOverridden(element: KtVariableDeclaration, type: KotlinType) : ChangeVariableTypeFix(element, type) { override fun variablePresentation(): String? { val presentation = super.variablePresentation() ?: return null return KotlinBundle.message("base.property.0", presentation) } } override fun getFamilyName() = KotlinBundle.message("fix.change.return.type.family") override fun isAvailable(project: Project, editor: Editor?, file: KtFile) = !typeContainsError override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val psiFactory = KtPsiFactory(file) assert(element.nameIdentifier != null) { "ChangeVariableTypeFix applied to variable without name" } val replacingTypeReference = psiFactory.createType(typeSourceCode) val toShorten = ArrayList<KtTypeReference>() toShorten.add(element.setTypeReference(replacingTypeReference)!!) if (element is KtProperty) { val getterReturnTypeRef = element.getter?.returnTypeReference if (getterReturnTypeRef != null) { toShorten.add(getterReturnTypeRef.replace(replacingTypeReference) as KtTypeReference) } val setterParameterTypeRef = element.setter?.parameter?.typeReference if (setterParameterTypeRef != null) { toShorten.add(setterParameterTypeRef.replace(replacingTypeReference) as KtTypeReference) } } ShortenReferences.DEFAULT.process(toShorten) } object ComponentFunctionReturnTypeMismatchFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val entry = ChangeCallableReturnTypeFix.getDestructuringDeclarationEntryThatTypeMismatchComponentFunction(diagnostic) val context = entry.analyze() val resolvedCall = context.get(BindingContext.COMPONENT_RESOLVED_CALL, entry) ?: return null if (DescriptorToSourceUtils.descriptorToDeclaration(resolvedCall.candidateDescriptor) == null) return null val expectedType = resolvedCall.candidateDescriptor.returnType ?: return null return ChangeVariableTypeFix(entry, expectedType) } } object PropertyOrReturnTypeMismatchOnOverrideFactory : KotlinIntentionActionsFactory() { override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> { val actions = LinkedList<IntentionAction>() val element = diagnostic.psiElement as? KtCallableDeclaration if (element !is KtProperty && element !is KtParameter) return actions val descriptor = element.resolveToDescriptorIfAny(BodyResolveMode.FULL) as? PropertyDescriptor ?: return actions var lowerBoundOfOverriddenPropertiesTypes = QuickFixUtil.findLowerBoundOfOverriddenCallablesReturnTypes(descriptor) val propertyType = descriptor.returnType ?: error("Property type cannot be null if it mismatches something") val overriddenMismatchingProperties = LinkedList<PropertyDescriptor>() var canChangeOverriddenPropertyType = true for (overriddenProperty in descriptor.overriddenDescriptors) { val overriddenPropertyType = overriddenProperty.returnType if (overriddenPropertyType != null) { if (!KotlinTypeChecker.DEFAULT.isSubtypeOf(propertyType, overriddenPropertyType)) { overriddenMismatchingProperties.add(overriddenProperty) } else if (overriddenProperty.isVar && !KotlinTypeChecker.DEFAULT.equalTypes( overriddenPropertyType, propertyType ) ) { canChangeOverriddenPropertyType = false } if (overriddenProperty.isVar && lowerBoundOfOverriddenPropertiesTypes != null && !KotlinTypeChecker.DEFAULT.equalTypes(lowerBoundOfOverriddenPropertiesTypes, overriddenPropertyType) ) { lowerBoundOfOverriddenPropertiesTypes = null } } } if (lowerBoundOfOverriddenPropertiesTypes != null) { actions.add(OnType(element, lowerBoundOfOverriddenPropertiesTypes)) } if (overriddenMismatchingProperties.size == 1 && canChangeOverriddenPropertyType) { val overriddenProperty = DescriptorToSourceUtils.descriptorToDeclaration(overriddenMismatchingProperties.single()) if (overriddenProperty is KtProperty) { actions.add(ForOverridden(overriddenProperty, propertyType)) } } return actions } } object VariableInitializedWithNullFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val binaryExpression = diagnostic.psiElement.getStrictParentOfType<KtBinaryExpression>() ?: return null val left = binaryExpression.left ?: return null if (binaryExpression.operationToken != KtTokens.EQ) return null val property = left.mainReference?.resolve() as? KtProperty ?: return null if (!property.isVar || property.typeReference != null || !property.initializer.isNullExpression()) return null val actualType = when (diagnostic.factory) { Errors.TYPE_MISMATCH -> Errors.TYPE_MISMATCH.cast(diagnostic).b Errors.TYPE_MISMATCH_WARNING -> Errors.TYPE_MISMATCH_WARNING.cast(diagnostic).b ErrorsJvm.NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS -> ErrorsJvm.NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS.cast(diagnostic).b else -> null } ?: return null return ChangeVariableTypeFix(property, actualType.makeNullable()) } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeVariableTypeFix.kt
1233761077
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package codegen.inline.changingCapturedLocal import kotlin.test.* var log = "" inline fun foo(x: Int, action: (Int) -> Unit) = action(x) fun box(): String { var x = 23 foo(x) { log += "$it;" x++ log += "$it;" } if (log != "23;23;") return "fail1: $log" if (x != 24) return "fail2: $x" return "OK" } @Test fun runTest() { println(box()) }
backend.native/tests/codegen/inline/changingCapturedLocal.kt
2644978943
package com.github.kerubistan.kerub.model import com.github.kerubistan.kerub.model.SoftwarePackage.Companion.pack import org.junit.Assert.assertEquals import org.junit.Test class SoftwarePackageTest { @Test fun testToString() { assertEquals("awesomeshit-1.2.3",pack("awesomeshit","1.2.3").toString()) } }
src/test/kotlin/com/github/kerubistan/kerub/model/SoftwarePackageTest.kt
2404459297
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.util.indexing import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.util.SystemProperties import com.intellij.util.ThrowableRunnable import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.concurrency.SequentialTaskExecutor import java.time.Duration import java.time.Instant import java.util.concurrent.Callable import java.util.concurrent.Future abstract class IndexDataInitializer<T> : Callable<T?> { override fun call(): T? { val log = Logger.getInstance(javaClass.name) val started = Instant.now() return try { val tasks = prepareTasks() runParallelTasks(tasks) val result = finish() val message = getInitializationFinishedMessage(result) log.info("Index data initialization done: ${Duration.between(started, Instant.now()).toMillis()} ms. " + message) result } catch (t: Throwable) { log.error("Index data initialization failed", t) throw t } } protected abstract fun getInitializationFinishedMessage(initializationResult: T): String protected abstract fun finish(): T protected abstract fun prepareTasks(): Collection<ThrowableRunnable<*>> @Throws(InterruptedException::class) private fun runParallelTasks(tasks: Collection<ThrowableRunnable<*>>) { if (tasks.isEmpty()) { return } if (ourDoParallelIndicesInitialization) { val taskExecutor = AppExecutorUtil.createBoundedApplicationPoolExecutor( "Index Instantiation Pool", UnindexedFilesUpdater.getNumberOfIndexingThreads() ) tasks .asSequence() .map<ThrowableRunnable<*>, Future<*>?> { taskExecutor.submit { executeTask(it) } } .forEach { try { it!!.get() } catch (e: Exception) { LOG.error(e) } } taskExecutor.shutdown() } else { for (callable in tasks) { executeTask(callable) } } } private fun executeTask(callable: ThrowableRunnable<*>) { val app = ApplicationManager.getApplication() try { // To correctly apply file removals in indices shutdown hook we should process all initialization tasks // Todo: make processing removed files more robust because ignoring 'dispose in progress' delays application exit and // may cause memory leaks IDEA-183718, IDEA-169374, if (app.isDisposed /*|| app.isDisposeInProgress()*/) { return } callable.run() } catch (t: Throwable) { LOG.error(t) } } companion object { private val LOG = Logger.getInstance(IndexDataInitializer::class.java) private val ourDoParallelIndicesInitialization = SystemProperties.getBooleanProperty("idea.parallel.indices.initialization", true) @JvmField val ourDoAsyncIndicesInitialization = SystemProperties.getBooleanProperty("idea.async.indices.initialization", true) private val ourGenesisExecutor = SequentialTaskExecutor.createSequentialApplicationPoolExecutor("Index Data Initializer Pool") @JvmStatic fun <T> submitGenesisTask(action: Callable<T>): Future<T> { return ourGenesisExecutor.submit(action) } } }
platform/lang-impl/src/com/intellij/util/indexing/IndexDataInitializer.kt
942159356
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.js.backend.ast.metadata import kotlin.reflect.KProperty class MetadataProperty<in T : HasMetadata, R>(val default: R) { operator fun getValue(thisRef: T, desc: KProperty<*>): R { if (!thisRef.hasData(desc.name)) return default return thisRef.getData<R>(desc.name) } operator fun setValue(thisRef: T, desc: KProperty<*>, value: R) { thisRef.setData(desc.name, value) } }
phizdets/phizdetsc/src/org/jetbrains/kotlin/js/backend/ast/metadata/MetadataProperty.kt
1485851488
// Copyright 2000-2021 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.vcs.log.history import com.intellij.diff.chains.DiffRequestChain import com.intellij.diff.chains.SimpleDiffRequestChain import com.intellij.diff.impl.DiffRequestProcessor import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.vcs.changes.ChainBackedDiffPreviewProvider import com.intellij.openapi.vcs.changes.actions.diff.ChangeDiffRequestProducer import com.intellij.vcs.log.VcsLogBundle import com.intellij.vcs.log.VcsLogDataKeys import com.intellij.vcs.log.ui.actions.history.CompareRevisionsFromFileHistoryActionProvider import com.intellij.vcs.log.ui.frame.EditorDiffPreview import org.jetbrains.annotations.Nls import javax.swing.JComponent import javax.swing.event.ListSelectionListener class FileHistoryEditorDiffPreview(project: Project, private val fileHistoryPanel: FileHistoryPanel) : EditorDiffPreview(project, fileHistoryPanel), ChainBackedDiffPreviewProvider { init { init() } override fun getOwnerComponent(): JComponent = fileHistoryPanel.graphTable override fun getEditorTabName(processor: DiffRequestProcessor?): @Nls String = VcsLogBundle.message("file.history.diff.preview.editor.tab.name", fileHistoryPanel.filePath.name) override fun addSelectionListener(listener: () -> Unit) { val selectionListener = ListSelectionListener { if (!fileHistoryPanel.graphTable.selectionModel.isSelectionEmpty) { listener() } } fileHistoryPanel.graphTable.selectionModel.addListSelectionListener(selectionListener) Disposer.register(owner, Disposable { fileHistoryPanel.graphTable.selectionModel.removeListSelectionListener(selectionListener) }) } override fun createDiffRequestProcessor(): DiffRequestProcessor { val preview: FileHistoryDiffProcessor = fileHistoryPanel.createDiffPreview(true) preview.updatePreview(true) return preview } override fun createDiffRequestChain(): DiffRequestChain? { val change = fileHistoryPanel.selectedChange ?: return null val producer = ChangeDiffRequestProducer.create(project, change) ?: return null return SimpleDiffRequestChain.fromProducer(producer) } override fun updateAvailability(event: AnActionEvent) { val log = event.getData(VcsLogDataKeys.VCS_LOG) ?: return CompareRevisionsFromFileHistoryActionProvider.setTextAndDescription(event, log) } }
platform/vcs-log/impl/src/com/intellij/vcs/log/history/FileHistoryDiffPreview.kt
4104240365
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.editor.tables import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.util.siblings import com.intellij.refactoring.suggested.endOffset import com.intellij.refactoring.suggested.startOffset import com.intellij.util.containers.ContainerUtil import org.intellij.plugins.markdown.editor.tables.TableUtils.calculateActualTextRange import org.intellij.plugins.markdown.editor.tables.TableUtils.columnsCount import org.intellij.plugins.markdown.editor.tables.TableUtils.getColumnAlignment import org.intellij.plugins.markdown.editor.tables.TableUtils.getColumnCells import org.intellij.plugins.markdown.editor.tables.TableUtils.separatorRow import org.intellij.plugins.markdown.lang.MarkdownTokenTypes import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTable import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTableCell import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTableRow import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTableSeparatorRow import org.intellij.plugins.markdown.lang.psi.util.hasType import org.jetbrains.annotations.ApiStatus @ApiStatus.Internal @ApiStatus.Experimental object TableModificationUtils { /** * Modifies column with [columnIndex], calling [transformCell] on each cell and * [transformSeparator] on corresponding separator cell. */ fun MarkdownTable.modifyColumn( columnIndex: Int, transformSeparator: (TextRange) -> Unit, transformCell: (MarkdownTableCell) -> Unit ): Boolean { val separatorRange = separatorRow?.getCellRange(columnIndex) ?: return false val headerCell = headerRow?.getCell(columnIndex) ?: return false val cells = getColumnCells(columnIndex, withHeader = false) for (cell in cells.asReversed()) { transformCell.invoke(cell) } transformSeparator.invoke(separatorRange) transformCell.invoke(headerCell) return true } private fun getCellPotentialWidth(cellText: String): Int { var width = cellText.length if (!cellText.startsWith(' ')) { width += 1 } if (!cellText.endsWith(' ')) { width += 1 } return width } private fun isSeparatorCellCorrectlyFormatted(cellText: String): Boolean { // Don't have to validate ':' count and positions, since it won't be a separator at all return cellText.all { it =='-' || it == ':' } } fun MarkdownTableCell.hasCorrectPadding(): Boolean { val cellText = text return text.length >= TableProps.MIN_CELL_WIDTH && cellText.startsWith(" ") && cellText.endsWith(" ") } @Suppress("MemberVisibilityCanBePrivate") fun MarkdownTable.isColumnCorrectlyFormatted(columnIndex: Int, checkAlignment: Boolean = true): Boolean { val cells = getColumnCells(columnIndex, withHeader = true) if (cells.isEmpty()) { return true } if (checkAlignment && !validateColumnAlignment(columnIndex)) { return false } val separatorCellText = separatorRow?.getCellText(columnIndex)!! val width = getCellPotentialWidth(cells.first().text) if (separatorCellText.length != width || !isSeparatorCellCorrectlyFormatted(separatorCellText)) { return false } return cells.all { val selfWidth = getCellPotentialWidth(it.text) it.hasCorrectPadding() && selfWidth == it.textRange.length && selfWidth == width } } fun MarkdownTable.isCorrectlyFormatted(checkAlignment: Boolean = true): Boolean { return (0 until columnsCount).all { isColumnCorrectlyFormatted(it, checkAlignment) } } fun MarkdownTableCell.hasValidAlignment(): Boolean { val table = parentTable ?: return true val columnAlignment = table.getColumnAlignment(columnIndex) return hasValidAlignment(columnAlignment) } fun MarkdownTableCell.hasValidAlignment(expected: MarkdownTableSeparatorRow.CellAlignment): Boolean { val content = text if (content.length < TableProps.MIN_CELL_WIDTH) { return false } if (content.isBlank()) { return true } when (expected) { MarkdownTableSeparatorRow.CellAlignment.LEFT -> { return content[0] == ' ' && content[1] != ' ' } MarkdownTableSeparatorRow.CellAlignment.RIGHT -> { return content.last() == ' ' && content[content.lastIndex - 1] != ' ' } MarkdownTableSeparatorRow.CellAlignment.CENTER -> { var spacesLeft = content.indexOfFirst { it != ' ' } var spacesRight = content.indexOfLast { it != ' ' } if (spacesLeft == -1 || spacesRight == -1) { return true } spacesLeft += 1 spacesRight = content.lastIndex - spacesRight + 1 return spacesLeft == spacesRight || (spacesLeft + 1 == spacesRight) } else -> return true } } fun MarkdownTable.validateColumnAlignment(columnIndex: Int): Boolean { val expected = separatorRow!!.getCellAlignment(columnIndex) if (expected == MarkdownTableSeparatorRow.CellAlignment.NONE) { return true } return getColumnCells(columnIndex, true).all { it.hasValidAlignment(expected) } } /** * @param cellContentWidth Should be at least 5 */ fun buildSeparatorCellContent(alignment: MarkdownTableSeparatorRow.CellAlignment, cellContentWidth: Int): String { check(cellContentWidth > 4) return when (alignment) { MarkdownTableSeparatorRow.CellAlignment.NONE -> "-".repeat(cellContentWidth) MarkdownTableSeparatorRow.CellAlignment.LEFT -> ":${"-".repeat(cellContentWidth - 1)}" MarkdownTableSeparatorRow.CellAlignment.RIGHT -> "${"-".repeat(cellContentWidth - 1)}:" MarkdownTableSeparatorRow.CellAlignment.CENTER -> ":${"-".repeat(cellContentWidth - 2)}:" } } fun buildRealignedCellContent(cellContent: String, wholeCellWidth: Int, alignment: MarkdownTableSeparatorRow.CellAlignment): String { check(wholeCellWidth >= cellContent.length) return when (alignment) { MarkdownTableSeparatorRow.CellAlignment.RIGHT -> "${" ".repeat(wholeCellWidth - cellContent.length - 1)}$cellContent " MarkdownTableSeparatorRow.CellAlignment.CENTER -> { val leftPadding = (wholeCellWidth - cellContent.length) / 2 val rightPadding = wholeCellWidth - cellContent.length - leftPadding buildString { repeat(leftPadding) { append(' ') } append(cellContent) repeat(rightPadding) { append(' ') } } } // MarkdownTableSeparatorRow.CellAlignment.LEFT else -> " $cellContent${" ".repeat(wholeCellWidth - cellContent.length - 1)}" } } fun MarkdownTableCell.getContentWithoutWhitespaces(document: Document): String { val range = textRange val content = document.charsSequence.substring(range.startOffset, range.endOffset) return content.trim(' ') } fun MarkdownTableSeparatorRow.updateAlignment(document: Document, columnIndex: Int, alignment: MarkdownTableSeparatorRow.CellAlignment) { val cellRange = getCellRange(columnIndex)!! val width = cellRange.length //check(width >= TableProps.MIN_CELL_WIDTH) val replacement = buildSeparatorCellContent(alignment, width) document.replaceString(cellRange.startOffset, cellRange.endOffset, replacement) } fun MarkdownTableCell.updateAlignment(document: Document, alignment: MarkdownTableSeparatorRow.CellAlignment) { if (alignment == MarkdownTableSeparatorRow.CellAlignment.NONE) { return } val documentText = document.charsSequence val cellRange = textRange val cellText = documentText.substring(cellRange.startOffset, cellRange.endOffset) val actualContent = cellText.trim(' ') val replacement = buildRealignedCellContent(actualContent, cellText.length, alignment) document.replaceString(cellRange.startOffset, cellRange.endOffset, replacement) } fun MarkdownTable.updateColumnAlignment(document: Document, columnIndex: Int, alignment: MarkdownTableSeparatorRow.CellAlignment) { modifyColumn( columnIndex, transformSeparator = { separatorRow?.updateAlignment(document, columnIndex, alignment) }, transformCell = { it.updateAlignment(document, alignment) } ) } fun MarkdownTable.updateColumnAlignment(document: Document, columnIndex: Int) { val alignment = separatorRow?.getCellAlignment(columnIndex) ?: return updateColumnAlignment(document, columnIndex, alignment) } fun MarkdownTable.buildEmptyRow(builder: StringBuilder = StringBuilder()): StringBuilder { val header = checkNotNull(headerRow) builder.append(TableProps.SEPARATOR_CHAR) for (cell in header.cells) { repeat(cell.textRange.length) { builder.append(' ') } builder.append(TableProps.SEPARATOR_CHAR) } return builder } fun MarkdownTable.selectColumn( editor: Editor, columnIndex: Int, withHeader: Boolean = false, withSeparator: Boolean = false, withBorders: Boolean = false ) { val cells = getColumnCells(columnIndex, withHeader) val caretModel = editor.caretModel caretModel.removeSecondaryCarets() caretModel.currentCaret.apply { val textRange = obtainCellSelectionRange(cells.first(), withBorders) moveToOffset(textRange.startOffset) setSelectionFromRange(textRange) } if (withSeparator) { val range = when { withBorders -> separatorRow?.getCellRangeWithPipes(columnIndex) else -> separatorRow?.getCellRange(columnIndex) } range?.let { textRange -> val caret = caretModel.addCaret(editor.offsetToVisualPosition(textRange.startOffset)) caret?.setSelectionFromRange(textRange) } } for (cell in cells.asSequence().drop(1)) { val textRange = obtainCellSelectionRange(cell, withBorders) val caret = caretModel.addCaret(editor.offsetToVisualPosition(textRange.startOffset)) caret?.setSelectionFromRange(textRange) } } private fun obtainCellSelectionRange(cell: MarkdownTableCell, withBorders: Boolean): TextRange { val range = cell.textRange if (!withBorders) { return range } val leftPipe = cell.siblings(forward = false, withSelf = false) .takeWhile { it !is MarkdownTableCell } .find { it.hasType(MarkdownTokenTypes.TABLE_SEPARATOR) } val rightPipe = cell.siblings(forward = true, withSelf = false) .takeWhile { it !is MarkdownTableCell } .find { it.hasType(MarkdownTokenTypes.TABLE_SEPARATOR) } val left = leftPipe?.startOffset ?: range.startOffset val right = rightPipe?.endOffset ?: range.endOffset return TextRange(left, right) } private fun Caret.setSelectionFromRange(textRange: TextRange) { setSelection(textRange.startOffset, textRange.endOffset) } fun MarkdownTable.insertColumn( document: Document, columnIndex: Int, after: Boolean = true, alignment: MarkdownTableSeparatorRow.CellAlignment = MarkdownTableSeparatorRow.CellAlignment.NONE, columnWidth: Int = TableProps.MIN_CELL_WIDTH ) { val cells = getColumnCells(columnIndex, withHeader = false) val headerCell = headerRow?.getCell(columnIndex)!! val separatorCell = separatorRow?.getCellRange(columnIndex)!! val cellContent = " ".repeat(columnWidth) for (cell in cells.asReversed()) { when { after -> document.insertString(cell.endOffset + 1, "${cellContent}${TableProps.SEPARATOR_CHAR}") else -> document.insertString(cell.startOffset - 1, "${TableProps.SEPARATOR_CHAR}${cellContent}") } } when { after -> document.insertString(separatorCell.endOffset + 1, "${buildSeparatorCellContent(alignment, columnWidth)}${TableProps.SEPARATOR_CHAR}") else -> document.insertString(separatorCell.startOffset - 1, "${TableProps.SEPARATOR_CHAR}${buildSeparatorCellContent(alignment, columnWidth)}") } when { after -> document.insertString(headerCell.endOffset + 1, "${cellContent}${TableProps.SEPARATOR_CHAR}") else -> document.insertString(headerCell.startOffset - 1, "${TableProps.SEPARATOR_CHAR}${cellContent}") } } fun buildEmptyRow(columns: Int, fillCharacter: Char = ' ', builder: StringBuilder = StringBuilder()): StringBuilder { return builder.apply { repeat(columns) { append(TableProps.SEPARATOR_CHAR) repeat(TableProps.MIN_CELL_WIDTH) { append(fillCharacter) } } append(TableProps.SEPARATOR_CHAR) } } @Suppress("MemberVisibilityCanBePrivate") fun buildHeaderSeparator(columns: Int, builder: StringBuilder = StringBuilder()): StringBuilder { return buildEmptyRow(columns, '-', builder) } fun buildEmptyTable(contentRows: Int, columns: Int): String { val builder = StringBuilder() buildEmptyRow(columns, builder = builder) builder.append('\n') buildHeaderSeparator(columns, builder = builder) builder.append('\n') repeat(contentRows) { buildEmptyRow(columns, builder = builder) builder.append('\n') } return builder.toString() } fun MarkdownTableRow.hasCorrectBorders(): Boolean { return firstChild?.hasType(MarkdownTokenTypes.TABLE_SEPARATOR) == true && lastChild?.hasType(MarkdownTokenTypes.TABLE_SEPARATOR) == true } fun MarkdownTableSeparatorRow.hasCorrectBorders(): Boolean { val range = calculateActualTextRange().shiftLeft(startOffset) val text = range.substring(text) val first = text.firstOrNull { !it.isWhitespace() } val last = text.lastOrNull { !it.isWhitespace() } return first == TableProps.SEPARATOR_CHAR && last == TableProps.SEPARATOR_CHAR } fun MarkdownTable.hasCorrectBorders(): Boolean { val rows = getRows(true) return rows.all { it.hasCorrectBorders() } && separatorRow?.hasCorrectBorders() == true } /** * Removes cell based on PSI. */ fun MarkdownTableSeparatorRow.removeCell(columnIndex: Int) { val contents = (0 until cellsCount).map { it to getCellText(it) } val newContents = contents.asSequence() .filter { (index, _) -> index != columnIndex } .map { (_, text) -> text } .joinToString( TableProps.SEPARATOR_CHAR.toString(), prefix = TableProps.SEPARATOR_CHAR.toString(), postfix = TableProps.SEPARATOR_CHAR.toString() ) replaceWithText(newContents) } /** * Swaps two cells based on PSI. */ fun MarkdownTableSeparatorRow.swapCells(leftIndex: Int, rightIndex: Int) { val contents = (0 until cellsCount).asSequence().map { getCellText(it) }.toMutableList() ContainerUtil.swapElements(contents, leftIndex, rightIndex) val newContents = contents.joinToString( TableProps.SEPARATOR_CHAR.toString(), prefix = TableProps.SEPARATOR_CHAR.toString(), postfix = TableProps.SEPARATOR_CHAR.toString() ) replaceWithText(newContents) } /** * Removes column based on PSI. */ fun MarkdownTable.removeColumn(columnIndex: Int) { val cells = getColumnCells(columnIndex, withHeader = true) for (cell in cells.asReversed()) { val parent = cell.parent when { columnIndex == 0 && cell.prevSibling?.hasType(MarkdownTokenTypes.TABLE_SEPARATOR) == true -> parent.deleteChildRange(cell.prevSibling, cell) cell.nextSibling?.hasType(MarkdownTokenTypes.TABLE_SEPARATOR) == true -> parent.deleteChildRange(cell, cell.nextSibling) else -> cell.delete() } } separatorRow?.removeCell(columnIndex) } }
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/tables/TableModificationUtils.kt
3192824272
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.camera.integration.camera2.pipe.dataholders /** * Data source for 1D graph visualizations. Implemented for both graphing state over time and * graphing value over time */ class KeyValueDataHolder { var value: String? = null fun updateValue(newValue: String?) { value = newValue } }
camera/integration-tests/camerapipetestapp/src/main/java/androidx/camera/integration/camera2/pipe/dataholders/KeyValueDataHolder.kt
3342570103
package com.kamer.orny.data.google import android.Manifest import android.content.Context import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential import com.google.api.client.util.ExponentialBackOff import com.google.api.services.sheets.v4.SheetsScopes import com.kamer.orny.data.android.ActivityHolder import com.kamer.orny.data.android.Prefs import com.kamer.orny.data.android.ReactiveActivities import com.kamer.orny.di.app.ApplicationScope import com.kamer.orny.utils.hasPermission import com.tbruyelle.rxpermissions2.RxPermissions import io.reactivex.Completable import io.reactivex.Observable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import java.util.* import javax.inject.Inject @ApplicationScope class GoogleAuthHolderImpl @Inject constructor( private val context: Context, private val prefs: Prefs, private val activityHolder: ActivityHolder, private val reactiveActivities: ReactiveActivities) : GoogleAuthHolder { companion object { private val SCOPES = arrayOf(SheetsScopes.SPREADSHEETS) } override fun login(): Completable { if (prefs.accountName.isNotEmpty()) { return Completable.complete() } return checkPermission() .andThen(createCredentials()) .flatMap { reactiveActivities.chooseGoogleAccount(it) } .flatMapCompletable { accountName -> Completable.fromAction { prefs.accountName = accountName } } } override fun logout(): Completable = Completable.fromAction { prefs.accountName = "" } override fun getActiveCredentials(): Single<GoogleAccountCredential> = checkAuth() .andThen(checkPermission()) .andThen(createCredentials()) .flatMap { credential -> checkIfAccountExist(credential) .toSingle { credential } } private fun createCredentials(): Single<GoogleAccountCredential> = Single.fromCallable { val accountCredential = GoogleAccountCredential.usingOAuth2( context, Arrays.asList<String>(*SCOPES)) .setBackOff(ExponentialBackOff()) accountCredential.selectedAccountName = prefs.accountName return@fromCallable accountCredential } private fun checkAuth(): Completable = Completable .fromAction { if (prefs.accountName.isEmpty()) { throw Exception("Not logged") } } .retryWhen { errorStream -> errorStream.flatMap { reactiveActivities.login().toSingleDefault("").toFlowable() } } private fun checkIfAccountExist(credential: GoogleAccountCredential): Completable = Completable .fromAction { if (context.hasPermission(Manifest.permission.GET_ACCOUNTS) && credential.selectedAccountName.isNullOrEmpty()) { prefs.accountName = "" throw Exception("Account not exist") } } .retryWhen { errorStream -> errorStream.flatMap { reactiveActivities.login().toSingleDefault("").toFlowable() } } private fun checkPermission(): Completable = Single.just("").flatMapCompletable { val activity = activityHolder.getActivity() return@flatMapCompletable when { context.hasPermission(Manifest.permission.GET_ACCOUNTS) -> Completable.complete() activity != null -> Observable .just("") .observeOn(AndroidSchedulers.mainThread()) //create RxPermissions() instance only when needed .flatMap { Observable.just("").compose(RxPermissions(activity).ensure(Manifest.permission.GET_ACCOUNTS)) } .observeOn(Schedulers.io()) .flatMapCompletable { granted -> if (granted) { Completable.complete() } else { Completable.error(SecurityException("Permission denied")) } } else -> Completable.error(Exception("No activity to check permission")) } } }
app/src/main/kotlin/com/kamer/orny/data/google/GoogleAuthHolderImpl.kt
3516167542
package com.wpapper.iping.ui.dialogs import android.os.Environment import android.os.Parcelable import android.support.v7.app.AlertDialog import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import android.util.Log import android.view.KeyEvent import android.view.LayoutInflater import com.simplemobiletools.commons.activities.BaseSimpleActivity import com.simplemobiletools.commons.adapters.FilepickerItemsAdapter import com.simplemobiletools.commons.dialogs.CreateNewFolderDialog import com.simplemobiletools.commons.dialogs.StoragePickerDialog import com.simplemobiletools.commons.extensions.beVisible import com.simplemobiletools.commons.extensions.getFilenameFromPath import com.simplemobiletools.commons.extensions.internalStoragePath import com.simplemobiletools.commons.extensions.setupDialogStuff import com.simplemobiletools.commons.models.FileDirItem import com.simplemobiletools.commons.views.Breadcrumbs import com.wpapper.iping.R import com.wpapper.iping.model.DataSave import com.wpapper.iping.ui.folder.FolderActivity import com.wpapper.iping.ui.utils.SSHManager import kotlinx.android.synthetic.main.dialog_filepicker.view.* import java.io.File import java.util.ArrayList import java.util.HashMap /** * The only filepicker constructor with a couple optional parameters * * @param activity * @param currPath initial path of the dialog, defaults to the external storage * @param pickFile toggle used to determine if we are picking a file or a folder * @param showHidden toggle for showing hidden items, whose name starts with a dot * @param showFAB toggle the displaying of a Floating Action Button for creating new folders * @param callback the callback used for returning the selected file/folder */ class FilePickerDialog(val activity: BaseSimpleActivity, var currPath: String = Environment.getExternalStorageDirectory().toString(), val pickFile: Boolean = true, val showHidden: Boolean = false, val showFAB: Boolean = false, val callback: (pickedPath: String) -> Unit) : Breadcrumbs.BreadcrumbsListener { var mFirstUpdate = true var mPrevPath = "" var mScrollStates = HashMap<String, Parcelable>() lateinit var mDialog: AlertDialog var mDialogView = LayoutInflater.from(activity).inflate(R.layout.dialog_filepicker, null) init { if (!File(currPath).exists()) { currPath = activity.internalStoragePath } if (File(currPath).isFile) { currPath = File(currPath).parent } mDialogView.filepicker_breadcrumbs.listener = this updateItems() val builder = AlertDialog.Builder(activity) .setNegativeButton(R.string.cancel, null) .setOnKeyListener({ dialogInterface, i, keyEvent -> if (keyEvent.action == KeyEvent.ACTION_UP && i == KeyEvent.KEYCODE_BACK) { val breadcrumbs = mDialogView.filepicker_breadcrumbs if (breadcrumbs.childCount > 1) { breadcrumbs.removeBreadcrumb() currPath = breadcrumbs.getLastItem().path updateItems() } else { mDialog.dismiss() } } true }) if (!pickFile) builder.setPositiveButton(R.string.ok, null) if (showFAB) { mDialogView.filepicker_fab.apply { beVisible() setOnClickListener { createNewFolder() } } } mDialog = builder.create().apply { context.setupDialogStuff(mDialogView, this, getTitle()) } if (!pickFile) { mDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener({ verifyPath() }) } } private fun getTitle() = if (pickFile) R.string.select_file else R.string.select_folder private fun createNewFolder() { CreateNewFolderDialog(activity, currPath) { callback(it.trimEnd('/')) mDialog.dismiss() } } private fun updateItems() { var items = getItems(currPath) if (!containsDirectory(items) && !mFirstUpdate && !pickFile && !showFAB) { verifyPath() return } items = items.sortedWith(compareBy({ !it.isDirectory }, { it.name.toLowerCase() })) val adapter = FilepickerItemsAdapter(activity, items) { if (it.isDirectory) { currPath = it.path updateItems() } else if (pickFile) { currPath = it.path verifyPath() } } val layoutManager = mDialogView.filepicker_list.layoutManager as LinearLayoutManager mScrollStates.put(mPrevPath.trimEnd('/'), layoutManager.onSaveInstanceState()) mDialogView.apply { if (filepicker_list.adapter == null) { DividerItemDecoration(context, DividerItemDecoration.VERTICAL).apply { setDrawable(context.resources.getDrawable(R.drawable.divider)) filepicker_list.addItemDecoration(this) } } filepicker_list.adapter = adapter filepicker_breadcrumbs.setBreadcrumb(currPath) filepicker_fastscroller.setViews(filepicker_list) } layoutManager.onRestoreInstanceState(mScrollStates[currPath.trimEnd('/')]) mFirstUpdate = false mPrevPath = currPath } private fun getItems(path: String, isRemote: Boolean = true, callback: (items: ArrayList<FileDirItem>) -> Unit) { Thread({ if (!isRemote) { getRegularItemsOf(path, callback) } else { Log.i("path=====", path) var host = (activity as FolderActivity).host var sshInfo = DataSave(activity).getData(host) if (sshInfo != null) { callback(SSHManager.newInstance().sshLs(sshInfo, path)) } } }).start() } private fun getRegularItemsOf(path: String, callback: (items: ArrayList<FileDirItem>) -> Unit) { val items = ArrayList<FileDirItem>() val files = File(path).listFiles() if (files != null) { for (file in files) { val curPath = file.absolutePath val curName = curPath.getFilenameFromPath() if (!showHidden && curName.startsWith(".")) continue val children = getChildren(file) val size = file.length() items.add(FileDirItem(curPath, curName, file.isDirectory, children, size)) } } callback(items) } private fun verifyPath() { val file = File(currPath) if ((pickFile && file.isFile) || (!pickFile && file.isDirectory)) { sendSuccess() } } private fun sendSuccess() { callback(if (currPath.length == 1) currPath else currPath.trimEnd('/')) mDialog.dismiss() } private fun getItems(path: String): List<FileDirItem> { val items = ArrayList<FileDirItem>() val base = File(path) val files = base.listFiles() ?: return items for (file in files) { if (!showHidden && file.isHidden) { continue } val curPath = file.absolutePath val curName = curPath.getFilenameFromPath() val size = file.length() items.add(FileDirItem(curPath, curName, file.isDirectory, getChildren(file), size)) } return items } private fun getChildren(file: File): Int { return if (file.listFiles() == null || !file.isDirectory) { 0 } else { file.listFiles().filter { !it.isHidden || (it.isHidden && showHidden) }.size } } private fun containsDirectory(items: List<FileDirItem>) = items.any { it.isDirectory } override fun breadcrumbClicked(id: Int) { if (id == 0) { StoragePickerDialog(activity, currPath) { index, path -> currPath = path updateItems() } } else { val item = mDialogView.filepicker_breadcrumbs.getChildAt(id).tag as FileDirItem if (currPath != item.path.trimEnd('/')) { currPath = item.path updateItems() } } } }
app/src/main/java/com/wpapper/iping/ui/dialogs/FilePickerDialog.kt
1211542898
/* * 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.room.util import androidx.room.migration.bundle.DatabaseBundle import androidx.room.migration.bundle.EntityBundle import androidx.room.migration.bundle.FieldBundle import androidx.room.migration.bundle.ForeignKeyBundle import androidx.room.migration.bundle.IndexBundle import androidx.room.migration.bundle.PrimaryKeyBundle import androidx.room.migration.bundle.SchemaBundle import androidx.room.migration.bundle.TABLE_NAME_PLACEHOLDER import androidx.room.processor.ProcessorErrors import androidx.room.vo.AutoMigration import com.google.common.truth.Truth.assertThat import org.junit.Assert.fail import org.junit.Test class SchemaDifferTest { @Test fun testPrimaryKeyChanged() { val diffResult = SchemaDiffer( fromSchemaBundle = from.database, toSchemaBundle = toChangeInPrimaryKey.database, className = "MyAutoMigration", renameColumnEntries = listOf(), deleteColumnEntries = listOf(), renameTableEntries = listOf(), deleteTableEntries = listOf() ).diffSchemas() assertThat(diffResult.complexChangedTables.keys).contains("Song") } @Test fun testForeignKeyFieldChanged() { val diffResult = SchemaDiffer( fromSchemaBundle = from.database, toSchemaBundle = toForeignKeyAdded.database, className = "MyAutoMigration", renameColumnEntries = listOf(), deleteColumnEntries = listOf(), renameTableEntries = listOf(), deleteTableEntries = listOf() ).diffSchemas() assertThat(diffResult.complexChangedTables["Song"] != null) } @Test fun testComplexChangeInvolvingIndex() { val diffResult = SchemaDiffer( fromSchemaBundle = from.database, toSchemaBundle = toIndexAdded.database, className = "MyAutoMigration", renameColumnEntries = listOf(), deleteColumnEntries = listOf(), renameTableEntries = listOf(), deleteTableEntries = listOf() ).diffSchemas() assertThat(diffResult.complexChangedTables["Song"] != null) } @Test fun testColumnAddedWithColumnInfoDefaultValue() { val schemaDiffResult = SchemaDiffer( fromSchemaBundle = from.database, toSchemaBundle = toColumnAddedWithColumnInfoDefaultValue.database, className = "MyAutoMigration", renameColumnEntries = listOf(), deleteColumnEntries = listOf(), renameTableEntries = listOf(), deleteTableEntries = listOf() ).diffSchemas() assertThat(schemaDiffResult.addedColumns.single().fieldBundle.columnName) .isEqualTo("artistId") } @Test fun testColumnsAddedInOrder() { val schemaDiffResult = SchemaDiffer( fromSchemaBundle = from.database, toSchemaBundle = toColumnsAddedInOrder.database, className = "MyAutoMigration", renameColumnEntries = listOf(), deleteColumnEntries = listOf(), renameTableEntries = listOf(), deleteTableEntries = listOf() ).diffSchemas() assertThat(schemaDiffResult.addedColumns).hasSize(2) assertThat(schemaDiffResult.addedColumns[0].fieldBundle.columnName) .isEqualTo("recordLabelId") assertThat(schemaDiffResult.addedColumns[1].fieldBundle.columnName) .isEqualTo("artistId") } @Test fun testColumnAddedWithNoDefaultValue() { try { SchemaDiffer( fromSchemaBundle = from.database, toSchemaBundle = toColumnAddedWithNoDefaultValue.database, className = "MyAutoMigration", renameColumnEntries = listOf(), deleteColumnEntries = listOf(), renameTableEntries = listOf(), deleteTableEntries = listOf() ).diffSchemas() fail("DiffException should have been thrown.") } catch (ex: DiffException) { assertThat(ex.errorMessage).isEqualTo( ProcessorErrors.newNotNullColumnMustHaveDefaultValue("artistId") ) } } @Test fun testTableAddedWithColumnInfoDefaultValue() { val schemaDiffResult = SchemaDiffer( fromSchemaBundle = from.database, toSchemaBundle = toTableAddedWithColumnInfoDefaultValue.database, className = "MyAutoMigration", renameColumnEntries = listOf(), deleteColumnEntries = listOf(), renameTableEntries = listOf(), deleteTableEntries = listOf() ).diffSchemas() assertThat(schemaDiffResult.addedTables.toList()[0].entityBundle.tableName) .isEqualTo("Album") } @Test fun testColumnsAddedWithSameName() { val schemaDiffResult = SchemaDiffer( fromSchemaBundle = from.database, toSchemaBundle = toColumnsAddedWithSameName.database, className = "MyAutoMigration", renameColumnEntries = listOf(), deleteColumnEntries = listOf(), renameTableEntries = listOf(), deleteTableEntries = listOf() ).diffSchemas() assertThat(schemaDiffResult.addedColumns).hasSize(2) assertThat( schemaDiffResult.addedColumns.any { it.tableName == "Song" && it.fieldBundle.columnName == "newColumn" } ).isTrue() assertThat( schemaDiffResult.addedColumns.any { it.tableName == "Artist" && it.fieldBundle.columnName == "newColumn" } ).isTrue() } @Test fun testColumnRenamed() { try { SchemaDiffer( fromSchemaBundle = from.database, toSchemaBundle = toColumnRenamed.database, className = "MyAutoMigration", renameColumnEntries = listOf(), deleteColumnEntries = listOf(), renameTableEntries = listOf(), deleteTableEntries = listOf() ).diffSchemas() fail("DiffException should have been thrown.") } catch (ex: DiffException) { assertThat(ex.errorMessage).isEqualTo( ProcessorErrors.deletedOrRenamedColumnFound("MyAutoMigration", "length", "Song") ) } } @Test fun testColumnRemoved() { try { SchemaDiffer( fromSchemaBundle = from.database, toSchemaBundle = toColumnRemoved.database, className = "MyAutoMigration", renameColumnEntries = listOf(), deleteColumnEntries = listOf(), renameTableEntries = listOf(), deleteTableEntries = listOf() ).diffSchemas() fail("DiffException should have been thrown.") } catch (ex: DiffException) { assertThat(ex.errorMessage).isEqualTo( ProcessorErrors.deletedOrRenamedColumnFound("MyAutoMigration", "length", "Song") ) } } @Test fun testTableRenamedWithoutAnnotation() { try { SchemaDiffer( fromSchemaBundle = from.database, toSchemaBundle = toTableRenamed.database, className = "MyAutoMigration", renameColumnEntries = listOf(), deleteColumnEntries = listOf(), renameTableEntries = listOf(), deleteTableEntries = listOf() ).diffSchemas() fail("DiffException should have been thrown.") } catch (ex: DiffException) { assertThat(ex.errorMessage).isEqualTo( ProcessorErrors.deletedOrRenamedTableFound("MyAutoMigration", "Artist") ) } } @Test fun testTableRemovedWithoutAnnotation() { try { SchemaDiffer( fromSchemaBundle = from.database, toSchemaBundle = toTableDeleted.database, className = "MyAutoMigration", renameColumnEntries = listOf(), deleteColumnEntries = listOf(), renameTableEntries = listOf(), deleteTableEntries = listOf() ).diffSchemas() fail("DiffException should have been thrown.") } catch (ex: DiffException) { assertThat(ex.errorMessage).isEqualTo( ProcessorErrors.deletedOrRenamedTableFound("MyAutoMigration", "Artist") ) } } @Test fun testRenameTwoColumnsOnComplexChangedTable() { val fromSchemaBundle = SchemaBundle( 1, DatabaseBundle( 1, "", mutableListOf( EntityBundle( "Song", "CREATE TABLE IF NOT EXISTS `$TABLE_NAME_PLACEHOLDER` (`id` " + "INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), mutableListOf(), mutableListOf() ) ), mutableListOf(), mutableListOf() ) ) val toSchemaBundle = SchemaBundle( 2, DatabaseBundle( 2, "", mutableListOf( EntityBundle( "SongTable", "CREATE TABLE IF NOT EXISTS `$TABLE_NAME_PLACEHOLDER` (`id` " + "INTEGER NOT NULL, " + "`songTitle` TEXT NOT NULL, `songLength` " + "INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "songTitle", "songTitle", "TEXT", true, "" ), FieldBundle( "songLength", "songLength", "INTEGER", true, "1" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), mutableListOf(), mutableListOf() ) ), mutableListOf(), mutableListOf() ) ) val schemaDiffResult = SchemaDiffer( fromSchemaBundle = fromSchemaBundle.database, toSchemaBundle = toSchemaBundle.database, className = "MyAutoMigration", renameColumnEntries = listOf( AutoMigration.RenamedColumn("Song", "title", "songTitle"), AutoMigration.RenamedColumn("Song", "length", "songLength") ), deleteColumnEntries = listOf(), renameTableEntries = listOf( AutoMigration.RenamedTable("Song", "SongTable") ), deleteTableEntries = listOf() ).diffSchemas() assertThat(schemaDiffResult.complexChangedTables.size).isEqualTo(1) schemaDiffResult.complexChangedTables.values.single().let { complexChange -> assertThat(complexChange.tableName).isEqualTo("Song") assertThat(complexChange.tableNameWithNewPrefix).isEqualTo("_new_SongTable") assertThat(complexChange.renamedColumnsMap).containsExactlyEntriesIn( mapOf("songTitle" to "title", "songLength" to "length") ) } } private val from = SchemaBundle( 1, DatabaseBundle( 1, "", mutableListOf( EntityBundle( "Song", "CREATE TABLE IF NOT EXISTS `Song` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), mutableListOf(), mutableListOf() ), EntityBundle( "Artist", "CREATE TABLE IF NOT EXISTS `Artist` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), mutableListOf(), mutableListOf() ) ), mutableListOf(), mutableListOf() ) ) //region Valid "to" Schemas private val toTableRenamed = SchemaBundle( 2, DatabaseBundle( 2, "", mutableListOf( EntityBundle( "Song", "CREATE TABLE IF NOT EXISTS `Song` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), mutableListOf(), mutableListOf() ), EntityBundle( "Album", "CREATE TABLE IF NOT EXISTS `Song` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), mutableListOf(), mutableListOf() ) ), mutableListOf(), mutableListOf() ) ) private val toTableDeleted = SchemaBundle( 2, DatabaseBundle( 2, "", mutableListOf( EntityBundle( "Song", "CREATE TABLE IF NOT EXISTS `Song` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), mutableListOf(), mutableListOf() ) ), mutableListOf(), mutableListOf() ) ) private val toColumnAddedWithColumnInfoDefaultValue = SchemaBundle( 2, DatabaseBundle( 2, "", listOf( EntityBundle( "Song", "CREATE TABLE IF NOT EXISTS `Song` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, `artistId` " + "INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ), FieldBundle( "artistId", "artistId", "INTEGER", true, "0" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), emptyList(), emptyList() ), EntityBundle( "Artist", "CREATE TABLE IF NOT EXISTS `Artist` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), mutableListOf(), mutableListOf() ) ), mutableListOf(), mutableListOf() ) ) /** * Adding multiple columns, preserving the order in which they have been added. */ private val toColumnsAddedInOrder = SchemaBundle( 2, DatabaseBundle( 2, "", listOf( EntityBundle( "Song", "CREATE TABLE IF NOT EXISTS `Song` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, `artistId` " + "INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ), FieldBundle( "recordLabelId", "recordLabelId", "INTEGER", true, "0" ), FieldBundle( "artistId", "artistId", "INTEGER", true, "0" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), emptyList(), emptyList() ), EntityBundle( "Artist", "CREATE TABLE IF NOT EXISTS `Artist` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ), ), PrimaryKeyBundle( false, mutableListOf("id") ), mutableListOf(), mutableListOf() ) ), mutableListOf(), mutableListOf() ) ) /** * Adding multiple columns, preserving the order in which they have been added. */ private val toColumnsAddedWithSameName = SchemaBundle( 2, DatabaseBundle( 2, "", listOf( EntityBundle( "Song", "CREATE TABLE IF NOT EXISTS `Song` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, `artistId` " + "INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ), FieldBundle( "newColumn", "newColumn", "INTEGER", true, "0" ), ), PrimaryKeyBundle( false, mutableListOf("id") ), emptyList(), emptyList() ), EntityBundle( "Artist", "CREATE TABLE IF NOT EXISTS `Artist` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ), FieldBundle( "newColumn", "newColumn", "INTEGER", true, "0" ), ), PrimaryKeyBundle( false, mutableListOf("id") ), mutableListOf(), mutableListOf() ) ), mutableListOf(), mutableListOf() ) ) /** * Renaming the length column to duration. */ private val toColumnRenamed = SchemaBundle( 2, DatabaseBundle( 2, "", mutableListOf( EntityBundle( "Song", "CREATE TABLE IF NOT EXISTS `Song` (`id` INTEGER NOT " + "NULL, `title` TEXT NOT NULL, `duration` INTEGER NOT NULL DEFAULT 0, " + "PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "duration", "duration", "INTEGER", true, "0" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), mutableListOf(), mutableListOf() ), EntityBundle( "Artist", "CREATE TABLE IF NOT EXISTS `Artist` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), mutableListOf(), mutableListOf() ) ), mutableListOf(), mutableListOf() ) ) /** * The affinity of a length column is changed from Integer to Text. No columns are * added/removed. */ val toColumnAffinityChanged = SchemaBundle( 2, DatabaseBundle( 2, "", mutableListOf( EntityBundle( "Song", "CREATE TABLE IF NOT EXISTS `Song` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` TEXT NOT NULL DEFAULT length, " + "PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "TEXT", true, "length" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), mutableListOf(), mutableListOf() ), EntityBundle( "Artist", "CREATE TABLE IF NOT EXISTS `Artist` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), mutableListOf(), mutableListOf() ) ), mutableListOf(), mutableListOf() ) ) private val toTableAddedWithColumnInfoDefaultValue = SchemaBundle( 1, DatabaseBundle( 1, "", mutableListOf( EntityBundle( "Song", "CREATE TABLE IF NOT EXISTS `Song` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), mutableListOf(), mutableListOf() ), EntityBundle( "Artist", "CREATE TABLE IF NOT EXISTS `Artist` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), mutableListOf(), mutableListOf() ), EntityBundle( "Album", "CREATE TABLE IF NOT EXISTS `Album` (`albumId` INTEGER NOT NULL, `name` TEXT " + "NOT NULL, PRIMARY KEY(`albumId`))", listOf( FieldBundle( "albumId", "albumId", "INTEGER", true, "1" ) ), PrimaryKeyBundle(true, listOf("albumId")), listOf(), listOf() ) ), mutableListOf(), mutableListOf() ) ) private val toForeignKeyAdded = SchemaBundle( 2, DatabaseBundle( 2, "", listOf( EntityBundle( "Song", "CREATE TABLE IF NOT EXISTS `Song` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, `artistId` " + "INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(`id`), FOREIGN KEY(`title`) " + "REFERENCES `Song`(`artistId`) ON UPDATE NO ACTION ON DELETE NO " + "ACTION DEFERRABLE INITIALLY DEFERRED))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ), FieldBundle( "artistId", "artistId", "INTEGER", true, "0" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), emptyList(), listOf( ForeignKeyBundle( "Song", "onDelete", "onUpdate", listOf("title"), listOf("artistId") ) ) ), EntityBundle( "Artist", "CREATE TABLE IF NOT EXISTS `Artist` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), mutableListOf(), mutableListOf() ) ), mutableListOf(), mutableListOf() ) ) val toIndexAdded = SchemaBundle( 2, DatabaseBundle( 2, "", mutableListOf( EntityBundle( "Song", "CREATE TABLE IF NOT EXISTS `Song` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), listOf( IndexBundle( "index1", true, emptyList<String>(), emptyList<String>(), "CREATE UNIQUE INDEX IF NOT EXISTS `index1` ON `Song`" + "(`title`)" ) ), mutableListOf() ), EntityBundle( "Artist", "CREATE TABLE IF NOT EXISTS `Artist` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), mutableListOf(), mutableListOf() ) ), mutableListOf(), mutableListOf() ) ) val toChangeInPrimaryKey = SchemaBundle( 2, DatabaseBundle( 2, "", mutableListOf( EntityBundle( "Song", "CREATE TABLE IF NOT EXISTS `Song` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, PRIMARY KEY(`title`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ) ), PrimaryKeyBundle( false, mutableListOf("title") ), mutableListOf(), mutableListOf() ), EntityBundle( "Artist", "CREATE TABLE IF NOT EXISTS `Artist` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), mutableListOf(), mutableListOf() ) ), mutableListOf(), mutableListOf() ) ) //endregion //region Invalid "to" Schemas (These are expected to throw an error.) /** * The length column is removed from the first version. No other changes made. */ private val toColumnRemoved = SchemaBundle( 2, DatabaseBundle( 2, "", listOf( EntityBundle( "Song", "CREATE TABLE IF NOT EXISTS `Song` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), ), PrimaryKeyBundle( false, mutableListOf("id") ), emptyList(), emptyList() ), EntityBundle( "Artist", "CREATE TABLE IF NOT EXISTS `Artist` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), mutableListOf(), mutableListOf() ) ), mutableListOf(), mutableListOf() ) ) /** * If the user declared the default value in the SQL statement and not used a @ColumnInfo, * Room will put null for that default value in the exported schema. In this case we * can't migrate. */ private val toColumnAddedWithNoDefaultValue = SchemaBundle( 2, DatabaseBundle( 2, "", listOf( EntityBundle( "Song", "CREATE TABLE IF NOT EXISTS `Song` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, `artistId` " + "INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ), FieldBundle( "artistId", "artistId", "INTEGER", true, null ) ), PrimaryKeyBundle( false, mutableListOf("id") ), emptyList(), emptyList() ), EntityBundle( "Artist", "CREATE TABLE IF NOT EXISTS `Artist` (`id` INTEGER NOT NULL, " + "`title` TEXT NOT NULL, `length` INTEGER NOT NULL, PRIMARY KEY(`id`))", listOf( FieldBundle( "id", "id", "INTEGER", true, "1" ), FieldBundle( "title", "title", "TEXT", true, "" ), FieldBundle( "length", "length", "INTEGER", true, "1" ) ), PrimaryKeyBundle( false, mutableListOf("id") ), mutableListOf(), mutableListOf() ) ), mutableListOf(), mutableListOf() ) ) //endregion }
room/room-compiler/src/test/kotlin/androidx/room/util/SchemaDifferTest.kt
2373413920
// WITH_STDLIB fun test(list: List<Pair<String, Int>>) { list.forEach { (s, _) -> println(s) }<caret> }
plugins/kotlin/idea/tests/testData/intentions/convertLambdaToSingleLine/simple6.kt
3898922483
class Foo { fun foo(other: Foo) { <lineMarker text="Recursive call">foo</lineMarker>(other) this.<lineMarker text="Recursive call">foo</lineMarker>(other) this@Foo.<lineMarker text="Recursive call">foo</lineMarker>(other) other.foo(this) with(other) { foo(this@Foo) foo(other) this@Foo.<lineMarker text="Recursive call">foo</lineMarker>(other) } } } open class Bar { open fun bar(other: Bar) { <lineMarker text="Recursive call">bar</lineMarker>(other) this.<lineMarker text="Recursive call">bar</lineMarker>(other) this@Bar.<lineMarker text="Recursive call">bar</lineMarker>(other) other.bar(this) } inner class Nested { fun bar(other: Bar) { <lineMarker text="Recursive call">bar</lineMarker>(other) this.<lineMarker text="Recursive call">bar</lineMarker>(other) this@Nested.<lineMarker text="Recursive call">bar</lineMarker>(other) [email protected](other) } } } object Obj { fun foo() { <lineMarker text="Recursive call">foo</lineMarker>() Obj.<lineMarker text="Recursive call">foo</lineMarker>() Nested.foo() } object Nested { fun foo() {} } } class BarImpl : Bar { override fun bar(other: Bar) {} }
plugins/kotlin/code-insight/line-markers/testData/recursive/dispatchReceiver.kt
2527085806
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.api object GHEServerVersionChecker { private const val REQUIRED_VERSION_MAJOR = 2 private const val REQUIRED_VERSION_MINOR = 21 const val ENTERPRISE_VERSION_HEADER = "x-github-enterprise-version" fun checkVersionSupported(versionValue: String) { val majorVersion: Int val minorVersion: Int try { val versionSplit = versionValue.split('.') majorVersion = versionSplit[0].toInt() minorVersion = versionSplit[1].toInt() } catch (e: Throwable) { throw IllegalStateException("Could not determine GitHub Enterprise server version", e) } when { majorVersion > REQUIRED_VERSION_MAJOR -> return majorVersion < REQUIRED_VERSION_MAJOR -> throwUnsupportedVersion(majorVersion, minorVersion) majorVersion == REQUIRED_VERSION_MAJOR -> if (minorVersion < REQUIRED_VERSION_MINOR) throwUnsupportedVersion(majorVersion, minorVersion) } } private fun throwUnsupportedVersion(currentMajor: Int, currentMinor: Int) { error( "Unsupported GitHub Enterprise server version $currentMajor.$currentMinor. Earliest supported version is $REQUIRED_VERSION_MAJOR.$REQUIRED_VERSION_MINOR" ) } }
plugins/github/src/org/jetbrains/plugins/github/api/GHEServerVersionChecker.kt
2660853143
// WITH_STDLIB annotation class Fancy class Foo(@get:Fancy val foo: Int, @param:Fancy val foo1: Int, @set:Fancy val foo2: Int) fun bar() { Foo(<caret>) } /* Text: (<highlight>foo: Int</highlight>, @Fancy foo1: Int, foo2: Int), Disabled: false, Strikeout: false, Green: true */
plugins/kotlin/idea/tests/testData/parameterInfo/annotations/ConstructorCallWithUseSite.kt
1794672494
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.asJava.classes import com.intellij.testFramework.LightProjectDescriptor import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.idea.perf.UltraLightChecker import org.jetbrains.kotlin.idea.perf.UltraLightChecker.checkByJavaFile import org.jetbrains.kotlin.idea.perf.UltraLightChecker.checkDescriptorsLeak import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.kotlin.idea.test.withCustomCompilerOptions import org.jetbrains.kotlin.psi.KtFile import java.io.File abstract class AbstractUltraLightClassLoadingTest : KotlinLightCodeInsightFixtureTestCase() { override fun getProjectDescriptor(): LightProjectDescriptor = KotlinWithJdkAndRuntimeLightProjectDescriptor.getInstance() open fun doTest(testDataPath: String) { val testDataFile = File(testDataPath) val sourceText = testDataFile.readText() InTextDirectivesUtils.checkIfMuted(sourceText) withCustomCompilerOptions(sourceText, project, module) { val file = myFixture.addFileToProject(testDataFile.name, sourceText) as KtFile UltraLightChecker.checkForReleaseCoroutine(sourceText, module) val checkByJavaFile = InTextDirectivesUtils.isDirectiveDefined(sourceText, "CHECK_BY_JAVA_FILE") val ktClassOrObjects = UltraLightChecker.allClasses(file) if (checkByJavaFile) { val classList = ktClassOrObjects.mapNotNull { it.toLightClass() } checkByJavaFile(testDataPath, classList) classList.forEach { checkDescriptorsLeak(it) } } else { for (ktClass in ktClassOrObjects) { val ultraLightClass = UltraLightChecker.checkClassEquivalence(ktClass) if (ultraLightClass != null) { checkDescriptorsLeak(ultraLightClass) } } } } } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/asJava/classes/AbstractUltraLightClassLoadingTest.kt
1269367419
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * 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.jetbrains.packagesearch.intellij.plugin.util import java.util.concurrent.atomic.AtomicInteger private val traceId = AtomicInteger(0) data class TraceInfo( val source: TraceSource, val id: Int = traceId.incrementAndGet() ) { override fun toString() = "[$id, source=${source.name}]" enum class TraceSource { EMPTY_VALUE, INIT, PROJECT_CHANGES, SEARCH_RESULTS, TARGET_MODULES, FILTERS, SEARCH_QUERY, TARGET_MODULES_KEYPRESS, TARGET_MODULES_SELECTION_CHANGE, STATUS_CHANGES, EXECUTE_OPS, DATA_CHANGED, PACKAGE_UPGRADES, INSTALLED_PACKAGES } companion object { val EMPTY = TraceInfo(TraceSource.EMPTY_VALUE, -1) } }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/util/TraceInfo.kt
889220239
val x: /*T0@*/Int? = null/*NULL!!U*/ fun foo(p: /*T1@*/Int? = null/*NULL!!U*/) {} //UPPER <: T0 due to 'INITIALIZER' //UPPER <: T1 due to 'INITIALIZER'
plugins/kotlin/j2k/new/tests/testData/inference/nullability/nullAsInitializer.kt
667773881
package pojo import java.io.Serializable import java.util.Date /** * Created by timothy.osborn on 4/14/15. */ class AllTypes : Serializable { var intValue: Int = 0 var intValueM: Int? = null var longValue: Long = 0 var longValueM: Long? = null var booleanValue: Boolean = false var booleanValueM: Boolean? = null var shortValue: Short = 0 var shortValueM: Short? = null var doubleValue: Double = 0.toDouble() var doubleValueM: Double? = null var floatValue: Float = 0.toFloat() var floatValueM: Float? = null var byteValue: Byte = 0 var byteValueM: Byte? = null var dateValue: Date? = null var stringValue: String? = null var nullValue: Any? = null var charValue: Char = ' ' var charValueM: Char? = null override fun hashCode(): Int = intValue override fun equals(other: Any?): Boolean = if (other is AllTypes) { other.intValue == intValue } else false }
onyx-database-tests/src/main/kotlin/pojo/AllTypes.kt
1023355119
// WITH_STDLIB object X { var string = "foo" } fun main() { X.string <caret>= "bar" }
plugins/kotlin/idea/tests/testData/intentions/convertVariableAssignmentToExpression/complexLhs.kt
1871118685
import Outer.Middle class Outer { class Middle { class Inner { companion object { const val SIZE = 1 } } } } class Test() { fun test() { val i = Middle.Inner.SIZE<caret> } fun test2() { val i = Outer.Middle.Inner.SIZE } }
plugins/kotlin/idea/tests/testData/intentions/introduceImportAlias/variable.kt
288236884
package first fun secondFun() { } private fun secondFunPrivate() {}
plugins/kotlin/completion/tests/testData/basic/multifile/TopLevelFunction/TopLevelFunction.dependency.kt
3119732664
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.groovy.transformations.inline import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.psi.PsiElement import com.intellij.psi.PsiType import com.intellij.psi.ResolveState import com.intellij.psi.scope.PsiScopeProcessor import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression import org.jetbrains.plugins.groovy.lang.resolve.ElementResolveResult /** * Allow to define custom code insight for an in-code transformation of the Groovy AST. * * Please don't rely on the lifetime of this class' instances. At each moment of time, multiple instances of [GroovyInlineASTTransformationPerformer] * can exist for the same AST subtree. */ interface GroovyInlineASTTransformationPerformer { /** * Allows to compute custom highlighting for the transformable code. * * Since all semantic highlighting is disabled in the transformable code, * the clients can provide custom "keywords" and "type-checking errors". * * **Node:** If some element within the transformation is [isUntransformed], then Groovy will add its regular highlighting to the element. */ fun computeHighlighting(): List<HighlightInfo> = emptyList() /** * Allows to indicate that an [element] will not be modified after AST transformation. * Therefore, regular Groovy code insight rules will be applied to it. */ fun isUntransformed(element: PsiElement): Boolean = false /** * Allows to tune type inference algorithms within the transformable code. * * A transformation affects a correctly-parsed AST, and it means that the main Groovy type-checker * is able to successfully run in the non-transformed code. Some parts of transformable code should not be type-checked by Groovy, * so that is where this method can be used. * * **Note:** If this method returns `null`, and [expression] is [isUntransformed], * then the main Groovy type-checker will handle the type of the [expression]. */ fun computeType(expression: GrExpression): PsiType? = null /** * Allows to add references during the heavyweight resolve (i.e. methods and non-static-referencable variables). */ fun processResolve(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean = true /** * Allows to mimic a synthetic variable declaration. Usually reference expressions do not serve as variables, but everything can happen * during the transformation. * * Please avoid the invocation of heavyweight algorithms (plain reference resolve and typechecking) in implementation. * Consider using [processResolve] in this case. * * @see [org.jetbrains.plugins.groovy.lang.resolve.markAsReferenceResolveTarget] */ fun computeStaticReference(element: PsiElement): ElementResolveResult<PsiElement>? = null }
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/inline/GroovyInlineASTTransformationPerformer.kt
2232928710
// ACTION_CLASS: org.jetbrains.kotlin.idea.actions.generate.KotlinGenerateTestSupportActionBase$SetUp // CONFIGURE_LIBRARY: TestNG import org.testng.annotations.Test open class A { open fun setUp() { } } @Test class B : A() {<caret> }
plugins/kotlin/idea/tests/testData/codeInsight/generate/testFrameworkSupport/testNG/setUpOverrides.kt
3932756139
// PROBLEM: Leaking 'this' in constructor of enum class Foo (with overridable members) // FIX: none enum class Foo { ONE { override val x = 1 }, TWO { override val x = 2 }; abstract val x: Int val double = double(<caret>this) } fun double(foo: Foo) = foo.x * foo.x fun test() { Foo.ONE.double Foo.TWO.double }
plugins/kotlin/idea/tests/testData/inspectionsLocal/leakingThis/enumEntryHasOverriddenMember.kt
3044682055
// "Replace with 'NewClass'" "false" // ACTION: Compiler warning 'TYPEALIAS_EXPANSION_DEPRECATION' options // ACTION: Convert to block body // ACTION: Introduce import alias // ACTION: Introduce local variable @Deprecated("", replaceWith = ReplaceWith("NewClass")) class OldClass() typealias Old1 = OldClass typealias Old2 = Old1 class NewClass() fun foo() = <caret>Old2()
plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/typeAliases/transitiveLong.kt
209555123
fun <T1, T2> T1.foo(handler: suspend (T2) -> Boolean) {} fun f() { "".<caret> } // ELEMENT: foo
plugins/kotlin/completion/tests/testData/handlers/basic/typeArgsForCall/FunctionTypeParameter3.kt
1426777412
// IS_APPLICABLE: false fun testing(x: Int, y: Int, f: (a: Int, b: Int) -> Int): Int { return f(x, y) } fun main() { val num = testing(1, 2, {<caret> x, y -> x + y }) }
plugins/kotlin/idea/tests/testData/intentions/removeExplicitLambdaParameterTypes/typesAlreadyImplicit.kt
1868349989
// "Remove getter and setter from property" "true" class A { <caret>lateinit var str: String get() = "" set(value) {} }
plugins/kotlin/idea/tests/testData/quickfix/lateinit/withGetterSetter.kt
60233953
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.codeInsight.gradle import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.runReadAction import com.intellij.openapi.application.runWriteActionAndWait import com.intellij.openapi.externalSystem.importing.ImportSpec import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder import com.intellij.openapi.projectRoots.JavaSdk import com.intellij.openapi.roots.LibraryOrderEntry import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.roots.impl.libraries.LibraryEx import junit.framework.TestCase import org.jetbrains.jps.model.java.JavaResourceRootType import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.cli.common.arguments.K2JSCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.K2MetadataCompilerArguments import org.jetbrains.kotlin.config.* import org.jetbrains.kotlin.idea.caches.project.productionSourceInfo import org.jetbrains.kotlin.idea.caches.project.testSourceInfo import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCommonCompilerArgumentsHolder import org.jetbrains.kotlin.idea.configuration.ConfigureKotlinStatus import org.jetbrains.kotlin.idea.configuration.ModuleSourceRootMap import org.jetbrains.kotlin.idea.configuration.allConfigurators import org.jetbrains.kotlin.idea.facet.KotlinFacet import org.jetbrains.kotlin.idea.framework.CommonLibraryKind import org.jetbrains.kotlin.idea.framework.JSLibraryKind import org.jetbrains.kotlin.idea.framework.KotlinSdkType import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.util.getProjectJdkTableSafe import org.jetbrains.kotlin.idea.util.projectStructure.allModules import org.jetbrains.kotlin.idea.util.projectStructure.sdk import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.platform.js.JsPlatforms import org.jetbrains.kotlin.platform.js.isJs import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions import org.junit.Ignore import org.junit.Test fun KotlinGradleImportingTestCase.facetSettings(moduleName: String): KotlinFacetSettings { val facet = KotlinFacet.get(getModule(moduleName)) ?: error("Kotlin facet not found in module $moduleName") return facet.configuration.settings } val KotlinGradleImportingTestCase.facetSettings: KotlinFacetSettings get() = facetSettings("project.main") val KotlinGradleImportingTestCase.testFacetSettings: KotlinFacetSettings get() = facetSettings("project.test") class GradleFacetImportTest8 : KotlinGradleImportingTestCase() { @Test fun testJvmImport() { configureByFiles() importProject() with(facetSettings) { assertEquals("1.3", languageLevel!!.versionString) assertEquals("1.3", apiLevel!!.versionString) assertFalse(compilerArguments!!.autoAdvanceLanguageVersion) assertFalse(compilerArguments!!.autoAdvanceApiVersion) assertEquals(JvmPlatforms.jvm18, targetPlatform) assertEquals("1.7", (compilerArguments as K2JVMCompilerArguments).jvmTarget) assertEquals( "-Xallow-no-source-files -Xdump-declarations-to=tmp -Xsingle-module", compilerSettings!!.additionalArguments ) } with(testFacetSettings) { assertEquals("1.3", languageLevel!!.versionString) assertEquals("1.0", apiLevel!!.versionString) assertFalse(compilerArguments!!.autoAdvanceLanguageVersion) assertFalse(compilerArguments!!.autoAdvanceApiVersion) assertEquals(JvmPlatforms.jvm16, targetPlatform) assertEquals("1.6", (compilerArguments as K2JVMCompilerArguments).jvmTarget) assertEquals( "-Xallow-no-source-files -Xdump-declarations-to=tmpTest", compilerSettings!!.additionalArguments ) } assertAllModulesConfigured() assertEquals( listOf( "file:///src/main/java" to JavaSourceRootType.SOURCE, "file:///src/main/kotlin" to JavaSourceRootType.SOURCE, "file:///src/main/resources" to JavaResourceRootType.RESOURCE ), getSourceRootInfos("project.main") ) assertEquals( listOf( "file:///src/test/java" to JavaSourceRootType.TEST_SOURCE, "file:///src/test/kotlin" to JavaSourceRootType.TEST_SOURCE, "file:///src/test/resources" to JavaResourceRootType.TEST_RESOURCE ), getSourceRootInfos("project.test") ) } @Test fun testJvmImportWithPlugin() { configureByFiles() importProject() assertAllModulesConfigured() } @Test fun testJvmImportWithCustomSourceSets() { configureByFiles() importProject() with(facetSettings("project.myMain")) { assertEquals("1.3", languageLevel!!.versionString) assertEquals("1.3", apiLevel!!.versionString) assertEquals(JvmPlatforms.jvm18, targetPlatform) assertEquals("1.7", (compilerArguments as K2JVMCompilerArguments).jvmTarget) assertEquals( "-Xallow-no-source-files -Xdump-declarations-to=tmp -Xsingle-module", compilerSettings!!.additionalArguments ) } with(facetSettings("project.myTest")) { assertEquals("1.3", languageLevel!!.versionString) assertEquals("1.0", apiLevel!!.versionString) assertEquals(JvmPlatforms.jvm16, targetPlatform) assertEquals("1.6", (compilerArguments as K2JVMCompilerArguments).jvmTarget) assertEquals( "-Xallow-no-source-files -Xdump-declarations-to=tmpTest", compilerSettings!!.additionalArguments ) } assertAllModulesConfigured() assertEquals( listOf( "file:///src/main/java" to JavaSourceRootType.SOURCE, "file:///src/main/kotlin" to JavaSourceRootType.SOURCE, "file:///src/main/resources" to JavaResourceRootType.RESOURCE ), getSourceRootInfos("project.main") ) assertEquals( listOf( "file:///src/test/java" to JavaSourceRootType.TEST_SOURCE, "file:///src/test/kotlin" to JavaSourceRootType.TEST_SOURCE, "file:///src/test/resources" to JavaResourceRootType.TEST_RESOURCE ), getSourceRootInfos("project.test") ) } @Test fun testJsImport() { configureByFiles() importProject() with(facetSettings) { assertEquals("1.3", languageLevel!!.versionString) assertEquals("1.3", apiLevel!!.versionString) assertFalse(compilerArguments!!.autoAdvanceLanguageVersion) assertFalse(compilerArguments!!.autoAdvanceApiVersion) assertTrue(targetPlatform.isJs()) with(compilerArguments as K2JSCompilerArguments) { assertEquals(true, sourceMap) assertEquals("plain", moduleKind) } assertEquals( "-main callMain", compilerSettings!!.additionalArguments ) } with(testFacetSettings) { assertEquals("1.3", languageLevel!!.versionString) assertEquals("1.0", apiLevel!!.versionString) assertFalse(compilerArguments!!.autoAdvanceLanguageVersion) assertFalse(compilerArguments!!.autoAdvanceApiVersion) assertTrue(targetPlatform.isJs()) with(compilerArguments as K2JSCompilerArguments) { assertEquals(false, sourceMap) assertEquals("umd", moduleKind) } assertEquals( "-main callTest", compilerSettings!!.additionalArguments ) } val rootManager = ModuleRootManager.getInstance(getModule("project.main")) val libraryEntries = rootManager.orderEntries.filterIsInstance<LibraryOrderEntry>() val stdlib = libraryEntries.single { it.libraryName?.contains("js") ?: false }.library assertEquals(JSLibraryKind, (stdlib as LibraryEx).kind) assertTrue(stdlib.getFiles(OrderRootType.CLASSES).isNotEmpty()) assertSameKotlinSdks("project.main", "project.test") assertEquals( listOf( "file:///src/main/kotlin" to SourceKotlinRootType, "file:///src/main/resources" to ResourceKotlinRootType ), getSourceRootInfos("project.main") ) assertEquals( listOf( "file:///src/test/kotlin" to TestSourceKotlinRootType, "file:///src/test/resources" to TestResourceKotlinRootType ), getSourceRootInfos("project.test") ) assertAllModulesConfigured() } @Test fun testJsImportTransitive() { configureByFiles() importProject() with(facetSettings) { assertEquals("1.3", languageLevel!!.versionString) assertEquals("1.3", apiLevel!!.versionString) assertTrue(targetPlatform.isJs()) } val rootManager = ModuleRootManager.getInstance(getModule("project.main")) val stdlib = rootManager.orderEntries .filterIsInstance<LibraryOrderEntry>() .map { it.library as LibraryEx } .first { "kotlin-stdlib-js" in it.name!! } assertEquals(JSLibraryKind, stdlib.kind) assertAllModulesConfigured() assertEquals( listOf( "file:///src/main/kotlin" to SourceKotlinRootType, "file:///src/main/resources" to ResourceKotlinRootType ), getSourceRootInfos("project.main") ) assertEquals( listOf( "file:///src/test/kotlin" to TestSourceKotlinRootType, "file:///src/test/resources" to TestResourceKotlinRootType ), getSourceRootInfos("project.test") ) } @Test fun testJsImportWithCustomSourceSets() { configureByFiles() importProject() with(facetSettings("project.myMain")) { assertEquals("1.3", languageLevel!!.versionString) assertEquals("1.3", apiLevel!!.versionString) assertTrue(targetPlatform.isJs()) with(compilerArguments as K2JSCompilerArguments) { assertEquals(true, sourceMap) assertEquals("plain", moduleKind) } assertEquals("-main callMain", compilerSettings!!.additionalArguments) } with(facetSettings("project.myTest")) { assertEquals("1.3", languageLevel!!.versionString) assertEquals("1.0", apiLevel!!.versionString) assertTrue(targetPlatform.isJs()) with(compilerArguments as K2JSCompilerArguments) { assertEquals(false, sourceMap) assertEquals("umd", moduleKind) } assertEquals("-main callTest", compilerSettings!!.additionalArguments) } assertAllModulesConfigured() assertEquals( listOf( "file:///src/main/kotlin" to SourceKotlinRootType, "file:///src/main/resources" to ResourceKotlinRootType ), getSourceRootInfos("project.main") ) assertEquals( listOf( "file:///src/test/kotlin" to TestSourceKotlinRootType, "file:///src/test/resources" to TestResourceKotlinRootType ), getSourceRootInfos("project.test") ) } @Test fun testDetectOldJsStdlib() { configureByFiles() importProject() with(facetSettings) { assertTrue(targetPlatform.isJs()) } } @Test fun testJvmImportByPlatformPlugin() { configureByFiles() importProject() with(facetSettings) { assertEquals("1.3", languageLevel!!.versionString) assertEquals("1.3", apiLevel!!.versionString) assertEquals(JvmPlatforms.jvm16, targetPlatform) } assertEquals( listOf( "file:///src/main/java" to JavaSourceRootType.SOURCE, "file:///src/main/kotlin" to JavaSourceRootType.SOURCE, "file:///src/main/resources" to JavaResourceRootType.RESOURCE ), getSourceRootInfos("project.main") ) assertEquals( listOf( "file:///src/test/java" to JavaSourceRootType.TEST_SOURCE, "file:///src/test/kotlin" to JavaSourceRootType.TEST_SOURCE, "file:///src/test/resources" to JavaResourceRootType.TEST_RESOURCE ), getSourceRootInfos("project.test") ) } @Test fun testJsImportByPlatformPlugin() { configureByFiles() importProject() with(facetSettings) { assertEquals("1.3", languageLevel!!.versionString) assertEquals("1.3", apiLevel!!.versionString) assertTrue(targetPlatform.isJs()) } val rootManager = ModuleRootManager.getInstance(getModule("project.main")) val libraries = rootManager.orderEntries.filterIsInstance<LibraryOrderEntry>().map { it.library as LibraryEx } assertEquals(JSLibraryKind, libraries.single { it.name?.contains("kotlin-stdlib-js") == true }.kind) assertEquals(CommonLibraryKind, libraries.single { it.name?.contains("kotlin-stdlib-common") == true }.kind) assertEquals( listOf( "file:///src/main/kotlin" to SourceKotlinRootType, "file:///src/main/resources" to ResourceKotlinRootType ), getSourceRootInfos("project.main") ) assertEquals( listOf( "file:///src/test/kotlin" to TestSourceKotlinRootType, "file:///src/test/resources" to TestResourceKotlinRootType ), getSourceRootInfos("project.test") ) } @Ignore @Test @TargetVersions("4.9") fun testCommonImportByPlatformPlugin() { configureByFiles() importProject() with(facetSettings) { assertEquals("1.1", languageLevel!!.versionString) assertEquals("1.1", apiLevel!!.versionString) assertTrue(targetPlatform.isCommon()) } val rootManager = ModuleRootManager.getInstance(getModule("project.main")) val stdlib = rootManager.orderEntries.filterIsInstance<LibraryOrderEntry>().single().library assertEquals(CommonLibraryKind, (stdlib as LibraryEx).kind) assertEquals( listOf( "file:///src/main/java" to SourceKotlinRootType, "file:///src/main/kotlin" to SourceKotlinRootType, "file:///src/main/resources" to ResourceKotlinRootType ), getSourceRootInfos("project.main") ) assertEquals( listOf( "file:///src/test/java" to TestSourceKotlinRootType, "file:///src/test/kotlin" to TestSourceKotlinRootType, "file:///src/test/resources" to TestResourceKotlinRootType ), getSourceRootInfos("project.test") ) } @Test fun testJvmImportByKotlinPlugin() { configureByFiles() importProject() with(facetSettings) { assertEquals("1.3", languageLevel!!.versionString) assertEquals("1.3", apiLevel!!.versionString) assertEquals(JvmPlatforms.jvm16, targetPlatform) } assertEquals( listOf( "file:///src/main/java" to JavaSourceRootType.SOURCE, "file:///src/main/kotlin" to JavaSourceRootType.SOURCE, "file:///src/main/resources" to JavaResourceRootType.RESOURCE ), getSourceRootInfos("project.main") ) assertEquals( listOf( "file:///src/test/java" to JavaSourceRootType.TEST_SOURCE, "file:///src/test/kotlin" to JavaSourceRootType.TEST_SOURCE, "file:///src/test/resources" to JavaResourceRootType.TEST_RESOURCE ), getSourceRootInfos("project.test") ) } @Test fun testJsImportByKotlin2JsPlugin() { configureByFiles() importProject() with(facetSettings) { assertEquals("1.3", languageLevel!!.versionString) assertEquals("1.3", apiLevel!!.versionString) assertTrue(targetPlatform.isJs()) } assertEquals( listOf( "file:///src/main/kotlin" to SourceKotlinRootType, "file:///src/main/resources" to ResourceKotlinRootType ), getSourceRootInfos("project.main") ) assertEquals( listOf( "file:///src/test/kotlin" to TestSourceKotlinRootType, "file:///src/test/resources" to TestResourceKotlinRootType ), getSourceRootInfos("project.test") ) } @Test fun testArgumentEscaping() { configureByFiles() importProject() with(facetSettings) { assertEquals( listOf("-Xallow-no-source-files", "-Xbuild-file=module with spaces"), compilerSettings!!.additionalArgumentsAsList ) } } @Test fun testNoPluginsInAdditionalArgs() { configureByFiles() importProject() with(facetSettings) { assertEquals("-version", compilerSettings!!.additionalArguments) assertEquals( listOf( "plugin:org.jetbrains.kotlin.allopen:annotation=org.springframework.stereotype.Component", "plugin:org.jetbrains.kotlin.allopen:annotation=org.springframework.transaction.annotation.Transactional", "plugin:org.jetbrains.kotlin.allopen:annotation=org.springframework.scheduling.annotation.Async", "plugin:org.jetbrains.kotlin.allopen:annotation=org.springframework.cache.annotation.Cacheable", "plugin:org.jetbrains.kotlin.allopen:annotation=org.springframework.boot.test.context.SpringBootTest", "plugin:org.jetbrains.kotlin.allopen:annotation=org.springframework.validation.annotation.Validated" ), compilerArguments!!.pluginOptions!!.toList() ) } } @Test fun testNoArgInvokeInitializers() { configureByFiles() importProject() with(facetSettings) { assertEquals( "-version", compilerSettings!!.additionalArguments ) assertEquals( listOf( "plugin:org.jetbrains.kotlin.noarg:annotation=NoArg", "plugin:org.jetbrains.kotlin.noarg:invokeInitializers=true" ), compilerArguments!!.pluginOptions!!.toList() ) } } @Test @Ignore // android.sdk needed fun testAndroidGradleJsDetection() { configureByFiles() createLocalPropertiesSubFileForAndroid() importProject() with(facetSettings("js-module")) { assertTrue(targetPlatform.isJs()) } val rootManager = ModuleRootManager.getInstance(getModule("js-module")) val stdlib = rootManager .orderEntries .filterIsInstance<LibraryOrderEntry>() .first { it.libraryName?.startsWith("Gradle: kotlin-stdlib-js-") ?: false } .library!! assertTrue(stdlib.getFiles(OrderRootType.CLASSES).isNotEmpty()) assertEquals(JSLibraryKind, (stdlib as LibraryEx).kind) } @Test @Ignore // android.sdk needed fun testKotlinAndroidPluginDetection() { configureByFiles() createLocalPropertiesSubFileForAndroid() importProject() assertNotNull(KotlinFacet.get(getModule("project"))) } @Test fun testNoFacetInModuleWithoutKotlinPlugin() { configureByFiles() importProject() assertNotNull(KotlinFacet.get(getModule("gr01.main"))) assertNotNull(KotlinFacet.get(getModule("gr01.test"))) assertNull(KotlinFacet.get(getModule("gr01.m1.main"))) assertNull(KotlinFacet.get(getModule("gr01.m1.test"))) } @Test fun testClasspathWithDependenciesImport() { configureByFiles() importProject() with(facetSettings) { assertEquals("tmp.jar", (compilerArguments as K2JVMCompilerArguments).classpath) } } @Test fun testDependenciesClasspathImport() { configureByFiles() importProject() with(facetSettings) { assertEquals(null, (compilerArguments as K2JVMCompilerArguments).classpath) } } @Test fun testJDKImport() { val mockJdkPath = "${PathManager.getHomePath()}/community/java/mockJDK-1.8" runWriteActionAndWait { val jdk = JavaSdk.getInstance().createJdk("myJDK", mockJdkPath) getProjectJdkTableSafe().addJdk(jdk) ProjectRootManager.getInstance(myProject).projectSdk = jdk } try { configureByFiles() importProject() val moduleSDK = ModuleRootManager.getInstance(getModule("project.main")).sdk!! assertTrue(moduleSDK.sdkType is JavaSdk) assertEquals("myJDK", moduleSDK.name) assertEquals(mockJdkPath, moduleSDK.homePath) } finally { runWriteActionAndWait { val jdkTable = getProjectJdkTableSafe() jdkTable.removeJdk(jdkTable.findJdk("myJDK")!!) ProjectRootManager.getInstance(myProject).projectSdk = null } } } @Test fun testImplementsDependency() { configureByFiles() importProject() assertEquals(listOf("MultiTest.main"), facetSettings("MultiTest.MultiTest-jvm.main").implementedModuleNames) assertEquals(listOf("MultiTest.test"), facetSettings("MultiTest.MultiTest-jvm.test").implementedModuleNames) assertEquals(listOf("MultiTest.main"), facetSettings("MultiTest.MultiTest-js.main").implementedModuleNames) assertEquals(listOf("MultiTest.test"), facetSettings("MultiTest.MultiTest-js.test").implementedModuleNames) } @Test fun testImplementsDependencyWithCustomSourceSets() { configureByFiles() importProject() assertEquals(listOf("MultiTest.myMain"), facetSettings("MultiTest.MultiTest-jvm.myMain").implementedModuleNames) assertEquals(listOf("MultiTest.myTest"), facetSettings("MultiTest.MultiTest-jvm.myTest").implementedModuleNames) assertEquals(listOf("MultiTest.myMain"), facetSettings("MultiTest.MultiTest-js.myMain").implementedModuleNames) assertEquals(listOf("MultiTest.myTest"), facetSettings("MultiTest.MultiTest-js.myTest").implementedModuleNames) } @Test fun testAPIVersionExceedingLanguageVersion() { configureByFiles() importProject() with(facetSettings) { assertEquals("1.3", languageLevel!!.versionString) assertEquals("1.3", apiLevel!!.versionString) } assertAllModulesConfigured() } @Test fun testIgnoreProjectLanguageAndAPIVersion() { KotlinCommonCompilerArgumentsHolder.getInstance(myProject).update { languageVersion = "1.0" apiVersion = "1.0" } configureByFiles() importProject() with(facetSettings) { assertEquals("1.3", languageLevel!!.versionString) assertEquals("1.3", apiLevel!!.versionString) } assertAllModulesConfigured() } @Test fun testCommonArgumentsImport() { configureByFiles() importProject() with(facetSettings) { assertEquals("1.1", languageLevel!!.versionString) assertEquals("1.0", apiLevel!!.versionString) assertFalse(compilerArguments!!.autoAdvanceLanguageVersion) assertFalse(compilerArguments!!.autoAdvanceApiVersion) assertTrue(targetPlatform.isCommon()) assertEquals("my/classpath", (compilerArguments as K2MetadataCompilerArguments).classpath) assertEquals("my/destination", (compilerArguments as K2MetadataCompilerArguments).destination) } with(facetSettings("project.test")) { assertEquals("1.1", languageLevel!!.versionString) assertEquals("1.0", apiLevel!!.versionString) assertFalse(compilerArguments!!.autoAdvanceLanguageVersion) assertFalse(compilerArguments!!.autoAdvanceApiVersion) assertTrue(targetPlatform.isCommon()) assertEquals("my/test/classpath", (compilerArguments as K2MetadataCompilerArguments).classpath) assertEquals("my/test/destination", (compilerArguments as K2MetadataCompilerArguments).destination) } val rootManager = ModuleRootManager.getInstance(getModule("project.main")) val stdlib = rootManager.orderEntries.filterIsInstance<LibraryOrderEntry>().single().library assertEquals(CommonLibraryKind, (stdlib as LibraryEx).kind) assertSameKotlinSdks("project.main", "project.test") assertEquals( listOf( "file:///src/main/java" to SourceKotlinRootType, "file:///src/main/kotlin" to SourceKotlinRootType, "file:///src/main/resources" to ResourceKotlinRootType ), getSourceRootInfos("project.main") ) assertEquals( listOf( "file:///src/test/java" to TestSourceKotlinRootType, "file:///src/test/kotlin" to TestSourceKotlinRootType, "file:///src/test/resources" to TestResourceKotlinRootType ), getSourceRootInfos("project.test") ) } @Test fun testInternalArgumentsFacetImporting() { configureByFiles() importProject() // Version is indeed 1.3 assertEquals(LanguageVersion.KOTLIN_1_3, facetSettings.languageLevel) // We haven't lost internal argument during importing to facet assertEquals("-Xallow-no-source-files -XXLanguage:+InlineClasses", facetSettings.compilerSettings?.additionalArguments) // Inline classes are enabled even though LV = 1.3 assertEquals( LanguageFeature.State.ENABLED, getModule("project.main").languageVersionSettings.getFeatureSupport(LanguageFeature.InlineClasses) ) assertAllModulesConfigured() } @Test fun testStableModuleNameWhileUsingGradleJS() { configureByFiles() importProject() checkStableModuleName("project.main", "project", JsPlatforms.defaultJsPlatform, isProduction = true) // Note "_test" suffix: this is current behavior of K2JS Compiler checkStableModuleName("project.test", "project_test", JsPlatforms.defaultJsPlatform, isProduction = false) assertAllModulesConfigured() } @Test fun testStableModuleNameWhileUsingGradleJVM() { configureByFiles() importProject() checkStableModuleName("project.main", "project", JvmPlatforms.unspecifiedJvmPlatform, isProduction = true) checkStableModuleName("project.test", "project", JvmPlatforms.unspecifiedJvmPlatform, isProduction = false) assertAllModulesConfigured() } @Test fun testNoFriendPathsAreShown() { configureByFiles() importProject() assertEquals( "-Xallow-no-source-files", testFacetSettings.compilerSettings!!.additionalArguments ) assertAllModulesConfigured() } @Test fun testSharedLanguageVersion() { configureByFiles() val holder = KotlinCommonCompilerArgumentsHolder.getInstance(myProject) holder.update { languageVersion = "1.1" } importProject() TestCase.assertEquals("1.3", holder.settings.languageVersion) } @Test fun testNonSharedLanguageVersion() { configureByFiles() val holder = KotlinCommonCompilerArgumentsHolder.getInstance(myProject) holder.update { languageVersion = "1.1" } importProject() TestCase.assertEquals("1.1", holder.settings.languageVersion) } @Test fun testImportCompilerArgumentsWithInvalidDependencies() { configureByFiles() importProject() with(facetSettings("project.main")) { assertEquals("1.8", (mergedCompilerArguments as K2JVMCompilerArguments).jvmTarget) } } private fun checkStableModuleName(projectName: String, expectedName: String, platform: TargetPlatform, isProduction: Boolean) { runReadAction { val module = getModule(projectName) val moduleInfo = if (isProduction) module.productionSourceInfo() else module.testSourceInfo() val resolutionFacade = KotlinCacheService.getInstance(myProject).getResolutionFacadeByModuleInfo(moduleInfo!!, platform)!! val moduleDescriptor = resolutionFacade.moduleDescriptor assertEquals("<$expectedName>", moduleDescriptor.stableName?.asString()) } } private fun assertAllModulesConfigured() { runReadAction { for (moduleGroup in ModuleSourceRootMap(myProject).groupByBaseModules(myProject.allModules())) { val configurator = allConfigurators().find { it.getStatus(moduleGroup) == ConfigureKotlinStatus.CAN_BE_CONFIGURED } assertNull("Configurator $configurator tells that ${moduleGroup.baseModule} can be configured", configurator) } } } private fun assertSameKotlinSdks(vararg moduleNames: String) { val sdks = moduleNames.map { getModule(it).sdk!! } val refSdk = sdks.firstOrNull() ?: return assertTrue(refSdk.sdkType is KotlinSdkType) assertTrue(sdks.all { it === refSdk }) } override fun createImportSpec(): ImportSpec = ImportSpecBuilder(super.createImportSpec()).createDirectoriesForEmptyContentRoots().build() override fun testDataDirName(): String = "gradleFacetImportTest" }
plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/GradleFacetImportTest.kt
2868204417
// FIX: Convert to run { ... } // WITH_STDLIB class C { fun f4() = {<caret> "single-expression function which returns lambda" } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/functionWithLambdaExpressionBody/wrapRun/kt32580.kt
3921598696
@<caret>A class MyClass annotation class A
plugins/kotlin/idea/tests/testData/hierarchy/class/type/CaretAtAnnotation/main.kt
1724563286
package org.jtrim2.build import org.gradle.api.Project import org.gradle.api.provider.Property import org.gradle.kotlin.dsl.property class JTrimProjectInfo(project: Project) { val displayName: Property<String> val description: Property<String> init { val objects = project.objects displayName = objects.property() displayName.set(project.name) description = objects.property() description.set(displayName.map { project.description ?: it }) } }
buildSrc/src/main/kotlin/org/jtrim2/build/JTrimProjectInfo.kt
914605544
package io.kotest.engine.extensions import io.kotest.core.test.TestCase import io.kotest.core.test.TestResult import io.kotest.engine.EngineResult import io.kotest.engine.TestSuite import io.kotest.engine.listener.CompositeTestEngineListener import io.kotest.engine.listener.TestEngineListener import java.util.concurrent.atomic.AtomicBoolean /** * Wraps the [TestEngineListener] to listen for test events and errors if there were no tests executed. */ internal object EmptyTestSuiteExtension : EngineExtension { override suspend fun intercept( suite: TestSuite, listener: TestEngineListener, execute: suspend (TestSuite, TestEngineListener) -> EngineResult ): EngineResult { // listens to engine events, and if we have a test finished, we know we didn't have an empty test suite val emptyTestSuite = AtomicBoolean(true) val emptyTestSuiteListener = object : TestEngineListener { override fun testFinished(testCase: TestCase, result: TestResult) { emptyTestSuite.set(false) } } val result = execute(suite, CompositeTestEngineListener(listOf(listener, emptyTestSuiteListener))) return when { emptyTestSuite.get() -> EngineResult(result.errors + RuntimeException("No tests were executed")) else -> result } } }
kotest-framework/kotest-framework-engine/src/jvmMain/kotlin/io/kotest/engine/extensions/EmptyTestSuiteExtension.kt
3352790429
package totoro.pix.converter import javafx.scene.image.Image import javafx.scene.paint.Color import java.util.* import kotlin.collections.HashMap object Converter { fun convert(image: Image): ByteArray { val matrix = ArrayList<Byte>() val reader = image.pixelReader // encode width / height val width = Math.min(image.width.toInt(), 160) val height = Math.min(image.height.toInt(), 100) matrix.add(width.toByte()) matrix.add((height / 2).toByte()) println("Width: $width") println("Height: $height\n") // encode basic fore / back colors val pairs = HashMap<Pair<Color, Color>, Int>() for (x in 0 until width) { (0 until height / 2) .map { Pair(reader.getColor(x, it*2), reader.getColor(x, it*2+1)) } .forEach { pairs[it] = pairs[it]?.plus(1) ?: 1 } } val basic = pairs.toSortedMap(compareBy<Pair<Color, Color>> { pairs[it] }.reversed()).firstKey() encodeColor(matrix, basic.first) encodeColor(matrix, basic.second) println("Basic fore: ${basic.first.red * 255}, ${basic.first.green * 255}, ${basic.first.blue * 255}") println("Basic back: ${basic.second.red * 255}, ${basic.second.green * 255}, ${basic.second.blue * 255}\n") // encode the rest of matrix val list = LinkedList<Sequence>() var current: Sequence? = null for (y in 0 until height / 2) { for (x in 0 until width) { val upper = inflate(deflate(reader.getColor(x, y * 2))) val lower = inflate(deflate(reader.getColor(x, y * 2 + 1))) if (current == null || current.str.size >= 255 || x == 0 || !current.add(upper, lower)) { if (current != null) list.add(current) current = Sequence(upper, lower, x + 1, y + 1) } } } if (current != null) list.add(current) val sorted = HashMap<Color, HashMap<Color, LinkedList<Sequence>>>() for (seq in list) { if (sorted[seq.fore] == null) sorted[seq.fore] = HashMap<Color, LinkedList<Sequence>>() if (sorted[seq.fore]?.get(seq.back) == null) sorted[seq.fore]?.set(seq.back, LinkedList<Sequence>()) sorted[seq.fore]?.get(seq.back)?.add(seq) } print("Compressed char sequence: ") val raw = ArrayList<Byte>() var index = 0 var byte = 0 sorted.forEach { _, sub -> sub.forEach { _, l -> l.forEach { seq -> seq.str.forEach { char -> if (index % 4 == 0 && index > 0) { raw.add(byte.toByte()) print("$byte.") byte = 0 } byte = byte * 4 + char index++ } } } } if (index % 4 != 0) { while (index % 4 != 0) { byte *= 4; index++ } raw.add(byte.toByte()) } raw.add(byte.toByte()) print("$byte.\n") encodeLen(matrix, index) raw.forEach { matrix.add(it) } println("Total: $index symbols / ${raw.size} bytes\n") encodeLen(matrix, sorted.size) println("Fore colors: ${sorted.size}") sorted.forEach { fore, sub -> encodeColor(matrix, fore) println("- ${fore.red * 255}, ${fore.green * 255}, ${fore.blue * 255}") encodeLen(matrix, sub.size) println("- Back colors: ${sub.size}") sub.forEach { back, l -> encodeColor(matrix, back) println("- - ${back.red * 255}, ${back.green * 255}, ${back.blue * 255}") encodeLen(matrix, l.size) println("- - Sequences: ${l.size}") l.forEach { seq -> matrix.add(seq.x.toByte()) println("- - - x: ${seq.x}") matrix.add(seq.y.toByte()) println("- - - y: ${seq.y}") matrix.add(seq.str.size.toByte()) println("- - - len: ${seq.str.size}") println("- - - * * *") } } } return ByteArray(matrix.size, { matrix[it] }) } private fun encodeColor(matrix: ArrayList<Byte>, color: Color) { matrix.add((color.red * 255).toByte()) matrix.add((color.green * 255).toByte()) matrix.add((color.blue * 255).toByte()) } private fun encodeLen(matrix: ArrayList<Byte>, len : Int) { matrix.add((len / 256).toByte()) matrix.add((len % 256).toByte()) } private val reds = 6 private val greens = 8 private val blues = 5 private val grays = arrayOf ( 0.05859375, 0.1171875, 0.17578125, 0.234375, 0.29296875, 0.3515625, 0.41015625, 0.46875, 0.52734375, 0.5859375, 0.64453125, 0.703125, 0.76171875, 0.8203125, 0.87890625, 0.9375 ) private fun delta(a: Color, b: Color): Double { val dr = a.red - b.red val dg = a.green - b.green val db = a.blue - b.blue return 0.2126 * dr * dr + 0.7152 * dg * dg + 0.0722 * db * db } fun deflate(color: Color): Int { val idxR = (color.red * 255 * (reds - 1.0) / 0xFF + 0.5).toInt() val idxG = (color.green * 255 * (greens - 1.0) / 0xFF + 0.5).toInt() val idxB = (color.blue * 255 * (blues - 1.0) / 0xFF + 0.5).toInt() val compressed = 16 + idxR * greens * blues + idxG * blues + idxB return (0..15).fold(compressed, { acc, i -> if (delta(inflate(i), color) < delta(inflate(acc), color)) i else acc }) } fun inflate(value: Int): Color { if (value < 16) { return Color.gray(grays[value]) } else { val index = value - 16 val idxB = index % blues val idxG = (index / blues) % greens val idxR = (index / blues / greens) % reds val r = (idxR * 0xFF / (reds - 1.0) + 0.5).toInt() val g = (idxG * 0xFF / (greens - 1.0) + 0.5).toInt() val b = (idxB * 0xFF / (blues - 1.0) + 0.5).toInt() return Color.rgb(r, g, b) } } }
src/main/kotlin/totoro/pix/converter/Converter.kt
1203257158
/** * BreadWallet * * Created by Drew Carlson <[email protected]> on 9/10/19. * Copyright (c) 2019 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.breadwallet.breadbox import com.breadwallet.app.BreadApp import com.breadwallet.crypto.Account import com.breadwallet.crypto.Key import com.breadwallet.crypto.Network import com.breadwallet.crypto.System import com.breadwallet.crypto.Transfer import com.breadwallet.crypto.Wallet import com.breadwallet.crypto.WalletManager import com.breadwallet.crypto.WalletManagerState import com.breadwallet.crypto.blockchaindb.BlockchainDb import com.breadwallet.crypto.events.network.NetworkEvent import com.breadwallet.crypto.events.system.SystemDiscoveredNetworksEvent import com.breadwallet.crypto.events.system.SystemEvent import com.breadwallet.crypto.events.system.SystemListener import com.breadwallet.crypto.events.system.SystemNetworkAddedEvent import com.breadwallet.crypto.events.transfer.TranferEvent import com.breadwallet.crypto.events.wallet.WalletEvent import com.breadwallet.crypto.events.wallet.WalletTransferAddedEvent import com.breadwallet.crypto.events.wallet.WalletTransferChangedEvent import com.breadwallet.crypto.events.wallet.WalletTransferDeletedEvent import com.breadwallet.crypto.events.wallet.WalletTransferSubmittedEvent import com.breadwallet.crypto.events.walletmanager.WalletManagerChangedEvent import com.breadwallet.crypto.events.walletmanager.WalletManagerCreatedEvent import com.breadwallet.crypto.events.walletmanager.WalletManagerEvent import com.breadwallet.crypto.events.walletmanager.WalletManagerSyncProgressEvent import com.breadwallet.crypto.events.walletmanager.WalletManagerSyncRecommendedEvent import com.breadwallet.ext.throttleLatest import com.breadwallet.logger.logDebug import com.breadwallet.logger.logInfo import com.breadwallet.tools.manager.BRSharedPrefs import com.breadwallet.tools.security.BrdUserManager import com.breadwallet.tools.util.Bip39Reader import com.breadwallet.tools.util.TokenUtil import com.breadwallet.util.errorHandler import com.platform.interfaces.WalletProvider import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.cancel import kotlinx.coroutines.channels.BroadcastChannel import kotlinx.coroutines.channels.Channel.Factory.BUFFERED import kotlinx.coroutines.channels.Channel.Factory.CONFLATED import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.dropWhile import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.take import kotlinx.coroutines.flow.transform import kotlinx.coroutines.launch import kotlinx.coroutines.plus import java.io.File import java.util.Locale import java.util.concurrent.Executors import java.util.concurrent.atomic.AtomicBoolean private const val DEFAULT_THROTTLE_MS = 500L private const val AGGRESSIVE_THROTTLE_MS = 800L @Suppress("TooManyFunctions") internal class CoreBreadBox( private val storageFile: File, override val isMainnet: Boolean = false, private val walletProvider: WalletProvider, private val blockchainDb: BlockchainDb, private val userManager: BrdUserManager ) : BreadBox, SystemListener { init { // Set default words list val context = BreadApp.getBreadContext() val words = Bip39Reader.getBip39Words(context, BRSharedPrefs.recoveryKeyLanguage) Key.setDefaultWordList(words) } @Volatile private var system: System? = null private val systemExecutor = Executors.newSingleThreadScheduledExecutor() private var openScope = CoroutineScope( SupervisorJob() + Dispatchers.Default + errorHandler("openScope") ) private val systemChannel = BroadcastChannel<Unit>(CONFLATED) private val accountChannel = BroadcastChannel<Unit>(CONFLATED) private val walletsChannel = BroadcastChannel<Unit>(CONFLATED) private val walletSyncStateChannel = BroadcastChannel<WalletSyncState>(BUFFERED) private val walletTransfersChannelMap = BroadcastChannel<String>(BUFFERED) private val transferUpdatedChannelMap = BroadcastChannel<Transfer>(BUFFERED) private var networkManager: NetworkManager? = null private val isDiscoveryComplete = AtomicBoolean(false) private val _isOpen = AtomicBoolean(false) override var isOpen: Boolean get() = _isOpen.get() set(value) { _isOpen.set(value) } @Synchronized override fun open(account: Account) { logDebug("Opening CoreBreadBox") check(!isOpen) { "open() called while BreadBox was open." } check(account.serialize().isNotEmpty()) { "Account.serialize() contains 0 bytes" } if (!storageFile.exists()) { logDebug("Making storage directories") check(storageFile.mkdirs()) { "Failed to create storage directory: ${storageFile.absolutePath}" } } fun newSystem() = System.create( systemExecutor, this@CoreBreadBox, account, isMainnet, storageFile.absolutePath, blockchainDb ).apply { logDebug("Created new System instance") configure(emptyList()) } system = (system ?: newSystem()).also { system -> logDebug("Dispatching initial System values") system.resume() networkManager = NetworkManager( system, openScope + systemExecutor.asCoroutineDispatcher(), listOf(DefaultNetworkInitializer(userManager)) ) systemChannel.offer(Unit) accountChannel.offer(Unit) system.wallets?.let { wallets -> walletsChannel.offer(Unit) wallets.forEach { wallet -> walletTransfersChannelMap.offer(wallet.eventKey()) } } } isOpen = true walletProvider .enabledWallets() .onEach { enabledWallets -> networkManager?.enabledWallets = enabledWallets system?.wallets?.let { walletsChannel.offer(Unit) } } .launchIn(openScope) walletProvider .walletModes() .onEach { modes -> networkManager?.managerModes = modes system?.wallets?.let { walletsChannel.offer(Unit) } } .launchIn(openScope) logInfo("BreadBox opened successfully") } @Synchronized override fun close(wipe: Boolean) { logDebug("Closing BreadBox") check(isOpen) { "BreadBox must be opened before calling close()." } openScope.cancel() openScope = CoroutineScope( SupervisorJob() + Dispatchers.Default + errorHandler("openScope") ) checkNotNull(system).pause() if (wipe) { System.wipe(system) system = null } isOpen = false networkManager = null } override fun system(): Flow<System> = systemChannel .asFlow() .dropWhile { !isOpen } .mapNotNull { system } override fun account() = accountChannel .asFlow() .mapNotNull { system?.account } override fun wallets(filterByTracked: Boolean) = walletsChannel .asFlow() .throttleLatest(AGGRESSIVE_THROTTLE_MS) .mapNotNull { val wallets = system?.wallets when { filterByTracked -> { wallets?.filterByCurrencyIds( walletProvider.enabledWallets().first() ) } else -> wallets } } override fun wallet(currencyCode: String) = walletsChannel .asFlow() .throttleLatest(DEFAULT_THROTTLE_MS) .run { if (currencyCode.contains(":")) { mapNotNull { system?.wallets?.firstOrNull { it.currency.uids.equals(currencyCode, true) } } } else { mapNotNull { system?.wallets?.firstOrNull { it.currency.code.equals(currencyCode, true) } } } } override fun currencyCodes(): Flow<List<String>> = combine( walletProvider.enabledWallets().throttleLatest(AGGRESSIVE_THROTTLE_MS), wallets() ) { enabledWallets, wallets -> enabledWallets .associateWith { wallets.findByCurrencyId(it) } .mapValues { (currencyId, wallet) -> wallet?.currency?.code ?: TokenUtil.tokenForCurrencyId(currencyId) ?.symbol?.toLowerCase(Locale.ROOT) }.values .filterNotNull() .toList() }.throttleLatest(AGGRESSIVE_THROTTLE_MS) .distinctUntilChanged() override fun walletSyncState(currencyCode: String) = walletSyncStateChannel .asFlow() .filter { it.currencyCode.equals(currencyCode, true) } .throttleLatest(DEFAULT_THROTTLE_MS) .onStart { // Dispatch initial sync state val isSyncing = wallet(currencyCode) .map { it.walletManager.state.type == WalletManagerState.Type.SYNCING } .first() emit( WalletSyncState( currencyCode = currencyCode, percentComplete = if (isSyncing) 0f else 1f, timestamp = 0, isSyncing = isSyncing ) ) } .distinctUntilChanged() override fun walletTransfers(currencyCode: String) = walletTransfersChannelMap .asFlow() .onStart { emit(currencyCode) } .filter { currencyCode.equals(it, true) } .throttleLatest(AGGRESSIVE_THROTTLE_MS) .mapNotNull { system?.wallets ?.find { it.currency.code.equals(currencyCode, true) } ?.transfers } override fun walletTransfer(currencyCode: String, transferHash: String): Flow<Transfer> { return transferUpdatedChannelMap .asFlow() .filter { transfer -> transfer.wallet.currency.code.equals(currencyCode, true) && transfer.hash.isPresent && transfer.hashString().equals(transferHash, true) } .onStart { system?.wallets ?.find { it.currency.code.equals(currencyCode, true) } ?.transfers ?.firstOrNull { it.hash.isPresent && it.hashString() == transferHash } ?.also { emit(it) } } } override fun walletTransfer(currencyCode: String, transfer: Transfer): Flow<Transfer> { val targetWallet = { wallet: Wallet -> wallet.currency.code.equals(currencyCode, true) } val targetTransfer = { updatedTransfer: Transfer -> (transfer == updatedTransfer || (transfer.hash.isPresent && transfer.hash == updatedTransfer.hash)) } return transferUpdatedChannelMap .asFlow() .filter { updatedTransfer -> updatedTransfer.wallet.currency.code.equals(currencyCode, true) && targetTransfer(updatedTransfer) } .onStart { emit( system?.wallets ?.firstOrNull(targetWallet) ?.transfers ?.firstOrNull(targetTransfer) ?: return@onStart ) } } override fun initializeWallet(currencyCode: String) { check(isOpen) { "initializeWallet cannot be called before open." } val system = checkNotNull(system) val networkManager = checkNotNull(networkManager) val network = system.networks.find { it.containsCurrencyCode(currencyCode) } checkNotNull(network) { "Network with currency code '$currencyCode' not found." } openScope.launch { networkManager.completeNetworkInitialization(network.currency.uids) } } override fun walletState(currencyCode: String): Flow<WalletState> = system() .map { system -> system.networks.find { it.containsCurrencyCode(currencyCode) } } .mapNotNull { network -> network?.currency?.uids ?: TokenUtil.tokenForCode(currencyCode)?.currencyId } .take(1) .flatMapLatest { uids -> checkNotNull(networkManager).networkState(uids).map { networkState -> when (networkState) { is NetworkState.Initialized -> WalletState.Initialized is NetworkState.Loading -> WalletState.Loading is NetworkState.ActionNeeded -> WalletState.WaitingOnAction is NetworkState.Error -> WalletState.Error } } } override fun networks(whenDiscoveryComplete: Boolean): Flow<List<Network>> = system().transform { if (whenDiscoveryComplete) { if (isDiscoveryComplete.get()) { emit(it.networks) } } else { emit(it.networks) } } override fun getSystemUnsafe(): System? = system override fun handleWalletEvent( system: System, manager: WalletManager, wallet: Wallet, event: WalletEvent ) { walletsChannel.offer(Unit) fun updateTransfer(transfer: Transfer) { transferUpdatedChannelMap.offer(transfer) walletTransfersChannelMap.offer(wallet.eventKey()) } when (event) { is WalletTransferSubmittedEvent -> updateTransfer(event.transfer) is WalletTransferDeletedEvent -> updateTransfer(event.transfer) is WalletTransferAddedEvent -> updateTransfer(event.transfer) is WalletTransferChangedEvent -> updateTransfer(event.transfer) } } override fun handleManagerEvent( system: System, manager: WalletManager, event: WalletManagerEvent ) { walletsChannel.offer(Unit) when (event) { is WalletManagerCreatedEvent -> { logDebug("Wallet Manager Created: '${manager.name}' mode ${manager.mode}") networkManager?.connectManager(manager) } is WalletManagerSyncProgressEvent -> { val timeStamp = event.timestamp?.get()?.time logDebug("(${manager.currency.code}) Sync Progress progress=${event.percentComplete} time=$timeStamp") // NOTE: Fulfill percentComplete fractional expectation of consumers walletSyncStateChannel.offer( WalletSyncState( currencyCode = manager.currency.code, percentComplete = event.percentComplete / 100, timestamp = event.timestamp.orNull()?.time ?: 0L, isSyncing = true ) ) } is WalletManagerChangedEvent -> { val fromStateType = event.oldState.type val toStateType = event.newState.type logDebug("(${manager.currency.code}) State Changed from='$fromStateType' to='$toStateType'") // Syncing is complete, manually signal change to observers if (fromStateType == WalletManagerState.Type.SYNCING) { walletSyncStateChannel.offer( WalletSyncState( currencyCode = manager.currency.code, percentComplete = 1f, timestamp = 0L, isSyncing = false ) ) } if (toStateType == WalletManagerState.Type.SYNCING) { walletSyncStateChannel.offer( WalletSyncState( currencyCode = manager.currency.code, percentComplete = 0f, timestamp = 0L, isSyncing = true ) ) } if (fromStateType != WalletManagerState.Type.CONNECTED && toStateType == WalletManagerState.Type.CONNECTED ) { logDebug("Wallet Manager Connected: '${manager.name}'") networkManager?.registerCurrencies(manager) } } is WalletManagerSyncRecommendedEvent -> { logDebug("Syncing '${manager.currency.code}' to ${event.depth}") manager.syncToDepth(event.depth) } } } override fun handleNetworkEvent(system: System, network: Network, event: NetworkEvent) = Unit override fun handleSystemEvent(system: System, event: SystemEvent) { when (event) { is SystemNetworkAddedEvent -> { logDebug("Network '${event.network.name}' added.") networkManager?.initializeNetwork(event.network) } is SystemDiscoveredNetworksEvent -> { isDiscoveryComplete.set(true) } } systemChannel.offer(Unit) } override fun handleTransferEvent( system: System, manager: WalletManager, wallet: Wallet, transfer: Transfer, event: TranferEvent ) { transferUpdatedChannelMap.offer(transfer) walletTransfersChannelMap.offer(wallet.eventKey()) } private fun Wallet.eventKey() = currency.code.toLowerCase(Locale.ROOT) }
app/src/main/java/com/breadwallet/breadbox/CoreBreadBox.kt
2158439369
/* * Copyright 2018 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 com.android.tools.build.jetifier.core.rule import com.android.tools.build.jetifier.core.proguard.ProGuardType import com.android.tools.build.jetifier.core.type.JavaType import com.google.gson.annotations.SerializedName import java.util.regex.Pattern /** * Rule that rewrites a Java type based on the given arguments. * * Used in the preprocessor when generating [TypesMap]. * * @param from Regular expression where packages are separated via '/' and inner class separator * is "$". Used to match the input type. * @param to A string to be used as a replacement if the 'from' pattern is matched. It can also * apply groups matched from the original pattern using {x} annotation, e.g. {0}. */ class RewriteRule(private val from: String, private val to: String) { companion object { const val IGNORE_RUNTIME = "ignore" const val IGNORE_PREPROCESSOR_ONLY = "ignoreInPreprocessorOnly" } // We escape '$' so we don't conflict with regular expression symbols. private val inputPattern = Pattern.compile("^${from.replace("$", "\\$")}$") private val outputPattern = to.replace("$", "\$") /* * Whether this is any type of an ignore rule. */ fun isIgnoreRule() = isRuntimeIgnoreRule() || isPreprocessorOnlyIgnoreRule() /* * Whether this rules is an ignore rule. * * Any type matched to [from] will be in such case ignored by the preprocessor (thus missing * from the map) but it will be also ignored during rewriting. */ fun isRuntimeIgnoreRule() = to == IGNORE_RUNTIME /* * Whether this rule is an ignore rule that should be used only in the preprocessor. * * That means that error is still thrown if [from] is found in a library that is being * rewritten. Use this for types that are internal to support library. This is weaker version of * [isRuntimeIgnoreRule]. */ fun isPreprocessorOnlyIgnoreRule() = to == IGNORE_PREPROCESSOR_ONLY /** * Rewrites the given java type. Returns null if this rule is not applicable for the given type. */ fun apply(input: JavaType): TypeRewriteResult { val matcher = inputPattern.matcher(input.fullName) if (!matcher.matches()) { return TypeRewriteResult.NOT_APPLIED } if (isIgnoreRule()) { return TypeRewriteResult.IGNORED } var result = outputPattern for (i in 0 until matcher.groupCount()) { result = result.replace("{$i}", matcher.group(i + 1)) } return TypeRewriteResult(JavaType(result)) } fun reverse(): RewriteRule { val newFrom = to.replace("{0}", "(.*)") val newTo = from.replace("(.*)", "{0}") return RewriteRule(newFrom, newTo) } /* * Returns whether this rule is an ignore rule and applies to the given proGuard type. */ fun doesThisIgnoreProGuard(type: ProGuardType): Boolean { if (!isIgnoreRule()) { return false } val matcher = inputPattern.matcher(type.value) return matcher.matches() } override fun toString(): String { return "$inputPattern -> $outputPattern " } /** Returns JSON data model of this class */ fun toJson(): JsonData { return JsonData(from, to) } /** * JSON data model for [RewriteRule]. */ data class JsonData( @SerializedName("from") val from: String, @SerializedName("to") val to: String) { /** Creates instance of [RewriteRule] */ fun toRule(): RewriteRule { return RewriteRule(from, to) } } /** * Result of java type rewrite using [RewriteRule] */ data class TypeRewriteResult(val result: JavaType?, val isIgnored: Boolean = false) { companion object { val NOT_APPLIED = TypeRewriteResult(result = null, isIgnored = false) val IGNORED = TypeRewriteResult(result = null, isIgnored = true) } } }
jetifier/jetifier/core/src/main/kotlin/com/android/tools/build/jetifier/core/rule/RewriteRule.kt
94481574
/* * Copyright (C) 2017-2019 Hazuki * * 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 jp.hazuki.yuzubrowser.core.utility.hash /** * Calculate vector hash from ARGB image bytes */ fun ByteArray.getVectorHash(): Long { val mono = IntArray(size / 4) for (i in mono.indices) { mono[i] = 150 * this[i * 4 + 1] + 77 * this[i * 4 + 2] + 29 * this[i * 4 + 3] shr 8 } var result: Long = 0 var p = 0 for (y in 0..7) { for (x in 0..7) { result = result shl 1 or if (mono[p] > mono[p + 1]) 1 else 0 p++ } p++ } return result }
module/core/src/main/java/jp/hazuki/yuzubrowser/core/utility/hash/Gochiusearch.kt
228715038
/* * Copyright 2019 Ross Binden * * 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.rpkit.banks.bukkit.event.bank import com.rpkit.characters.bukkit.character.RPKCharacter import com.rpkit.core.bukkit.event.RPKBukkitEvent import com.rpkit.economy.bukkit.currency.RPKCurrency import org.bukkit.event.Cancellable import org.bukkit.event.HandlerList class RPKBukkitBankDepositEvent( override var character: RPKCharacter, override var currency: RPKCurrency, override var amount: Int ): RPKBukkitEvent(), RPKBankDepositEvent, Cancellable { companion object { @JvmStatic val handlerList = HandlerList() } private var cancel: Boolean = false override fun isCancelled(): Boolean { return cancel } override fun setCancelled(cancel: Boolean) { this.cancel = cancel } override fun getHandlers(): HandlerList { return handlerList } }
bukkit/rpk-bank-lib-bukkit/src/main/kotlin/com/rpkit/banks/bukkit/event/bank/RPKBukkitBankDepositEvent.kt
1560750722
/* * Copyright 2020 Netflix, 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 com.netflix.spinnaker.kork.plugins.api.internal import com.netflix.spinnaker.kork.plugins.proxy.ExtensionInvocationProxy import com.netflix.spinnaker.kork.plugins.proxy.LazyExtensionInvocationProxy import dev.minutest.junit.JUnit5Minutests import dev.minutest.rootContext import io.mockk.mockk import strikt.api.expectThat class ExtensionInvocationHandlerProviderTest : JUnit5Minutests { fun tests() = rootContext<Fixture> { fixture { Fixture() } test("Provides the proxied class") { val extensionClass = proxy.extensionClass expectThat(extensionClass == extension.javaClass) } test("Provides the lazily proxied class") { val extensionClass = lazyProxy.extensionClass expectThat(extensionClass == extension.javaClass) } test("Passes through the class if not proxied") { val extensionClass = extension.extensionClass expectThat(extensionClass == extension.javaClass) } } private inner class Fixture { val extension = SomeExtension() val proxy = ExtensionInvocationProxy.proxy(extension, emptyList(), mockk(relaxed = true)) as SpinnakerExtensionPoint val lazyProxy = LazyExtensionInvocationProxy.proxy( lazy { extension }, extension.javaClass, emptyList(), mockk(relaxed = true) ) as SpinnakerExtensionPoint } } class SomeExtension : SpinnakerExtensionPoint
kork-plugins-api/src/test/kotlin/com/netflix/spinnaker/kork/plugins/api/internal/ExtensionClassProviderTest.kt
2973261047
/* * Copyright 2019 Ren Binden * * 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.rpkit.skills.bukkit.command import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import com.rpkit.skills.bukkit.RPKSkillsBukkit import com.rpkit.skills.bukkit.skills.RPKSkillProvider import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player class BindSkillCommand(private val plugin: RPKSkillsBukkit): CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (!sender.hasPermission("rpkit.skills.command.bindskill")) { sender.sendMessage(plugin.messages["no-permission-bind-skill"]) return true } if (args.isEmpty()) { sender.sendMessage(plugin.messages["bind-skill-usage"]) return true } val skillProvider = plugin.core.serviceManager.getServiceProvider(RPKSkillProvider::class) val skillName = args[0] val skill = skillProvider.getSkill(skillName) if (skill == null) { sender.sendMessage(plugin.messages["bind-skill-invalid-skill"]) return true } if (sender !is Player) { sender.sendMessage(plugin.messages["not-from-console"]) return true } val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender) if (minecraftProfile == null) { sender.sendMessage(plugin.messages["no-minecraft-profile"]) return true } val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val character = characterProvider.getActiveCharacter(minecraftProfile) if (character == null) { sender.sendMessage(plugin.messages["no-character"]) return true } val item = sender.inventory.itemInMainHand if (skillProvider.getSkillBinding(character, item) != null) { sender.sendMessage(plugin.messages["bind-skill-invalid-binding-already-exists"]) return true } skillProvider.setSkillBinding(character, item, skill) sender.sendMessage(plugin.messages["bind-skill-valid", mapOf( "character" to character.name, "item" to item.type.toString().toLowerCase().replace('_', ' '), "skill" to skill.name )]) return true } }
bukkit/rpk-skills-bukkit/src/main/kotlin/com/rpkit/skills/bukkit/command/BindSkillCommand.kt
318539625