content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
//package com.sksamuel.kotest.properties.shrinking // //import io.kotest.matchers.comparables.lte //import io.kotest.matchers.doubles.lt //import io.kotest.matchers.ints.shouldBeLessThan //import io.kotest.matchers.string.shouldHaveLength //import io.kotest.properties.Gen //import io.kotest.properties.PropertyTesting //import io.kotest.properties.assertAll //import io.kotest.properties.double //import io.kotest.properties.int //import io.kotest.properties.negativeIntegers //import io.kotest.properties.positiveIntegers //import io.kotest.properties.shrinking.ChooseShrinker //import io.kotest.properties.shrinking.Shrinker //import io.kotest.properties.shrinking.StringShrinker //import io.kotest.properties.string //import io.kotest.shouldBe //import io.kotest.shouldThrowAny //import io.kotest.core.spec.style.StringSpec // //class ShrinkTest : StringSpec({ // // beforeSpec { // PropertyTesting.shouldPrintShrinkSteps = false // } // // afterSpec { // PropertyTesting.shouldPrintShrinkSteps = true // } // // "should report shrinked values for arity 1 ints" { // shouldThrowAny { // assertAll(Gen.int()) { // it.shouldBeLessThan(5) // } // }.message shouldBe "Property failed for\n" + // "Arg 0: 5 (shrunk from 2147483647)\n" + // "after 2 attempts\n" + // "Caused by: 2147483647 should be < 5" // } // // "should shrink arity 2 strings" { // shouldThrowAny { // assertAll(Gen.string(), Gen.string()) { a, b -> // (a.length + b.length).shouldBeLessThan(4) // } // }.message shouldBe "Property failed for\n" + // "Arg 0: <empty string>\n" + // "Arg 1: aaaaa (shrunk from \n" + // "abc\n" + // "123\n" + // ")\n" + // "after 3 attempts\n" + // "Caused by: 9 should be < 4" // } // // "should shrink arity 3 positiveIntegers" { // shouldThrowAny { // assertAll(Gen.positiveIntegers(), Gen.positiveIntegers(), Gen.positiveIntegers()) { a, b, c -> // a.toLong() + b.toLong() + c.toLong() shouldBe 4L // } // }.message shouldBe "Property failed for\nArg 0: 1 (shrunk from 2147483647)\nArg 1: 1 (shrunk from 2147483647)\nArg 2: 1 (shrunk from 2147483647)\nafter 1 attempts\nCaused by: expected: 4L but was: 6442450941L" // } // // "should shrink arity 4 negativeIntegers" { // shouldThrowAny { // assertAll(Gen.negativeIntegers(), // Gen.negativeIntegers(), // Gen.negativeIntegers(), // Gen.negativeIntegers()) { a, b, c, d -> // a + b + c + d shouldBe 4 // } // }.message shouldBe "Property failed for\nArg 0: -1 (shrunk from -2147483648)\nArg 1: -1 (shrunk from -2147483648)\nArg 2: -1 (shrunk from -2147483648)\nArg 3: -1 (shrunk from -2147483648)\nafter 1 attempts\nCaused by: expected: 4 but was: 0" // } // // "should shrink arity 1 doubles" { // shouldThrowAny { // assertAll(Gen.double()) { a -> // a shouldBe lt(3.0) // } // }.message shouldBe "Property failed for\nArg 0: 3.0 (shrunk from 1.0E300)\nafter 4 attempts\nCaused by: 1.0E300 should be < 3.0" // } // // "should shrink Gen.choose" { // shouldThrowAny { // assertAll(object : Gen<Int> { // override fun constants(): Iterable<Int> = emptyList() // override fun random(seed: Long?): Sequence<Int> = generateSequence { 14 } // override fun shrinker() = ChooseShrinker(5, 15) // }) { a -> // a shouldBe lte(10) // } // }.message shouldBe "Property failed for\nArg 0: 11 (shrunk from 14)\nafter 1 attempts\nCaused by: 14 should be <= 10" // } // // "should shrink strings to empty string" { // val gen = object : Gen<String> { // override fun random(seed: Long?): Sequence<String> = generateSequence { "asjfiojoqiwehuoahsuidhqweqwe" } // override fun constants(): Iterable<String> = emptyList() // override fun shrinker(): Shrinker<String>? = StringShrinker // } // shouldThrowAny { // assertAll(gen) { a -> // a.shouldHaveLength(10) // } // }.message shouldBe "Property failed for\nArg 0: <empty string> (shrunk from asjfiojoqiwehuoahsuidhqweqwe)\nafter 1 attempts\nCaused by: asjfiojoqiwehuoahsuidhqweqwe should have length 10, but instead was 28" // } // // "should shrink strings to min failing size" { // val gen = object : Gen<String> { // override fun random(seed: Long?): Sequence<String> = generateSequence { "asjfiojoqiwehuoahsuidhqweqwe" } // override fun constants(): Iterable<String> = emptyList() // override fun shrinker(): Shrinker<String>? = StringShrinker // } // shouldThrowAny { // assertAll(gen) { a -> // a.padEnd(10, '*').shouldHaveLength(10) // } // }.message shouldBe "Property failed for\nArg 0: aaaaaaaaaaaaaa (shrunk from asjfiojoqiwehuoahsuidhqweqwe)\nafter 1 attempts\nCaused by: asjfiojoqiwehuoahsuidhqweqwe should have length 10, but instead was 28" // } //})
kotest-assertions/src/jvmTest/kotlin/com/sksamuel/kotest/properties/shrinking/ShrinkTest.kt
1512359212
package io.kotest.properties.shrinking import io.kotest.assertions.show.show import io.kotest.properties.Gen import io.kotest.properties.PropertyContext import io.kotest.properties.PropertyFailureInput import io.kotest.properties.PropertyTesting import io.kotest.properties.propertyAssertionError fun <T> shrink(t: T, gen: Gen<T>, test: (T) -> Unit): T = shrink2(t, gen.shrinker(), test) fun <T> shrink2(t: T, shrinker: Shrinker<T>?, test: (T) -> Unit): T { return when (shrinker) { null -> t else -> shrink(t, shrinker, test) } } fun <T> shrink(t: T, shrinker: Shrinker<T>, test: (T) -> Unit): T { val sb = StringBuilder() sb.append("Attempting to shrink failed arg ${t.show()}\n") var candidate = t val tested = HashSet<T>() var count = 0 while (true) { val candidates = shrinker.shrink(candidate).filterNot { tested.contains(it) } if (candidates.isEmpty()) { sb.append("Shrink result => ${candidate.show()}\n") if (PropertyTesting.shouldPrintShrinkSteps) { println(sb) } return candidate } else { val next = candidates.firstOrNull { tested.add(it) count++ try { test(it) sb.append("Shrink #$count: ${it.show()} pass\n") false } catch (t: Throwable) { sb.append("Shrink #$count: ${it.show()} fail\n") true } } if (next == null) { sb.append("Shrink result => ${candidate.show()}\n") if (PropertyTesting.shouldPrintShrinkSteps) { println(sb) } return candidate } else { candidate = next } } } } fun <A, B, C, D> shrinkInputs(a: A, b: B, c: C, d: D, gena: Gen<A>, genb: Gen<B>, genc: Gen<C>, gend: Gen<D>, context: PropertyContext, fn: PropertyContext.(a: A, b: B, c: C, d: D) -> Unit, e: AssertionError) { val smallestA = shrink(a, gena) { context.fn(it, b, c, d) } val smallestB = shrink(b, genb) { context.fn(smallestA, it, c, d) } val smallestC = shrink(c, genc) { context.fn(smallestA, smallestB, it, d) } val smallestD = shrink(d, gend) { context.fn(smallestA, smallestB, smallestC, it) } val inputs = listOf( PropertyFailureInput<A>(a, smallestA), PropertyFailureInput<B>(b, smallestB), PropertyFailureInput<C>(c, smallestC), PropertyFailureInput<D>(d, smallestD) ) throw propertyAssertionError(e, context.attempts(), inputs) }
kotest-assertions/src/commonMain/kotlin/io/kotest/properties/shrinking/shrink.kt
3029170728
package com.github.alondero.nestlin.ppu import com.github.alondero.nestlin.* class PpuAddressedMemory { val controller = Control() // $2000 val mask = Mask() // $2001 val status = Status() // $2002 var oamAddress: Byte = 0 // $2003 var oamData: Byte = 0 // $2004 var scroll: Byte = 0 // $2005 var address: Byte = 0 // $2006 var data: Byte = 0 // $2007 private var writeToggle = false val ppuInternalMemory = PpuInternalMemory() val objectAttributeMemory = ObjectAttributeMemory() val vRamAddress = VramAddress() // v val tempVRamAddress = VramAddress() // t var fineXScroll = 0 // x var nmiOccurred = false var nmiOutput = false fun reset() { controller.reset() mask.reset() status.reset() oamAddress = 0 oamData = 0 scroll = 0 address = 0 data = 0 writeToggle = false } operator fun get(addr: Int) = when (addr) { 0 -> controller.register 1 -> mask.register 2 -> { writeToggle = false val value = status.register.letBit(7, nmiOccurred) status.clearVBlank() nmiOccurred = false value } 3 -> oamAddress 4 -> oamData 5 -> scroll 6 -> address else /*7*/ -> { vRamAddress += controller.vramAddressIncrement() data } } operator fun set(addr: Int, value: Byte) { // println("Setting PPU Addressed data ${addr.toHexString()}, with ${value.toHexString()}") when (addr) { 0 -> { controller.register = value tempVRamAddress.updateNameTable(value.toUnsignedInt() and 0x03) } 1 -> mask.register = value 2 -> status.register = value 3 -> oamAddress = value 4 -> oamData = value 5 -> { scroll = value if (writeToggle) { tempVRamAddress.coarseYScroll = (value.toUnsignedInt() shr 3) and 0x1F tempVRamAddress.fineYScroll = value.toUnsignedInt() and 0x07 } else { tempVRamAddress.coarseXScroll = (value.toUnsignedInt() shr 3) and 0x1F fineXScroll = value.toUnsignedInt() and 0x07 } writeToggle = !writeToggle } 6 -> { address = value if (writeToggle) { tempVRamAddress.setLowerByte(value) } else { tempVRamAddress.setUpper7Bits(value) } } else /*7*/ -> { vRamAddress += controller.vramAddressIncrement() data = value.letBit(7, nmiOutput) } } } } class VramAddress { /** 15 bit register yyy NN YYYYY XXXXX ||| || ||||| +++++-- coarse X scroll ||| || +++++-------- coarse Y scroll ||| |+-------------- horizontal nametable select ||| +--------------- vertical nametable select +++----------------- fine Y scroll */ var coarseXScroll = 0 var coarseYScroll = 0 // 5 bits so maximum value is 31 var horizontalNameTable = false var verticalNameTable = false var fineYScroll = 0 // 3 bits so maximum value is 7 - wraps to coarseY if overflows fun setUpper7Bits(bits: Byte) { fineYScroll = (bits.toUnsignedInt() shr 4) and 0x03 horizontalNameTable = bits.isBitSet(2) verticalNameTable = bits.isBitSet(3) coarseYScroll = (coarseYScroll and 0x07) or ((bits.toUnsignedInt() and 0x03) shl 3) } fun setLowerByte(byte: Byte) { coarseXScroll = byte.toUnsignedInt() and 0x1F coarseYScroll = (coarseYScroll and 0x18) or ((byte.toUnsignedInt()) shr 5) } fun updateNameTable(nameTable: Int) { nameTable.toSignedByte().let { horizontalNameTable = it.isBitSet(0) verticalNameTable = it.isBitSet(1) } } private fun getNameTable() = (if (verticalNameTable) 2 else 0) + (if (horizontalNameTable) 1 else 0) fun incrementVerticalPosition() { fineYScroll++ if (fineYScroll > 7) { coarseYScroll++ fineYScroll = 0 if (coarseYScroll > 29) { // Y Scroll now out of bounds if (coarseYScroll < 32) { // Hasn't overflowed therefore switch vertical nametable verticalNameTable = !verticalNameTable } coarseYScroll = 0 } } } fun incrementHorizontalPosition() { coarseXScroll++ if (coarseXScroll > 31) { horizontalNameTable = !horizontalNameTable coarseXScroll = 0 } } infix operator fun plusAssign(vramAddressIncrement: Int) { if (vramAddressIncrement == 32) { coarseYScroll++ } else { coarseXScroll++ } } fun asAddress() = (((((fineYScroll shl 2) or getNameTable()) shl 5) or coarseYScroll) shl 5) or coarseXScroll } class Control { var register: Byte = 0 fun reset() { register = 0 } fun baseNametableAddr() = 0x2000 + ((register.toUnsignedInt() and 0b00000011) * 0x400) fun vramAddressIncrement() = if (register.isBitSet(2)) 32 else 1 fun spritePatternTableAddress() = if (register.isBitSet(3)) 0x1000 else 0 fun backgroundPatternTableAddress() = if (register.isBitSet(4)) 0x1000 else 0 fun spriteSize() = if (register.isBitSet(5)) SpriteSize.X_8_16 else SpriteSize.X_8_8 fun generateNmi() = register.isBitSet(7) enum class SpriteSize { X_8_8, X_8_16 } } class Mask { var register: Byte = 0 fun reset() { register = 0 } /** 7 bit 0 ---- ---- BGRs bMmG |||| |||| |||| |||+- Greyscale (0: normal color, 1: produce a greyscale display) |||| ||+-- 1: Show background in leftmost 8 pixels of screen, 0: Hide |||| |+--- 1: Show sprites in leftmost 8 pixels of screen, 0: Hide |||| +---- 1: Show background |||+------ 1: Show sprites ||+------- Emphasize red* |+-------- Emphasize green* +--------- Emphasize blue* */ fun greyscale() = register.isBitSet(0) fun backgroundInLeftmost8px() = register.isBitSet(1) fun spritesInLeftmost8px() = register.isBitSet(2) fun showBackground() = register.isBitSet(3) fun showSprites() = register.isBitSet(4) fun emphasizeRed() = register.isBitSet(5) fun emphasizeGreen() = register.isBitSet(6) fun emphasizeBlue() = register.isBitSet(7) } class Status { var register: Byte = 0 /** 7 bit 0 ---- ---- VSO. .... |||| |||| |||+-++++- Least significant bits previously written into a PPU register ||| (due to register not being updated for this address) ||+------- Sprite overflow. The intent was for this flag to be set || whenever more than eight sprites appear on a scanline, but a || hardware bug causes the actual behavior to be more complicated || and generate false positives as well as false negatives; see || PPU sprite evaluation. This flag is set during sprite || evaluation and cleared at dot 1 (the second dot) of the || pre-render line. |+-------- Sprite 0 Hit. Set when a nonzero pixel of sprite 0 overlaps | a nonzero background pixel; cleared at dot 1 of the pre-render | line. Used for raster timing. +--------- Vertical blank has started (0: not in vblank; 1: in vblank). Set at dot 1 of line 241 (the line *after* the post-render line); cleared after reading $2002 and at dot 1 of the pre-render line. */ fun spriteOverflow() = register.isBitSet(5) fun sprite0Hit() = register.isBitSet(6) fun vBlankStarted() = register.isBitSet(7) fun reset() { register = 0 } fun clearOverflow() { register = register.clearBit(5) } fun clearVBlank() { register = register.clearBit(7) } fun clearFlags() {reset()} } class PpuInternalMemory { private val patternTable0 = ByteArray(0x1000) private val patternTable1 = ByteArray(0x1000) private val nameTable0 = ByteArray(0x400) private val nameTable1 = ByteArray(0x400) private val nameTable2 = ByteArray(0x400) private val nameTable3 = ByteArray(0x400) private val paletteRam = PaletteRam() // private val backgroundNametables = Background() // private val spriteNametables = Sprites() operator fun get(addr: Int): Byte = when (addr) { in 0x0000..0x0999 -> patternTable0[addr % 0x1000] in 0x1000..0x1999 -> patternTable1[addr % 0x1000] in 0x2000..0x23FF -> nameTable0[addr % 0x400] in 0x2400..0x27FF -> nameTable1[addr % 0x400] in 0x2800..0x2BFF -> nameTable2[addr % 0x400] in 0x2C00..0x2FFF -> nameTable3[addr % 0x400] in 0x3000..0x3EFF -> this[addr - 0x1000] // Mirror of 0x2000 - 0x2EFF else /*in 0x3F00..0x3FFF*/ -> paletteRam[addr % 0x020] } } class PaletteRam { private val bgPalette = ByteArray(0x10) private val spritePalette = ByteArray(0x10) operator fun get(addr: Int): Byte = when (addr) { in 0x00..0x0F -> bgPalette[addr] else /*in 0x10..0x1F*/ -> spritePalette[addr] } }
src/main/kotlin/com/github/alondero/nestlin/ppu/PpuAddressedMemory.kt
328409974
package tileentity.electric import com.cout970.magneticraft.api.internal.energy.ElectricNode import com.cout970.magneticraft.block.PROPERTY_DIRECTION import com.cout970.magneticraft.config.Config import com.cout970.magneticraft.misc.gui.ValueAverage import com.cout970.magneticraft.misc.inventory.get import com.cout970.magneticraft.misc.tileentity.ITileTrait import com.cout970.magneticraft.misc.tileentity.TraitElectricity import com.cout970.magneticraft.registry.ITEM_ENERGY_CONSUMER import com.cout970.magneticraft.registry.ITEM_ENERGY_PROVIDER import com.cout970.magneticraft.registry.fromItem import com.cout970.magneticraft.tileentity.TileBase import com.cout970.magneticraft.util.interpolate import com.teamwizardry.librarianlib.common.util.autoregister.TileRegister import net.minecraft.nbt.NBTTagCompound import net.minecraft.util.EnumFacing import net.minecraftforge.items.ItemStackHandler /** * Created by cout970 on 11/07/2016. */ @TileRegister("battery") class TileBattery : TileBase() { var mainNode = ElectricNode({ world }, { pos }, capacity = 1.25) val traitElectricity = TraitElectricity(this, listOf(mainNode), canConnectAtSideImpl = this::canConnectAtSide) override val traits: List<ITileTrait> = listOf(traitElectricity) var storage: Int = 0 val inventory = ItemStackHandler(2) val chargeRate = ValueAverage(20) val itemChargeRate = ValueAverage(20) override fun update() { if (worldObj.isServer) { if (mainNode.voltage > UPPER_LIMIT) { val speed = interpolate(mainNode.voltage, UPPER_LIMIT, 120.0) * MAX_CHARGE_SPEED val finalSpeed = Math.min(Math.floor(speed).toInt(), Config.blockBatteryCapacity - storage) mainNode.applyPower(-finalSpeed.toDouble(), false) storage += finalSpeed chargeRate += finalSpeed } else if (mainNode.voltage < LOWER_LIMIT) { val speed = (1 - interpolate(mainNode.voltage, 60.0, LOWER_LIMIT)) * MAX_CHARGE_SPEED val finalSpeed = Math.min(Math.floor(speed).toInt(), storage) mainNode.applyPower(finalSpeed.toDouble(), false) storage -= finalSpeed chargeRate -= finalSpeed } chargeRate.tick() val toCharge = inventory[0] if(toCharge != null){ val cap = ITEM_ENERGY_CONSUMER!!.fromItem(toCharge) if(cap != null){ val amount = Math.min(storage, Config.blockBatteryTransferRate) //simulated val given = cap.giveEnergy(amount.toDouble(), true) //this avoid energy deletion creation when the battery has decimals in the energy value\ val floored = Math.floor(given) if(floored > 0){ cap.giveEnergy(floored, false) storage -= floored.toInt() itemChargeRate -= floored } } } val toDischarge = inventory[1] if(toDischarge != null){ val cap = ITEM_ENERGY_PROVIDER!!.fromItem(toDischarge) if(cap != null){ val amount = Math.min(Config.blockBatteryCapacity - storage, Config.blockBatteryTransferRate) //simulated val taken = cap.takeEnergy(amount.toDouble(), true) //this avoid energy deletion creation when the battery has decimals in the energy value val floored = Math.floor(taken) if(floored > 0){ cap.takeEnergy(floored, false) storage += floored.toInt() itemChargeRate += floored } } } itemChargeRate.tick() } super.update() } override fun save(): NBTTagCompound { val nbt = NBTTagCompound() nbt.setInteger("storage", storage) nbt.setTag("inventory", inventory.serializeNBT()) return super.save().also { it.merge(nbt) } } override fun load(nbt: NBTTagCompound) { super.load(nbt) storage = nbt.getInteger("storage") inventory.deserializeNBT(nbt.getCompoundTag("inventory")) } fun getFacing(): EnumFacing { val state = world.getBlockState(pos) return state[PROPERTY_DIRECTION] } fun canConnectAtSide(facing: EnumFacing?): Boolean { return facing == null || facing == getFacing() } companion object { //this is only used with voltage to charge the block, not for charging items val MAX_CHARGE_SPEED = 400 val UPPER_LIMIT = 100.0 val LOWER_LIMIT = 90.0 } }
ignore/test/tileentity/electric/TileBattery.kt
2442589273
package com.freaklius.kotlin.algorithms.sort /** * Heap sort algorithm * AveragePerformance = O(n*lg(n)) */ class HeapSort : SortAlgorithm { /** * Stores size of the heap to be used */ private var heapSize = 0 override fun sort(arr: Array<Long>): Array<Long> { buildMaxHeap(arr) var i: Int = arr.size - 1 while (i >= 1){ swap(arr, i, 0) heapSize-- maxHeapify(arr, 0) i-- } return arr } /** * Builds a max-heap data structure from the input array (the original array is replaced) using maxHeapify method * @param arr */ private fun buildMaxHeap(arr: Array<Long>){ heapSize = arr.size var i: Int = Math.floor(arr.size / 2.0).toInt() while (i >= 0){ maxHeapify(arr, i) i-- } } /** * Restores MaxHeap property starting from the array's ith element and going down * @param arr * @param i heap index where we need to check the property; we implicitly assume that child heaps conform to the * MaxHeap property */ private fun maxHeapify(arr: Array<Long>, i: Int){ val leftElementIndex = left(i) val rightElementIndex = right(i) var largestElementIndex : Int = i if ( (leftElementIndex <= heapSize - 1) && (arr[leftElementIndex] > arr[i]) ){ largestElementIndex = leftElementIndex } if ( (rightElementIndex <= heapSize - 1) && (arr[rightElementIndex] > arr[largestElementIndex]) ){ largestElementIndex = rightElementIndex } if (largestElementIndex != i){ swap(arr, i, largestElementIndex) maxHeapify(arr, largestElementIndex) } } /** * Returns the index of the array element corresponding to the left element of the ith element in the heap * @param i an element to get the left element */ private fun left(i: Int) : Int{ return 2 * i + 1 } /** * Returns the index of the array element corresponding to the right element of the ith element in the heap * @param i an element to get the left element */ private fun right(i: Int) : Int{ return 2 * i + 2 } override fun getName(): String { return "HeapSort" } }
src/com/freaklius/kotlin/algorithms/sort/HeapSort.kt
2873214773
package reactivecircus.flowbinding.viewpager2 import androidx.test.filters.LargeTest import androidx.viewpager2.widget.ViewPager2 import com.google.common.truth.Truth.assertThat import org.junit.Test import reactivecircus.blueprint.testing.action.swipeLeftOnView import reactivecircus.blueprint.testing.action.swipeRightOnView import reactivecircus.flowbinding.testing.FlowRecorder import reactivecircus.flowbinding.testing.launchTest import reactivecircus.flowbinding.testing.recordWith import reactivecircus.flowbinding.viewpager2.fixtures.ViewPager2Fragment import reactivecircus.flowbinding.viewpager2.test.R @LargeTest class ViewPager2PageSelectedFlowTest { @Test fun pageSelections_swipe() { launchTest<ViewPager2Fragment> { val recorder = FlowRecorder<Int>(testScope) getViewById<ViewPager2>(R.id.viewPager).pageSelections().recordWith(recorder) assertThat(recorder.takeValue()) .isEqualTo(0) recorder.assertNoMoreValues() swipeLeftOnView(R.id.viewPager) assertThat(recorder.takeValue()) .isEqualTo(1) recorder.assertNoMoreValues() cancelTestScope() swipeRightOnView(R.id.viewPager) recorder.assertNoMoreValues() } } @Test fun pageSelections_programmatic() { launchTest<ViewPager2Fragment> { val recorder = FlowRecorder<Int>(testScope) val viewPager = getViewById<ViewPager2>(R.id.viewPager) viewPager.pageSelections().recordWith(recorder) assertThat(recorder.takeValue()) .isEqualTo(0) recorder.assertNoMoreValues() viewPager.currentItem = 1 assertThat(recorder.takeValue()) .isEqualTo(1) recorder.assertNoMoreValues() cancelTestScope() viewPager.currentItem = 0 recorder.assertNoMoreValues() } } @Test fun pageSelections_skipInitialValue() { launchTest<ViewPager2Fragment> { val recorder = FlowRecorder<Int>(testScope) val viewPager = getViewById<ViewPager2>(R.id.viewPager) viewPager.pageSelections() .skipInitialValue() .recordWith(recorder) recorder.assertNoMoreValues() viewPager.currentItem = 1 assertThat(recorder.takeValue()) .isEqualTo(1) recorder.assertNoMoreValues() cancelTestScope() viewPager.currentItem = 0 recorder.assertNoMoreValues() } } }
flowbinding-viewpager2/src/androidTest/java/reactivecircus/flowbinding/viewpager2/ViewPager2PageSelectedFlowTest.kt
66006066
package com.waz.zclient.framework.data.conversations import com.waz.zclient.framework.data.TestDataProvider data class ConversationsTestData( val id: String, val remoteId: String, val name: String?, val creator: String, val conversationType: Int, val team: String?, val managed: Boolean?, val lastEventTime: Long, val active: Boolean, val lastRead: Long, val mutedStatus: Int, val muteTime: Long, val archived: Boolean, val archiveTime: Long, val cleared: Long?, val generatedName: String, val searchKey: String?, val unreadCount: Int, val unsentCount: Int, val hidden: Boolean, val missedCall: String?, val incomingKnock: String?, val verified: String?, val ephemeral: Long?, val globalEphemeral: Long?, val unreadCallCount: Int, val unreadPingCount: Int, val access: String?, val accessRole: String?, val link: String?, val unreadMentionsCount: Int, val unreadQuoteCount: Int, val receiptMode: Int?, val legalHoldStatus: Int, val domain: String? ) object ConversationsTestDataProvider : TestDataProvider<ConversationsTestData>() { override fun provideDummyTestData(): ConversationsTestData = ConversationsTestData( id = "3-1-70b5baab-323d-446e-936d-745c64d6c7d8", remoteId = "3-1-70b5baab-323d-446e-936d-745c64d6c7d8", name = null, creator = "3762d820-83a1-4fae-ae58-6c39fb2e9d8a", conversationType = 0, team = null, managed = false, lastEventTime = 0, active = true, lastRead = 0, mutedStatus = 0, muteTime = 0, archived = false, archiveTime = 0, cleared = null, generatedName = "Conversation name", searchKey = null, unreadCount = 0, unsentCount = 0, hidden = false, missedCall = null, incomingKnock = null, verified = null, ephemeral = null, globalEphemeral = null, unreadCallCount = 0, unreadPingCount = 0, access = null, accessRole = null, link = null, unreadMentionsCount = 0, unreadQuoteCount = 0, receiptMode = null, legalHoldStatus = 0, domain = "staging" ) }
common-test/src/main/kotlin/com/waz/zclient/framework/data/conversations/ConversationsTestDataProvider.kt
2854807000
package leakcanary.internal internal sealed class RetainInstanceEvent { object NoMoreObjects : RetainInstanceEvent() sealed class CountChanged : RetainInstanceEvent() { class BelowThreshold(val retainedCount: Int) : RetainInstanceEvent() class DumpingDisabled(val reason: String) : RetainInstanceEvent() object DumpHappenedRecently : RetainInstanceEvent() } } /** * Called by LeakCanary when the number of retained instances updates . */ internal fun interface OnRetainInstanceListener { /** * Called when there's a change to the Retained Instances. See [RetainInstanceEvent] for * possible events. */ fun onEvent(event: RetainInstanceEvent) } internal class DefaultOnRetainInstanceListener : OnRetainInstanceListener { override fun onEvent(event: RetainInstanceEvent) {} }
leakcanary-android-core/src/main/java/leakcanary/internal/OnRetainInstanceListener.kt
3967419700
/* * Copyright (c) 2021 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.browser.webview import android.content.Context import io.mockk.MockKAnnotations import io.mockk.every import io.mockk.impl.annotations.InjectMockKs import io.mockk.impl.annotations.MockK import io.mockk.mockk import io.mockk.unmockkAll import io.mockk.verify import jp.toastkid.yobidashi.browser.webview.factory.WebChromeClientFactory import jp.toastkid.yobidashi.browser.webview.factory.WebViewClientFactory import jp.toastkid.yobidashi.browser.webview.factory.WebViewFactory import org.junit.After import org.junit.Before import org.junit.Test class WebViewFactoryUseCaseTest { @InjectMockKs private lateinit var webViewFactoryUseCase: WebViewFactoryUseCase @MockK private lateinit var webViewFactory: WebViewFactory @MockK private lateinit var webViewClientFactory: WebViewClientFactory @MockK private lateinit var webChromeClientFactory: WebChromeClientFactory @MockK private lateinit var context: Context @MockK private lateinit var webView: CustomWebView @Before fun setUp() { MockKAnnotations.init(this) every { webView.setWebViewClient(any()) }.answers { Unit } every { webView.setWebChromeClient(any()) }.answers { Unit } every { webViewFactory.make(any()) }.returns(webView) every { webViewClientFactory.invoke() }.returns(mockk()) every { webChromeClientFactory.invoke() }.returns(mockk()) } @After fun tearDown() { unmockkAll() } @Test fun test() { webViewFactoryUseCase.invoke(context) verify(atLeast = 1) { webView.setWebViewClient(any()) } verify(atLeast = 1) { webView.setWebChromeClient(any()) } verify(atLeast = 1) { webViewFactory.make(any()) } verify(atLeast = 1) { webViewClientFactory.invoke() } verify(atLeast = 1) { webChromeClientFactory.invoke() } } }
app/src/test/java/jp/toastkid/yobidashi/browser/webview/WebViewFactoryUseCaseTest.kt
1195404684
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.refactoring import com.intellij.lang.ImportOptimizer import com.intellij.psi.PsiFile import org.rust.ide.formatter.processors.asTrivial import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.RsElement import org.rust.lang.core.psi.ext.RsMod import org.rust.lang.core.psi.ext.childrenOfType class RsImportOptimizer : ImportOptimizer { override fun supports(file: PsiFile?): Boolean = file is RsFile override fun processFile(file: PsiFile?) = Runnable { executeForUseItem(file as RsFile) executeForExternCrate(file) } private fun executeForExternCrate(file: RsFile) { val first = file.childrenOfType<RsElement>() .firstOrNull { it !is RsInnerAttr } ?: return val externCrateItems = file.childrenOfType<RsExternCrateItem>() externCrateItems .sortedBy { it.referenceName } .mapNotNull { it.copy() as? RsExternCrateItem } .forEach { file.addBefore(it, first) } externCrateItems.forEach { it.delete() } } private fun executeForUseItem(mod: RsMod) { val uses = mod.childrenOfType<RsUseItem>() if (uses.isEmpty()) { return } replaceOrderOfUseItems(mod, uses) val mods = mod.childrenOfType<RsMod>() mods.forEach { executeForUseItem(it) } } companion object { private fun optimizeUseSpeck(psiFactory: RsPsiFactory, useSpeck: RsUseSpeck) { if (removeCurlyBraces(psiFactory, useSpeck)) return val useSpeckList = useSpeck.useGroup?.useSpeckList ?: return if (useSpeckList.size < 2) return useSpeckList.forEach { optimizeUseSpeck(psiFactory, it) } val sortedList = useSpeckList .sortedWith(compareBy<RsUseSpeck> { it.path?.self == null }.thenBy { it.pathText }) .map { it.copy() } useSpeckList.zip(sortedList).forEach { it.first.replace(it.second) } } private fun removeCurlyBraces(psiFactory: RsPsiFactory, useSpeck: RsUseSpeck): Boolean { val name = useSpeck.useGroup?.asTrivial?.text ?: return false val path = useSpeck.path?.text val tempPath = "${if (path != null) "$path::" else ""}$name" val newUseSpeck = psiFactory.createUseSpeck(tempPath) useSpeck.replace(newUseSpeck) return true } private fun replaceOrderOfUseItems(file: RsMod, uses: Collection<RsUseItem>) { val first = file.childrenOfType<RsElement>() .firstOrNull { it !is RsExternCrateItem && it !is RsInnerAttr } ?: return val psiFactory = RsPsiFactory(file.project) val sortedUses = uses .sortedBy { it.useSpeck?.pathText } .mapNotNull { it.copy() as? RsUseItem } sortedUses .mapNotNull { it.useSpeck } .forEach { optimizeUseSpeck(psiFactory, it) } for (importPath in sortedUses) { file.addBefore(importPath, first) } uses.forEach { it.delete() } } } } private val RsUseSpeck.pathText get() = path?.text?.toLowerCase()
src/main/kotlin/org/rust/lang/refactoring/RsImportOptimizer.kt
4241693162
/* * Copyright (C) 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 com.example.android.trackr.ui.utils import android.app.Application import android.content.res.Resources import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.example.android.trackr.data.Avatar import com.example.android.trackr.data.Tag import com.example.android.trackr.data.TagColor import com.example.android.trackr.data.TaskSummary import com.example.android.trackr.data.TaskStatus import com.example.android.trackr.data.User import com.example.android.trackr.utils.DateTimeUtils import io.mockk.every import io.mockk.mockkObject import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import java.time.Clock import java.time.Instant import java.time.ZoneId import com.google.common.truth.Truth.assertThat @RunWith(AndroidJUnit4::class) class AccessibilityUtilsTest { private val dateInEpochSecond = 1584310694L // March 15, 2020 private val fakeClock = Clock.fixed(Instant.ofEpochSecond(dateInEpochSecond), ZoneId.of("US/Central")) private lateinit var resources: Resources private lateinit var application: Application @Before fun setup() { application = ApplicationProvider.getApplicationContext() resources = application.resources mockkObject(DateTimeUtils) every { DateTimeUtils.durationMessageOrDueDate( resources, any(), fakeClock ) } returns dateTimeValue } @Test fun taskSummaryLabel_noTags() { assertThat( AccessibilityUtils.taskSummaryLabel( application, taskSummary, fakeClock ) ).isEqualTo("task 1. Owner: user. $dateTimeValue.") } @Test fun taskSummaryLabel_withTags() { assertThat( AccessibilityUtils.taskSummaryLabel( application, taskSummaryWithTags, fakeClock ) ).isEqualTo("task 2. Owner: user. $dateTimeValue. Tag: tag1. Tag: tag2") } companion object { private val user1 = User(1, "user", Avatar.DEFAULT_USER) private val tag1 = Tag(1, "tag1", TagColor.BLUE) private val tag2 = Tag(2, "tag2", TagColor.RED) private const val dateTimeValue = "Due today" var taskSummary = TaskSummary( id = 1, title = "task 1", dueAt = Instant.now(), owner = user1, status = TaskStatus.IN_PROGRESS, tags = emptyList(), orderInCategory = 1, starred = false, ) var taskSummaryWithTags = TaskSummary( id = 2, title = "task 2", dueAt = Instant.now(), owner = user1, status = TaskStatus.IN_PROGRESS, tags = listOf(tag1, tag2), orderInCategory = 2, starred = false, ) } }
app/src/test/java/com/example/android/trackr/ui/utils/AccessibilityUtilsTest.kt
2799558754
package com.eden.orchid.impl.resources import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.resources.resourcesource.FileResourceSource import com.eden.orchid.api.resources.resourcesource.LocalResourceSource import com.google.inject.Provider import com.google.inject.name.Named import javax.inject.Inject class LocalFileResourceSource @Inject constructor( context: Provider<OrchidContext>, @Named("src") resourcesDir: String ) : FileResourceSource(context, resourcesDir, Integer.MAX_VALUE), LocalResourceSource
OrchidCore/src/main/kotlin/com/eden/orchid/impl/resources/LocalFileResourceSource.kt
2380097788
package model import org.jetbrains.dokka.DokkaConfiguration import org.jetbrains.dokka.Platform import org.jetbrains.dokka.base.transformers.documentables.InheritorsInfo import org.jetbrains.dokka.links.* import org.jetbrains.dokka.model.* import org.jetbrains.dokka.model.doc.Param import org.jetbrains.dokka.model.doc.Text import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import utils.AbstractModelTest import utils.assertNotNull import utils.name import kotlin.test.assertEquals import org.jetbrains.dokka.links.Callable as DRICallable class JavaTest : AbstractModelTest("/src/main/kotlin/java/Test.java", "java") { val configuration = dokkaConfiguration { sourceSets { sourceSet { sourceRoots = listOf("src/") analysisPlatform = Platform.jvm.toString() classpath += jvmStdlibPath!! documentedVisibilities = setOf( DokkaConfiguration.Visibility.PUBLIC, DokkaConfiguration.Visibility.PRIVATE, DokkaConfiguration.Visibility.PROTECTED, DokkaConfiguration.Visibility.PACKAGE, ) } } } @Test fun function() { inlineModelTest( """ |class Test { | /** | * Summary for Function | * @param name is String parameter | * @param value is int parameter | */ | public void fn(String name, int value) {} |} """, configuration = configuration ) { with((this / "java" / "Test").cast<DClass>()) { name equals "Test" children counts 1 with((this / "fn").cast<DFunction>()) { name equals "fn" val params = parameters.map { it.documentation.values.first().children.first() as Param } params.map { it.firstMemberOfType<Text>().body } equals listOf( "is String parameter", "is int parameter" ) } } } } @Test fun allImplementedInterfacesInJava() { inlineModelTest( """ |interface Highest { } |interface Lower extends Highest { } |class Extendable { } |class Tested extends Extendable implements Lower { } """, configuration = configuration){ with((this / "java" / "Tested").cast<DClass>()){ extra[ImplementedInterfaces]?.interfaces?.entries?.single()?.value?.map { it.dri.sureClassNames }?.sorted() equals listOf("Highest", "Lower").sorted() } } } @Test fun multipleClassInheritanceWithInterface() { inlineModelTest( """ |interface Highest { } |interface Lower extends Highest { } |class Extendable { } |class Tested extends Extendable implements Lower { } """, configuration = configuration){ with((this / "java" / "Tested").cast<DClass>()) { supertypes.entries.single().value.map { it.typeConstructor.dri.sureClassNames to it.kind }.sortedBy { it.first } equals listOf("Extendable" to JavaClassKindTypes.CLASS, "Lower" to JavaClassKindTypes.INTERFACE) } } } @Test fun superClass() { inlineModelTest( """ |public class Foo extends Exception implements Cloneable {} """, configuration = configuration ) { with((this / "java" / "Foo").cast<DClass>()) { val sups = listOf("Exception", "Cloneable") assertTrue( sups.all { s -> supertypes.values.flatten().any { it.typeConstructor.dri.classNames == s } }) "Foo must extend ${sups.joinToString(", ")}" } } } @Test fun arrayType() { inlineModelTest( """ |class Test { | public String[] arrayToString(int[] data) { | return null; | } |} """, configuration = configuration ) { with((this / "java" / "Test").cast<DClass>()) { name equals "Test" children counts 1 with((this / "arrayToString").cast<DFunction>()) { name equals "arrayToString" type.name equals "Array" with(parameters.firstOrNull().assertNotNull("parameters")) { name equals "data" type.name equals "Array" } } } } } @Test fun typeParameter() { inlineModelTest( """ |class Foo<T extends Comparable<T>> { | public <E> E foo(); |} """, configuration = configuration ) { with((this / "java" / "Foo").cast<DClass>()) { generics counts 1 generics[0].dri.classNames equals "Foo" (functions[0].type as? TypeParameter)?.dri?.run { packageName equals "java" name equals "Foo" callable?.name equals "foo" } } } } @Test fun typeParameterIntoDifferentClasses2596() { inlineModelTest( """ |class GenericDocument { } |public interface DocumentClassFactory<T> { | String getSchemaName(); | GenericDocument toGenericDocument(T document); | T fromGenericDocument(GenericDocument genericDoc); |} | |public final class DocumentClassFactoryRegistry { | public <T> DocumentClassFactory<T> getOrCreateFactory(T documentClass) { | return null; | } |} """, configuration = configuration ) { with((this / "java" / "DocumentClassFactory").cast<DInterface>()) { generics counts 1 generics[0].dri.classNames equals "DocumentClassFactory" } with((this / "java" / "DocumentClassFactoryRegistry").cast<DClass>()) { functions.forEach { (it.type as GenericTypeConstructor).dri.classNames equals "DocumentClassFactory" ((it.type as GenericTypeConstructor).projections[0] as TypeParameter).dri.classNames equals "DocumentClassFactoryRegistry" } } } } @Test fun constructors() { inlineModelTest( """ |class Test { | public Test() {} | | public Test(String s) {} |} """, configuration = configuration ) { with((this / "java" / "Test").cast<DClass>()) { name equals "Test" constructors counts 2 constructors.forEach { it.name equals "Test" } constructors.find { it.parameters.isEmpty() }.assertNotNull("Test()") with(constructors.find { it.parameters.isNotEmpty() }.assertNotNull("Test(String)")) { parameters.firstOrNull()?.type?.name equals "String" } } } } @Test fun innerClass() { inlineModelTest( """ |class InnerClass { | public class D {} |} """, configuration = configuration ) { with((this / "java" / "InnerClass").cast<DClass>()) { children counts 1 with((this / "D").cast<DClass>()) { name equals "D" children counts 0 } } } } @Test fun varargs() { inlineModelTest( """ |class Foo { | public void bar(String... x); |} """, configuration = configuration ) { with((this / "java" / "Foo").cast<DClass>()) { name equals "Foo" children counts 1 with((this / "bar").cast<DFunction>()) { name equals "bar" with(parameters.firstOrNull().assertNotNull("parameter")) { name equals "x" type.name equals "Array" } } } } } @Test fun fields() { inlineModelTest( """ |class Test { | public int i; | public static final String s; |} """, configuration = configuration ) { with((this / "java" / "Test").cast<DClass>()) { children counts 2 with((this / "i").cast<DProperty>()) { getter equals null setter equals null } with((this / "s").cast<DProperty>()) { getter equals null setter equals null } } } } @Test fun staticMethod() { inlineModelTest( """ |class C { | public static void foo() {} |} """, configuration = configuration ) { with((this / "java" / "C" / "foo").cast<DFunction>()) { with(extra[AdditionalModifiers]!!.content.entries.single().value.assertNotNull("AdditionalModifiers")) { this counts 1 first() equals ExtraModifiers.JavaOnlyModifiers.Static } } } } @Test fun throwsList() { inlineModelTest( """ |class C { | public void foo() throws java.io.IOException, ArithmeticException {} |} """, configuration = configuration ) { with((this / "java" / "C" / "foo").cast<DFunction>()) { with(extra[CheckedExceptions]?.exceptions?.entries?.single()?.value.assertNotNull("CheckedExceptions")) { this counts 2 first().packageName equals "java.io" first().classNames equals "IOException" get(1).packageName equals "java.lang" get(1).classNames equals "ArithmeticException" } } } } @Test fun annotatedAnnotation() { inlineModelTest( """ |import java.lang.annotation.*; | |@Target({ElementType.FIELD, ElementType.TYPE, ElementType.METHOD}) |public @interface Attribute { | String value() default ""; |} """, configuration = configuration ) { with((this / "java" / "Attribute").cast<DAnnotation>()) { with(extra[Annotations]!!.directAnnotations.entries.single().value.assertNotNull("Annotations")) { with(single()) { dri.classNames equals "Target" (params["value"].assertNotNull("value") as ArrayValue).value equals listOf( EnumValue("ElementType.FIELD", DRI("java.lang.annotation", "ElementType")), EnumValue("ElementType.TYPE", DRI("java.lang.annotation", "ElementType")), EnumValue("ElementType.METHOD", DRI("java.lang.annotation", "ElementType")) ) } } } } } @Test fun javaLangObject() { inlineModelTest( """ |class Test { | public Object fn() { return null; } |} """, configuration = configuration ) { with((this / "java" / "Test" / "fn").cast<DFunction>()) { assertTrue(type is JavaObject) } } } @Test fun enumValues() { inlineModelTest( """ |enum E { | Foo |} """, configuration = configuration ) { with((this / "java" / "E").cast<DEnum>()) { name equals "E" entries counts 1 with((this / "Foo").cast<DEnumEntry>()) { name equals "Foo" } } } } @Test fun inheritorLinks() { inlineModelTest( """ |public class InheritorLinks { | public static class Foo {} | | public static class Bar extends Foo {} |} """, configuration = configuration ) { with((this / "java" / "InheritorLinks").cast<DClass>()) { val dri = (this / "Bar").assertNotNull("Foo dri").dri with((this / "Foo").cast<DClass>()) { with(extra[InheritorsInfo].assertNotNull("InheritorsInfo")) { with(value.values.flatten().distinct()) { this counts 1 first() equals dri } } } } } } @Test fun `retention should work with static import`() { inlineModelTest( """ |import java.lang.annotation.Retention; |import java.lang.annotation.RetentionPolicy; |import static java.lang.annotation.RetentionPolicy.RUNTIME; | |@Retention(RUNTIME) |public @interface JsonClass { |}; """, configuration = configuration ) { with((this / "java" / "JsonClass").cast<DAnnotation>()) { val annotation = extra[Annotations]?.directAnnotations?.entries ?.firstOrNull()?.value //First sourceset ?.firstOrNull() val expectedDri = DRI("java.lang.annotation", "Retention", null, PointingToDeclaration) val expectedParams = "value" to EnumValue( "RUNTIME", DRI( "java.lang.annotation", "RetentionPolicy.RUNTIME", null, PointingToDeclaration, DRIExtraContainer().also { it[EnumEntryDRIExtra] = EnumEntryDRIExtra }.encode() ) ) assertEquals(expectedDri, annotation?.dri) assertEquals(expectedParams.first, annotation?.params?.entries?.first()?.key) assertEquals(expectedParams.second, annotation?.params?.entries?.first()?.value) } } } }
plugins/base/src/test/kotlin/model/JavaTest.kt
1763674164
package com.artfable.telegram.api.request import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.core.type.TypeReference import com.artfable.telegram.api.TelegramBotMethod import com.artfable.telegram.api.TelegramResponse /** * @author aveselov * @since 06/08/2020 */ data class DeleteMessageRequest( @JsonProperty("chat_id") val chatId: Long, @JsonProperty("message_id") val messageId: Long ) : TelegramRequest<Boolean>(TelegramBotMethod.DELETE_MESSAGE, object : TypeReference<TelegramResponse<Boolean>>() {})
src/main/kotlin/com/artfable/telegram/api/request/DeleteMessageRequest.kt
4030631235
package ru.icarumbas.bagel.view.screens import com.badlogic.gdx.ScreenAdapter import com.badlogic.gdx.graphics.g2d.Animation import com.badlogic.gdx.graphics.g2d.Animation.PlayMode import com.badlogic.gdx.graphics.g2d.TextureAtlas import com.badlogic.gdx.math.Interpolation import com.badlogic.gdx.scenes.scene2d.Stage import com.badlogic.gdx.scenes.scene2d.ui.Image import com.badlogic.gdx.utils.viewport.ExtendViewport import ru.icarumbas.Bagel import ru.icarumbas.bagel.engine.resources.ResourceManager import ru.icarumbas.bagel.view.ui.actors.LoadingBar class LoadingScreen( private val assets: ResourceManager, private val game: Bagel ) : ScreenAdapter() { private val WIDTH = 800f private val HEIGHT = 480f private val loadingPack = TextureAtlas("Packs/LoadingScreen.pack") private val stage = Stage(ExtendViewport(WIDTH, HEIGHT)) private val screenBg = Image(loadingPack.findRegion("screen-bg")).apply { setSize(WIDTH, HEIGHT) } private val logo = Image(loadingPack.findRegion("IcaIcon")).apply { x = (WIDTH - width) / 2 y = (HEIGHT - height) / 2 + 100 } private val loadingFrame = Image(loadingPack.findRegion("loading-frame")).apply { x = (WIDTH - width) / 2 y = (HEIGHT - height) / 2 } private val loadingBar = LoadingBar( Animation(0.05f, loadingPack.findRegions("loading-bar-anim"), PlayMode.LOOP_REVERSED)).apply { x = loadingFrame.x + 15 y = loadingFrame.y + 5 } private val loadingBarHidden = Image( loadingPack.findRegion("loading-bar-hidden")).apply { x = loadingBar.x + 35 y = loadingBar.y - 3 } /* The rest of the hidden bar */ private val loadingBg = Image(loadingPack.findRegion("loading-frame-bg")).apply { setSize(450f, 50f) x = loadingBarHidden.x + 30 y = loadingBarHidden.y + 3 invalidate() } /* The start position and how far to move the hidden loading bar */ private var startX = loadingBarHidden.x private var endX = 440f private var percent = 0f init { assets.loadAssets() with (stage) { addActor(screenBg) addActor(loadingBar) addActor(loadingBg) addActor(loadingBarHidden) addActor(loadingFrame) addActor(logo) } } override fun render(delta: Float) { if (assets.assetManager.update()) { game.screen = MainMenuScreen(game) } // Interpolate the percentage to make it more smooth percent = Interpolation.linear.apply(percent, assets.assetManager.progress, 0.1f) loadingBarHidden.x = startX + endX * percent loadingBg.x = loadingBarHidden.x + 30 loadingBg.width = 450 - 450 * percent stage.draw() stage.act() } override fun resize(width: Int, height: Int) { stage.viewport.update(width , height, false) } override fun dispose() { stage.dispose() loadingPack.dispose() } }
core/src/ru/icarumbas/bagel/view/screens/LoadingScreen.kt
4145058913
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("ProjectUtil") package com.intellij.openapi.project import com.intellij.ide.DataManager import com.intellij.ide.highlighter.ProjectFileType import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.appSystemDir import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.fileEditor.UniqueVFilePathBuilder import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.module.ModifiableModuleModel import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFilePathWrapper import com.intellij.util.PathUtilRt import com.intellij.util.io.exists import com.intellij.util.text.trimMiddle import org.jetbrains.annotations.TestOnly import java.nio.file.InvalidPathException import java.nio.file.Path import java.nio.file.Paths import java.util.* import java.util.function.Consumer import javax.swing.JComponent val Module.rootManager: ModuleRootManager get() = ModuleRootManager.getInstance(this) @JvmOverloads fun calcRelativeToProjectPath(file: VirtualFile, project: Project?, includeFilePath: Boolean = true, includeUniqueFilePath: Boolean = false, keepModuleAlwaysOnTheLeft: Boolean = false): String { if (file is VirtualFilePathWrapper && file.enforcePresentableName()) { return if (includeFilePath) file.presentablePath else file.name } val url = if (includeFilePath) { file.presentableUrl } else if (includeUniqueFilePath) { UniqueVFilePathBuilder.getInstance().getUniqueVirtualFilePath(project, file) } else { file.name } if (project == null) { return url } return displayUrlRelativeToProject(file, url, project, includeFilePath, keepModuleAlwaysOnTheLeft) } fun guessProjectForFile(file: VirtualFile?): Project? = ProjectLocator.getInstance().guessProjectForFile(file) /*** * guessProjectForFile works incorrectly - even if file is config (idea config file) first opened project will be returned */ @JvmOverloads fun guessProjectForContentFile(file: VirtualFile, fileType: FileType = file.fileType): Project? { if (ProjectCoreUtil.isProjectOrWorkspaceFile(file, fileType)) { return null } return ProjectManager.getInstance().openProjects.firstOrNull { !it.isDefault && it.isInitialized && !it.isDisposed && ProjectRootManager.getInstance(it).fileIndex.isInContent(file) } } fun isProjectOrWorkspaceFile(file: VirtualFile): Boolean { // do not use file.getFileType() to avoid autodetection by content loading for arbitrary files return ProjectCoreUtil.isProjectOrWorkspaceFile(file, FileTypeManager.getInstance().getFileTypeByFileName(file.name)) } fun guessCurrentProject(component: JComponent?): Project { var project: Project? = null if (component != null) { project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(component)) } @Suppress("DEPRECATION") return project ?: ProjectManager.getInstance().openProjects.firstOrNull() ?: CommonDataKeys.PROJECT.getData(DataManager.getInstance().dataContext) ?: ProjectManager.getInstance().defaultProject } inline fun <T> Project.modifyModules(crossinline task: ModifiableModuleModel.() -> T): T { val model = ModuleManager.getInstance(this).modifiableModel val result = model.task() runWriteAction { model.commit() } return result } fun isProjectDirectoryExistsUsingIo(parent: VirtualFile): Boolean { try { return Paths.get(FileUtil.toSystemDependentName(parent.path), Project.DIRECTORY_STORE_FOLDER).exists() } catch (e: InvalidPathException) { return false } } /** * Tries to guess the "main project directory" of the project. * * There is no strict definition of what is a project directory, since a project can contain multiple modules located in different places, * and the `.idea` directory can be located elsewhere (making the popular [Project.getBaseDir] method not applicable to get the "project * directory"). This method should be preferred, although it can't provide perfect accuracy either. * * @throws IllegalStateException if called on the default project, since there is no sense in "project dir" in that case. */ fun Project.guessProjectDir() : VirtualFile { if (isDefault) { throw IllegalStateException("Not applicable for default project") } val modules = ModuleManager.getInstance(this).modules val module = if (modules.size == 1) modules.first() else modules.find { it.name == this.name } module?.rootManager?.contentRoots?.firstOrNull()?.let { return it } return this.baseDir!! } private fun Project.getProjectCacheFileName(forceNameUse: Boolean, hashSeparator: String): String { val presentableUrl = presentableUrl var name = if (forceNameUse || presentableUrl == null) { name } else { // lower case here is used for cosmetic reasons (develar - discussed with jeka - leave it as it was, user projects will not have long names as in our tests) FileUtil.sanitizeFileName(PathUtilRt.getFileName(presentableUrl).toLowerCase(Locale.US).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION), false) } // do not use project.locationHash to avoid prefix for IPR projects (not required in our case because name in any case is prepended). val locationHash = Integer.toHexString((presentableUrl ?: name).hashCode()) // trim to avoid "File name too long" name = name.trimMiddle(Math.min(name.length, 255 - hashSeparator.length - locationHash.length), useEllipsisSymbol = false) return "$name$hashSeparator${locationHash}" } @JvmOverloads fun Project.getProjectCachePath(cacheName: String, forceNameUse: Boolean = false): Path { return getProjectCachePath(appSystemDir.resolve(cacheName), forceNameUse) } fun Project.getExternalConfigurationDir(): Path { return getProjectCachePath("external_build_system") } @set:TestOnly var IS_EXTERNAL_STORAGE_ENABLED = false val isExternalStorageEnabled: Boolean get() = Registry.`is`("store.imported.project.elements.separately", false) || IS_EXTERNAL_STORAGE_ENABLED /** * Use parameters only for migration purposes, once all usages will be migrated, parameters will be removed */ @JvmOverloads fun Project.getProjectCachePath(baseDir: Path, forceNameUse: Boolean = false, hashSeparator: String = "."): Path { return baseDir.resolve(getProjectCacheFileName(forceNameUse, hashSeparator)) } /** * Add one-time projectOpened listener. */ fun Project.runWhenProjectOpened(handler: Runnable) = runWhenProjectOpened(this) { handler.run() } /** * Add one-time first projectOpened listener. */ @JvmOverloads fun runWhenProjectOpened(project: Project? = null, handler: Consumer<Project>) = runWhenProjectOpened(project) { handler.accept(it) } /** * Add one-time projectOpened listener. */ inline fun runWhenProjectOpened(project: Project? = null, crossinline handler: (project: Project) -> Unit) { val connection = (project ?: ApplicationManager.getApplication()).messageBus.connect() connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener { override fun projectOpened(eventProject: Project) { if (project == null || project === eventProject) { connection.disconnect() handler(eventProject) } } }) }
platform/platform-api/src/com/intellij/openapi/project/ProjectUtil.kt
154258874
package me.mrkirby153.KirBot.command.executors.admin import me.mrkirby153.KirBot.Bot import me.mrkirby153.KirBot.command.CommandException import me.mrkirby153.KirBot.command.annotations.AdminCommand import me.mrkirby153.KirBot.command.annotations.Command import me.mrkirby153.KirBot.command.annotations.CommandDescription import me.mrkirby153.KirBot.command.args.CommandContext import me.mrkirby153.KirBot.module.ModuleManager import me.mrkirby153.KirBot.modules.Database import me.mrkirby153.KirBot.utils.Context import me.mrkirby153.KirBot.utils.checkPermissions import me.mrkirby153.kcutils.Time import me.mrkirby153.kcutils.use import me.mrkirby153.kcutils.utils.TableBuilder import net.dv8tion.jda.api.MessageBuilder import net.dv8tion.jda.api.Permission import java.sql.SQLException import java.util.concurrent.CompletableFuture import java.util.function.Supplier class CommandSQL { @Command(name = "sql", arguments = ["<query:string...>"]) @AdminCommand @CommandDescription("Execute raw SQL against the database") fun execute(context: Context, cmdContext: CommandContext) { val query = cmdContext.get<String>("query") ?: throw CommandException( "Please specify a query") context.addReaction("\uD83D\uDD04").queue() val future = CompletableFuture.supplyAsync(Supplier { ModuleManager[Database::class].database.getConnection().use { con -> con.createStatement().use { statement -> try { val start_time = System.currentTimeMillis() val r = statement.execute(query) val end_time = System.currentTimeMillis() if (r) { val rs = statement.resultSet val meta = rs.metaData val columns = (1..meta.columnCount).map { meta.getColumnLabel(it) } val builder = TableBuilder(columns.toTypedArray()) while (rs.next()) { val data = mutableListOf<String?>() columns.forEach { data.add(rs.getString(it)) } builder.addRow(data.toTypedArray()) } val table = builder.buildTable() if (table.length > 1900) { if (context.channel.checkPermissions( Permission.MESSAGE_ATTACH_FILES)) { context.channel.sendMessage( MessageBuilder("_Took ${Time.format(1, end_time - start_time)}_").build()).addFile( table.toByteArray(), "query.txt").queue() } else { context.send().error( "Query is too long and files cannot be uploaded!").queue() } } else { context.channel.sendMessage("```$table```_Took ${Time.format(1, end_time - start_time)}_").queue() } } else { context.channel.sendMessage( ":ballot_box_with_check: ${statement.updateCount} row(s) updated").queue() } } catch (ex: SQLException) { context.channel.sendMessage(":x: Error: ```${ex.message}```").queue() } } } }, Bot.scheduler) future.whenComplete { _, throwable -> if (throwable != null) { context.send().error("An error occurred: ${throwable.localizedMessage}") } } } }
src/main/kotlin/me/mrkirby153/KirBot/command/executors/admin/CommandSQL.kt
2067212110
package com.krenvpravo.sampleappcompat.otherscreens import android.support.v4.app.DialogFragment import android.view.View import com.viewbinder.BindingResetter import com.viewbinder.ResettableLazy import com.viewbinder.support.abstractBind /** * DialogFragment is a Fragment * * @author Dmitry Borodin on 2017-10-22. * */ open class BaseDialogFragment : DialogFragment() { private val resetter = BindingResetter() fun <T : View> bindView(id: Int): ResettableLazy<T> = abstractBind(id, resetter) /** * Reset lazy at stop, so next time we'll touch views they will be bound again, because * fragment will recreate it's view hierarchy after restoring from backstack */ override fun onStop() { super.onStop() resetter.reset() } }
sample-appcompat/src/main/java/com/krenvpravo/sampleappcompat/otherscreens/BaseDialogFragment.kt
880540869
package com.charlag.promind.core.context_data import java.util.* /** * Created by charlag on 27/03/2017. */ interface DateProvider { fun currentDate(): Date }
app/src/main/java/com/charlag/promind/core/context_data/DateProvider.kt
2062085837
package org.ozinger.ika.database.models import org.jetbrains.exposed.dao.IntEntity import org.jetbrains.exposed.dao.IntEntityClass import org.jetbrains.exposed.dao.id.EntityID import org.jetbrains.exposed.dao.id.IntIdTable import org.jetbrains.exposed.sql.javatime.datetime object ChannelIntegrations : IntIdTable() { val channel = reference("channel", Channels) val type = varchar("type", 32) val target = varchar("target", 255).uniqueIndex() val extra = varchar("extra", 255) val isAuthorized = bool("is_authorized") val createdAt = datetime("created_at") } class ChannelIntegration(id: EntityID<Int>) : IntEntity(id) { companion object : IntEntityClass<ChannelIntegration>(ChannelIntegrations) var channel by Channel referencedOn ChannelIntegrations.channel var type by ChannelFlags.type var target by ChannelIntegrations.target var extra by ChannelIntegrations.extra var isAuthorized by ChannelIntegrations.isAuthorized var createdAt by ChannelIntegrations.createdAt }
app/src/main/kotlin/org/ozinger/ika/database/models/ChannelIntegration.kt
2336328197
package io.gitlab.arturbosch.detekt.rules import io.gitlab.arturbosch.detekt.api.Finding fun <T> SubRule<T>.verify(param: T, findings: (List<Finding>) -> Unit) { this.apply(param) findings.invoke(this.findings) }
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/SubRuleExtensions.kt
3993460993
/* * Copyright (C) 2019. OpenLattice, Inc. * * 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/>. * * You can contact the owner of the copyright at [email protected] * * */ package com.openlattice.hazelcast.serializers import com.geekbeast.rhizome.hazelcast.AbstractDelegatedIntListStreamSerializer import com.geekbeast.rhizome.hazelcast.DelegatedIntList import com.openlattice.hazelcast.InternalTestDataFactory import com.openlattice.hazelcast.StreamSerializerTypeIds import org.springframework.stereotype.Component @Component class DelegatedIntListStreamSerializer : AbstractDelegatedIntListStreamSerializer() { override fun generateTestValue(): DelegatedIntList { return InternalTestDataFactory.delegatedIntList() } override fun getTypeId(): Int { return StreamSerializerTypeIds.INT_LIST.ordinal } }
src/main/kotlin/com/openlattice/hazelcast/serializers/DelegatedIntListStreamSerializer.kt
2317475139
/* * Copyright 2016, Moshe Waisberg * * 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.github.duplicates.call import android.content.Context import com.github.duplicates.DuplicateFindTask import com.github.duplicates.DuplicateFindTaskListener import com.github.duplicates.DuplicateItemType /** * Task to find duplicate calls. * * @author moshe.w */ class CallLogFindTask<L : DuplicateFindTaskListener<CallLogItem, CallLogViewHolder>>( context: Context, listener: L ) : DuplicateFindTask<CallLogItem, CallLogViewHolder, L>( DuplicateItemType.CALL_LOG, context, listener ) { override fun createProvider(context: Context): CallLogProvider { return CallLogProvider(context) } override fun createAdapter(): CallLogAdapter { return CallLogAdapter() } override fun createComparator(): CallLogComparator { return CallLogComparator() } }
duplicates-android/app/src/main/java/com/github/duplicates/call/CallLogFindTask.kt
2284939147
/* * Copyright 2016, Moshe Waisberg * * 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.github.duplicates.contact import android.graphics.Bitmap import android.graphics.BitmapFactory import android.provider.ContactsContract.CommonDataKinds.Photo import android.text.TextUtils import android.util.Base64 /** * Contact photograph data. * * @author moshe.w */ class PhotoData : ContactData() { private var _photo: Bitmap? = null val photo: Bitmap? get() { if (_photo == null) { val data15 = data15 if (!TextUtils.isEmpty(data15)) { val blob = Base64.decode(data15, Base64.DEFAULT) if (blob != null) { _photo = BitmapFactory.decodeByteArray(blob, 0, blob.size) } } } return _photo } val photoFileId: Long get() = data14?.toLong() ?: 0L override var data15: String? get() = super.data15 set(data15) { super.data15 = data15 _photo = null } override val isEmpty: Boolean get() = data15 == null init { mimeType = Photo.CONTENT_ITEM_TYPE } override fun toString(): String { return data15 ?: super.toString() } override fun containsAny(s: CharSequence, ignoreCase: Boolean): Boolean { return false } }
duplicates-android/app/src/main/java/com/github/duplicates/contact/PhotoData.kt
40728392
package com.jara.kotlin_myshare.interfaces import android.view.View /** * RecyclerView点击事件接口 * Created by jara on 2017/9/17. */ interface IMyItemclickListener { fun onItemClick(view: View, position: Int) }
kotlin_myshare/src/main/java/com/jara/kotlin_myshare/interfaces/IMyItemclickListener.kt
2976447224
package org.ooverkommelig.examples.ooverkommelig.lifecycle import java.util.concurrent.CountDownLatch class BackgroundTask : Runnable { @Volatile private var mustStop = false private val hasStoppedLatch = CountDownLatch(1) override fun run() { try { while (!mustStop) { println("Doing background tasks: ${System.currentTimeMillis()}") Thread.sleep(500) } } finally { hasStoppedLatch.countDown() } } fun stop() { mustStop = true hasStoppedLatch.await() } }
examples/src/main/kotlin/org/ooverkommelig/examples/ooverkommelig/lifecycle/BackgroundTask.kt
758779440
package guide.howto.use_html_forms import org.http4k.core.Body import org.http4k.core.ContentType import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.with import org.http4k.lens.FormField import org.http4k.lens.Header import org.http4k.lens.LensFailure import org.http4k.lens.Validator import org.http4k.lens.WebForm import org.http4k.lens.int import org.http4k.lens.webForm data class Name(val value: String) fun main() { // define fields using the standard lens syntax val ageField = FormField.int().required("age") val nameField = FormField.map(::Name, Name::value).optional("name") // add fields to a form definition, along with a validator val strictFormBody = Body.webForm(Validator.Strict, nameField, ageField).toLens() val feedbackFormBody = Body.webForm(Validator.Feedback, nameField, ageField).toLens() val invalidRequest = Request(GET, "/") .with(Header.CONTENT_TYPE of ContentType.APPLICATION_FORM_URLENCODED) // the "strict" form rejects (throws a LensFailure) because "age" is required try { strictFormBody(invalidRequest) } catch (e: LensFailure) { println(e.message) } // the "feedback" form doesn't throw, but collects errors to be reported later val invalidForm = feedbackFormBody(invalidRequest) println(invalidForm.errors) // creating valid form using "with()" and setting it onto the request val webForm = WebForm().with(ageField of 55, nameField of Name("rita")) val validRequest = Request(GET, "/").with(strictFormBody of webForm) // to extract the contents, we first extract the form and then extract the fields from it // using the lenses val validForm = strictFormBody(validRequest) val age = ageField(validForm) println(age) }
src/docs/guide/howto/use_html_forms/example_lens.kt
3081671345
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.digitalwellbeingexperiments.toolkit.applist import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.digitalwellbeingexperiments.toolkit.applist", appContext.packageName) } }
appInteraction/app-list/app/src/androidTest/java/com/digitalwellbeingexperiments/toolkit/applist/ExampleInstrumentedTest.kt
4080949155
package com.muhron.kotlinq import org.junit.Assert import org.junit.Test import java.util.* class SingleTest { @Test fun test0() { val result = sequenceOf(1).single() Assert.assertEquals(result, 1) } @Test(expected = IllegalArgumentException::class) fun test1() { sequenceOf(1, 2).single() } @Test(expected = NoSuchElementException::class) fun test2() { emptySequence<Int>().single() } @Test fun test3() { val result = sequenceOf(1).single { it > 0 } Assert.assertEquals(result, 1) } @Test fun test4() { val result = sequenceOf(-1, 0, 1).single { it > 0 } Assert.assertEquals(result, 1) } @Test(expected = IllegalArgumentException::class) fun test5() { sequenceOf(1, 2).single { it > 0 } } @Test(expected = NoSuchElementException::class) fun test6() { emptySequence<Int>().single { it > 0 } } }
src/test/kotlin/com/muhron/kotlinq/SingleTest.kt
2837905597
package org.abhijitsarkar.service import com.github.benmanes.caffeine.cache.Cache import io.kotlintest.properties.forAll import io.kotlintest.properties.headers import io.kotlintest.properties.row import io.kotlintest.properties.table import io.kotlintest.specs.ShouldSpec import org.mockito.Mockito.`when` import org.mockito.Mockito.anyBoolean import org.mockito.Mockito.eq import org.mockito.Mockito.mock import org.mockito.Mockito.never import org.mockito.Mockito.times import org.mockito.Mockito.verify import reactor.test.StepVerifier import java.time.Duration /** * @author Abhijit Sarkar */ class LinkVerifierTest : ShouldSpec() { init { should("verify if link is valid") { val myTable = table( headers("link", "valid"), row("http://www.slf4j.org/license.html", true), row("http://www.apache.org/licenses/LICENSE-2.0.txt", true), row("https://glassfish.dev.java.net/nonav/public/CDDL+GPL.html", true), row("http://doesnotexist.blah.com", false), row("http://www.opensource.org/licenses/cddl1.php", true), row("", false) ) val linkVerifier = LinkVerifierImpl.newInstance() forAll(myTable) { link, valid -> StepVerifier.create(linkVerifier.isValid(link)) .expectNext(valid) .expectComplete() .verify(Duration.ofSeconds(3L)) } } should("not make remote call if in cache") { val path = "www.apache.org/licenses/LICENSE-2.0.txt" @Suppress("UNCHECKED_CAST") val cache: Cache<String, Boolean> = mock(Cache::class.java) as Cache<String, Boolean> `when`(cache.getIfPresent(path)) .thenReturn(null, true) val myTable = table( headers("link", "valid"), row("http://$path", true), row("https://$path", true) ) val linkVerifier = LinkVerifierImpl.newInstance(cache = cache) forAll(myTable) { link, valid -> StepVerifier.create(linkVerifier.isValid(link)) .expectNext(valid) .expectComplete() .verify(Duration.ofSeconds(3L)) } verify(cache, times(2)).getIfPresent(path) verify(cache).put(path, true) } should("not cache failed response") { val path = "doesnotexist.blah.com" @Suppress("UNCHECKED_CAST") val cache: Cache<String, Boolean> = mock(Cache::class.java) as Cache<String, Boolean> val linkVerifier = LinkVerifierImpl.newInstance(cache = cache) for (i in 1..2) { StepVerifier.create(linkVerifier.isValid("http://$path")) .expectNext(false) .expectComplete() .verify(Duration.ofSeconds(3L)) } verify(cache, times(2)).getIfPresent("$path") verify(cache, never()).put(eq("$path"), anyBoolean()) } } }
license-report-kotlin/src/test/kotlin/org/abhijitsarkar/service/LinkVerifierTest.kt
3934576447
package net.moltendorf.bukkit.intellidoors.settings import net.moltendorf.bukkit.intellidoors.* private const val SETTINGS_VERSION = 5 fun upgradeSettings(settings : GlobalSettings) { if (settings.version < SETTINGS_VERSION) { var versions = 0 for (i in settings.version + 1 .. SETTINGS_VERSION) { upgrade[i]?.invoke(settings) ?: continue ++versions } settings.version = SETTINGS_VERSION if (versions > 0) { w { "Your config is $versions version${if (versions > 1) "s" else ""} out of date. New values have been inferred." } w { "It is recommended to back up your config and delete it so the latest can be generated." } } } } val upgrade = mapOf( Pair(5, fun(settings : GlobalSettings) { val ironTrapdoor = settings["iron-trapdoor"] ?: return // The settings loader needs refactoring badly so we'll just hack this in. ironTrapdoor.pair.interact = ironTrapdoor.single.interact }) )
src/main/kotlin/net/moltendorf/bukkit/intellidoors/settings/SettingsUpgrade.kt
3562822725
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.ktfmt.format import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class WhitespaceTombstonesTest { @Test fun testReplaceTrailingWhitespaceWithTombstone() { assertThat(WhitespaceTombstones.replaceTrailingWhitespaceWithTombstone("")).isEqualTo("") assertThat(WhitespaceTombstones.replaceTrailingWhitespaceWithTombstone(" sdfl")) .isEqualTo(" sdfl") assertThat(WhitespaceTombstones.replaceTrailingWhitespaceWithTombstone(" sdfl ")) .isEqualTo(" sdfl${WhitespaceTombstones.SPACE_TOMBSTONE}") assertThat(WhitespaceTombstones.replaceTrailingWhitespaceWithTombstone(" sdfl ")) .isEqualTo(" sdfl ${WhitespaceTombstones.SPACE_TOMBSTONE}") assertThat(WhitespaceTombstones.replaceTrailingWhitespaceWithTombstone(" sdfl \n skdjfh")) .isEqualTo(" sdfl ${WhitespaceTombstones.SPACE_TOMBSTONE}\n skdjfh") assertThat(WhitespaceTombstones.replaceTrailingWhitespaceWithTombstone(" sdfl \n skdjfh ")) .isEqualTo( " sdfl ${WhitespaceTombstones.SPACE_TOMBSTONE}\n skdjfh${WhitespaceTombstones.SPACE_TOMBSTONE}") assertThat(WhitespaceTombstones.replaceTrailingWhitespaceWithTombstone(" sdfl \n\n skdjfh ")) .isEqualTo( " sdfl ${WhitespaceTombstones.SPACE_TOMBSTONE}\n\n skdjfh${WhitespaceTombstones.SPACE_TOMBSTONE}") } }
core/src/test/java/com/facebook/ktfmt/format/WhitespaceTombstonesTest.kt
1931407375
package org.droidplanner.android.utils import android.os.Parcel import android.os.Parcelable import com.o3dr.services.android.lib.coordinate.LatLongAlt /** * @author ne0fhyk (Fredia Huya-Kouadio) */ class SpaceTime(latitude: Double, longitude: Double, altitude: Double, var timeInMs: Long) : LatLongAlt(latitude, longitude, altitude) { constructor(space: LatLongAlt, timeInMs: Long): this(space.latitude, space.longitude, space.altitude, timeInMs) constructor(spaceTime: SpaceTime): this(spaceTime.latitude, spaceTime.longitude, spaceTime.altitude, spaceTime.timeInMs) fun set(reference: SpaceTime) { super.set(reference) timeInMs = reference.timeInMs } override fun equals(other: Any?): Boolean{ if (this === other) return true if (other !is SpaceTime) return false if (!super.equals(other)) return false if (timeInMs != other.timeInMs) return false return true } override fun hashCode(): Int{ var result = super.hashCode() result = 31 * result + timeInMs.hashCode() return result } override fun toString(): String{ val superToString = super.toString() return "SpaceTime{$superToString, time=$timeInMs}" } companion object { @JvmStatic val CREATOR = object : Parcelable.Creator<SpaceTime> { override fun createFromParcel(source: Parcel): SpaceTime { return source.readSerializable() as SpaceTime } override fun newArray(size: Int): Array<out SpaceTime?> { return arrayOfNulls(size) } } } }
Android/src/org/droidplanner/android/utils/SpaceTime.kt
3268023892
package com.android.example.paging.pagingwithnetwork.reddit.util import android.arch.lifecycle.LiveData import android.arch.lifecycle.MutableLiveData import android.arch.paging.PagingRequestHelper import com.android.example.paging.pagingwithnetwork.reddit.repository.NetworkState private fun getErrorMessage(report: PagingRequestHelper.StatusReport): String { return PagingRequestHelper.RequestType.values().mapNotNull { report.getErrorFor(it)?.message }.first() } fun PagingRequestHelper.createStatusLiveData(): LiveData<NetworkState> { val liveData = MutableLiveData<NetworkState>() addListener { report -> when { report.hasRunning() -> liveData.postValue(NetworkState.LOADING) report.hasError() -> liveData.postValue( NetworkState.error(getErrorMessage(report))) else -> liveData.postValue(NetworkState.LOADED) } } return liveData }
PagingWithNetworkSample/app/src/main/java/com/android/example/paging/pagingwithnetwork/reddit/util/PagingRequestHelperExt.kt
492667996
package eu.kanade.tachiyomi.ui.library import android.view.ViewGroup import android.view.ViewGroup.LayoutParams.MATCH_PARENT import android.widget.RelativeLayout import eu.davidea.flexibleadapter.FlexibleAdapter import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.util.inflate import kotlinx.android.synthetic.main.fragment_library_category.* import kotlinx.android.synthetic.main.item_catalogue_grid.view.* import java.util.* /** * Adapter storing a list of manga in a certain category. * * @param fragment the fragment containing this adapter. */ class LibraryCategoryAdapter(val fragment: LibraryCategoryFragment) : FlexibleAdapter<LibraryHolder, Manga>() { /** * The list of manga in this category. */ private var mangas: List<Manga>? = null init { setHasStableIds(true) } /** * Sets a list of manga in the adapter. * * @param list the list to set. */ fun setItems(list: List<Manga>) { mItems = list // A copy of manga that it's always unfiltered mangas = ArrayList(list) updateDataSet(null) } /** * Returns the identifier for a manga. * * @param position the position in the adapter. * @return an identifier for the item. */ override fun getItemId(position: Int): Long { return mItems[position].id } /** * Filters the list of manga applying [filterObject] for each element. * * @param param the filter. Not used. */ override fun updateDataSet(param: String?) { mangas?.let { filterItems(it) notifyDataSetChanged() } } /** * Filters a manga depending on a query. * * @param manga the manga to filter. * @param query the query to apply. * @return true if the manga should be included, false otherwise. */ override fun filterObject(manga: Manga, query: String): Boolean = with(manga) { title != null && title.toLowerCase().contains(query) || author != null && author.toLowerCase().contains(query) } /** * Creates a new view holder. * * @param parent the parent view. * @param viewType the type of the holder. * @return a new view holder for a manga. */ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LibraryHolder { val view = parent.inflate(R.layout.item_catalogue_grid) view.image_container.layoutParams = RelativeLayout.LayoutParams(MATCH_PARENT, coverHeight) return LibraryHolder(view, this, fragment) } /** * Binds a holder with a new position. * * @param holder the holder to bind. * @param position the position to bind. */ override fun onBindViewHolder(holder: LibraryHolder, position: Int) { val presenter = (fragment.parentFragment as LibraryFragment).presenter val manga = getItem(position) holder.onSetValues(manga, presenter) //When user scrolls this bind the correct selection status holder.itemView.isActivated = isSelected(position) } /** * Property to return the height for the covers based on the width to keep an aspect ratio. */ val coverHeight: Int get() = fragment.recycler.itemWidth / 3 * 4 }
app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryCategoryAdapter.kt
3868575584
package com.infinum.dbinspector.data.models.local.cursor.output internal data class Row( val position: Int, val fields: List<Field> )
dbinspector/src/main/kotlin/com/infinum/dbinspector/data/models/local/cursor/output/Row.kt
2567878416
package com.infinum.dbinspector.ui.content.view import com.infinum.dbinspector.domain.UseCases import com.infinum.dbinspector.domain.shared.models.Sort import com.infinum.dbinspector.domain.shared.models.Statements import com.infinum.dbinspector.ui.content.shared.ContentViewModel internal class ViewViewModel( openConnection: UseCases.OpenConnection, closeConnection: UseCases.CloseConnection, tableInfo: UseCases.GetTableInfo, view: UseCases.GetView, dropView: UseCases.DropView ) : ContentViewModel( openConnection, closeConnection, tableInfo, view, dropView ) { override fun headerStatement(name: String) = Statements.Pragma.tableInfo(name) override fun schemaStatement(name: String, orderBy: String?, sort: Sort) = Statements.Schema.view(name) override fun dropStatement(name: String) = Statements.Schema.dropView(name) }
dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/content/view/ViewViewModel.kt
46778985
/* * Copyright (c) 2021 David Allison <[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.ichi2.anki.reviewer import android.view.KeyEvent import com.ichi2.anki.cardviewer.Gesture import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.junit.Assert.assertEquals import org.junit.Test import org.mockito.ArgumentMatchers.anyInt import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import kotlin.reflect.KFunction1 import kotlin.reflect.KFunction2 class BindingTest { @Test fun modifierKeys_Are_Loaded() { testModifierKeys("shift", KeyEvent::isShiftPressed, Binding.ModifierKeys::shiftMatches) testModifierKeys("ctrl", KeyEvent::isCtrlPressed, Binding.ModifierKeys::ctrlMatches) testModifierKeys("alt", KeyEvent::isAltPressed, Binding.ModifierKeys::altMatches) } @Test fun unicodeKeyIsLoaded() { val binding = unicodeCharacter('a') assertThat(binding.unicodeCharacter, equalTo('a')) } @Test fun keycodeIsLoaded() { val binding = keyCode(KeyEvent.KEYCODE_A) assertThat(binding.keycode, equalTo(KeyEvent.KEYCODE_A)) } @Test fun testUnicodeToString() { assertEquals(unicodePrefix + "Ä", Binding.unicode('Ä').toString()) assertEquals(unicodePrefix + "Ctrl+Ä", Binding.unicode(Binding.ModifierKeys.ctrl(), 'Ä').toString()) assertEquals(unicodePrefix + "Shift+Ä", Binding.unicode(Binding.ModifierKeys.shift(), 'Ä').toString()) assertEquals(unicodePrefix + "Alt+Ä", Binding.unicode(Binding.ModifierKeys.alt(), 'Ä').toString()) assertEquals(unicodePrefix + "Ctrl+Alt+Shift+Ä", Binding.unicode(allModifierKeys(), 'Ä').toString()) } @Test fun testGestureToString() { assertEquals(gesturePrefix + "TAP_TOP", Binding.gesture(Gesture.TAP_TOP).toString()) } @Test fun testUnknownToString() { // This seems sensible - serialising an unknown will mean that nothing is saved. assertThat(Binding.unknown().toString(), equalTo("")) } private fun testModifierKeys(name: String, event: KFunction1<KeyEvent, Boolean>, getValue: KFunction2<Binding.ModifierKeys, Boolean, Boolean>) { fun testModifierResult(event: KFunction1<KeyEvent, Boolean>, returnedFromMock: Boolean) { val mock = mock<KeyEvent> { on(event) doReturn returnedFromMock } val bindings = Binding.key(mock) for (binding in bindings) { assertThat("Should match when '$name:$returnedFromMock': ", getValue(binding.modifierKeys!!, true), equalTo(returnedFromMock)) assertThat("Should match when '$name:${!returnedFromMock}': ", getValue(binding.modifierKeys!!, false), equalTo(!returnedFromMock)) } } testModifierResult(event, true) testModifierResult(event, false) } companion object { const val gesturePrefix = '\u235D' const val keyPrefix = '\u2328' const val unicodePrefix = '\u2705' fun allModifierKeys() = Binding.ModifierKeys(true, true, true) fun unicodeCharacter(c: Char): Binding { val mock = mock<KeyEvent> { on { getUnicodeChar(anyInt()) } doReturn c.code on { unicodeChar } doReturn c.code } return Binding.key(mock).first { x -> x.unicodeCharacter != null } } fun keyCode(keyCode: Int): Binding { val mock = mock<KeyEvent> { on { getKeyCode() } doReturn keyCode } return Binding.key(mock).first { x -> x.keycode != null } } } }
AnkiDroid/src/test/java/com/ichi2/anki/reviewer/BindingTest.kt
37157167
/** * Copyright (C) 2015 Fernando Cejas 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.social.com.data.repository.fake import com.social.com.data.repository.fake.datasource.tutorial.FeedFakeProvider import com.social.com.domain.model.Feed import com.social.com.domain.repository.FeedRepository import com.social.com.domain.repository.TutorialRepository import io.reactivex.Observable import javax.inject.Inject /** * [TutorialRepository] for retrieving user data. */ class FakeFeedRepository @Inject internal constructor(val feedRepository: FeedFakeProvider) : FeedRepository { init { android.util.Log.d("DAGGER TEST", "" + this::class.java.name) } override fun feed(): Observable<List<Feed>> { return Observable.just(feedRepository.getFeedData()) } }
data/src/main/java/com/social/com/data/repository/fake/FakeFeedRepository.kt
1956180459
package de.troido.bleacon.config.advertise import android.bluetooth.le.AdvertiseData import de.troido.bleacon.ble.NORDIC_ID import de.troido.ekstend.uuid.Uuid16 import de.troido.ekstend.uuid.bytes import java.util.UUID @JvmOverloads fun bleAdData(uuid16: Uuid16? = null, uuid128: UUID? = null, includeTxPowerLevel: Boolean = false, includeDeviceName: Boolean = false, build: AdDataBuilder.() -> Unit = {}): AdvertiseData = AdvertiseData.Builder() .apply { setIncludeTxPowerLevel(includeTxPowerLevel) setIncludeDeviceName(includeDeviceName) AdDataBuilder(this).apply { uuid16?.let { msd[NORDIC_ID] = it.bytes } uuid128?.let { msd[NORDIC_ID] = it.bytes } }.apply(build) } .build()
library/src/main/java/de/troido/bleacon/config/advertise/BleAdData.kt
3187531273
/* * Copyright (c) 2017. Toshi Inc * * 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.toshi.manager.chat.tasks import com.toshi.model.local.Group import org.whispersystems.libsignal.util.Hex import org.whispersystems.signalservice.api.SignalServiceMessageSender import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage import org.whispersystems.signalservice.api.messages.SignalServiceGroup import rx.Completable import rx.Single class CreateGroupTask( private val signalMessageSender: SignalServiceMessageSender ) : BaseGroupTask() { fun run(group: Group): Single<Group> { return Completable.fromAction { val signalGroup = SignalServiceGroup .newBuilder(SignalServiceGroup.Type.UPDATE) .withId(Hex.fromStringCondensed(group.id)) .withName(group.title) .withMembers(group.memberIds) .withAvatar(group.avatar.stream) .build() val groupDataMessage = SignalServiceDataMessage .newBuilder() .withTimestamp(System.currentTimeMillis()) .asGroupMessage(signalGroup) .build() signalMessageSender.sendMessage(group.memberAddresses, groupDataMessage) } .onErrorResumeNext { handleException(it) } .toSingle { group } } }
app/src/main/java/com/toshi/manager/chat/tasks/CreateGroupTask.kt
2560104746
package de.westnordost.streetcomplete.data.elementfilter.filters import de.westnordost.streetcomplete.data.elementfilter.matches import org.junit.Assert.* import org.junit.Test class HasTagGreaterOrEqualThanTest { @Test fun matches() { val c = HasTagGreaterOrEqualThan("width", 3.5f) assertFalse(c.matches(mapOf())) assertFalse(c.matches(mapOf("width" to "broad"))) assertTrue(c.matches(mapOf("width" to "3.6"))) assertTrue(c.matches(mapOf("width" to "3.5"))) assertFalse(c.matches(mapOf("width" to "3.4"))) } @Test fun `to string`() { assertEquals( "[width](if: number(t['width']) >= 3.5)", HasTagGreaterOrEqualThan("width", 3.5f).toOverpassQLString() ) assertEquals( "['wid th'](if: number(t['wid th']) >= 3.5)", HasTagGreaterOrEqualThan("wid th", 3.5f).toOverpassQLString() ) } }
app/src/test/java/de/westnordost/streetcomplete/data/elementfilter/filters/HasTagGreaterOrEqualThanTest.kt
2236017165
/* * Copyright (c) 2017. Toshi Inc * * 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.toshi.view.adapter.viewholder import android.support.v7.widget.RecyclerView import android.view.View import com.toshi.extensions.isVisible import com.toshi.model.local.User import com.toshi.util.ImageUtil import kotlinx.android.synthetic.main.list_item__popular_user.view.avatar import kotlinx.android.synthetic.main.list_item__popular_user.view.description import kotlinx.android.synthetic.main.list_item__popular_user.view.name import kotlinx.android.synthetic.main.list_item__popular_user.view.username class PopularUserViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) { fun setUser(user: User) { itemView.name.text = user.displayName itemView.username.text = user.username setDescription(user) ImageUtil.load(user.avatar, itemView.avatar) } private fun setDescription(user: User) { if (user.about.orEmpty().isEmpty()) itemView.description.isVisible(false) else { itemView.description.isVisible(true) itemView.description.text = user.about } } fun setOnItemClickListener(onItemClickListener: (User) -> Unit, user: User) { itemView.setOnClickListener { onItemClickListener(user) } } }
app/src/main/java/com/toshi/view/adapter/viewholder/PopularUserViewHolder.kt
2401184198
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.process.util import kotlinx.serialization.Serializable import kotlinx.serialization.Serializer import kotlinx.serialization.* import kotlinx.serialization.builtins.serializer import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import nl.adaptivity.serialutil.DelegatingSerializer import nl.adaptivity.serialutil.simpleSerialClassDesc /** * A class representing a simple identifier. It just holds a single string. */ @Serializable(Identifier.Companion::class) class Identifier(override var id: String) : Identified { override val identifier: Identifier get() = this private class ChangeableIdentifier(private val idBase: String) : Identified { private var idNo: Int = 1 override val id: String get() = idBase + idNo.toString() override fun compareTo(other: Identifiable): Int { val otherId = other.id if (otherId == null) return 1 return id.compareTo(otherId) } operator fun next() { ++idNo } } constructor(id: CharSequence) : this(id.toString()) {} override fun compareTo(o: Identifiable): Int { val otherId = o.id ?: return 1 return id.compareTo(otherId) } override fun toString(): String = id override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false other as Identifier if (id != other.id) return false return true } override fun hashCode(): Int { return id.hashCode() } companion object: DelegatingSerializer<Identifier, String>(String.serializer()) { override fun fromDelegate(delegate: String): Identifier = Identifier(delegate) override fun Identifier.toDelegate(): String = id fun findIdentifier(idBase: String, exclusions: Iterable<Identifiable>): String { val idFactory = ChangeableIdentifier(idBase) return generateSequence({ idFactory.id }, { idFactory.next(); idFactory.id }) .filter { candidate -> exclusions.none { candidate == it.id } } .first() } } }
PE-common/src/commonMain/kotlin/nl/adaptivity/process/util/Identifier.kt
2379909266
package com.boardgamegeek.ui.dialog import android.content.Context import android.view.LayoutInflater import android.widget.ArrayAdapter import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModelProvider import com.boardgamegeek.R import com.boardgamegeek.databinding.DialogCollectionFilterRecommendedPlayerCountBinding import com.boardgamegeek.extensions.createThemedBuilder import com.boardgamegeek.filterer.CollectionFilterer import com.boardgamegeek.filterer.RecommendedPlayerCountFilterer import com.boardgamegeek.ui.viewmodel.CollectionViewViewModel class RecommendedPlayerCountFilterDialog : CollectionFilterDialog { private var _binding: DialogCollectionFilterRecommendedPlayerCountBinding? = null private val binding get() = _binding!! private val defaultPlayerCount = 4 override fun createDialog(activity: FragmentActivity, filter: CollectionFilterer?) { val viewModel by lazy { ViewModelProvider(activity)[CollectionViewViewModel::class.java] } _binding = DialogCollectionFilterRecommendedPlayerCountBinding.inflate(LayoutInflater.from(activity), null, false) binding.rangeBar.addOnChangeListener { _, value, _ -> binding.playerCountDisplay.text = value.toInt().toString() } val bestString = activity.getString(R.string.best) val goodString = activity.getString(R.string.good) binding.autocompleteView.setAdapter(ArrayAdapter(activity, R.layout.support_simple_spinner_dropdown_item, listOf(bestString, goodString))) val recommendedPlayerCountFilterer = filter as? RecommendedPlayerCountFilterer when (recommendedPlayerCountFilterer?.recommendation ?: RecommendedPlayerCountFilterer.RECOMMENDED) { RecommendedPlayerCountFilterer.BEST -> binding.autocompleteView.setText(bestString, false) else -> binding.autocompleteView.setText(goodString, false) } val playerCount = recommendedPlayerCountFilterer?.playerCount?.coerceIn(binding.rangeBar.valueFrom.toInt(), binding.rangeBar.valueTo.toInt()) ?: defaultPlayerCount binding.rangeBar.value = playerCount.toFloat() activity.createThemedBuilder() .setTitle(R.string.menu_recommended_player_count) .setPositiveButton(R.string.set) { _, _ -> viewModel.addFilter(RecommendedPlayerCountFilterer(activity).apply { this.playerCount = binding.rangeBar.value.toInt() recommendation = if (binding.autocompleteView.text.toString() == bestString) RecommendedPlayerCountFilterer.BEST else RecommendedPlayerCountFilterer.RECOMMENDED }) } .setNegativeButton(R.string.clear) { _, _ -> viewModel.removeFilter(getType(activity)) } .setView(binding.root) .create() .show() } override fun getType(context: Context) = RecommendedPlayerCountFilterer(context).type }
app/src/main/java/com/boardgamegeek/ui/dialog/RecommendedPlayerCountFilterDialog.kt
2516306848
package io.github.binaryfoo.crypto import io.github.binaryfoo.DecodedData /** * Covers both Issuer and ICC (chip card) cases. */ data class RecoveredPublicKeyCertificate( val owner: String, val detail: List<DecodedData>, val exponentLength: String, val leftKeyPart: String, var rightKeyPart: String? = null) : PublicKeyCertificate { override var exponent: String? = null override val modulus: String get() = leftKeyPart + (rightKeyPart ?: "") override val name: String get() = "$owner public key" }
src/main/java/io/github/binaryfoo/crypto/RecoveredPublicKeyCertificate.kt
2849026064
package org.cobraparser import java.util.logging.Level import java.util.logging.Logger object CobraParser { private val logger = Logger.getLogger(CobraParser::class.java.name) @JvmField var isDebugOn = false @JvmStatic fun setDebug(debug:Boolean) { CobraParser.isDebugOn = debug logger.log(Level.INFO, "Logging has been " + (if (debug) "Enabled" else "Disabled")) } }
src/main/kotlin/org/cobraparser/CobraParser.kt
2046381479
package kotlinx.benchmarks.json import kotlinx.serialization.* import kotlinx.serialization.json.* import kotlinx.serialization.modules.* import org.openjdk.jmh.annotations.* import java.util.concurrent.* @Warmup(iterations = 7, time = 1) @Measurement(iterations = 5, time = 1) @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.MILLISECONDS) @State(Scope.Benchmark) @Fork(1) open class PolymorphismOverheadBenchmark { @Serializable @JsonClassDiscriminator("poly") data class PolymorphicWrapper(val i: @Polymorphic Poly, val i2: Impl) // amortize the cost a bit @Serializable data class SimpleWrapper(val poly: @Polymorphic Poly) @Serializable data class BaseWrapper(val i: Impl, val i2: Impl) @JsonClassDiscriminator("poly") interface Poly @Serializable @JsonClassDiscriminator("poly") class Impl(val a: Int, val b: String) : Poly private val impl = Impl(239, "average_size_string") private val module = SerializersModule { polymorphic(Poly::class) { subclass(Impl.serializer()) } } private val json = Json { serializersModule = module } private val implString = json.encodeToString(impl) private val polyString = json.encodeToString<Poly>(impl) private val serializer = serializer<Poly>() private val wrapper = SimpleWrapper(Impl(1, "abc")) private val wrapperString = json.encodeToString(wrapper) private val wrapperSerializer = serializer<SimpleWrapper>() // 5000 @Benchmark fun base() = json.decodeFromString(Impl.serializer(), implString) // As of 1.3.x // Baseline -- 1500 // v1, no skip -- 2000 // v2, with skip -- 3000 [withdrawn] @Benchmark fun poly() = json.decodeFromString(serializer, polyString) // test for child polymorphic serializer in decoding @Benchmark fun polyChildDecode() = json.decodeFromString(wrapperSerializer, wrapperString) // test for child polymorphic serializer in encoding @Benchmark fun polyChildEncode() = json.encodeToString(wrapperSerializer, wrapper) }
benchmark/src/jmh/kotlin/kotlinx/benchmarks/json/PolymorphismOverheadBenchmark.kt
3529457087
/* * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.hocon import com.typesafe.config.* import kotlinx.serialization.* internal fun SerializerNotFoundException(type: String?) = SerializationException( "Polymorphic serializer was not found for " + if (type == null) "missing class discriminator ('null')" else "class discriminator '$type'" ) internal inline fun <reified T> ConfigValueTypeCastException(valueOrigin: ConfigOrigin) = SerializationException( "${valueOrigin.description()} required to be of type ${T::class.simpleName}." ) internal fun InvalidKeyKindException(value: ConfigValue) = SerializationException( "Value of type '${value.valueType()}' can't be used in HOCON as a key in the map. " + "It should have either primitive or enum kind." )
formats/hocon/src/main/kotlin/kotlinx/serialization/hocon/HoconExceptions.kt
238481861
/* * Copyright 2016 Marco Gomiero * * 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.prof.youtubeparser.models.videos.internal internal data class Thumbnails( val default: Default? = null, val medium: Medium? = null, val high: High? = null )
youtubeparser/src/main/java/com/prof/youtubeparser/models/videos/internal/Thumbnails.kt
313779554
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.topeka.helper import android.annotation.TargetApi import android.app.Activity import android.os.Build import androidx.annotation.IdRes import androidx.core.util.Pair import android.view.View /** * Helper class for creating content transitions used with [android.app.ActivityOptions]. */ object TransitionHelper { /** * Create the transition participants required during a activity transition while * avoiding glitches with the system UI. * @param activity The activity used as start for the transition. * * @param includeStatusBar If false, the status bar will not be added as the transition * participant. * * @return All transition participants. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) fun createSafeTransitionParticipants(activity: Activity, includeStatusBar: Boolean, vararg others: Pair<View, String> ): Array<Pair<View, String>> { // Avoid system UI glitches as described here: // https://plus.google.com/+AlexLockwood/posts/RPtwZ5nNebb return ArrayList<Pair<View, String>>(3).apply { if (includeStatusBar) { addViewById(activity, android.R.id.statusBarBackground, this) } addViewById(activity, android.R.id.navigationBarBackground, this) addAll(others.toList()) }.toTypedArray() } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private fun addViewById(activity: Activity, @IdRes viewId: Int, participants: ArrayList<Pair<View, String>>) { val view = activity.window.decorView.findViewById<View>(viewId) view?.transitionName?.let { participants.add(Pair(view, it)) } } }
base/src/main/java/com/google/samples/apps/topeka/helper/TransitionHelper.kt
1380022522
package pyxis.uzuki.live.richutilskt.demo import android.Manifest import android.content.Context import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.MenuItem import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.activity_index.* import kotlinx.android.synthetic.main.activity_index_item.view.* import pyxis.uzuki.live.richutilskt.demo.item.CategoryItem import pyxis.uzuki.live.richutilskt.demo.item.ExecuteItem import pyxis.uzuki.live.richutilskt.demo.item.MainItem import pyxis.uzuki.live.richutilskt.utils.RPermission import pyxis.uzuki.live.richutilskt.utils.inflate /** * RichUtilsKt * Class: IndexActivity * Created by Pyxis on 2017-11-06. * * Description: */ class IndexActivity : AppCompatActivity() { private val itemList = ArrayList<ExecuteItem>() private val adapter = ListAdapter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_index) val item = intent.getSerializableExtra("index") as MainItem itemList.addAll(getItemList(item.categoryItem)) itemList.sortBy { it.title } recyclerView.layoutManager = LinearLayoutManager(this) recyclerView.adapter = adapter recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (dy > 0 && fab.visibility == View.VISIBLE) { fab.hide() } else if (dy < 0 && fab.visibility != View.VISIBLE) { fab.show() } } }) supportActionBar?.title = "${item.title} :: RichUtils" supportActionBar?.setDefaultDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayHomeAsUpEnabled(true) adapter.notifyDataSetChanged() fab.setOnClickListener { browseToFile(item.link) } val permissionArray = when (item.categoryItem) { CategoryItem.DEVICEID -> arrayOf(Manifest.permission.READ_PHONE_STATE) CategoryItem.PICKMEDIA -> arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA) else -> null } if (permissionArray != null) { RPermission.instance.checkPermission(this, permissionArray) } } inner class ListAdapter : RecyclerView.Adapter<ViewHolder>() { override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bindData(itemList[position]) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(this@IndexActivity, inflate(R.layout.activity_index_item, parent)) } override fun getItemCount(): Int = itemList.size } var extendedPosition = -1 inner class ViewHolder(private val context: Context, itemView: View) : RecyclerView.ViewHolder(itemView) { fun bindData(item: ExecuteItem) { val isShow = extendedPosition == adapterPosition itemView.imgExpand.isSelected = isShow itemView.txtTitle.text = item.title itemView.txtSummary.text = item.message itemView.btnExecute.visibility = if (item.execute == null) View.GONE else View.VISIBLE itemView.btnExecute.setOnClickListener { item.execute?.invoke(context) } if (isShow) { itemView.containerMore.visibility = View.VISIBLE itemView.divider.visibility = View.VISIBLE } else { itemView.containerMore.visibility = View.GONE itemView.divider.visibility = View.GONE } itemView.txtKotlinSample.text = item.kotlinSample itemView.txtJavaSample.text = item.javaSample itemView.containerTitle.setOnClickListener { extendedPosition = if (isShow) -1 else adapterPosition recyclerView.layoutManager.scrollToPosition(extendedPosition) adapter.notifyDataSetChanged() } } } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { onBackPressed() } return super.onOptionsItemSelected(item) } }
demo/src/main/java/pyxis/uzuki/live/richutilskt/demo/IndexActivity.kt
2584710768
// 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 com.intellij.usages import com.intellij.openapi.components.* import com.intellij.util.PathUtil import com.intellij.util.xmlb.annotations.OptionTag import com.intellij.util.xmlb.annotations.Transient /** * Passed params will be used as default values, so, do not use constructor if instance will be used as a state (unless you want to change defaults) */ @State(name = "UsageViewSettings", storages = [Storage("usageView.xml")]) open class UsageViewSettings( isGroupByFileStructure: Boolean = true, isGroupByModule: Boolean = true, isGroupByPackage: Boolean = true, isGroupByUsageType: Boolean = true, isGroupByScope: Boolean = false ) : BaseState(), PersistentStateComponent<UsageViewSettings> { companion object { @JvmStatic val instance: UsageViewSettings get() = ServiceManager.getService(UsageViewSettings::class.java) } @Suppress("unused") @JvmField @Transient @Deprecated(message = "Use isGroupByModule") var GROUP_BY_MODULE: Boolean = isGroupByModule @Suppress("unused") @JvmField @Transient @Deprecated(message = "Use isGroupByUsageType") var GROUP_BY_USAGE_TYPE: Boolean = isGroupByUsageType @Suppress("unused") @JvmField @Transient @Deprecated(message = "Use isGroupByFileStructure") var GROUP_BY_FILE_STRUCTURE: Boolean = isGroupByFileStructure @Suppress("unused") @JvmField @Transient @Deprecated(message = "Use isGroupByScope") var GROUP_BY_SCOPE: Boolean = isGroupByScope @Suppress("unused") @JvmField @Transient @Deprecated(message = "Use isGroupByPackage") var GROUP_BY_PACKAGE: Boolean = isGroupByPackage @Suppress("MemberVisibilityCanPrivate") @get:OptionTag("EXPORT_FILE_NAME") internal var EXPORT_FILE_NAME by property("report.txt") @get:OptionTag("IS_EXPANDED") var isExpanded: Boolean by property(false) @get:OptionTag("IS_AUTOSCROLL_TO_SOURCE") var isAutoScrollToSource: Boolean by property(false) @get:OptionTag("IS_FILTER_DUPLICATED_LINE") var isFilterDuplicatedLine: Boolean by property(true) @get:OptionTag("IS_SHOW_METHODS") var isShowModules: Boolean by property(false) @get:OptionTag("IS_PREVIEW_USAGES") var isPreviewUsages: Boolean by property(false) @get:OptionTag("IS_REPLACE_PREVIEW_USAGES") var isReplacePreviewUsages: Boolean by property(true) @get:OptionTag("IS_SORT_MEMBERS_ALPHABETICALLY") var isSortAlphabetically: Boolean by property(false) @get:OptionTag("PREVIEW_USAGES_SPLITTER_PROPORTIONS") var previewUsagesSplitterProportion: Float by property(0.5f) @get:OptionTag("GROUP_BY_USAGE_TYPE") var isGroupByUsageType: Boolean by property(isGroupByUsageType) @get:OptionTag("GROUP_BY_MODULE") var isGroupByModule: Boolean by property(isGroupByModule) @get:OptionTag("FLATTEN_MODULES") var isFlattenModules: Boolean by property(true) @get:OptionTag("GROUP_BY_PACKAGE") var isGroupByPackage: Boolean by property(isGroupByPackage) @get:OptionTag("GROUP_BY_FILE_STRUCTURE") var isGroupByFileStructure: Boolean by property(isGroupByFileStructure) @get:OptionTag("GROUP_BY_SCOPE") var isGroupByScope: Boolean by property(isGroupByScope) var exportFileName: String? @Transient get() = PathUtil.toSystemDependentName(EXPORT_FILE_NAME) set(value) { EXPORT_FILE_NAME = PathUtil.toSystemIndependentName(value) } override fun getState(): UsageViewSettings = this @Suppress("DEPRECATION") override fun loadState(state: UsageViewSettings) { copyFrom(state) GROUP_BY_MODULE = isGroupByModule GROUP_BY_USAGE_TYPE = isGroupByUsageType GROUP_BY_FILE_STRUCTURE = isGroupByFileStructure GROUP_BY_SCOPE = isGroupByScope GROUP_BY_PACKAGE = isGroupByPackage } }
platform/usageView/src/com/intellij/usages/UsageViewSettings.kt
3393117443
package com.zhufucdev.pctope.adapters import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import android.util.Log import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.Animation import android.view.animation.TranslateAnimation import android.widget.FrameLayout /** * Created by zhufu on 17-10-21. */ abstract class TutorialActivity(LayoutRes : Array<Int>) : AppCompatActivity(){ private val res = LayoutRes var layouts = ArrayList<TutorialLayout>() var showingPosition = 0 var isInAnimations = false lateinit var animationLeftToCenter : Animation lateinit var animationCenterToLeft : Animation lateinit var animationRightToCenter : Animation lateinit var animationCenterToRight : Animation open class TutorialLayout(var view: View) { var parmas = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT, Gravity.START) } override fun onCreate(savedInstanceState: Bundle?) { for (i in res.indices){ layouts.add(TutorialLayout(LayoutInflater.from(this).inflate(res[i],null))) Log.i("Tutorial","Added layout ${res[i]}.") } animationLeftToCenter = TranslateAnimation(-resources.displayMetrics.widthPixels.toFloat(),0f,0f,0f) animationLeftToCenter.duration = 400 animationCenterToLeft = TranslateAnimation(0f,-resources.displayMetrics.widthPixels.toFloat(),0f,0f) animationCenterToLeft.duration = 400 animationRightToCenter = TranslateAnimation(resources.displayMetrics.widthPixels.toFloat(),0f,0f,0f) animationRightToCenter.duration = 400 animationCenterToRight = TranslateAnimation(0f,resources.displayMetrics.widthPixels.toFloat(),0f,0f) animationCenterToRight.duration = 400 super.onCreate(savedInstanceState) onPageSwitched() } fun show(index : Int){ if (layouts.size>index && index>=0){ if (index>showingPosition){ //Next layouts[showingPosition].view.startAnimation(animationCenterToLeft) addContentView(layouts[index].view,layouts[index].parmas) layouts[index].view.startAnimation(animationRightToCenter) animationRightToCenter.setAnimationListener(object : Animation.AnimationListener{ override fun onAnimationRepeat(animation: Animation?) {} override fun onAnimationEnd(animation: Animation?) { (layouts[showingPosition].view.parent as ViewGroup).removeView(layouts[showingPosition].view) animationRightToCenter.setAnimationListener(null) showingPosition++ isInAnimations = false onPageSwitched() } override fun onAnimationStart(animation: Animation?) { isInAnimations = true } }) } else if (index<showingPosition){ //Back layouts[showingPosition].view.startAnimation(animationCenterToRight) addContentView(layouts[index].view,layouts[index].parmas) layouts[index].view.startAnimation(animationLeftToCenter) animationCenterToRight.setAnimationListener(object : Animation.AnimationListener{ override fun onAnimationRepeat(animation: Animation?) {} override fun onAnimationEnd(animation: Animation?) { (layouts[showingPosition].view.parent as ViewGroup).removeView(layouts[showingPosition].view) animationCenterToRight.setAnimationListener(null) showingPosition-- isInAnimations = false onPageSwitched() } override fun onAnimationStart(animation: Animation?) { isInAnimations = true } }) } else if (index==showingPosition){ setContentView(layouts[index].view) } } } fun next(){ show(showingPosition+1) } fun back(){ show(showingPosition-1) } override fun <T : View?> findViewById(id: Int): T = layouts[showingPosition].view.findViewById<T>(id) abstract fun onPageSwitched() }
app/src/main/java/com/zhufucdev/pctope/adapters/TutorialActivity.kt
2743909006
package org.worshipsongs.fragment import android.app.Activity import android.content.Intent import android.content.pm.ActivityInfo import android.graphics.drawable.ColorDrawable import android.os.Build import android.os.Bundle import android.util.Log import android.view.* import android.widget.AdapterView import android.widget.ListView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import com.getbase.floatingactionbutton.FloatingActionButton import com.getbase.floatingactionbutton.FloatingActionsMenu import com.google.android.youtube.player.YouTubePlayer import org.worshipsongs.CommonConstants import org.worshipsongs.R import org.worshipsongs.WorshipSongApplication import org.worshipsongs.activity.CustomYoutubeBoxActivity import org.worshipsongs.adapter.PresentSongCardViewAdapter import org.worshipsongs.domain.Setting import org.worshipsongs.domain.Song import org.worshipsongs.parser.LiveShareSongParser import org.worshipsongs.service.* import org.worshipsongs.utils.CommonUtils import org.worshipsongs.utils.LiveShareUtils import org.worshipsongs.utils.PermissionUtils import java.io.File import java.util.* /** * @author: Madasamy, Vignesh Palanisamy * @since: 1.0.0 */ class SongContentPortraitViewFragment : Fragment(), ISongContentPortraitViewFragment { private var title: String? = "" private var tilteList: ArrayList<String>? = ArrayList() private var millis: Int = 0 private val youTubePlayer: YouTubePlayer? = null private val preferenceSettingService = UserPreferenceSettingService() private val songDao = SongService(WorshipSongApplication.context!!) private val authorService = AuthorService(WorshipSongApplication.context!!) private var popupMenuService: PopupMenuService? = null private var floatingActionMenu: FloatingActionsMenu? = null private var song: Song? = null private var listView: ListView? = null private var presentSongCardViewAdapter: PresentSongCardViewAdapter? = null private var nextButton: FloatingActionButton? = null private var previousButton: FloatingActionButton? = null private var presentSongFloatingButton: FloatingActionButton? = null // @Override // public void onAttach(Context context) // { // super.onAttach(context); // Log.i(SongContentPortraitViewFragment.class.getSimpleName(), "" + context); // if (context instanceof SongContentViewActivity) { // activity = (SongContentViewActivity) context; // } // } var presentationScreenService: PresentationScreenService? = null private val customTagColorService = CustomTagColorService() private val liveShareSongParser = LiveShareSongParser() private val isPresentSong: Boolean get() { return presentationScreenService != null && presentationScreenService!!.presentation != null } private val songBookNumber: String get() { try { if (arguments!!.containsKey(CommonConstants.SONG_BOOK_NUMBER_KEY)) { val songBookNumber = arguments!!.getInt(CommonConstants.SONG_BOOK_NUMBER_KEY, 0) return if (songBookNumber > 0) "$songBookNumber. " else "" } } catch (ex: Exception) { Log.e(SongContentPortraitViewFragment::class.java.simpleName, "Error ", ex) } return "" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(CommonUtils.isPhone(WorshipSongApplication.context!!)) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.song_content_portrait_view, container, false) initSetUp() setListView(view, song!!) setFloatingActionMenu(view, song!!) setNextButton(view) setPreviousButton(view) view.setOnTouchListener(SongContentPortraitViewTouchListener()) onBecameVisible(song) return view } private fun initSetUp() { showStatusBar() val bundle = arguments title = bundle!!.getString(CommonConstants.TITLE_KEY) tilteList = bundle.getStringArrayList(CommonConstants.TITLE_LIST_KEY) if (bundle != null) { millis = bundle.getInt(KEY_VIDEO_TIME) Log.i(this.javaClass.simpleName, "Video time $millis") } setSong() } private fun showStatusBar() { if (CommonUtils.isPhone(context!!)) { if (Build.VERSION.SDK_INT < 16) { activity!!.window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) } else { val decorView = activity!!.window.decorView decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE } } val appCompatActivity = activity as AppCompatActivity? if (appCompatActivity!!.supportActionBar != null) { appCompatActivity.supportActionBar!!.show() appCompatActivity.supportActionBar!!.setDisplayHomeAsUpEnabled(CommonUtils.isPhone(WorshipSongApplication.context!!)) } } private fun setSong() { if (arguments!!.containsKey(CommonConstants.SERVICE_NAME_KEY)) { val serviceName = arguments!!.getString(CommonConstants.SERVICE_NAME_KEY) val serviceFilePath = LiveShareUtils.getServiceDirPath(context!!) + File.separator + serviceName song = liveShareSongParser.parseSong(serviceFilePath, title!!) } else { song = songDao.findContentsByTitle(title!!) if (song == null) { song = Song(title!!) val contents = ArrayList<String>() contents.add(getString(R.string.message_song_not_available, "\"" + title + "\"")) song!!.contents = contents } song!!.authorName = authorService.findAuthorNameByTitle(title!!) } } private fun setListView(view: View, song: Song) { listView = view.findViewById<View>(R.id.content_list) as ListView presentSongCardViewAdapter = PresentSongCardViewAdapter(activity!!, song.contents!!) listView!!.adapter = presentSongCardViewAdapter listView!!.onItemClickListener = ListViewOnItemClickListener() listView!!.onItemLongClickListener = ListViewOnItemLongClickListener() } private fun setFloatingActionMenu(view: View, song: Song) { floatingActionMenu = view.findViewById<View>(R.id.floating_action_menu) as FloatingActionsMenu if (isPlayVideo(song.urlKey) && isPresentSong) { floatingActionMenu!!.visibility = View.VISIBLE floatingActionMenu!!.setOnFloatingActionsMenuUpdateListener(object : FloatingActionsMenu.OnFloatingActionsMenuUpdateListener { override fun onMenuExpanded() { val color = R.color.gray_transparent setListViewForegroundColor(ContextCompat.getColor(activity!!, color)) } override fun onMenuCollapsed() { val color = 0x00000000 setListViewForegroundColor(color) } }) setPlaySongFloatingMenuButton(view, song.urlKey!!) setPresentSongFloatingMenuButton(view) } else { floatingActionMenu!!.visibility = View.GONE if (isPresentSong) { setPresentSongFloatingButton(view) } if (isPlayVideo(song.urlKey)) { setPlaySongFloatingButton(view, song.urlKey!!) } } } private fun setPlaySongFloatingMenuButton(view: View, urrlKey: String) { val playSongFloatingActionButton = view.findViewById<View>(R.id.play_song_floating_menu_button) as FloatingActionButton if (isPlayVideo(urrlKey)) { playSongFloatingActionButton.visibility = View.VISIBLE playSongFloatingActionButton.setOnClickListener { showYouTube(urrlKey) if (floatingActionMenu!!.isExpanded) { floatingActionMenu!!.collapse() } } } } private fun setPresentSongFloatingMenuButton(view: View) { val presentSongFloatingMenuButton = view.findViewById<View>(R.id.present_song_floating_menu_button) as FloatingActionButton presentSongFloatingMenuButton.visibility = View.VISIBLE presentSongFloatingMenuButton.setOnClickListener { if (floatingActionMenu!!.isExpanded) { floatingActionMenu!!.collapse() } if (presentationScreenService!!.presentation != null) { presentSelectedVerse(0) floatingActionMenu!!.visibility = View.GONE activity!!.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT } else { Toast.makeText(activity, "Your device is not connected to any remote display", Toast.LENGTH_SHORT).show() } } } private fun setPresentSongFloatingButton(view: View) { presentSongFloatingButton = view.findViewById<View>(R.id.present_song_floating_button) as FloatingActionButton presentSongFloatingButton!!.visibility = View.VISIBLE presentSongFloatingButton!!.setOnClickListener { if (presentationScreenService!!.presentation != null) { presentSelectedVerse(0) presentSongFloatingButton!!.visibility = View.GONE activity!!.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT } else { Toast.makeText(activity, "Your device is not connected to any remote display", Toast.LENGTH_SHORT).show() } } } private fun setPlaySongFloatingButton(view: View, urlKey: String) { val playSongFloatingButton = view.findViewById<View>(R.id.play_song_floating_button) as FloatingActionButton playSongFloatingButton.visibility = View.VISIBLE playSongFloatingButton.setOnClickListener { showYouTube(urlKey) } } private fun showYouTube(urlKey: String) { Log.i(this.javaClass.simpleName, "Url key: $urlKey") val youTubeIntent = Intent(activity, CustomYoutubeBoxActivity::class.java) youTubeIntent.putExtra(CustomYoutubeBoxActivity.KEY_VIDEO_ID, urlKey) youTubeIntent.putExtra(CommonConstants.TITLE_KEY, title) activity!!.startActivity(youTubeIntent) } private fun setNextButton(view: View) { nextButton = view.findViewById<View>(R.id.next_verse_floating_button) as FloatingActionButton nextButton!!.visibility = View.GONE nextButton!!.setOnClickListener(NextButtonOnClickListener()) } private fun setPreviousButton(view: View) { previousButton = view.findViewById<View>(R.id.previous_verse_floating_button) as FloatingActionButton previousButton!!.visibility = View.GONE previousButton!!.setOnClickListener(PreviousButtonOnClickListener()) } override fun fragmentBecameVisible() { onBecameVisible(song) } private fun onBecameVisible(song: Song?) { val presentingSong = Setting.instance.song if (presentingSong != null && presentingSong == song && presentationScreenService!!.presentation != null) { setPresentation(song) } else { hideOrShowComponents(song) } setActionBarTitle() } private fun setPresentation(song: Song) { val currentPosition = Setting.instance.slidePosition presentSelectedVerse(currentPosition) if (floatingActionMenu != null) { floatingActionMenu!!.visibility = View.GONE } if (presentSongFloatingButton != null) { presentSongFloatingButton!!.visibility = View.GONE } nextButton!!.visibility = if (song.contents!!.size - 1 == currentPosition) View.GONE else View.VISIBLE previousButton!!.visibility = if (currentPosition == 0) View.GONE else View.VISIBLE activity!!.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT } private fun hideOrShowComponents(song: Song?) { if (nextButton != null) { nextButton!!.visibility = View.GONE } if (previousButton != null) { previousButton!!.visibility = View.GONE } if (isPlayVideo(song!!.urlKey) && isPresentSong && floatingActionMenu != null) { floatingActionMenu!!.visibility = View.VISIBLE } else if (presentSongFloatingButton != null) { presentSongFloatingButton!!.visibility = View.VISIBLE } if (presentSongCardViewAdapter != null) { presentSongCardViewAdapter!!.setItemSelected(-1) presentSongCardViewAdapter!!.notifyDataSetChanged() } if (listView != null) { listView!!.smoothScrollToPosition(0) } } private inner class NextButtonOnClickListener : View.OnClickListener { override fun onClick(v: View) { val position = presentSongCardViewAdapter!!.selectedItem + 1 listView!!.smoothScrollToPositionFromTop(position, 2) presentSelectedVerse(if (position <= song!!.contents!!.size) position else position - 1) } } private inner class PreviousButtonOnClickListener : View.OnClickListener { override fun onClick(v: View) { val position = presentSongCardViewAdapter!!.selectedItem - 1 val previousPosition = if (position >= 0) position else 0 listView!!.smoothScrollToPosition(previousPosition, 2) presentSelectedVerse(previousPosition) } } private inner class ListViewOnItemClickListener : AdapterView.OnItemClickListener { override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) { if (previousButton!!.visibility == View.VISIBLE || nextButton!!.visibility == View.VISIBLE) { listView!!.smoothScrollToPositionFromTop(position, 2) presentSelectedVerse(position) } if (floatingActionMenu != null && floatingActionMenu!!.isExpanded) { activity!!.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED floatingActionMenu!!.collapse() val color = 0x00000000 setListViewForegroundColor(color) } } } private fun presentSelectedVerse(position: Int) { if (presentationScreenService!!.presentation != null) { presentationScreenService!!.showNextVerse(song, position) presentSongCardViewAdapter!!.setItemSelected(position) presentSongCardViewAdapter!!.notifyDataSetChanged() previousButton!!.visibility = if (position <= 0) View.GONE else View.VISIBLE nextButton!!.visibility = if (position >= song!!.contents!!.size - 1) View.GONE else View.VISIBLE } } private inner class ListViewOnItemLongClickListener : AdapterView.OnItemLongClickListener { internal val isCopySelectedVerse: Boolean get() = !isPresentSong || isPlayVideo(song!!.urlKey) && floatingActionMenu != null && floatingActionMenu!!.visibility == View.VISIBLE || presentSongFloatingButton != null && presentSongFloatingButton!!.visibility == View.VISIBLE override fun onItemLongClick(parent: AdapterView<*>, view: View, position: Int, id: Long): Boolean { if (isCopySelectedVerse) { val selectedVerse = song!!.contents!![position] presentSongCardViewAdapter!!.setItemSelected(position) presentSongCardViewAdapter!!.notifyDataSetChanged() shareSongInSocialMedia(selectedVerse) } return false } internal fun shareSongInSocialMedia(selectedText: String) { val formattedContent = song!!.title + "\n\n" + customTagColorService.getFormattedLines(selectedText) + "\n" + String.format(getString(R.string.verse_share_info), getString(R.string.app_name)) val textShareIntent = Intent(Intent.ACTION_SEND) textShareIntent.putExtra(Intent.EXTRA_TEXT, formattedContent) textShareIntent.type = "text/plain" val intent = Intent.createChooser(textShareIntent, "Share verse with...") activity!!.startActivity(intent) } } private fun setListViewForegroundColor(color: Int) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { listView!!.foreground = ColorDrawable(color) } } private fun isPlayVideo(urrlKey: String?): Boolean { val playVideoStatus = preferenceSettingService.isPlayVideo return urrlKey != null && urrlKey.length > 0 && playVideoStatus } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) if (youTubePlayer != null) { outState.putInt(KEY_VIDEO_TIME, youTubePlayer.currentTimeMillis) Log.i(this.javaClass.simpleName, "Video duration: " + youTubePlayer.currentTimeMillis) } } private inner class SongContentPortraitViewTouchListener : View.OnTouchListener { override fun onTouch(v: View, event: MotionEvent): Boolean { val position = tilteList!!.indexOf(title) Setting.instance.position = position return true } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { menu.clear() if (CommonUtils.isPhone(context!!)) { inflater!!.inflate(R.menu.action_bar_options, menu) } super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { Log.i(SongContentPortraitViewFragment::class.java.simpleName, "Menu item " + item.itemId + " " + R.id.options) when (item.itemId) { android.R.id.home -> { activity!!.finish() return true } R.id.options -> { Log.i(SongContentPortraitViewFragment::class.java.simpleName, "On tapped options") popupMenuService = PopupMenuService() PermissionUtils.isStoragePermissionGranted(activity as Activity) popupMenuService!!.showPopupmenu(activity as AppCompatActivity, activity!!.findViewById(R.id.options), title!!, false) return true } else -> return super.onOptionsItemSelected(item) } } override fun onPrepareOptionsMenu(menu: Menu) { super.onPrepareOptionsMenu(menu) } override fun setUserVisibleHint(isVisibleToUser: Boolean) { super.setUserVisibleHint(isVisibleToUser) if (isVisibleToUser) { setActionBarTitle() } } private fun setActionBarTitle() { val appCompatActivity = activity as AppCompatActivity? try { if (preferenceSettingService != null && tilteList!!.size > 0 && CommonUtils.isPhone(context!!)) { val title: String if (tilteList!!.size == 1) { title = tilteList!![0] } else { title = tilteList!![Setting.instance.position] } val song = songDao.findContentsByTitle(title) appCompatActivity!!.title = getTitle(song, title) } } catch (ex: Exception) { appCompatActivity!!.title = title } } private fun getTitle(song: Song?, defaultTitle: String): String { try { val title = if (preferenceSettingService.isTamil && song!!.tamilTitle!!.length > 0) song.tamilTitle else song!!.title return songBookNumber + title } catch (e: Exception) { return songBookNumber + defaultTitle } } companion object { val KEY_VIDEO_TIME = "KEY_VIDEO_TIME" fun newInstance(title: String, titles: ArrayList<String>): SongContentPortraitViewFragment { val songContentPortraitViewFragment = SongContentPortraitViewFragment() val bundle = Bundle() bundle.putStringArrayList(CommonConstants.TITLE_LIST_KEY, titles) bundle.putString(CommonConstants.TITLE_KEY, title) songContentPortraitViewFragment.arguments = bundle return songContentPortraitViewFragment } fun newInstance(bundle: Bundle): SongContentPortraitViewFragment { val songContentPortraitViewFragment = SongContentPortraitViewFragment() songContentPortraitViewFragment.arguments = bundle return songContentPortraitViewFragment } } }
app/src/main/java/org/worshipsongs/fragment/SongContentPortraitViewFragment.kt
133219863
package org.rliz.cfm.recorder.playback.api import org.rliz.cfm.recorder.playback.boundary.BatchResultItem data class BatchResultRes( val results: List<BatchResultItemRes> ) fun List<BatchResultItem>.toRes() = BatchResultRes(results = map(BatchResultItem::toRes))
server/recorder/src/main/kotlin/org/rliz/cfm/recorder/playback/api/BatchResultRes.kt
986147289
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.execution.impl import com.intellij.execution.ProgramRunnerUtil import com.intellij.execution.RunnerAndConfigurationSettings import com.intellij.execution.configurations.RuntimeConfigurationException import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.IndexNotReadyException import com.intellij.openapi.project.Project import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.registry.Registry import com.intellij.ui.IconDeferrer import com.intellij.util.containers.ObjectLongHashMap import gnu.trove.THashMap import java.util.concurrent.locks.ReentrantReadWriteLock import javax.swing.Icon import kotlin.concurrent.read import kotlin.concurrent.write class TimedIconCache { private val idToIcon = THashMap<String, Icon>() private val iconCheckTimes = ObjectLongHashMap<String>() private val iconCalcTime = ObjectLongHashMap<String>() private val lock = ReentrantReadWriteLock() fun remove(id: String) { lock.write { idToIcon.remove(id) iconCheckTimes.remove(id) iconCalcTime.remove(id) } } fun get(id: String, settings: RunnerAndConfigurationSettings, project: Project): Icon { return lock.read { idToIcon.get(id) } ?: lock.write { idToIcon.get(id)?.let { return it } val icon = IconDeferrer.getInstance().deferAutoUpdatable(settings.configuration.icon, project.hashCode() xor settings.hashCode()) { if (project.isDisposed) { return@deferAutoUpdatable null } lock.write { iconCalcTime.remove(id) } val startTime = System.currentTimeMillis() var icon: Icon if (DumbService.isDumb(project) && !Registry.`is`("dumb.aware.run.configurations")) { icon = IconLoader.getDisabledIcon(ProgramRunnerUtil.getRawIcon(settings))!! if (settings.isTemporary) { icon = ProgramRunnerUtil.getTemporaryIcon(icon) } } else { try { DumbService.getInstance(project).isAlternativeResolveEnabled = true settings.checkSettings() icon = ProgramRunnerUtil.getConfigurationIcon(settings, false) } catch (e: IndexNotReadyException) { icon = ProgramRunnerUtil.getConfigurationIcon(settings, !Registry.`is`("dumb.aware.run.configurations")) } catch (ignored: RuntimeConfigurationException) { icon = ProgramRunnerUtil.getConfigurationIcon(settings, true) } finally { DumbService.getInstance(project).isAlternativeResolveEnabled = false } } lock.write { iconCalcTime.put(id, System.currentTimeMillis() - startTime) } icon } set(id, icon) icon } } private fun set(id: String, icon: Icon) { idToIcon.put(id, icon) iconCheckTimes.put(id, System.currentTimeMillis()) } fun clear() { lock.write { idToIcon.clear() iconCheckTimes.clear() iconCalcTime.clear() } } fun checkValidity(id: String) { lock.read { val lastCheckTime = iconCheckTimes.get(id) var expired = lastCheckTime == -1L if (!expired) { var calcTime = iconCalcTime.get(id) if (calcTime == -1L || calcTime < 150) { calcTime = 150L } expired = (System.currentTimeMillis() - lastCheckTime) > (calcTime * 10) } if (expired) { lock.write { idToIcon.remove(id) } } } } }
platform/lang-impl/src/com/intellij/execution/impl/TimedIconCache.kt
2342346154
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.openapi.components.StateStorage import com.intellij.openapi.components.StateStorageOperation import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.components.TrackingPathMacroSubstitutor import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.impl.ModuleEx import com.intellij.openapi.module.impl.ModuleManagerImpl import com.intellij.openapi.module.impl.getModuleNameByFilePath import com.intellij.openapi.vfs.newvfs.events.VFileEvent import org.jdom.Element internal class ModuleStateStorageManager(macroSubstitutor: TrackingPathMacroSubstitutor, module: Module) : StateStorageManagerImpl("module", macroSubstitutor, module) { override fun getOldStorageSpec(component: Any, componentName: String, operation: StateStorageOperation) = StoragePathMacros.MODULE_FILE override fun pathRenamed(oldPath: String, newPath: String, event: VFileEvent?) { try { super.pathRenamed(oldPath, newPath, event) } finally { val requestor = event?.requestor if (requestor == null || requestor !is StateStorage /* not renamed as result of explicit rename */) { val module = componentManager as ModuleEx val oldName = module.name module.rename(getModuleNameByFilePath(newPath), false) (ModuleManager.getInstance(module.project) as? ModuleManagerImpl)?.fireModuleRenamedByVfsEvent(module, oldName) } } } override fun beforeElementLoaded(element: Element) { val optionElement = Element("component").setAttribute("name", "DeprecatedModuleOptionManager") val iterator = element.attributes.iterator() for (attribute in iterator) { if (attribute.name != ProjectStateStorageManager.VERSION_OPTION) { iterator.remove() optionElement.addContent(Element("option").setAttribute("key", attribute.name).setAttribute("value", attribute.value)) } } element.addContent(optionElement) } override fun beforeElementSaved(element: Element) { val componentIterator = element.getChildren("component").iterator() for (component in componentIterator) { if (component.getAttributeValue("name") == "DeprecatedModuleOptionManager") { componentIterator.remove() for (option in component.getChildren("option")) { element.setAttribute(option.getAttributeValue("key"), option.getAttributeValue("value")) } break } } // need be last for compat reasons element.setAttribute(ProjectStateStorageManager.VERSION_OPTION, "4") } }
platform/configuration-store-impl/src/ModuleStateStorageManager.kt
3343642265
/* * ************************************************************************ * HttpImageLoader.kt * ************************************************************************* * Copyright © 2020 VLC authors and VideoLAN * Author: Nicolas POMEPUY * 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 2 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * ************************************************************************** * * */ package org.videolan.tools import android.graphics.Bitmap import android.graphics.BitmapFactory import android.util.Log import androidx.collection.SimpleArrayMap import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import java.io.BufferedInputStream import java.io.IOException import java.io.InputStream import java.net.HttpURLConnection import java.net.URL import kotlin.math.floor import kotlin.math.max object HttpImageLoader { private val currentJobs = SimpleArrayMap<String, CompletableDeferred<Bitmap?>>() private val jobsLocker = Mutex() suspend fun downloadBitmap(imageUrl: String): Bitmap? { val icon = BitmapCache.getBitmapFromMemCache(imageUrl) ?: jobsLocker.withLock { currentJobs[imageUrl]?.takeIf { it.isActive } }?.await() if (icon != null) return icon return withContext(Dispatchers.IO) { jobsLocker.withLock { currentJobs.put(imageUrl, CompletableDeferred()) } var urlConnection: HttpURLConnection? = null var inputStream: InputStream? = null try { val url = URL(imageUrl) urlConnection = url.openConnection() as HttpURLConnection inputStream = BufferedInputStream(urlConnection.inputStream) val options = BitmapFactory.Options() options.inJustDecodeBounds = true BitmapFactory.decodeStream(inputStream, null, options) options.inJustDecodeBounds = false //limit image to 150dp for the larger size val ratio: Float = max(options.outHeight, options.outWidth).toFloat() / 150.dp.toFloat() if (ratio > 1) options.inSampleSize = floor(ratio).toInt() urlConnection = url.openConnection() as HttpURLConnection inputStream = BufferedInputStream(urlConnection.inputStream) BitmapFactory.decodeStream(inputStream, null, options).also { BitmapCache.addBitmapToMemCache(imageUrl, it) } } catch (ignored: IOException) { Log.e("", ignored.message, ignored) null } catch (ignored: IllegalArgumentException) { Log.e("", ignored.message, ignored) null } finally { CloseableUtils.close(inputStream) urlConnection?.disconnect() } }.also { jobsLocker.withLock { currentJobs[imageUrl]?.complete(it) } } } }
application/tools/src/main/java/org/videolan/tools/HttpImageLoader.kt
2322197228
package com.nextfaze.devfun.compiler import javax.inject.Inject import javax.inject.Singleton import javax.lang.model.element.Element import javax.lang.model.element.QualifiedNameable import javax.lang.model.util.Elements @Singleton internal class Options @Inject constructor( override val elements: Elements, private val options: Map<String, String> ) : WithElements { private fun String.optionOf(): String? = options[this]?.trim()?.takeIf { it.isNotBlank() } private fun String.booleanOf(default: Boolean = false): Boolean = optionOf()?.toBoolean() ?: default val useKotlinReflection = FLAG_USE_KOTLIN_REFLECTION.booleanOf() private val isDebugVerbose = FLAG_DEBUG_VERBOSE.booleanOf() val isDebugCommentsEnabled = isDebugVerbose || FLAG_DEBUG_COMMENTS.booleanOf() val packageRoot = PACKAGE_ROOT.optionOf() val packageSuffix = PACKAGE_SUFFIX.optionOf() val packageOverride = PACKAGE_OVERRIDE.optionOf() val applicationPackage = APPLICATION_PACKAGE.optionOf() val applicationVariant = APPLICATION_VARIANT.optionOf() val extPackageRoot = EXT_PACKAGE_ROOT.optionOf() val extPackageSuffix = EXT_PACKAGE_SUFFIX.optionOf() val extPackageOverride = EXT_PACKAGE_OVERRIDE.optionOf() val generateInterfaces = GENERATE_INTERFACES.booleanOf(true) val generateDefinitions = GENERATE_DEFINITIONS.booleanOf(true) val noteLoggingEnabled = NOTE_LOGGING_ENABLED.booleanOf(false) val promoteNoteMessages = PROMOTE_NOTE_LOG_MESSAGES.booleanOf(false) private val elementFilterInclude = ELEMENTS_FILTER_INCLUDE.optionOf()?.split(",")?.map { it.trim() } ?: emptyList() private val elementFilterExclude = ELEMENTS_FILTER_EXCLUDE.optionOf()?.split(",")?.map { it.trim() } ?: emptyList() fun shouldProcessElement(element: Element): Boolean { if (elementFilterInclude.isEmpty() && elementFilterExclude.isEmpty()) return true val fqn = (element as? QualifiedNameable)?.qualifiedName?.toString() ?: "${element.packageElement}.${element.simpleName}" return (elementFilterInclude.isEmpty() || elementFilterInclude.any { fqn.startsWith(it) }) && elementFilterExclude.none { fqn.startsWith(it) } } }
devfun-compiler/src/main/java/com/nextfaze/devfun/compiler/SupportedOptions.kt
3363878440
/* * Copyright 2016 - 2017 Florian Spieß * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("KJDABuilders") package club.minnced.kjda import club.minnced.kjda.builders.KEmbedBuilder import net.dv8tion.jda.core.MessageBuilder import net.dv8tion.jda.core.entities.IMentionable import net.dv8tion.jda.core.entities.Message import net.dv8tion.jda.core.entities.MessageEmbed /** * Constructs a [Message] from the specified [init] function * which has a [MessageBuilder] as its receiver. * * To set an embed use [embed]! * * @param[builder] * An optional [MessageBuilder] to use as receiver, * this creates a new instance by default. * @param[init] * A function which constructs a new [Message] by using * the receiving [MessageBuilder] * * @return[Message] - a sendable finished Message instance */ fun message(builder: MessageBuilder = MessageBuilder(), init: MessageBuilder.() -> Unit): Message { builder.init() return builder.build() } operator fun Appendable.plusAssign(other: CharSequence) { append(other) } operator fun Appendable.plusAssign(other: Char) { append(other) } operator fun Appendable.plusAssign(other: IMentionable) { append(other.asMention) } /** * Constructs a [MessageEmbed] for the receiving [MessageBuilder] * and sets that constructed Embed using [MessageBuilder.setEmbed]! * * @param[init] * A function which constructs a [MessageEmbed] from the receiving * [EmbedBuilder] * * @receiver[MessageBuilder] * * @return[MessageBuilder] - current MessageBuilder */ infix inline fun MessageBuilder.embed(crossinline init: KEmbedBuilder.() -> Unit): MessageBuilder = setEmbed(club.minnced.kjda.builders.embed { init() })
src/main/kotlin/club/minnced/kjda/KJDABuilders.kt
102434848
package net.nemerosa.ontrack.kdsl.spec import com.apollographql.apollo.api.Input import net.nemerosa.ontrack.kdsl.connector.Connected import net.nemerosa.ontrack.kdsl.connector.Connector import net.nemerosa.ontrack.kdsl.connector.graphql.GraphQLMissingDataException import net.nemerosa.ontrack.kdsl.connector.graphql.checkData import net.nemerosa.ontrack.kdsl.connector.graphql.convert import net.nemerosa.ontrack.kdsl.connector.graphql.schema.CreateProjectMutation import net.nemerosa.ontrack.kdsl.connector.graphql.schema.FindBranchByNameQuery import net.nemerosa.ontrack.kdsl.connector.graphql.schema.FindByBuildByNameQuery import net.nemerosa.ontrack.kdsl.connector.graphql.schema.FindProjectByNameQuery import net.nemerosa.ontrack.kdsl.connector.graphqlConnector class Ontrack(connector: Connector) : Connected(connector) { /** * Creates a project * * @param name Name of the project * @param description Description for the project */ fun createProject(name: String, description: String): Project = graphqlConnector.mutate( CreateProjectMutation( name, Input.optional(description), ) ) { it?.createProject()?.fragments()?.payloadUserErrors()?.convert() }?.checkData { it.createProject()?.project() } ?.fragments()?.projectFragment()?.toProject(this) ?: throw GraphQLMissingDataException("Did not get back the created project") /** * Getting a project using its name * * @param name Name to look for * @return Project or null if not found */ fun findProjectByName(name: String): Project? = graphqlConnector.query( FindProjectByNameQuery(name) )?.projects()?.firstOrNull() ?.fragments()?.projectFragment()?.toProject(this) /** * Getting a branch using its name * * @param project Project name * @param branch Branch name * @return Branch or null if not found */ fun findBranchByName(project: String, branch: String): Branch? = graphqlConnector.query( FindBranchByNameQuery(project, branch) )?.branches()?.firstOrNull() ?.fragments()?.branchFragment()?.toBranch(this@Ontrack) /** * Getting a build using its name * * @param project Project name * @param branch Branch name * @param build Build name * @return Build or null if not found */ fun findBuildByName(project: String, branch: String, build: String): Build? = graphqlConnector.query( FindByBuildByNameQuery(project, branch, build) )?.builds()?.firstOrNull() ?.fragments()?.buildFragment()?.toBuild(this@Ontrack) }
ontrack-kdsl/src/main/java/net/nemerosa/ontrack/kdsl/spec/Ontrack.kt
2435974281
object Plugin { const val SPOTLESS = "5.7.0" const val KTLINT = "0.39.0" const val DETEKT = "1.14.2" const val JACOCO = "0.8.6" const val VERSIONS = "0.34.0" const val KOTLIN = "1.4.10" const val DOKKA = "1.4.10.2" }
buildSrc/src/main/kotlin/Plugin.kt
2988298308
package net.nemerosa.ontrack.service.security import net.nemerosa.ontrack.common.Time import net.nemerosa.ontrack.it.AbstractDSLTestJUnit4Support import net.nemerosa.ontrack.model.security.Account import net.nemerosa.ontrack.model.security.AccountManagement import net.nemerosa.ontrack.model.structure.ID import net.nemerosa.ontrack.model.structure.TokensService import org.junit.Test import org.springframework.beans.factory.annotation.Autowired import java.time.Duration import java.util.* import kotlin.test.* class TokensServiceIT : AbstractDSLTestJUnit4Support() { @Autowired private lateinit var tokensService: TokensService @Test fun `Access to tokens is only for authenticated users`() { asAnonymous { assertNull(tokensService.currentToken) } } @Test fun `Generating tokens is only for authenticated users`() { asAnonymous { assertFailsWith<TokenGenerationNoAccountException> { tokensService.generateNewToken() } } } @Test fun `Getting the current token returns none when no token is set`() { asUser { assertNull(tokensService.currentToken) } } @Test fun `Getting the current token when a token is set`() { asUser { tokensService.generateNewToken() assertNotNull(tokensService.currentToken) { assertTrue(it.value.isNotBlank()) assertNotNull(it.creation) assertNull(it.validUntil) } } } @Test fun `Getting the current token with a validity period being set`() { asUser { withCustomTokenValidityDuration(Duration.ofDays(1)) { tokensService.generateNewToken() } assertNotNull(tokensService.currentToken) { assertTrue(it.value.isNotBlank()) assertNotNull(it.creation) assertNotNull(it.validUntil) { until -> assertTrue(until > it.creation, "Validity is set and in the future of the creation period") } } } } @Test fun `Revoking a token`() { asUser { tokensService.generateNewToken() assertNotNull(tokensService.currentToken) tokensService.revokeToken() assertNull(tokensService.currentToken) } } @Test fun `Unknown token`() { val t = tokensService.findAccountByToken(UUID.randomUUID().toString()) assertNull(t, "Token not found") } @Test fun `Bound user`() { asUser { val accountId = securityService.currentAccount!!.id() tokensService.generateNewToken() val token = tokensService.currentToken!!.value val t = tokensService.findAccountByToken(token) assertNotNull(t, "Token found") { assertEquals(token, it.token.value) assertNotNull(it.token.creation) assertNull(it.token.validUntil) assertEquals(accountId, it.account.id(), "Same account") } } } @Test fun `Token not found when invalidated`() { asUser { tokensService.generateNewToken() val token = tokensService.currentToken!!.value val t = tokensService.findAccountByToken(token) assertNotNull(t, "Token found") // Invalidates the token tokensService.revokeToken() val tt = tokensService.findAccountByToken(token) assertNull(tt) } } @Test fun `Get the token of an account`() { asUser { val token = tokensService.generateNewToken() // Gets the account ID val accountId = securityService.currentAccount!!.id() asUserWith<AccountManagement> { val result = tokensService.getToken(accountId) assertNotNull(result) { assertEquals(token.value, it.value) } } } } @Test fun `Revoke an account`() { asUser { tokensService.generateNewToken() val accountId = securityService.currentAccount!!.id() asUserWith<AccountManagement> { tokensService.revokeToken(accountId) } assertNull(tokensService.currentToken) } } @Test fun `Revoke all tokens`() { val accounts = (1..3).map { accountWithToken() } asAdmin { // Checks that they all have tokens accounts.forEach { account -> val token = tokensService.getToken(account) assertNotNull(token, "Tokens are set") } // Revokes all tokens asUserWith<AccountManagement> { val count = tokensService.revokeAll() assertTrue(count >= 3) } // Checks that all tokens are gone accounts.forEach { account -> val token = tokensService.getToken(account) assertNull(token, "Tokens are gone") } } } @Test fun `Checking the validity of a token with cache not enabled`() { withCustomTokenCache(false) { asUser { val id = securityService.currentAccount!!.id() val token = tokensService.generateNewToken() assertTrue(tokensService.isValid(token.value), "Token is valid") asAdmin { tokensService.revokeToken(id) } assertFalse(tokensService.isValid(token.value), "Token has been revoked") assertFalse(tokensService.isValid(token.value), "Token has been revoked") } } } @Test fun `Checking the validity of a token with cache enabled`() { withCustomTokenCache(true) { asUser { val id = securityService.currentAccount!!.id() val token = tokensService.generateNewToken() assertTrue(tokensService.isValid(token.value), "Token is valid") asAdmin { tokensService.revokeToken(id) } assertFalse(tokensService.isValid(token.value), "Token has been revoked") assertFalse(tokensService.isValid(token.value), "Token has been revoked") } } } @Test fun `Changing the validity of a token to a shorter one with unlimited defaults`() { asUser { val id = securityService.currentAccount!!.id() asAdmin { val t = tokensService.generateToken(id, Duration.ofDays(14), false) assertNotNull(t.validUntil) { assertFalse(t.isValid(Time.now() + Duration.ofDays(15))) } } } } @Test fun `Generating a token with default duration`() { withCustomTokenValidityDuration(Duration.ofDays(14)) { asUser { val id = securityService.currentAccount!!.id() asAdmin { val t = tokensService.generateToken(id, null, false) assertNotNull(t.validUntil) { assertFalse(t.isValid(Time.now() + Duration.ofDays(15))) } } } } } @Test fun `Generating a token with unlimited duration`() { withCustomTokenValidityDuration(Duration.ofDays(14)) { asUser { val id = securityService.currentAccount!!.id() asAdmin { val t = tokensService.generateToken(id, null, true) assertNull(t.validUntil, "Unlimited token") } } } } private fun accountWithToken(): Account { return asUser { tokensService.generateNewToken() val accountId = securityService.currentAccount!!.id() asAdmin { accountService.getAccount(ID.of(accountId)) } } } private fun <T> withCustomTokenValidityDuration(duration: Duration, code: () -> T): T { val old = ontrackConfigProperties.security.tokens.validity return try { ontrackConfigProperties.security.tokens.validity = duration code() } finally { ontrackConfigProperties.security.tokens.validity = old } } private fun <T> withCustomTokenCache(enabled: Boolean, code: () -> T): T { val old = ontrackConfigProperties.security.tokens.cache.enabled return try { ontrackConfigProperties.security.tokens.cache.enabled = enabled code() } finally { ontrackConfigProperties.security.tokens.cache.enabled = old } } }
ontrack-service/src/test/java/net/nemerosa/ontrack/service/security/TokensServiceIT.kt
1034796665
package com.mobilejazz.colloc.feature.encoder.domain.interactor import com.mobilejazz.colloc.domain.model.Translation import com.mobilejazz.colloc.randomInt import com.mobilejazz.colloc.randomString internal fun anyTranslation(): Translation = buildMap { repeat(randomInt(min = 1, max = 20)) { put(randomString(), randomString()) } }
server/src/test/kotlin/com/mobilejazz/colloc/feature/encoder/domain/interactor/EncodeInteractorObjectMother.kt
1574171663
package net.bjoernpetersen.musicbot.spi.plugin import net.bjoernpetersen.musicbot.api.plugin.ActiveBase /** * A generic plugin. * * Implementations can be used to do any number of things, but here are some examples: * * - A plugin providing authentication for a specific service. * Other plugins can depend on it and that way, authentication for that service is handled by this * single, central plugin. * - A plugin providing literally any non-plugin dependency. * - A plugin that actively changes the bot-behavior. * The plugin can request various bot-internals by dependency injection and provide features like * (for example) media key support. * Such a plugin would be enabled even if no other plugin depends on it (see [ActiveBase]). */ interface GenericPlugin : Plugin
src/main/kotlin/net/bjoernpetersen/musicbot/spi/plugin/GenericPlugin.kt
1126575787
package net.nemerosa.ontrack.extension.general class MessageProperty(val type: MessageType, val text: String)
ontrack-extension-general/src/main/java/net/nemerosa/ontrack/extension/general/MessageProperty.kt
1244167796
package co.ideaportal.srirangadigital.shankaraandroid.home.bindings import android.view.View import android.widget.FrameLayout import android.widget.ImageView import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout import androidx.recyclerview.widget.RecyclerView import co.ideaportal.srirangadigital.shankaraandroid.R import co.ideaportal.srirangadigital.shankaraandroid.util.AdapterClickListener class BookViewHolder(itemView: View, mAdapterClickListener: AdapterClickListener) : RecyclerView.ViewHolder(itemView) { var ivBook: ImageView = itemView.findViewById(R.id.ivBook) init { itemView.setOnClickListener { mAdapterClickListener.onClick(adapterPosition, itemView) } } }
app/src/main/java/co/ideaportal/srirangadigital/shankaraandroid/home/bindings/BookViewHolder.kt
2156878921
package net.bjoernpetersen.musicbot.spi.plugin import net.bjoernpetersen.musicbot.api.config.Config import net.bjoernpetersen.musicbot.api.player.Song import net.bjoernpetersen.musicbot.api.plugin.IdBase import net.bjoernpetersen.musicbot.api.plugin.bases import net.bjoernpetersen.musicbot.api.plugin.id import net.bjoernpetersen.musicbot.spi.loader.Resource import net.bjoernpetersen.musicbot.spi.plugin.management.ProgressFeedback import org.junit.jupiter.api.Assertions.assertDoesNotThrow import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test class PluginTest { @Test fun allBases() { val uut = TestProvider() val bases = uut.bases.toSet() assertEquals(setOf(Provider::class, TestProviderBase::class), bases) } @Test fun idDoesNotThrow() { val uut = TestProvider() assertDoesNotThrow { uut.id } } @Test fun idCorrect() { val uut = TestProvider() assertEquals(TestProviderBase::class, uut.id.type) } } @IdBase("Test") private interface TestProviderBase : Provider private class TestProvider : TestProviderBase { override fun createConfigEntries(config: Config): List<Config.Entry<*>> { TODO("not implemented") } override fun createSecretEntries(secrets: Config): List<Config.Entry<*>> { TODO("not implemented") } override fun createStateEntries(state: Config) { TODO("not implemented") } override suspend fun initialize(progressFeedback: ProgressFeedback) { TODO("not implemented") } override suspend fun close() { TODO("not implemented") } override val subject: String = "For testing eyes only" override val description: String = "" override val name: String = "TestProvider" override suspend fun loadSong(song: Song): Resource { TODO("not implemented") } override suspend fun supplyPlayback(song: Song, resource: Resource): Playback { TODO("not implemented") } override suspend fun lookup(id: String): Song { TODO("not implemented") } override suspend fun search(query: String, offset: Int): List<Song> { TODO("not implemented") } }
src/test/kotlin/net/bjoernpetersen/musicbot/spi/plugin/PluginTest.kt
2645001336
// 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. /* * Copyright 2000-2012 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.plugins.github import com.intellij.icons.AllIcons import com.intellij.ide.BrowserUtil import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.application.invokeAndWaitIfNeed import com.intellij.openapi.components.service import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.Splitter import com.intellij.openapi.util.ThrowableComputable import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsDataKeys import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.openapi.vcs.changes.ui.SelectFilesDialog import com.intellij.openapi.vcs.ui.CommitMessage import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.components.JBLabel import com.intellij.ui.components.labels.LinkLabel import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.mapSmartSet import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.vcsUtil.VcsFileUtil import git4idea.DialogManager import git4idea.GitUtil import git4idea.actions.BasicAction import git4idea.actions.GitInit import git4idea.commands.Git import git4idea.commands.GitCommand import git4idea.commands.GitLineHandler import git4idea.i18n.GitBundle import git4idea.repo.GitRepository import git4idea.util.GitFileUtils import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.TestOnly import org.jetbrains.plugins.github.api.GithubApiRequestExecutorManager import org.jetbrains.plugins.github.api.GithubApiRequests import org.jetbrains.plugins.github.api.util.GithubApiPagesLoader import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.authentication.accounts.GithubAccountInformationProvider import org.jetbrains.plugins.github.ui.GithubShareDialog import org.jetbrains.plugins.github.util.GithubAccountsMigrationHelper import org.jetbrains.plugins.github.util.GithubGitHelper import org.jetbrains.plugins.github.util.GithubNotifications import org.jetbrains.plugins.github.util.GithubUtil import java.awt.BorderLayout import java.awt.Component import java.awt.Container import java.awt.FlowLayout import java.io.IOException import java.util.* import javax.swing.BoxLayout import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JPanel class GithubShareAction : DumbAwareAction("Share Project on GitHub", "Easily share project on GitHub", AllIcons.Vcs.Vendors.Github) { override fun update(e: AnActionEvent) { val project = e.getData(CommonDataKeys.PROJECT) e.presentation.isEnabledAndVisible = project != null && !project.isDefault } // get gitRepository // check for existing git repo // check available repos and privateRepo access (net) // Show dialog (window) // create GitHub repo (net) // create local git repo (if not exist) // add GitHub as a remote host // make first commit // push everything (net) override fun actionPerformed(e: AnActionEvent) { val project = e.getData(CommonDataKeys.PROJECT) val file = e.getData(CommonDataKeys.VIRTUAL_FILE) if (project == null || project.isDisposed) { return } shareProjectOnGithub(project, file) } companion object { private val LOG = GithubUtil.LOG @JvmStatic fun shareProjectOnGithub(project: Project, file: VirtualFile?) { BasicAction.saveAll() val gitRepository = GithubGitHelper.findGitRepository(project, file) if (!service<GithubAccountsMigrationHelper>().migrate(project)) return val authManager = service<GithubAuthenticationManager>() if (!authManager.ensureHasAccounts(project)) return val accounts = authManager.getAccounts() val progressManager = service<ProgressManager>() val requestExecutorManager = service<GithubApiRequestExecutorManager>() val accountInformationProvider = service<GithubAccountInformationProvider>() val gitHelper = service<GithubGitHelper>() val git = service<Git>() val possibleRemotes = gitRepository?.let(gitHelper::getAccessibleRemoteUrls).orEmpty() if (possibleRemotes.isNotEmpty()) { val existingRemotesDialog = GithubExistingRemotesDialog(project, possibleRemotes) DialogManager.show(existingRemotesDialog) if (!existingRemotesDialog.isOK) { return } } val accountInformationLoader = object : (GithubAccount, Component) -> Pair<Boolean, Set<String>> { private val loadedInfo = mutableMapOf<GithubAccount, Pair<Boolean, Set<String>>>() @Throws(IOException::class) override fun invoke(account: GithubAccount, parentComponent: Component) = loadedInfo.getOrPut(account) { val requestExecutor = requestExecutorManager.getExecutor(account, parentComponent) ?: throw ProcessCanceledException() progressManager.runProcessWithProgressSynchronously(ThrowableComputable<Pair<Boolean, Set<String>>, IOException> { val user = requestExecutor.execute(progressManager.progressIndicator, GithubApiRequests.CurrentUser.get(account.server)) val names = GithubApiPagesLoader .loadAll(requestExecutor, progressManager.progressIndicator, GithubApiRequests.CurrentUser.Repos.pages(account.server, false)) .mapSmartSet { it.name } user.canCreatePrivateRepo() to names }, "Loading Account Information For $account", true, project) } } val shareDialog = GithubShareDialog(project, accounts, authManager.getDefaultAccount(project), gitRepository?.remotes?.map { it.name }?.toSet() ?: emptySet(), accountInformationLoader) DialogManager.show(shareDialog) if (!shareDialog.isOK) { return } val name: String = shareDialog.getRepositoryName() val isPrivate: Boolean = shareDialog.isPrivate() val remoteName: String = shareDialog.getRemoteName() val description: String = shareDialog.getDescription() val account: GithubAccount = shareDialog.getAccount() val requestExecutor = requestExecutorManager.getExecutor(account, project) ?: return object : Task.Backgroundable(project, "Sharing Project on GitHub...") { private lateinit var url: String override fun run(indicator: ProgressIndicator) { // create GitHub repo (network) LOG.info("Creating GitHub repository") indicator.text = "Creating GitHub repository..." url = requestExecutor .execute(indicator, GithubApiRequests.CurrentUser.Repos.create(account.server, name, description, isPrivate)).htmlUrl LOG.info("Successfully created GitHub repository") val root = gitRepository?.root ?: project.baseDir // creating empty git repo if git is not initialized LOG.info("Binding local project with GitHub") if (gitRepository == null) { LOG.info("No git detected, creating empty git repo") indicator.text = "Creating empty git repo..." if (!createEmptyGitRepository(project, root)) { return } } val repositoryManager = GitUtil.getRepositoryManager(project) val repository = repositoryManager.getRepositoryForRoot(root) if (repository == null) { GithubNotifications.showError(project, "Failed to create GitHub Repository", "Can't find Git repository") return } indicator.text = "Retrieving username..." val username = accountInformationProvider.getInformation(requestExecutor, indicator, account).login val remoteUrl = gitHelper.getRemoteUrl(account.server, username, name) //git remote add origin [email protected]:login/name.git LOG.info("Adding GitHub as a remote host") indicator.text = "Adding GitHub as a remote host..." git.addRemote(repository, remoteName, remoteUrl).throwOnError() repository.update() // create sample commit for binding project if (!performFirstCommitIfRequired(project, root, repository, indicator, name, url)) { return } //git push origin master LOG.info("Pushing to github master") indicator.text = "Pushing to github master..." if (!pushCurrentBranch(project, repository, remoteName, remoteUrl, name, url)) { return } GithubNotifications.showInfoURL(project, "Successfully shared project on GitHub", name, url) } private fun createEmptyGitRepository(project: Project, root: VirtualFile): Boolean { val result = Git.getInstance().init(project, root) if (!result.success()) { VcsNotifier.getInstance(project).notifyError(GitBundle.getString("initializing.title"), result.errorOutputAsHtmlString) LOG.info("Failed to create empty git repo: " + result.errorOutputAsJoinedString) return false } GitInit.refreshAndConfigureVcsMappings(project, root, root.path) return true } private fun performFirstCommitIfRequired(project: Project, root: VirtualFile, repository: GitRepository, indicator: ProgressIndicator, name: String, url: String): Boolean { // check if there is no commits if (!repository.isFresh) { return true } LOG.info("Trying to commit") try { LOG.info("Adding files for commit") indicator.text = "Adding files to git..." // ask for files to add val trackedFiles = ChangeListManager.getInstance(project).affectedFiles val untrackedFiles = filterOutIgnored(project, repository.untrackedFilesHolder.retrieveUntrackedFiles()) trackedFiles.removeAll(untrackedFiles) // fix IDEA-119855 val allFiles = ArrayList<VirtualFile>() allFiles.addAll(trackedFiles) allFiles.addAll(untrackedFiles) val dialog = invokeAndWaitIfNeed(indicator.modalityState) { GithubUntrackedFilesDialog(project, allFiles).apply { if (!trackedFiles.isEmpty()) { selectedFiles = trackedFiles } DialogManager.show(this) } } val files2commit = dialog.selectedFiles if (!dialog.isOK || files2commit.isEmpty()) { GithubNotifications.showInfoURL(project, "Successfully created empty repository on GitHub", name, url) return false } val files2add = ContainerUtil.intersection(untrackedFiles, files2commit) val files2rm = ContainerUtil.subtract(trackedFiles, files2commit) val modified = HashSet(trackedFiles) modified.addAll(files2commit) GitFileUtils.addFiles(project, root, files2add) GitFileUtils.deleteFilesFromCache(project, root, files2rm) // commit LOG.info("Performing commit") indicator.text = "Performing commit..." val handler = GitLineHandler(project, root, GitCommand.COMMIT) handler.setStdoutSuppressed(false) handler.addParameters("-m", dialog.commitMessage) handler.endOptions() Git.getInstance().runCommand(handler).throwOnError() VcsFileUtil.markFilesDirty(project, modified) } catch (e: VcsException) { LOG.warn(e) GithubNotifications.showErrorURL(project, "Can't finish GitHub sharing process", "Successfully created project ", "'$name'", " on GitHub, but initial commit failed:<br/>" + GithubUtil.getErrorTextFromException(e), url) return false } LOG.info("Successfully created initial commit") return true } private fun filterOutIgnored(project: Project, files: Collection<VirtualFile>): Collection<VirtualFile> { val changeListManager = ChangeListManager.getInstance(project) val vcsManager = ProjectLevelVcsManager.getInstance(project) return ContainerUtil.filter(files) { file -> !changeListManager.isIgnoredFile(file) && !vcsManager.isIgnored(file) } } private fun pushCurrentBranch(project: Project, repository: GitRepository, remoteName: String, remoteUrl: String, name: String, url: String): Boolean { val currentBranch = repository.currentBranch if (currentBranch == null) { GithubNotifications.showErrorURL(project, "Can't finish GitHub sharing process", "Successfully created project ", "'$name'", " on GitHub, but initial push failed: no current branch", url) return false } val result = git.push(repository, remoteName, remoteUrl, currentBranch.name, true) if (!result.success()) { GithubNotifications.showErrorURL(project, "Can't finish GitHub sharing process", "Successfully created project ", "'$name'", " on GitHub, but initial push failed:<br/>" + result.errorOutputAsHtmlString, url) return false } return true } override fun onThrowable(error: Throwable) { GithubNotifications.showError(project, "Failed to create GitHub Repository", error) } }.queue() } } @TestOnly class GithubExistingRemotesDialog(project: Project, private val remotes: List<String>) : DialogWrapper(project) { init { title = "Project Is Already on GitHub" setOKButtonText("Share Anyway") init() } override fun createCenterPanel(): JComponent? { val mainText = JBLabel(if (remotes.size == 1) "Remote is already on GitHub:" else "Following remotes are already on GitHub:") val remotesPanel = JPanel().apply { layout = BoxLayout(this, BoxLayout.Y_AXIS) } for (remote in remotes) { remotesPanel.add(JPanel(FlowLayout(FlowLayout.LEFT, 0, 0)).apply { add(LinkLabel.create(remote, Runnable { BrowserUtil.browse(remote) })) add(JBLabel(AllIcons.Ide.External_link_arrow)) }) } val messagesPanel = JBUI.Panels.simplePanel(UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP) .addToTop(mainText) .addToCenter(remotesPanel) val iconContainer = Container().apply { layout = BorderLayout() add(JLabel(Messages.getQuestionIcon()), BorderLayout.NORTH) } return JBUI.Panels.simplePanel(UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP) .addToCenter(messagesPanel) .addToLeft(iconContainer) .apply { border = JBUI.Borders.emptyBottom(UIUtil.LARGE_VGAP) } } } @TestOnly class GithubUntrackedFilesDialog(private val myProject: Project, untrackedFiles: List<VirtualFile>) : SelectFilesDialog(myProject, untrackedFiles, null, null, true, false), DataProvider { private var myCommitMessagePanel: CommitMessage? = null val commitMessage: String get() = myCommitMessagePanel!!.comment init { title = "Add Files For Initial Commit" init() } override fun createNorthPanel(): JComponent? { return null } override fun createCenterPanel(): JComponent? { val tree = super.createCenterPanel() myCommitMessagePanel = CommitMessage(myProject) myCommitMessagePanel!!.setCommitMessage("Initial commit") val splitter = Splitter(true) splitter.setHonorComponentsMinimumSize(true) splitter.firstComponent = tree splitter.secondComponent = myCommitMessagePanel splitter.proportion = 0.7f return splitter } override fun getData(@NonNls dataId: String): Any? { return if (VcsDataKeys.COMMIT_MESSAGE_CONTROL.`is`(dataId)) { myCommitMessagePanel } else null } override fun getDimensionServiceKey(): String? { return "Github.UntrackedFilesDialog" } } }
plugins/github/src/org/jetbrains/plugins/github/GithubShareAction.kt
3362215166
/* * NextCloud Android client application * * @copyright Copyright (C) 2019 Daniele Fognini <[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 <https://www.gnu.org/licenses/>. */ package com.owncloud.android.ui.db import com.owncloud.android.datamodel.UploadsStorageManager.UploadStatus.UPLOAD_FAILED import com.owncloud.android.datamodel.UploadsStorageManager.UploadStatus.UPLOAD_IN_PROGRESS import com.owncloud.android.db.OCUpload import com.owncloud.android.db.OCUploadComparator import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals import org.junit.BeforeClass import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.junit.runners.Suite import org.mockito.MockitoAnnotations import org.mockito.kotlin.mock import org.mockito.kotlin.whenever @RunWith(Suite::class) @Suite.SuiteClasses( OCUploadComparatorTest.Ordering::class, OCUploadComparatorTest.ComparatorContract::class ) class OCUploadComparatorTest { internal abstract class Base { companion object { val failed = mock<OCUpload>(name = "failed") val failedLater = mock<OCUpload>(name = "failedLater") val failedSameTimeOtherId = mock<OCUpload>(name = "failedSameTimeOtherId") val equalsNotSame = mock<OCUpload>(name = "equalsNotSame") val inProgress = mock<OCUpload>(name = "InProgress") val inProgressNow = mock<OCUpload>(name = "inProgressNow") private const val FIXED_UPLOAD_END_TIMESTAMP = 42L private const val FIXED_UPLOAD_END_TIMESTAMP_LATER = 43L private const val UPLOAD_ID = 40L private const val UPLOAD_ID2 = 43L fun uploads(): Array<OCUpload> { return arrayOf(failed, failedLater, inProgress, inProgressNow, failedSameTimeOtherId) } @JvmStatic @BeforeClass fun setupMocks() { MockitoAnnotations.initMocks(this) whenever(failed.fixedUploadStatus).thenReturn(UPLOAD_FAILED) whenever(inProgress.fixedUploadStatus).thenReturn(UPLOAD_IN_PROGRESS) whenever(inProgressNow.fixedUploadStatus).thenReturn(UPLOAD_IN_PROGRESS) whenever(failedLater.fixedUploadStatus).thenReturn(UPLOAD_FAILED) whenever(failedSameTimeOtherId.fixedUploadStatus).thenReturn(UPLOAD_FAILED) whenever(equalsNotSame.fixedUploadStatus).thenReturn(UPLOAD_FAILED) whenever(inProgressNow.isFixedUploadingNow).thenReturn(true) whenever(inProgress.isFixedUploadingNow).thenReturn(false) whenever(failed.fixedUploadEndTimeStamp).thenReturn(FIXED_UPLOAD_END_TIMESTAMP) whenever(failedLater.fixedUploadEndTimeStamp).thenReturn(FIXED_UPLOAD_END_TIMESTAMP_LATER) whenever(failedSameTimeOtherId.fixedUploadEndTimeStamp).thenReturn(FIXED_UPLOAD_END_TIMESTAMP) whenever(equalsNotSame.fixedUploadEndTimeStamp).thenReturn(FIXED_UPLOAD_END_TIMESTAMP) whenever(failedLater.uploadId).thenReturn(UPLOAD_ID2) whenever(failedSameTimeOtherId.uploadId).thenReturn(UPLOAD_ID) whenever(equalsNotSame.uploadId).thenReturn(UPLOAD_ID) } } } internal class Ordering : Base() { @Test fun `same are compared equals in the list`() { assertEquals(0, OCUploadComparator().compare(failed, failed)) } @Test fun `in progress is before failed in the list`() { assertEquals(1, OCUploadComparator().compare(failed, inProgress)) } @Test fun `in progress uploading now is before in progress in the list`() { assertEquals(1, OCUploadComparator().compare(inProgress, inProgressNow)) } @Test fun `later upload end is earlier in the list`() { assertEquals(1, OCUploadComparator().compare(failed, failedLater)) } @Test fun `smaller upload id is earlier in the list`() { assertEquals(1, OCUploadComparator().compare(failed, failedLater)) } @Test fun `same parameters compare equal in the list`() { assertEquals(0, OCUploadComparator().compare(failedSameTimeOtherId, equalsNotSame)) } @Test fun `sort some uploads in the list`() { val array = arrayOf( inProgress, inProgressNow, failedSameTimeOtherId, inProgressNow, null, failedLater, failed ) array.sortWith(OCUploadComparator()) assertArrayEquals( arrayOf( null, inProgressNow, inProgressNow, inProgress, failedLater, failedSameTimeOtherId, failed ), array ) } } @RunWith(Parameterized::class) internal class ComparatorContract( private val upload1: OCUpload, private val upload2: OCUpload, private val upload3: OCUpload ) : Base() { companion object { @JvmStatic @Parameterized.Parameters(name = "{0}, {1}, {2}") fun data(): List<Array<OCUpload>> { return uploads().flatMap { u1 -> uploads().flatMap { u2 -> uploads().map { u3 -> arrayOf(u1, u2, u3) } } } } } @Test fun `comparator is reflective`() { assertEquals( -OCUploadComparator().compare(upload1, upload2), OCUploadComparator().compare(upload2, upload1) ) } @Test fun `comparator is compatible with equals`() { if (upload1 == upload2) { assertEquals(0, OCUploadComparator().compare(upload1, upload2)) } } @Test fun `comparator is transitive`() { val compare12 = OCUploadComparator().compare(upload1, upload2) val compare23 = OCUploadComparator().compare(upload2, upload3) if (compare12 == compare23) { assertEquals(compare12, OCUploadComparator().compare(upload1, upload3)) } } } }
app/src/test/java/com/owncloud/android/ui/db/OCUploadComparatorTest.kt
1637166140
/* * Nextcloud Android client application * * @author Chris Narkiewicz * Copyright (C) 2019 Chris Narkiewicz <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nextcloud.client.core import java.util.concurrent.atomic.AtomicBoolean /** * This is a wrapper for a task function running in background. * It executes task function and handles result or error delivery. */ @Suppress("LongParameterList") internal class Task<T, P>( private val postResult: (Runnable) -> Boolean, private val removeFromQueue: (Runnable) -> Boolean, private val taskBody: TaskFunction<T, P>, private val onSuccess: OnResultCallback<T>?, private val onError: OnErrorCallback?, private val onProgress: OnProgressCallback<P>? ) : Runnable, Cancellable { val isCancelled: Boolean get() = cancelled.get() private val cancelled = AtomicBoolean(false) private fun postProgress(p: P) { postResult(Runnable { onProgress?.invoke(p) }) } @Suppress("TooGenericExceptionCaught") // this is exactly what we want here override fun run() { try { val result = taskBody.invoke({ postProgress(it) }, this::isCancelled) if (!cancelled.get()) { postResult.invoke( Runnable { onSuccess?.invoke(result) } ) } } catch (t: Throwable) { if (!cancelled.get()) { postResult(Runnable { onError?.invoke(t) }) } } removeFromQueue(this) } override fun cancel() { cancelled.set(true) removeFromQueue(this) } }
app/src/main/java/com/nextcloud/client/core/Task.kt
1194875657
package org.equeim.tremotesf.ui.utils import androidx.annotation.StringRes import androidx.coordinatorlayout.widget.CoordinatorLayout import com.google.android.material.snackbar.BaseTransientBottomBar import com.google.android.material.snackbar.Snackbar fun CoordinatorLayout.showSnackbar( message: CharSequence, length: Int, @StringRes actionText: Int = 0, action: (() -> Unit)? = null, onDismissed: ((Snackbar) -> Unit)? = null ) = Snackbar.make(this, message, length).apply { if (actionText != 0 && action != null) { setAction(actionText) { action() } } if (onDismissed != null) { addCallback(object : BaseTransientBottomBar.BaseCallback<Snackbar>() { override fun onDismissed(transientBottomBar: Snackbar, event: Int) { onDismissed(transientBottomBar) } }) } show() } fun CoordinatorLayout.showSnackbar( @StringRes message: Int, length: Int, @StringRes actionText: Int = 0, action: (() -> Unit)? = null, onDismissed: ((Snackbar) -> Unit)? = null ) = showSnackbar(resources.getString(message), length, actionText, action, onDismissed)
app/src/main/kotlin/org/equeim/tremotesf/ui/utils/Snackbar.kt
947829765
package com.jakewharton.rxbinding3.widget import android.widget.SearchView data class SearchViewQueryTextEvent( /** The view from which this event occurred. */ val view: SearchView, val queryText: CharSequence, val isSubmitted: Boolean )
rxbinding/src/main/java/com/jakewharton/rxbinding3/widget/SearchViewQueryTextEvent.kt
4280020152
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.debug import com.demonwav.mcdev.facet.MinecraftFacet import com.demonwav.mcdev.platform.mcp.McpModuleType import com.demonwav.mcdev.util.ModuleDebugRunConfigurationExtension import com.intellij.debugger.DebuggerManager import com.intellij.debugger.engine.DebugProcess import com.intellij.debugger.engine.DebugProcessImpl import com.intellij.debugger.engine.DebugProcessListener import com.intellij.execution.process.ProcessHandler import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModulePointer import com.intellij.openapi.module.ModulePointerManager class McpRunConfigurationExtension : ModuleDebugRunConfigurationExtension() { override fun attachToProcess(handler: ProcessHandler, module: Module) { if (MinecraftFacet.getInstance(module)?.isOfType(McpModuleType) == true) { val modulePointer = ModulePointerManager.getInstance(module.project).create(module) DebuggerManager.getInstance(module.project) .addDebugProcessListener(handler, MyProcessListener(modulePointer)) } } private inner class MyProcessListener(private val modulePointer: ModulePointer) : DebugProcessListener { override fun processAttached(process: DebugProcess) { if (process !is DebugProcessImpl) { return } // Add session listener process.xdebugProcess?.session?.addSessionListener(UngrabMouseDebugSessionListener(process, modulePointer)) // We don't need any further events process.removeDebugProcessListener(this) } } }
src/main/kotlin/platform/mcp/debug/McpRunConfigurationExtension.kt
2991942428
/* * Copyright (c) 2016-present. Drakeet Xu * * 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.drakeet.multitype.sample.communication import android.os.Bundle import androidx.recyclerview.widget.RecyclerView import com.drakeet.multitype.MultiTypeAdapter import com.drakeet.multitype.sample.MenuBaseActivity import com.drakeet.multitype.sample.R import com.drakeet.multitype.sample.normal.TextItem import java.util.* /** * @author Drakeet Xu */ class CommunicateWithBinderActivity : MenuBaseActivity() { private val aFieldValue = "aFieldValue of SimpleActivity" private var adapter: MultiTypeAdapter = MultiTypeAdapter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_list) val recyclerView = findViewById<RecyclerView>(R.id.list) val items = ArrayList<Any>() adapter.register(TextItemWithOutsizeDataViewBinder(aFieldValue)) recyclerView.adapter = adapter for (i in 0..19) { items.add(TextItem(i.toString())) } adapter.items = items adapter.notifyDataSetChanged() } }
sample/src/main/kotlin/com/drakeet/multitype/sample/communication/CommunicateWithBinderActivity.kt
218306984
@file:Suppress("UNUSED_PARAMETER") package io.mockk.junit5 import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.impl.annotations.RelaxedMockK import io.mockk.impl.annotations.SpyK import io.mockk.verify import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import kotlin.test.assertEquals import kotlin.test.assertNull import kotlin.test.assertTrue @ExtendWith(MockKExtension::class) class MockKExtensionTest { enum class Direction { NORTH, SOUTH, EAST, WEST } enum class Outcome { FAILURE, RECORDED } class RelaxedOutcome class Car { fun recordTelemetry(speed: Int, direction: Direction, lat: Double, long: Double): Outcome { return Outcome.FAILURE } fun relaxedTest(): RelaxedOutcome? { return null } } @MockK private lateinit var car2: Car @RelaxedMockK private lateinit var relaxedCar: Car @SpyK private var carSpy = Car() @Test fun injectsValidMockInMethods(@MockK car: Car) { every { car.recordTelemetry( speed = more(50), direction = Direction.NORTH, lat = any(), long = any() ) } returns Outcome.RECORDED val result = car.recordTelemetry(51, Direction.NORTH, 1.0, 2.0) assertEquals(Outcome.RECORDED, result) } @Test fun injectsValidMockInClass() { every { car2.recordTelemetry( speed = more(50), direction = Direction.NORTH, lat = any(), long = any() ) } returns Outcome.RECORDED val result = car2.recordTelemetry(51, Direction.NORTH, 1.0, 2.0) assertEquals(Outcome.RECORDED, result) } @Test fun injectsValidRelaxedMockInMethods(@RelaxedMockK car: Car) { val result = car.relaxedTest() assertTrue(result is RelaxedOutcome) } @Test fun injectsValidRelaxedMockInClass() { val result = relaxedCar.relaxedTest() assertTrue(result is RelaxedOutcome) } @Test fun testInjectsValidSpyInClass() { val result = carSpy.relaxedTest() assertNull(result) verify { carSpy.relaxedTest() } } }
modules/mockk/src/jvmTest/kotlin/io/mockk/junit5/MockKExtensionTest.kt
1418657272
package com.emogoth.android.phone.mimi.util import android.util.Log import com.emogoth.android.phone.mimi.BuildConfig import com.emogoth.android.phone.mimi.db.ArchiveTableConnection import com.emogoth.android.phone.mimi.db.models.Archive import com.emogoth.android.phone.mimi.viewmodel.ChanDataSource import com.mimireader.chanlib.models.ChanThread import io.reactivex.Single import io.reactivex.SingleEmitter import io.reactivex.schedulers.Schedulers class ArchivesManager constructor(private val connector: ChanDataSource) { val TAG = ArchivesManager::class.java.simpleName private fun archives(board: String): Single<List<Archive>> { return ArchiveTableConnection.fetchArchives(board) } fun thread(board: String, threadId: Long): Single<ChanThread> { return ArchiveTableConnection.fetchArchives(board) .observeOn(Schedulers.io()) .flatMap { archiveItems: List<Archive> -> if (BuildConfig.DEBUG) { if (archiveItems.isNotEmpty()) { for (item in archiveItems) { Log.d(TAG, "Archive: name=${item.name}, domain=${item.domain}") } } else { Log.w(TAG, "No archive servers found for /$board/") } } Single.create { emitter: SingleEmitter<ChanThread> -> var success = false var done = archiveItems.isEmpty() var i = 0 while (!done) { done = try { val item = archiveItems[i] val archivedThread = connector.fetchArchivedThread(board, threadId, item).subscribeOn(Schedulers.io()).blockingGet() if (archivedThread.name?.isNotEmpty() == true && archivedThread.posts.size > 0) { success = true if (!emitter.isDisposed) { emitter.onSuccess(archivedThread) } true } else { i++ archiveItems.size <= i } } catch (e: Exception) { Log.e(TAG, "Caught exception while fetching archives", e) i++ archiveItems.size <= i } } if (!success && !emitter.isDisposed) { emitter.onError(Exception("No Archive Found For Thread")) } } } } }
mimi-app/src/main/java/com/emogoth/android/phone/mimi/util/ArchivesManager.kt
687253072
package com.soywiz.korge.render import com.soywiz.kmem.* import com.soywiz.korag.* import com.soywiz.korge.view.* import com.soywiz.korim.bitmap.* import com.soywiz.korim.format.* import com.soywiz.korio.* import com.soywiz.korio.file.* import com.soywiz.korio.lang.* import com.soywiz.korma.geom.* /** * A [Texture] is a region (delimited by [left], [top], [right] and [bottom]) of a [Texture.Base]. * A [Texture.Base] wraps a [AG.Texture] but adds [width] and [height] information. */ class Texture( val base: Base, /** Left position of the region of the texture in pixels */ val left: Int = 0, /** Top position of the region of the texture in pixels */ val top: Int = 0, /** Right position of the region of the texture in pixels */ val right: Int = base.width, /** Bottom position of the region of the texture in pixels */ val bottom: Int = base.height ) : Closeable, BmpCoords { /** Wether the texture is multiplied or not */ val premultiplied get() = base.premultiplied /** Left position of the region of the texture in pixels */ val x = left /** Top position of the region of the texture in pixels */ val y = top /** Width of this texture region in pixels */ val width = right - left /** Height of this texture region in pixels */ val height = bottom - top /** Left coord of the texture region as a ratio (a value between 0 and 1) */ val x0: Float = (left).toFloat() / base.width.toFloat() /** Right coord of the texture region as a ratio (a value between 0 and 1) */ val x1: Float = (right).toFloat() / base.width.toFloat() /** Top coord of the texture region as a ratio (a value between 0 and 1) */ val y0: Float = (top).toFloat() / base.height.toFloat() /** Bottom coord of the texture region as a ratio (a value between 0 and 1) */ val y1: Float = (bottom).toFloat() / base.height.toFloat() override val tl_x get() = x0 override val tl_y get() = y0 override val tr_x get() = x1 override val tr_y get() = y0 override val bl_x get() = x0 override val bl_y get() = y1 override val br_x get() = x1 override val br_y get() = y1 /** * Creates a slice of this texture, by [x], [y], [width] and [height]. */ fun slice(x: Int, y: Int, width: Int, height: Int) = sliceBounds(x, y, x + width, y + height) /** * Createa a slice of this texture by [rect]. */ fun slice(rect: Rectangle) = slice(rect.x.toInt(), rect.y.toInt(), rect.width.toInt(), rect.height.toInt()) /** * Creates a slice of this texture by its bounds [left], [top], [right], [bottom]. */ fun sliceBounds(left: Int, top: Int, right: Int, bottom: Int): Texture { val tleft = (this.x + left).clamp(this.left, this.right) val tright = (this.x + right).clamp(this.left, this.right) val ttop = (this.y + top).clamp(this.top, this.bottom) val tbottom = (this.y + bottom).clamp(this.top, this.bottom) return Texture(base, tleft, ttop, tright, tbottom) } companion object { /** * Creates a [Texture] from a texture [agBase] and its wanted size [width], [height]. */ operator fun invoke(agBase: AG.Texture, width: Int, height: Int): Texture = Texture(Base(agBase, width, height), 0, 0, width, height) } /** * Represents a full texture region wraping a [base] [AG.Texture] and specifying its [width] and [height] */ class Base(var base: AG.Texture?, var width: Int, var height: Int) : Closeable { var version = -1 val premultiplied get() = base?.premultiplied == true override fun close(): Unit { base?.close() base = null } fun update(bmp: Bitmap, mipmaps: Boolean = bmp.mipmaps) { base?.upload(bmp, mipmaps) } } /** * Updates this texture from a [bmp] and optionally generates [mipmaps]. */ fun update(bmp: Bitmap32, mipmaps: Boolean = false) { base.update(bmp, mipmaps) } /** * Closes the texture */ override fun close() = base.close() override fun toString(): String = "Texture($base, (x=$x, y=$y, width=$width, height=$height))" } //suspend fun VfsFile.readTexture(ag: AG, imageFormats: ImageFormats, mipmaps: Boolean = true): Texture { // //println("VfsFile.readTexture[1]") // val tex = ag.createTexture() // //println("VfsFile.readTexture[2]") // val bmp = this.readBitmapOptimized(imageFormats) // //val bmp = this.readBitmapNoNative() // //println("VfsFile.readTexture[3]") // val canHasMipmaps = bmp.width.isPowerOfTwo && bmp.height.isPowerOfTwo // //println("VfsFile.readTexture[4]") // tex.upload(bmp, mipmaps = canHasMipmaps && mipmaps) // //println("VfsFile.readTexture[5]") // return Texture(tex, bmp.width, bmp.height) //}
korge/src/commonMain/kotlin/com/soywiz/korge/render/Texture.kt
2611389209
package utils object UID { private var uid = 10000 fun setUID(id: String) { uid = id.toInt() } fun getNewUID(): String { return "${uid++}" } fun getUID(): String { return "$uid" } }
src/main/kotlin/utils/UID.kt
3829182067
package ru.dageev.compiler.domain.node.expression import ru.dageev.compiler.bytecodegeneration.expression.ExpressionGenerator import ru.dageev.compiler.domain.node.statement.Statement import ru.dageev.compiler.domain.type.Type /** * Created by dageev * on 15-May-16. */ abstract class Expression(val type: Type) : Statement { abstract fun accept(generator: ExpressionGenerator) }
src/main/kotlin/ru/dageev/compiler/domain/node/expression/Expression.kt
1325937932
package jp.sugnakys.usbserialconsole.preference import android.annotation.SuppressLint import android.content.SharedPreferences import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty /** * Boolean Read Write Delegate */ fun SharedPreferences.boolean( defaultValue: Boolean = false, key: String? = null ): ReadWriteProperty<Any, Boolean> = delegate(defaultValue, key, SharedPreferences::getBoolean, SharedPreferences.Editor::putBoolean) /** * Nullable Boolean Read Write Delegate */ fun SharedPreferences.nullableBoolean(key: String? = null): ReadWriteProperty<Any, Boolean?> = nullableDelegate( false, key, SharedPreferences::getBoolean, SharedPreferences.Editor::putBoolean ) /** * Float Read Write Delegate */ fun SharedPreferences.float( defaultValue: Float = 0f, key: String? = null ): ReadWriteProperty<Any, Float> = delegate(defaultValue, key, SharedPreferences::getFloat, SharedPreferences.Editor::putFloat) /** * Nullable Float Read Write Delegate */ fun SharedPreferences.nullableFloat(key: String? = null): ReadWriteProperty<Any, Float?> = nullableDelegate(0f, key, SharedPreferences::getFloat, SharedPreferences.Editor::putFloat) /** * Int Read Write Delegate */ fun SharedPreferences.int(defaultValue: Int = 0, key: String? = null): ReadWriteProperty<Any, Int> = delegate(defaultValue, key, SharedPreferences::getInt, SharedPreferences.Editor::putInt) /** * Nullable Int Read Write Delegate */ fun SharedPreferences.nullableInt(key: String? = null): ReadWriteProperty<Any, Int?> = nullableDelegate(0, key, SharedPreferences::getInt, SharedPreferences.Editor::putInt) /** * Long Read Write Delegate */ fun SharedPreferences.long( defaultValue: Long = 0, key: String? = null ): ReadWriteProperty<Any, Long> = delegate(defaultValue, key, SharedPreferences::getLong, SharedPreferences.Editor::putLong) /** * Nullable Long Read Write Delegate */ fun SharedPreferences.nullableLong(key: String? = null): ReadWriteProperty<Any, Long?> = nullableDelegate(0, key, SharedPreferences::getLong, SharedPreferences.Editor::putLong) /** * String Read Write Delegate */ fun SharedPreferences.string( defaultValue: String = "", key: String? = null ): ReadWriteProperty<Any, String> = delegate(defaultValue, key, SharedPreferences::getString, SharedPreferences.Editor::putString) /** * Nullable String Read Write Delegate */ fun SharedPreferences.nullableString(key: String? = null): ReadWriteProperty<Any, String?> = nullableDelegate("", key, SharedPreferences::getString, SharedPreferences.Editor::putString) /** * Enum Read Write Delegate */ fun <T : Enum<T>> SharedPreferences.enum( valueOf: (String) -> T, defaultValue: Lazy<T>, key: String? = null ) = object : ReadWriteProperty<Any, T> { override fun getValue(thisRef: Any, property: KProperty<*>): T { return getString(key ?: property.name, null)?.let { valueOf(it) } ?: defaultValue.value } override fun setValue(thisRef: Any, property: KProperty<*>, value: T) { edit().putString(key ?: property.name, value.name).apply() } } /** * Nullable Enum Read Write Delegate */ fun <T : Enum<T>> SharedPreferences.nullableEnum(valueOf: (String) -> T, key: String? = null) = object : ReadWriteProperty<Any, T?> { override fun getValue(thisRef: Any, property: KProperty<*>): T? { return getString(key ?: property.name, null)?.let { valueOf(it) } } override fun setValue(thisRef: Any, property: KProperty<*>, value: T?) { edit().putString(key ?: property.name, value?.name).apply() } } private inline fun <T : Any> SharedPreferences.delegate( defaultValue: T, key: String?, crossinline getter: SharedPreferences.(key: String, defaultValue: T) -> T?, crossinline setter: SharedPreferences.Editor.(key: String, value: T) -> SharedPreferences.Editor ) = object : ReadWriteProperty<Any, T> { override fun getValue(thisRef: Any, property: KProperty<*>) = getter(key ?: property.name, defaultValue) ?: defaultValue @SuppressLint("CommitPrefEdits") override fun setValue(thisRef: Any, property: KProperty<*>, value: T) = edit().setter(key ?: property.name, value).apply() } private inline fun <T : Any> SharedPreferences.nullableDelegate( dummy: T, key: String?, crossinline getter: SharedPreferences.(key: String, defaultValue: T) -> T?, crossinline setter: SharedPreferences.Editor.(key: String, value: T) -> SharedPreferences.Editor ) = object : ReadWriteProperty<Any, T?> { override fun getValue(thisRef: Any, property: KProperty<*>): T? { val target = key ?: property.name return if (contains(target)) getter(target, dummy) else null } @SuppressLint("CommitPrefEdits") override fun setValue(thisRef: Any, property: KProperty<*>, value: T?) { val target = key ?: property.name if (value == null) { edit().remove(target).apply() } else { edit().setter(target, value).apply() } } }
UsbSerialConsole/app/src/main/java/jp/sugnakys/usbserialconsole/preference/SharedPreferencesExtension.kt
1726482345
package com.anyaku.epd.structure.v1 import com.anyaku.crypt.coder.decode import com.anyaku.crypt.coder.encode import com.anyaku.crypt.symmetric.Key import com.anyaku.epd.structure.Factory as FactoryBase import com.anyaku.epd.structure.UnlockedKeysMap import com.anyaku.epd.structure.UnlockedSection as UnlockedSectionBase import com.anyaku.epd.structure.UnlockedModulesMap import com.anyaku.epd.structure.UnlockedContactsMap import com.anyaku.epd.structure.UnlockedMapper as UnlockedMapperTrait import com.anyaku.epd.structure.modules.Basic import java.util.HashMap class UnlockedMapper(private val factory: FactoryBase) : UnlockedMapperTrait { override fun keysToMap(keys: UnlockedKeysMap): Map<String, Any?> { val result = HashMap<String, Any?>() for (entry in keys.entrySet()) result[ entry.key ] = encode(entry.value) return result } override fun keysFromMap(map: Map<String, Any?>): UnlockedKeysMap { val result = UnlockedKeysMap(factory) for (entry in map.entrySet()) result[entry.key] = decode(entry.value as String) as Key return result } override fun sectionToMap(unlockedSection: UnlockedSectionBase): Map<String, Any?> { val result = HashMap<String, Any?>() if (unlockedSection.title != null) result["title"] = unlockedSection.title result["modules"] = modulesToMap(unlockedSection.modules) return result } [ suppress("UNCHECKED_CAST") ] override fun sectionFromMap( id: String, map: Map<String, Any?>, contacts: UnlockedContactsMap? ): UnlockedSectionBase { val result = UnlockedSectionBase(id, map["title"] as String?, contacts, factory) result.modules.setAll(modulesFromMap(map["modules"] as Map<String, Any?>)) return result } [ suppress("UNCHECKED_CAST") ] fun modulesFromMap(map: Map<String, Any?>): UnlockedModulesMap { val result = UnlockedModulesMap(factory) for (entry in map.entrySet()) { val moduleMap = entry.value as Map<String, Any?> val moduleContentMap = moduleMap["content"] as Map<String, Any?> result[ entry.key ] = factory.buildModule(entry.key, moduleContentMap) } return result } fun modulesToMap(unlockedModulesMap: UnlockedModulesMap): Map<String, Any?> { val result = HashMap<String, Any?>() for (entry in unlockedModulesMap.entrySet()) { val moduleMap = HashMap<String, Any?>() moduleMap["content"] = entry.value.toMap() result[ entry.key ] = moduleMap } return result } }
src/main/kotlin/com/anyaku/epd/structure/v1/UnlockedMapper.kt
62728174
package net.numa08.gochisou.data.repositories import android.os.Build import net.numa08.gochisou.BuildConfig import net.numa08.gochisou.data.model.Client import net.numa08.gochisou.data.model.TempLoginInfo import net.numa08.gochisou.testtools.RoboSharedPreferencesRule import org.hamcrest.CoreMatchers.`is` import org.junit.Assert.assertThat import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricGradleTestRunner import org.robolectric.annotation.Config @RunWith(RobolectricGradleTestRunner::class) @Config(constants = BuildConfig::class, manifest = Config.NONE, sdk = intArrayOf(Build.VERSION_CODES.LOLLIPOP)) class TempLoginInfoRepositoryImplTest { @get:Rule val preferenceRule = RoboSharedPreferencesRule() lateinit var repository: TempLoginInfoRepository @Before fun initRepository() { repository = TempLoginInfoRepositoryImpl(preferenceRule.sharedPreferences) } @Test fun initEmpty() { assertThat(repository.isEmpty(), `is`(true)) } @Test fun putTempLoginInfo() { repository["key"] = TempLoginInfo( teamName = "teamName", client = Client(id = "id", secret = "secret"), redirectURL = "https://redirect.url" ) val saved = repository["key"] val newRepository = TempLoginInfoRepositoryImpl(preferenceRule.sharedPreferences) assertThat(newRepository["key"], `is`(saved)) } @Test fun clearTempLoginInfo() { repository["key"] = TempLoginInfo( teamName = "teamName", client = Client(id = "id", secret = "secret"), redirectURL = "https://redirect.url" ) repository.clear() val newRepository = TempLoginInfoRepositoryImpl(preferenceRule.sharedPreferences) assertThat(newRepository.isEmpty(), `is`(true)) } @Test fun removeTempLoginInfo() { repository["key"] = TempLoginInfo( teamName = "teamName", client = Client(id = "id", secret = "secret"), redirectURL = "https://redirect.url" ) repository.remove("key") val newRepository = TempLoginInfoRepositoryImpl(preferenceRule.sharedPreferences) assert(newRepository["key"] == null) } }
app/src/test/java/net/numa08/gochisou/data/repositories/TempLoginInfoRepositoryImplTest.kt
1677052890
package org.wikipedia.search.db import androidx.room.Entity import androidx.room.PrimaryKey import java.util.* @Entity class RecentSearch constructor( @PrimaryKey val text: String, val timestamp: Date = Date())
app/src/main/java/org/wikipedia/search/db/RecentSearch.kt
2886562278
package ru.slartus.http /* * Created by slinkin on 01.07.13. */ object AppHttpStatus { fun getReasonPhrase(code: Int, defaultPhrase: String): String { when (code) { 500 -> return "Внутренняя ошибка сервера" 501 -> return "Не реализовано" 502 -> return "Плохой шлюз" 503 -> return "Сервис недоступен" 504 -> return "Шлюз не отвечает" 505 -> return "Версия HTTP не поддерживается" 506 -> return "Вариант тоже согласован" 507 -> return "Переполнение хранилища" 509 -> return "Исчерпана пропускная ширина канала" 510 -> return "Не расширено" } return defaultPhrase } }
http/src/main/java/ru/slartus/http/AppHttpStatus.kt
383472504
package com.stripe.android.paymentsheet.flowcontroller import android.os.Parcelable import com.stripe.android.model.PaymentMethod import com.stripe.android.model.StripeIntent import com.stripe.android.paymentsheet.PaymentSheet import com.stripe.android.paymentsheet.model.ClientSecret import com.stripe.android.paymentsheet.model.SavedSelection import kotlinx.parcelize.Parcelize @Parcelize internal data class InitData( val config: PaymentSheet.Configuration?, val clientSecret: ClientSecret, val stripeIntent: StripeIntent, // the customer's existing payment methods val paymentMethods: List<PaymentMethod>, val savedSelection: SavedSelection, val isGooglePayReady: Boolean ) : Parcelable
paymentsheet/src/main/java/com/stripe/android/paymentsheet/flowcontroller/InitData.kt
2507284290
package com.eje_c.player import android.content.Context import android.graphics.SurfaceTexture import android.net.Uri import android.view.Surface import com.google.android.exoplayer2.ExoPlaybackException import com.google.android.exoplayer2.PlaybackParameters import com.google.android.exoplayer2.SimpleExoPlayer import com.google.android.exoplayer2.Timeline import com.google.android.exoplayer2.source.ExtractorMediaSource import com.google.android.exoplayer2.source.TrackGroupArray import com.google.android.exoplayer2.trackselection.TrackSelectionArray import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory import com.google.android.exoplayer2.util.Util import com.google.android.exoplayer2.video.VideoListener class ExoPlayerImpl( private val context: Context, private val exoPlayer: SimpleExoPlayer) : Player, com.google.android.exoplayer2.Player.EventListener, VideoListener { private val userAgent = Util.getUserAgent(context, context.applicationInfo.name) private val dataSourceFactory = DefaultDataSourceFactory(context, userAgent) private val mediaSourceFactory = ExtractorMediaSource.Factory(dataSourceFactory) private var surface: Surface? = null private var _videoWidth: Int = 0 private var _videoHeight: Int = 0 init { // Register event listeners exoPlayer.addVideoListener(this) exoPlayer.addListener(this) } override val duration: Long get() = exoPlayer.duration override var currentPosition: Long set(value) = exoPlayer.seekTo(value) get() = exoPlayer.currentPosition override val isPlaying: Boolean get() = exoPlayer.playWhenReady && exoPlayer.playbackState != com.google.android.exoplayer2.Player.STATE_ENDED override var volume: Float get() = exoPlayer.volume set(value) { exoPlayer.volume = value } override var onRenderFirstFrame: (() -> Unit)? = null override var onCompletion: (() -> Unit)? = null override val videoWidth: Int get() = _videoWidth override val videoHeight: Int get() = _videoHeight override fun pause() { exoPlayer.playWhenReady = false } override fun start() { exoPlayer.playWhenReady = true } override fun stop() = exoPlayer.stop() override fun load(uri: Uri) { val mediaSource = mediaSourceFactory.createMediaSource(uri) exoPlayer.prepare(mediaSource) } override fun release() { surface?.release() exoPlayer.release() } override fun setOutput(surfaceTexture: SurfaceTexture) { surface?.release() surface = Surface(surfaceTexture) exoPlayer.setVideoSurface(surface) } override fun setOutput(surface: Surface) { this.surface?.release() this.surface = surface exoPlayer.setVideoSurface(surface) } override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) { when (playbackState) { com.google.android.exoplayer2.Player.STATE_ENDED -> onCompletion?.invoke() } } override fun onRenderedFirstFrame() { onRenderFirstFrame?.invoke() } override fun onVideoSizeChanged(width: Int, height: Int, unappliedRotationDegrees: Int, pixelWidthHeightRatio: Float) { _videoWidth = width _videoHeight = height } /* * No-op events. */ override fun onPlaybackParametersChanged(playbackParameters: PlaybackParameters?) {} override fun onTracksChanged(trackGroups: TrackGroupArray?, trackSelections: TrackSelectionArray?) {} override fun onPlayerError(error: ExoPlaybackException?) {} override fun onLoadingChanged(isLoading: Boolean) {} override fun onPositionDiscontinuity(reason: Int) {} override fun onRepeatModeChanged(repeatMode: Int) {} override fun onTimelineChanged(timeline: Timeline?, manifest: Any?, reason: Int) {} override fun onSeekProcessed() {} override fun onShuffleModeEnabledChanged(shuffleModeEnabled: Boolean) {} }
player/src/main/java/com/eje_c/player/ExoPlayerImpl.kt
2176547704
/* * Copyright 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.basicpermissions.util import android.support.v4.app.ActivityCompat import android.support.v7.app.AppCompatActivity fun AppCompatActivity.checkSelfPermissionCompat(permission: String) = ActivityCompat.checkSelfPermission(this, permission) fun AppCompatActivity.shouldShowRequestPermissionRationaleCompat(permission: String) = ActivityCompat.shouldShowRequestPermissionRationale(this, permission) fun AppCompatActivity.requestPermissionsCompat(permissionsArray: Array<String>, requestCode: Int) { ActivityCompat.requestPermissions(this, permissionsArray, requestCode) }
kotlinApp/Application/src/main/java/com/example/android/basicpermissions/util/AppCompatActivityExt.kt
759631920
/* * 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 io.pixeloutlaw.minecraft.spigot.mythicdrops import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class DoublesKtTest { @Test fun `does isZero return true for 0`() { // given val toTest = 0.toDouble() // when val result = toTest.isZero() // then assertThat(result).isTrue() } @Test fun `does isZero return true for very very very close to 0`() { // given val toTest = 0.0000000007 // when val result = toTest.isZero() // then assertThat(result).isTrue() } @Test fun `does isZero return false for not very close to 0`() { // given val toTest = 0.0005 // when val result = toTest.isZero() // then assertThat(result).isFalse() } @Test fun `does isZero return false for 1`() { // given val toTest = 1.toDouble() // when val result = toTest.isZero() // then assertThat(result).isFalse() } }
src/test/kotlin/io/pixeloutlaw/minecraft/spigot/mythicdrops/DoublesKtTest.kt
1812714367
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.graphics import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.util.fastForEach actual typealias NativeCanvas = android.graphics.Canvas /** * Create a new Canvas instance that targets its drawing commands * to the provided [ImageBitmap] */ internal actual fun ActualCanvas(image: ImageBitmap): Canvas = AndroidCanvas().apply { internalCanvas = android.graphics.Canvas(image.asAndroidBitmap()) } fun Canvas(c: android.graphics.Canvas): Canvas = AndroidCanvas().apply { internalCanvas = c } /** * Holder class that is used to issue scoped calls to a [Canvas] from the framework * equivalent canvas without having to allocate an object on each draw call */ class CanvasHolder { @PublishedApi internal val androidCanvas = AndroidCanvas() inline fun drawInto(targetCanvas: android.graphics.Canvas, block: Canvas.() -> Unit) { val previousCanvas = androidCanvas.internalCanvas androidCanvas.internalCanvas = targetCanvas androidCanvas.block() androidCanvas.internalCanvas = previousCanvas } } /** * Return an instance of the native primitive that implements the Canvas interface */ actual val Canvas.nativeCanvas: NativeCanvas get() = (this as AndroidCanvas).internalCanvas // Stub canvas instance used to keep the internal canvas parameter non-null during its // scoped usage and prevent unnecessary byte code null checks from being generated private val EmptyCanvas = android.graphics.Canvas() @PublishedApi internal class AndroidCanvas() : Canvas { // Keep the internal canvas as a var prevent having to allocate an AndroidCanvas // instance on each draw call @PublishedApi internal var internalCanvas: NativeCanvas = EmptyCanvas private val srcRect = android.graphics.Rect() private val dstRect = android.graphics.Rect() /** * @see Canvas.save */ override fun save() { internalCanvas.save() } /** * @see Canvas.restore */ override fun restore() { internalCanvas.restore() } /** * @see Canvas.saveLayer */ @SuppressWarnings("deprecation") override fun saveLayer(bounds: Rect, paint: Paint) { @Suppress("DEPRECATION") internalCanvas.saveLayer( bounds.left, bounds.top, bounds.right, bounds.bottom, paint.asFrameworkPaint(), android.graphics.Canvas.ALL_SAVE_FLAG ) } /** * @see Canvas.translate */ override fun translate(dx: Float, dy: Float) { internalCanvas.translate(dx, dy) } /** * @see Canvas.scale */ override fun scale(sx: Float, sy: Float) { internalCanvas.scale(sx, sy) } /** * @see Canvas.rotate */ override fun rotate(degrees: Float) { internalCanvas.rotate(degrees) } /** * @see Canvas.skew */ override fun skew(sx: Float, sy: Float) { internalCanvas.skew(sx, sy) } /** * @throws IllegalStateException if an arbitrary transform is provided */ override fun concat(matrix: Matrix) { if (!matrix.isIdentity()) { val frameworkMatrix = android.graphics.Matrix() frameworkMatrix.setFrom(matrix) internalCanvas.concat(frameworkMatrix) } } @SuppressWarnings("deprecation") override fun clipRect(left: Float, top: Float, right: Float, bottom: Float, clipOp: ClipOp) { @Suppress("DEPRECATION") internalCanvas.clipRect(left, top, right, bottom, clipOp.toRegionOp()) } /** * @see Canvas.clipPath */ override fun clipPath(path: Path, clipOp: ClipOp) { @Suppress("DEPRECATION") internalCanvas.clipPath(path.asAndroidPath(), clipOp.toRegionOp()) } fun ClipOp.toRegionOp(): android.graphics.Region.Op = when (this) { ClipOp.Difference -> android.graphics.Region.Op.DIFFERENCE else -> android.graphics.Region.Op.INTERSECT } /** * @see Canvas.drawLine */ override fun drawLine(p1: Offset, p2: Offset, paint: Paint) { internalCanvas.drawLine( p1.x, p1.y, p2.x, p2.y, paint.asFrameworkPaint() ) } override fun drawRect(left: Float, top: Float, right: Float, bottom: Float, paint: Paint) { internalCanvas.drawRect(left, top, right, bottom, paint.asFrameworkPaint()) } override fun drawRoundRect( left: Float, top: Float, right: Float, bottom: Float, radiusX: Float, radiusY: Float, paint: Paint ) { internalCanvas.drawRoundRect( left, top, right, bottom, radiusX, radiusY, paint.asFrameworkPaint() ) } override fun drawOval(left: Float, top: Float, right: Float, bottom: Float, paint: Paint) { internalCanvas.drawOval(left, top, right, bottom, paint.asFrameworkPaint()) } /** * @see Canvas.drawCircle */ override fun drawCircle(center: Offset, radius: Float, paint: Paint) { internalCanvas.drawCircle( center.x, center.y, radius, paint.asFrameworkPaint() ) } override fun drawArc( left: Float, top: Float, right: Float, bottom: Float, startAngle: Float, sweepAngle: Float, useCenter: Boolean, paint: Paint ) { internalCanvas.drawArc( left, top, right, bottom, startAngle, sweepAngle, useCenter, paint.asFrameworkPaint() ) } /** * @see Canvas.drawPath */ override fun drawPath(path: Path, paint: Paint) { internalCanvas.drawPath(path.asAndroidPath(), paint.asFrameworkPaint()) } /** * @see Canvas.drawImage */ override fun drawImage(image: ImageBitmap, topLeftOffset: Offset, paint: Paint) { internalCanvas.drawBitmap( image.asAndroidBitmap(), topLeftOffset.x, topLeftOffset.y, paint.asFrameworkPaint() ) } /** * @See Canvas.drawImageRect */ override fun drawImageRect( image: ImageBitmap, srcOffset: IntOffset, srcSize: IntSize, dstOffset: IntOffset, dstSize: IntSize, paint: Paint ) { // There is no framework API to draw a subset of a target bitmap // that consumes only primitives so lazily allocate a src and dst // rect to populate the dimensions and re-use across calls internalCanvas.drawBitmap( image.asAndroidBitmap(), srcRect.apply { left = srcOffset.x top = srcOffset.y right = srcOffset.x + srcSize.width bottom = srcOffset.y + srcSize.height }, dstRect.apply { left = dstOffset.x top = dstOffset.y right = dstOffset.x + dstSize.width bottom = dstOffset.y + dstSize.height }, paint.asFrameworkPaint() ) } /** * @see Canvas.drawPoints */ override fun drawPoints(pointMode: PointMode, points: List<Offset>, paint: Paint) { when (pointMode) { // Draw a line between each pair of points, each point has at most one line // If the number of points is odd, then the last point is ignored. PointMode.Lines -> drawLines(points, paint, 2) // Connect each adjacent point with a line PointMode.Polygon -> drawLines(points, paint, 1) // Draw a point at each provided coordinate PointMode.Points -> drawPoints(points, paint) } } override fun enableZ() { CanvasUtils.enableZ(internalCanvas, true) } override fun disableZ() { CanvasUtils.enableZ(internalCanvas, false) } private fun drawPoints(points: List<Offset>, paint: Paint) { points.fastForEach { point -> internalCanvas.drawPoint( point.x, point.y, paint.asFrameworkPaint() ) } } /** * Draw lines connecting points based on the corresponding step. * * ex. 3 points with a step of 1 would draw 2 lines between the first and second points * and another between the second and third * * ex. 4 points with a step of 2 would draw 2 lines between the first and second and another * between the third and fourth. If there is an odd number of points, the last point is * ignored * * @see drawRawLines */ private fun drawLines(points: List<Offset>, paint: Paint, stepBy: Int) { if (points.size >= 2) { for (i in 0 until points.size - 1 step stepBy) { val p1 = points[i] val p2 = points[i + 1] internalCanvas.drawLine( p1.x, p1.y, p2.x, p2.y, paint.asFrameworkPaint() ) } } } /** * @throws IllegalArgumentException if a non even number of points is provided */ override fun drawRawPoints(pointMode: PointMode, points: FloatArray, paint: Paint) { if (points.size % 2 != 0) { throw IllegalArgumentException("points must have an even number of values") } when (pointMode) { PointMode.Lines -> drawRawLines(points, paint, 2) PointMode.Polygon -> drawRawLines(points, paint, 1) PointMode.Points -> drawRawPoints(points, paint, 2) } } private fun drawRawPoints(points: FloatArray, paint: Paint, stepBy: Int) { if (points.size % 2 == 0) { for (i in 0 until points.size - 1 step stepBy) { val x = points[i] val y = points[i + 1] internalCanvas.drawPoint(x, y, paint.asFrameworkPaint()) } } } /** * Draw lines connecting points based on the corresponding step. The points are interpreted * as x, y coordinate pairs in alternating index positions * * ex. 3 points with a step of 1 would draw 2 lines between the first and second points * and another between the second and third * * ex. 4 points with a step of 2 would draw 2 lines between the first and second and another * between the third and fourth. If there is an odd number of points, the last point is * ignored * * @see drawLines */ private fun drawRawLines(points: FloatArray, paint: Paint, stepBy: Int) { // Float array is treated as alternative set of x and y coordinates // x1, y1, x2, y2, x3, y3, ... etc. if (points.size >= 4 && points.size % 2 == 0) { for (i in 0 until points.size - 3 step stepBy * 2) { val x1 = points[i] val y1 = points[i + 1] val x2 = points[i + 2] val y2 = points[i + 3] internalCanvas.drawLine( x1, y1, x2, y2, paint.asFrameworkPaint() ) } } } override fun drawVertices(vertices: Vertices, blendMode: BlendMode, paint: Paint) { // TODO(njawad) align drawVertices blendMode parameter usage with framework // android.graphics.Canvas#drawVertices does not consume a blendmode argument internalCanvas.drawVertices( vertices.vertexMode.toAndroidVertexMode(), vertices.positions.size, vertices.positions, 0, // TODO(njawad) figure out proper vertOffset) vertices.textureCoordinates, 0, // TODO(njawad) figure out proper texOffset) vertices.colors, 0, // TODO(njawad) figure out proper colorOffset) vertices.indices, 0, // TODO(njawad) figure out proper indexOffset) vertices.indices.size, paint.asFrameworkPaint() ) } }
compose/ui/ui-graphics/src/androidMain/kotlin/androidx/compose/ui/graphics/AndroidCanvas.android.kt
1071432753
/* * 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.build.testConfiguration import androidx.build.getDistributionDirectory import com.google.gson.GsonBuilder import org.gradle.api.DefaultTask import org.gradle.api.Project import org.gradle.api.file.RegularFileProperty import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.Input import org.gradle.api.tasks.Internal import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.TaskAction import org.gradle.api.tasks.bundling.Zip import java.io.File @CacheableTask abstract class ModuleInfoGenerator : DefaultTask() { @get:OutputFile abstract val outputFile: RegularFileProperty @get:Internal val testModules: MutableList<TestModule> = mutableListOf() @Input fun getSerialized(): String { val gson = GsonBuilder().setPrettyPrinting().create() return gson.toJson(testModules.associateBy { it.name }) } @TaskAction fun writeModuleInfo() { val file = outputFile.get().asFile file.parentFile.mkdirs() file.writeText(getSerialized()) } } /** * Register two tasks need to generate information for Android test owners service. * One task zips all the OWNERS files in frameworks/support, and second task creates a * module-info.json that links test modules to paths. */ internal fun Project.registerOwnersServiceTasks() { tasks.register("zipOwnersFiles", Zip::class.java) { task -> task.archiveFileName.set("owners.zip") task.destinationDirectory.set(getDistributionDirectory()) task.from(layout.projectDirectory) task.include("**/OWNERS") task.includeEmptyDirs = false } tasks.register("createModuleInfo", ModuleInfoGenerator::class.java) { task -> task.outputFile.set(File(getDistributionDirectory(), "module-info.json")) } } data class TestModule( val name: String, val path: List<String> )
buildSrc/private/src/main/kotlin/androidx/build/testConfiguration/OwnersService.kt
3039690335
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.onnx.optimize import org.nd4j.samediff.frameworkimport.optimize.ModelOptimizer import java.io.File class OnnxOptimizer: ModelOptimizer { override fun optimize(input: File, outputFile: File) { TODO("Not yet implemented") } }
nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/optimize/OnnxOptimizer.kt
3769126852
/* * Copyright 2022 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.inspection import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @SmallTest class InspectorTest { @Test fun dummyTest() { val connection = object : Connection() {} val value = object : Inspector(connection) { override fun onReceiveCommand(data: ByteArray, callback: CommandCallback) { } } assertThat(value).isNotNull() } }
inspection/inspection/src/androidTest/java/androidx/inspection/InspectorTest.kt
2330681432
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.runconfig.target import com.intellij.execution.RunnerAndConfigurationSettings import com.intellij.execution.target.LanguageRuntimeType import com.intellij.execution.target.TargetEnvironmentConfiguration import com.intellij.execution.target.TargetEnvironmentType import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.options.Configurable import com.intellij.openapi.project.Project import org.rust.cargo.runconfig.RsCommandConfiguration import org.rust.ide.icons.RsIcons import java.util.function.Supplier import javax.swing.Icon class RsLanguageRuntimeType : LanguageRuntimeType<RsLanguageRuntimeConfiguration>(TYPE_ID) { override val displayName: String = "Rust" override val icon: Icon = RsIcons.RUST override val configurableDescription: String = "Rust Configuration" override val launchDescription: String = "Run Rust Command" override fun createSerializer(config: RsLanguageRuntimeConfiguration): PersistentStateComponent<*> = config override fun createDefaultConfig(): RsLanguageRuntimeConfiguration = RsLanguageRuntimeConfiguration() override fun duplicateConfig(config: RsLanguageRuntimeConfiguration): RsLanguageRuntimeConfiguration { return duplicatePersistentComponent(this, config) } override fun createIntrospector(config: RsLanguageRuntimeConfiguration): Introspector<RsLanguageRuntimeConfiguration>? { if (config.rustcPath.isNotBlank() && config.rustcVersion.isNotBlank() && config.cargoPath.isNotBlank() && config.cargoVersion.isNotBlank()) return null return RsLanguageRuntimeIntrospector(config) } override fun createConfigurable( project: Project, config: RsLanguageRuntimeConfiguration, targetEnvironmentType: TargetEnvironmentType<*>, targetSupplier: Supplier<TargetEnvironmentConfiguration> ): Configurable = RsLanguageRuntimeConfigurable(config) override fun findLanguageRuntime(target: TargetEnvironmentConfiguration): RsLanguageRuntimeConfiguration? { return target.runtimes.findByType() } override fun isApplicableTo(runConfig: RunnerAndConfigurationSettings): Boolean { return runConfig.configuration is RsCommandConfiguration } companion object { const val TYPE_ID: String = "RsLanguageRuntime" } }
src/main/kotlin/org/rust/cargo/runconfig/target/RsLanguageRuntimeType.kt
4223211324
package com.teamwizardry.librarianlib.foundation.item import net.minecraftforge.client.model.generators.ItemModelProvider import net.minecraftforge.client.model.generators.ModelFile import net.minecraftforge.common.extensions.IForgeItem /** * An interface for implementing Foundation's extended item functionality. */ public interface IFoundationItem: IForgeItem { /** * Gets this item's inventory texture name (e.g. the default, `item/item_id`). This is used by the * default [generateItemModel] implementation. */ public fun itemTextureName(): String { return "item/${item.registryName!!.path}" } /** * Generates the models for this item */ public fun generateItemModel(gen: ItemModelProvider) { gen.getBuilder(item.registryName!!.path) .parent(ModelFile.UncheckedModelFile("item/generated")) .texture("layer0", gen.modLoc(itemTextureName())) } }
modules/foundation/src/main/kotlin/com/teamwizardry/librarianlib/foundation/item/IFoundationItem.kt
2718315061
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.refactoring.suggested import com.intellij.refactoring.changeSignature.ParameterInfo.NEW_PARAMETER import com.intellij.refactoring.suggested.SuggestedChangeSignatureData import com.intellij.refactoring.suggested.SuggestedRefactoringExecution import org.rust.ide.refactoring.changeSignature.Parameter import org.rust.ide.refactoring.changeSignature.ParameterProperty import org.rust.ide.refactoring.changeSignature.RsChangeFunctionSignatureConfig import org.rust.ide.refactoring.changeSignature.RsChangeSignatureProcessor import org.rust.lang.core.psi.RsExpr import org.rust.lang.core.psi.RsFunction class RsSuggestedRefactoringExecution(support: RsSuggestedRefactoringSupport) : SuggestedRefactoringExecution(support) { override fun prepareChangeSignature(data: SuggestedChangeSignatureData): Any? { val function = data.declaration as? RsFunction ?: return null return RsChangeFunctionSignatureConfig.create(function) } override fun performChangeSignature( data: SuggestedChangeSignatureData, newParameterValues: List<NewParameterValue>, preparedData: Any? ) { // config holds the modified configuration changed by the user val config = preparedData as? RsChangeFunctionSignatureConfig ?: return val function = data.declaration as? RsFunction ?: return val project = function.project // At this point, function is restored to its old state // We need to create a new config which contains the original function, // but which has other attributes set to the modified configuration. val originalConfig = RsChangeFunctionSignatureConfig.create(function) // We only care about attributes which change triggers the suggested refactoring dialog. // Currently it is name and parameters. originalConfig.name = config.name val oldSignature = data.oldSignature val newSignature = data.newSignature // We need to mark "new" parameters with the new parameter index and find parameters swaps. var newParameterIndex = 0 val parameters = newSignature.parameters.zip(config.parameters).map { (signatureParameter, parameter) -> val oldParameter = oldSignature.parameterById(signatureParameter.id) val isNewParameter = oldParameter == null val index = when (oldParameter) { null -> NEW_PARAMETER else -> oldSignature.parameterIndex(oldParameter) } val defaultValue: ParameterProperty<RsExpr> = when (isNewParameter) { true -> { val newParameter = newParameterValues.getOrNull(newParameterIndex) newParameterIndex++ when (newParameter) { is NewParameterValue.Expression -> ParameterProperty.fromItem(newParameter.expression as? RsExpr) else -> null } } false -> null } ?: ParameterProperty.Empty() Parameter(parameter.factory, parameter.patText, parameter.type, index, defaultValue) } originalConfig.parameters.clear() originalConfig.parameters.addAll(parameters) RsChangeSignatureProcessor(project, originalConfig.createChangeInfo(changeSignature = false)).run() } }
src/main/kotlin/org/rust/ide/refactoring/suggested/RsSuggestedRefactoringExecution.kt
4249266177
package de.tum.`in`.tumcampusapp.component.ui.overview.card import android.content.Context import android.content.SharedPreferences abstract class StickyCard(cardType: Int, context: Context) : Card(cardType, context) { override val isDismissible: Boolean get() = false override fun discard(editor: SharedPreferences.Editor) { // Sticky cards can't be dismissed } }
app/src/main/java/de/tum/in/tumcampusapp/component/ui/overview/card/StickyCard.kt
4260715461
package org.tsdes.advanced.rest.patch import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.context.annotation.Bean import springfox.documentation.builders.PathSelectors import springfox.documentation.spi.DocumentationType import springfox.documentation.spring.web.plugins.Docket import springfox.documentation.swagger2.annotations.EnableSwagger2 /** * Created by arcuri82 on 20-Jul-17. */ @SpringBootApplication class PatchApplication { @Bean fun swaggerApi(): Docket { return Docket(DocumentationType.OAS_30) .select() .paths(PathSelectors.any()) .build() } } fun main(args: Array<String>) { SpringApplication.run(PatchApplication::class.java, *args) }
advanced/rest/patch/src/main/kotlin/org/tsdes/advanced/rest/patch/PatchApplication.kt
196408549
package org.signal.core.util import android.database.Cursor import java.util.Optional fun Cursor.requireString(column: String): String? { return CursorUtil.requireString(this, column) } fun Cursor.requireNonNullString(column: String): String { return CursorUtil.requireString(this, column)!! } fun Cursor.optionalString(column: String): Optional<String> { return CursorUtil.getString(this, column) } fun Cursor.requireInt(column: String): Int { return CursorUtil.requireInt(this, column) } fun Cursor.optionalInt(column: String): Optional<Int> { return CursorUtil.getInt(this, column) } fun Cursor.requireFloat(column: String): Float { return CursorUtil.requireFloat(this, column) } fun Cursor.requireLong(column: String): Long { return CursorUtil.requireLong(this, column) } fun Cursor.optionalLong(column: String): Optional<Long> { return CursorUtil.getLong(this, column) } fun Cursor.requireBoolean(column: String): Boolean { return CursorUtil.requireInt(this, column) != 0 } fun Cursor.optionalBoolean(column: String): Optional<Boolean> { return CursorUtil.getBoolean(this, column) } fun Cursor.requireBlob(column: String): ByteArray? { return CursorUtil.requireBlob(this, column) } fun Cursor.requireNonNullBlob(column: String): ByteArray { return CursorUtil.requireBlob(this, column)!! } fun Cursor.optionalBlob(column: String): Optional<ByteArray> { return CursorUtil.getBlob(this, column) } fun Cursor.isNull(column: String): Boolean { return CursorUtil.isNull(this, column) } fun <T> Cursor.requireObject(column: String, serializer: LongSerializer<T>): T { return serializer.deserialize(CursorUtil.requireLong(this, column)) } fun <T> Cursor.requireObject(column: String, serializer: StringSerializer<T>): T { return serializer.deserialize(CursorUtil.requireString(this, column)) } @JvmOverloads fun Cursor.readToSingleLong(defaultValue: Long = 0): Long { return use { if (it.moveToFirst()) { it.getLong(0) } else { defaultValue } } } @JvmOverloads inline fun <T> Cursor.readToList(predicate: (T) -> Boolean = { true }, mapper: (Cursor) -> T): List<T> { val list = mutableListOf<T>() use { while (moveToNext()) { val record = mapper(this) if (predicate(record)) { list += mapper(this) } } } return list } inline fun <T> Cursor.readToSet(predicate: (T) -> Boolean = { true }, mapper: (Cursor) -> T): Set<T> { val set = mutableSetOf<T>() use { while (moveToNext()) { val record = mapper(this) if (predicate(record)) { set += mapper(this) } } } return set } fun Boolean.toInt(): Int = if (this) 1 else 0
core-util/src/main/java/org/signal/core/util/CursorExtensions.kt
2708361003