repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
segmentio/analytics-android
analytics/src/test/java/com/segment/analytics/QueueFileTest.kt
1
31619
/** * The MIT License (MIT) * * Copyright (c) 2014 Segment.io, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.segment.analytics import com.segment.analytics.QueueFile.Element import com.segment.analytics.QueueFile.HEADER_LENGTH import java.io.ByteArrayOutputStream import java.io.File import java.io.IOException import java.io.RandomAccessFile import java.util.LinkedList import java.util.Queue import java.util.concurrent.atomic.AtomicInteger import java.util.logging.Logger import kotlin.NoSuchElementException import kotlin.jvm.Throws import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.fail import org.junit.Assert import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder class QueueFileTest { private val logger = Logger.getLogger(QueueFileTest::class.java.name) /** * Takes up 33401 bytes in the queue (N*(N+1)/2+4*N). Picked 254 instead of 255 so that the number * of bytes isn't a multiple of 4. */ private val N = 254 private val values = arrayOfNulls<ByteArray>(N) private fun populate() { for (i in 0 until N) { val value = ByteArray(i) for (ii in 0 until N) { // Example: values[3] = { 3, 2, 1 } for (ii in 0 until i) value[ii] = (i - ii).toByte() values[i] = value } } } @Rule @JvmField val folder = TemporaryFolder() private lateinit var file: File @Before @Throws(Exception::class) fun setUp() { populate() val parent = folder.root file = File(parent, "queue-file") } @Test @Throws(IOException::class) fun testAddOneElement() { // This test ensures that we update 'first' correctly. var queue = QueueFile(file) val expected = values[253] queue.add(expected) assertThat(queue.peek()).isEqualTo(expected) queue.close() queue = QueueFile(file) assertThat(queue.peek()).isEqualTo(expected) } @Test @Throws(IOException::class) fun testClearErases() { val queue = QueueFile(file) val expected = values[253] queue.add(expected) // Confirm that the data was in the file before we cleared. val data = ByteArray(expected!!.size) queue.raf.seek((HEADER_LENGTH + Element.HEADER_LENGTH).toLong()) queue.raf.readFully(data, 0, expected.size) assertThat(data).isEqualTo(expected) queue.clear() // Should have been erased. queue.raf.seek((HEADER_LENGTH + Element.HEADER_LENGTH).toLong()) queue.raf.readFully(data, 0, expected.size) assertThat(data).isEqualTo(ByteArray(expected.size)) } @Test @Throws(IOException::class) fun testClearDoesNotCorrupt() { var queue = QueueFile(file) val stuff = values[253] queue.add(stuff) queue.clear() queue = QueueFile(file) assertThat(queue.isEmpty).isTrue() assertThat(queue.peek()).isNull() queue.add(values[25]) assertThat(queue.peek()).isEqualTo(values[25]) } @Test @Throws(IOException::class) fun removeErasesEagerly() { val queue = QueueFile(file) val firstStuff = values[127] queue.add(firstStuff) val secondStuff = values[253] queue.add(secondStuff) // Confirm that first stuff was in the file before we remove. val data = ByteArray(firstStuff!!.size) queue.raf.seek((HEADER_LENGTH + Element.HEADER_LENGTH).toLong()) queue.raf.readFully(data, 0, firstStuff.size) assertThat(data).isEqualTo(firstStuff) queue.remove() // Next record is intact assertThat(queue.peek()).isEqualTo(secondStuff) // First should have been erased. queue.raf.seek((HEADER_LENGTH + Element.HEADER_LENGTH).toLong()) queue.raf.readFully(data, 0, firstStuff.size) assertThat(data).isEqualTo(ByteArray(firstStuff.size)) } @Test @Throws(IOException::class) fun testZeroSizeInHeaderThrows() { val emptyFile = RandomAccessFile(file, "rwd") emptyFile.setLength(4096) emptyFile.channel.force(true) emptyFile.close() try { QueueFile(file) fail("Should have thrown about bad header length") } catch (e: IOException) { assertThat(e).hasMessage("File is corrupt; length stored in header (0) is invalid.") } } @Test @Throws(IOException::class) fun testNegativeSizeInHeaderThrows() { val emptyFile = RandomAccessFile(file, "rwd") emptyFile.seek(0) emptyFile.writeInt(-2147483648) emptyFile.setLength(4096) emptyFile.channel.force(true) emptyFile.close() try { QueueFile(file) fail("Should have thrown about bad header length") } catch (ex: IOException) { assertThat(ex) .hasMessage("File is corrupt; length stored in header (-2147483648) is invalid.") } } @Test @Throws(IOException::class) fun testInvalidFirstPositionThrows() { val emptyFile = RandomAccessFile(file, "rwd") emptyFile.seek(0) emptyFile.writeInt(4096) emptyFile.setLength(4096) emptyFile.seek(8) emptyFile.writeInt(10000) emptyFile.channel.force(true) emptyFile.close() try { QueueFile(file) fail("Should have thrown about bad first position value") } catch (ex: IOException) { assertThat(ex) .hasMessage("File is corrupt; first position stored in header (10000) is invalid.") } } @Test @Throws(IOException::class) fun testNegativeFirstPositionThrows() { val emptyFile = RandomAccessFile(file, "rwd") emptyFile.seek(0) emptyFile.writeInt(4096) emptyFile.setLength(4096) emptyFile.seek(8) emptyFile.writeInt(-2147483648) emptyFile.channel.force(true) emptyFile.close() try { QueueFile(file) fail("Should have thrown about first position value") } catch (ex: IOException) { assertThat(ex) .hasMessage("File is corrupt; first position stored in header (-2147483648) is invalid.") } } @Test @Throws(IOException::class) fun testInvalidLastPositionThrows() { val emptyFile = RandomAccessFile(file, "rwd") emptyFile.seek(0) emptyFile.writeInt(4096) emptyFile.setLength(4096) emptyFile.seek(12) emptyFile.writeInt(10000) emptyFile.channel.force(true) emptyFile.close() try { QueueFile(file) fail("Should have thrown about bad last position value") } catch (ex: IOException) { assertThat(ex) .hasMessage("File is corrupt; last position stored in header (10000) is invalid.") } } @Test @Throws(IOException::class) fun testNegativeLastPositionThrows() { val emptyFile = RandomAccessFile(file, "rwd") emptyFile.seek(0) emptyFile.writeInt(4096) emptyFile.setLength(4096) emptyFile.seek(12) emptyFile.writeInt(-2147483648) emptyFile.channel.force(true) emptyFile.close() try { QueueFile(file) Assert.fail("Should have thrown about bad last position value") } catch (ex: IOException) { assertThat(ex) .hasMessage("File is corrupt; last position stored in header (-2147483648) is invalid.") } } @Test @Throws(IOException::class) fun removeMultipleDoesNotCorrupt() { var queue = QueueFile(file) for (i in 0 until 10) { queue.add(values[i]) } queue.remove(1) assertThat(queue.size()).isEqualTo(9) assertThat(queue.peek()).isEqualTo(values[1]) queue.remove(3) queue = QueueFile(file) assertThat(queue.size()).isEqualTo(6) assertThat(queue.peek()).isEqualTo(values[4]) queue.remove(6) assertThat(queue.isEmpty).isTrue() assertThat(queue.peek()).isNull() } @Test @Throws(IOException::class) fun removeDoesNotCorrupt() { var queue = QueueFile(file) queue.add(values[127]) val secondStuff = values[253] queue.add(secondStuff) queue.remove() queue = QueueFile(file) assertThat(queue.peek()).isEqualTo(secondStuff) } @Test @Throws(IOException::class) fun removeFromEmptyFileThrows() { val queue = QueueFile(file) try { queue.remove() fail("Should have thrown about removing from empty file.") } catch (ignored: NoSuchElementException) { } } @Test @Throws(IOException::class) fun removeNegativeNumberOfElementsThrows() { val queue = QueueFile(file) queue.add(values[127]) try { queue.remove(-1) Assert.fail("Should have thrown about removing negative number of elements.") } catch (ex: IllegalArgumentException) { assertThat(ex) .hasMessage("Cannot remove negative (-1) number of elements.") } } @Test @Throws(IOException::class) fun removeZeroElementsDoesNothing() { val queue = QueueFile(file) queue.add(values[127]) queue.remove(0) assertThat(queue.size()).isEqualTo(1) } @Test @Throws(IOException::class) fun removeBeyondQueueSizeElementsThrows() { val queue = QueueFile(file) queue.add(values[127]) try { queue.remove(10) fail("Should have thrown about removing too many elements.") } catch (ex: java.lang.IllegalArgumentException) { assertThat(ex) .hasMessage("Cannot remove more elements (10) than present in queue (1).") } } @Test @Throws(IOException::class) fun removingBigDamnBlocksErasesEffectively() { val bigBoy = ByteArray(7000) for (i in 0 until 7000 step 100) { values[100]!!.let { values[100]!!.size.let { length -> System.arraycopy(values[100]!!, 0, bigBoy, i, length) } } } val queue = QueueFile(file) queue.add(bigBoy) val secondStuff = values[123] queue.add(secondStuff) // Confirm that bigBoy was in the file before we remove. val data = ByteArray(bigBoy.size) queue.raf.seek((HEADER_LENGTH + Element.HEADER_LENGTH).toLong()) queue.raf.readFully(data, 0, bigBoy.size) assertThat(data).isEqualTo(bigBoy) queue.remove() // Next record is intact assertThat(queue.peek()).isEqualTo(secondStuff) // First should have been erased. queue.raf.seek((HEADER_LENGTH + Element.HEADER_LENGTH).toLong()) queue.raf.readFully(data, 0, bigBoy.size) assertThat(data).isEqualTo(ByteArray(bigBoy.size)) } @Test @Throws(IOException::class) fun testAddAndRemoveElements() { val start = System.nanoTime() val expected: Queue<ByteArray> = LinkedList() for (round in 0 until 5) { val queue = QueueFile(file) for (i in 0 until N) { queue.add(values[i]) expected.add(values[i]) } // Leave N elements in round N, 15 total for 5 rounds. Removing all the // elements would be like starting with an empty queue. for (i in 0 until N - round - 1) { assertThat(queue.peek()).isEqualTo(expected.remove()) queue.remove() } queue.close() } // Remove and validate remaining 15 elements. val queue = QueueFile(file) assertThat(queue.size()).isEqualTo(15) assertThat(queue.size()).isEqualTo(expected.size) while (!expected.isEmpty()) { assertThat(queue.peek()).isEqualTo(expected.remove()) queue.remove() } queue.close() // length() returns 0, but I checked the size w/ 'ls', and it is correct. // assertEquals(65536, file.length()); logger.info("Ran in " + (System.nanoTime() - start) / 1000000 + "ms.") } /** Tests queue expansion when the data crosses EOF. */ @Test @Throws(IOException::class) fun testSplitExpansion() { // This should result in 3560 bytes. val max = 80 val expected: Queue<ByteArray> = LinkedList() val queue = QueueFile(file) for (i in 0 until max) { expected.add(values[i]) queue.add(values[i]) } // Remove all but 1. for (i in 1 until max) { assertThat(queue.peek()).isEqualTo(expected.remove()) queue.remove() } // This should wrap around before expanding. for (i in 0 until N) { expected.add(values[i]) queue.add(values[i]) } while (!expected.isEmpty()) { assertThat(queue.peek()).isEqualTo(expected.remove()) queue.remove() } queue.close() } @Test @Throws(IOException::class) fun testFailedAdd() { var queueFile = QueueFile(file) queueFile.add(values[253]) queueFile.close() val braf = BrokenRandomAccessFile(file, "rwd") queueFile = QueueFile(braf) try { queueFile.add(values[252]) Assert.fail() } catch (e: IOException) { /* expected */ } braf.rejectCommit = false // Allow a subsequent add to succeed. queueFile.add(values[251]) queueFile.close() queueFile = QueueFile(file) assertThat(queueFile.size()).isEqualTo(2) assertThat(queueFile.peek()).isEqualTo(values[253]) queueFile.remove() assertThat(queueFile.peek()).isEqualTo(values[251]) } @Test @Throws(IOException::class) fun testFailedRemoval() { var queueFile = QueueFile(file) queueFile.add(values[253]) queueFile.close() val braf = BrokenRandomAccessFile(file, "rwd") queueFile = QueueFile(braf) try { queueFile.remove() Assert.fail() } catch (e: IOException) { /* expected */ } queueFile.close() queueFile = QueueFile(file) assertThat(queueFile.size()).isEqualTo(1) assertThat(queueFile.peek()).isEqualTo(values[253]) queueFile.add(values[99]) queueFile.remove() assertThat(queueFile.peek()).isEqualTo(values[99]) } @Test @Throws(IOException::class) fun testFailedExpansion() { var queueFile = QueueFile(file) queueFile.add(values[253]) queueFile.close() val braf = BrokenRandomAccessFile(file, "rwd") queueFile = QueueFile(braf) try { // This should trigger an expansion which should fail. queueFile.add(ByteArray(8000)) Assert.fail() } catch (e: IOException) { /* expected */ } queueFile.close() queueFile = QueueFile(file) assertThat(queueFile.size()).isEqualTo(1) assertThat(queueFile.peek()).isEqualTo(values[253]) assertThat(queueFile.fileLength).isEqualTo(4096) queueFile.add(values[99]) queueFile.remove() assertThat(queueFile.peek()).isEqualTo(values[99]) } @Test @Throws(IOException::class) fun testForEachVisitor() { val queueFile = QueueFile(file) val a = byteArrayOf(1, 2) queueFile.add(a) val b = byteArrayOf(3, 4, 5) queueFile.add(b) val iteration = intArrayOf(0) val elementVisitor = PayloadQueue.ElementVisitor { input, length -> if (iteration[0] == 0) { assertThat(length).isEqualTo(2) val actual = ByteArray(length) input.read(actual) assertThat(actual).isEqualTo(a) } else if (iteration[0] == 1) { assertThat(length).isEqualTo(3) val actual = ByteArray(length) input.read(actual) assertThat(actual).isEqualTo(b) } else { Assert.fail() } iteration[0]++ true } val saw = queueFile.forEach(elementVisitor) assertThat(saw).isEqualTo(2) assertThat(queueFile.peek()).isEqualTo(a) assertThat(iteration[0]).isEqualTo(2) } @Test @Throws(IOException::class) fun testForEachVisitorReadWithOffset() { val queueFile = QueueFile(file) queueFile.add(byteArrayOf(1, 2)) queueFile.add(byteArrayOf(3, 4, 5)) val actual = ByteArray(5) val offset = intArrayOf(0) val elementVisitor = PayloadQueue.ElementVisitor { input, length -> input.read(actual, offset[0], length) offset[0] += length true } val saw = queueFile.forEach(elementVisitor) assertThat(saw).isEqualTo(2) assertThat(actual).isEqualTo(byteArrayOf(1, 2, 3, 4, 5)) } @Test @Throws(IOException::class) fun testForEachVisitorStreamCopy() { val queueFile = QueueFile(file) queueFile.add(byteArrayOf(1, 2)) queueFile.add(byteArrayOf(3, 4, 5)) val baos = ByteArrayOutputStream() val buffer = ByteArray(8) val elementVisitor = PayloadQueue.ElementVisitor { input, length -> // A common idiom for copying data between two streams, but it depends on the // InputStream correctly returning -1 when no more data is available var count: Int while (input.read(buffer).also { count = it } != -1) { if (count == 0) { // In the past, the ElementInputStream.read(byte[], int, int) method would return 0 // when no more bytes were available for reading. This test detects that error. // // Note: 0 is a valid return value for InputStream.read(byte[], int, int), which // happens // when the passed length is zero. We could trigger that through // InputStream.read(byte[]) // by passing a zero-length buffer. However, since we won't do that during this // test, // we can safely assume that a return value of 0 indicates the past error in logic. Assert.fail("This test should never receive a result of 0 from InputStream.read(byte[])") } baos.write(buffer, 0, count) } true } val saw = queueFile.forEach(elementVisitor) assertThat(saw).isEqualTo(2) assertThat(baos.toByteArray()).isEqualTo(byteArrayOf(1, 2, 3, 4, 5)) } @Test @Throws(IOException::class) fun testForEachCanAbortEarly() { val queueFile = QueueFile(file) val a = byteArrayOf(1, 2) queueFile.add(a) val b = byteArrayOf(3, 4, 5) queueFile.add(b) val iteration = AtomicInteger() val elementVisitor = PayloadQueue.ElementVisitor { input, length -> if (iteration.get() == 0) { assertThat(length).isEqualTo(2) val actual = ByteArray(length) input.read(actual) assertThat(actual).isEqualTo(a) } else { Assert.fail() } iteration.incrementAndGet() false } val saw = queueFile.forEach(elementVisitor) assertThat(saw).isEqualTo(1) assertThat(queueFile.peek()).isEqualTo(a) assertThat(iteration.get()).isEqualTo(1) } /** * Exercise a bug where wrapped elements were getting corrupted when the QueueFile was forced to * expand in size and a portion of the final Element had been wrapped into space at the beginning * of the file. */ @Test @Throws(IOException::class) fun testFileExpansionDoesntCorruptWrappedElements() { val queue = QueueFile(file) // Create test data - 1k blocks marked consecutively 1, 2, 3, 4 and 5. val values = arrayOfNulls<ByteArray>(5) for (blockNum in values.indices) { values[blockNum] = ByteArray(1024) for (i in 0 until (values[blockNum]!!.size)) { values[blockNum]!![i] = (blockNum + 1).toByte() } } // First, add the first two blocks to the queue, remove one leaving a // 1K space at the beginning of the buffer. queue.add(values[0]) queue.add(values[1]) queue.remove() // The trailing end of block "4" will be wrapped to the start of the buffer. queue.add(values[2]) queue.add(values[3]) // Cause buffer to expand as there isn't space between the end of block "4" // and the start of block "2". Internally the queue should cause block "4" // to be contiguous, but there was a bug where that wasn't happening. queue.add(values[4]) // Make sure values are not corrupted, specifically block "4" that wasn't // being made contiguous in the version with the bug. for (blockNum in 1 until values.size) { val value = queue.peek() queue.remove() for (i in value.indices) { assertThat(value[i]) .isEqualTo((blockNum + 1).toByte()) to "Block " + (blockNum + 1) + " corrupted at byte index " + i } } queue.close() } /** * Exercise a bug where wrapped elements were getting corrupted when the QueueFile was forced to * expand in size and a portion of the final Element had been wrapped into space at the beginning * of the file - if multiple Elements have been written to empty buffer space at the start does * the expansion correctly update all their positions? */ @Test @Throws(IOException::class) fun testFileExpansionCorrectlyMovesElements() { val queue = QueueFile(file) // Create test data - 1k blocks marked consecutively 1, 2, 3, 4 and 5. val values = arrayOfNulls<ByteArray>(5) for (blockNum in values.indices) { values[blockNum] = ByteArray(1024) for (i in 0 until (values[blockNum]!!.size)) { values[blockNum]!![i] = (blockNum + 1).toByte() } } // smaller data elements val smaller = arrayOfNulls<ByteArray>(3) for (blockNum in smaller.indices) { smaller[blockNum] = ByteArray(256) for (i in smaller[blockNum]!!.indices) { smaller[blockNum]!![i] = (blockNum + 6).toByte() } } // First, add the first two blocks to the queue, remove one leaving a // 1K space at the beginning of the buffer. queue.add(values[0]) queue.add(values[1]) queue.remove() // The trailing end of block "4" will be wrapped to the start of the buffer. queue.add(values[2]) queue.add(values[3]) // Now fill in some space with smaller blocks, none of which will cause // an expansion. queue.add(smaller[0]) queue.add(smaller[1]) queue.add(smaller[2]) // Cause buffer to expand as there isn't space between the end of the // smaller block "8" and the start of block "2". Internally the queue // should cause all of tbe smaller blocks, and the trailing end of // block "5" to be moved to the end of the file. queue.add(values[4]) val expectedBlockNumbers = byteArrayOf(2, 3, 4, 6, 7, 8, 5) // Make sure values are not corrupted, specifically block "4" that wasn't // being made contiguous in the version with the bug. for (expectedBlockNumber in expectedBlockNumbers) { val value = queue.peek() queue.remove() for (i in value.indices) { assertThat(value[i]) .isEqualTo(expectedBlockNumber) to "Block $expectedBlockNumber corrupted at byte index $i" } } queue.close() } /** * Exercise a bug where file expansion would leave garbage at the start of the header and after * the last element. */ @Test @Throws(IOException::class) fun testFileExpansionCorrectlyZeroesData() { val queue = QueueFile(file) // Create test data - 1k blocks marked consecutively 1, 2, 3, 4 and 5. // Create test data - 1k blocks marked consecutively 1, 2, 3, 4 and 5. val values = arrayOfNulls<ByteArray>(5) for (blockNum in values.indices) { values[blockNum] = ByteArray(1024) for (i in values[blockNum]!!.indices) { values[blockNum]!![i] = (blockNum + 1).toByte() } } // First, add the first two blocks to the queue, remove one leaving a // 1K space at the beginning of the buffer. queue.add(values[0]) queue.add(values[1]) queue.remove() // The trailing end of block "4" will be wrapped to the start of the buffer. queue.add(values[2]) queue.add(values[3]) // Cause buffer to expand as there isn't space between the end of block "4" // and the start of block "2". Internally the queue will cause block "4" // to be contiguous. There was a bug where the start of the buffer still // contained the tail end of block "4", and garbage was copied after the tail // end of the last element. queue.add(values[4]) // Read from header to first element and make sure it's zeroed. val firstElementPadding = 1028 var data = ByteArray(firstElementPadding) queue.raf.seek(HEADER_LENGTH.toLong()) queue.raf.readFully(data, 0, firstElementPadding) assertThat(data).containsOnly(0x00.toByte()) // Read from the last element to the end and make sure it's zeroed. val endOfLastElement = HEADER_LENGTH + firstElementPadding + 4 * (Element.HEADER_LENGTH + 1024) val readLength = (queue.raf.length() - endOfLastElement).toInt() data = ByteArray(readLength) queue.raf.seek(endOfLastElement.toLong()) queue.raf.readFully(data, 0, readLength) assertThat(data).containsOnly(0x00.toByte()) } /** * Exercise a bug where an expanding queue file where the start and end positions are the same * causes corruption. */ @Test @Throws(IOException::class) fun testSaturatedFileExpansionMovesElements() { val queue = QueueFile(file) // Create test data - 1016-byte blocks marked consecutively 1, 2, 3, 4, 5 and 6, // four of which perfectly fill the queue file, taking into account the file header // and the item headers. // Each item is of length // (QueueFile.INITIAL_LENGTH - QueueFile.HEADER_LENGTH) / 4 - element_header_length // // = 1016 bytes val values = arrayOfNulls<ByteArray>(6) for (blockNum in values.indices) { values[blockNum] = ByteArray(1016) for (i in values[blockNum]!!.indices) { values[blockNum]!![i] = (blockNum + 1).toByte() } } // Saturate the queue file queue.add(values[0]) queue.add(values[1]) queue.add(values[2]) queue.add(values[3]) // Remove an element and add a new one so that the position of the start and // end of the queue are equal queue.remove() queue.add(values[4]) // Cause the queue file to expand queue.add(values[5]) // Make sure values are not corrupted for (i in 1..5) { assertThat(queue.peek()).isEqualTo(values[i]) queue.remove() } queue.close() } /** * Exercise a bug where opening a queue whose first or last element's header was non contiguous * throws an {@link java.io.EOFException}. */ @Test @Throws(IOException::class) fun testReadHeadersFromNonContiguousQueueWorks() { val queueFile = QueueFile(file) // Fill the queue up to `length - 2` (i.e. remainingBytes() == 2). for (i in 0 until 15) { queueFile.add(values[N - 1]) } queueFile.add(values[219]) // Remove first item so we have room to add another one without growing the file. queueFile.remove() // Add any element element and close the queue. queueFile.add(values[6]) val queueSize = queueFile.size() queueFile.close() // File should not be corrupted. val queueFile2 = QueueFile(file) assertThat(queueFile2.size()).isEqualTo(queueFile.size()) } /* @Test public void testOverflow() throws IOException { QueueFile queueFile = new QueueFile(file); // Create a 32k block of test data. byte[] value = new byte[32768]; // Run 32764 iterations = (32768 + 4) * 32764 = 1073741808 bytes. for (int i = 0; i < 32764; i++) { queueFile.add(value); } // Grow the file to 1073741808 + (32768 + 4) = 1073774580 bytes. try { queueFile.add(value); fail("QueueFile should throw error if attempted to grow beyond 1073741824 bytes"); } catch (EOFException e) { assertThat(e).hasMessage("Cannot grow file beyond 1073741824 bytes"); } } */ /** A RandomAccessFile that can break when you go to write the COMMITTED status. */ internal class BrokenRandomAccessFile(file: File, mode: String) : RandomAccessFile(file, mode) { var rejectCommit = true @Throws(IOException::class) override fun write(buffer: ByteArray) { if (rejectCommit && filePointer == 0L) { throw IOException("No commit for you!") } super.write(buffer) } } }
mit
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadTDDs.kt
1
852
package info.nightscout.androidaps.queue.commands import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.queue.Callback import javax.inject.Inject class CommandLoadTDDs( injector: HasAndroidInjector, callback: Callback? ) : Command(injector, CommandType.LOAD_TDD, callback) { @Inject lateinit var activePlugin: ActivePlugin override fun execute() { val pump = activePlugin.activePump val r = pump.loadTDDs() aapsLogger.debug(LTag.PUMPQUEUE, "Result success: " + r.success + " enacted: " + r.enacted) callback?.result(r)?.run() } override fun status(): String = rh.gs(R.string.load_tdds) override fun log(): String = "LOAD TDDs" }
agpl-3.0
esqr/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/Navigator.kt
1
3432
package io.github.feelfreelinux.wykopmobilny.ui.modules import android.app.Activity import io.github.feelfreelinux.wykopmobilny.ui.modules.input.entry.add.AddEntryActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.input.entry.comment.EditEntryCommentActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.input.entry.edit.EditEntryActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.loginscreen.LoginScreenActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.mainnavigation.NavigationActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.entry.EntryActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.feed.tag.TagActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.photoview.PhotoViewActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.pm.conversation.ConversationActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.settings.SettingsActivity interface NavigatorApi { fun openMainActivity(context: Activity, targetFragment: String? = null) fun openEntryDetailsActivity(context : Activity, entryId : Int) fun openTagActivity(context : Activity, tag : String) fun openConversationListActivity(context : Activity, user : String) fun openPhotoViewActivity(context: Activity, url : String) fun openSettingsActivity(context : Activity) fun openLoginScreen(context : Activity, requestCode : Int) fun openAddEntryActivity(context: Activity, receiver : String? = null) fun openEditEntryActivity(context: Activity, body: String, entryId : Int) fun openEditEntryCommentActivity(context: Activity, body: String, entryId : Int, commentId : Int) } class Navigator : NavigatorApi { override fun openMainActivity(context : Activity, targetFragment : String?) { context.startActivity(NavigationActivity.getIntent(context, targetFragment)) } override fun openEntryDetailsActivity(context : Activity, entryId : Int) { context.startActivity(EntryActivity.createIntent(context, entryId, null)) } override fun openTagActivity(context : Activity, tag : String) { context.startActivity(TagActivity.createIntent(context, tag)) } override fun openConversationListActivity(context : Activity, user : String) { context.startActivity(ConversationActivity.createIntent(context, user)) } override fun openPhotoViewActivity(context: Activity, url : String) { context.startActivity(PhotoViewActivity.createIntent(context, url)) } override fun openSettingsActivity(context : Activity) { context.startActivity(SettingsActivity.createIntent(context)) } override fun openLoginScreen(context : Activity, requestCode : Int) { context.startActivityForResult(LoginScreenActivity.createIntent(context), requestCode) } override fun openAddEntryActivity(context: Activity, receiver : String?) { context.startActivity(AddEntryActivity.createIntent(context, receiver)) } override fun openEditEntryActivity(context: Activity, body: String, entryId : Int) { context.startActivity(EditEntryActivity.createIntent(context, body, entryId)) } override fun openEditEntryCommentActivity(context: Activity, body: String, entryId : Int, commentId : Int) { context.startActivity(EditEntryCommentActivity.createIntent(context, body, entryId, commentId)) } }
mit
exponentjs/exponent
packages/expo-media-library/android/src/main/java/expo/modules/medialibrary/albums/AssetFileStrategy.kt
2
1277
package expo.modules.medialibrary.albums import android.content.ContentUris import android.content.Context import android.os.Build import android.provider.MediaStore import expo.modules.medialibrary.EXTERNAL_CONTENT_URI import expo.modules.medialibrary.MediaLibraryUtils import java.io.File import java.io.IOException internal fun interface AssetFileStrategy { @Throws(IOException::class) fun apply(src: File, dir: File, context: Context): File companion object { val copyStrategy = AssetFileStrategy { src, dir, _ -> MediaLibraryUtils.safeCopyFile(src, dir) } val moveStrategy = AssetFileStrategy strategy@{ src, dir, context -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && src is MediaLibraryUtils.AssetFile) { val assetId = src.assetId val assetUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, assetId.toLong()) val newFile = MediaLibraryUtils.safeCopyFile(src, dir) context.contentResolver.delete(assetUri, null) return@strategy newFile } val newFile = MediaLibraryUtils.safeMoveFile(src, dir) context.contentResolver.delete( EXTERNAL_CONTENT_URI, "${MediaStore.MediaColumns.DATA}=?", arrayOf(src.path) ) newFile } } }
bsd-3-clause
Heiner1/AndroidAPS
core/src/main/java/info/nightscout/androidaps/utils/MidnightTime.kt
1
1613
package info.nightscout.androidaps.utils import android.util.LongSparseArray import java.util.* object MidnightTime { val times = LongSparseArray<Long>() private var hits: Long = 0 private var misses: Long = 0 private const val THRESHOLD = 100000 fun calc(): Long { val c = Calendar.getInstance() c[Calendar.HOUR_OF_DAY] = 0 c[Calendar.MINUTE] = 0 c[Calendar.SECOND] = 0 c[Calendar.MILLISECOND] = 0 return c.timeInMillis } fun calcPlusMinutes(minutes: Int): Long { val h = minutes / 60 val m = minutes % 60 val c = Calendar.getInstance() c[Calendar.HOUR_OF_DAY] = h c[Calendar.MINUTE] = m c[Calendar.SECOND] = 0 c[Calendar.MILLISECOND] = 0 return c.timeInMillis } fun calc(time: Long): Long { var m: Long? synchronized(times) { m = times[time] if (m != null) { ++hits return m!! } val c = Calendar.getInstance() c.timeInMillis = time c[Calendar.HOUR_OF_DAY] = 0 c[Calendar.MINUTE] = 0 c[Calendar.SECOND] = 0 c[Calendar.MILLISECOND] = 0 m = c.timeInMillis times.append(time, m) ++misses if (times.size() > THRESHOLD) resetCache() } return m!! } fun resetCache() { hits = 0 misses = 0 times.clear() } fun log(): String = "Hits: " + hits + " misses: " + misses + " stored: " + times.size() }
agpl-3.0
realm/realm-java
realm/kotlin-extensions/src/main/kotlin/io/realm/kotlin/RealmObjectExtensions.kt
1
5579
/* * Copyright 2020 Realm 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 io.realm.kotlin import io.realm.* import io.realm.annotations.Beta import io.realm.internal.RealmObjectProxy import io.realm.rx.ObjectChange import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf /** * Returns a [Flow] that monitors changes to this RealmObject. It will emit the current * RealmObject upon subscription. Object updates will continually be emitted as the RealmObject is * updated - `onCompletion` will never be called. * * Items emitted from Realm flows are frozen - see [RealmObject.freeze]. This means that they are * immutable and can be read from any thread. * * Realm flows always emit items from the thread holding the live RealmObject. This means that if * you need to do further processing, it is recommended to collect the values on a computation * dispatcher: * * ``` * object.toFlow() * .map { obj -> doExpensiveWork(obj) } * .flowOn(Dispatchers.IO) * .onEach { flowObject -> * // ... * }.launchIn(Dispatchers.Main) * ``` * * If your would like `toFlow()` to stop emitting items you can instruct the flow to only emit the * first item by calling [kotlinx.coroutines.flow.first]: * ``` * val foo = object.toFlow() * .flowOn(context) * .first() * ``` * * @return Kotlin [Flow] on which calls to `onEach` or `collect` can be made. */ @Beta fun <T : RealmModel> T?.toFlow(): Flow<T?> { // Return flow with object or null flow if this function is called on null return this?.let { obj -> if (obj is RealmObjectProxy) { val proxy = obj as RealmObjectProxy @Suppress("INACCESSIBLE_TYPE") when (val realm = proxy.`realmGet$proxyState`().`realm$realm`) { is Realm -> realm.configuration.flowFactory.from<T>(realm, obj) is DynamicRealm -> (obj as DynamicRealmObject).let { dynamicRealmObject -> realm.configuration.flowFactory.from(realm, dynamicRealmObject) as Flow<T?> } else -> throw UnsupportedOperationException("${realm.javaClass} is not supported as a candidate for 'toFlow'. Only subclasses of RealmModel/RealmObject can be used.") } } else { // Return a one-time emission in case the object is unmanaged return flowOf(this) } } ?: flowOf(null) } /** * Returns a [Flow] that monitors changes to this RealmObject. It will emit the current * RealmObject upon subscription. For each update to the RealmObject a [ObjectChange] consisting of * a pair with the RealmObject and its corresponding [ObjectChangeSet] will be sent. The changeset * will be `null` the first time the RealmObject is emitted. * * The RealmObject will continually be emitted as it is updated. This flow will never complete. * * Items emitted are frozen (see [RealmObject.freeze]). This means that they are immutable and can * be read on any thread. * * Realm flows always emit items from the thread holding the live Realm. This means that if * you need to do further processing, it is recommended to collect the values on a computation * dispatcher: * * ``` * object.toChangesetFlow() * .map { change -> doExpensiveWork(change) } * .flowOn(Dispatchers.IO) * .onEach { change -> * // ... * }.launchIn(Dispatchers.Main) * ``` * * If you would like `toChangesetFlow()` to stop emitting items you can instruct the flow to only * emit the first item by calling [kotlinx.coroutines.flow.first]: * ``` * val foo = object.toChangesetFlow() * .flowOn(context) * .first() * ``` * * @return Kotlin [Flow] that will never complete. * @throws UnsupportedOperationException if the required coroutines framework is not on the * classpath or the corresponding Realm instance doesn't support flows. * @throws IllegalStateException if the Realm wasn't opened on a Looper thread. */ @Beta fun <T : RealmModel> T?.toChangesetFlow(): Flow<ObjectChange<T>?> { // Return flow with objectchange containing this object or null flow if this function is called on null return this?.let { obj -> if (obj is RealmObjectProxy) { val proxy = obj as RealmObjectProxy @Suppress("INACCESSIBLE_TYPE") when (val realm = proxy.`realmGet$proxyState`().`realm$realm`) { is Realm -> realm.configuration.flowFactory.changesetFrom<T>(realm, obj) is DynamicRealm -> (obj as DynamicRealmObject).let { dynamicRealmObject -> realm.configuration.flowFactory.changesetFrom(realm, dynamicRealmObject) as Flow<ObjectChange<T>?> } else -> throw UnsupportedOperationException("${realm.javaClass} is not supported as a candidate for 'toFlow'. Only subclasses of RealmModel/RealmObject can be used.") } } else { // Return a one-time emission in case the object is unmanaged return flowOf(ObjectChange(this, null)) } } ?: flowOf(null) }
apache-2.0
k9mail/k-9
backend/imap/src/main/java/com/fsck/k9/backend/imap/CommandSearch.kt
2
693
package com.fsck.k9.backend.imap import com.fsck.k9.mail.Flag import com.fsck.k9.mail.store.imap.ImapStore internal class CommandSearch(private val imapStore: ImapStore) { fun search( folderServerId: String, query: String?, requiredFlags: Set<Flag>?, forbiddenFlags: Set<Flag>?, performFullTextSearch: Boolean ): List<String> { val folder = imapStore.getFolder(folderServerId) try { return folder.search(query, requiredFlags, forbiddenFlags, performFullTextSearch) .sortedWith(UidReverseComparator()) .map { it.uid } } finally { folder.close() } } }
apache-2.0
PolymerLabs/arcs
javatests/arcs/android/e2e/testapp/TestActivity.kt
1
13755
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.android.e2e.testapp // TODO(b/170962663) Disabled due to different ordering after copybara transformations. /* ktlint-disable import-ordering */ import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import android.view.View import android.widget.Button import android.widget.RadioButton import android.widget.TextView import arcs.android.devtools.DevToolsStarter import arcs.android.labs.host.AndroidManifestHostRegistry import arcs.core.allocator.Allocator import arcs.core.common.ArcId import arcs.core.data.CollectionType import arcs.core.data.EntityType import arcs.core.data.HandleMode import arcs.core.data.SingletonType import arcs.core.entity.HandleSpec import arcs.core.entity.awaitReady import arcs.core.entity.ForeignReferenceCheckerImpl import arcs.core.host.HandleManagerImpl import arcs.core.host.SimpleSchedulerProvider import arcs.jvm.util.JvmTime import arcs.sdk.ReadWriteCollectionHandle import arcs.sdk.ReadWriteSingletonHandle import arcs.sdk.android.storage.AndroidStorageServiceEndpointManager import arcs.sdk.android.storage.service.DefaultBindHelper import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.MainScope import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext /** Entry UI to launch Arcs Test. */ @OptIn(ExperimentalCoroutinesApi::class) class TestActivity : AppCompatActivity() { private lateinit var resultView1: TextView private lateinit var resultView2: TextView private var result1 = "" private var result2 = "" private val scope: CoroutineScope = MainScope() private val schedulerProvider = SimpleSchedulerProvider(Dispatchers.Default) private var storageMode = TestEntity.StorageMode.IN_MEMORY private var isCollection = false private var setFromRemoteService = false private var singletonHandle: ReadWriteSingletonHandle<TestEntity, TestEntitySlice>? = null private var collectionHandle: ReadWriteCollectionHandle<TestEntity, TestEntitySlice>? = null private var allocator: Allocator? = null private var resurrectionArcId: ArcId? = null val storageEndpointManager = AndroidStorageServiceEndpointManager( scope, DefaultBindHelper(this) ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.test_activity) resultView1 = findViewById<Button>(R.id.result1) resultView2 = findViewById<Button>(R.id.result2) findViewById<Button>(R.id.create).setOnClickListener { scope.launch { createHandle() } } findViewById<Button>(R.id.fetch).setOnClickListener { scope.launch { fetchHandle() } } findViewById<Button>(R.id.set).setOnClickListener { scope.launch { setHandle() } } findViewById<Button>(R.id.clear).setOnClickListener { scope.launch { clearHandle() } } findViewById<RadioButton>(R.id.singleton).setOnClickListener(::onTestOptionClicked) findViewById<RadioButton>(R.id.collection).setOnClickListener(::onTestOptionClicked) findViewById<RadioButton>(R.id.in_memory).setOnClickListener(::onTestOptionClicked) findViewById<RadioButton>(R.id.persistent).setOnClickListener(::onTestOptionClicked) findViewById<RadioButton>(R.id.local).setOnClickListener(::onTestOptionClicked) findViewById<RadioButton>(R.id.remote).setOnClickListener(::onTestOptionClicked) findViewById<Button>(R.id.read_write_test).setOnClickListener { scope.launch { testReadWriteArc() } } findViewById<Button>(R.id.start_resurrection_arc).setOnClickListener { scope.launch { startResurrectionArc() } } findViewById<Button>(R.id.stop_read_service).setOnClickListener { scope.launch { stopReadService() } } findViewById<Button>(R.id.trigger_write).setOnClickListener { scope.launch { triggerWrite() } } findViewById<Button>(R.id.stop_resurrection_arc).setOnClickListener { scope.launch { stopResurrectionArc() } } findViewById<Button>(R.id.persistent_read_write_test).setOnClickListener { scope.launch { runPersistentPersonRecipe() } } DevToolsStarter(this).start() } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) intent?.run { if ([email protected](RESULT_NAME)) { scope.launch { appendResultText([email protected](RESULT_NAME) ?: "") } } } } override fun onDestroy() { val intent = Intent( this, StorageAccessService::class.java ) stopService(intent) scope.cancel() super.onDestroy() } private suspend fun testReadWriteArc() { appendResultText(getString(R.string.waiting_for_result)) allocator = Allocator.create( AndroidManifestHostRegistry.create(this@TestActivity), HandleManagerImpl( time = JvmTime, scheduler = schedulerProvider("readWriteArc"), storageEndpointManager = storageEndpointManager, foreignReferenceChecker = ForeignReferenceCheckerImpl(emptyMap()) ), scope ) allocator?.startArcForPlan(PersonRecipePlan) ?.also { allocator?.stopArc(it.id) } } private suspend fun startResurrectionArc() { appendResultText(getString(R.string.waiting_for_result)) allocator = Allocator.create( AndroidManifestHostRegistry.create(this@TestActivity), HandleManagerImpl( time = JvmTime, scheduler = schedulerProvider("resurrectionArc"), storageEndpointManager = storageEndpointManager, foreignReferenceChecker = ForeignReferenceCheckerImpl(emptyMap()) ), scope ) resurrectionArcId = allocator?.startArcForPlan(AnimalRecipePlan)?.id } private fun stopReadService() { val intent = Intent( this, ReadAnimalHostService::class.java ) stopService(intent) } private fun triggerWrite() { val intent = Intent( this, WriteAnimalHostService::class.java ).apply { putExtra(WriteAnimalHostService.ARC_ID_EXTRA, resurrectionArcId?.toString()) } startService(intent) } private suspend fun stopResurrectionArc() { resurrectionArcId?.let { allocator?.stopArc(it) } } private suspend fun runPersistentPersonRecipe() { appendResultText(getString(R.string.waiting_for_result)) val allocator = Allocator.create( AndroidManifestHostRegistry.create(this@TestActivity), HandleManagerImpl( time = JvmTime, scheduler = schedulerProvider("allocator"), storageEndpointManager = storageEndpointManager, foreignReferenceChecker = ForeignReferenceCheckerImpl(emptyMap()) ), scope ) val arcId = allocator.startArcForPlan(PersonRecipePlan).id allocator.stopArc(arcId) } private fun onTestOptionClicked(view: View) { if (view is RadioButton && view.isChecked) { when (view.getId()) { R.id.singleton -> isCollection = false R.id.collection -> isCollection = true R.id.in_memory -> storageMode = TestEntity.StorageMode.IN_MEMORY R.id.persistent -> storageMode = TestEntity.StorageMode.PERSISTENT R.id.local -> setFromRemoteService = false R.id.remote -> setFromRemoteService = true } } } private suspend fun createHandle() { singletonHandle?.dispatcher?.let { withContext(it) { singletonHandle?.close() } } collectionHandle?.dispatcher?.let { withContext(it) { collectionHandle?.close() } } appendResultText(getString(R.string.waiting_for_result)) val handleManager = HandleManagerImpl( time = JvmTime, scheduler = schedulerProvider("handle"), storageEndpointManager = storageEndpointManager, foreignReferenceChecker = ForeignReferenceCheckerImpl(emptyMap()) ) if (isCollection) { @Suppress("UNCHECKED_CAST") collectionHandle = handleManager.createHandle( HandleSpec( "collectionHandle", HandleMode.ReadWrite, CollectionType(EntityType(TestEntity.SCHEMA)), TestEntity ), when (storageMode) { TestEntity.StorageMode.PERSISTENT -> TestEntity.collectionPersistentStorageKey else -> TestEntity.collectionInMemoryStorageKey } ).awaitReady() as ReadWriteCollectionHandle<TestEntity, TestEntitySlice> collectionHandle?.dispatcher?.let { withContext(it) { collectionHandle?.onReady { scope.launch { fetchAndUpdateResult("onReady") } } collectionHandle?.onUpdate { scope.launch { fetchAndUpdateResult("onUpdate") } } collectionHandle?.onDesync { scope.launch { fetchAndUpdateResult("onDesync") } } collectionHandle?.onResync { scope.launch { fetchAndUpdateResult("onResync") } } } } } else { @Suppress("UNCHECKED_CAST") singletonHandle = handleManager.createHandle( HandleSpec( "singletonHandle", HandleMode.ReadWrite, SingletonType(EntityType(TestEntity.SCHEMA)), TestEntity ), when (storageMode) { TestEntity.StorageMode.PERSISTENT -> TestEntity.singletonPersistentStorageKey else -> TestEntity.singletonInMemoryStorageKey } ).awaitReady() as ReadWriteSingletonHandle<TestEntity, TestEntitySlice> singletonHandle?.dispatcher?.let { withContext(it) { singletonHandle?.onReady { scope.launch { fetchAndUpdateResult("onReady") } } singletonHandle?.onUpdate { scope.launch { fetchAndUpdateResult("onUpdate") } } singletonHandle?.onDesync { scope.launch { fetchAndUpdateResult("onDesync") } } singletonHandle?.onResync { scope.launch { fetchAndUpdateResult("onResync") } } } } } } private suspend fun fetchHandle() { fetchAndUpdateResult("Fetch") } private suspend fun setHandle() { if (setFromRemoteService) { val intent = Intent( this, StorageAccessService::class.java ) intent.putExtra( StorageAccessService.IS_COLLECTION_EXTRA, isCollection ) intent.putExtra( StorageAccessService.STORAGE_MODE_EXTRA, storageMode.ordinal ) intent.putExtra( StorageAccessService.HANDLE_ACTION_EXTRA, StorageAccessService.Action.SET.ordinal ) startService(intent) } else { if (isCollection) { for (i in 0 until 2) { collectionHandle?.dispatcher?.let { withContext(it) { collectionHandle?.store( TestEntity( text = TestEntity.text, number = i.toDouble(), boolean = TestEntity.boolean ) )?.join() } } } } else { singletonHandle?.dispatcher?.let { withContext(it) { singletonHandle?.store( TestEntity( text = TestEntity.text, number = TestEntity.number, boolean = TestEntity.boolean ) )?.join() } } } } } private suspend fun clearHandle() { if (setFromRemoteService) { val intent = Intent( this, StorageAccessService::class.java ) intent.putExtra( StorageAccessService.IS_COLLECTION_EXTRA, isCollection ) intent.putExtra( StorageAccessService.HANDLE_ACTION_EXTRA, StorageAccessService.Action.CLEAR.ordinal ) intent.putExtra( StorageAccessService.STORAGE_MODE_EXTRA, storageMode.ordinal ) startService(intent) } else { singletonHandle?.dispatcher?.let { withContext(it) { singletonHandle?.clear()?.join() } } collectionHandle?.dispatcher?.let { withContext(it) { collectionHandle?.clear()?.join() } } } } private fun fetchAndUpdateResult(prefix: String) { var result: String? = "null" if (isCollection) { collectionHandle?.dispatcher?.let { val testEntities = runBlocking(it) { collectionHandle?.fetchAll() } if (testEntities != null && !testEntities.isNullOrEmpty()) { result = testEntities .sortedBy { it.number } .joinToString(separator = ";") { "${it.text},${it.number},${it.boolean}" } } } } else { singletonHandle?.dispatcher?.let { val testEntity = runBlocking(it) { singletonHandle?.fetch() } result = testEntity?.let { "${it.text},${it.number},${it.boolean}" } } } appendResultText("$prefix:$result") } private fun appendResultText(result: String) { result1 = result2 result2 = result resultView1.text = "1: $result1" resultView2.text = "2: $result2" } companion object { const val RESULT_NAME = "result" } }
bsd-3-clause
AcornUI/Acorn
acornui-core/src/main/kotlin/com/acornui/audio/JsWebAudioSound.kt
1
2855
/* * Copyright 2020 Poly Forest, 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.acornui.audio import com.acornui.time.nowS import org.khronos.webgl.ArrayBuffer import kotlin.time.Duration import kotlin.time.seconds class JsWebAudioSound( private val audioManager: AudioManager, private val context: AudioContext, decodedData: ArrayBuffer, override val priority: Double) : Sound { override var onCompleted: (() -> Unit)? = null private var gain: GainNode private val panner: PannerNode private val audioBufferSourceNode: AudioBufferSourceNode private var _isPlaying: Boolean = false override val isPlaying: Boolean get() = _isPlaying private var _startTime: Double = 0.0 private var _stopTime: Double = 0.0 init { // create a sound source audioBufferSourceNode = context.createBufferSource() audioBufferSourceNode.addEventListener("ended", { complete() }) // Add the buffered data to our object audioBufferSourceNode.buffer = decodedData // Panning panner = context.createPanner() panner.panningModel = PanningModel.EQUAL_POWER.value // Volume gain = context.createGain() gain.gain.value = audioManager.soundVolume // Wire them together. audioBufferSourceNode.connect(panner) panner.connect(gain) panner.setPosition(0.0, 0.0, 1.0) gain.connect(context.destination) audioManager.registerSound(this) } private fun complete() { _stopTime = nowS() _isPlaying = false onCompleted?.invoke() onCompleted = null audioManager.unregisterSound(this) } override var loop: Boolean get() = audioBufferSourceNode.loop set(value) { audioBufferSourceNode.loop = value } private var _volume: Double = 1.0 override var volume: Double get() = _volume set(value) { _volume = value gain.gain.value = com.acornui.math.clamp(value * audioManager.soundVolume, 0.0, 1.0) } override fun setPosition(x: Double, y: Double, z: Double) { panner.setPosition(x, y, z) } override fun start() { audioBufferSourceNode.start(context.currentTime) _startTime = nowS() } override fun stop() { audioBufferSourceNode.stop(0.0) } override val currentTime: Duration get() { return if (!_isPlaying) (_stopTime - _startTime).seconds else (nowS() - _startTime).seconds } override fun dispose() { stop() } }
apache-2.0
blindpirate/gradle
subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/KotlinBuildScriptPatternTest.kt
3
2649
/* * Copyright 2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import kotlin.reflect.KClass import kotlin.reflect.full.findAnnotation import kotlin.script.templates.ScriptTemplateDefinition @RunWith(Parameterized::class) class KotlinBuildScriptPatternTest(val script: Script) { enum class ScriptType { BUILD, INIT, SETTINGS } data class Script(val name: String, val type: ScriptType) companion object { @Parameterized.Parameters(name = "{0}") @JvmStatic fun scripts(): Iterable<Script> = listOf( Script("settings.gradle.kts", ScriptType.SETTINGS), Script("my.settings.gradle.kts", ScriptType.SETTINGS), Script("init.gradle.kts", ScriptType.INIT), Script("my.init.gradle.kts", ScriptType.INIT), Script("build.gradle.kts", ScriptType.BUILD), Script("no-settings.gradle.kts", ScriptType.BUILD), Script("no-init.gradle.kts", ScriptType.BUILD), Script("anything.gradle.kts", ScriptType.BUILD), ) } @Test fun `recognizes build scripts`() { checkScriptRecognizedBy(KotlinBuildScript::class, ScriptType.BUILD) } @Test fun `recognizes settings scripts`() { checkScriptRecognizedBy(KotlinSettingsScript::class, ScriptType.SETTINGS) } @Test fun `recognizes init scripts`() { checkScriptRecognizedBy(KotlinInitScript::class, ScriptType.INIT) } private fun checkScriptRecognizedBy(scriptParserClass: KClass<*>, supportedScriptType: ScriptType) { val buildScriptPattern = scriptParserClass.findAnnotation<ScriptTemplateDefinition>()!!.scriptFilePattern val shouldMatch = script.type == supportedScriptType assertEquals("${script.name} should${if (shouldMatch) "" else " not"} match $buildScriptPattern", shouldMatch, script.name.matches(buildScriptPattern.toRegex())) } }
apache-2.0
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/expressions/DictionaryExpression.kt
1
1508
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.vimscript.model.expressions import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.vimscript.model.VimLContext import com.maddyhome.idea.vim.vimscript.model.datatypes.VimDataType import com.maddyhome.idea.vim.vimscript.model.datatypes.VimDictionary import com.maddyhome.idea.vim.vimscript.model.datatypes.VimFuncref import com.maddyhome.idea.vim.vimscript.model.datatypes.VimString import com.maddyhome.idea.vim.vimscript.model.functions.DefinedFunctionHandler data class DictionaryExpression(val dictionary: LinkedHashMap<Expression, Expression>) : Expression() { override fun evaluate(editor: VimEditor, context: ExecutionContext, vimContext: VimLContext): VimDataType { val dict = VimDictionary(linkedMapOf()) for ((key, value) in dictionary) { val evaluatedVal = value.evaluate(editor, context, vimContext) var newFuncref = evaluatedVal if (evaluatedVal is VimFuncref && evaluatedVal.handler is DefinedFunctionHandler && !evaluatedVal.isSelfFixed) { newFuncref = evaluatedVal.copy() newFuncref.dictionary = dict } dict.dictionary[VimString(key.evaluate(editor, context, vimContext).asString())] = newFuncref } return dict } }
mit
JStege1206/AdventOfCode
aoc-archetype/src/main/resources/archetype-resources/src/main/kotlin/days/Day11.kt
1
285
package ${package}.days import nl.jstege.adventofcode.aoccommon.days.Day class Day11 : Day(title = "") { override fun first(input: Sequence<String>): Any { TODO("Implement") } override fun second(input: Sequence<String>): Any { TODO("Implement") } }
mit
theScrabi/NewPipe
app/src/test/java/org/schabi/newpipe/settings/ContentSettingsManagerTest.kt
1
2736
package org.schabi.newpipe.settings import android.content.SharedPreferences import org.junit.Assert import org.junit.Assume import org.junit.Before import org.junit.BeforeClass import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Suite import org.mockito.Mockito import org.mockito.Mockito.`when` import org.mockito.junit.MockitoJUnitRunner import org.schabi.newpipe.settings.ContentSettingsManagerTest.ExportTest import java.io.File import java.io.ObjectInputStream import java.util.zip.ZipFile @RunWith(Suite::class) @Suite.SuiteClasses(ExportTest::class) class ContentSettingsManagerTest { @RunWith(MockitoJUnitRunner::class) class ExportTest { companion object { private lateinit var newpipeDb: File private lateinit var newpipeSettings: File @JvmStatic @BeforeClass fun setupFiles() { val dbPath = ExportTest::class.java.classLoader?.getResource("settings/newpipe.db")?.file val settingsPath = ExportTest::class.java.classLoader?.getResource("settings/newpipe.settings")?.path Assume.assumeNotNull(dbPath) Assume.assumeNotNull(settingsPath) newpipeDb = File(dbPath!!) newpipeSettings = File(settingsPath!!) } } private lateinit var preferences: SharedPreferences @Before fun setupMocks() { preferences = Mockito.mock(SharedPreferences::class.java, Mockito.withSettings().stubOnly()) } @Test fun `The settings must be exported successfully in the correct format`() { val expectedPreferences = mapOf("such pref" to "much wow") `when`(preferences.all).thenReturn(expectedPreferences) val manager = ContentSettingsManager(newpipeDb, newpipeSettings) val output = File.createTempFile("newpipe_", "") manager.exportDatabase(preferences, output.absolutePath) val zipFile = ZipFile(output.absoluteFile) val entries = zipFile.entries().toList() Assert.assertEquals(2, entries.size) zipFile.getInputStream(entries.first { it.name == "newpipe.db" }).use { actual -> newpipeDb.inputStream().use { expected -> Assert.assertEquals(expected.reader().readText(), actual.reader().readText()) } } zipFile.getInputStream(entries.first { it.name == "newpipe.settings" }).use { actual -> val actualPreferences = ObjectInputStream(actual).readObject() Assert.assertEquals(expectedPreferences, actualPreferences) } } } }
gpl-3.0
wordpress-mobile/WordPress-Android
WordPress/src/test/java/org/wordpress/android/ui/domains/DomainRegistrationMainViewModelTest.kt
1
3379
package org.wordpress.android.ui.domains import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.mockito.Mock import org.wordpress.android.BaseUnitTest import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.ui.domains.DomainRegistrationActivity.DomainRegistrationPurpose.AUTOMATED_TRANSFER import org.wordpress.android.ui.domains.DomainRegistrationActivity.DomainRegistrationPurpose.CTA_DOMAIN_CREDIT_REDEMPTION import org.wordpress.android.ui.domains.DomainRegistrationActivity.DomainRegistrationPurpose.DOMAIN_PURCHASE import org.wordpress.android.ui.domains.DomainRegistrationNavigationAction.FinishDomainRegistration import org.wordpress.android.ui.domains.DomainRegistrationNavigationAction.OpenDomainRegistrationDetails import org.wordpress.android.ui.domains.DomainRegistrationNavigationAction.OpenDomainRegistrationResult import org.wordpress.android.ui.domains.DomainRegistrationNavigationAction.OpenDomainSuggestions import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper class DomainRegistrationMainViewModelTest : BaseUnitTest() { @Mock lateinit var tracker: AnalyticsTrackerWrapper @Mock lateinit var site: SiteModel private lateinit var viewModel: DomainRegistrationMainViewModel private val testDomainProductDetails = DomainProductDetails(76, "testdomain.blog") private val domainRegisteredEvent = DomainRegistrationCompletedEvent("testdomain.blog", "[email protected]") private val navigationActions = mutableListOf<DomainRegistrationNavigationAction>() @Before fun setUp() { viewModel = DomainRegistrationMainViewModel(tracker) viewModel.onNavigation.observeForever { it.applyIfNotHandled { navigationActions.add(this) } } } @Test fun `domain suggestions are visible at start`() { viewModel.start(site, CTA_DOMAIN_CREDIT_REDEMPTION) assertThat(navigationActions).containsOnly(OpenDomainSuggestions) } @Test fun `selecting domain opens registration details`() { viewModel.start(site, CTA_DOMAIN_CREDIT_REDEMPTION) viewModel.selectDomain(testDomainProductDetails) assertThat(navigationActions.last()).isEqualTo(OpenDomainRegistrationDetails(testDomainProductDetails)) } @Test fun `completing domain registration when registration purpose is credit redemption opens registration result`() { viewModel.start(site, CTA_DOMAIN_CREDIT_REDEMPTION) viewModel.completeDomainRegistration(domainRegisteredEvent) assertThat(navigationActions.last()).isEqualTo(OpenDomainRegistrationResult(domainRegisteredEvent)) } @Test fun `completing domain registration when registration purpose is domain purchase opens registration result`() { viewModel.start(site, DOMAIN_PURCHASE) viewModel.completeDomainRegistration(domainRegisteredEvent) assertThat(navigationActions.last()).isEqualTo(OpenDomainRegistrationResult(domainRegisteredEvent)) } @Test fun `completing domain registration when registration purpose is automated transfer finishes flow`() { viewModel.start(site, AUTOMATED_TRANSFER) viewModel.completeDomainRegistration(domainRegisteredEvent) assertThat(navigationActions.last()).isEqualTo(FinishDomainRegistration(domainRegisteredEvent)) } }
gpl-2.0
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/ui/fragments/settings/BaseSettingFragment.kt
1
1635
package forpdateam.ru.forpda.ui.fragments.settings import android.os.Bundle import androidx.preference.PreferenceFragmentCompat import androidx.recyclerview.widget.RecyclerView import forpdateam.ru.forpda.App import forpdateam.ru.forpda.ui.activities.SettingsActivity /** * Created by radiationx on 24.09.17. */ open class BaseSettingFragment : PreferenceFragmentCompat() { private var listScrollY = 0 private var lastIsVisible = false override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) view?.findViewById<androidx.recyclerview.widget.RecyclerView>(androidx.preference.R.id.recycler_view)?.also { list -> list.setPadding(0, 0, 0, 0) list.addOnScrollListener(object : androidx.recyclerview.widget.RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: androidx.recyclerview.widget.RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) listScrollY = recyclerView.computeVerticalScrollOffset() updateToolbarShadow() } }) } updateToolbarShadow() setDividerHeight(0) } private fun updateToolbarShadow() { val isVisible = listScrollY > 0 if (lastIsVisible != isVisible) { (activity as? SettingsActivity)?.supportActionBar?.elevation = if (isVisible) App.px2.toFloat() else 0f lastIsVisible = isVisible } } }
gpl-3.0
mdaniel/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceJavaStaticMethodWithKotlinAnalog/math/signum.kt
9
64
// WITH_STDLIB fun test(x: Double) { Math.<caret>signum(x) }
apache-2.0
kelsos/mbrc
app/src/main/kotlin/com/kelsos/mbrc/ui/navigation/library/albums/BrowseAlbumFragment.kt
1
3909
package com.kelsos.mbrc.ui.navigation.library.albums import android.os.Bundle import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import androidx.core.view.isGone import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import butterknife.BindView import butterknife.ButterKnife import com.google.android.material.snackbar.Snackbar import com.kelsos.mbrc.R import com.kelsos.mbrc.adapters.AlbumEntryAdapter import com.kelsos.mbrc.annotations.Queue import com.kelsos.mbrc.data.library.Album import com.kelsos.mbrc.helper.PopupActionHandler import com.kelsos.mbrc.ui.navigation.library.LibraryActivity.Companion.LIBRARY_SCOPE import com.kelsos.mbrc.ui.widgets.EmptyRecyclerView import com.raizlabs.android.dbflow.list.FlowCursorList import toothpick.Toothpick import toothpick.smoothie.module.SmoothieActivityModule import javax.inject.Inject class BrowseAlbumFragment : Fragment(), BrowseAlbumView, AlbumEntryAdapter.MenuItemSelectedListener { @BindView(R.id.library_data_list) lateinit var recycler: EmptyRecyclerView @BindView(R.id.empty_view) lateinit var emptyView: View @BindView(R.id.list_empty_title) lateinit var emptyTitle: TextView @Inject lateinit var adapter: AlbumEntryAdapter @Inject lateinit var actionHandler: PopupActionHandler @Inject lateinit var presenter: BrowseAlbumPresenter private lateinit var syncButton: Button; override fun search(term: String) { syncButton.isGone = term.isNotEmpty() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_library_search, container, false) ButterKnife.bind(this, view) emptyTitle.setText(R.string.albums_list_empty) syncButton = view.findViewById<Button>(R.id.list_empty_sync); syncButton.setOnClickListener { presenter.sync() } return view } override fun onStart() { super.onStart() presenter.attach(this) adapter.refresh() } override fun onResume() { super.onResume() adapter.refresh() } override fun onCreate(savedInstanceState: Bundle?) { val scope = Toothpick.openScopes(requireActivity().application, LIBRARY_SCOPE, activity, this) scope.installModules( SmoothieActivityModule(requireActivity()), BrowseAlbumModule() ) super.onCreate(savedInstanceState) Toothpick.inject(this, scope) presenter.attach(this) presenter.load() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recycler.adapter = adapter recycler.emptyView = emptyView recycler.layoutManager = LinearLayoutManager(recycler.context) recycler.setHasFixedSize(true) adapter.setMenuItemSelectedListener(this) } override fun onMenuItemSelected(menuItem: MenuItem, album: Album) { val action = actionHandler.albumSelected(menuItem, album, requireActivity()) if (action != Queue.PROFILE) { presenter.queue(action, album) } } override fun onItemClicked(album: Album) { actionHandler.albumSelected(album, requireActivity()) } override fun onStop() { super.onStop() presenter.detach() } override fun update(cursor: FlowCursorList<Album>) { adapter.update(cursor) } override fun queue(success: Boolean, tracks: Int) { val message = if (success) { getString(R.string.queue_result__success, tracks) } else { getString(R.string.queue_result__failure) } Snackbar.make(recycler, R.string.queue_result__success, Snackbar.LENGTH_SHORT) .setText(message) .show() } override fun onDestroy() { Toothpick.closeScope(this) super.onDestroy() } }
gpl-3.0
ingokegel/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/implement/inner.kt
9
192
// "Implement abstract class" "true" // WITH_STDLIB // SHOULD_BE_AVAILABLE_AFTER_EXECUTION class Container { inner abstract class <caret>Base { abstract fun foo(): String } }
apache-2.0
mdaniel/intellij-community
plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/sequence/exec/KotlinTraceTestCase.kt
1
6849
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.test.sequence.exec import com.intellij.debugger.engine.evaluation.EvaluationContextImpl import com.intellij.debugger.impl.OutputChecker import com.intellij.debugger.streams.lib.LibrarySupportProvider import com.intellij.debugger.streams.psi.DebuggerPositionResolver import com.intellij.debugger.streams.psi.impl.DebuggerPositionResolverImpl import com.intellij.debugger.streams.trace.* import com.intellij.debugger.streams.trace.impl.TraceResultInterpreterImpl import com.intellij.debugger.streams.wrapper.StreamChain import com.intellij.debugger.streams.wrapper.StreamChainBuilder import com.intellij.execution.process.ProcessOutputTypes import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.util.Computable import com.intellij.xdebugger.XDebugSessionListener import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinEvaluator import org.jetbrains.kotlin.idea.debugger.test.KotlinDescriptorTestCaseWithStepping import org.jetbrains.kotlin.idea.debugger.test.TestFiles import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferences import java.util.concurrent.atomic.AtomicBoolean abstract class KotlinTraceTestCase : KotlinDescriptorTestCaseWithStepping() { private companion object { val DEFAULT_CHAIN_SELECTOR = ChainSelector.byIndex(0) } private lateinit var traceChecker: StreamTraceChecker override fun initOutputChecker(): OutputChecker { traceChecker = StreamTraceChecker(this) return super.initOutputChecker() } abstract val librarySupportProvider: LibrarySupportProvider override fun doMultiFileTest(files: TestFiles, preferences: DebuggerPreferences) { // Sequence expressions are verbose. Disable expression logging for sequence debugger KotlinEvaluator.LOG_COMPILATIONS = false val session = debuggerSession.xDebugSession ?: kotlin.test.fail("XDebugSession is null") assertNotNull(session) val completed = AtomicBoolean(false) val positionResolver = getPositionResolver() val chainBuilder = getChainBuilder() val resultInterpreter = getResultInterpreter() val expressionBuilder = getExpressionBuilder() val chainSelector = DEFAULT_CHAIN_SELECTOR session.addSessionListener(object : XDebugSessionListener { override fun sessionPaused() { if (completed.getAndSet(true)) { resume() return } try { sessionPausedImpl() } catch (t: Throwable) { println("Exception caught: $t, ${t.message}", ProcessOutputTypes.SYSTEM) t.printStackTrace() resume() } } private fun sessionPausedImpl() { printContext(debugProcess.debuggerContext) val chain = ApplicationManager.getApplication().runReadAction( Computable<StreamChain> { val elementAtBreakpoint = positionResolver.getNearestElementToBreakpoint(session) val chains = if (elementAtBreakpoint == null) null else chainBuilder.build(elementAtBreakpoint) if (chains.isNullOrEmpty()) null else chainSelector.select(chains) }) if (chain == null) { complete(null, null, null, FailureReason.CHAIN_CONSTRUCTION) return } EvaluateExpressionTracer(session, expressionBuilder, resultInterpreter).trace(chain, object : TracingCallback { override fun evaluated(result: TracingResult, context: EvaluationContextImpl) { complete(chain, result, null, null) } override fun evaluationFailed(traceExpression: String, message: String) { complete(chain, null, message, FailureReason.EVALUATION) } override fun compilationFailed(traceExpression: String, message: String) { complete(chain, null, message, FailureReason.COMPILATION) } }) } private fun complete(chain: StreamChain?, result: TracingResult?, error: String?, errorReason: FailureReason?) { try { if (error != null) { assertNotNull(errorReason) assertNotNull(chain) throw AssertionError(error) } else { assertNull(errorReason) handleSuccess(chain, result) } } catch (t: Throwable) { println("Exception caught: " + t + ", " + t.message, ProcessOutputTypes.SYSTEM) } finally { resume() } } private fun resume() { ApplicationManager.getApplication().invokeLater { session.resume() } } }, testRootDisposable) } private fun getPositionResolver(): DebuggerPositionResolver { return DebuggerPositionResolverImpl() } protected fun handleSuccess(chain: StreamChain?, result: TracingResult?) { kotlin.test.assertNotNull(chain) kotlin.test.assertNotNull(result) println(chain.text, ProcessOutputTypes.SYSTEM) val trace = result.trace traceChecker.checkChain(trace) val resolvedTrace = result.resolve(librarySupportProvider.librarySupport.resolverFactory) traceChecker.checkResolvedChain(resolvedTrace) } private fun getResultInterpreter(): TraceResultInterpreter { return TraceResultInterpreterImpl(librarySupportProvider.librarySupport.interpreterFactory) } private fun getChainBuilder(): StreamChainBuilder { return librarySupportProvider.chainBuilder } private fun getExpressionBuilder(): TraceExpressionBuilder { return librarySupportProvider.getExpressionBuilder(project) } protected enum class FailureReason { COMPILATION, EVALUATION, CHAIN_CONSTRUCTION } @FunctionalInterface protected interface ChainSelector { fun select(chains: List<StreamChain>): StreamChain companion object { fun byIndex(index: Int): ChainSelector { return object : ChainSelector { override fun select(chains: List<StreamChain>): StreamChain = chains[index] } } } } }
apache-2.0
ingokegel/intellij-community
plugins/kotlin/j2k/new/tests/testData/newJ2k/strings/formattedString.kt
13
171
object A { const val TEXT1 = "text1.\n" + "text2\n" + "text3" const val TEXT2 = ("text1\n" + "text2\n" + "text3") }
apache-2.0
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/common/TimePickerDialogViewController.kt
1
3299
package io.ipoli.android.common import android.annotation.SuppressLint import android.os.Bundle import android.support.v7.app.AlertDialog import android.view.LayoutInflater import android.view.View import android.widget.TimePicker import io.ipoli.android.R import io.ipoli.android.common.datetime.Time import io.ipoli.android.common.redux.Action import io.ipoli.android.common.redux.BaseViewState import io.ipoli.android.common.view.BaseDialogController /** * Created by Polina Zhelyazkova <[email protected]> * on 6/1/18. */ sealed class TimePickerDialogAction : Action object TimePickerDialogReducer : BaseViewStateReducer<TimePickerDialogViewState>() { override val stateKey = key<TimePickerDialogViewState>() override fun reduce( state: AppState, subState: TimePickerDialogViewState, action: Action ): TimePickerDialogViewState { return subState } override fun defaultState() = TimePickerDialogViewState( type = TimePickerDialogViewState.StateType.LOADING ) } data class TimePickerDialogViewState( val type: StateType ) : BaseViewState() { enum class StateType { LOADING } } @Suppress("DEPRECATION") class TimePickerDialogViewController(args: Bundle? = null) : BaseDialogController(args) { private var time: Time? = null private var shouldUse24HourFormat: Boolean = false private lateinit var listener: (Time?) -> Unit private var showNeutral: Boolean = true private var onDismissListener: (() -> Unit)? = null constructor( time: Time? = null, shouldUse24HourFormat: Boolean, showNeutral: Boolean = false, listener: (Time?) -> Unit ) : this() { this.time = time this.showNeutral = showNeutral this.shouldUse24HourFormat = shouldUse24HourFormat this.listener = listener } @SuppressLint("InflateParams") override fun onCreateContentView(inflater: LayoutInflater, savedViewState: Bundle?): View { val view = inflater.inflate(R.layout.dialog_time_picker, null) (view as TimePicker).setIs24HourView(shouldUse24HourFormat) time?.let { view.currentHour = it.hours view.currentMinute = it.getMinutes() } return view } override fun onCreateDialog( dialogBuilder: AlertDialog.Builder, contentView: View, savedViewState: Bundle? ): AlertDialog { val builder = dialogBuilder .setCustomTitle(null) .setPositiveButton(R.string.dialog_ok) { _, _ -> listener( Time.at( (contentView as TimePicker).currentHour, contentView.currentMinute ) ) } .setNegativeButton(R.string.cancel, null) if (showNeutral) { builder.setNeutralButton(R.string.do_not_know) { _, _ -> listener(null) } } return builder.create() } override fun createHeaderView(inflater: LayoutInflater): View? = null fun setOnDismissListener(onDismiss: () -> Unit) { this.onDismissListener = onDismiss } override fun onDismiss() { onDismissListener?.invoke() } }
gpl-3.0
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/pet/usecase/EquipPetItemUseCase.kt
1
880
package io.ipoli.android.pet.usecase import io.ipoli.android.common.UseCase import io.ipoli.android.pet.PetItem import io.ipoli.android.player.data.Player import io.ipoli.android.player.persistence.PlayerRepository /** * Created by Venelin Valkov <[email protected]> * on 12/13/17. */ class EquipPetItemUseCase(private val playerRepository: PlayerRepository) : UseCase<EquipPetItemUseCase.Params, Player> { override fun execute(parameters: Params): Player { val item = parameters.item val player = playerRepository.find() requireNotNull(player) val petAvatar = player!!.pet.avatar require(player.inventory.getPet(petAvatar).hasItem(item)) return playerRepository.save( player.copy( pet = player.pet.equipItem(item) ) ) } data class Params(val item: PetItem) }
gpl-3.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/inline/inlineVariableOrProperty/localVariableOnDeclaration2.kt
2
83
fun simpleFun(): String { val s<caret> = "string" val s2 = s return s }
apache-2.0
GunoH/intellij-community
plugins/eclipse/src/org/jetbrains/idea/eclipse/codeStyleMapping/mappingDefinitions/EclipseBracePositionsMappingDefinition.kt
8
2936
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.idea.eclipse.codeStyleMapping.mappingDefinitions import org.jetbrains.idea.eclipse.codeStyleMapping.EclipseJavaCodeStyleMappingDefinitionBuilder import org.jetbrains.idea.eclipse.codeStyleMapping.util.SettingsMappingHelpers.const import org.jetbrains.idea.eclipse.codeStyleMapping.util.SettingsMappingHelpers.field import org.jetbrains.idea.eclipse.codeStyleMapping.util.SettingsMappingHelpers.compute import org.jetbrains.idea.eclipse.codeStyleMapping.util.convertBoolean import org.jetbrains.idea.eclipse.codeStyleMapping.util.doNotImport import org.jetbrains.idea.eclipse.codeStyleMapping.valueConversions.convertBracePosition import org.jetbrains.idea.eclipse.importer.EclipseFormatterOptions.VALUE_END_OF_LINE internal fun EclipseJavaCodeStyleMappingDefinitionBuilder.addBracePositionsMapping() { "brace_position_for_type_declaration" mapTo field(common::CLASS_BRACE_STYLE) .convertBracePosition() "brace_position_for_anonymous_type_declaration" mapTo field(common::CLASS_BRACE_STYLE) .doNotImport() .convertBracePosition() "brace_position_for_constructor_declaration" mapTo field(common::METHOD_BRACE_STYLE) .doNotImport() .convertBracePosition() "brace_position_for_method_declaration" mapTo field(common::METHOD_BRACE_STYLE) .convertBracePosition() "brace_position_for_enum_declaration" mapTo field(common::CLASS_BRACE_STYLE) .doNotImport() .convertBracePosition() "brace_position_for_enum_constant" mapTo field(common::BRACE_STYLE) .doNotImport() .convertBracePosition() "brace_position_for_record_declaration" mapTo field(common::CLASS_BRACE_STYLE) .doNotImport() .convertBracePosition() "brace_position_for_record_constructor" mapTo field(common::METHOD_BRACE_STYLE) .doNotImport() .convertBracePosition() "brace_position_for_annotation_type_declaration" mapTo field(common::CLASS_BRACE_STYLE) .doNotImport() .convertBracePosition() "brace_position_for_block" mapTo field(common::BRACE_STYLE) .convertBracePosition() "brace_position_for_block_in_case" mapTo field(common::BRACE_STYLE) .doNotImport() .convertBracePosition() "brace_position_for_switch" mapTo field(common::BRACE_STYLE) .doNotImport() .convertBracePosition() "brace_position_for_array_initializer" mapTo compute( import = { _ -> common.ARRAY_INITIALIZER_LBRACE_ON_NEXT_LINE = false common.ARRAY_INITIALIZER_RBRACE_ON_NEXT_LINE = false }, export = { VALUE_END_OF_LINE } ) "keep_empty_array_initializer_on_one_line" mapTo const(true) .convertBoolean() "brace_position_for_lambda_body" mapTo field(common::LAMBDA_BRACE_STYLE) .convertBracePosition() }
apache-2.0
GunoH/intellij-community
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/KotlinFocusModeProvider.kt
3
1044
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.core import com.intellij.codeInsight.daemon.impl.focusMode.FocusModeProvider import com.intellij.openapi.util.Segment import com.intellij.psi.PsiAnonymousClass import com.intellij.psi.PsiFile import com.intellij.psi.SyntaxTraverser import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClass class KotlinFocusModeProvider : FocusModeProvider { override fun calcFocusZones(file: PsiFile): MutableList<out Segment> = SyntaxTraverser.psiTraverser(file) .postOrderDfsTraversal() .filter { it is KtClassOrObject || it is KtFunction || it is KtClassInitializer } .filter { val p = it.parent p is KtFile || p is KtClassBody } .map { it.textRange }.toMutableList() }
apache-2.0
andrewoma/dexx
collection/src/test/java/com/github/andrewoma/dexx/collection/ArrayListTest.kt
1
1320
/* * Copyright (c) 2014 Andrew O'Malley * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.andrewoma.dexx.collection class ArrayListTest() : AbstractListTest() { override fun <T> factory(): BuilderFactory<T, out List<T>> { return ArrayList.factory() } }
mit
pdvrieze/kotlinsql
monadic/src/main/kotlin/io/github/pdvrieze/kotlinsql/monadic/actions/Actions.kt
1
2237
/* * Copyright (c) 2020. * * This file is part of kotlinsql. * * This file is licenced to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You should have received a copy of the license with the source distribution. * Alternatively, you may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.github.pdvrieze.kotlinsql.monadic.actions import io.github.pdvrieze.kotlinsql.ddl.Column import io.github.pdvrieze.kotlinsql.ddl.Database import io.github.pdvrieze.kotlinsql.ddl.IColumnType import io.github.pdvrieze.kotlinsql.UnmanagedSql import io.github.pdvrieze.kotlinsql.dml.* import io.github.pdvrieze.kotlinsql.dml.impl._Where import io.github.pdvrieze.kotlinsql.monadic.* import io.github.pdvrieze.kotlinsql.monadic.actions.impl.LazyDataActionImpl import io.github.pdvrieze.kotlinsql.monadic.actions.impl.SelectActionImpl import io.github.pdvrieze.kotlinsql.monadic.actions.impl.TransformActionImpl @Suppress("FunctionName") fun <DB : Database, S : Select> SelectAction<DB, S>.WHERE(config: _Where.() -> WhereClause?): SelectAction<DB, S> { @Suppress("UNCHECKED_CAST") val n = query.WHERE(config) as S return SelectActionImpl(n) } fun <DB : Database, S : Select1<T1, S1, C1>, R, T1 : Any, S1 : IColumnType<T1, S1, C1>, C1 : Column<T1, S1, C1>> SelectAction<DB, S>.mapSeq(transform: (Sequence<T1?>) -> R): DBAction<DB, R> { @OptIn(UnmanagedSql::class) return map { rs -> transform(sequence { while (rs.next()) { yield(rs.rowData.value(query.select.col1, 1)) } }) } } fun <DB : Database, S : Select1<T1, S1, C1>, T1 : Any, S1 : IColumnType<T1, S1, C1>, C1 : Column<T1, S1, C1>> SelectAction<DB, S>.transform(): DBAction<DB, List<T1?>> { return mapSeq { it.toList() } }
apache-2.0
cfieber/orca
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/StartStageHandler.kt
1
7567
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.fasterxml.jackson.databind.ObjectMapper import com.netflix.spectator.api.Registry import com.netflix.spinnaker.orca.ExecutionStatus.NOT_STARTED import com.netflix.spinnaker.orca.ExecutionStatus.RUNNING import com.netflix.spinnaker.orca.events.StageStarted import com.netflix.spinnaker.orca.exceptions.ExceptionHandler import com.netflix.spinnaker.orca.ext.* import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilderFactory import com.netflix.spinnaker.orca.pipeline.expressions.PipelineExpressionEvaluator import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.pipeline.model.OptionalStageSupport import com.netflix.spinnaker.orca.pipeline.model.Stage import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor import com.netflix.spinnaker.orca.pipeline.util.StageNavigator import com.netflix.spinnaker.orca.q.* import com.netflix.spinnaker.q.AttemptsAttribute import com.netflix.spinnaker.q.MaxAttemptsAttribute import com.netflix.spinnaker.q.Queue import org.springframework.beans.factory.annotation.Qualifier import org.springframework.beans.factory.annotation.Value import org.springframework.context.ApplicationEventPublisher import org.springframework.stereotype.Component import java.time.Clock import java.time.Duration import java.time.Instant import kotlin.collections.set @Component class StartStageHandler( override val queue: Queue, override val repository: ExecutionRepository, override val stageNavigator: StageNavigator, override val stageDefinitionBuilderFactory: StageDefinitionBuilderFactory, override val contextParameterProcessor: ContextParameterProcessor, @Qualifier("queueEventPublisher") private val publisher: ApplicationEventPublisher, private val exceptionHandlers: List<ExceptionHandler>, @Qualifier("mapper") private val objectMapper: ObjectMapper, private val clock: Clock, private val registry: Registry, @Value("\${queue.retry.delay.ms:15000}") retryDelayMs: Long ) : OrcaMessageHandler<StartStage>, StageBuilderAware, ExpressionAware, AuthenticationAware { private val retryDelay = Duration.ofMillis(retryDelayMs) override fun handle(message: StartStage) { message.withStage { stage -> if (stage.anyUpstreamStagesFailed()) { // this only happens in restart scenarios log.warn("Tried to start stage ${stage.id} but something upstream had failed (executionId: ${message.executionId})") queue.push(CompleteExecution(message)) } else if (stage.allUpstreamStagesComplete()) { if (stage.status != NOT_STARTED) { log.warn("Ignoring $message as stage is already ${stage.status}") } else if (stage.shouldSkip()) { queue.push(SkipStage(message)) } else if (stage.isAfterStartTimeExpiry()) { log.warn("Stage is being skipped because its start time is after TTL (stageId: ${stage.id}, executionId: ${message.executionId})") queue.push(SkipStage(stage)) } else { try { stage.withAuth { stage.plan() } stage.status = RUNNING stage.startTime = clock.millis() repository.storeStage(stage) stage.start() publisher.publishEvent(StageStarted(this, stage)) trackResult(stage) } catch(e: Exception) { val exceptionDetails = exceptionHandlers.shouldRetry(e, stage.name) if (exceptionDetails?.shouldRetry == true) { val attempts = message.getAttribute<AttemptsAttribute>()?.attempts ?: 0 log.warn("Error planning ${stage.type} stage for ${message.executionType}[${message.executionId}] (attempts: $attempts)") message.setAttribute(MaxAttemptsAttribute(40)) queue.push(message, retryDelay) } else { log.error("Error running ${stage.type} stage for ${message.executionType}[${message.executionId}]", e) stage.apply { context["exception"] = exceptionDetails context["beforeStagePlanningFailed"] = true } repository.storeStage(stage) queue.push(CompleteStage(message)) } } } } else { log.warn("Re-queuing $message as upstream stages are not yet complete") queue.push(message, retryDelay) } } } private fun trackResult(stage: Stage) { // We only want to record invocations of parent-level stages; not synthetics if (stage.parentStageId != null) { return } val id = registry.createId("stage.invocations") .withTag("type", stage.type) .withTag("application", stage.execution.application) .let { id -> // TODO rz - Need to check synthetics for their cloudProvider. stage.context["cloudProvider"]?.let { id.withTag("cloudProvider", it.toString()) } ?: id } registry.counter(id).increment() } override val messageType = StartStage::class.java private fun Stage.plan() { builder().let { builder -> builder.buildTasks(this) builder.buildBeforeStages(this) { it: Stage -> repository.addStage(it.withMergedContext()) } } } private fun Stage.start() { val beforeStages = firstBeforeStages() if (beforeStages.isEmpty()) { val task = firstTask() if (task == null) { // TODO: after stages are no longer planned at this point. We could skip this val afterStages = firstAfterStages() if (afterStages.isEmpty()) { queue.push(CompleteStage(this)) } else { afterStages.forEach { queue.push(StartStage(it)) } } } else { queue.push(StartTask(this, task.id)) } } else { beforeStages.forEach { queue.push(StartStage(it)) } } } private fun Stage.shouldSkip(): Boolean { if (this.execution.type != PIPELINE) { return false } val clonedContext = objectMapper.convertValue(this.context, Map::class.java) as Map<String, Any> val clonedStage = Stage(this.execution, this.type, clonedContext).also { it.refId = refId it.requisiteStageRefIds = requisiteStageRefIds it.syntheticStageOwner = syntheticStageOwner it.parentStageId = parentStageId } if (clonedStage.context.containsKey(PipelineExpressionEvaluator.SUMMARY)) { this.context.put(PipelineExpressionEvaluator.SUMMARY, clonedStage.context[PipelineExpressionEvaluator.SUMMARY]) } return OptionalStageSupport.isOptional(clonedStage.withMergedContext(), contextParameterProcessor) } private fun Stage.isAfterStartTimeExpiry(): Boolean = startTimeExpiry?.let { Instant.ofEpochMilli(it) }?.isBefore(clock.instant()) ?: false }
apache-2.0
mmo5/mmo5
mmo5-server/src/test/java/com/mmo5/server/manager/BoardManagerV2Test.kt
1
4151
package com.mmo5.server.manager import com.mmo5.server.model.Position import com.mmo5.server.model.messages.PlayerMove import com.mmo5.server.model.messages.Winner import org.junit.Assert.* import org.junit.Test class BoardManagerV2Test { @Test fun winToRight() { val tested = BoardManagerV2(boardSize = 3, winSeq = 2) tested.updatePlayerMove(PlayerMove(1, Position(0, 0))) tested.updatePlayerMove(PlayerMove(1, Position(1, 0))) val winner = tested.checkWinner() validateWinner(setOf(Position(0, 0), Position(1, 0)), winner) } private fun validateWinner(winSet: Set<Position>, winner: Winner?) { if (winner == null) { fail() } else { assertEquals(1, winner.playerId) assertEquals(winSet, winner.positions.toSet()) } } @Test fun winToBottom() { val tested = BoardManagerV2(boardSize = 3, winSeq = 2) tested.updatePlayerMove(PlayerMove(1, Position(0, 0))) tested.updatePlayerMove(PlayerMove(1, Position(0, 1))) val winner = tested.checkWinner() validateWinner(setOf(Position(0, 0), Position(0, 1)), winner) } @Test fun winToTopRight() { val tested = BoardManagerV2(boardSize = 3, winSeq = 2) tested.updatePlayerMove(PlayerMove(1, Position(1, 0))) tested.updatePlayerMove(PlayerMove(1, Position(0, 1))) val winner = tested.checkWinner() validateWinner(setOf(Position(0, 1), Position(1, 0)), winner) } @Test fun winToBottomRight() { val tested = BoardManagerV2(boardSize = 3, winSeq = 2) tested.updatePlayerMove(PlayerMove(1, Position(0, 0))) tested.updatePlayerMove(PlayerMove(1, Position(1, 1))) val winner = tested.checkWinner() validateWinner(setOf(Position(0, 0), Position(1, 1)), winner) } @Test fun `winToRight - More Than 2`() { val tested = BoardManagerV2(boardSize = 3, winSeq = 2) tested.updatePlayerMove(PlayerMove(1, Position(0, 0))) tested.updatePlayerMove(PlayerMove(1, Position(1, 0))) tested.updatePlayerMove(PlayerMove(1, Position(2, 0))) val winner = tested.checkWinner() validateWinner(setOf(Position(0, 0), Position(1, 0), Position(2, 0)), winner) } @Test fun `winToRight - real size board`() { val tested = BoardManagerV2() tested.updatePlayerMove(PlayerMove(1, Position(0, 0))) tested.updatePlayerMove(PlayerMove(1, Position(1, 0))) tested.updatePlayerMove(PlayerMove(1, Position(2, 0))) tested.updatePlayerMove(PlayerMove(1, Position(3, 0))) tested.updatePlayerMove(PlayerMove(1, Position(4, 0))) val winner = tested.checkWinner() validateWinner(setOf(Position(0, 0), Position(1, 0), Position(2, 0), Position(3, 0), Position(4, 0)), winner) } @Test fun `no winner - real size board`() { val tested = BoardManagerV2() tested.updatePlayerMove(PlayerMove(1, Position(0, 0))) tested.updatePlayerMove(PlayerMove(1, Position(1, 0))) tested.updatePlayerMove(PlayerMove(1, Position(3, 0))) tested.updatePlayerMove(PlayerMove(1, Position(4, 0))) val winner = tested.checkWinner() assertTrue(winner == null) } @Test fun `win in complex shape`() { val tested = BoardManagerV2(boardSize = 3, winSeq = 2) tested.updatePlayerMove(PlayerMove(1, Position(0, 0))) tested.updatePlayerMove(PlayerMove(1, Position(1, 0))) tested.updatePlayerMove(PlayerMove(1, Position(0, 1))) val winner = tested.checkWinner() validateWinner(setOf(Position(0, 0), Position(1, 0), Position(0, 1)), winner) } @Test fun `validate winner with another player - was a bug`() { val tested = BoardManagerV2(boardSize = 3, winSeq = 2) tested.updatePlayerMove(PlayerMove(1, Position(0, 0))) tested.updatePlayerMove(PlayerMove(1, Position(1, 0))) tested.updatePlayerMove(PlayerMove(2, Position(1, 1))) val winner = tested.checkWinner() validateWinner(setOf(Position(0, 0), Position(1, 0)), winner) } }
apache-2.0
yole/deckjs-presentations
snippets/smartcasts.kt
1
388
package smartcasts trait Expr class Number(val value: Int): Expr class Sum(val left: Expr, val right: Expr): Expr class Mult(val left: Expr, val right: Expr): Expr fun eval(e: Expr): Int { if (e is Number) return e.value if (e is Sum) return eval(e.left) + eval(e.right) throw IllegalArgumentException( "Unknown expression: $e") }
mit
mdanielwork/intellij-community
platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/model/DataNodeTest.kt
6
2541
/* * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.intellij.openapi.externalSystem.model import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatExceptionOfType import org.junit.Before import org.junit.Test import java.io.* import java.lang.reflect.InvocationHandler import java.lang.reflect.Method import java.lang.reflect.Proxy import java.net.URL import java.net.URLClassLoader class DataNodeTest { lateinit var cl: ClassLoader private val myLibUrl: URL = javaClass.classLoader.getResource("dataNodeTest/lib.jar") @Before fun setUp() { cl = URLClassLoader(arrayOf(myLibUrl), javaClass.classLoader) } @Test fun `instance of class from a classloader can be deserialized`() { val barObject = cl.loadClass("foo.Bar").newInstance() val deserialized = wrapAndDeserialize(Any::class.java, barObject) assertThatExceptionOfType(IllegalStateException::class.java) .isThrownBy { deserialized.prepareData(javaClass.classLoader) } val newCl = URLClassLoader(arrayOf(myLibUrl), javaClass.classLoader) deserialized.prepareData(newCl) assertThat(deserialized.data.javaClass.name) .contains("foo.Bar") } @Test fun `proxy instance can be deserialized`() { val interfaceClass = cl.loadClass("foo.Baz") val invocationHandler = object : InvocationHandler, Serializable { override fun invoke(proxy: Any?, method: Method?, args: Array<out Any>?) = 0 } var proxyInstance = Proxy.newProxyInstance(cl, arrayOf(interfaceClass), invocationHandler) val deserialized = wrapAndDeserialize(interfaceClass as Class<Any>, proxyInstance) assertThatExceptionOfType(IllegalStateException::class.java) .isThrownBy { deserialized.prepareData(javaClass.classLoader) } val newCl = URLClassLoader(arrayOf(myLibUrl), javaClass.classLoader) deserialized.prepareData(newCl) assertThat(deserialized.data.javaClass.interfaces) .extracting("name") .contains("foo.Baz") } private fun wrapAndDeserialize(clz: Class<Any>, barObject: Any): DataNode<Any> { val original = DataNode(Key.create(clz, 0), barObject, null) val bos = ByteArrayOutputStream() ObjectOutputStream(bos).use { it.writeObject(original) } val bytes = bos.toByteArray() return ObjectInputStream(ByteArrayInputStream(bytes)).use { it.readObject() } as DataNode<Any> } }
apache-2.0
imknown/ImkGithub
ZMain/ImkGithubApp/src/main/java/net/imknown/imkgithub/web/converter/StringConverterFactory.kt
1
1821
/* * Copyright (C) 2015 Square, 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 net.imknown.imkgithub.web.converter import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.ResponseBody import retrofit2.Converter import retrofit2.Retrofit import java.lang.reflect.Type /** * Modified * https://github.com/square/retrofit/issues/1151 * https://github.com/zhimin115200/Retrofit_StringAndJsonConverter */ class StringConverterFactory : Converter.Factory() { override fun responseBodyConverter( type: Type, annotations: Array<Annotation>, retrofit: Retrofit ): Converter<ResponseBody, String> { return Converter { it.string() } } override fun requestBodyConverter( type: Type, parameterAnnotations: Array<Annotation>, methodAnnotations: Array<Annotation>, retrofit: Retrofit ): Converter<String, RequestBody> { return Converter { it.toRequestBody(MEDIA_TYPE) } } companion object { private val MEDIA_TYPE = "text/plain".toMediaTypeOrNull() fun create(): StringConverterFactory { return StringConverterFactory() } } }
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/findUsages/kotlin/findClassUsages/kotlinClassDerivedLocalClasses.0.kt
24
162
// FIR_COMPARISON // PSI_ELEMENT: org.jetbrains.kotlin.psi.KtClass // OPTIONS: derivedClasses interface X { } open class <caret>A: X { } interface Y : X { }
apache-2.0
dahlstrom-g/intellij-community
platform/smRunner/src/com/intellij/execution/testframework/sm/runner/LongLineCutter.kt
12
2677
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.testframework.sm.runner import com.intellij.execution.impl.ConsoleBuffer import com.intellij.execution.testframework.sm.ServiceMessageUtil import jetbrains.buildServer.messages.serviceMessages.ServiceMessage private const val ELLIPSIS = "<...>" private val FIELDS_NOT_TO_TOUCH = setOf("name", "duration", "type", "flowId", "nodeId", "parentNodeId") private val EXPECTED_ACTUAL = arrayOf("expected", "actual") /** * If [text] is longer than [maxLength] cut it and insert [ELLIPSIS] in cut. * If it is a [ServiceMessage], then find longest attribute and cut it leaving [margin] as prefix and postfix * [EXPECTED_ACTUAL] attrs both are cut. * */ fun cutLineIfTooLong(text: String, maxLength: Int = ConsoleBuffer.getCycleBufferSize(), margin: Int = 1000): String { val minValueLengthToCut = (margin * 2) + ELLIPSIS.length if (text.length <= maxLength || maxLength < minValueLengthToCut) { return text } val message = ServiceMessageUtil.parse(text.trim(), false, false) if (message == null) { //Not a message, cut as regular text return text.substring(0, maxLength - ELLIPSIS.length) + ELLIPSIS } val attributes = HashMap(message.attributes) val attributesToCut = attributes .filter { it.key !in FIELDS_NOT_TO_TOUCH } .toList() .sortedByDescending { it.second.length } .map { it.first } val shortener = Shortener(attributes, text.length, margin, minValueLengthToCut) for (attr in attributesToCut) { if (shortener.currentLength < maxLength) { break } shortener.shortenAttribute(attr) if (attr in EXPECTED_ACTUAL) { EXPECTED_ACTUAL.forEach(shortener::shortenAttribute) } } return ServiceMessage.asString(message.messageName, attributes) } private class Shortener(private val attributes: MutableMap<String, String>, var currentLength: Int, private val margin: Int, private val minValueLengthToCut: Int) { private val shortened = mutableSetOf<String>() fun shortenAttribute(attribute: String) { if (attribute in shortened) { return } val value = attributes[attribute] ?: return if (value.length <= minValueLengthToCut) { // Too short to cut return } val lenBefore = value.length val newValue = StringBuilder(value).replace(margin, value.length - margin, ELLIPSIS).toString() currentLength -= (lenBefore - newValue.length) attributes[attribute] = newValue shortened.add(attribute) } }
apache-2.0
intellij-solidity/intellij-solidity
src/test/kotlin/me/serce/solidity/lang/core/resolve/SolFunctionOverrideTest.kt
1
1313
package me.serce.solidity.lang.core.resolve import me.serce.solidity.lang.psi.SolFunctionDefinition import me.serce.solidity.lang.resolve.function.SolFunctionResolver class SolFunctionOverrideTest : SolResolveTestBase() { fun testFindOverrides() { InlineFile(""" contract A { function test(uint256 test); //X function test(); } contract B is A { function test(uint test1) { //^ } function test(uint128 test2) { } } contract C is B { function test(uint256 test2) { //Y } function test(uint128 test) { } } """) val (func, _) = findElementAndDataInEditor<SolFunctionDefinition>("^") val (overriden, _) = findElementAndDataInEditor<SolFunctionDefinition>("X") val (overrides, _) = findElementAndDataInEditor<SolFunctionDefinition>("Y") val overridenList = SolFunctionResolver.collectOverriden(func) assert(overridenList.size == 1) assert(overridenList.firstOrNull() == overriden) val overridesList = SolFunctionResolver.collectOverrides(func) assert(overridesList.size == 1) assert(overridesList.firstOrNull() == overrides) } }
mit
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/rename/renameKotlinPropertyWithJvmField/after/RenameKotlinPropertyWithJvmField.kt
13
77
package testing.rename public open class C { @JvmStatic var second = 1 }
apache-2.0
dkandalov/katas
kotlin/src/katas/kotlin/eightQueen/EightQueen23.kt
1
2658
package katas.kotlin.eightQueen import datsok.shouldEqual import org.junit.Test class EightQueen23 { @Test fun `find positions of queens on board in which they don't attack each other`() { Board(size = 0).doFindQueenPositions() shouldEqual listOf() Board(size = 1).doFindQueenPositions() shouldEqual listOf(Board(size = 1, queens = listOf(Queen(0, 0)))) Board(size = 2).doFindQueenPositions() shouldEqual listOf() Board(size = 3).doFindQueenPositions() shouldEqual listOf() Board(size = 4).doFindQueenPositions() shouldEqual listOf( Board(size = 4, queens = listOf(Queen(x = 0, y = 1), Queen(x = 1, y = 3), Queen(x = 2, y = 0), Queen(x = 3, y = 2))), Board(size = 4, queens = listOf(Queen(x = 0, y = 2), Queen(x = 1, y = 0), Queen(x = 2, y = 3), Queen(x = 3, y = 1))) ) Board(size = 8).doFindQueenPositions().size shouldEqual 92 Board(size = 10).doFindQueenPositions().size shouldEqual 724 Board(size = 20).findQueenPositions().take(1).toList() shouldEqual listOf( Board(size = 20, queens = listOf( Queen(x = 0, y = 0), Queen(x = 1, y = 2), Queen(x = 2, y = 4), Queen(x = 3, y = 1), Queen(x = 4, y = 3), Queen(x = 5, y = 12), Queen(x = 6, y = 14), Queen(x = 7, y = 11), Queen(x = 8, y = 17), Queen(x = 9, y = 19), Queen(x = 10, y = 16), Queen(x = 11, y = 8), Queen(x = 12, y = 15), Queen(x = 13, y = 18), Queen(x = 14, y = 7), Queen(x = 15, y = 9), Queen(x = 16, y = 6), Queen(x = 17, y = 13), Queen(x = 18, y = 5), Queen(x = 19, y = 10) )) ) } private fun Board.doFindQueenPositions(): List<Board> = findQueenPositions().toList() private fun Board.findQueenPositions(): Sequence<Board> { val nextMoves = sequence { val x = (queens.map { it.x }.maxOrNull() ?: -1) + 1 0.until(size) .map { y -> Queen(x, y) } .filter { isValidMove(it) } .forEach { yield(it) } } return nextMoves.flatMap { move -> val newBoard = copy(queens = queens + move) if (newBoard.queens.size == size) sequenceOf(newBoard) else newBoard.findQueenPositions() } } private fun Board.isValidMove(queen: Queen) = queens.size < size && queens.none { it.x == queen.x || it.y == queen.y } && queens.none { Math.abs(it.x - queen.x) == Math.abs(it.y - queen.y) } private data class Board(val size: Int, val queens: List<Queen> = emptyList()) private data class Queen(val x: Int, val y: Int) }
unlicense
phylame/jem
scj/src/main/kotlin/jem/sci/Commands.kt
1
3249
/* * Copyright 2015-2017 Peng Wan <[email protected]> * * This file is part of Jem. * * 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 jem.sci import jem.Book import jem.asBook import jem.epm.ParserParam import mala.App import mala.App.tr import mala.cli.CDelegate import mala.cli.Command import mala.cli.ListFetcher interface InputProcessor { fun process(input: String, format: String): Boolean } interface ProcessorCommand : Command, InputProcessor { override fun execute(delegate: CDelegate): Int = SCI.processInputs(this) } interface BookConsumer : ProcessorCommand { val attaching get() = true fun consume(book: Book): Boolean override fun process(input: String, format: String): Boolean { return openBook(ParserParam(input, format, SCI.inArguments), attaching)?.let { try { consume(it) } finally { it.cleanup() } } == true } } class ViewBook : ListFetcher("w"), BookConsumer { @Suppress("UNCHECKED_CAST") override fun consume(book: Book): Boolean { viewBook(book, (SCI["w"] as? List<String>) ?: listOf("all"), SCISettings.viewSettings()) return true } } class ConvertBook : BookConsumer { override fun consume(book: Book): Boolean { val path = saveBook(outParam(book)) ?: return false println(tr("save.result", path)) return true } } class JoinBook : Command, InputProcessor { private val book = Book() override fun execute(delegate: CDelegate): Int { var code = SCI.processInputs(this) if (!book.isSection) { // no input books App.error("no book specified") return -1 } attachBook(book, true) val path = saveBook(outParam(book)) if (path != null) { println(tr("save.result", path)) } else { code = -1 } book.cleanup() return code } override fun process(input: String, format: String): Boolean { book += openBook(ParserParam(input, format, SCI.inArguments), false) ?: return false return true } } class ExtractBook : ListFetcher("x"), BookConsumer { override val attaching get() = false @Suppress("UNCHECKED_CAST") override fun consume(book: Book): Boolean { return (SCI["x"] as? List<String> ?: return false).mapNotNull(::parseIndices).mapNotNull { locateChapter(book, it) }.map { val b = it.asBook() attachBook(b, true) saveBook(outParam(b)) }.all { if (it != null) { println(tr("save.result", it)) true } else false } } }
apache-2.0
ThePreviousOne/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadManager.kt
1
17103
package eu.kanade.tachiyomi.data.download import android.content.Context import android.net.Uri import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.google.gson.stream.JsonReader import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.download.model.Download import eu.kanade.tachiyomi.data.download.model.DownloadQueue import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.data.source.Source import eu.kanade.tachiyomi.data.source.SourceManager import eu.kanade.tachiyomi.data.source.model.Page import eu.kanade.tachiyomi.data.source.online.OnlineSource import eu.kanade.tachiyomi.util.* import rx.Observable import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import rx.subjects.BehaviorSubject import rx.subjects.PublishSubject import timber.log.Timber import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import java.io.File import java.io.FileReader import java.util.* class DownloadManager( private val context: Context, private val sourceManager: SourceManager = Injekt.get(), private val preferences: PreferencesHelper = Injekt.get() ) { private val gson = Gson() private val downloadsQueueSubject = PublishSubject.create<List<Download>>() val runningSubject = BehaviorSubject.create<Boolean>() private var downloadsSubscription: Subscription? = null val downloadNotifier by lazy { DownloadNotifier(context) } private val threadsSubject = BehaviorSubject.create<Int>() private var threadsSubscription: Subscription? = null val queue = DownloadQueue() val imageFilenameRegex = "[^\\sa-zA-Z0-9.-]".toRegex() val PAGE_LIST_FILE = "index.json" @Volatile var isRunning: Boolean = false private set private fun initializeSubscriptions() { downloadsSubscription?.unsubscribe() threadsSubscription = preferences.downloadThreads().asObservable() .subscribe { threadsSubject.onNext(it) downloadNotifier.multipleDownloadThreads = it > 1 } downloadsSubscription = downloadsQueueSubject.flatMap { Observable.from(it) } .lift(DynamicConcurrentMergeOperator<Download, Download>({ downloadChapter(it) }, threadsSubject)) .onBackpressureBuffer() .observeOn(AndroidSchedulers.mainThread()) .subscribe({ // Delete successful downloads from queue if (it.status == Download.DOWNLOADED) { // remove downloaded chapter from queue queue.del(it) downloadNotifier.onProgressChange(queue) } if (areAllDownloadsFinished()) { DownloadService.stop(context) } }, { error -> DownloadService.stop(context) Timber.e(error) downloadNotifier.onError(error.message) }) if (!isRunning) { isRunning = true runningSubject.onNext(true) } } fun destroySubscriptions() { if (isRunning) { isRunning = false runningSubject.onNext(false) } if (downloadsSubscription != null) { downloadsSubscription?.unsubscribe() downloadsSubscription = null } if (threadsSubscription != null) { threadsSubscription?.unsubscribe() } } // Create a download object for every chapter and add them to the downloads queue fun downloadChapters(manga: Manga, chapters: List<Chapter>) { val source = sourceManager.get(manga.source) as? OnlineSource ?: return // Add chapters to queue from the start val sortedChapters = chapters.sortedByDescending { it.source_order } // Used to avoid downloading chapters with the same name val addedChapters = ArrayList<String>() val pending = ArrayList<Download>() for (chapter in sortedChapters) { if (addedChapters.contains(chapter.name)) continue addedChapters.add(chapter.name) val download = Download(source, manga, chapter) if (!prepareDownload(download)) { queue.add(download) pending.add(download) } } // Initialize queue size downloadNotifier.initialQueueSize = queue.size // Show notification downloadNotifier.onProgressChange(queue) if (isRunning) downloadsQueueSubject.onNext(pending) } // Public method to check if a chapter is downloaded fun isChapterDownloaded(source: Source, manga: Manga, chapter: Chapter): Boolean { val directory = getAbsoluteChapterDirectory(source, manga, chapter) if (!directory.exists()) return false val pages = getSavedPageList(source, manga, chapter) return isChapterDownloaded(directory, pages) } // Prepare the download. Returns true if the chapter is already downloaded private fun prepareDownload(download: Download): Boolean { // If the chapter is already queued, don't add it again for (queuedDownload in queue) { if (download.chapter.id == queuedDownload.chapter.id) return true } // Add the directory to the download object for future access download.directory = getAbsoluteChapterDirectory(download) // If the directory doesn't exist, the chapter isn't downloaded. if (!download.directory.exists()) { return false } // If the page list doesn't exist, the chapter isn't downloaded val savedPages = getSavedPageList(download) ?: return false // Add the page list to the download object for future access download.pages = savedPages // If the number of files matches the number of pages, the chapter is downloaded. // We have the index file, so we check one file more return isChapterDownloaded(download.directory, download.pages) } // Check that all the images are downloaded private fun isChapterDownloaded(directory: File, pages: List<Page>?): Boolean { return pages != null && !pages.isEmpty() && pages.size + 1 == directory.listFiles().size } // Download the entire chapter private fun downloadChapter(download: Download): Observable<Download> { DiskUtils.createDirectory(download.directory) val pageListObservable: Observable<List<Page>> = if (download.pages == null) // Pull page list from network and add them to download object download.source.fetchPageListFromNetwork(download.chapter) .doOnNext { pages -> download.pages = pages savePageList(download) } else // Or if the page list already exists, start from the file Observable.just(download.pages) return Observable.defer { pageListObservable .doOnNext { pages -> download.downloadedImages = 0 download.status = Download.DOWNLOADING } // Get all the URLs to the source images, fetch pages if necessary .flatMap { download.source.fetchAllImageUrlsFromPageList(it) } // Start downloading images, consider we can have downloaded images already .concatMap { page -> getOrDownloadImage(page, download) } // Do when page is downloaded. .doOnNext { downloadNotifier.onProgressChange(download, queue) } // Do after download completes .doOnCompleted { onDownloadCompleted(download) } .toList() .map { pages -> download } // If the page list threw, it will resume here .onErrorResumeNext { error -> download.status = Download.ERROR downloadNotifier.onError(error.message, download.chapter.name) Observable.just(download) } }.subscribeOn(Schedulers.io()) } // Get the image from the filesystem if it exists or download from network private fun getOrDownloadImage(page: Page, download: Download): Observable<Page> { // If the image URL is empty, do nothing if (page.imageUrl == null) return Observable.just(page) val filename = getImageFilename(page) val imagePath = File(download.directory, filename) // If the image is already downloaded, do nothing. Otherwise download from network val pageObservable = if (isImageDownloaded(imagePath)) Observable.just(page) else downloadImage(page, download.source, download.directory, filename) return pageObservable // When the image is ready, set image path, progress (just in case) and status .doOnNext { page.imagePath = imagePath.absolutePath page.progress = 100 download.downloadedImages++ page.status = Page.READY } // Mark this page as error and allow to download the remaining .onErrorResumeNext { page.progress = 0 page.status = Page.ERROR Observable.just(page) } } // Save image on disk private fun downloadImage(page: Page, source: OnlineSource, directory: File, filename: String): Observable<Page> { page.status = Page.DOWNLOAD_IMAGE return source.imageResponse(page) .map { val file = File(directory, filename) try { file.parentFile.mkdirs() it.body().source().saveTo(file.outputStream()) } catch (e: Exception) { it.close() file.delete() throw e } page } // Retry 3 times, waiting 2, 4 and 8 seconds between attempts. .retryWhen(RetryWithDelay(3, { (2 shl it - 1) * 1000 }, Schedulers.trampoline())) } // Public method to get the image from the filesystem. It does NOT provide any way to download the image fun getDownloadedImage(page: Page, chapterDir: File): Observable<Page> { if (page.imageUrl == null) { page.status = Page.ERROR return Observable.just(page) } val imagePath = File(chapterDir, getImageFilename(page)) // When the image is ready, set image path, progress (just in case) and status if (isImageDownloaded(imagePath)) { page.imagePath = imagePath.absolutePath page.progress = 100 page.status = Page.READY } else { page.status = Page.ERROR } return Observable.just(page) } // Get the filename for an image given the page private fun getImageFilename(page: Page): String { val url = page.imageUrl val number = String.format("%03d", page.pageNumber + 1) // Try to preserve file extension return when { UrlUtil.isJpg(url) -> "$number.jpg" UrlUtil.isPng(url) -> "$number.png" UrlUtil.isGif(url) -> "$number.gif" else -> Uri.parse(url).lastPathSegment.replace(imageFilenameRegex, "_") } } private fun isImageDownloaded(imagePath: File): Boolean { return imagePath.exists() } // Called when a download finishes. This doesn't mean the download was successful, so we check it private fun onDownloadCompleted(download: Download) { checkDownloadIsSuccessful(download) savePageList(download) } private fun checkDownloadIsSuccessful(download: Download) { var actualProgress = 0 var status = Download.DOWNLOADED // If any page has an error, the download result will be error for (page in download.pages!!) { actualProgress += page.progress if (page.status != Page.READY) { status = Download.ERROR downloadNotifier.onError(context.getString(R.string.download_notifier_page_ready_error), download.chapter.name) } } // Ensure that the chapter folder has all the images if (!isChapterDownloaded(download.directory, download.pages)) { status = Download.ERROR downloadNotifier.onError(context.getString(R.string.download_notifier_page_error), download.chapter.name) } download.totalProgress = actualProgress download.status = status } // Return the page list from the chapter's directory if it exists, null otherwise fun getSavedPageList(source: Source, manga: Manga, chapter: Chapter): List<Page>? { val chapterDir = getAbsoluteChapterDirectory(source, manga, chapter) val pagesFile = File(chapterDir, PAGE_LIST_FILE) return try { JsonReader(FileReader(pagesFile)).use { val collectionType = object : TypeToken<List<Page>>() {}.type gson.fromJson(it, collectionType) } } catch (e: Exception) { null } } // Shortcut for the method above private fun getSavedPageList(download: Download): List<Page>? { return getSavedPageList(download.source, download.manga, download.chapter) } // Save the page list to the chapter's directory fun savePageList(source: Source, manga: Manga, chapter: Chapter, pages: List<Page>) { val chapterDir = getAbsoluteChapterDirectory(source, manga, chapter) val pagesFile = File(chapterDir, PAGE_LIST_FILE) pagesFile.outputStream().use { try { it.write(gson.toJson(pages).toByteArray()) it.flush() } catch (error: Exception) { Timber.e(error) } } } // Shortcut for the method above private fun savePageList(download: Download) { savePageList(download.source, download.manga, download.chapter, download.pages!!) } fun getAbsoluteMangaDirectory(source: Source, manga: Manga): File { val mangaRelativePath = source.toString() + File.separator + manga.title.replace("[^\\sa-zA-Z0-9.-]".toRegex(), "_") return File(preferences.downloadsDirectory().getOrDefault(), mangaRelativePath) } // Get the absolute path to the chapter directory fun getAbsoluteChapterDirectory(source: Source, manga: Manga, chapter: Chapter): File { val chapterRelativePath = chapter.name.replace("[^\\sa-zA-Z0-9.-]".toRegex(), "_") return File(getAbsoluteMangaDirectory(source, manga), chapterRelativePath) } // Shortcut for the method above private fun getAbsoluteChapterDirectory(download: Download): File { return getAbsoluteChapterDirectory(download.source, download.manga, download.chapter) } fun deleteChapter(source: Source, manga: Manga, chapter: Chapter) { val path = getAbsoluteChapterDirectory(source, manga, chapter) DiskUtils.deleteFiles(path) } fun areAllDownloadsFinished(): Boolean { for (download in queue) { if (download.status <= Download.DOWNLOADING) return false } return true } fun startDownloads(): Boolean { if (queue.isEmpty()) return false if (downloadsSubscription == null || downloadsSubscription!!.isUnsubscribed) initializeSubscriptions() val pending = ArrayList<Download>() for (download in queue) { if (download.status != Download.DOWNLOADED) { if (download.status != Download.QUEUE) download.status = Download.QUEUE pending.add(download) } } downloadsQueueSubject.onNext(pending) return !pending.isEmpty() } fun stopDownloads(errorMessage: String? = null) { destroySubscriptions() for (download in queue) { if (download.status == Download.DOWNLOADING) { download.status = Download.ERROR } } errorMessage?.let { downloadNotifier.onError(it) } } fun clearQueue() { queue.clear() downloadNotifier.onClear() } }
apache-2.0
Pagejects/pagejects-core
src/main/kotlin/net/pagejects/core/error/ReadFormUserActionException.kt
1
273
package net.pagejects.core.error /** * TODO Describe class * * @author [Andrey Paslavsky](mailto:[email protected]) * @since 0.1 */ open class ReadFormUserActionException(message: String, cause: Exception? = null) : FormUserActionException(message, cause)
apache-2.0
Piasy/OkBuck
libraries/kotlinlibrary/src/main/java/demo/Anno2.kt
3
37
package demo annotation class Anno2
mit
JuliaSoboleva/SmartReceiptsLibrary
app/src/test/java/co/smartreceipts/android/tooltip/rating/RateThisAppTooltipControllerTest.kt
2
5051
package co.smartreceipts.android.tooltip.rating import android.content.Context import androidx.test.core.app.ApplicationProvider import co.smartreceipts.analytics.Analytics import co.smartreceipts.analytics.events.Events import co.smartreceipts.android.R import co.smartreceipts.android.rating.AppRatingManager import co.smartreceipts.android.tooltip.TooltipView import co.smartreceipts.android.tooltip.model.TooltipInteraction import co.smartreceipts.android.tooltip.model.TooltipMetadata import co.smartreceipts.android.tooltip.model.TooltipType import com.hadisatrio.optional.Optional import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.verifyZeroInteractions import com.nhaarman.mockitokotlin2.whenever import io.reactivex.Single import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito import org.mockito.MockitoAnnotations import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class RateThisAppTooltipControllerTest { companion object { private val TOOLTIP_METADATA = TooltipMetadata(TooltipType.RateThisApp, ApplicationProvider.getApplicationContext<Context>().getString(R.string.rating_tooltip_text)) } lateinit var controller: RateThisAppTooltipController @Mock lateinit var tooltipView: TooltipView @Mock lateinit var router: RateThisAppTooltipRouter @Mock lateinit var appRatingManager: AppRatingManager @Mock lateinit var analytics: Analytics @Before fun setUp() { MockitoAnnotations.initMocks(this) controller = RateThisAppTooltipController(ApplicationProvider.getApplicationContext(), tooltipView, router, appRatingManager, analytics) } @Test fun displayTooltipWhenWeShouldAskForRating() { whenever(appRatingManager.checkIfNeedToAskRating()).thenReturn(Single.just(true)) controller.shouldDisplayTooltip() .test() .await() .assertValue(Optional.of(TOOLTIP_METADATA)) .assertComplete() .assertNoErrors() } @Test fun doNotDisplayTooltipWhenWeShouldNotAskForRating() { whenever(appRatingManager.checkIfNeedToAskRating()).thenReturn(Single.just(false)) controller.shouldDisplayTooltip() .test() .await() .assertValue(Optional.absent()) .assertComplete() .assertNoErrors() } @Test fun handleTooltipInteractionForTooltipClick() { val interaction = TooltipInteraction.TooltipClick controller.handleTooltipInteraction(interaction) .test() .await() .assertComplete() .assertNoErrors() verifyZeroInteractions(analytics, appRatingManager) } @Test fun handleTooltipInteractionForCloseCancelClick() { val interaction = TooltipInteraction.CloseCancelButtonClick controller.handleTooltipInteraction(interaction) .test() .await() .assertComplete() .assertNoErrors() verifyZeroInteractions(analytics, appRatingManager) } @Test fun handleTooltipInteractionForYesClick() { val interaction = TooltipInteraction.YesButtonClick controller.handleTooltipInteraction(interaction) .test() .await() .assertComplete() .assertNoErrors() verify(appRatingManager).dontShowRatingPromptAgain() verify(analytics).record(Events.Ratings.UserAcceptedRatingPrompt) } @Test fun handleTooltipInteractionForNoClick() { val interaction = TooltipInteraction.NoButtonClick controller.handleTooltipInteraction(interaction) .test() .await() .assertComplete() .assertNoErrors() verify(appRatingManager).dontShowRatingPromptAgain() verify(analytics).record(Events.Ratings.UserDeclinedRatingPrompt) } @Test fun consumeYesClickInteraction() { controller.consumeTooltipInteraction().accept(TooltipInteraction.YesButtonClick) Mockito.verify(tooltipView).hideTooltip() Mockito.verify(router).navigateToRatingOptions() } @Test fun consumeNoInteraction() { controller.consumeTooltipInteraction().accept(TooltipInteraction.NoButtonClick) Mockito.verify(tooltipView).hideTooltip() Mockito.verify(router).navigateToFeedbackOptions() } @Test fun consumeTooltipClickInteraction() { controller.consumeTooltipInteraction().accept(TooltipInteraction.TooltipClick) verifyZeroInteractions(tooltipView, router) } @Test fun consumeCloseClickInteraction() { controller.consumeTooltipInteraction().accept(TooltipInteraction.CloseCancelButtonClick) verifyZeroInteractions(tooltipView, router) } }
agpl-3.0
mkobit/ratpack-kotlin
ratpack-core-kotlin/src/test/kotlin/com/mkobit/ratpack/handling/KotlinChainTest.kt
1
2932
package com.mkobit.ratpack.handling import com.nhaarman.mockito_kotlin.KArgumentCaptor import com.nhaarman.mockito_kotlin.argumentCaptor import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import ratpack.handling.Chain import ratpack.handling.Context import ratpack.handling.Handler internal class KotlinChainTest { lateinit var mockChain: Chain lateinit var mockContext: Context lateinit var chain: KotlinChain lateinit var handlerCaptor: KArgumentCaptor<Handler> @BeforeEach internal fun setUp() { mockChain = mock() mockContext = mock() handlerCaptor = argumentCaptor() chain = KotlinChain(mockChain) } @Test internal fun all() { chain.all { render("hello") } verify(mockChain).all(handlerCaptor.capture()) handlerCaptor.firstValue.handle(mockContext) verify(mockContext).render("hello") } @Test internal fun `delete`() { chain.delete { render("hello") } verify(mockChain).delete(handlerCaptor.capture()) handlerCaptor.firstValue.handle(mockContext) verify(mockContext).render("hello") } @Test internal fun `delete with path`() { chain.delete("path") { render("hello") } verify(mockChain).delete(eq("path"), handlerCaptor.capture()) handlerCaptor.firstValue.handle(mockContext) verify(mockContext).render("hello") } @Test internal fun `get`() { chain.get { render("hello") } verify(mockChain).get(handlerCaptor.capture()) handlerCaptor.firstValue.handle(mockContext) verify(mockContext).render("hello") } @Test internal fun `get with path`() { chain.get("path") { render("hello") } verify(mockChain).get(eq("path"), handlerCaptor.capture()) handlerCaptor.firstValue.handle(mockContext) verify(mockContext).render("hello") } @Test internal fun `post`() { chain.post { render("hello") } verify(mockChain).post(handlerCaptor.capture()) handlerCaptor.firstValue.handle(mockContext) verify(mockContext).render("hello") } @Test internal fun `post with path`() { chain.post("path") { render("hello") } verify(mockChain).post(eq("path"), handlerCaptor.capture()) handlerCaptor.firstValue.handle(mockContext) verify(mockContext).render("hello") } @Test internal fun `put`() { chain.put { render("hello") } verify(mockChain).put(handlerCaptor.capture()) handlerCaptor.firstValue.handle(mockContext) verify(mockContext).render("hello") } @Test internal fun `put with path`() { chain.put("path") { render("hello") } verify(mockChain).put(eq("path"), handlerCaptor.capture()) handlerCaptor.firstValue.handle(mockContext) verify(mockContext).render("hello") } }
apache-2.0
paplorinc/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/references/GrNewExpressionReference.kt
2
771
// 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 org.jetbrains.plugins.groovy.lang.resolve.references import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrNewExpression import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments import org.jetbrains.plugins.groovy.lang.resolve.impl.getArguments class GrNewExpressionReference(element: GrNewExpression) : GrConstructorReference<GrNewExpression>(element) { override fun resolveClass(): GroovyResolveResult? = element.referenceElement?.advancedResolve() override val arguments: Arguments? get() = element.getArguments() }
apache-2.0
jmfayard/skripts
kotlin/man.kt
1
2160
#!/usr/bin/env kotlin-script.sh package man import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.produce import kotlinx.coroutines.runBlocking import okio.Buffer import org.zeroturnaround.exec.ProcessExecutor import kotlin.coroutines.CoroutineContext fun main(args: Array<String>) = runBlocking { if (args.size < 2) { println("Usage: $ main.kt ls -l") System.exit(1) return@runBlocking } val (command, option) = args println("Parsing $ man $command $option") val producer = executeBashCommand(coroutineContext, "man", command) searchForOption(option, producer) } suspend fun searchForOption(option: String, producer: ReceiveChannel<String>) { var foundBefore = false for (line in producer) { val words = line.splitToWords() val tries = listOf(words.getOrNull(0), words.getOrNull(1)) val foundNow = tries.any { it?.startsWith(option) == true } val hasArgument = tries.any { it?.startsWith("-") == true } if (foundBefore && hasArgument) break foundBefore = foundBefore or foundNow if (foundBefore && line.isNotBlank()) println(line) } } suspend fun CoroutineScope.executeBashCommand(context: CoroutineContext, command: String, vararg args: String) = produce<String>(context, Channel.UNLIMITED) { val allArgs = arrayOf(command, *args) Buffer().use { buffer -> ProcessExecutor().command(*allArgs) .redirectOutput(buffer.outputStream()) .setMessageLogger { _, _, _ -> } .execute() while (!buffer.exhausted()) { val line = buffer.readUtf8Line() ?: break channel.send(line) } } } private fun String.splitToWords(): List<String> { var line = this.trim() line = line.filterIndexed { i, c -> if (i == 0) return@filterIndexed true c != '\b' && line[i - 1] != '\b' } val words = line.split(' ', '\t', ',') return words.filter { it.isNotBlank() } }
apache-2.0
outbrain/ob1k
ob1k-crud/src/main/java/com/outbrain/ob1k/crud/service/ModelService.kt
1
285
package com.outbrain.ob1k.crud.service import com.outbrain.ob1k.Service import com.outbrain.ob1k.concurrent.ComposableFutures import com.outbrain.ob1k.crud.model.Model class ModelService(private val model: Model) : Service { fun getModel() = ComposableFutures.fromValue(model) }
apache-2.0
paplorinc/intellij-community
plugins/svn4idea/src/org/jetbrains/idea/svn/actions/MarkTreeConflictResolvedAction.kt
2
3938
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.svn.actions import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.Messages import com.intellij.openapi.vcs.AbstractVcsHelper import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.VcsDataKeys import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.changes.ChangesUtil.getAfterPath import com.intellij.openapi.vcs.changes.ChangesUtil.getBeforePath import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager import com.intellij.openapi.vcs.changes.ui.ChangesListView import org.jetbrains.idea.svn.* import org.jetbrains.idea.svn.api.Depth private fun getConflict(e: AnActionEvent): Conflict? { val changes = e.getData(VcsDataKeys.CHANGE_LEAD_SELECTION) val locallyDeletedChanges = e.getData(ChangesListView.LOCALLY_DELETED_CHANGES) if (locallyDeletedChanges.isNullOrEmpty()) { return (changes?.singleOrNull() as? ConflictedSvnChange)?.let { ChangeConflict(it) } } if (changes.isNullOrEmpty()) { return (locallyDeletedChanges.singleOrNull() as? SvnLocallyDeletedChange)?.let { LocallyDeletedChangeConflict(it) } } return null } class MarkTreeConflictResolvedAction : DumbAwareAction() { override fun update(e: AnActionEvent) { val project = e.project val conflict = getConflict(e) val enabled = project != null && conflict?.conflictState?.isTree == true e.presentation.isEnabledAndVisible = enabled } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val conflict = getConflict(e)!! val markText = SvnBundle.message("action.mark.tree.conflict.resolved.confirmation.title") val result = Messages.showYesNoDialog(project, SvnBundle.message("action.mark.tree.conflict.resolved.confirmation.text"), markText, Messages.getQuestionIcon()) if (result == Messages.YES) { object : Task.Backgroundable(project, markText, true) { private var exception: VcsException? = null override fun run(indicator: ProgressIndicator) { val path = conflict.path val vcs = SvnVcs.getInstance(project) try { vcs.getFactory(path.ioFile).createConflictClient().resolve(path.ioFile, Depth.EMPTY, false, false, true) } catch (e: VcsException) { exception = e } VcsDirtyScopeManager.getInstance(project).filePathsDirty(conflict.getPathsToRefresh(), null) } override fun onSuccess() { if (exception != null) { AbstractVcsHelper.getInstance(project).showError(exception, markText) } } }.queue() } } } private interface Conflict { val path: FilePath val conflictState: ConflictState fun getPathsToRefresh(): Collection<FilePath> } private class ChangeConflict(val change: ConflictedSvnChange) : Conflict { override val path: FilePath get() = change.treeConflictMarkHolder override val conflictState: ConflictState get() = change.conflictState override fun getPathsToRefresh(): Collection<FilePath> { val beforePath = getBeforePath(change) val afterPath = getAfterPath(change) val isAddMoveRename = beforePath == null || change.isMoved || change.isRenamed return listOfNotNull(beforePath, if (isAddMoveRename) afterPath else null) } } private class LocallyDeletedChangeConflict(val change: SvnLocallyDeletedChange) : Conflict { override val path: FilePath get() = change.path override val conflictState: ConflictState get() = change.conflictState override fun getPathsToRefresh(): Collection<FilePath> = listOf(path) }
apache-2.0
ssseasonnn/RxDownload
rxdownload4-manager/src/main/java/zlc/season/rxdownload4/manager/Status.kt
1
716
package zlc.season.rxdownload4.manager import zlc.season.rxdownload4.Progress fun Status.isEndStatus(): Boolean { return when (this) { is Normal -> false is Pending -> false is Started -> false is Downloading -> false is Paused -> true is Completed -> true is Failed -> true is Deleted -> true } } sealed class Status { var progress: Progress = Progress() } class Normal : Status() class Pending : Status() class Started : Status() class Downloading : Status() class Paused : Status() class Completed : Status() class Failed : Status() { var throwable: Throwable = RuntimeException("UNKNOWN ERROR") } class Deleted : Status()
apache-2.0
paplorinc/intellij-community
java/java-tests/testSrc/com/intellij/java/codeInspection/enhancedSwitch/SwitchLabeledRuleCanBeCodeBlockFixTest.kt
2
998
// 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.java.codeInspection.enhancedSwitch import com.intellij.codeInsight.daemon.quickFix.LightQuickFixParameterizedTestCase import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.enhancedSwitch.SwitchLabeledRuleCanBeCodeBlockInspection import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase /** * @author Pavel.Dolgov */ class SwitchLabeledRuleCanBeCodeBlockFixTest : LightQuickFixParameterizedTestCase() { override fun configureLocalInspectionTools(): Array<LocalInspectionTool> = arrayOf(SwitchLabeledRuleCanBeCodeBlockInspection()) override fun getProjectDescriptor(): LightProjectDescriptor = LightCodeInsightFixtureTestCase.JAVA_12 override fun getBasePath() = "/inspection/switchLabeledRuleCanBeCodeBlockFix" }
apache-2.0
ssseasonnn/RxDownload
rxdownload4-manager/src/main/java/zlc/season/rxdownload4/manager/EmptyNotification.kt
1
302
package zlc.season.rxdownload4.manager import android.app.Notification import zlc.season.rxdownload4.task.Task object EmptyNotification : NotificationCreator { override fun init(task: Task) { } override fun create(task: Task, status: Status): Notification? { return null } }
apache-2.0
denzelby/telegram-bot-bumblebee
telegram-bot-bumblebee-core/src/main/kotlin/com/github/bumblebee/command/youtube/service/YoutubeSubscriptionService.kt
2
3002
package com.github.bumblebee.command.youtube.service import com.github.bumblebee.bot.BumblebeeConfig import com.github.bumblebee.command.youtube.api.YoutubeSubscriptionApi import com.github.bumblebee.command.youtube.dao.YoutubePostedVideosRepository import com.github.bumblebee.command.youtube.dao.YoutubeSubscriptionRepository import com.github.bumblebee.command.youtube.entity.PostedVideo import com.github.bumblebee.command.youtube.entity.Subscription import com.github.bumblebee.util.logger import feign.Feign import feign.slf4j.Slf4jLogger import org.springframework.stereotype.Service @Service class YoutubeSubscriptionService(private val subscriptionRepository: YoutubeSubscriptionRepository, private val postedVideosRepository: YoutubePostedVideosRepository, private val config: BumblebeeConfig) { private val youtubeSubscriptionApi: YoutubeSubscriptionApi = Feign.builder() .logLevel(feign.Logger.Level.BASIC) .logger(Slf4jLogger()) .target(YoutubeSubscriptionApi::class.java, YoutubeSubscriptionApi.API_ROOT) private val existingSubscriptions: MutableList<Subscription> = subscriptionRepository.findAll().toMutableList() fun getSubscriptions(): MutableList<Subscription> = existingSubscriptions fun storeSubscription(subscription: Subscription) { subscriptionRepository.save(subscription) } fun deleteSubscription(subscription: Subscription) { subscriptionRepository.delete(subscription) } fun subscribeChannel(channelId: String): Boolean { val response = youtubeSubscriptionApi.subscribe( hubMode = "subscribe", hubTopicUrl = CHANNEL_URL + channelId, hubCallbackUrl = config.url + URL_POSTFIX ) return response.status() == 202 } fun unsubscribeChannel(channelId: String): Boolean { val response = youtubeSubscriptionApi.subscribe( hubMode = "unsubscribe", hubTopicUrl = CHANNEL_URL + channelId, hubCallbackUrl = config.url + URL_POSTFIX ) return response.status() == 202 } fun getChatIds(channelId: String): Set<Long> { // todo: remove this after troubleshooting logger<YoutubeSubscriptionService>().info("existing subscriptions: {}", existingSubscriptions) return existingSubscriptions.asSequence() .filter { it.channelId == channelId } .flatMap { it.chats.asSequence() } .map { it.chatId } .toSet() } fun addPostedVideo(video: PostedVideo) { postedVideosRepository.save(video) } fun retrievePostedVideos(): Iterable<PostedVideo> { return postedVideosRepository.findAll() } companion object { private val CHANNEL_URL = "https://www.youtube.com/xml/feeds/videos.xml?channel_id=" private val URL_POSTFIX = "/youtube" } }
mit
apoi/quickbeer-next
app/src/main/java/quickbeer/android/util/ktx/ZonedDateTimeExt.kt
2
2220
/* * This file is part of QuickBeer. * Copyright (C) 2017 Antti Poikela <[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 quickbeer.android.util.ktx import org.threeten.bp.Instant import org.threeten.bp.ZoneId import org.threeten.bp.ZoneOffset import org.threeten.bp.ZonedDateTime import org.threeten.bp.format.DateTimeFormatter import org.threeten.bp.format.FormatStyle import org.threeten.bp.temporal.ChronoUnit fun ZonedDateTime?.orEpoch(): ZonedDateTime { return if (isValidDate()) this!! else ZonedDateTime.ofInstant(Instant.ofEpochSecond(0), ZoneOffset.UTC) } fun ZonedDateTime?.isValidDate(): Boolean { return this != null && this.toEpochSecond() > 0 } fun ZonedDateTime?.within(millis: Long): Boolean { val compare = ZonedDateTime.now().minus(millis, ChronoUnit.MILLIS) return this != null && this > compare } fun ZonedDateTime?.formatDateTime(template: String): String { val localTime = orEpoch().withZoneSameInstant(ZoneId.systemDefault()) return String.format( template, localTime.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)), localTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)) ) } fun ZonedDateTime?.formatDate(): String { return orEpoch() .withZoneSameInstant(ZoneId.systemDefault()) .format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)) } fun ZonedDateTime?.orLater(other: ZonedDateTime?): ZonedDateTime? { return when { this == null -> other other == null -> this this > other -> this else -> other } }
gpl-3.0
google/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/impl/ToolboxLiteGen.kt
4
2842
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.intellij.build.impl import com.intellij.openapi.util.SystemInfo import com.intellij.util.SystemProperties import com.intellij.util.execution.ParametersListUtil import org.codehaus.groovy.runtime.ProcessGroovyMethods import org.jetbrains.intellij.build.BuildMessages import org.jetbrains.intellij.build.dependencies.BuildDependenciesCommunityRoot import org.jetbrains.intellij.build.dependencies.BuildDependenciesDownloader import org.jetbrains.intellij.build.dependencies.BuildDependenciesExtractOptions import org.jetbrains.intellij.build.dependencies.BuildDependenciesManualRunOnly import java.io.OutputStream import java.net.URI import java.nio.file.Files import java.nio.file.Path internal object ToolboxLiteGen { private fun downloadToolboxLiteGen(communityRoot: BuildDependenciesCommunityRoot?, liteGenVersion: String): Path { val liteGenUri = URI("https://repo.labs.intellij.net/toolbox/lite-gen/lite-gen-$liteGenVersion.zip") val zip = BuildDependenciesDownloader.downloadFileToCacheLocation(communityRoot, liteGenUri) return BuildDependenciesDownloader.extractFileToCacheLocation(communityRoot, zip, BuildDependenciesExtractOptions.STRIP_ROOT) } fun runToolboxLiteGen(communityRoot: BuildDependenciesCommunityRoot?, messages: BuildMessages, liteGenVersion: String, vararg args: String) { check(SystemInfo.isUnix) { "Currently, lite gen runs only on Unix" } val liteGenPath = downloadToolboxLiteGen(communityRoot, liteGenVersion) messages.info("Toolbox LiteGen is at $liteGenPath") val binPath = liteGenPath.resolve("bin/lite") check(Files.isExecutable(binPath)) { "File at \'$binPath\' is missing or not executable" } val command: MutableList<String?> = ArrayList() command.add(binPath.toString()) command.addAll(args) messages.info("Running " + ParametersListUtil.join(command)) val processBuilder = ProcessBuilder(command) processBuilder.directory(liteGenPath.toFile()) processBuilder.environment()["JAVA_HOME"] = SystemProperties.getJavaHome() val process = processBuilder.start() // todo get rid of ProcessGroovyMethods ProcessGroovyMethods.consumeProcessOutputStream(process, System.out as OutputStream) ProcessGroovyMethods.consumeProcessErrorStream(process, System.err as OutputStream) val rc = process.waitFor() check(rc == 0) { "\'${command.joinToString(separator = " ")}\' exited with exit code $rc" } } @JvmStatic fun main(args: Array<String>) { val path = downloadToolboxLiteGen(BuildDependenciesManualRunOnly.getCommunityRootFromWorkingDirectory(), "1.2.1553") println("litegen is at $path") } }
apache-2.0
JetBrains/intellij-community
plugins/kotlin/idea/tests/testData/intentions/importAllMembers/EnumSyntheticMethods.kt
1
120
enum class MyEnum { A, B, C, D, E } fun main() { <caret>MyEnum.A MyEnum.valueOf("A") MyEnum.values() }
apache-2.0
JetBrains/intellij-community
platform/webSymbols/src/com/intellij/webSymbols/documentation/impl/WebSymbolDocumentationTargetImpl.kt
1
6747
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.webSymbols.documentation.impl import com.intellij.lang.documentation.DocumentationMarkup import com.intellij.lang.documentation.DocumentationResult import com.intellij.lang.documentation.DocumentationTarget import com.intellij.model.Pointer import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.scale.ScaleContext import com.intellij.ui.scale.ScaleType import com.intellij.util.IconUtil import com.intellij.util.ui.UIUtil import com.intellij.webSymbols.WebSymbol import com.intellij.webSymbols.WebSymbolOrigin import com.intellij.webSymbols.WebSymbolsBundle import com.intellij.webSymbols.documentation.WebSymbolDocumentation import com.intellij.webSymbols.documentation.WebSymbolDocumentationTarget import com.intellij.webSymbols.impl.scaleToHeight import java.awt.Image import java.awt.image.BufferedImage import javax.swing.Icon internal class WebSymbolDocumentationTargetImpl(override val symbol: WebSymbol) : WebSymbolDocumentationTarget { override fun createPointer(): Pointer<out DocumentationTarget> { val pointer = symbol.createPointer() return Pointer<DocumentationTarget> { pointer.dereference()?.let { WebSymbolDocumentationTargetImpl(it) } } } companion object { fun buildDocumentation(origin: WebSymbolOrigin, doc: WebSymbolDocumentation): DocumentationResult? { val url2ImageMap = mutableMapOf<String, Image>() @Suppress("HardCodedStringLiteral") val contents = StringBuilder() .appendDefinition(doc, url2ImageMap) .appendDescription(doc) .appendSections(doc) .appendFootnote(doc) .toString() .loadLocalImages(origin, url2ImageMap) return DocumentationResult.documentation(contents).images(url2ImageMap).externalUrl(doc.docUrl) } private fun StringBuilder.appendDefinition(doc: WebSymbolDocumentation, url2ImageMap: MutableMap<String, Image>): StringBuilder = append(DocumentationMarkup.DEFINITION_START) .also { doc.icon?.let { appendIcon(it, url2ImageMap).append("&nbsp;&nbsp;") } } .append(doc.definition) .append(DocumentationMarkup.DEFINITION_END) .append('\n') private fun StringBuilder.appendDescription(doc: WebSymbolDocumentation): StringBuilder = doc.description?.let { append(DocumentationMarkup.CONTENT_START).append('\n') .append(it).append('\n') .append(DocumentationMarkup.CONTENT_END) } ?: this private fun StringBuilder.appendSections(doc: WebSymbolDocumentation): StringBuilder = buildSections(doc).let { sections -> if (sections.isNotEmpty()) { append(DocumentationMarkup.SECTIONS_START) .append('\n') sections.entries.forEach { (name, value) -> append(DocumentationMarkup.SECTION_HEADER_START) .append(StringUtil.capitalize(name)) if (value.isNotBlank()) { if (!name.endsWith(":")) append(':') // Workaround misalignment of monospace font if (value.contains("<code")) { append("<code> </code>") } append(DocumentationMarkup.SECTION_SEPARATOR) .append(value) } append(DocumentationMarkup.SECTION_END) .append('\n') } append(DocumentationMarkup.SECTIONS_END) .append('\n') } this } private fun StringBuilder.appendFootnote(doc: WebSymbolDocumentation): StringBuilder = doc.footnote?.let { append(DocumentationMarkup.CONTENT_START) .append(it) .append(DocumentationMarkup.CONTENT_END) .append('\n') } ?: this private fun buildSections(doc: WebSymbolDocumentation): Map<String, String> = LinkedHashMap(doc.descriptionSections).also { sections -> if (doc.required) sections[WebSymbolsBundle.message("mdn.documentation.section.isRequired")] = "" if (doc.deprecated) sections[WebSymbolsBundle.message("mdn.documentation.section.status.Deprecated")] = "" if (doc.experimental) sections[WebSymbolsBundle.message("mdn.documentation.section.status.Experimental")] = "" doc.defaultValue?.let { sections[WebSymbolsBundle.message("mdn.documentation.section.defaultValue")] = "<p><code>$it</code>" } doc.library?.let { sections[WebSymbolsBundle.message("mdn.documentation.section.library")] = "<p>$it" } } private fun StringBuilder.appendIcon(icon: Icon, url2ImageMap: MutableMap<String, Image>): StringBuilder { // TODO adjust it to the actual component being used @Suppress("UndesirableClassUsage") val bufferedImage = BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB) val g = bufferedImage.createGraphics() g.font = UIUtil.getToolTipFont() val height = (g.fontMetrics.getStringBounds("a", g).height / ScaleContext.create().getScale(ScaleType.USR_SCALE)).toInt() g.dispose() val image = try { IconUtil.toBufferedImage(icon.scaleToHeight(height)) } catch (e: Exception) { // ignore return this } val url = "https://img${url2ImageMap.size}" url2ImageMap[url] = image val screenHeight = height * ScaleContext.create().getScale(ScaleType.SYS_SCALE) append("<img src='$url' height=\"$screenHeight\" width=\"${(screenHeight * icon.iconWidth) / icon.iconHeight}\" border=0 />") return this } private val imgSrcRegex = Regex("<img [^>]*src\\s*=\\s*['\"]([^'\"]+)['\"]") private fun String.loadLocalImages(origin: WebSymbolOrigin, url2ImageMap: MutableMap<String, Image>): String { val replaces = imgSrcRegex.findAll(this) .mapNotNull { it.groups[1] } .filter { !it.value.contains(':') } .mapNotNull { group -> origin.loadIcon(group.value) ?.let { IconUtil.toBufferedImage(it, true) } ?.let { val url = "https://img${url2ImageMap.size}" url2ImageMap[url] = it Pair(group.range, url) } } .sortedBy { it.first.first } .toList() if (replaces.isEmpty()) return this val result = StringBuilder() var lastIndex = 0 for (replace in replaces) { result.appendRange(this, lastIndex, replace.first.first) result.append(replace.second) lastIndex = replace.first.last + 1 } if (lastIndex < this.length) { result.appendRange(this, lastIndex, this.length) } return result.toString() } } }
apache-2.0
Atsky/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/debugger/protocol/FlowCommand.kt
1
4649
package org.jetbrains.haskell.debugger.protocol import org.jetbrains.haskell.debugger.parser.GHCiParser import java.util.Deque import org.jetbrains.haskell.debugger.parser.HsStackFrameInfo import org.jetbrains.haskell.debugger.utils.HaskellUtils import org.jetbrains.haskell.debugger.frames.HsDebuggerEvaluator import com.intellij.xdebugger.evaluation.XDebuggerEvaluator import com.intellij.xdebugger.frame.XValue import org.jetbrains.haskell.debugger.frames.HsDebugValue import com.intellij.notification.Notifications import com.intellij.notification.Notification import com.intellij.notification.NotificationType import org.jetbrains.haskell.debugger.frames.HsSuspendContext import org.jetbrains.haskell.debugger.frames.ProgramThreadInfo import org.json.simple.JSONObject import org.jetbrains.haskell.debugger.frames.HsHistoryFrame import org.jetbrains.haskell.debugger.parser.JSONConverter import org.jetbrains.haskell.debugger.procdebuggers.utils.DebugRespondent import org.jetbrains.haskell.debugger.procdebuggers.ProcessDebugger import org.jetbrains.haskell.debugger.breakpoints.HaskellLineBreakpointDescription /** * Base class for commands that continue program execution until reaching breakpoint or finish * (trace and continue commands) * * Created by vlad on 7/17/14. */ abstract class FlowCommand(callback: CommandCallback<HsStackFrameInfo?>?) : AbstractCommand<HsStackFrameInfo?>(callback) { override fun parseGHCiOutput(output: Deque<String?>): HsStackFrameInfo? = GHCiParser.tryParseStoppedAt(output) override fun parseJSONOutput(output: JSONObject): HsStackFrameInfo? = JSONConverter.stoppedAtFromJSON(output) class StandardFlowCallback(val debugger: ProcessDebugger, val debugRespondent: DebugRespondent) : CommandCallback<HsStackFrameInfo?>() { override fun execBeforeSending() = debugRespondent.resetHistoryStack() override fun execAfterParsing(result: HsStackFrameInfo?) { if (result != null) { if (result.filePosition == null) { setExceptionContext(result) return } val module = debugRespondent.getModuleByFile(result.filePosition.filePath) val breakpoint = debugRespondent.getBreakpointAt(module, result.filePosition.rawStartLine) val condition = breakpoint?.condition if (breakpoint != null && condition != null) { handleCondition(breakpoint, condition, result) } else { setContext(result, breakpoint) } } else { debugRespondent.traceFinished() } } private fun handleCondition(breakpoint: HaskellLineBreakpointDescription, condition: String, result: HsStackFrameInfo) { val evaluator = HsDebuggerEvaluator(debugger) evaluator.evaluate(condition, object : XDebuggerEvaluator.XEvaluationCallback { override fun errorOccurred(errorMessage: String) { val msg = "Condition \"$condition\" of breakpoint at line ${breakpoint.line}" + "cannot be evaluated, reason: $errorMessage" Notifications.Bus.notify(Notification("", "Wrong breakpoint condition", msg, NotificationType.WARNING)) setContext(result, breakpoint) } override fun evaluated(evalResult: XValue) { if (evalResult is HsDebugValue && evalResult.binding.typeName == HaskellUtils.HS_BOOLEAN_TYPENAME && evalResult.binding.value == HaskellUtils.HS_BOOLEAN_TRUE) { setContext(result, breakpoint) } else { debugger.resume() } } }, null) } private fun setExceptionContext(result: HsStackFrameInfo) { val frame = HsHistoryFrame(debugger, result) frame.obsolete = false debugRespondent.historyChange(frame, null) val context = HsSuspendContext(debugger, ProgramThreadInfo(null, "Main", result)) debugRespondent.exceptionReached(context) } private fun setContext(result: HsStackFrameInfo, breakpoint: HaskellLineBreakpointDescription?) { val frame = HsHistoryFrame(debugger, result) frame.obsolete = false debugger.history(HistoryCommand.DefaultHistoryCallback(debugger, debugRespondent, frame, breakpoint)) } } }
apache-2.0
tid-kijyun/Android-Kotlin-Sampler
app/src/androidTest/java/com/tid/android_kotlin_sampler/ApplicationTest.kt
1
284
package com.tid.android_kotlin_sampler import android.app.Application import android.test.ApplicationTestCase /** * [Testing Fundamentals](http://d.android.com/tools/testing/testing_android.html) */ class ApplicationTest : ApplicationTestCase<Application>(Application::class.java)
apache-2.0
JetBrains/intellij-community
platform/platform-tests/testSrc/com/intellij/openapi/project/impl/RecentProjectsTest.kt
1
7473
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet") package com.intellij.openapi.project.impl import com.intellij.ide.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.ProjectCloseListener import com.intellij.openapi.project.ex.ProjectManagerEx import com.intellij.project.stateStore import com.intellij.testFramework.* import com.intellij.testFramework.assertions.Assertions.assertThat import com.intellij.ui.DeferredIconImpl import com.intellij.util.IconUtil import com.intellij.util.PathUtil import com.intellij.util.messages.SimpleMessageBusConnection import com.intellij.util.ui.EmptyIcon import kotlinx.coroutines.runBlocking import org.junit.ClassRule import org.junit.Rule import org.junit.Test import org.junit.rules.ExternalResource import java.awt.Color import java.nio.file.Path import java.util.* class RecentProjectsTest { companion object { @ClassRule @JvmField val appRule = ApplicationRule() @ClassRule @JvmField val edtRule = EdtRule() } @Rule @JvmField val disposableRule = DisposableRule() @Rule @JvmField internal val busConnection = RecentProjectManagerListenerRule() @Rule @JvmField val tempDir = TemporaryDirectory() @Test fun testMostRecentOnTop() = runBlocking { val p1 = createAndOpenProject("p1") val p2 = createAndOpenProject("p2") val p3 = createAndOpenProject("p3") checkRecents("p3", "p2", "p1") doReopenCloseAndCheck(p2, "p2", "p3", "p1") doReopenCloseAndCheck(p1, "p1", "p2", "p3") doReopenCloseAndCheck(p3, "p3", "p1", "p2") } @Test fun testGroupsOrder() = runBlocking { val p1 = createAndOpenProject("p1") val p2 = createAndOpenProject("p2") val p3 = createAndOpenProject("p3") val p4 = createAndOpenProject("p4") val manager = RecentProjectsManager.getInstance() val g1 = ProjectGroup("g1") val g2 = ProjectGroup("g2") manager.addGroup(g1) manager.addGroup(g2) g1.addProject(p1.toString()) g1.addProject(p2.toString()) g2.addProject(p3.toString()) checkGroups(listOf("g2", "g1")) doReopenCloseAndCheckGroups(p4, listOf("g2", "g1")) doReopenCloseAndCheckGroups(p1, listOf("g1", "g2")) doReopenCloseAndCheckGroups(p3, listOf("g2", "g1")) } @Test fun timestampForOpenProjectUpdatesWhenGetStateCalled(): Unit = runBlocking { val z1 = tempDir.newPath("z1") val projectManager = ProjectManagerEx.getInstanceEx() var project = projectManager.openProjectAsync(z1, createTestOpenProjectOptions(runPostStartUpActivities = false))!! try { val recentProjectManager = RecentProjectsManagerBase.getInstanceEx() recentProjectManager.projectOpened(project) val timestamp = getProjectOpenTimestamp("z1") projectManager.forceCloseProjectAsync(project) project = projectManager.openProjectAsync(z1, createTestOpenProjectOptions(runPostStartUpActivities = false))!! recentProjectManager.projectOpened(project) recentProjectManager.updateLastProjectPath() // "Timestamp for opened project has not been updated" assertThat(getProjectOpenTimestamp("z1")).isGreaterThan(timestamp) } finally { projectManager.forceCloseProjectAsync(project) } } @Test fun testSlnLikeProjectIcon() { // For Rider val rpm = (RecentProjectsManager.getInstance() as RecentProjectsManagerBase) val projectDir = Path.of("${PlatformTestUtil.getPlatformTestDataPath()}/recentProjects/dotNetSampleRecent/Povysh") val slnFile = projectDir.resolve("Povysh.sln") val icon = (rpm.getProjectIcon(slnFile.toString(), isProjectValid = true) as DeferredIconImpl<*>).evaluate() assertThat(icon).isNotInstanceOf(EmptyIcon::class.java) // Check that image is loaded from file, and not generated by IDE val iconImage = IconUtil.toBufferedImage(icon) for (x in 0 until iconImage.width) { for (y in 0 until iconImage.height) { val color = iconImage.getRGB(x, y) assertThat(color).isEqualTo(Color.BLUE.rgb) } } } private fun getProjectOpenTimestamp(@Suppress("SameParameterValue") projectName: String): Long { val additionalInfo = RecentProjectsManagerBase.getInstanceEx().state.additionalInfo for (s in additionalInfo.keys) { if (s.endsWith(projectName) || s.substringBeforeLast('_').endsWith(projectName)) { return additionalInfo.get(s)!!.projectOpenTimestamp } } return -1 } private suspend fun doReopenCloseAndCheck(projectPath: Path, vararg results: String) { openProjectAndClose(projectPath) checkRecents(*results) } private suspend fun openProjectAndClose(projectPath: Path) { val projectManager = ProjectManagerEx.getInstanceEx() val project = projectManager.openProjectAsync(projectPath, createTestOpenProjectOptions(runPostStartUpActivities = false))!! try { RecentProjectsManagerBase.getInstanceEx().projectOpened(project) } finally { projectManager.forceCloseProjectAsync(project) } } private suspend fun doReopenCloseAndCheckGroups(projectPath: Path, results: List<String>) { openProjectAndClose(projectPath) checkGroups(results) } private fun checkRecents(vararg recents: String) { val recentProjects = listOf(*recents) val state = (RecentProjectsManager.getInstance() as RecentProjectsManagerBase).state val projects = state.additionalInfo.keys.asSequence() .map { s -> PathUtil.getFileName(s).substringAfter('_').substringBeforeLast('_') } .filter { recentProjects.contains(it) } .toList() assertThat(projects.reversed()).isEqualTo(recentProjects) } private fun checkGroups(groups: List<String>) { val recentGroups = RecentProjectListActionProvider.getInstance().getActions(false, true).asSequence() .filter { a -> a is ProjectGroupActionGroup } .map { a -> (a as ProjectGroupActionGroup).group.name } .toList() assertThat(recentGroups).isEqualTo(groups) } private suspend fun createAndOpenProject(name: String): Path { val path = tempDir.newPath(name) val projectManager = ProjectManagerEx.getInstanceEx() var project = projectManager.openProjectAsync(path, createTestOpenProjectOptions(runPostStartUpActivities = false))!! try { val recentProjectManager = RecentProjectsManagerBase.getInstanceEx() recentProjectManager.projectOpened(project) project.stateStore.saveComponent(RecentProjectsManager.getInstance() as RecentProjectsManagerBase) projectManager.forceCloseProjectAsync(project) project = projectManager.openProjectAsync(path, createTestOpenProjectOptions(runPostStartUpActivities = false))!! recentProjectManager.projectOpened(project) return path } finally { projectManager.forceCloseProjectAsync(project) } } } internal class RecentProjectManagerListenerRule : ExternalResource() { private var connection: SimpleMessageBusConnection? = null override fun before() { connection = ApplicationManager.getApplication().messageBus.simpleConnect() connection!!.subscribe(ProjectCloseListener.TOPIC, RecentProjectsManagerBase.MyProjectListener()) connection!!.subscribe(AppLifecycleListener.TOPIC, RecentProjectsManagerBase.MyAppLifecycleListener()) } override fun after() { connection?.disconnect() } }
apache-2.0
Atsky/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/psi/reference/TypeReference.kt
1
1643
package org.jetbrains.haskell.psi.reference import org.jetbrains.haskell.psi.SomeId import com.intellij.psi.PsiReferenceBase import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import org.jetbrains.haskell.psi.Module import org.jetbrains.haskell.psi.TypeVariable import org.jetbrains.haskell.scope.ModuleScope import com.intellij.psi.ElementManipulator import org.jetbrains.haskell.psi.util.HaskellElementFactory /** * Created by atsky on 4/25/14. */ class TypeReference(val typeRef: TypeVariable) : PsiReferenceBase<TypeVariable>( typeRef, TextRange(0, typeRef.textRange!!.length)) { override fun resolve(): PsiElement? { val module = Module.findModule(element!!) if (module != null) { for (aType in ModuleScope(module).getVisibleDataDeclarations()) { if (aType.getDeclarationName() == typeRef.text) { return aType.getNameElement() } } for (aType in ModuleScope(module).getVisibleTypeSynonyms()) { if (aType.getDeclarationName() == typeRef.text) { return aType.getNameElement() } } } return null } override fun getVariants(): Array<Any> = arrayOf() override fun handleElementRename(newElementName: String?): PsiElement? { if (newElementName != null) { val qcon = HaskellElementFactory.createExpressionFromText(element.project, newElementName) element.firstChild.replace(qcon) return qcon } else { return null } } }
apache-2.0
sheaam30/setlist
domain/src/main/java/setlist/shea/domain/csv/Parser.kt
1
218
package setlist.shea.domain.csv import setlist.shea.domain.model.Song import java.io.InputStream /** * Created by Adam on 8/27/2017. */ interface Parser { fun readFile(inputStream: InputStream?) : List<Song> }
apache-2.0
Skatteetaten/boober
src/main/kotlin/no/skatteetaten/aurora/boober/utils/ConditionalOnPropertyMissingOrEmpty.kt
1
1360
package no.skatteetaten.aurora.boober.utils import org.springframework.context.annotation.Condition import org.springframework.context.annotation.ConditionContext import org.springframework.context.annotation.Conditional import org.springframework.core.type.AnnotatedTypeMetadata import java.lang.annotation.Retention import java.lang.annotation.RetentionPolicy @Target( AnnotationTarget.CLASS, AnnotationTarget.FILE, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER ) @Retention(RetentionPolicy.RUNTIME) @Conditional(ConditionalOnPropertyMissingOrEmpty.OnPropertyNotEmptyCondition::class) annotation class ConditionalOnPropertyMissingOrEmpty(vararg val value: String) { class OnPropertyNotEmptyCondition : Condition { override fun matches(context: ConditionContext, metadata: AnnotatedTypeMetadata): Boolean { val properties: List<String?>? = metadata.getAnnotationAttributes(ConditionalOnPropertyMissingOrEmpty::class.java.name) ?.let { it["value"] as Array<*> }?.map { context.environment.getProperty(it as String) } return properties?.any { it == null || it == "false" } ?: true } } }
apache-2.0
allotria/intellij-community
plugins/changeReminder/src/com/jetbrains/changeReminder/plugin/UserSettings.kt
2
1312
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.changeReminder.plugin import com.intellij.openapi.Disposable import com.intellij.openapi.components.BaseState import com.intellij.openapi.components.SimplePersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.util.EventDispatcher import java.util.* @State(name = "ChangeReminder", storages = [Storage(file = "changeReminder.xml")]) internal class UserSettings : SimplePersistentStateComponent<UserSettingsState>(UserSettingsState()) { private val eventDispatcher = EventDispatcher.create(PluginStatusListener::class.java) var isPluginEnabled: Boolean get() = state.isPluginEnabled set(value) { state.isPluginEnabled = value eventDispatcher.multicaster.statusChanged(value) } fun addPluginStatusListener(listener: PluginStatusListener, parentDisposable: Disposable) { eventDispatcher.addListener(listener, parentDisposable) } interface PluginStatusListener : EventListener { fun statusChanged(isEnabled: Boolean) } } internal class UserSettingsState : BaseState() { var isPluginEnabled: Boolean by property(false) }
apache-2.0
WeAthFoLD/Momentum
Demo/Hello/src/main/kotlin/Hello.kt
1
274
import org.lwjgl.opengl.Display import org.lwjgl.opengl.DisplayMode fun main(args: Array<String>) { Display.setDisplayMode(DisplayMode(1280, 720)) Display.create() while (!Display.isCloseRequested()) { Display.update() } Display.destroy() }
mit
googlemaps/android-places-demos
demo-kotlin/app/src/v3/java/com/example/placesdemo/programmatic_autocomplete/PlacePredictionAdapter.kt
1
3105
/** * DO NOT EDIT THIS FILE. * * This source code was autogenerated from source code within the `app/src/gms` directory * and is not intended for modifications. If any edits should be made, please do so in the * corresponding file under the `app/src/gms` directory. */ // Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.placesdemo.programmatic_autocomplete import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ViewHolder import com.example.placesdemo.R import com.example.placesdemo.programmatic_autocomplete.PlacePredictionAdapter.PlacePredictionViewHolder import com.google.android.libraries.places.api.model.AutocompletePrediction import java.util.* /** * A [RecyclerView.Adapter] for a [com.google.android.libraries.places.api.model.AutocompletePrediction]. */ class PlacePredictionAdapter : RecyclerView.Adapter<PlacePredictionViewHolder>() { private val predictions: MutableList<AutocompletePrediction> = ArrayList() var onPlaceClickListener: ((AutocompletePrediction) -> Unit)? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlacePredictionViewHolder { val inflater = LayoutInflater.from(parent.context) return PlacePredictionViewHolder( inflater.inflate(R.layout.place_prediction_item, parent, false)) } override fun onBindViewHolder(holder: PlacePredictionViewHolder, position: Int) { val place = predictions[position] holder.setPrediction(place) holder.itemView.setOnClickListener { onPlaceClickListener?.invoke(place) } } override fun getItemCount(): Int { return predictions.size } fun setPredictions(predictions: List<AutocompletePrediction>?) { this.predictions.clear() this.predictions.addAll(predictions!!) notifyDataSetChanged() } class PlacePredictionViewHolder(itemView: View) : ViewHolder(itemView) { private val title: TextView = itemView.findViewById(R.id.text_view_title) private val address: TextView = itemView.findViewById(R.id.text_view_address) fun setPrediction(prediction: AutocompletePrediction) { title.text = prediction.getPrimaryText(null) address.text = prediction.getSecondaryText(null) } } interface OnPlaceClickListener { fun onPlaceClicked(place: AutocompletePrediction) } }
apache-2.0
allotria/intellij-community
platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/SoftLinksTest.kt
3
4557
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage import com.intellij.testFramework.UsefulTestCase.assertOneElement import com.intellij.workspaceModel.storage.entities.* import junit.framework.Assert.assertEquals import junit.framework.Assert.assertNotNull import org.junit.Test /** * Soft reference * Persistent id via soft reference * Persistent id via strong reference */ class SoftLinksTest { @Test fun `test add diff with soft links`() { val id = "MyId" val newId = "MyNewId" // Setup builder for test val builder = createEmptyBuilder() builder.addEntity(ModifiableWithSoftLinkEntity::class.java, MySource) { this.link = NameId(id) } builder.addEntity(ModifiableNamedEntity::class.java, MySource) { name = id } // Change persistent id in a different builder val newBuilder = createBuilderFrom(builder.toStorage()) val entity = newBuilder.resolve(NameId(id))!! newBuilder.modifyEntity(ModifiableNamedEntity::class.java, entity) { this.name = newId } // Apply changes builder.addDiff(newBuilder) // Check assertNotNull(builder.resolve(NameId(newId))) assertOneElement(builder.referrers(NameId(newId), WithSoftLinkEntity::class.java).toList()) } @Test fun `test add diff with soft links and back`() { val id = "MyId" val newId = "MyNewId" // Setup builder for test val builder = createEmptyBuilder() builder.addEntity(ModifiableWithSoftLinkEntity::class.java, MySource) { this.link = NameId(id) } builder.addEntity(ModifiableNamedEntity::class.java, MySource) { name = id } // Change persistent id in a different builder val newBuilder = createBuilderFrom(builder.toStorage()) val entity = newBuilder.resolve(NameId(id))!! newBuilder.modifyEntity(ModifiableNamedEntity::class.java, entity) { this.name = newId } // Apply changes builder.addDiff(newBuilder) // Check assertNotNull(builder.resolve(NameId(newId))) assertOneElement(builder.referrers(NameId(newId), WithSoftLinkEntity::class.java).toList()) // Change persistent id to the initial value val anotherNewBuilder = createBuilderFrom(builder.toStorage()) val anotherEntity = anotherNewBuilder.resolve(NameId(newId))!! anotherNewBuilder.modifyEntity(ModifiableNamedEntity::class.java, anotherEntity) { this.name = id } // Apply changes builder.addDiff(anotherNewBuilder) // Check assertNotNull(builder.resolve(NameId(id))) assertOneElement(builder.referrers(NameId(id), WithSoftLinkEntity::class.java).toList()) } @Test fun `change persistent id part`() { val builder = createEmptyBuilder() val entity = builder.addNamedEntity("Name") builder.addWithSoftLinkEntity(entity.persistentId()) builder.modifyEntity(ModifiableNamedEntity::class.java, entity) { this.name = "newName" } builder.assertConsistency() assertEquals("newName", builder.entities(WithSoftLinkEntity::class.java).single().link.presentableName) } @Test fun `change persistent id part of composed id entity`() { val builder = createEmptyBuilder() val entity = builder.addNamedEntity("Name") builder.addComposedIdSoftRefEntity("AnotherName", entity.persistentId()) builder.modifyEntity(ModifiableNamedEntity::class.java, entity) { this.name = "newName" } builder.assertConsistency() val updatedPersistentId = builder.entities(ComposedIdSoftRefEntity::class.java).single().persistentId() assertEquals("newName", updatedPersistentId.link.presentableName) } @Test fun `change persistent id part of composed id entity and with linked entity`() { val builder = createEmptyBuilder() val entity = builder.addNamedEntity("Name") val composedIdEntity = builder.addComposedIdSoftRefEntity("AnotherName", entity.persistentId()) builder.addWithSoftLinkEntity(composedIdEntity.persistentId()) builder.modifyEntity(ModifiableNamedEntity::class.java, entity) { this.name = "newName" } builder.assertConsistency() val updatedPersistentId = builder.entities(ComposedIdSoftRefEntity::class.java).single().persistentId() assertEquals("newName", updatedPersistentId.link.presentableName) assertEquals("newName", (builder.entities(WithSoftLinkEntity::class.java).single().link as ComposedId).link.presentableName) } }
apache-2.0
fboldog/anko
anko/library/robolectricTests/src/test/java/IntentForTest.kt
2
1195
package test import android.app.Activity import android.os.Bundle import org.jetbrains.anko.intentFor import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricGradleTestRunner import org.robolectric.annotation.Config open class IntentForTestActivity : Activity() { public override fun onCreate(savedInstanceState: Bundle?): Unit { super.onCreate(savedInstanceState) } } @RunWith(RobolectricGradleTestRunner::class) @Config(constants = BuildConfig::class) class IntentForTest { @Test fun test() { val activity = Robolectric.buildActivity(IntentForTestActivity::class.java).create().get() val intent1 = activity.intentFor<IntentForTestActivity>() assert(intent1.extras == null) val intent2 = activity.intentFor<IntentForTestActivity>( "one" to 1, "abc" to "ABC", "null" to null) val extras2 = intent2.extras!! assert(extras2.size() == 3) assert(extras2.get("one") == 1) assert(extras2.get("abc") == "ABC") assert(extras2.get("null") == null) println("[COMPLETE]") } }
apache-2.0
PaulWoitaschek/Slimber
slimber/src/test/kotlin/slimber/log/SlimberTest.kt
1
1618
package slimber.log import com.google.common.truth.Truth import org.junit.After import org.junit.Before import org.junit.Test import timber.log.Timber class SlimberTest { @Before @After fun uproot() { // clear timber after each test Timber.uprootAll() } /** Tests that the log messages arrive */ @Test fun logs() { val loggingTree = LoggingTree() Timber.plant(loggingTree) Timber.tag("i") i { "info" } Timber.tag("d") d { "debug" } Timber.tag("w") w { "warn" } Timber.tag("e") e { "error" } Timber.tag("v") v { "verbose" } Timber.tag("wtf") wtf { "assert" } Truth.assertThat(loggingTree.logs()) .containsExactly( LogItem.i("i", "info"), LogItem.d("d", "debug"), LogItem.w("w", "warn"), LogItem.e("e", "error"), LogItem.v("v", "verbose"), LogItem.wtf("wtf", "assert"), ) } /** test that the blocks are not executed when there are no trees planted */ @Test fun blockNotExecuted() { val logThrowable = RuntimeException() val throwAssertionError = { throw AssertionError() } i(throwAssertionError) i(logThrowable, throwAssertionError) d(throwAssertionError) d(logThrowable, throwAssertionError) w(throwAssertionError) w(logThrowable, throwAssertionError) e(throwAssertionError) e(logThrowable, throwAssertionError) v(throwAssertionError) v(logThrowable, throwAssertionError) wtf(throwAssertionError) wtf(logThrowable, throwAssertionError) } }
apache-2.0
VREMSoftwareDevelopment/WiFiAnalyzer
app/src/main/kotlin/com/vrem/wifianalyzer/navigation/NavigationGroup.kt
1
2152
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.vrem.wifianalyzer.navigation import android.view.Menu enum class NavigationGroup(val navigationMenus: List<NavigationMenu>) { GROUP_FEATURE(listOf(NavigationMenu.ACCESS_POINTS, NavigationMenu.CHANNEL_RATING, NavigationMenu.CHANNEL_GRAPH, NavigationMenu.TIME_GRAPH)), GROUP_OTHER(listOf(NavigationMenu.EXPORT, NavigationMenu.CHANNEL_AVAILABLE, NavigationMenu.VENDORS, NavigationMenu.PORT_AUTHORITY)), GROUP_SETTINGS(listOf(NavigationMenu.SETTINGS, NavigationMenu.ABOUT)); fun next(navigationMenu: NavigationMenu): NavigationMenu { var index = navigationMenus.indexOf(navigationMenu) if (index < 0) { return navigationMenu } index++ if (index >= navigationMenus.size) { index = 0 } return navigationMenus[index] } fun previous(navigationMenu: NavigationMenu): NavigationMenu { var index = navigationMenus.indexOf(navigationMenu) if (index < 0) { return navigationMenu } index-- if (index < 0) { index = navigationMenus.size - 1 } return navigationMenus[index] } fun populateMenuItems(menu: Menu): Unit = navigationMenus.forEach { val menuItem = menu.add(ordinal, it.ordinal, it.ordinal, it.title) menuItem.setIcon(it.icon) } }
gpl-3.0
crispab/codekvast
product/server/intake/src/main/kotlin/io/codekvast/intake/file_import/InvocationDataImporter.kt
1
1573
/* * Copyright (c) 2015-2022 Hallin Information Technology AB * * 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.codekvast.intake.file_import import io.codekvast.javaagent.model.v2.InvocationDataPublication2 /** @author [email protected] */ interface InvocationDataImporter { /** * Imports an InvocationDataPublication2 * * @param publication The publication to import. * @return true iff the publication was handled. */ fun importPublication(publication: InvocationDataPublication2): Boolean }
mit
leafclick/intellij-community
platform/workspaceModel-core-tests/test/com/intellij/workspace/api/ProxyBasedDiffBuilderTest.kt
1
3150
package com.intellij.workspace.api import org.junit.Assert.assertEquals import org.junit.Test private fun TypedEntityStorageBuilder.applyDiff(anotherBuilder: TypedEntityStorageBuilder): TypedEntityStorage { val storage = (this as ProxyBasedEntityStorage).applyDiff(anotherBuilder as TypedEntityStorageDiffBuilder) storage.checkConsistency() return storage } class ProxyBasedDiffBuilderTest { @Test fun `add entity`() { val source = TypedEntityStorageBuilder.create() source.addSampleEntity("first") val target = TypedEntityStorageBuilder.create() target.addSampleEntity("second") val storage = target.applyDiff(source) assertEquals(setOf("first", "second"), storage.entities(SampleEntity::class.java).mapTo(HashSet()) { it.stringProperty }) } @Test fun `remove entity`() { val target = TypedEntityStorageBuilder.create() val entity = target.addSampleEntity("hello") val entity2 = target.addSampleEntity("hello") val source = TypedEntityStorageBuilder.from(target.toStorage()) source.removeEntity(entity) val storage = target.applyDiff(source) assertEquals(entity2, storage.singleSampleEntity()) } @Test fun `modify entity`() { val target = TypedEntityStorageBuilder.create() val entity = target.addSampleEntity("hello") val source = TypedEntityStorageBuilder.from(target.toStorage()) source.modifyEntity(ModifiableSampleEntity::class.java, entity) { stringProperty = "changed" } val storage = target.applyDiff(source) assertEquals("changed", storage.singleSampleEntity().stringProperty) } @Test fun `remove removed entity`() { val target = TypedEntityStorageBuilder.create() val entity = target.addSampleEntity("hello") val entity2 = target.addSampleEntity("hello") val source = TypedEntityStorageBuilder.from(target.toStorage()) target.removeEntity(entity) target.checkConsistency() source.checkConsistency() source.removeEntity(entity) val storage = target.applyDiff(source) assertEquals(entity2, storage.singleSampleEntity()) } @Test fun `modify removed entity`() { val target = TypedEntityStorageBuilder.create() val entity = target.addSampleEntity("hello") val source = TypedEntityStorageBuilder.from(target.toStorage()) target.removeEntity(entity) source.checkConsistency() source.modifyEntity(ModifiableSampleEntity::class.java, entity) { stringProperty = "changed" } val storage = target.applyDiff(source) assertEquals(emptyList<SampleEntity>(), storage.entities(SampleEntity::class.java).toList()) } @Test fun `remove modified entity`() { val target = TypedEntityStorageBuilder.create() val entity = target.addSampleEntity("hello") val source = TypedEntityStorageBuilder.from(target.toStorage()) target.modifyEntity(ModifiableSampleEntity::class.java, entity) { stringProperty = "changed" } source.removeEntity(entity) source.checkConsistency() val storage = target.applyDiff(source) assertEquals(emptyList<SampleEntity>(), storage.entities(SampleEntity::class.java).toList()) } }
apache-2.0
agoda-com/Kakao
kakao/src/main/kotlin/com/agoda/kakao/dialog/KAlertDialog.kt
1
1051
package com.agoda.kakao.dialog import android.app.AlertDialog import com.agoda.kakao.common.views.KBaseView import com.agoda.kakao.image.KImageView import com.agoda.kakao.text.KButton import com.agoda.kakao.text.KTextView /** * View for interact with default alert dialog * * @see AlertDialog */ class KAlertDialog : KBaseView<KAlertDialog>({ isRoot() }) { init { inRoot { isDialog() } } val positiveButton = KButton { withId(android.R.id.button1) } .also { it.inRoot { isDialog() } } val negativeButton = KButton { withId(android.R.id.button2) } .also { it.inRoot { isDialog() } } val neutralButton = KButton { withId(android.R.id.button3) } .also { it.inRoot { isDialog() } } val title = KTextView { withResourceName("alertTitle")} .also { it.inRoot { isDialog() } } val message = KTextView { withId(android.R.id.message) } .also { it.inRoot { isDialog() } } val icon = KImageView { withId(android.R.id.icon) } .also { it.inRoot { isDialog() } } }
apache-2.0
code-helix/slatekit
src/lib/kotlin/slatekit-meta/src/main/kotlin/slatekit/meta/models/Model.kt
1
5488
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: Kishore Reddy * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A tool-kit, utility library and server-backend * mantra: Simplicity above all else * </slate_header> */ package slatekit.meta.models import slatekit.utils.naming.Namer import slatekit.common.ext.orElse import slatekit.meta.Reflector import slatekit.meta.Schema import kotlin.reflect.KClass /** * Stores the schema of a data-model with properties. */ class Model( val name: String, val fullName: String, val dataType: KClass<*>? = null, val desc: String = "", tableName: String = "", modelFields: List<ModelField>? = null, val namer: Namer? = null ) { constructor(dataType: KClass<*>, tableName: String = "") : this(dataType.simpleName!!, dataType.qualifiedName!!, dataType, tableName = tableName) constructor(dataType: KClass<*>, fields: List<ModelField>, tableName: String = "") : this(dataType.simpleName!!, dataType.qualifiedName!!, dataType, tableName = tableName, modelFields = fields) /** * The name of the table */ val table = tableName.orElse(name) /** * gets the list of fields in this model or returns an emptylist if none * @return */ val fields: List<ModelField> = modelFields ?: listOf() /** * Lookup of field names to column names */ val lookup: Map<String, ModelField> = loadFields(fields) /** * The field that represents the id */ val idField: ModelField? = fields.find { p -> p.category == FieldCategory.Id } /** * whether there are any fields in the model * @return */ val any: Boolean get() = size > 0 /** * whether this model has an id field * @return */ val hasId: Boolean get() = idField != null /** * the number of fields in this model. * @return */ val size: Int get() = fields.size fun add(field: ModelField): Model { val newPropList = fields.plus(field) return Model(this.name, fullName, this.dataType, desc, table, newPropList) } companion object { inline fun <reified TId, reified T> of(builder: Schema<TId, T>.() -> Unit ): Model where TId : Comparable<TId>, T:Any { val schema = Schema<TId, T>(TId::class, T::class) builder(schema) return schema.model } fun <TId, T> of(idType:KClass<*>, tType:KClass<*>, builder: Schema<TId, T>.() -> Unit ): Model where TId : Comparable<TId>, T:Any { val schema = Schema<TId, T>(idType, tType) builder(schema) return schema.model } /** * Builds a schema ( Model ) from the Class/Type supplied. * NOTE: The mapper then works off the Model class for to/from mapping of data to model. * @param dataType * @return */ @JvmStatic fun load (dataType: KClass<*>, idFieldName: String? = null, namer: Namer? = null, table: String? = null): Model { val modelName = dataType.simpleName ?: "" val modelNameFull = dataType.qualifiedName ?: "" // Get Id val idFields = Reflector.getAnnotatedProps<Id>(dataType, Id::class) val idField = idFields.firstOrNull() // Now add all the fields. val matchedFields = Reflector.getAnnotatedProps<Field>(dataType, Field::class) // Loop through each field val withAnnos = matchedFields.filter { it.second != null } val fields = withAnnos.map { matchedField -> val modelField = ModelField.ofData(matchedField.first, matchedField.second!!, namer, idField == null, idFieldName) val finalModelField = if (!modelField.isBasicType()) { val model = load(modelField.dataCls, namer = namer) modelField.copy(model = model) } else modelField finalModelField } val allFields = when(idField) { null -> fields else -> mutableListOf(ModelField.ofId(idField.first, "", namer)).plus(fields) } return Model(modelName, modelNameFull, dataType, modelFields = allFields, namer = namer, tableName = table ?: modelName) } fun loadFields(modelFields: List<ModelField>):Map<String, ModelField> { val fields = modelFields.fold(mutableListOf<Pair<String, ModelField>>()) { acc, field -> when(field.model) { null -> acc.add(field.name to field) else -> { acc.add(field.name to field) field.model.fields.forEach { subField -> // Need to modify the field name and stored name here as "a_b" val subFieldName = field.name + "_" + subField.name val subFieldColumn = field.name + "_" + subField.storedName val subFieldFinal = subField.copy(storedName = subFieldColumn) acc.add(subFieldName to subFieldFinal) } } } acc }.toMap() return fields } } }
apache-2.0
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/boxInline/defaultValues/lambdaInlining/callableReferences/privateFunctionReference.kt
1
287
// FILE: 1.kt // LANGUAGE_VERSION: 1.2 // SKIP_INLINE_CHECK_IN: inlineFun$default package test private fun ok() = "OK" internal inline fun inlineFun(lambda: () -> String = ::ok): String { return lambda() } // FILE: 2.kt import test.* fun box(): String { return inlineFun() }
apache-2.0
AndroidX/androidx
compose/foundation/foundation-layout/benchmark/src/androidTest/java/androidx/compose/foundation/layout/benchmark/view/WeightedLinearLayoutBenchmark.kt
3
3028
/* * 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.compose.foundation.layout.benchmark.view import androidx.compose.testutils.benchmark.AndroidBenchmarkRule import androidx.compose.testutils.benchmark.benchmarkDrawPerf import androidx.compose.testutils.benchmark.benchmarkFirstDraw import androidx.compose.testutils.benchmark.benchmarkFirstLayout import androidx.compose.testutils.benchmark.benchmarkFirstMeasure import androidx.compose.testutils.benchmark.benchmarkFirstSetContent import androidx.compose.testutils.benchmark.benchmarkLayoutPerf import androidx.compose.testutils.benchmark.toggleStateBenchmarkDraw import androidx.compose.testutils.benchmark.toggleStateBenchmarkLayout import androidx.compose.testutils.benchmark.toggleStateBenchmarkMeasure import androidx.test.filters.LargeTest import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @LargeTest @RunWith(Parameterized::class) class WeightedLinearLayoutBenchmark(private val numberOfBoxes: Int) { private val subLayouts = 5 companion object { @JvmStatic @Parameterized.Parameters(name = "numberOfBoxes={0}") fun initParameters(): Array<Int> = arrayOf(10, 100) } @get:Rule val benchmarkRule = AndroidBenchmarkRule() private val linearLayoutCaseFactory = { WeightedLinearLayoutTestCase(subLayouts, numberOfBoxes) } @Test fun first_setContent() { benchmarkRule.benchmarkFirstSetContent(linearLayoutCaseFactory) } @Test fun first_measure() { benchmarkRule.benchmarkFirstMeasure(linearLayoutCaseFactory) } @Test fun first_layout() { benchmarkRule.benchmarkFirstLayout(linearLayoutCaseFactory) } @Test fun first_draw() { benchmarkRule.benchmarkFirstDraw(linearLayoutCaseFactory) } @Test fun layout() { benchmarkRule.benchmarkLayoutPerf(linearLayoutCaseFactory) } @Test fun draw() { benchmarkRule.benchmarkDrawPerf(linearLayoutCaseFactory) } @Test fun changeLayoutContents_measure() { benchmarkRule.toggleStateBenchmarkMeasure(linearLayoutCaseFactory) } @Test fun changeLayoutContents_layout() { benchmarkRule.toggleStateBenchmarkLayout(linearLayoutCaseFactory) } @Test fun changeLayoutContents_draw() { benchmarkRule.toggleStateBenchmarkDraw(linearLayoutCaseFactory) } }
apache-2.0
hannesa2/owncloud-android
owncloudDomain/src/main/java/com/owncloud/android/domain/exceptions/MoveIntoDescendantException.kt
2
832
/** * ownCloud Android client application * * @author David González Verdugo * Copyright (C) 2020 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * 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.owncloud.android.domain.exceptions import java.lang.Exception class MoveIntoDescendantException : Exception()
gpl-2.0
smmribeiro/intellij-community
platform/vcs-api/src/com/intellij/openapi/vcs/changes/InclusionModel.kt
13
796
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes import com.intellij.util.ui.ThreeStateCheckBox import java.util.* interface InclusionModel { fun getInclusion(): Set<Any> fun getInclusionState(item: Any): ThreeStateCheckBox.State fun isInclusionEmpty(): Boolean fun addInclusion(items: Collection<Any>) fun removeInclusion(items: Collection<Any>) fun setInclusion(items: Collection<Any>) fun retainInclusion(items: Collection<Any>) fun clearInclusion() fun addInclusionListener(listener: InclusionListener) fun removeInclusionListener(listener: InclusionListener) } interface InclusionListener : EventListener { fun inclusionChanged() }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/override/nothingToOverride/removeFunctionReciever.kt
13
162
// "Change function signature to 'fun x(s: String)'" "true" open class A { open fun x(s: String) {} } class B : A() { <caret>override fun String.x() {} }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/j2k/new/tests/testData/newJ2k/types/recursiveType.kt
13
118
class Unconvertable { fun cantConvertThis() { val tester = TestClass2() tester.test(null) } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/properties/callToCustomProperty.kt
13
150
// "Replace with 'bar'" "true" val bar get() = 1 @Deprecated("use property instead", ReplaceWith("bar")) fun foo() = 1 fun test(){ foo<caret>() }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/renameMultiModule/headersAndImplsByImplFun/before/Common/src/test/test.kt
26
124
package test expect fun foo() expect fun foo(n: Int) expect fun bar(n: Int) fun test() { foo() foo(1) bar(1) }
apache-2.0
smmribeiro/intellij-community
plugins/gradle/tooling-proxy/src/org/jetbrains/plugins/gradle/tooling/proxy/ProgressEventConverter.kt
10
4372
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.tooling.proxy import org.gradle.tooling.Failure import org.gradle.tooling.events.* import org.gradle.tooling.events.task.* import org.gradle.tooling.model.UnsupportedMethodException import org.jetbrains.plugins.gradle.tooling.serialization.internal.adapter.events.* import org.jetbrains.plugins.gradle.tooling.serialization.internal.adapter.events.task.* import java.util.* class ProgressEventConverter { private val descriptorsMap = IdentityHashMap<OperationDescriptor, InternalOperationDescriptor>() fun convert(progressEvent: ProgressEvent): ProgressEvent = when (progressEvent) { is TaskStartEvent -> progressEvent.run { InternalTaskStartEvent(eventTime, displayName, convert(descriptor) as InternalTaskOperationDescriptor) } is TaskFinishEvent -> progressEvent.run { InternalTaskFinishEvent(eventTime, displayName, convert(descriptor) as InternalTaskOperationDescriptor, convert(result)) } is StatusEvent -> progressEvent.run { InternalStatusEvent(eventTime, displayName, convert(descriptor), total, progress, unit) } is StartEvent -> progressEvent.run { InternalStartEvent(eventTime, displayName, convert(descriptor)) } is FinishEvent -> progressEvent.run { InternalFinishEvent(eventTime, displayName, convert(descriptor), convert(result)) } else -> progressEvent } private fun convert(result: TaskOperationResult?): TaskOperationResult? { when (result) { null -> return null is TaskSuccessResult -> return result.run { InternalTaskSuccessResult(startTime, endTime, isUpToDate, isFromCache, taskExecutionDetails()) } is TaskFailureResult -> return result.run { InternalTaskFailureResult(startTime, endTime, failures?.map<Failure?, Failure?>(::convert), taskExecutionDetails()) } is TaskSkippedResult -> return result.run { InternalTaskSkippedResult(startTime, endTime, skipMessage) } else -> throw IllegalArgumentException("Unsupported task operation result ${result.javaClass}") } } private fun convert(result: OperationResult?): OperationResult? { when (result) { null -> return null is SuccessResult -> return result.run { InternalOperationSuccessResult(startTime, endTime) } is FailureResult -> return result.run { InternalOperationFailureResult(startTime, endTime, failures?.map<Failure?, Failure?>(::convert)) } else -> throw IllegalArgumentException("Unsupported operation result ${result.javaClass}") } } private fun TaskExecutionResult.taskExecutionDetails(): InternalTaskExecutionDetails? = try { InternalTaskExecutionDetails.of(isIncremental, executionReasons) } catch (e: UnsupportedMethodException) { InternalTaskExecutionDetails.unsupported() } private fun convert(failure: Failure?): InternalFailure? { return failure?.run { InternalFailure(message, description, causes?.map<Failure?, InternalFailure?>(::convert)) } } fun convert(operationDescriptor: OperationDescriptor?): InternalOperationDescriptor? { if (operationDescriptor == null) return null val id = if (operationDescriptor is org.gradle.tooling.internal.protocol.events.InternalOperationDescriptor) operationDescriptor.id.toString() else operationDescriptor.displayName return descriptorsMap.getOrPut(operationDescriptor, { when (operationDescriptor) { is TaskOperationDescriptor -> operationDescriptor.run { InternalTaskOperationDescriptor( id, name, displayName, convert(parent), taskPath, { mutableSetOf<OperationDescriptor>().apply { dependencies.mapNotNullTo(this) { convert(it) } } }, { convert(originPlugin) }) } else -> operationDescriptor.run { InternalOperationDescriptor(id, name, displayName, convert(parent)) } } }) } private fun convert(pluginIdentifier: PluginIdentifier?): PluginIdentifier? = when (pluginIdentifier) { null -> null is BinaryPluginIdentifier -> pluginIdentifier.run { InternalBinaryPluginIdentifier(displayName, className, pluginId) } is ScriptPluginIdentifier -> pluginIdentifier.run { InternalScriptPluginIdentifier(displayName, uri) } else -> null } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/j2k/old/tests/testData/fileOrElement/postProcessing/NotIs.kt
13
108
internal class C { fun foo(o: Any) { if (o !is String) return println("String") } }
apache-2.0
jotomo/AndroidAPS
core/src/main/java/info/nightscout/androidaps/activities/ErrorHelperActivity.kt
1
1073
package info.nightscout.androidaps.activities import android.os.Bundle import info.nightscout.androidaps.core.R import info.nightscout.androidaps.dialogs.ErrorDialog import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.utils.sharedPreferences.SP import javax.inject.Inject class ErrorHelperActivity : DialogAppCompatActivity() { @Inject lateinit var sp : SP @Inject lateinit var nsUpload: NSUpload @Override override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val errorDialog = ErrorDialog() errorDialog.helperActivity = this errorDialog.status = intent.getStringExtra("status") errorDialog.sound = intent.getIntExtra("soundid", R.raw.error) errorDialog.title = intent.getStringExtra("title") errorDialog.show(supportFragmentManager, "Error") if (sp.getBoolean(R.string.key_ns_create_announcements_from_errors, true)) { nsUpload.uploadError(intent.getStringExtra("status")) } } }
agpl-3.0
jotomo/AndroidAPS
core/src/main/java/info/nightscout/androidaps/db/StaticInjector.kt
1
783
package info.nightscout.androidaps.db import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import java.lang.IllegalStateException import javax.inject.Inject import javax.inject.Singleton @Singleton class StaticInjector @Inject constructor( private val injector: HasAndroidInjector ) : HasAndroidInjector { companion object { private var instance : StaticInjector? = null @Deprecated("Only until DB is refactored") fun getInstance() : StaticInjector { if (instance == null) throw IllegalStateException("StaticInjector not initialized") return instance!! } } init { instance = this } override fun androidInjector(): AndroidInjector<Any> = injector.androidInjector() }
agpl-3.0
Flank/flank
test_projects/android/multi-modules/fullyIgnoredModule/src/androidTest/java/com/example/fullyIgnoredModule/ModuleTests2.kt
1
796
package com.example.fullyIgnoredModule import androidx.test.ext.junit.runners.AndroidJUnit4 import com.example.common.anotherSampleTestMethod import com.example.common.ignoredTest import com.example.common.testSampleMethod import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ModuleTests2 { @Test @Ignore("For testing #818") fun sampleFullyIgnoredModuleAdvancedTest() { testSampleMethod() anotherSampleTestMethod() } @Test @Ignore("For testing #818") fun sampleFullyIgnoredModuleAdvancedTest2() { anotherSampleTestMethod() testSampleMethod() } @Test @Ignore("For testing #818") fun sampleFullyIgnoredModuleIgnoredTest3() { ignoredTest() } }
apache-2.0
mdaniel/intellij-community
platform/core-impl/src/com/intellij/ide/plugins/PluginLoadingResult.kt
1
6661
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment") package com.intellij.ide.plugins import com.intellij.core.CoreBundle import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.util.BuildNumber import com.intellij.util.PlatformUtils import com.intellij.util.lang.Java11Shim import com.intellij.util.text.VersionComparatorUtil import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.TestOnly import org.jetbrains.annotations.VisibleForTesting import java.util.* // https://www.jetbrains.org/intellij/sdk/docs/basics/getting_started/plugin_compatibility.html // If a plugin does not include any module dependency tags in its plugin.xml, // it's assumed to be a legacy plugin and is loaded only in IntelliJ IDEA. @ApiStatus.Internal class PluginLoadingResult(private val checkModuleDependencies: Boolean = !PlatformUtils.isIntelliJ()) { private val incompletePlugins = HashMap<PluginId, IdeaPluginDescriptorImpl>() @JvmField val enabledPluginsById = HashMap<PluginId, IdeaPluginDescriptorImpl>() private val idMap = HashMap<PluginId, IdeaPluginDescriptorImpl>() @JvmField var duplicateModuleMap: MutableMap<PluginId, MutableList<IdeaPluginDescriptorImpl>>? = null private val pluginErrors = HashMap<PluginId, PluginLoadingError>() @VisibleForTesting @JvmField val shadowedBundledIds: MutableSet<PluginId> = Collections.newSetFromMap(HashMap()) @get:TestOnly val hasPluginErrors: Boolean get() = !pluginErrors.isEmpty() @get:TestOnly val enabledPlugins: List<IdeaPluginDescriptorImpl> get() = enabledPluginsById.entries.sortedBy { it.key }.map { it.value } internal fun copyPluginErrors(): MutableMap<PluginId, PluginLoadingError> = HashMap(pluginErrors) fun getIncompleteIdMap(): Map<PluginId, IdeaPluginDescriptorImpl> = incompletePlugins fun getIdMap(): Map<PluginId, IdeaPluginDescriptorImpl> = idMap private fun addIncompletePlugin(plugin: IdeaPluginDescriptorImpl, error: PluginLoadingError?) { // do not report if some compatible plugin were already added // no race condition here: plugins from classpath are loaded before and not in parallel to loading from plugin dir if (idMap.containsKey(plugin.pluginId)) { return } val existingIncompletePlugin = incompletePlugins.putIfAbsent(plugin.pluginId, plugin) if (existingIncompletePlugin != null && VersionComparatorUtil.compare(plugin.version, existingIncompletePlugin.version) > 0) { incompletePlugins.put(plugin.pluginId, plugin) if (error != null) { // force put pluginErrors.put(plugin.pluginId, error) } } else if (error != null) { pluginErrors.putIfAbsent(plugin.pluginId, error) } } fun addAll(descriptors: Iterable<IdeaPluginDescriptorImpl?>, overrideUseIfCompatible: Boolean, productBuildNumber: BuildNumber) { for (descriptor in descriptors) { if (descriptor != null) { add(descriptor, overrideUseIfCompatible, productBuildNumber) } } } private fun add(descriptor: IdeaPluginDescriptorImpl, overrideUseIfCompatible: Boolean, productBuildNumber: BuildNumber) { val pluginId = descriptor.pluginId descriptor.isIncomplete?.let { error -> addIncompletePlugin(descriptor, error.takeIf { !it.isDisabledError }) return } if (checkModuleDependencies && !descriptor.isBundled && descriptor.packagePrefix == null && !hasModuleDependencies(descriptor)) { addIncompletePlugin(descriptor, PluginLoadingError( plugin = descriptor, detailedMessageSupplier = { CoreBundle.message("plugin.loading.error.long.compatible.with.intellij.idea.only", descriptor.name) }, shortMessageSupplier = { CoreBundle.message("plugin.loading.error.short.compatible.with.intellij.idea.only") }, isNotifyUser = true )) return } // remove any error that occurred for plugin with the same `id` pluginErrors.remove(pluginId) incompletePlugins.remove(pluginId) val prevDescriptor = if (descriptor.onDemand) null else enabledPluginsById.put(pluginId, descriptor) if (prevDescriptor == null) { idMap.put(pluginId, descriptor) for (module in descriptor.modules) { checkAndAdd(descriptor, module) } return } if (prevDescriptor.isBundled || descriptor.isBundled) { shadowedBundledIds.add(pluginId) } if (PluginManagerCore.checkBuildNumberCompatibility(descriptor, productBuildNumber) == null && (overrideUseIfCompatible || VersionComparatorUtil.compare(descriptor.version, prevDescriptor.version) > 0)) { PluginManagerCore.getLogger().info("$descriptor overrides $prevDescriptor") idMap.put(pluginId, descriptor) return } else { enabledPluginsById.put(pluginId, prevDescriptor) return } } private fun checkAndAdd(descriptor: IdeaPluginDescriptorImpl, id: PluginId) { duplicateModuleMap?.get(id)?.let { duplicates -> duplicates.add(descriptor) return } val existingDescriptor = idMap.put(id, descriptor) ?: return // if duplicated, both are removed idMap.remove(id) if (duplicateModuleMap == null) { duplicateModuleMap = LinkedHashMap() } val list = ArrayList<IdeaPluginDescriptorImpl>(2) list.add(existingDescriptor) list.add(descriptor) duplicateModuleMap!!.put(id, list) } } // todo merge into PluginSetState? @ApiStatus.Internal class PluginManagerState internal constructor(@JvmField val pluginSet: PluginSet, disabledRequiredIds: Set<IdeaPluginDescriptorImpl>, effectiveDisabledIds: Set<IdeaPluginDescriptorImpl>) { @JvmField val effectiveDisabledIds: Set<PluginId> = Java11Shim.INSTANCE.copyOf(effectiveDisabledIds.mapTo(HashSet(effectiveDisabledIds.size), IdeaPluginDescriptorImpl::getPluginId)) @JvmField val disabledRequiredIds: Set<PluginId> = Java11Shim.INSTANCE.copyOf(disabledRequiredIds.mapTo(HashSet(disabledRequiredIds.size), IdeaPluginDescriptorImpl::getPluginId)) } internal fun hasModuleDependencies(descriptor: IdeaPluginDescriptorImpl): Boolean { for (dependency in descriptor.pluginDependencies) { val dependencyPluginId = dependency.pluginId if (PluginManagerCore.JAVA_PLUGIN_ID == dependencyPluginId || PluginManagerCore.JAVA_MODULE_ID == dependencyPluginId || PluginManagerCore.isModuleDependency(dependencyPluginId)) { return true } } return false }
apache-2.0
ingokegel/intellij-community
plugins/kotlin/idea/tests/testData/hierarchy/class/sub/SecondaryConstructorCallCaretAfter/main.kt
13
76
open class A { constructor(a: Int) } class B: A<caret>(1) class C: A(1)
apache-2.0
siosio/intellij-community
plugins/kotlin/completion/tests/testData/keywords/topScope2.kt
4
722
// COMPILER_ARGUMENTS: -XXLanguage:+SealedInterfaces -XXLanguage:+MultiPlatformProjects <caret> // EXIST: abstract // EXIST: class // EXIST: enum class // EXIST: final // EXIST: fun // EXIST: import // EXIST: internal // EXIST: object // EXIST: open // EXIST: package // EXIST: private // EXIST: public // EXIST: interface // EXIST: val // EXIST: var // EXIST: operator // EXIST: infix // EXIST: sealed class // EXIST: sealed interface // EXIST: data class // EXIST: inline // EXIST: value // EXIST: tailrec // EXIST: external // EXIST: annotation class // EXIST: const val // EXIST: suspend fun // EXIST: typealias // EXIST: expect // EXIST: actual // EXIST: lateinit var // NOTHING_ELSE
apache-2.0
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/models/scraper/BlockedUsers.kt
1
213
package io.github.feelfreelinux.wykopmobilny.models.scraper import pl.droidsonroids.jspoon.annotation.Selector class BlockedUsers { @Selector("div.usercard") var blockedUsers: List<BlockedUser>? = null }
mit
siosio/intellij-community
plugins/kotlin/idea/tests/testData/indentationOnNewline/controlFlowConstructions/DoWithBraces2.after.kt
12
58
fun some() { do <caret>{ } while (true) }
apache-2.0
kivensolo/UiUsingListView
module-Common/src/main/java/com/kingz/module/common/utils/RvUtils.kt
1
1044
package com.kingz.module.common.utils import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView /** * author:ZekeWang * date:2021/2/23 * description:RecyclerView 工具类 */ object RvUtils { /** * 平滑滚动到第1个元素 */ fun smoothScrollTop(rv: RecyclerView?) { if (rv != null) { val layoutManager: RecyclerView.LayoutManager? = rv.layoutManager if (layoutManager is LinearLayoutManager) { val linearLayoutManager: LinearLayoutManager = layoutManager val first: Int = linearLayoutManager.findFirstVisibleItemPosition() val last: Int = linearLayoutManager.findLastVisibleItemPosition() val visibleCount = last - first + 1 val scrollIndex = visibleCount * 2 - 1 if (first > scrollIndex) { rv.scrollToPosition(scrollIndex) } } rv.smoothScrollToPosition(0) } } }
gpl-2.0
JetBrains/xodus
crypto/src/main/kotlin/jetbrains/exodus/crypto/convert/ScytaleEngine.kt
1
6514
/** * Copyright 2010 - 2022 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.exodus.crypto.convert import jetbrains.exodus.crypto.StreamCipherProvider import jetbrains.exodus.crypto.asHashedIV import jetbrains.exodus.log.LogUtil import jetbrains.exodus.util.ByteArraySpinAllocator import mu.KLogging import java.io.Closeable import java.util.concurrent.ArrayBlockingQueue import java.util.concurrent.TimeUnit class ScytaleEngine( private val listener: EncryptListener, private val cipherProvider: StreamCipherProvider, private val key: ByteArray, private val basicIV: Long, private val blockAlignment: Int = LogUtil.LOG_BLOCK_ALIGNMENT, bufferSize: Int = 1024 * 1024, // 1MB inputQueueSize: Int = 40, outputQueueSize: Int = 40 ) : Closeable { companion object : KLogging() { val timeout = 200L } private val inputQueue = ArrayBlockingQueue<EncryptMessage>(inputQueueSize) private val outputQueue = ArrayBlockingQueue<EncryptMessage>(outputQueueSize) private val bufferAllocator = ByteArraySpinAllocator(bufferSize, inputQueueSize + outputQueueSize + 4) @Volatile private var producerFinished = false @Volatile private var consumerFinished = false @Volatile private var cancelled = false @Volatile var error: Throwable? = null private val statefulProducer = object : Runnable { private val cipher = cipherProvider.newCipher() private var offset = 0 private var iv = 0L override fun run() { try { while (!cancelled && error == null) { inputQueue.poll(timeout, TimeUnit.MILLISECONDS)?.let { when (it) { is FileHeader -> { offset = 0 iv = basicIV + if (it.chunkedIV) { it.handle / blockAlignment } else { it.handle } cipher.init(key, iv.asHashedIV()) } is FileChunk -> encryptChunk(it) is EndChunk -> Unit else -> throw IllegalArgumentException() } while (!outputQueue.offer(it, timeout, TimeUnit.MILLISECONDS)) { if (cancelled || error != null) { return } } } ?: if (producerFinished) { return } } } catch (t: Throwable) { producerFinished = true error = t } } private fun encryptChunk(it: FileChunk) { if (it.header.canBeEncrypted) { val data = it.data if (it.header.chunkedIV) { blockEncrypt(it.size, data) } else { encrypt(it.size, data) } } } private fun encrypt(size: Int, data: ByteArray) { for (i in 0 until size) { data[i] = cipher.crypt(data[i]) } } private fun blockEncrypt(size: Int, data: ByteArray) { for (i in 0 until size) { data[i] = cipher.crypt(data[i]) if (++offset == blockAlignment) { offset = 0 cipher.init(key, (++iv).asHashedIV()) } } } } private val producer = Thread(statefulProducer, "xodus encrypt " + hashCode()) private val consumer = Thread({ try { var currentFile: FileHeader? = null while (!cancelled && error == null) { outputQueue.poll(timeout, TimeUnit.MILLISECONDS)?.let { when (it) { is FileHeader -> { currentFile?.let { listener.onFileEnd(it) } currentFile = it listener.onFile(it) } is FileChunk -> { val current = currentFile if (current != null && current != it.header) { throw Throwable("Invalid chunk with header " + it.header.path) } else { listener.onData(it.header, it.size, it.data) bufferAllocator.dispose(it.data) } } is EndChunk -> { currentFile?.let { listener.onFileEnd(it) } } else -> throw IllegalArgumentException() } } ?: if (consumerFinished) { return@Thread } } } catch (t: Throwable) { consumerFinished = true error = t } }, "xodus write " + hashCode()) fun start() { producer.start() consumer.start() } fun alloc(): ByteArray = bufferAllocator.alloc() fun put(e: EncryptMessage) { while (!inputQueue.offer(e, timeout, TimeUnit.MILLISECONDS)) { if (error != null) { throw RuntimeException(error) } } } fun cancel() { cancelled = true } override fun close() { producerFinished = true producer.join() consumerFinished = true consumer.join() error?.let { throw RuntimeException(it) } } }
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/indentationOnNewline/emptyParameters/EmptyConditionInFor.after.kt
24
90
fun a() { for ( <caret> ) } // SET_FALSE: ALIGN_MULTILINE_METHOD_BRACKETS
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/indentationOnNewline/emptyParameters/EmptyParameterInSecondaryConstructor.kt
12
83
class A { constructor(<caret>) } // SET_FALSE: ALIGN_MULTILINE_METHOD_BRACKETS
apache-2.0
siosio/intellij-community
plugins/kotlin/jps/jps-plugin/src/org/jetbrains/kotlin/compilerRunner/JpsCompilerServicesFacadeImpl.kt
1
1779
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.compilerRunner import org.jetbrains.kotlin.daemon.client.CompilerCallbackServicesFacadeServer import org.jetbrains.kotlin.daemon.client.reportFromDaemon import org.jetbrains.kotlin.daemon.common.JpsCompilerServicesFacade import org.jetbrains.kotlin.daemon.common.SOCKET_ANY_FREE_PORT import org.jetbrains.kotlin.incremental.components.ExpectActualTracker import org.jetbrains.kotlin.incremental.components.LookupTracker import org.jetbrains.kotlin.incremental.js.IncrementalDataProvider import org.jetbrains.kotlin.incremental.js.IncrementalResultsConsumer import org.jetbrains.kotlin.load.kotlin.incremental.components.IncrementalCompilationComponents import org.jetbrains.kotlin.progress.CompilationCanceledStatus import java.io.Serializable internal class JpsCompilerServicesFacadeImpl( private val env: JpsCompilerEnvironment, port: Int = SOCKET_ANY_FREE_PORT ) : CompilerCallbackServicesFacadeServer( env.services[IncrementalCompilationComponents::class.java], env.services[LookupTracker::class.java], env.services[CompilationCanceledStatus::class.java], env.services[ExpectActualTracker::class.java], env.services[IncrementalResultsConsumer::class.java], env.services[IncrementalDataProvider::class.java], port ), JpsCompilerServicesFacade { override fun report(category: Int, severity: Int, message: String?, attachment: Serializable?) { env.messageCollector.reportFromDaemon( { outFile, srcFiles -> env.outputItemsCollector.add(srcFiles, outFile) }, category, severity, message, attachment ) } }
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/intentions/destructuringVariables/withModifiers.kt
4
161
data class XY(val x: Int, val y: Int) fun create() = XY(1, 2) annotation class Ann fun use(): Int { @Ann val <caret>xy = create() return xy.x + xy.y }
apache-2.0
jwren/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/imports/AbstractFilteringAutoImportTest.kt
4
1896
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.imports import com.intellij.codeInsight.daemon.ReferenceImporter import org.jetbrains.kotlin.idea.codeInsight.AbstractKotlinReferenceImporter import org.jetbrains.kotlin.idea.codeInsight.KotlinCodeInsightSettings import org.jetbrains.kotlin.idea.codeInsight.KotlinAutoImportsFilter import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtFile private class KotlinAutoImportsFilterImpl(val isEnabled: Boolean) : KotlinAutoImportsFilter { override fun forceAutoImportForElement(file: KtFile, suggestions: Collection<FqName>): Boolean = isEnabled override fun filterSuggestions(suggestions: Collection<FqName>): Collection<FqName> = suggestions.filter { it.asString() == "a.b.AmbiguousClazzForFilter" }.ifEmpty { suggestions } } private class TestReferenceImporterImpl(val isEnabled: Boolean) : AbstractKotlinReferenceImporter() { override fun isEnabledFor(file: KtFile): Boolean = isEnabled override val enableAutoImportFilter: Boolean = true } abstract class AbstractFilteringAutoImportTest : AbstractAutoImportTest() { override fun setupAutoImportEnvironment(settings: KotlinCodeInsightSettings, withAutoImport: Boolean) { // KotlinAutoImportsFilter.forceAutoImportForFile() should work even if addUnambiguousImportsOnTheFly is disabled: settings.addUnambiguousImportsOnTheFly = false KotlinAutoImportsFilter.EP_NAME.point.registerExtension( KotlinAutoImportsFilterImpl(isEnabled = withAutoImport), testRootDisposable ) ReferenceImporter.EP_NAME.point.registerExtension( TestReferenceImporterImpl(isEnabled = withAutoImport), testRootDisposable ) } }
apache-2.0
jwren/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinUPostfixExpression.kt
4
1564
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.kotlin import com.intellij.psi.PsiMethod import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtPostfixExpression import org.jetbrains.uast.* import org.jetbrains.uast.kotlin.internal.DelegatedMultiResolve @ApiStatus.Internal class KotlinUPostfixExpression( override val sourcePsi: KtPostfixExpression, givenParent: UElement? ) : KotlinAbstractUExpression(givenParent), UPostfixExpression, KotlinUElementWithType, KotlinEvaluatableUElement, UResolvable, DelegatedMultiResolve { override val operand by lz { baseResolveProviderService.baseKotlinConverter.convertOrEmpty(sourcePsi.baseExpression, this) } override val operator = when (sourcePsi.operationToken) { KtTokens.PLUSPLUS -> UastPostfixOperator.INC KtTokens.MINUSMINUS -> UastPostfixOperator.DEC KtTokens.EXCLEXCL -> KotlinPostfixOperators.EXCLEXCL else -> UastPostfixOperator.UNKNOWN } override val operatorIdentifier: UIdentifier get() = KotlinUIdentifier(sourcePsi.operationReference, this) override fun resolveOperator(): PsiMethod? = baseResolveProviderService.resolveCall(sourcePsi) override fun resolve(): PsiMethod? = when (sourcePsi.operationToken) { KtTokens.EXCLEXCL -> operand.tryResolve() as? PsiMethod else -> null } }
apache-2.0
K0zka/kerub
src/test/kotlin/com/github/kerubistan/kerub/planner/steps/vm/start/virtualbox/VirtualBoxStartVirtualMachineExecutorTest.kt
2
1206
package com.github.kerubistan.kerub.planner.steps.vm.start.virtualbox import com.github.kerubistan.kerub.data.dynamic.VirtualMachineDynamicDao import com.github.kerubistan.kerub.host.HostCommandExecutor import com.github.kerubistan.kerub.host.mockHost import com.github.kerubistan.kerub.sshtestutils.mockCommandExecution import com.github.kerubistan.kerub.sshtestutils.verifyCommandExecution import com.github.kerubistan.kerub.testHost import com.github.kerubistan.kerub.testVm import com.nhaarman.mockito_kotlin.atLeast import com.nhaarman.mockito_kotlin.mock import org.apache.sshd.client.session.ClientSession import org.junit.Test class VirtualBoxStartVirtualMachineExecutorTest { @Test fun execute() { val hostCommandExecutor = mock<HostCommandExecutor>() val vmDynDao = mock<VirtualMachineDynamicDao>() val session = mock<ClientSession>() session.mockCommandExecution("VBoxManage .*".toRegex()) hostCommandExecutor.mockHost(testHost, session) VirtualBoxStartVirtualMachineExecutor(hostCommandExecutor, vmDynDao).execute( VirtualBoxStartVirtualMachine( host = testHost, vm = testVm ) ) session.verifyCommandExecution("VBoxManage .*".toRegex(), atLeast(1)) } }
apache-2.0
K0zka/kerub
src/test/kotlin/com/github/kerubistan/kerub/host/distros/UbuntuTest.kt
2
628
package com.github.kerubistan.kerub.host.distros import com.github.kerubistan.kerub.model.Version import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test class UbuntuTest { @Test fun testHandlesVersion() { assertFalse(Ubuntu().handlesVersion(Version.fromVersionString("blah"))) assertFalse(Ubuntu().handlesVersion(Version.fromVersionString("blah.blah"))) assertFalse(Ubuntu().handlesVersion(Version.fromVersionString("10.04"))) assertTrue(Ubuntu().handlesVersion(Version.fromVersionString("12.04"))) assertTrue(Ubuntu().handlesVersion(Version.fromVersionString("14.04"))) } }
apache-2.0