repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
qoncept/TensorKotlin
src/jp/co/qoncept/tensorkotlin/Shape.kt
1
681
package jp.co.qoncept.tensorkotlin import java.util.* class Shape(vararg dimensions: Int) { val dimensions: IntArray = dimensions.clone() val volume: Int get() = dimensions.fold(1) { a, x -> a * x } override fun equals(other: Any?): Boolean { if (other !is Shape) { return false } return dimensions.size == other.dimensions.size && zipFold(dimensions, other.dimensions, true) { result, a, b -> if (!result) { return false } a == b } } override fun hashCode(): Int { return dimensions.hashCode() } override fun toString(): String { return Arrays.toString(dimensions) } }
mit
3b22f6db10e2949fd089283cc04a3866
24.222222
120
0.594714
4.10241
false
false
false
false
google/flatbuffers
kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlexBuffersBuilder.kt
6
27376
/* * Copyright 2021 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NOTHING_TO_INLINE") package com.google.flatbuffers.kotlin public class FlexBuffersBuilder( public val buffer: ReadWriteBuffer, private val shareFlag: Int = SHARE_KEYS ) { public constructor(initialCapacity: Int = 1024, shareFlag: Int = SHARE_KEYS) : this(ArrayReadWriteBuffer(initialCapacity), shareFlag) private val stringValuePool: HashMap<String, Value> = HashMap() private val stringKeyPool: HashMap<String, Int> = HashMap() private val stack: MutableList<Value> = mutableListOf() private var finished: Boolean = false /** * Reset the FlexBuffersBuilder by purging all data that it holds. Buffer might * keep its capacity after a reset. */ public fun clear() { buffer.clear() stringValuePool.clear() stringKeyPool.clear() stack.clear() finished = false } /** * Finish writing the message into the buffer. After that no other element must * be inserted into the buffer. Also, you must call this function before start using the * FlexBuffer message * @return [ReadBuffer] containing the FlexBuffer message */ public fun finish(): ReadBuffer { // If you hit this assert, you likely have objects that were never included // in a parent. You need to have exactly one root to finish a buffer. // Check your Start/End calls are matched, and all objects are inside // some other object. if (stack.size != 1) error("There is must be only on object as root. Current ${stack.size}.") // Write root value. val byteWidth = align(stack[0].elemWidth(buffer.writePosition, 0)) writeAny(stack[0], byteWidth) // Write root type. buffer.put(stack[0].storedPackedType()) // Write root size. Normally determined by parent, but root has no parent :) buffer.put(byteWidth.value.toByte()) this.finished = true return buffer // TODO: make a read-only shallow copy } /** * Insert a single [Boolean] into the buffer * @param value true or false */ public fun put(value: Boolean): Unit = run { this[null] = value } /** * Insert a null reference into the buffer. A key must be present if element is inserted into a map. */ public fun putNull(key: String? = null): Unit = run { stack.add(Value(T_NULL, putKey(key), W_8, 0UL)) } /** * Insert a single [Boolean] into the buffer. A key must be present if element is inserted into a map. */ public operator fun set(key: String? = null, value: Boolean): Unit = run { stack.add(Value(T_BOOL, putKey(key), W_8, if (value) 1UL else 0UL)) } /** * Insert a single [Byte] into the buffer */ public fun put(value: Byte): Unit = set(null, value.toLong()) /** * Insert a single [Byte] into the buffer. A key must be present if element is inserted into a map. */ public operator fun set(key: String? = null, value: Byte): Unit = set(key, value.toLong()) /** * Insert a single [Short] into the buffer. */ public fun put(value: Short): Unit = set(null, value.toLong()) /** * Insert a single [Short] into the buffer. A key must be present if element is inserted into a map. */ public inline operator fun set(key: String? = null, value: Short): Unit = set(key, value.toLong()) /** * Insert a single [Int] into the buffer. */ public fun put(value: Int): Unit = set(null, value.toLong()) /** * Insert a single [Int] into the buffer. A key must be present if element is inserted into a map. */ public inline operator fun set(key: String? = null, value: Int): Unit = set(key, value.toLong()) /** * Insert a single [Long] into the buffer. */ public fun put(value: Long): Unit = set(null, value) /** * Insert a single [Long] into the buffer. A key must be present if element is inserted into a map. */ public operator fun set(key: String? = null, value: Long): Unit = run { stack.add(Value(T_INT, putKey(key), value.toULong().widthInUBits(), value.toULong())) } /** * Insert a single [UByte] into the buffer */ public fun put(value: UByte): Unit = set(null, value.toULong()) /** * Insert a single [UByte] into the buffer. A key must be present if element is inserted into a map. */ public inline operator fun set(key: String? = null, value: UByte): Unit = set(key, value.toULong()) /** * Insert a single [UShort] into the buffer. */ public fun put(value: UShort): Unit = set(null, value.toULong()) /** * Insert a single [UShort] into the buffer. A key must be present if element is inserted into a map. */ private inline operator fun set(key: String? = null, value: UShort): Unit = set(key, value.toULong()) /** * Insert a single [UInt] into the buffer. */ public fun put(value: UInt): Unit = set(null, value.toULong()) /** * Insert a single [UInt] into the buffer. A key must be present if element is inserted into a map. */ private inline operator fun set(key: String? = null, value: UInt): Unit = set(key, value.toULong()) /** * Insert a single [ULong] into the buffer. */ public fun put(value: ULong): Unit = set(null, value) /** * Insert a single [ULong] into the buffer. A key must be present if element is inserted into a map. */ public operator fun set(key: String? = null, value: ULong): Unit = run { stack.add(Value(T_UINT, putKey(key), value.widthInUBits(), value)) } /** * Insert a single [Float] into the buffer. */ public fun put(value: Float): Unit = run { this[null] = value } /** * Insert a single [Float] into the buffer. A key must be present if element is inserted into a map. */ public operator fun set(key: String? = null, value: Float): Unit = run { stack.add(Value(T_FLOAT, putKey(key), W_32, dValue = value.toDouble())) } /** * Insert a single [Double] into the buffer. */ public fun put(value: Double): Unit = run { this[null] = value } /** * Insert a single [Double] into the buffer. A key must be present if element is inserted into a map. */ public operator fun set(key: String? = null, value: Double): Unit = run { stack.add(Value(T_FLOAT, putKey(key), W_64, dValue = value)) } /** * Insert a single [String] into the buffer. */ public fun put(value: String): Int = set(null, value) /** * Insert a single [String] into the buffer. A key must be present if element is inserted into a map. */ public operator fun set(key: String? = null, value: String): Int { val iKey = putKey(key) val holder = if (shareFlag and SHARE_STRINGS != 0) { stringValuePool.getOrPut(value) { writeString(iKey, value).also { stringValuePool[value] = it } }.copy(key = iKey) } else { writeString(iKey, value) } stack.add(holder) return holder.iValue.toInt() } /** * Adds a [ByteArray] into the message as a [Blob]. * @param value byte array * @return position in buffer as the start of byte array */ public fun put(value: ByteArray): Int = set(null, value) /** * Adds a [ByteArray] into the message as a [Blob]. A key must be present if element is inserted into a map. * @param value byte array * @return position in buffer as the start of byte array */ public operator fun set(key: String? = null, value: ByteArray): Int { val element = writeBlob(putKey(key), value, T_BLOB, false) stack.add(element) return element.iValue.toInt() } /** * Adds a [IntArray] into the message as a typed vector of fixed size. * @param value [IntArray] * @return position in buffer as the start of byte array */ public fun put(value: IntArray): Int = set(null, value) /** * Adds a [IntArray] into the message as a typed vector of fixed size. * A key must be present if element is inserted into a map. * @param value [IntArray] * @return position in buffer as the start of byte array */ public operator fun set(key: String? = null, value: IntArray): Int = setTypedVector(key, value.size, T_VECTOR_INT, value.widthInUBits()) { writeIntArray(value, it) } /** * Adds a [ShortArray] into the message as a typed vector of fixed size. * @param value [ShortArray] * @return position in buffer as the start of byte array */ public fun put(value: ShortArray): Int = set(null, value) /** * Adds a [ShortArray] into the message as a typed vector of fixed size. * A key must be present if element is inserted into a map. * @param value [ShortArray] * @return position in buffer as the start of byte array */ public operator fun set(key: String? = null, value: ShortArray): Int = setTypedVector(key, value.size, T_VECTOR_INT, value.widthInUBits()) { writeIntArray(value, it) } /** * Adds a [LongArray] into the message as a typed vector of fixed size. * @param value [LongArray] * @return position in buffer as the start of byte array */ public fun put(value: LongArray): Int = set(null, value) /** * Adds a [LongArray] into the message as a typed vector of fixed size. * A key must be present if element is inserted into a map. * @param value [LongArray] * @return position in buffer as the start of byte array */ public operator fun set(key: String? = null, value: LongArray): Int = setTypedVector(key, value.size, T_VECTOR_INT, value.widthInUBits()) { writeIntArray(value, it) } /** * Adds a [FloatArray] into the message as a typed vector of fixed size. * @param value [FloatArray] * @return position in buffer as the start of byte array */ public fun put(value: FloatArray): Int = set(null, value) /** * Adds a [FloatArray] into the message as a typed vector of fixed size. * A key must be present if element is inserted into a map. * @param value [FloatArray] * @return position in buffer as the start of byte array */ public operator fun set(key: String? = null, value: FloatArray): Int = setTypedVector(key, value.size, T_VECTOR_FLOAT, W_32) { writeFloatArray(value) } /** * Adds a [DoubleArray] into the message as a typed vector of fixed size. * @param value [DoubleArray] * @return position in buffer as the start of byte array */ public fun put(value: DoubleArray): Int = set(null, value) /** * Adds a [DoubleArray] into the message as a typed vector of fixed size. * A key must be present if element is inserted into a map. * @param value [DoubleArray] * @return position in buffer as the start of byte array */ public operator fun set(key: String? = null, value: DoubleArray): Int = setTypedVector(key, value.size, T_VECTOR_FLOAT, W_64) { writeFloatArray(value) } /** * Adds a [UByteArray] into the message as a typed vector of fixed size. * @param value [UByteArray] * @return position in buffer as the start of byte array */ public fun put(value: UByteArray): Int = set(null, value) /** * Adds a [UByteArray] into the message as a typed vector of fixed size. * A key must be present if element is inserted into a map. * @param value [UByteArray] * @return position in buffer as the start of byte array */ public operator fun set(key: String? = null, value: UByteArray): Int = setTypedVec(key) { value.forEach { put(it) } } /** * Adds a [UShortArray] into the message as a typed vector of fixed size. * @param value [UShortArray] * @return position in buffer as the start of byte array */ public fun put(value: UShortArray): Int = set(null, value) /** * Adds a [UShortArray] into the message as a typed vector of fixed size. * A key must be present if element is inserted into a map. * @param value [UShortArray] * @return position in buffer as the start of byte array */ public operator fun set(key: String? = null, value: UShortArray): Int = setTypedVec(key) { value.forEach { put(it) } } /** * Adds a [UIntArray] into the message as a typed vector of fixed size. * @param value [UIntArray] * @return position in buffer as the start of byte array */ public fun put(value: UIntArray): Int = set(null, value) /** * Adds a [UIntArray] into the message as a typed vector of fixed size. * A key must be present if element is inserted into a map. * @param value [UIntArray] * @return position in buffer as the start of byte array */ public fun set(key: String? = null, value: UIntArray): Int = setTypedVec(key) { value.forEach { put(it) } } /** * Adds a [ULongArray] into the message as a typed vector of fixed size. * @param value [ULongArray] * @return position in buffer as the start of byte array */ public fun put(value: ULongArray): Int = set(null, value) /** * Adds a [ULongArray] into the message as a typed vector of fixed size. * A key must be present if element is inserted into a map. * @param value [ULongArray] * @return position in buffer as the start of byte array */ public operator fun set(key: String? = null, value: ULongArray): Int = setTypedVec(key) { value.forEach { put(it) } } /** * Creates a new vector will all elements inserted in [block]. * @param block where elements will be inserted * @return position in buffer as the start of byte array */ public inline fun putVector(crossinline block: FlexBuffersBuilder.() -> Unit): Int { val pos = startVector() this.block() return endVector(pos) } /** * Creates a new typed vector will all elements inserted in [block]. * @param block where elements will be inserted * @return position in buffer as the start of byte array */ public inline fun putTypedVector(crossinline block: FlexBuffersBuilder.() -> Unit): Int { val pos = startVector() this.block() return endTypedVector(pos) } /** * Helper function to return position for starting a new vector. */ public fun startVector(): Int = stack.size /** * Finishes a vector element. The initial position of the vector must be passed * @param position position at the start of the vector */ public fun endVector(position: Int): Int = endVector(null, position) /** * Finishes a vector element. The initial position of the vector must be passed * @param position position at the start of the vector */ public fun endVector(key: String? = null, position: Int): Int = endAnyVector(position) { createVector(putKey(key), position, stack.size - position) } /** * Finishes a typed vector element. The initial position of the vector must be passed * @param position position at the start of the vector */ public fun endTypedVector(position: Int): Int = endTypedVector(position, null) /** * Helper function to return position for starting a new vector. */ public fun startMap(): Int = stack.size /** * Creates a new map will all elements inserted in [block]. * @param block where elements will be inserted * @return position in buffer as the start of byte array */ public inline fun putMap(key: String? = null, crossinline block: FlexBuffersBuilder.() -> Unit): Int { val pos = startMap() this.block() return endMap(pos, key) } /** * Finishes a map, but writing the information in the buffer * @param key key used to store element in map * @return Reference to the map */ public fun endMap(start: Int, key: String? = null): Int { stack.subList(start, stack.size).sortWith(keyComparator) val length = stack.size - start val keys = createKeyVector(start, length) val vec = putMap(putKey(key), start, length, keys) // Remove temp elements and return map. while (stack.size > start) { stack.removeAt(stack.size - 1) } stack.add(vec) return vec.iValue.toInt() } private inline fun setTypedVector( key: String? = null, length: Int, vecType: FlexBufferType, bitWidth: BitWidth, crossinline writeBlock: (ByteWidth) -> Unit ): Int { val keyPos = putKey(key) val byteWidth = align(bitWidth) // Write vector. First the keys width/offset if available, and size. // write the size writeInt(length, byteWidth) // Then the actual data. val vloc: Int = buffer.writePosition writeBlock(byteWidth) stack.add(Value(vecType, keyPos, bitWidth, vloc.toULong())) return vloc } private inline fun setTypedVec(key: String? = null, crossinline block: FlexBuffersBuilder.() -> Unit): Int { val pos = startVector() this.block() return endTypedVector(pos, key) } public fun endTypedVector(position: Int, key: String? = null): Int = endAnyVector(position) { createTypedVector(putKey(key), position, stack.size - position) } private inline fun endAnyVector(start: Int, crossinline creationBlock: () -> Value): Int { val vec = creationBlock() // Remove temp elements and return vector. while (stack.size > start) { stack.removeLast() } stack.add(vec) return vec.iValue.toInt() } private inline fun putKey(key: String? = null): Int { if (key == null) return -1 return if ((shareFlag and SHARE_KEYS) != 0) { stringKeyPool.getOrPut(key) { val pos: Int = buffer.writePosition buffer.put(key) buffer.put(ZeroByte) pos } } else { val pos: Int = buffer.writePosition buffer.put(key) buffer.put(ZeroByte) pos } } private fun writeAny(toWrite: Value, byteWidth: ByteWidth) = when (toWrite.type) { T_NULL, T_BOOL, T_INT, T_UINT -> writeInt(toWrite.iValue, byteWidth) T_FLOAT -> writeDouble(toWrite.dValue, byteWidth) else -> writeOffset(toWrite.iValue.toInt(), byteWidth) } private fun writeString(key: Int, s: String): Value { val size = Utf8.encodedLength(s) val bitWidth = size.toULong().widthInUBits() val byteWidth = align(bitWidth) writeInt(size, byteWidth) val sloc: Int = buffer.writePosition if (size > 0) buffer.put(s, size) buffer.put(ZeroByte) return Value(T_STRING, key, bitWidth, sloc.toULong()) } private fun writeDouble(toWrite: Double, byteWidth: ByteWidth): Unit = when (byteWidth.value) { 4 -> buffer.put(toWrite.toFloat()) 8 -> buffer.put(toWrite) else -> Unit } private fun writeOffset(toWrite: Int, byteWidth: ByteWidth) { val relativeOffset = (buffer.writePosition - toWrite) if (byteWidth.value != 8 && relativeOffset >= 1L shl byteWidth.value * 8) error("invalid offset $relativeOffset, writer pos ${buffer.writePosition}") writeInt(relativeOffset, byteWidth) } private inline fun writeBlob(key: Int, blob: ByteArray, type: FlexBufferType, trailing: Boolean): Value { val bitWidth = blob.size.toULong().widthInUBits() val byteWidth = align(bitWidth) writeInt(blob.size, byteWidth) val sloc: Int = buffer.writePosition buffer.put(blob, 0, blob.size) if (trailing) { buffer.put(ZeroByte) } return Value(type, key, bitWidth, sloc.toULong()) } private fun writeIntArray(value: IntArray, byteWidth: ByteWidth) = writeIntegerArray(0, value.size, byteWidth) { value[it].toULong() } private fun writeIntArray(value: ShortArray, byteWidth: ByteWidth) = writeIntegerArray(0, value.size, byteWidth) { value[it].toULong() } private fun writeIntArray(value: LongArray, byteWidth: ByteWidth) = writeIntegerArray(0, value.size, byteWidth) { value[it].toULong() } private fun writeFloatArray(value: FloatArray) { val byteWidth = Float.SIZE_BYTES // since we know we are writing an array, we can avoid multiple copy/growth of the buffer by requesting // the right size on the spot buffer.requestCapacity(buffer.writePosition + (value.size * byteWidth)) value.forEach { buffer.put(it) } } private fun writeFloatArray(value: DoubleArray) { val byteWidth = Double.SIZE_BYTES // since we know we are writing an array, we can avoid multiple copy/growth of the buffer by requesting // the right size on the spot buffer.requestCapacity(buffer.writePosition + (value.size * byteWidth)) value.forEach { buffer.put(it) } } private inline fun writeIntegerArray( start: Int, size: Int, byteWidth: ByteWidth, crossinline valueBlock: (Int) -> ULong ) { // since we know we are writing an array, we can avoid multiple copy/growth of the buffer by requesting // the right size on the spot buffer.requestCapacity(buffer.writePosition + (size * byteWidth)) return when (byteWidth.value) { 1 -> for (i in start until start + size) { buffer.put(valueBlock(i).toUByte()) } 2 -> for (i in start until start + size) { buffer.put(valueBlock(i).toUShort()) } 4 -> for (i in start until start + size) { buffer.put(valueBlock(i).toUInt()) } 8 -> for (i in start until start + size) { buffer.put(valueBlock(i)) } else -> Unit } } private fun writeInt(value: Int, byteWidth: ByteWidth) = when (byteWidth.value) { 1 -> buffer.put(value.toUByte()) 2 -> buffer.put(value.toUShort()) 4 -> buffer.put(value.toUInt()) 8 -> buffer.put(value.toULong()) else -> Unit } private fun writeInt(value: ULong, byteWidth: ByteWidth) = when (byteWidth.value) { 1 -> buffer.put(value.toUByte()) 2 -> buffer.put(value.toUShort()) 4 -> buffer.put(value.toUInt()) 8 -> buffer.put(value) else -> Unit } // Align to prepare for writing a scalar with a certain size. // returns the amounts of bytes needed to be written. private fun align(alignment: BitWidth): ByteWidth { val byteWidth = 1 shl alignment.value var padBytes = paddingBytes(buffer.writePosition, byteWidth) while (padBytes-- != 0) { buffer.put(ZeroByte) } return ByteWidth(byteWidth) } private fun calculateKeyVectorBitWidth(start: Int, length: Int): BitWidth { val bitWidth = length.toULong().widthInUBits() var width = bitWidth val prefixElems = 1 // Check bit widths and types for all elements. for (i in start until stack.size) { val elemWidth = elemWidth(T_KEY, W_8, stack[i].key.toLong(), buffer.writePosition, i + prefixElems) width = width.max(elemWidth) } return width } private fun createKeyVector(start: Int, length: Int): Value { // Figure out smallest bit width we can store this vector with. val bitWidth = calculateKeyVectorBitWidth(start, length) val byteWidth = align(bitWidth) // Write vector. First the keys width/offset if available, and size. writeInt(length, byteWidth) // Then the actual data. val vloc = buffer.writePosition.toULong() for (i in start until stack.size) { val pos = stack[i].key if (pos == -1) error("invalid position $pos for key") writeOffset(stack[i].key, byteWidth) } // Then the types. return Value(T_VECTOR_KEY, -1, bitWidth, vloc) } private inline fun createVector(key: Int, start: Int, length: Int, keys: Value? = null): Value { return createAnyVector(key, start, length, T_VECTOR, keys) { // add types since we are not creating a typed vector. for (i in start until stack.size) { buffer.put(stack[i].storedPackedType(it)) } } } private fun putMap(key: Int, start: Int, length: Int, keys: Value? = null): Value { return createAnyVector(key, start, length, T_MAP, keys) { // add types since we are not creating a typed vector. for (i in start until stack.size) { buffer.put(stack[i].storedPackedType(it)) } } } private inline fun createTypedVector(key: Int, start: Int, length: Int, keys: Value? = null): Value { // We assume the callers of this method guarantees all elements are of the same type. val elementType: FlexBufferType = stack[start].type for (i in start + 1 until length) { if (elementType != stack[i].type) error("TypedVector does not support array of different element types") } if (!elementType.isTypedVectorElementType()) error("TypedVector does not support this element type") return createAnyVector(key, start, length, elementType.toTypedVector(), keys) } private inline fun createAnyVector( key: Int, start: Int, length: Int, type: FlexBufferType, keys: Value? = null, crossinline typeBlock: (BitWidth) -> Unit = {} ): Value { // Figure out smallest bit width we can store this vector with. var bitWidth = W_8.max(length.toULong().widthInUBits()) var prefixElems = 1 if (keys != null) { // If this vector is part of a map, we will pre-fix an offset to the keys // to this vector. bitWidth = bitWidth.max(keys.elemWidth(buffer.writePosition, 0)) prefixElems += 2 } // Check bit widths and types for all elements. for (i in start until stack.size) { val elemWidth = stack[i].elemWidth(buffer.writePosition, i + prefixElems) bitWidth = bitWidth.max(elemWidth) } val byteWidth = align(bitWidth) // Write vector. First the keys width/offset if available, and size. if (keys != null) { writeOffset(keys.iValue.toInt(), byteWidth) writeInt(1 shl keys.minBitWidth.value, byteWidth) } // write the size writeInt(length, byteWidth) // Then the actual data. val vloc: Int = buffer.writePosition for (i in start until stack.size) { writeAny(stack[i], byteWidth) } // Optionally you can introduce the types for non-typed vector typeBlock(bitWidth) return Value(type, key, bitWidth, vloc.toULong()) } // A lambda to sort map keys internal val keyComparator = object : Comparator<Value> { override fun compare(a: Value, b: Value): Int { var ia: Int = a.key var io: Int = b.key var c1: Byte var c2: Byte do { c1 = buffer[ia] c2 = buffer[io] if (c1.toInt() == 0) return c1 - c2 ia++ io++ } while (c1 == c2) return c1 - c2 } } public companion object { /** * No keys or strings will be shared */ public const val SHARE_NONE: Int = 0 /** * Keys will be shared between elements. Identical keys will only be serialized once, thus possibly saving space. * But serialization performance might be slower and consumes more memory. */ public const val SHARE_KEYS: Int = 1 /** * Strings will be shared between elements. Identical strings will only be serialized once, thus possibly saving space. * But serialization performance might be slower and consumes more memory. This is ideal if you expect many repeated * strings on the message. */ public const val SHARE_STRINGS: Int = 2 /** * Strings and keys will be shared between elements. */ public const val SHARE_KEYS_AND_STRINGS: Int = 3 } }
apache-2.0
04e5daa9c0fe488a52b25b7a8edd54ca
34.507134
153
0.664889
3.80857
false
false
false
false
SkyTreasure/Kotlin-Firebase-Group-Chat
app/src/main/java/io/skytreasure/kotlingroupchat/MainActivity.kt
1
3790
package io.skytreasure.kotlingroupchat import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_main.* import android.view.View import android.widget.Toast import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import io.skytreasure.kotlingroupchat.chat.MyChatManager import io.skytreasure.kotlingroupchat.chat.ui.CreateGroupActivity import io.skytreasure.kotlingroupchat.chat.ui.OneOnOneChat import io.skytreasure.kotlingroupchat.chat.ui.ViewGroupsActivity import io.skytreasure.kotlingroupchat.common.constants.DataConstants import io.skytreasure.kotlingroupchat.common.constants.DataConstants.Companion.sCurrentUser import io.skytreasure.kotlingroupchat.common.constants.NetworkConstants import io.skytreasure.kotlingroupchat.common.controller.NotifyMeInterface import io.skytreasure.kotlingroupchat.common.util.SharedPrefManager import com.google.firebase.database.DatabaseError import android.databinding.adapters.NumberPickerBindingAdapter.setValue import android.util.Log import com.google.firebase.database.DataSnapshot import com.google.firebase.database.ValueEventListener import com.google.firebase.iid.FirebaseInstanceId class MainActivity : AppCompatActivity(), View.OnClickListener { var onlineRef: DatabaseReference? = null var currentUserRef: DatabaseReference? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) MyChatManager.setmContext(this@MainActivity) sCurrentUser = SharedPrefManager.getInstance(this@MainActivity).savedUserModel btn_creategroup.setOnClickListener(this) btn_showgroup.setOnClickListener(this) btn_oneonone.setOnClickListener(this) btn_logout.setOnClickListener(this) MyChatManager.setOnlinePresence() MyChatManager.updateFCMTokenAndDeviceId(this@MainActivity, FirebaseInstanceId.getInstance().token!!) MyChatManager.fetchAllUserInformation() MyChatManager.fetchMyGroups(object : NotifyMeInterface { override fun handleData(`object`: Any, requestCode: Int?) { var i = 0 for (group in DataConstants.sGroupMap!!) { if (group.value.members.containsKey(sCurrentUser?.uid!!)) { i += group.value.members.get(sCurrentUser?.uid)?.unread_group_count!! } } tv_notification_count.text = "Total Notification Count :" + i } }, NetworkConstants.FETCH_GROUPS, sCurrentUser, false) } override fun onClick(v: View?) { when (v?.id) { R.id.btn_creategroup -> { val intent = Intent(this@MainActivity, CreateGroupActivity::class.java) startActivity(intent) } R.id.btn_showgroup -> { val intent = Intent(this@MainActivity, ViewGroupsActivity::class.java) startActivity(intent) } R.id.btn_oneonone -> { val intent = Intent(this@MainActivity, OneOnOneChat::class.java) startActivity(intent) } R.id.btn_logout -> { MyChatManager.logout(this@MainActivity) } } } override fun onDestroy() { MyChatManager.goOffline(object : NotifyMeInterface { override fun handleData(`object`: Any, requestCode: Int?) { Toast.makeText(this@MainActivity, "You are offline now", Toast.LENGTH_SHORT).show() } }, sCurrentUser, NetworkConstants.GO_OFFLINE) super.onDestroy() } }
mit
2135250d007d7490119c5d235fbc7c75
38.479167
108
0.7
4.719801
false
false
false
false
Major-/Vicis
modern/src/main/kotlin/rs/emulate/modern/codec/bundle/Bundle.kt
1
4552
package rs.emulate.modern.codec.bundle import io.netty.buffer.ByteBuf import io.netty.buffer.Unpooled import rs.emulate.modern.codec.Archive import rs.emulate.modern.codec.Archive.Companion.readArchive import rs.emulate.modern.codec.Container import rs.emulate.modern.codec.Container.Companion.readContainer import rs.emulate.modern.codec.ReferenceTable import rs.emulate.modern.codec.ReferenceTable.Companion.readRefTable import java.io.FileNotFoundException import java.util.* class Bundle(private val referenceTable: ReferenceTable = ReferenceTable()) { private val entries = TreeMap<Int, ByteBuf>() private var dirtyReferenceTable = false val capacity: Int get() = referenceTable.capacity val listFiles: List<Int> get() = referenceTable.entryIds private fun createArchive(entry: ReferenceTable.Entry): BundleArchive { val archive = Archive() return BundleArchive(this, archive, entry) } fun createArchive(name: String): BundleArchive { val entry = referenceTable.createEntry() entry.setName(name) return createArchive(entry) } fun createArchive(file: Int): BundleArchive { val entry = referenceTable.createEntry(file) return createArchive(entry) } private fun openArchive(entry: ReferenceTable.Entry): BundleArchive { val archive = read(entry).readArchive(entry) return BundleArchive(this, archive, entry) } fun openArchive(name: String): BundleArchive { return openArchive(referenceTable.getEntry(name) ?: throw FileNotFoundException()) } fun openArchive(file: Int): BundleArchive { return openArchive(referenceTable.getEntry(file) ?: throw FileNotFoundException()) } fun flushArchive(entry: ReferenceTable.Entry, archive: Archive) { entry.bumpVersion() write(entry, archive.write()) dirtyReferenceTable = true } operator fun contains(file: Int) = referenceTable.containsEntry(file) operator fun contains(name: String) = referenceTable.containsEntry(name) fun read(file: Int): ByteBuf { return read(referenceTable.getEntry(file) ?: throw FileNotFoundException()) } fun read(name: String): ByteBuf { return read(referenceTable.getEntry(name) ?: throw FileNotFoundException()) } private fun read(entry: ReferenceTable.Entry): ByteBuf { return requireNotNull(entries[entry.id]) { "Entry in ReferenceTable but not in Bundle" } } fun write(file: Int, buf: ByteBuf) { val entry = referenceTable.getEntry(file) if (entry != null) { entry.bumpVersion() write(entry, buf) } else { val newEntry = referenceTable.createEntry(file) write(newEntry, buf) } dirtyReferenceTable = true } fun write(name: String, buf: ByteBuf) { val entry = referenceTable.getEntry(name) if (entry != null) { entry.bumpVersion() write(entry, buf) } else { val newEntry = referenceTable.createEntry() newEntry.setName(name) write(newEntry, buf) } dirtyReferenceTable = true } private fun write(entry: ReferenceTable.Entry, buf: ByteBuf) { entries[entry.id] = buf } fun remove(file: Int) { referenceTable.getEntry(file) ?: throw FileNotFoundException() entries.remove(file) referenceTable.removeEntry(file) dirtyReferenceTable = true } fun remove(name: String) { val entry = referenceTable.getEntry(name) ?: throw FileNotFoundException() val file = entry.id entries.remove(file) referenceTable.removeEntry(file) dirtyReferenceTable = true } fun write(): ByteBuf { if (dirtyReferenceTable) { dirtyReferenceTable = false referenceTable.bumpVersion() } val buf = Unpooled.compositeBuffer() buf.addComponent(true, Container.pack(referenceTable.write())) for (entry in entries.values) { buf.addComponent(true, Container.pack(entry)) } return buf.asReadOnly() } companion object { fun ByteBuf.readBundle(): Bundle { val table = readContainer().buffer.readRefTable() val bundle = Bundle(table) for (id in table.entryIds) { bundle.entries[id] = readContainer().buffer } return bundle } } }
isc
012d27b6ee6f49b8f54ed8872c3ca9e6
28.179487
96
0.649165
4.616633
false
false
false
false
android/nowinandroid
feature/bookmarks/src/test/java/com/google/samples/apps/nowinandroid/feature/bookmarks/BookmarksViewModelTest.kt
1
3715
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid.feature.bookmarks import com.google.samples.apps.nowinandroid.core.domain.GetSaveableNewsResourcesStreamUseCase import com.google.samples.apps.nowinandroid.core.model.data.previewNewsResources import com.google.samples.apps.nowinandroid.core.testing.repository.TestNewsRepository import com.google.samples.apps.nowinandroid.core.testing.repository.TestUserDataRepository import com.google.samples.apps.nowinandroid.core.testing.util.MainDispatcherRule import com.google.samples.apps.nowinandroid.core.ui.NewsFeedUiState.Loading import com.google.samples.apps.nowinandroid.core.ui.NewsFeedUiState.Success import kotlin.test.assertEquals import kotlin.test.assertIs import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Rule import org.junit.Test /** * To learn more about how this test handles Flows created with stateIn, see * https://developer.android.com/kotlin/flow/test#statein */ class BookmarksViewModelTest { @get:Rule val dispatcherRule = MainDispatcherRule() private val userDataRepository = TestUserDataRepository() private val newsRepository = TestNewsRepository() private val getSaveableNewsResourcesStreamUseCase = GetSaveableNewsResourcesStreamUseCase( newsRepository = newsRepository, userDataRepository = userDataRepository ) private lateinit var viewModel: BookmarksViewModel @Before fun setup() { viewModel = BookmarksViewModel( userDataRepository = userDataRepository, getSaveableNewsResourcesStream = getSaveableNewsResourcesStreamUseCase ) } @Test fun stateIsInitiallyLoading() = runTest { assertEquals(Loading, viewModel.feedUiState.value) } @Test fun oneBookmark_showsInFeed() = runTest { val collectJob = launch(UnconfinedTestDispatcher()) { viewModel.feedUiState.collect() } newsRepository.sendNewsResources(previewNewsResources) userDataRepository.updateNewsResourceBookmark(previewNewsResources[0].id, true) val item = viewModel.feedUiState.value assertIs<Success>(item) assertEquals(item.feed.size, 1) collectJob.cancel() } @Test fun oneBookmark_whenRemoving_removesFromFeed() = runTest { val collectJob = launch(UnconfinedTestDispatcher()) { viewModel.feedUiState.collect() } // Set the news resources to be used by this test newsRepository.sendNewsResources(previewNewsResources) // Start with the resource saved userDataRepository.updateNewsResourceBookmark(previewNewsResources[0].id, true) // Use viewModel to remove saved resource viewModel.removeFromSavedResources(previewNewsResources[0].id) // Verify list of saved resources is now empty val item = viewModel.feedUiState.value assertIs<Success>(item) assertEquals(item.feed.size, 0) collectJob.cancel() } }
apache-2.0
719c50216287472f40016138574fe873
38.521277
95
0.756931
4.702532
false
true
false
false
ianhanniballake/ContractionTimer
mobile/src/main/java/com/ianhanniballake/contractiontimer/ui/AboutActivity.kt
1
1538
package com.ianhanniballake.contractiontimer.ui import android.content.pm.ActivityInfo import android.os.Bundle import android.preference.PreferenceManager import android.util.Log import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.ianhanniballake.contractiontimer.BuildConfig import com.ianhanniballake.contractiontimer.R /** * About screen for the application. Shows as a dialog on large devices */ class AboutActivity : AppCompatActivity() { companion object { private const val TAG = "AboutActivity" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_about) val version = findViewById<TextView>(R.id.version) version.text = getString(R.string.version, BuildConfig.VERSION_NAME) } override fun onStart() { super.onStart() supportActionBar?.setDisplayHomeAsUpEnabled(true) } override fun onResume() { super.onResume() val preferences = PreferenceManager.getDefaultSharedPreferences(this) val isLockPortrait = preferences.getBoolean(Preferences.LOCK_PORTRAIT_PREFERENCE_KEY, resources.getBoolean(R.bool.pref_lock_portrait_default)) if (BuildConfig.DEBUG) Log.d(TAG, "Lock Portrait: $isLockPortrait") requestedOrientation = if (isLockPortrait) ActivityInfo.SCREEN_ORIENTATION_PORTRAIT else ActivityInfo.SCREEN_ORIENTATION_SENSOR } }
bsd-3-clause
a340ee8e6f4072c0ad47d03b88abe12d
33.954545
93
0.724317
4.929487
false
true
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmark/ui/tree/BookmarkNode.kt
2
4172
// 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.ide.bookmark.ui.tree import com.intellij.ide.bookmark.Bookmark import com.intellij.ide.bookmark.BookmarkGroup import com.intellij.ide.bookmark.BookmarkType import com.intellij.ide.bookmark.ui.BookmarksView import com.intellij.ide.projectView.PresentationData import com.intellij.ide.projectView.ProjectViewNode import com.intellij.ide.projectView.ProjectViewSettings.Immutable.DEFAULT import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.presentation.FilePresentationService import com.intellij.ui.BackgroundSupplier import com.intellij.ui.IconManager import com.intellij.ui.SimpleTextAttributes import javax.swing.Icon abstract class BookmarkNode<B : Bookmark>(project: Project, bookmark: B) : BackgroundSupplier, ProjectViewNode<B>(project, bookmark, DEFAULT) { val bookmarksView: BookmarksView? get() = parentRootNode?.value private val bookmarkType get() = bookmarksManager?.getType(value) val bookmarkDescription get() = bookmarkGroup?.getDescription(value)?.ifBlank { null } var bookmarkGroup: BookmarkGroup? = null override fun canRepresent(element: Any?) = virtualFile?.equals(element) ?: false override fun contains(file: VirtualFile) = virtualFile?.let { VfsUtil.isAncestor(it, file, true) } ?: false override fun canNavigate() = value.canNavigate() override fun canNavigateToSource() = value.canNavigateToSource() override fun navigate(requestFocus: Boolean) = value.navigate(requestFocus) override fun computeBackgroundColor() = FilePresentationService.getFileBackgroundColor(project, virtualFile) override fun getElementBackground(row: Int) = presentation.background protected fun wrapIcon(icon: Icon?): Icon { val type = bookmarkType ?: BookmarkType.DEFAULT return when { icon == null -> type.icon type == BookmarkType.DEFAULT -> icon else -> IconManager.getInstance().createRowIcon(type.icon, icon) } } override fun update(presentation: PresentationData) { val file = virtualFile ?: return presentation.setIcon(wrapIcon(findFileIcon())) addTextTo(presentation, file) } protected fun addTextTo(presentation: PresentationData, file: VirtualFile, line: Int = 0) { val name = file.presentableName val location = file.parent?.let { getRelativePath(it) } addTextTo(presentation, name, location, line) } protected fun addTextTo(presentation: PresentationData, name: @NlsSafe String, location: @NlsSafe String? = null, line: Int = 0) { val description = bookmarkDescription if (description == null) { presentation.presentableText = name // configure speed search presentation.addText(name, SimpleTextAttributes.REGULAR_ATTRIBUTES) if (line > 0) presentation.addText(" :$line", SimpleTextAttributes.GRAYED_ATTRIBUTES) location?.let { presentation.addText(" $it", SimpleTextAttributes.GRAYED_ATTRIBUTES) } } else { presentation.presentableText = "$description $name" // configure speed search presentation.addText("$description ", SimpleTextAttributes.REGULAR_ATTRIBUTES) presentation.addText(name, SimpleTextAttributes.GRAYED_ATTRIBUTES) if (line > 0) presentation.addText(" :$line", SimpleTextAttributes.GRAYED_ATTRIBUTES) location?.let { presentation.addText(" ($it)", SimpleTextAttributes.GRAYED_ATTRIBUTES) } } } private fun getRelativePath(file: VirtualFile): @NlsSafe String? { val project = project ?: return null if (project.isDisposed) return null val index = ProjectFileIndex.getInstance(project) index.getModuleForFile(file, false) ?: return computeExternalLocation(file) var root = file while (true) { val parent = root.parent ?: break index.getModuleForFile(parent, false) ?: break root = parent } return if (file == root) null else VfsUtil.getRelativePath(file, root) } }
apache-2.0
aec0d81c123247b4a986f5d4f5a8c92d
42.010309
132
0.754314
4.549618
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/compilingEvaluator/inaccessibleMembers/selfMembersNoReflection.kt
7
1260
package ceMembers fun main(args: Array<String>) { A().test() } class A { public fun publicFun(): Int = 1 public val publicVal: Int = 2 protected fun protectedFun(): Int = 3 protected val protectedVal: Int = 4 @JvmField protected val protectedField: Int = 5 private fun privateFun() = 6 private val privateVal = 7 fun test() { //Breakpoint! val a = 1 } } fun <T> block(block: () -> T): T { return block() } // Working as intended on EE-IR: No support for disabling reflective access // REFLECTION_PATCHING: false // EXPRESSION: block { publicFun() } // RESULT: 1: I // EXPRESSION: block { publicVal } // RESULT: Method threw 'java.lang.IllegalAccessError' exception. // EXPRESSION: block { protectedFun() } // RESULT: Method threw 'java.lang.IllegalAccessError' exception. // EXPRESSION: block { protectedVal } // RESULT: Method threw 'java.lang.IllegalAccessError' exception. // EXPRESSION: block { protectedField } // RESULT: Method threw 'java.lang.IllegalAccessError' exception. // EXPRESSION: block { privateFun() } // RESULT: Method threw 'java.lang.VerifyError' exception. // EXPRESSION: block { privateVal } // RESULT: Method threw 'java.lang.IllegalAccessError' exception.
apache-2.0
cde10110ff06859fe7fd10668f034f25
22.792453
75
0.678571
3.876923
false
false
false
false
OnyxDevTools/onyx-database-parent
onyx-database-tests/src/main/kotlin/entities/OneToOneChildFetchEntity.kt
1
529
package entities import com.onyx.persistence.IManagedEntity import com.onyx.persistence.annotations.* import com.onyx.persistence.annotations.values.RelationshipType /** * Created by timothy.osborn on 11/15/14. */ @Entity class OneToOneChildFetchEntity : AbstractInheritedAttributes(), IManagedEntity { @Attribute @Identifier var id: String? = null @Relationship(type = RelationshipType.ONE_TO_ONE, inverseClass = OneToOneFetchEntity::class, inverse = "child") var parent: OneToOneFetchEntity? = null }
agpl-3.0
a538cbc80898e0b989632b26f1a22db2
26.842105
115
0.765595
4.371901
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/internal/ui/uiDslTestAction/OthersPanel.kt
8
1373
// 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.internal.ui.uiDslTestAction import com.intellij.openapi.ui.Messages import com.intellij.ui.dsl.builder.COLUMNS_LARGE import com.intellij.ui.dsl.builder.columns import com.intellij.ui.dsl.builder.panel import com.intellij.ui.dsl.builder.text import org.jetbrains.annotations.ApiStatus import javax.swing.JEditorPane @Suppress("DialogTitleCapitalization") @ApiStatus.Internal internal class OthersPanel { val panel = panel { group("DslLabel text update") { lateinit var dslText: JEditorPane row { dslText = text("Initial text with a <a href='link'>link</a>", action = { Messages.showMessageDialog("Link '${it.description}' is clicked", "Message", null) }) .component } row { val textField = textField() .text("New text with <a href='another link'>another link</a><br>Second line") .columns(COLUMNS_LARGE) .component button("Update") { dslText.text = textField.text } } } group("Size groups") { row { button("Button", {}).widthGroup("group1") button("A very long button", {}).widthGroup("group1") }.rowComment("Buttons with the same widthGroup") } } }
apache-2.0
200e07b154227ca568d365afdfc11935
30.227273
120
0.657684
4.123123
false
false
false
false
daviddenton/k2
src/test/kotlin/Runners.kt
1
4507
import io.github.daviddenton.k2.Filter import io.github.daviddenton.k2.Service import io.github.daviddenton.k2.Service.Companion.mk import io.github.daviddenton.k2.Svc import io.github.daviddenton.k2.contract.* import io.github.daviddenton.k2.contract.ContentType.Companion.APPLICATION_FORM_URLENCODED import io.github.daviddenton.k2.contract.ContentType.Companion.APPLICATION_XML import io.github.daviddenton.k2.formats.Argo import io.github.daviddenton.k2.formats.Argo.Json import io.github.daviddenton.k2.formats.Argo.Json.asJson import io.github.daviddenton.k2.formats.Argo.Json.obj import io.github.daviddenton.k2.formats.Argo.Response import io.github.daviddenton.k2.http.Method import io.github.daviddenton.k2.http.Method.Get import io.github.daviddenton.k2.http.Request import io.github.daviddenton.k2.http.Root import io.github.daviddenton.k2.module.render.RouteModule import java.time.LocalDate data class Bob(val value: String) data class DateWrapper(val value: LocalDate) fun main(args: Array<String>) { fun servicesAndFilters() { println("filters") val asInt = Filter.mk { req: String, svc: Service<Int, Int> -> svc(req.toInt()).toString() } val tripleResult = Filter.mk { req: Int, svc: Service<Int, Int> -> svc(req) * 3 } println((asInt.andThen(tripleResult).andThen(Service.const(123)))("321")) } fun routes() { println("routes") val bob = Path.of(Parameter.string().map(::Bob, Bob::value).single("bob")) val json = Path.of(Argo.parameter.single("bob")) val query = Query.required(Argo.parameter.single("bob")) fun svc(string: Bob): Svc = Service.const(Response(200).build()) val serverRoute = Route("bob") .producing(APPLICATION_FORM_URLENCODED) .consuming(APPLICATION_XML) .body(Body.of(Body.string(ContentType.TEXT_HTML))) .taking(query) / "bob" / bob at Get bind ::svc val clientRoute = Route("bob2") / "bob" / bob at Get bindClient mk { r: Request -> Response(200).withContent(Json.array(Json.string(r.uri))).build() } val a = RouteModule(Root) .withRoute(serverRoute).toService() println(a(Request(Get, "/asd"))) } fun parameters() { println("parameters") val date: NamedParameter<DateWrapper, DateWrapper> = Parameter.localDate().map(::DateWrapper).single("date") val dates: NamedParameter<DateWrapper, Iterable<DateWrapper>> = Parameter.localDate().map(::DateWrapper).multi("dates") val dateWOpt: DateWrapper? = Query.optional(date).from(Request(Get, "http://location/index?date=2012-10-02", "")) val dateWListOpt: Iterable<DateWrapper>? = Query.optional(dates).from(Request(Get, "http://location/index?dates=2012-10-02", "")) val dateW: DateWrapper = Query.required(date).from(Request(Get, "http://location/index?date=2012-10-02", "")) val dateWList: Iterable<DateWrapper> = Query.required(dates).from(Request(Get, "http://location/index?dates=2012-10-02", "")) println(Query.optional(date).extract(Request(Get, "http://location/index", ""))) println(Query.optional(dates).extract(Request(Get, "http://location/index", ""))) println(Query.required(date).extract(Request(Get, "http://location/index?date=2012-10-02", ""))) println(Query.required(dates).extract(Request(Get, "http://location/index?dates=2012-10-02", ""))) } fun bodies() { println("bodies") val field1 = FormField.required(Parameter.string().map(::Bob, Bob::value).multi("bob")) val field2 = FormField.required(Parameter.boolean().single("sue")) val form = Body.of(Form.mk(field1, field2)).from(Request(Method.Post, "http://location/index", "bob=hello&bob=hello2&sue=true")) println("${field1.named.name}=${form[field1]}") println("${field2.named.name}=${form[field2]}") Form(field1.of(listOf<Bob>()), field2.of(true)) println(Body.of(Form.mk(field1, field2)).extract(Request(Method.Post, "http://location/index", "bob=hello&bob=hello2"))) val body = Body.of(Argo.body.map({ Bob(it.getStringValue("name")) }) { obj("name" to it.value.asJson()) }) println(body.from(Request(Get, "http://location/index?bob=foo&bob=fo2", """{"name":"bobby"}"""))) } fun formats() { println("formats") println(obj("name" to Json.string("hello"))) } servicesAndFilters() formats() routes() parameters() bodies() }
apache-2.0
a1dece6c9009a74fe902f1eb78d0f2f8
46.452632
158
0.674284
3.404079
false
false
false
false
MichaelRocks/grip
library/src/main/java/io/michaelrocks/grip/commons/CollectionsExtensions.kt
1
1285
/* * Copyright 2021 Michael Rozumyanskiy * * 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.michaelrocks.grip.commons import java.util.Collections import java.util.SortedMap import java.util.SortedSet internal fun <T> Collection<T>.immutable(): Collection<T> = Collections.unmodifiableCollection(this) internal fun <T> List<T>.immutable(): List<T> = Collections.unmodifiableList(this) internal fun <K, V> Map<K, V>.immutable(): Map<K, V> = Collections.unmodifiableMap(this) internal fun <T> Set<T>.immutable(): Set<T> = Collections.unmodifiableSet(this) internal fun <K, V> SortedMap<K, V>.immutable(): SortedMap<K, V> = Collections.unmodifiableSortedMap(this) internal fun <T> SortedSet<T>.immutable(): SortedSet<T> = Collections.unmodifiableSortedSet(this)
apache-2.0
74537a0802c8de45cf8abced563423dd
44.892857
106
0.755642
3.941718
false
false
false
false
MichaelRocks/grip
library/src/main/java/io/michaelrocks/grip/MethodsResult.kt
1
1909
/* * Copyright 2021 Michael Rozumyanskiy * * 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.michaelrocks.grip import io.michaelrocks.grip.commons.LazyMap import io.michaelrocks.grip.mirrors.ClassMirror import io.michaelrocks.grip.mirrors.MethodMirror import io.michaelrocks.grip.mirrors.Type interface MethodsResult : Map<Type.Object, List<MethodMirror>> { val types: Set<Type.Object> get() = keys fun containsType(type: Type.Object) = containsKey(type) class Builder { private val methods = LazyMap<Type.Object, List<MethodMirror>>() fun addMethods(classMirror: ClassMirror, methodMirrors: Iterable<MethodMirror>) = apply { val oldMethods = methods.put(classMirror.type, methodMirrors.toList()) require(oldMethods == null) { "Methods for class ${classMirror.type} have already been added" } } fun build(): MethodsResult = ImmutableMethodsResult(this) private class ImmutableMethodsResult( builder: Builder ) : MethodsResult, Map<Type.Object, List<MethodMirror>> by builder.methods.detachImmutableCopy() } } internal inline fun buildMethodsResult(body: MethodsResult.Builder.() -> Unit) = MethodsResult.Builder().run { body() build() } val Map.Entry<Type.Object, List<MethodMirror>>.type: Type.Object get() = key val Map.Entry<Type.Object, List<MethodMirror>>.methods: List<MethodMirror> get() = value
apache-2.0
88ea6d6181fab855c2ff318808c37904
33.089286
101
0.738083
3.985386
false
false
false
false
KDE/kdeconnect-android
src/org/kde/kdeconnect/UserInterface/About/ApplicationAboutData.kt
1
2910
/* * SPDX-FileCopyrightText: 2021 Maxim Leshchenko <[email protected]> * * SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL */ package org.kde.kdeconnect.UserInterface.About import android.content.Context import org.kde.kdeconnect_tp.BuildConfig import org.kde.kdeconnect_tp.R /** * Add authors and credits here */ fun getApplicationAboutData(context: Context): AboutData { val aboutData = AboutData(context.getString(R.string.kde_connect), R.string.app_description, R.drawable.icon, BuildConfig.VERSION_NAME, context.getString(R.string.copyright_statement), context.getString(R.string.report_bug_url), context.getString(R.string.website_url), context.getString(R.string.source_code_url), context.getString(R.string.donate_url), R.string.everyone_else) aboutData.authors += AboutPerson("Albert Vaca Cintora", R.string.maintainer_and_developer, "[email protected]") aboutData.authors += AboutPerson("Aleix Pol", R.string.developer, "[email protected]") aboutData.authors += AboutPerson("Inoki Shaw", R.string.apple_support, "[email protected]") aboutData.authors += AboutPerson("Matthijs Tijink", R.string.developer, "[email protected]") aboutData.authors += AboutPerson("Nicolas Fella", R.string.developer, "[email protected]") aboutData.authors += AboutPerson("Philip Cohn-Cort", R.string.developer, "[email protected]") aboutData.authors += AboutPerson("Piyush Aggarwal", R.string.developer, "[email protected]") aboutData.authors += AboutPerson("Simon Redman", R.string.developer, "[email protected]") aboutData.authors += AboutPerson("Erik Duisters", R.string.developer, "[email protected]") aboutData.authors += AboutPerson("Isira Seneviratne", R.string.developer, "[email protected]") aboutData.authors += AboutPerson("Vineet Garg", R.string.developer, "[email protected]") aboutData.authors += AboutPerson("Anjani Kumar", R.string.bug_fixes_and_general_improvements, "[email protected]") aboutData.authors += AboutPerson("Samoilenko Yuri", R.string.samoilenko_yuri_task, "[email protected]") aboutData.authors += AboutPerson("Aniket Kumar", R.string.aniket_kumar_task, "[email protected]") aboutData.authors += AboutPerson("Àlex Fiestas", R.string.alex_fiestas_task, "[email protected]") aboutData.authors += AboutPerson("Daniel Tang", R.string.bug_fixes_and_general_improvements, "[email protected]") aboutData.authors += AboutPerson("Maxim Leshchenko", R.string.maxim_leshchenko_task, "[email protected]") aboutData.authors += AboutPerson("Holger Kaelberer", R.string.holger_kaelberer_task, "[email protected]") aboutData.authors += AboutPerson("Saikrishna Arcot", R.string.saikrishna_arcot_task, "[email protected]") return aboutData }
gpl-2.0
2d8d49de129e8fffe18ac2feabc5c924
68.285714
199
0.742867
3.13808
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinUsageInfo.kt
6
1846
// 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.refactoring.changeSignature.usages import com.intellij.openapi.util.Key import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.util.descendantsOfType import com.intellij.usageView.UsageInfo import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeInfo import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.NotNullablePsiCopyableUserDataProperty abstract class KotlinUsageInfo<T : PsiElement> : UsageInfo { constructor(element: T) : super(element) constructor(reference: PsiReference) : super(reference) @Suppress("UNCHECKED_CAST") override fun getElement() = super.getElement() as T? open fun preprocessUsage() {} abstract fun processUsage(changeInfo: KotlinChangeInfo, element: T, allUsages: Array<out UsageInfo>): Boolean protected fun <T: KtElement> T.asMarkedForShortening(): T = apply { isMarked = true } protected fun KtElement.flushElementsForShorteningToWaitList(options: ShortenReferences.Options = ShortenReferences.Options.ALL_ENABLED) { for (element in descendantsOfType<KtElement>()) { if (element.isMarked) { element.isMarked = false element.addToShorteningWaitSet(options) } } } companion object { private var KtElement.isMarked: Boolean by NotNullablePsiCopyableUserDataProperty( key = Key.create("MARKER_FOR_SHORTENING"), defaultValue = false, ) } }
apache-2.0
48ff9203c8983acb25351378091b10b5
39.130435
158
0.742145
4.733333
false
false
false
false
dahlstrom-g/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonTooltipActionProvider.kt
5
5756
// 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.codeInsight.daemon.impl import com.intellij.codeInsight.daemon.impl.tooltips.TooltipActionProvider import com.intellij.codeInsight.intention.AbstractEmptyIntentionAction import com.intellij.codeInsight.intention.CustomizableIntentionAction import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.IntentionActionDelegate import com.intellij.codeInsight.intention.impl.CachedIntentions import com.intellij.codeInsight.intention.impl.ShowIntentionActionsHandler import com.intellij.internal.statistic.service.fus.collectors.TooltipActionsLogger import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ex.TooltipAction import com.intellij.openapi.util.NlsActions import com.intellij.openapi.util.NlsContexts import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.xml.util.XmlStringUtil import java.awt.event.InputEvent import java.util.* class DaemonTooltipActionProvider : TooltipActionProvider { override fun getTooltipAction(info: HighlightInfo, editor: Editor, psiFile: PsiFile): TooltipAction? { val intention = extractMostPriorityFixFromHighlightInfo(info, editor, psiFile) ?: return null return wrapIntentionToTooltipAction(intention, info, editor) } } /** * Tooltip link-action that proxies its execution to intention action with text [myActionText] * @param myFixText is a text to show in tooltip * @param myActionText is a text to search for in intentions' actions */ class DaemonTooltipAction(@NlsActions.ActionText private val myFixText: String, @NlsContexts.Command private val myActionText: String, private val myActualOffset: Int) : TooltipAction { override fun getText(): String { return myFixText } override fun execute(editor: Editor, inputEvent: InputEvent?) { val project = editor.project ?: return TooltipActionsLogger.logExecute(project, inputEvent) val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return val intentions = ShowIntentionsPass.getAvailableFixes(editor, psiFile, -1, myActualOffset) for (descriptor in intentions) { val action = descriptor.action if (action.text == myActionText) { //unfortunately it is very common case when quick fixes/refactorings use caret position editor.caretModel.moveToOffset(myActualOffset) ShowIntentionActionsHandler.chooseActionAndInvoke(psiFile, editor, action, myActionText) return } } } override fun showAllActions(editor: Editor) { editor.caretModel.moveToOffset(myActualOffset) val project = editor.project ?: return TooltipActionsLogger.showAllEvent.log(project) val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return ShowIntentionActionsHandler().invoke(project, editor, psiFile) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val info = other as DaemonTooltipAction? return myActualOffset == info!!.myActualOffset && myFixText == info.myFixText } override fun hashCode(): Int { return Objects.hash(myFixText, myActualOffset) } } fun extractMostPriorityFixFromHighlightInfo(highlightInfo: HighlightInfo, editor: Editor, psiFile: PsiFile): IntentionAction? { ApplicationManager.getApplication().assertReadAccessAllowed() val fixes = mutableListOf<HighlightInfo.IntentionActionDescriptor>() val quickFixActionMarkers = highlightInfo.quickFixActionRanges if (quickFixActionMarkers.isNullOrEmpty()) return null fixes.addAll(quickFixActionMarkers.map { it.first }.toList()) val intentionsInfo = ShowIntentionsPass.IntentionsInfo() ShowIntentionsPass.fillIntentionsInfoForHighlightInfo(highlightInfo, intentionsInfo, fixes) intentionsInfo.filterActions(psiFile) return getFirstAvailableAction(psiFile, editor, intentionsInfo) } fun getFirstAvailableAction(psiFile: PsiFile, editor: Editor, intentionsInfo: ShowIntentionsPass.IntentionsInfo): IntentionAction? { val project = psiFile.project //sort the actions val cachedIntentions = CachedIntentions.createAndUpdateActions(project, psiFile, editor, intentionsInfo) val allActions = cachedIntentions.allActions if (allActions.isEmpty()) return null allActions.forEach { val action = IntentionActionDelegate.unwrap(it.action) if (action !is AbstractEmptyIntentionAction && action.isAvailable(project, editor, psiFile)) { val text = it.text //we cannot properly render html inside the fix button fixes with html text if (!XmlStringUtil.isWrappedInHtml(text)) { return action } } } return null } fun wrapIntentionToTooltipAction(intention: IntentionAction, info: HighlightInfo, editor: Editor): TooltipAction { val editorOffset = editor.caretModel.offset val text = (intention as? CustomizableIntentionAction)?.tooltipText ?: intention.text if ((info.actualStartOffset .. info.actualEndOffset).contains(editorOffset)) { //try to avoid caret movements return DaemonTooltipAction(text, intention.text, editorOffset) } val pair = info.quickFixActionMarkers?.find { it.first?.action == intention } val offset = if (pair?.second?.isValid == true) pair.second.startOffset else info.actualStartOffset return DaemonTooltipAction(text, intention.text, offset) }
apache-2.0
22d0a56bf462daa839ea1d9c2438cc36
41.323529
185
0.768416
4.698776
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/table/FavMute.kt
1
2779
package jp.juggler.subwaytooter.table import android.content.ContentValues import android.database.Cursor import android.database.sqlite.SQLiteDatabase import jp.juggler.subwaytooter.api.entity.Acct import jp.juggler.subwaytooter.global.appDatabase import jp.juggler.util.LogCategory import jp.juggler.util.TableCompanion object FavMute : TableCompanion { private val log = LogCategory("FavMute") override val table = "fav_mute" const val COL_ID = "_id" const val COL_ACCT = "acct" override fun onDBCreate(db: SQLiteDatabase) { log.d("onDBCreate!") db.execSQL( """create table if not exists $table ($COL_ID INTEGER PRIMARY KEY ,$COL_ACCT text not null )""".trimIndent() ) db.execSQL("create unique index if not exists ${table}_acct on $table($COL_ACCT)") } override fun onDBUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { if (oldVersion < 22 && newVersion >= 22) { onDBCreate(db) } } fun save(acct: Acct?) { acct ?: return try { val cv = ContentValues() cv.put(COL_ACCT, acct.ascii) appDatabase.replace(table, null, cv) } catch (ex: Throwable) { log.e(ex, "save failed.") } } fun delete(acct: Acct) { try { appDatabase.delete(table, "$COL_ACCT=?", arrayOf(acct.ascii)) } catch (ex: Throwable) { log.e(ex, "delete failed.") } } fun createCursor(): Cursor { return appDatabase.query(table, null, null, null, null, null, "$COL_ACCT asc") } val acctSet: HashSet<Acct> get() = HashSet<Acct>().also { dst -> try { appDatabase.query(table, null, null, null, null, null, null) .use { cursor -> val idx_name = cursor.getColumnIndex(COL_ACCT) while (cursor.moveToNext()) { val s = cursor.getString(idx_name) dst.add(Acct.parse(s)) } } } catch (ex: Throwable) { log.trace(ex) } } fun contains(acct: Acct): Boolean { var found = false try { appDatabase.query(table, null, "$COL_ACCT=?", arrayOf(acct.ascii), null, null, null) .use { cursor -> while (cursor.moveToNext()) { found = true } } } catch (ex: Throwable) { log.trace(ex) } return found } }
apache-2.0
a4031ac1d8ba561ccf220702dd44da6f
28.877778
96
0.504858
4.439297
false
false
false
false
dmillerw/LoreExpansion
src/main/kotlin/me/dmillerw/loreexpansion/adapter/KotlinAdapter.kt
1
2992
package me.dmillerw.loreexpansion.adapter import net.minecraftforge.fml.common.FMLModContainer import net.minecraftforge.fml.common.ILanguageAdapter import net.minecraftforge.fml.common.ModContainer import net.minecraftforge.fml.relauncher.Side import org.apache.logging.log4j.LogManager import java.lang.reflect.Field import java.lang.reflect.Method /** * @author Arkan <[email protected]> */ public class KotlinAdapter : ILanguageAdapter { companion object metadata { public final val ADAPTER_VERSION: String = "@VERSION@-@KOTLIN@" } private val log = LogManager.getLogger("ILanguageAdapter/Kotlin") override fun supportsStatics(): Boolean { return false } override fun setProxy(target: Field, proxyTarget: Class<*>, proxy: Any) { log.debug("Setting proxy: {}.{} -> {}", target.declaringClass.simpleName, target.name, proxy) if (proxyTarget.fields.any { x -> x.getName().equals("INSTANCE$") }) { // Singleton try { log.debug("Setting proxy on INSTANCE$; singleton target.") val obj = proxyTarget.getField("INSTANCE$").get(null) target.set(obj, proxy) } catch (ex: Exception) { throw KotlinAdapterException(ex) } } else { //TODO Log? target.set(proxyTarget, proxy) } } override fun getNewInstance(container: FMLModContainer?, objectClass: Class<*>, classLoader: ClassLoader, factoryMarkedAnnotation: Method?): Any? { log.debug("FML has asked for {} to be constructed...", objectClass.getSimpleName()) try { // Try looking for an object type val f = objectClass.getField("INSTANCE$") val obj = f.get(null) ?: throw NullPointerException() log.debug("Found an object INSTANCE$ reference in {}, using that. ({})", objectClass.getSimpleName(), obj) return obj } catch (ex: Exception) { // Try looking for a class type log.debug("Failed to get object reference, trying class construction.") try { val obj = objectClass.newInstance() ?: throw NullPointerException() log.debug("Constructed an object from a class type ({}), using that. ({})", objectClass, obj) log.warn("Hey, you, modder who owns {} - you should be using 'object' instead of 'class' on your @Mod class.", objectClass.getSimpleName()) return obj } catch (ex: Exception) { throw KotlinAdapterException(ex) } } } override fun setInternalProxies(mod: ModContainer?, side: Side?, loader: ClassLoader?) { // Nothing to do; FML's got this covered for Kotlin. } private class KotlinAdapterException(ex:Exception): RuntimeException("Kotlin adapter error - do not report to Forge!", ex) }
mit
fc8be019791045871f9e4c819ebd9668
39.583333
155
0.613636
4.660436
false
false
false
false
BreakOutEvent/breakout-backend
src/main/java/backend/util/GeoTools.kt
1
2184
package backend.util import backend.model.location.Location import backend.model.location.SpeedToLocation import backend.model.misc.Coord import com.grum.geocalc.DegreeCoordinate import com.grum.geocalc.EarthCalc import com.grum.geocalc.Point import java.time.temporal.ChronoUnit /** * Used Library Geocalc: * Copyright (c) 2015, Grumlimited Ltd (Romain Gallet) * * https://github.com/grumlimited/geocalc * * Full License Text: https://github.com/grumlimited/geocalc/blob/master/LICENSE.txt */ fun speedToLocation(toLocation: Location, fromLocation: Location): SpeedToLocation? { val secondsDifference = toLocation.date.until(fromLocation.date, ChronoUnit.SECONDS) val distanceKm = distanceCoordsKM(fromLocation.coord, toLocation.coord) return calculateSpeed(distanceKm, secondsDifference) } fun calculateSpeed(distanceKm: Double, secondsDifference: Long): SpeedToLocation? { return if (distanceKm > 0 && secondsDifference > 0) { val speed = distanceKm / (secondsDifference / 3600.0) SpeedToLocation(speed, secondsDifference, distanceKm) } else { null } } fun distanceCoordsKM(from: Coord, to: Coord): Double { val fromPoint: Point = coordToPoint(from) val toPoint: Point = coordToPoint(to) return EarthCalc.getVincentyDistance(fromPoint, toPoint) / 1000 } fun distanceCoordsListKMfromStart(startingPoint: Coord, list: List<Coord>): Double { val coordsList = arrayListOf(startingPoint) coordsList.addAll(list) return distanceCoordsListKM(coordsList) } fun distanceCoordsListKM(list: List<Coord>): Double = coordsListToPairList(list).fold(0.0) { total, (first, second) -> total + distanceCoordsKM(first, second) } fun coordsListToPairList(list: List<Coord>): List<Pair<Coord, Coord>> { val coordPairs: MutableList<Pair<Coord, Coord>> = arrayListOf() var lastCoord: Coord? = null list.forEach { thisCoord -> if (lastCoord != null) { coordPairs.add(Pair(lastCoord!!, thisCoord)) } lastCoord = thisCoord } return coordPairs } fun coordToPoint(coord: Coord): Point = Point(DegreeCoordinate(coord.latitude), DegreeCoordinate(coord.longitude))
agpl-3.0
ecde9be844866e5ac37e776a17a53875
32.615385
160
0.738095
3.682968
false
false
false
false
paplorinc/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/GuiTestThread.kt
1
5512
// 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.testGuiFramework.impl import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.impl.ApplicationImpl import com.intellij.openapi.diagnostic.Logger import com.intellij.testGuiFramework.framework.param.GuiTestLocalRunnerParam import com.intellij.testGuiFramework.launcher.GuiTestOptions import com.intellij.testGuiFramework.launcher.GuiTestOptions.RESUME_LABEL import com.intellij.testGuiFramework.remote.JUnitClientListener import com.intellij.testGuiFramework.remote.client.ClientHandler import com.intellij.testGuiFramework.remote.client.JUnitClient import com.intellij.testGuiFramework.remote.client.JUnitClientImpl import com.intellij.testGuiFramework.remote.transport.JUnitTestContainer import com.intellij.testGuiFramework.remote.transport.MessageType import com.intellij.testGuiFramework.remote.transport.TransportMessage import org.junit.runner.JUnitCore import org.junit.runner.Request import org.junit.runners.model.TestClass import org.junit.runners.parameterized.TestWithParameters import java.util.concurrent.BlockingQueue import java.util.concurrent.LinkedBlockingQueue /** * @author Sergey Karashevich */ class GuiTestThread : Thread(GUI_TEST_THREAD_NAME) { private var testQueue: BlockingQueue<JUnitTestContainer> = LinkedBlockingQueue() private val core = JUnitCore() private val LOG = Logger.getInstance("#com.intellij.testGuiFramework.impl.GuiTestThread") companion object { const val GUI_TEST_THREAD_NAME: String = "GuiTest Thread" var client: JUnitClient? = null } override fun run() { client = JUnitClientImpl(host(), port(), createInitHandlers()) client!!.addHandler(createCloseHandler()) val myListener = JUnitClientListener { jUnitInfo -> client!!.send(TransportMessage(MessageType.JUNIT_INFO, jUnitInfo)) } core.addListener(myListener) try { while (true) { val testContainer = testQueue.take() LOG.info("Running test: $testContainer") runTest(testContainer) } } catch (e: InterruptedException) { Thread.currentThread().interrupt() } } private fun createInitHandlers(): Array<ClientHandler> { val testHandler = object : ClientHandler { override fun accept(message: TransportMessage) = message.type == MessageType.RUN_TEST override fun handle(message: TransportMessage) { val content = (message.content as JUnitTestContainer) LOG.info("Added test to testQueue: $content") testQueue.add(content) } } val testResumeHandler = object : ClientHandler { override fun accept(message: TransportMessage) = message.type == MessageType.RESUME_TEST override fun handle(message: TransportMessage) { val content = (message.content as JUnitTestContainer) if (!content.additionalInfo.containsKey(RESUME_LABEL)) throw Exception( "Cannot resume test without any additional info (label where to resume) in JUnitTestContainer") System.setProperty(GuiTestOptions.RESUME_LABEL, content.additionalInfo[RESUME_LABEL].toString()) System.setProperty(GuiTestOptions.RESUME_TEST, "${content.testClassName}#${content.testName}") LOG.info("Added test to testQueue: $content") testQueue.add(content) } } return arrayOf(testHandler, testResumeHandler) } private fun createCloseHandler(): ClientHandler { return object : ClientHandler { override fun accept(message: TransportMessage) = message.type == MessageType.CLOSE_IDE override fun handle(message: TransportMessage) { client?.send(TransportMessage(MessageType.RESPONSE, null, message.id)) ?: throw Exception( "Unable to handle transport message: \"$message\", because JUnitClient is accidentally null") val application = ApplicationManager.getApplication() (application as ApplicationImpl).exit(true, true) } } } private fun host(): String = System.getProperty(GuiTestStarter.GUI_TEST_HOST) private fun port(): Int = System.getProperty(GuiTestStarter.GUI_TEST_PORT).toInt() private fun runTest(testContainer: JUnitTestContainer) { val testClass: Class<*> = try { Class.forName(testContainer.testClassName) } catch (e: ClassNotFoundException) { loadClassFromPlugins(testContainer.testClassName) } if (testContainer.additionalInfo["parameters"] == null) { //todo: replace request with a runner val request = Request.method(testClass, testContainer.testName) core.run(request) } else { val runner = GuiTestLocalRunnerParam(TestWithParameters(testContainer.testName, TestClass(testClass), testContainer.additionalInfo["parameters"] as MutableList<*>)) core.run(runner) } } private fun loadClassFromPlugins(className: String): Class<*> { return PluginManagerCore.getPlugins().firstOrNull { try { it.pluginClassLoader.loadClass(className) true } catch (e: ClassNotFoundException) { false } }?.let { it.pluginClassLoader.loadClass(className) } ?: throw ClassNotFoundException("Unable to find class ($className) in IDE plugin classloaders") } private fun String.getParameterisedPart(): String { return Regex("\\[(.)*]").find(this)?.value ?: "" } }
apache-2.0
d322bc64539db90e05d0032024fac87f
39.536765
170
0.739659
4.691064
false
true
false
false
PaulWoitaschek/MaterialAudiobookPlayer
app/src/main/java/de/ph1b/audiobook/misc/ElevateToolbarOnScroll.kt
1
838
package de.ph1b.audiobook.misc import androidx.appcompat.widget.Toolbar import androidx.interpolator.view.animation.FastOutSlowInInterpolator import androidx.recyclerview.widget.RecyclerView class ElevateToolbarOnScroll(val toolbar: Toolbar) : RecyclerView.OnScrollListener() { private val interpolator = FastOutSlowInInterpolator() private val finalElevation = toolbar.context.dpToPxRounded(4F) override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { val toolbarHeight = toolbar.height if (toolbarHeight == 0) { return } val scrollY = recyclerView.computeVerticalScrollOffset() val fraction = (scrollY.toFloat() / toolbarHeight).coerceIn(0F, 1F) val interpolatedFraction = interpolator.getInterpolation(fraction) toolbar.elevation = interpolatedFraction * finalElevation } }
lgpl-3.0
d75a0162159cbf888ea27b4e5eeb4c61
37.090909
86
0.782816
4.681564
false
false
false
false
igorini/kotlin-android-app
app/src/main/java/com/igorini/kotlin/android/app/MainActivity.kt
1
950
package com.igorini.kotlin.android.app import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.Window import android.widget.Button import android.widget.EditText import org.jetbrains.anko.* /** Represents a main activity */ class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) requestWindowFeature(Window.FEATURE_NO_TITLE) setContentView(R.layout.activity_main) } } /** Represents a main activity UI */ /*class MainActivityUi : AnkoComponent<MainActivity> { private val customStyle = { v: Any -> when (v) { is Button -> v.textSize = 26f is EditText -> v.textSize = 24f } } override fun createView(ui: AnkoContext<MainActivity>) = with(ui) { verticalLayout { padding = dip(32) }.applyRecursively(customStyle) } }*/
apache-2.0
29d70919d5166fa6dcacac34ebc15e85
26.941176
71
0.676842
4.357798
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/tests/testData/decompiler/stubBuilder/InheritingClasses/InheritingClasses.kt
1
979
package a class InheritingClasses { abstract class A(override val c: Int = 1) : C { open fun of() = 3 abstract fun af(): Int open val op = 4 abstract val ap: Int } open class B : A(2) { override fun of() = 4 override fun af() = 5 override val op = 5 override val ap = 5 } interface C { val c: Int } interface D<T> : C { override val c: Int } interface E class G : B(), C, D<Int>, E class InheritAny { interface SomeInterface interface SomeInterface2 class ImplicitAny class ExplicitAny : Any() class OnlyInterface : SomeInterface class OnlyInterfaces : SomeInterface, SomeInterface2 class InterfaceWithExplicitAny : Any(), SomeInterface class InterfacesWithExplicitAny : SomeInterface2, Any(), SomeInterface } abstract class InheritFunctionType : ((Int, String) -> Int) }
apache-2.0
bef02970260c5dca233f3c494c0c5948
20.304348
78
0.581205
4.661905
false
false
false
false
JetBrains/intellij-community
platform/analysis-impl/src/com/intellij/profile/codeInspection/ProjectInspectionProfileManager.kt
1
9890
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.profile.codeInspection import com.intellij.codeInspection.ex.InspectionProfileImpl import com.intellij.codeInspection.ex.InspectionToolRegistrar import com.intellij.configurationStore.* import com.intellij.diagnostic.runActivity import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.openapi.options.SchemeManagerFactory import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupManager import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.packageDependencies.DependencyValidationManager import com.intellij.profile.ProfileChangeAdapter import com.intellij.project.isDirectoryBased import com.intellij.psi.search.scope.packageSet.NamedScopeManager import com.intellij.psi.search.scope.packageSet.NamedScopesHolder import com.intellij.util.xmlb.annotations.OptionTag import org.jdom.Element import org.jetbrains.annotations.TestOnly import java.util.function.Function private const val VERSION = "1.0" const val PROJECT_DEFAULT_PROFILE_NAME = "Project Default" private val defaultSchemeDigest = JDOMUtil.load("""<component name="InspectionProjectProfileManager"> <profile version="1.0"> <option name="myName" value="Project Default" /> </profile> </component>""").digest() const val PROFILE_DIR: String = "inspectionProfiles" const val PROFILES_SETTINGS: String = "profiles_settings.xml" @State(name = "InspectionProjectProfileManager", storages = [(Storage(value = "$PROFILE_DIR/profiles_settings.xml", exclusive = true))]) open class ProjectInspectionProfileManager(override val project: Project) : BaseInspectionProfileManager(project.messageBus), PersistentStateComponentWithModificationTracker<Element>, ProjectBasedInspectionProfileManager, Disposable { companion object { @JvmStatic fun getInstance(project: Project): ProjectInspectionProfileManager { return project.getService(InspectionProjectProfileManager::class.java) as ProjectInspectionProfileManager } } private var state = ProjectInspectionProfileManagerState() protected val schemeManagerIprProvider = if (project.isDirectoryBased) null else SchemeManagerIprProvider("profile") override val schemeManager = SchemeManagerFactory.getInstance(project).create(PROFILE_DIR, object : InspectionProfileProcessor() { override fun createScheme(dataHolder: SchemeDataHolder<InspectionProfileImpl>, name: String, attributeProvider: Function<in String, String?>, isBundled: Boolean): InspectionProfileImpl { val profile = InspectionProfileImpl(name, InspectionToolRegistrar.getInstance(), this@ProjectInspectionProfileManager, dataHolder) profile.isProjectLevel = true return profile } override fun isSchemeFile(name: CharSequence) = !StringUtil.equals(name, PROFILES_SETTINGS) override fun isSchemeDefault(scheme: InspectionProfileImpl, digest: ByteArray): Boolean { return scheme.name == PROJECT_DEFAULT_PROFILE_NAME && digest.contentEquals(defaultSchemeDigest) } override fun onSchemeDeleted(scheme: InspectionProfileImpl) { schemeRemoved(scheme) } override fun onSchemeAdded(scheme: InspectionProfileImpl) { if (scheme.wasInitialized()) { fireProfileChanged(scheme) } } override fun onCurrentSchemeSwitched(oldScheme: InspectionProfileImpl?, newScheme: InspectionProfileImpl?, processChangeSynchronously: Boolean) { project.messageBus.syncPublisher(ProfileChangeAdapter.TOPIC).profileActivated(oldScheme, newScheme) } }, schemeNameToFileName = OLD_NAME_CONVERTER, streamProvider = schemeManagerIprProvider) override fun initializeComponent() { val app = ApplicationManager.getApplication() if (!project.isDirectoryBased || app.isUnitTestMode) { return } runActivity("project inspection profile loading") { schemeManager.loadSchemes() currentProfile.initInspectionTools(project) } StartupManager.getInstance(project).runAfterOpened { project.messageBus.syncPublisher(ProfileChangeAdapter.TOPIC).profilesInitialized() val projectScopeListener = NamedScopesHolder.ScopeListener { for (profile in schemeManager.allSchemes) { profile.scopesChanged() } } scopesManager.addScopeListener(projectScopeListener, project) NamedScopeManager.getInstance(project).addScopeListener(projectScopeListener, project) } } override fun dispose() { val cleanupInspectionProfilesRunnable = { cleanupSchemes(project) (serviceIfCreated<InspectionProfileManager>() as BaseInspectionProfileManager?)?.cleanupSchemes(project) } val app = ApplicationManager.getApplication() if (app.isUnitTestMode || app.isHeadlessEnvironment) { cleanupInspectionProfilesRunnable.invoke() } else { app.executeOnPooledThread(cleanupInspectionProfilesRunnable) } } override fun getStateModificationCount() = state.modificationCount + severityRegistrar.modificationCount + (schemeManagerIprProvider?.modificationCount ?: 0) @TestOnly fun forceLoadSchemes() { LOG.assertTrue(ApplicationManager.getApplication().isUnitTestMode) schemeManager.loadSchemes() } fun isCurrentProfileInitialized() = currentProfile.wasInitialized() override fun schemeRemoved(scheme: InspectionProfileImpl) { scheme.cleanup(project) } @Synchronized override fun getState(): Element? { val result = Element("settings") schemeManagerIprProvider?.writeState(result) serializeObjectInto(state, result) if (result.children.isNotEmpty()) { result.addContent(Element("version").setAttribute("value", VERSION)) } severityRegistrar.writeExternal(result) return wrapState(result, project) } @Synchronized override fun loadState(state: Element) { val data = unwrapState(state, project, schemeManagerIprProvider, schemeManager) val newState = ProjectInspectionProfileManagerState() data?.let { try { severityRegistrar.readExternal(it) } catch (e: Throwable) { LOG.error(e) } it.deserializeInto(newState) } this.state = newState if (data != null && data.getChild("version")?.getAttributeValue("value") != VERSION) { for (o in data.getChildren("option")) { if (o.getAttributeValue("name") == "USE_PROJECT_LEVEL_SETTINGS") { if (o.getAttributeBooleanValue("value") && newState.projectProfile != null) { currentProfile.convert(data, project) } break } } } } override fun getScopesManager() = DependencyValidationManager.getInstance(project) @Synchronized override fun getProfiles(): Collection<InspectionProfileImpl> { currentProfile return schemeManager.allSchemes } val projectProfile: String? get() = state.projectProfile @Synchronized override fun setRootProfile(name: String?) { state.useProjectProfile = name != null if (name != null) { state.projectProfile = name } schemeManager.setCurrentSchemeName(name, true) } @Synchronized fun useApplicationProfile(name: String) { state.useProjectProfile = false // yes, we reuse the same field - useProjectProfile field will be used to distinguish - is it app or project level // to avoid data format change state.projectProfile = name } @Synchronized @TestOnly fun setCurrentProfile(profile: InspectionProfileImpl?) { schemeManager.setCurrent(profile) state.useProjectProfile = profile != null if (profile != null) { state.projectProfile = profile.name } } @Synchronized override fun getCurrentProfile(): InspectionProfileImpl { if (!state.useProjectProfile) { val applicationProfileManager = InspectionProfileManager.getInstance() return (state.projectProfile?.let { applicationProfileManager.getProfile(it, false) } ?: applicationProfileManager.currentProfile) } var currentScheme = state.projectProfile?.let { schemeManager.findSchemeByName(it) } if (currentScheme == null) { currentScheme = schemeManager.allSchemes.firstOrNull() if (currentScheme == null) { currentScheme = InspectionProfileImpl(PROJECT_DEFAULT_PROFILE_NAME, InspectionToolRegistrar.getInstance(), this) currentScheme.copyFrom(InspectionProfileManager.getInstance().currentProfile) currentScheme.isProjectLevel = true currentScheme.name = PROJECT_DEFAULT_PROFILE_NAME schemeManager.addScheme(currentScheme) } schemeManager.setCurrent(currentScheme, false) } return currentScheme } @Synchronized override fun getProfile(name: String, returnRootProfileIfNamedIsAbsent: Boolean): InspectionProfileImpl? { val profile = schemeManager.findSchemeByName(name) return profile ?: InspectionProfileManager.getInstance().getProfile(name, returnRootProfileIfNamedIsAbsent) } fun fireProfileChanged() { fireProfileChanged(currentProfile) } override fun fireProfileChanged(profile: InspectionProfileImpl) { profile.profileChanged() project.messageBus.syncPublisher(ProfileChangeAdapter.TOPIC).profileChanged(profile) } } private class ProjectInspectionProfileManagerState : BaseState() { @get:OptionTag("PROJECT_PROFILE") var projectProfile by string(PROJECT_DEFAULT_PROFILE_NAME) @get:OptionTag("USE_PROJECT_PROFILE") var useProjectProfile by property(true) }
apache-2.0
8e6d396f5ee63e8b15929553bf536b08
35.765799
234
0.742568
5.363341
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/completion/testData/injava/mockLib/mockLib/foo/main.kt
1
887
package mockLib.foo public class LibClass { public fun foo() { } companion object { fun classObjectFun() { } public object NestedObject } public class Nested { public val valInNested: Int = 1 public fun funInNested() { } } public val nested: Nested = Nested() } public interface LibInterface { public fun foo() { } } public enum class LibEnum { RED, GREEN, BLUE } public object LibObject public fun topLevelFunction(): String = "" public fun String.topLevelExtFunction(): String = "" public var topLevelVar: String = "" class F() { companion object { class F { companion object { object F { } } } } } interface MyInterface { fun foo() = 1 } annotation class Anno(val c: Int = 3, val d: String)
apache-2.0
a2fe6c2e54d73a4750214c0ad7f81aaf
14.578947
52
0.559188
4.183962
false
false
false
false
spacecowboy/Feeder
app/src/main/java/com/nononsenseapps/feeder/archmodel/FeedStore.kt
1
4839
package com.nononsenseapps.feeder.archmodel import com.nononsenseapps.feeder.db.room.Feed import com.nononsenseapps.feeder.db.room.FeedDao import com.nononsenseapps.feeder.db.room.FeedTitle import com.nononsenseapps.feeder.db.room.ID_UNSET import com.nononsenseapps.feeder.db.room.upsertFeed import com.nononsenseapps.feeder.model.FeedUnreadCount import com.nononsenseapps.feeder.ui.compose.navdrawer.DrawerFeed import com.nononsenseapps.feeder.ui.compose.navdrawer.DrawerItemWithUnreadCount import com.nononsenseapps.feeder.ui.compose.navdrawer.DrawerTag import com.nononsenseapps.feeder.ui.compose.navdrawer.DrawerTop import java.net.URL import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.mapLatest import org.kodein.di.DI import org.kodein.di.DIAware import org.kodein.di.instance import org.threeten.bp.Instant class FeedStore(override val di: DI) : DIAware { private val feedDao: FeedDao by instance() // Need only be internally consistent within the composition // this object outlives all compositions private var nextTagUiId: Long = -1000 // But IDs need to be consistent even if tags come and go private val tagUiIds = mutableMapOf<String, Long>() private fun getTagUiId(tag: String): Long { return tagUiIds.getOrPut(tag) { --nextTagUiId } } suspend fun getFeed(feedId: Long): Feed? = feedDao.loadFeed(feedId) suspend fun getFeed(url: URL): Feed? = feedDao.loadFeedWithUrl(url) suspend fun saveFeed(feed: Feed): Long { return if (feed.id > ID_UNSET) { feedDao.updateFeed(feed) feed.id } else { feedDao.insertFeed(feed) } } suspend fun getDisplayTitle(feedId: Long): String? = feedDao.getFeedTitle(feedId)?.displayTitle suspend fun deleteFeeds(feedIds: List<Long>) { feedDao.deleteFeeds(feedIds) } val allTags: Flow<List<String>> = feedDao.loadAllTags() @OptIn(ExperimentalCoroutinesApi::class) val drawerItemsWithUnreadCounts: Flow<List<DrawerItemWithUnreadCount>> = feedDao.loadFlowOfFeedsWithUnreadCounts() .mapLatest { feeds -> mapFeedsToSortedDrawerItems(feeds) } private fun mapFeedsToSortedDrawerItems( feeds: List<FeedUnreadCount>, ): List<DrawerItemWithUnreadCount> { var topTag = DrawerTop(unreadCount = 0, totalChildren = 0) val tags: MutableMap<String, DrawerTag> = mutableMapOf() val data: MutableList<DrawerItemWithUnreadCount> = mutableListOf() for (feedDbo in feeds) { val feed = DrawerFeed( unreadCount = feedDbo.unreadCount, tag = feedDbo.tag, id = feedDbo.id, displayTitle = feedDbo.displayTitle, imageUrl = feedDbo.imageUrl, ) data.add(feed) topTag = topTag.copy( unreadCount = topTag.unreadCount + feed.unreadCount, totalChildren = topTag.totalChildren + 1, ) if (feed.tag.isNotEmpty()) { val tag = tags[feed.tag] ?: DrawerTag( tag = feed.tag, unreadCount = 0, uiId = getTagUiId(feed.tag), totalChildren = 0, ) tags[feed.tag] = tag.copy( unreadCount = tag.unreadCount + feed.unreadCount, totalChildren = tag.totalChildren + 1, ) } } data.add(topTag) data.addAll(tags.values) return data.sorted() } fun getFeedTitles(feedId: Long, tag: String): Flow<List<FeedTitle>> = when { feedId > ID_UNSET -> feedDao.getFeedTitlesWithId(feedId) tag.isNotBlank() -> feedDao.getFeedTitlesWithTag(tag) else -> feedDao.getAllFeedTitles() } fun getCurrentlySyncingLatestTimestamp(): Flow<Instant?> = feedDao.getCurrentlySyncingLatestTimestamp() suspend fun setCurrentlySyncingOn(feedId: Long, syncing: Boolean, lastSync: Instant? = null) { if (lastSync != null) { feedDao.setCurrentlySyncingOn(feedId = feedId, syncing = syncing, lastSync = lastSync) } else { feedDao.setCurrentlySyncingOn(feedId = feedId, syncing = syncing) } } suspend fun upsertFeed(feedSql: Feed) = feedDao.upsertFeed(feed = feedSql) suspend fun getFeedsOrderedByUrl(): List<Feed> { return feedDao.getFeedsOrderedByUrl() } fun getFlowOfFeedsOrderedByUrl(): Flow<List<Feed>> { return feedDao.getFlowOfFeedsOrderedByUrl() } suspend fun deleteFeed(url: URL) { feedDao.deleteFeedWithUrl(url) } }
gpl-3.0
67a4ff90afe8ffe18fedbec0918f704a
33.319149
98
0.646001
4.336022
false
false
false
false
allotria/intellij-community
plugins/github/src/org/jetbrains/plugins/github/api/data/GHRepositoryOwnerName.kt
3
800
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.api.data import com.fasterxml.jackson.annotation.JsonSubTypes import com.fasterxml.jackson.annotation.JsonTypeInfo @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "__typename", visible = false) @JsonSubTypes( JsonSubTypes.Type(name = "User", value = GHRepositoryOwnerName.User::class), JsonSubTypes.Type(name = "Organization", value = GHRepositoryOwnerName.Organization::class) ) interface GHRepositoryOwnerName { val login: String class User(override val login: String) : GHRepositoryOwnerName class Organization(override val login: String) : GHRepositoryOwnerName }
apache-2.0
23155da33bad5c7400db902bdb63e4af
46.058824
140
0.79125
4.232804
false
false
false
false
allotria/intellij-community
platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/FileNode.kt
2
2422
// 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.analysis.problemsView.toolWindow import com.intellij.icons.AllIcons import com.intellij.ide.projectView.PresentationData import com.intellij.ide.projectView.impl.CompoundIconProvider.findIcon import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil.getLocationRelativeToUserHome import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.util.PsiUtilCore.findFileSystemItem import com.intellij.ui.SimpleTextAttributes.GRAYED_ATTRIBUTES import com.intellij.ui.SimpleTextAttributes.REGULAR_ATTRIBUTES import com.intellij.ui.tree.LeafState import java.util.Objects.hash internal class FileNode(parent: Node, val file: VirtualFile) : Node(parent) { override fun getLeafState() = if (parentDescriptor is Root) LeafState.NEVER else LeafState.DEFAULT override fun getName() = file.presentableName ?: file.name override fun getVirtualFile() = file override fun getDescriptor() = project?.let { OpenFileDescriptor(it, file) } override fun update(project: Project, presentation: PresentationData) { presentation.addText(name, REGULAR_ATTRIBUTES) presentation.setIcon(findIcon(findFileSystemItem(project, file), 0) ?: when (file.isDirectory) { true -> AllIcons.Nodes.Folder else -> AllIcons.FileTypes.Any_type }) if (parentDescriptor !is FileNode) { val url = file.parent?.presentableUrl ?: return presentation.addText(" ${getLocationRelativeToUserHome(url)}", GRAYED_ATTRIBUTES) } val root = findAncestor(Root::class.java) val count = root?.getFileProblemCount(file) ?: 0 if (count > 0) { val text = ProblemsViewBundle.message("problems.view.file.problems", count) presentation.addText(" $text", GRAYED_ATTRIBUTES) } } override fun getChildren(): Collection<Node> { val root = findAncestor(Root::class.java) return root?.getChildren(file) ?: super.getChildren() } override fun hashCode() = hash(project, file) override fun equals(other: Any?): Boolean { if (this === other) return true if (this.javaClass != other?.javaClass) return false val that = other as? FileNode ?: return false return that.project == project && that.file == file } }
apache-2.0
ccf72248336464de2ebbf09b0193ea34
40.758621
140
0.752271
4.241681
false
false
false
false
ParaskP7/sample-code-posts-kotlin
app/src/main/java/io/petros/posts/kotlin/app/Dependencies.kt
1
1853
package io.petros.posts.kotlin.app import android.arch.persistence.room.Room import android.content.Context import com.github.salomonbrys.kodein.Kodein import io.petros.posts.kotlin.R import io.petros.posts.kotlin.activity.posts.fragment.adapter.PostsAdapter import io.petros.posts.kotlin.datastore.db.CommentDao import io.petros.posts.kotlin.datastore.db.PostDao import io.petros.posts.kotlin.datastore.db.PostsDatabase import io.petros.posts.kotlin.datastore.db.UserDao import io.petros.posts.kotlin.service.retrofit.WebService import io.petros.posts.kotlin.util.rx.RxSchedulers import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory fun constructPostsAdapter(kodein: Kodein): PostsAdapter = PostsAdapter(kodein) fun constructRxSchedulers(): RxSchedulers { return RxSchedulers(Schedulers.io(), Schedulers.computation(), Schedulers.trampoline(), AndroidSchedulers.mainThread()) } fun constructWebService(context: Context): WebService { val retrofit = Retrofit.Builder() .baseUrl(context.getString(R.string.posts_url)) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() return retrofit.create(WebService::class.java) } fun constructPostsDatabase(context: Context): PostsDatabase = Room.databaseBuilder(context, PostsDatabase::class.java, "posts.db") .build() fun constructUserDao(postsDatabase: PostsDatabase): UserDao = postsDatabase.userDao() fun constructPostDao(postsDatabase: PostsDatabase): PostDao = postsDatabase.postDao() fun constructCommentDao(postsDatabase: PostsDatabase): CommentDao = postsDatabase.commentDao()
apache-2.0
dde994731d6b4bf4ff192f7dbea75d38
43.119048
130
0.807339
4.279446
false
false
false
false
zdary/intellij-community
platform/platform-impl/src/com/intellij/ide/plugins/CreateAllServicesAndExtensionsAction.kt
1
8025
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.plugins import com.intellij.diagnostic.PluginException import com.intellij.ide.impl.ProjectUtil import com.intellij.ide.plugins.cl.PluginClassLoader import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionNotApplicableException import com.intellij.openapi.extensions.impl.ExtensionPointImpl import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.runModalTask import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.psi.stubs.StubElementTypeHolderEP import com.intellij.serviceContainer.ComponentManagerImpl import io.github.classgraph.AnnotationEnumValue import io.github.classgraph.ClassGraph import io.github.classgraph.ClassInfo import java.util.function.BiConsumer import kotlin.properties.Delegates.notNull @Suppress("HardCodedStringLiteral") private class CreateAllServicesAndExtensionsAction : AnAction("Create All Services And Extensions"), DumbAware { companion object { @JvmStatic fun createAllServicesAndExtensions() { val errors = mutableListOf<Throwable>() runModalTask("Creating All Services And Extensions", cancellable = true) { indicator -> val logger = logger<ComponentManagerImpl>() val taskExecutor: (task: () -> Unit) -> Unit = { task -> try { task() } catch (e: ProcessCanceledException) { throw e } catch (e: Throwable) { logger.error(e) errors.add(e) } } // check first checkExtensionPoint(StubElementTypeHolderEP.EP_NAME.point as ExtensionPointImpl<*>, taskExecutor) checkContainer(ApplicationManager.getApplication() as ComponentManagerImpl, indicator, taskExecutor) ProjectUtil.getOpenProjects().firstOrNull()?.let { checkContainer(it as ComponentManagerImpl, indicator, taskExecutor) } indicator.text2 = "Checking light services..." checkLightServices(taskExecutor) } // some errors are not thrown but logged val message = (if (errors.isEmpty()) "No errors" else "${errors.size} errors were logged") + ". Check also that no logged errors." Notification("Error Report", null, "", message, NotificationType.INFORMATION, null) .notify(null) } } override fun actionPerformed(e: AnActionEvent) { createAllServicesAndExtensions() } } @Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") private val badServices = java.util.Set.of( "com.intellij.usageView.impl.UsageViewContentManagerImpl", "com.jetbrains.python.scientific.figures.PyPlotToolWindow", "org.jetbrains.plugins.grails.runner.GrailsConsole", "com.intellij.analysis.pwa.analyser.PwaServiceImpl", "com.intellij.analysis.pwa.view.toolwindow.PwaProblemsViewImpl", ) @Suppress("HardCodedStringLiteral") private fun checkContainer(container: ComponentManagerImpl, indicator: ProgressIndicator, taskExecutor: (task: () -> Unit) -> Unit) { indicator.text2 = "Checking ${container.activityNamePrefix()}services..." ComponentManagerImpl.createAllServices(container, badServices) indicator.text2 = "Checking ${container.activityNamePrefix()}extensions..." container.extensionArea.processExtensionPoints { extensionPoint -> // requires read action if (extensionPoint.name == "com.intellij.favoritesListProvider" || extensionPoint.name == "com.intellij.favoritesListProvider") { return@processExtensionPoints } checkExtensionPoint(extensionPoint, taskExecutor) } } private fun checkExtensionPoint(extensionPoint: ExtensionPointImpl<*>, taskExecutor: (task: () -> Unit) -> Unit) { extensionPoint.processImplementations(false, BiConsumer { supplier, pluginDescriptor -> var extensionClass: Class<out Any> by notNull() taskExecutor { extensionClass = extensionPoint.extensionClass } taskExecutor { try { val extension = supplier.get() ?: return@taskExecutor if (!extensionClass.isInstance(extension)) { throw PluginException("Extension ${extension.javaClass.name} does not implement $extensionClass", pluginDescriptor.pluginId) } } catch (ignore: ExtensionNotApplicableException) { } } }) taskExecutor { extensionPoint.extensionList } } private fun checkLightServices(taskExecutor: (task: () -> Unit) -> Unit) { for (plugin in PluginManagerCore.getLoadedPlugins(null)) { // we don't check classloader for sub descriptors because url set is the same if (plugin.classLoader !is PluginClassLoader || plugin.pluginDependencies == null) { continue } ClassGraph() .enableAnnotationInfo() .ignoreParentClassLoaders() .overrideClassLoaders(plugin.classLoader) .scan() .use { scanResult -> val lightServices = scanResult.getClassesWithAnnotation(Service::class.java.name) for (lightService in lightServices) { // not clear - from what classloader light service will be loaded in reality val lightServiceClass = loadLightServiceClass(lightService, plugin) val isProjectLevel: Boolean val isAppLevel: Boolean val annotationParameterValue = lightService.getAnnotationInfo(Service::class.java.name).parameterValues.find { it.name == "value" } if (annotationParameterValue == null) { isAppLevel = lightServiceClass.declaredConstructors.any { it.parameterCount == 0 } isProjectLevel = lightServiceClass.declaredConstructors.any { it.parameterCount == 1 && it.parameterTypes.get(0) == Project::class.java } } else { val list = annotationParameterValue.value as Array<*> isAppLevel = list.any { v -> (v as AnnotationEnumValue).valueName == Service.Level.APP.name } isProjectLevel = list.any { v -> (v as AnnotationEnumValue).valueName == Service.Level.PROJECT.name } } if (isAppLevel) { taskExecutor { ApplicationManager.getApplication().getService(lightServiceClass) } } if (isProjectLevel) { taskExecutor { ProjectUtil.getOpenProjects().firstOrNull()?.getService(lightServiceClass) } } } } } } private fun loadLightServiceClass(lightService: ClassInfo, mainDescriptor: IdeaPluginDescriptorImpl): Class<*> { // for (pluginDependency in mainDescriptor.pluginDependencies!!) { val subPluginClassLoader = pluginDependency.subDescriptor?.classLoader as? PluginClassLoader ?: continue val packagePrefix = subPluginClassLoader.packagePrefix ?: continue if (lightService.name.startsWith(packagePrefix)) { return subPluginClassLoader.loadClass(lightService.name, true) } } for (pluginDependency in mainDescriptor.pluginDependencies!!) { val subPluginClassLoader = pluginDependency.subDescriptor?.classLoader as? PluginClassLoader ?: continue val clazz = subPluginClassLoader.loadClass(lightService.name, true) if (clazz != null && clazz.classLoader === subPluginClassLoader) { // light class is resolved from this sub plugin classloader - check successful return clazz } } // ok, or no plugin dependencies at all, or all are disabled, resolve from main return (mainDescriptor.classLoader as PluginClassLoader).loadClass(lightService.name, true) }
apache-2.0
727757aa75f1c09a0418ed8c8558b779
41.242105
149
0.720997
5.114723
false
false
false
false
VREMSoftwareDevelopment/WiFiAnalyzer
app/src/test/kotlin/com/vrem/wifianalyzer/wifi/model/WiFiConnectionTest.kt
1
2736
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.vrem.wifianalyzer.wifi.model import com.vrem.util.EMPTY import org.junit.Assert.* import org.junit.Test class WiFiConnectionTest { private val ipAddress = "21.205.91.7" private val linkSpeed = 21 private val wiFiIdentifier = WiFiIdentifier("SSID-123", "BSSID-123") private val fixture: WiFiConnection = WiFiConnection(wiFiIdentifier, ipAddress, linkSpeed) @Test fun testWiFiConnectionEmpty() { // validate assertEquals(WiFiIdentifier.EMPTY, WiFiConnection.EMPTY.wiFiIdentifier) assertEquals(String.EMPTY, WiFiConnection.EMPTY.ipAddress) assertEquals(WiFiConnection.LINK_SPEED_INVALID, WiFiConnection.EMPTY.linkSpeed) assertFalse(WiFiConnection.EMPTY.connected) } @Test fun testWiFiConnection() { // validate assertEquals(wiFiIdentifier, fixture.wiFiIdentifier) assertEquals(ipAddress, fixture.ipAddress) assertEquals(linkSpeed, fixture.linkSpeed) assertTrue(fixture.connected) } @Test fun testEquals() { // setup val wiFiIdentifier = WiFiIdentifier("SSID-123", "BSSID-123") val other = WiFiConnection(wiFiIdentifier, String.EMPTY, WiFiConnection.LINK_SPEED_INVALID) // execute & validate assertEquals(fixture, other) assertNotSame(fixture, other) } @Test fun testHashCode() { // setup val wiFiIdentifier = WiFiIdentifier("SSID-123", "BSSID-123") val other = WiFiConnection(wiFiIdentifier, String.EMPTY, WiFiConnection.LINK_SPEED_INVALID) // execute & validate assertEquals(fixture.hashCode(), other.hashCode()) } @Test fun testCompareTo() { // setup val wiFiIdentifier = WiFiIdentifier("SSID-123", "BSSID-123") val other = WiFiConnection(wiFiIdentifier, String.EMPTY, WiFiConnection.LINK_SPEED_INVALID) // execute & validate assertEquals(0, fixture.compareTo(other)) } }
gpl-3.0
7ccbbcbf655f572f5139f697cd48beb9
35.013158
99
0.700292
4.391653
false
true
false
false
leafclick/intellij-community
platform/vcs-log/graph/src/com/intellij/vcs/log/graph/utils/BfsUtil.kt
1
1662
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.vcs.log.graph.utils import com.intellij.util.containers.ContainerUtil import com.intellij.vcs.log.graph.api.LiteLinearGraph import com.intellij.vcs.log.graph.utils.impl.BitSetFlags class BfsWalk(val start: Int, private val graph: LiteLinearGraph, private val visited: Flags) { constructor(start: Int, graph: LiteLinearGraph) : this(start, graph, BitSetFlags(graph.nodesCount())) private val queue = ContainerUtil.newLinkedList(start) fun isFinished() = queue.isEmpty() fun currentNodes(): List<Int> = queue fun step(consumer: (Int) -> Boolean = { true }): List<Int> { while (!queue.isEmpty()) { val node = queue.poll() if (!visited.get(node)) { visited.set(node, true) if (!consumer(node)) return emptyList() val next = graph.getNodes(node, LiteLinearGraph.NodeFilter.DOWN).sorted() queue.addAll(next) return next } } return emptyList() } fun walk(consumer: (Int) -> Boolean = { true }) { while (!isFinished()) { step(consumer) } } }
apache-2.0
6c5998f9b3f3a9497fe4007a2a312314
32.26
103
0.695548
3.947743
false
false
false
false
faceofcat/Tesla-Core-Lib
src/main/kotlin/net/modcrafters/mclib/ingredients/implementations/BaseItemIngredient.kt
1
2028
package net.modcrafters.mclib.ingredients.implementations import net.minecraftforge.fluids.capability.CapabilityFluidHandler import net.modcrafters.mclib.ingredients.IFluidIngredient import net.modcrafters.mclib.ingredients.IItemIngredient import net.modcrafters.mclib.ingredients.IMachineIngredient import net.modcrafters.mclib.ingredients.IngredientAmountMatch abstract class BaseItemIngredient : IItemIngredient { override fun isMatch(ingredient: IMachineIngredient, amountMatch: IngredientAmountMatch) = when (ingredient) { is IItemIngredient -> this.isMatchItem(ingredient, amountMatch) is IFluidIngredient -> this.isMatchFluid(ingredient, amountMatch) else -> false } protected open fun isMatchItem(ingredient: IItemIngredient, amountMatch: IngredientAmountMatch) = this.itemStacks.any { mine -> ingredient.itemStacks.any { other -> mine.isItemEqual(other) && amountMatch.compare(mine.count, other.count) } } protected open fun isMatchFluid(ingredient: IFluidIngredient, amountMatch: IngredientAmountMatch) = this.itemStacks.let { if ((it.size == 1) && it[0].hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { val cap = it[0].getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null) if (cap != null) { val fluid = cap.drain(ingredient.fluidStack, false) when (amountMatch) { IngredientAmountMatch.EXACT -> { fluid?.amount == ingredient.fluidStack.amount } IngredientAmountMatch.BE_ENOUGH -> { fluid?.amount == ingredient.fluidStack.amount } IngredientAmountMatch.IGNORE_SIZE -> { (fluid?.amount ?: 0) > 0 } } } else false } else false } }
mit
96c62dbc94be576abbd4b9452ff43355
44.066667
125
0.63215
4.863309
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/inference/graph/InferenceUnitGraphBuilder.kt
13
2593
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.intentions.style.inference.graph import com.intellij.psi.PsiType class InferenceUnitGraphBuilder { private val relations: MutableList<Pair<InferenceUnit, InferenceUnit>> = mutableListOf() private val registered: MutableSet<InferenceUnit> = mutableSetOf() private val fixedInstantiations: MutableMap<InferenceUnit, PsiType> = mutableMapOf() private val directUnits: MutableSet<InferenceUnit> = mutableSetOf() /** * Creates a relation between units (left is a supertype of right) */ fun addRelation(left: InferenceUnit, right: InferenceUnit): InferenceUnitGraphBuilder { register(left) register(right) relations.add(left to right) return this } fun register(unit: InferenceUnit): InferenceUnitGraphBuilder { registered.add(unit) return this } fun register(unitNode: InferenceUnitNode): InferenceUnitGraphBuilder { if (unitNode.direct) { setDirect(unitNode.core) } setType(unitNode.core, unitNode.typeInstantiation) return this } fun setDirect(unit: InferenceUnit): InferenceUnitGraphBuilder { register(unit) directUnits.add(unit) return this } fun setType(unit: InferenceUnit, type: PsiType): InferenceUnitGraphBuilder { register(unit) fixedInstantiations[unit] = type return this } fun build(): InferenceUnitGraph { val inferenceNodes = ArrayList<InferenceUnitNode>() val superTypesMap = mutableListOf<MutableSet<() -> InferenceUnitNode>>() val subTypesMap = mutableListOf<MutableSet<() -> InferenceUnitNode>>() val registeredUnits = registered.sortedBy { it.initialTypeParameter.name } repeat(registeredUnits.size) { superTypesMap.add(mutableSetOf()) subTypesMap.add(mutableSetOf()) } val unitIndexMap = registeredUnits.zip(registeredUnits.indices).toMap() for ((left, right) in relations) { subTypesMap[unitIndexMap.getValue(left)].add { inferenceNodes[unitIndexMap.getValue(right)] } superTypesMap[unitIndexMap.getValue(right)].add { inferenceNodes[unitIndexMap.getValue(left)] } } for ((unit, index) in unitIndexMap) { inferenceNodes.add(InferenceUnitNode(unit, superTypesMap[index], subTypesMap[index], fixedInstantiations[unit] ?: PsiType.NULL, direct = unit in directUnits)) } return InferenceUnitGraph(inferenceNodes) } }
apache-2.0
3e3df9843e4c0cd46c4f27a1e5dbf945
34.534247
140
0.715002
4.440068
false
false
false
false
ianhanniballake/muzei
main/src/main/java/com/google/android/apps/muzei/wearable/WearableController.kt
1
3800
/* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.muzei.wearable import android.content.Context import android.graphics.Bitmap import android.util.Log import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import com.google.android.apps.muzei.render.ImageLoader import com.google.android.apps.muzei.room.Artwork import com.google.android.apps.muzei.room.MuzeiDatabase import com.google.android.apps.muzei.util.launchWhenStartedIn import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.GoogleApiAvailability import com.google.android.gms.common.api.AvailabilityException import com.google.android.gms.wearable.Asset import com.google.android.gms.wearable.PutDataMapRequest import com.google.android.gms.wearable.Wearable import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.tasks.await import kotlinx.coroutines.withContext import java.io.ByteArrayOutputStream /** * Controller for updating Android Wear devices with new wallpapers. */ class WearableController(private val context: Context) : DefaultLifecycleObserver { companion object { private const val TAG = "WearableController" } override fun onCreate(owner: LifecycleOwner) { // Update Android Wear whenever the artwork changes val database = MuzeiDatabase.getInstance(context) database.artworkDao().currentArtwork.filterNotNull().onEach { artwork -> updateArtwork(artwork) }.launchWhenStartedIn(owner) } private suspend fun updateArtwork(artwork: Artwork) = withContext(NonCancellable) { if (ConnectionResult.SUCCESS != GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context)) { return@withContext } val dataClient = Wearable.getDataClient(context) try { GoogleApiAvailability.getInstance().checkApiAvailability(dataClient).await() } catch (e: AvailabilityException) { val connectionResult = e.getConnectionResult(dataClient) if (connectionResult.errorCode != ConnectionResult.API_UNAVAILABLE) { Log.w(TAG, "onConnectionFailed: $connectionResult", e.cause) } return@withContext } catch (e: Exception) { Log.w(TAG, "Unable to check for Wear API availability", e) return@withContext } val image: Bitmap = ImageLoader.decode( context.contentResolver, artwork.contentUri, 320) ?: return@withContext val byteStream = ByteArrayOutputStream() image.compress(Bitmap.CompressFormat.PNG, 100, byteStream) val asset = Asset.createFromBytes(byteStream.toByteArray()) val dataMapRequest = PutDataMapRequest.create("/artwork").apply { dataMap.putDataMap("artwork", artwork.toDataMap()) dataMap.putAsset("image", asset) } try { dataClient.putDataItem(dataMapRequest.asPutDataRequest().setUrgent()).await() } catch (e: Exception) { Log.w(TAG, "Error uploading artwork to Wear", e) } } }
apache-2.0
626b58282aa1c79731b4037f3ce09718
39.860215
117
0.721579
4.71464
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/inspections/dfa/NothingType.kt
9
238
// WITH_STDLIB fun test(x : Int) { if (x > 5) { fail(x) } if (<warning descr="Condition 'x == 10' is always false">x == 10</warning>) {} } fun fail(value: Int) : Nothing { throw RuntimeException("Oops: ${value}") }
apache-2.0
1015d418adfa0464427a8ac02a8c7112
22.9
82
0.55042
3.173333
false
true
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertPropertyToFunctionIntention.kt
2
11344
// 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.intentions import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.* import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.refactoring.util.RefactoringUIUtil import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress import org.jetbrains.kotlin.idea.refactoring.* import org.jetbrains.kotlin.idea.references.KtReference import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.hasJvmFieldAnnotation import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.resolve.calls.util.getCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.utils.findFunction class ConvertPropertyToFunctionIntention : SelfTargetingIntention<KtProperty>( KtProperty::class.java, KotlinBundle.lazyMessage("convert.property.to.function") ), LowPriorityAction { private inner class Converter( project: Project, editor: Editor?, descriptor: CallableDescriptor ) : CallableRefactoring<CallableDescriptor>(project, editor, descriptor, text) { private val newName: String = JvmAbi.getterName(callableDescriptor.name.asString()) private fun convertProperty(originalProperty: KtProperty, psiFactory: KtPsiFactory) { val property = originalProperty.copy() as KtProperty val getter = property.getter val sampleFunction = psiFactory.createFunction("fun foo() {\n\n}") property.valOrVarKeyword.replace(sampleFunction.funKeyword!!) property.addAfter(psiFactory.createParameterList("()"), property.nameIdentifier) if (property.initializer == null) { if (getter != null) { val dropGetterTo = (getter.equalsToken ?: getter.bodyExpression) ?.siblings(forward = false, withItself = false) ?.firstOrNull { it !is PsiWhiteSpace } getter.deleteChildRange(getter.firstChild, dropGetterTo) val dropPropertyFrom = getter .siblings(forward = false, withItself = false) .first { it !is PsiWhiteSpace } .nextSibling property.deleteChildRange(dropPropertyFrom, getter.prevSibling) val typeReference = property.typeReference if (typeReference != null) { property.addAfter(psiFactory.createWhiteSpace(), typeReference) } } } property.setName(newName) property.annotationEntries.forEach { if (it.useSiteTarget != null) { it.replace(psiFactory.createAnnotationEntry("@${it.shortName}${it.valueArgumentList?.text ?: ""}")) } } originalProperty.replace(psiFactory.createFunction(property.text)) } override fun performRefactoring(descriptorsForChange: Collection<CallableDescriptor>) { val propertyName = callableDescriptor.name.asString() val nameChanged = propertyName != newName val getterName = JvmAbi.getterName(callableDescriptor.name.asString()) val conflicts = MultiMap<PsiElement, String>() val callables = getAffectedCallables(project, descriptorsForChange) val kotlinRefsToReplaceWithCall = ArrayList<KtSimpleNameExpression>() val refsToRename = ArrayList<PsiReference>() val javaRefsToReplaceWithCall = ArrayList<PsiReferenceExpression>() project.runSynchronouslyWithProgress(KotlinBundle.message("looking.for.usages.and.conflicts"), true) { runReadAction { val progressIndicator = ProgressManager.getInstance().progressIndicator progressIndicator.isIndeterminate = false val progressStep = 1.0 / callables.size for ((i, callable) in callables.withIndex()) { progressIndicator.fraction = (i + 1) * progressStep if (callable !is PsiNamedElement) continue if (!checkModifiable(callable)) { val renderedCallable = RefactoringUIUtil.getDescription(callable, true).capitalize() conflicts.putValue(callable, KotlinBundle.message("can.t.modify.0", renderedCallable)) } if (callable is KtParameter) { conflicts.putValue( callable, if (callable.hasActualModifier()) KotlinBundle.message("property.has.an.actual.declaration.in.the.class.constructor") else KotlinBundle.message("property.overloaded.in.child.class.constructor") ) } if (callable is KtProperty) { callableDescriptor.getContainingScope() ?.findFunction(callableDescriptor.name, NoLookupLocation.FROM_IDE) { it.valueParameters.isEmpty() } ?.takeIf { it.receiverType() == callableDescriptor.receiverType() } ?.let { DescriptorToSourceUtilsIde.getAnyDeclaration(project, it) } ?.let { reportDeclarationConflict(conflicts, it) { s -> KotlinBundle.message("0.already.exists", s) } } } else if (callable is PsiMethod) callable.checkDeclarationConflict(propertyName, conflicts, callables) val usages = ReferencesSearch.search(callable) for (usage in usages) { if (usage is KtReference) { if (usage is KtSimpleNameReference) { val expression = usage.expression if (expression.getCall(expression.analyze(BodyResolveMode.PARTIAL)) != null && expression.getStrictParentOfType<KtCallableReferenceExpression>() == null ) { kotlinRefsToReplaceWithCall.add(expression) } else if (nameChanged) { refsToRename.add(usage) } } else { val refElement = usage.element conflicts.putValue( refElement, KotlinBundle.message( "unrecognized.reference.will.be.skipped.0", StringUtil.htmlEmphasize(refElement.text) ) ) } continue } val refElement = usage.element if (refElement.text.endsWith(getterName)) continue if (usage is PsiJavaReference) { if (usage.resolve() is PsiField && usage is PsiReferenceExpression) { javaRefsToReplaceWithCall.add(usage) } continue } conflicts.putValue( refElement, KotlinBundle.message( "can.t.replace.foreign.reference.with.call.expression.0", StringUtil.htmlEmphasize(refElement.text) ) ) } } } } project.checkConflictsInteractively(conflicts) { project.executeWriteCommand(text) { val kotlinPsiFactory = KtPsiFactory(project) val javaPsiFactory = PsiElementFactory.getInstance(project) val newKotlinCallExpr = kotlinPsiFactory.createExpression("$newName()") kotlinRefsToReplaceWithCall.forEach { it.replace(newKotlinCallExpr) } refsToRename.forEach { it.handleElementRename(newName) } javaRefsToReplaceWithCall.forEach { val getterRef = it.handleElementRename(newName) getterRef.replace(javaPsiFactory.createExpressionFromText("${getterRef.text}()", null)) } callables.forEach { when (it) { is KtProperty -> convertProperty(it, kotlinPsiFactory) is PsiMethod -> it.name = newName } } } } } } override fun startInWriteAction(): Boolean = false override fun isApplicableTo(element: KtProperty, caretOffset: Int): Boolean { val identifier = element.nameIdentifier ?: return false if (!identifier.textRange.containsOffset(caretOffset)) return false return element.delegate == null && !element.isVar && !element.isLocal && (element.initializer == null || element.getter == null) && !element.hasJvmFieldAnnotation() && !element.hasModifier(KtTokens.CONST_KEYWORD) } override fun applyTo(element: KtProperty, editor: Editor?) { val descriptor = element.resolveToDescriptorIfAny(BodyResolveMode.FULL) as? CallableDescriptor ?: return Converter(element.project, editor, descriptor).run() } }
apache-2.0
a21625b805a3db7e0917b54e0d8defc7
51.762791
158
0.580483
6.22271
false
false
false
false
FuturemanGaming/FutureBot-Discord
src/main/kotlin/com/futuremangaming/futurebot/music/display/DisplaySymbol.kt
1
1266
/* * Copyright 2014-2017 FuturemanGaming * * 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.futuremangaming.futurebot.music.display // WHY NOT USE AN ENUM?? CONVERSION IS ANNOYING!! object DisplaySymbol { const val PLAY_PAUSE = "\u23EF" const val PAUSE = "\u23F8" const val PLAY = "\u25B6" const val NOTE = "\uD83C\uDFA7" const val SKIP = "\u23ed" const val SHUFFLE = "\ud83d\udd00" const val MUTED = "\ud83d\udd07" const val VOLUME_LOW = "\ud83d\udd08" const val VOLUME_DOWN = "\ud83d\udd09" const val VOLUME_UP = "\ud83d\udd0A" const val PLAY_BAR = "\u25ac" const val PLAY_POS = "\ud83d\udd18" const val REFRESH = "\uD83d\uDD18" }
apache-2.0
4bb049d37d1c75f3abf01eaa53906ef2
36.235294
75
0.665877
3.385027
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/models/user/Stats.kt
1
4373
package com.habitrpg.android.habitica.models.user import android.content.Context import com.google.gson.annotations.SerializedName import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.models.HabitRpgClass import io.realm.RealmObject import io.realm.annotations.PrimaryKey open class Stats : RealmObject() { @PrimaryKey var userId: String? = null set(userId) { field = userId if (buffs?.isManaged == false) { buffs?.userId = userId } if (training?.isManaged == false) { training?.userId = userId } } internal var user: User? = null @SerializedName("con") var constitution: Int? = null @SerializedName("str") var strength: Int? = null @SerializedName("per") var per: Int? = null @SerializedName("int") var intelligence: Int? = null var training: Training? = null var buffs: Buffs? = null var points: Int? = null var lvl: Int? = null @SerializedName("class") var habitClass: String? = null var gp: Double? = null var exp: Double? = null var mp: Double? = null var hp: Double? = null var toNextLevel: Int? = null get() = if (field != null) field else 0 set(value) { if (value != 0) { field = value } } var maxHealth: Int? = null get() = if (field != null) field else 0 set(value) { if (value != 0) { field = value } } var maxMP: Int? = null get() = if (field != null) field else 0 set(value) { if (value != 0) { field = value } } val isBuffed: Boolean get() { return buffs?.str ?: 0f > 0 || buffs?.con ?: 0f > 0 || buffs?._int ?: 0f > 0 || buffs?.per ?: 0f > 0 } fun getTranslatedClassName(context: Context): String { return when (habitClass) { HEALER -> context.getString(R.string.healer) ROGUE -> context.getString(R.string.rogue) WARRIOR -> context.getString(R.string.warrior) MAGE -> context.getString(R.string.mage) else -> context.getString(R.string.warrior) } } fun merge(stats: Stats?) { if (stats == null) { return } this.constitution = if (stats.constitution != null) stats.constitution else this.constitution this.strength = if (stats.strength != null) stats.strength else this.strength this.per = if (stats.per != null) stats.per else this.per this.intelligence = if (stats.intelligence != null) stats.intelligence else this.intelligence this.training?.merge(stats.training) this.buffs?.merge(stats.buffs) this.points = if (stats.points != null) stats.points else this.points this.lvl = if (stats.lvl != null) stats.lvl else this.lvl this.habitClass = if (stats.habitClass != null) stats.habitClass else this.habitClass this.gp = if (stats.gp != null) stats.gp else this.gp this.exp = if (stats.exp != null) stats.exp else this.exp this.hp = if (stats.hp != null) stats.hp else this.hp this.mp = if (stats.mp != null) stats.mp else this.mp this.toNextLevel = if (stats.toNextLevel != null) stats.toNextLevel else this.toNextLevel this.maxHealth = if (stats.maxHealth != null) stats.maxHealth else this.maxHealth this.maxMP = if (stats.maxMP != null) stats.maxMP else this.maxMP } fun setHabitClass(habitRpgClass: HabitRpgClass) { habitClass = habitRpgClass.toString() } companion object { const val STRENGTH = "str" const val INTELLIGENCE = "int" const val CONSTITUTION = "con" const val PERCEPTION = "per" const val WARRIOR = "warrior" const val MAGE = "wizard" const val HEALER = "healer" const val ROGUE = "rogue" const val AUTO_ALLOCATE_FLAT = "flat" const val AUTO_ALLOCATE_CLASSBASED = "classbased" const val AUTO_ALLOCATE_TASKBASED = "taskbased" } }
gpl-3.0
57b15f3ec4bf3d4afdb098d3657754ed
32.984
101
0.560713
4.079291
false
false
false
false
devjn/GithubSearch
ios/src/main/kotlin/com/github/devjn/githubsearch/db/SQLiteCursor.kt
1
1692
package com.github.devjn.githubsearch.db import com.github.devjn.githubsearch.database.ISQLiteCursor import org.sqlite.c.Globals class SQLiteCursor(private var stmt: SQLiteStatement?) : ISQLiteCursor { override var isAfterLast = false init { moveToNext() } override fun moveToFirst() { if (stmt == null) { throw RuntimeException("statement is closed") } stmt!!.reset() moveToNext() } override fun close() { if (stmt == null) { throw RuntimeException("statement is closed") } stmt = null } override fun getString(i: Int): String { if (stmt == null) { throw RuntimeException("statement is closed") } return Globals.sqlite3_column_text(stmt!!.stmtHandle, i) } override fun getInt(i: Int): Int { if (stmt == null) { throw RuntimeException("statement is closed") } return Globals.sqlite3_column_int(stmt!!.stmtHandle, i) } override fun getLong(i: Int): Long { if (stmt == null) { throw RuntimeException("statement is closed") } return Globals.sqlite3_column_int64(stmt!!.stmtHandle, i) } override fun getDouble(i: Int): Double { if (stmt == null) { throw RuntimeException("statement is closed") } return Globals.sqlite3_column_double(stmt!!.stmtHandle, i) } override fun moveToNext() { if (stmt == null) { throw RuntimeException("statement is closed") } isAfterLast = !stmt!!.step() } }
apache-2.0
950d798a0cc51681785f80896d61db1b
24.46875
72
0.55792
4.5
false
false
false
false
kohesive/kohesive-iac
model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/clients/DeferredAmazonCodeDeploy.kt
1
2528
package uy.kohesive.iac.model.aws.clients import com.amazonaws.services.codedeploy.AbstractAmazonCodeDeploy import com.amazonaws.services.codedeploy.AmazonCodeDeploy import com.amazonaws.services.codedeploy.model.* import uy.kohesive.iac.model.aws.IacContext import uy.kohesive.iac.model.aws.proxy.makeProxy open class BaseDeferredAmazonCodeDeploy(val context: IacContext) : AbstractAmazonCodeDeploy(), AmazonCodeDeploy { override fun addTagsToOnPremisesInstances(request: AddTagsToOnPremisesInstancesRequest): AddTagsToOnPremisesInstancesResult { return with (context) { request.registerWithAutoName() AddTagsToOnPremisesInstancesResult().registerWithSameNameAs(request) } } override fun createApplication(request: CreateApplicationRequest): CreateApplicationResult { return with (context) { request.registerWithAutoName() makeProxy<CreateApplicationRequest, CreateApplicationResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } override fun createDeployment(request: CreateDeploymentRequest): CreateDeploymentResult { return with (context) { request.registerWithAutoName() makeProxy<CreateDeploymentRequest, CreateDeploymentResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } override fun createDeploymentConfig(request: CreateDeploymentConfigRequest): CreateDeploymentConfigResult { return with (context) { request.registerWithAutoName() makeProxy<CreateDeploymentConfigRequest, CreateDeploymentConfigResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } override fun createDeploymentGroup(request: CreateDeploymentGroupRequest): CreateDeploymentGroupResult { return with (context) { request.registerWithAutoName() makeProxy<CreateDeploymentGroupRequest, CreateDeploymentGroupResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } } class DeferredAmazonCodeDeploy(context: IacContext) : BaseDeferredAmazonCodeDeploy(context)
mit
332865325ea7af71b02276fd6601d60b
37.892308
129
0.670095
5.906542
false
true
false
false
ncoe/rosetta
Latin_Squares_in_reduced_form/Kotlin/src/Latin.kt
1
3150
typealias Matrix = MutableList<MutableList<Int>> fun dList(n: Int, sp: Int): Matrix { val start = sp - 1 // use 0 basing val a = generateSequence(0) { it + 1 }.take(n).toMutableList() a[start] = a[0].also { a[0] = a[start] } a.subList(1, a.size).sort() val first = a[1] // recursive closure permutes a[1:] val r = mutableListOf<MutableList<Int>>() fun recurse(last: Int) { if (last == first) { // bottom of recursion. you get here once for each permutation. // test if permutation is deranged for (jv in a.subList(1, a.size).withIndex()) { if (jv.index + 1 == jv.value) { return // no, ignore it } } // yes, save a copy with 1 based indexing val b = a.map { it + 1 } r.add(b.toMutableList()) return } for (i in last.downTo(1)) { a[i] = a[last].also { a[last] = a[i] } recurse(last - 1) a[i] = a[last].also { a[last] = a[i] } } } recurse(n - 1) return r } fun reducedLatinSquares(n: Int, echo: Boolean): Long { if (n <= 0) { if (echo) { println("[]\n") } return 0 } else if (n == 1) { if (echo) { println("[1]\n") } return 1 } val rlatin = MutableList(n) { MutableList(n) { it } } // first row for (j in 0 until n) { rlatin[0][j] = j + 1 } var count = 0L fun recurse(i: Int) { val rows = dList(n, i) outer@ for (r in 0 until rows.size) { rlatin[i - 1] = rows[r].toMutableList() for (k in 0 until i - 1) { for (j in 1 until n) { if (rlatin[k][j] == rlatin[i - 1][j]) { if (r < rows.size - 1) { continue@outer } if (i > 2) { return } } } } if (i < n) { recurse(i + 1) } else { count++ if (echo) { printSquare(rlatin) } } } } // remaining rows recurse(2) return count } fun printSquare(latin: Matrix) { for (row in latin) { println(row) } println() } fun factorial(n: Long): Long { if (n == 0L) { return 1 } var prod = 1L for (i in 2..n) { prod *= i } return prod } fun main() { println("The four reduced latin squares of order 4 are:\n") reducedLatinSquares(4, true) println("The size of the set of reduced latin squares for the following orders") println("and hence the total number of latin squares of these orders are:\n") for (n in 1 until 7) { val size = reducedLatinSquares(n, false) var f = factorial(n - 1.toLong()) f *= f * n * size println("Order $n: Size %-4d x $n! x ${n - 1}! => Total $f".format(size)) } }
mit
cec5499bef6b936dbd2f940738dd9269
25.033058
84
0.44
3.684211
false
false
false
false
JetBrains/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/cgen/CSyntaxSupport.kt
4
2156
package org.jetbrains.kotlin.backend.konan.cgen internal interface CType { fun render(name: String): String } internal class CVariable(val type: CType, val name: String) { override fun toString() = type.render(name) } internal object CTypes { fun simple(type: String): CType = SimpleCType(type) fun pointer(pointee: CType): CType = PointerCType(pointee) fun function(returnType: CType, parameterTypes: List<CType>, variadic: Boolean): CType = FunctionCType(returnType, parameterTypes, variadic) fun blockPointer(pointee: CType): CType = object : CType { override fun render(name: String): String = pointee.render("^$name") } val void = simple("void") val voidPtr = pointer(void) val signedChar = simple("signed char") val unsignedChar = simple("unsigned char") val short = simple("short") val unsignedShort = simple("unsigned short") val int = simple("int") val unsignedInt = simple("unsigned int") val longLong = simple("long long") val unsignedLongLong = simple("unsigned long long") val float = simple("float") val double = simple("double") val C99Bool = simple("_Bool") val char = simple("char") val vector128 = simple("float __attribute__ ((__vector_size__ (16)))") val id = simple("id") } private class SimpleCType(private val type: String) : CType { override fun render(name: String): String = if (name.isEmpty()) type else "$type $name" } private class PointerCType(private val pointee: CType) : CType { override fun render(name: String): String = pointee.render("*$name") } private class FunctionCType( private val returnType: CType, private val parameterTypes: List<CType>, private val variadic: Boolean ) : CType { override fun render(name: String): String = returnType.render(buildString { append("(") append(name) append(")(") parameterTypes.joinTo(this) { it.render("") } if (parameterTypes.isEmpty()) { if (!variadic) append("void") } else { if (variadic) append(", ...") } append(')') }) }
apache-2.0
d6f66cc252403fc23e184a82336d171f
31.666667
92
0.643321
4.178295
false
false
false
false
vovagrechka/fucking-everything
attic/alraune/alraune-back-kotlin-3/src/SpitOrderPage.kt
1
16208
package alraune.back import alraune.back.Al.* import alraune.back.AlTag.* import alraune.back.EntityPageTemplate.Identification import vgrechka.* import alraune.back.Col.* import java.util.function.Supplier @Suppress("unused") class SpitOrderPage : SpitPage { val spit = MakeOrderPageShit().dance().spitPage!! override fun spit() = spit.spit() override fun isPrivate() = spit.isPrivate } class MakeOrderPageShit { val filesTabID = "Files" var pedro by notNull<EntityPageTemplate.Pedro<AlUAOrder>>() fun dance(): EntityPageTemplate.Product { val t = EntityPageTemplate1<AlUAOrder>() pedro = object : EntityPageTemplate.Pedro<AlUAOrder>() { override fun identification() = Identification.ExplicitOrSearch override fun entityClass() = AlUAOrder::class.java override fun impersonationMakesSense(impersonateAs: AlUserKind) = when (impersonateAs) { AlUserKind.Customer -> true AlUserKind.Admin -> true AlUserKind.Writer -> Al2.isWriterAssigned(pedro.juan.entity) } override fun pageClass() = SpitOrderPage::class.java override fun applicableEntityAddressings() = when { rctx().isAdmin -> mutableListOf() else -> mutableListOf<EntityAddressing<AlUAOrder>>() } override fun getTable() = "ua_orders" override fun getNoEntityWithIDMessage() = t("TOTE", "Заказа с ID <b>%s</b> не существует, такие дела...") override fun getNoEntityWithUUIDMessage() = t("TOTE", "Заказа с UUID <b>%s</b> не существует, такие дела...") override fun getNoPermissionsForEntityWithIDMessage() = t("TOTE", "К заказу с ID <b>%s</b> у тебя доступа нет, приятель") override fun paramsModalContent(): EntityPageTemplate.ParamsModalContent { return EntityPageTemplate.ParamsModalContent {frc2, fields -> OrderPile2.renderOrderParamsFormBody(frc2, fields) } } override fun updateEntityParams(fs: BunchOfFields) { object : Al2.UpdateEntityParams() { override fun shortOperationDescription() = "Edit order" override fun entity() = juan.entity override fun fields() = fs }.dance() } override fun makeFields() = when { rctx().isAdmin -> OrderFieldsForAdmin() else -> OrderFields() } override fun pagePath() = AlPagePath.order override fun addTabs(xs: MutableList<EntityPageTemplate.Tab>) { xs.add(FilesTab()) } inner class FilesTab : EntityPageTemplate.Tab { override fun id() = filesTabID override fun title() = t("Files", "Файлы") override fun addTopRightControls(trb: TopRightControlsBuilder) { trb.addOrderingSelect() val canEdit: Boolean = canEditParams() if (canEdit) { trb.addButton(FA.plus, AlDebugTag.topRightButton, {buttonDomid -> AlRender.bustOutModalOnDomidClick(juan.script, buttonDomid, ModalWithScripts.make {frc, frc2 -> frc.fileValue = AlFileFormValue() renderFileModalContent(frc2, null, FieldSource.Initial()) }) }) } } override fun render(rpp: RenderingParamsPile) = object : RenderPaginatedShit<AlUAOrderFile>() { override fun makePageHref(pageFrom1: Int) = juan.makeHrefKeepingEverythingExcept {it.page.set(pageFrom1)} override fun renderItem(item: AlUAOrderFile) = OrderPile2.renderOrderFileItem(juan.script, item, false) override fun selectItems(offset: Long) = AlDB.betty(AlDB_Params_betty_Builder.begin() .counting(false) .offset(offset) .orderID(juan.entity.id) .ordering(rctx().getParams.get().ordering.get()).end()) .selectCompound(AlUAOrderFile::class.java, null) override fun count() = AlDB.betty(AlDB_Params_betty_Builder.begin() .counting(true) .orderID(juan.entity.id).end()) .selectOneLong() override fun initGivenItems(alUAOrderFileWithParams: List<AlUAOrderFile>) {} }.dance() fun renderFileModalContent(frc2: FormRenderingContext2, file: AlUAOrderFile?, source: FieldSource): Renderable { val rmc = RenderModalContent() rmc.title = when { file == null -> t("TOTE", "Файл") else -> t("TOTE", "Файл №" + file.id) } rmc.blueLeftMargin() rmc.body = div().with { val fields = Al.useFields(OrderFileFields(), source) oo((fields.file as FileField).render(frc2)) // TODO:vgrechka Get rid of cast oo(fields.title.render(frc2).focused()) oo(fields.details.render(frc2)) } rmc.footer = ButtonBarWithTicker(rctx().script, frc2) .tickerLocation(LeftOrRight.Left) .addSubmitFormButton(MinimalButtonShit( when { file == null -> AlConst.Text.create else -> AlConst.Text.save }, AlButtonLevel2.Primary, Servant {serveCreateOrUpdateFile(file)}), rmc.errorBannerDomid) .addCloseModalButton() return rmc.dance() } private fun serveCreateOrUpdateFile(file: AlUAOrderFile?) { val fs = Al.useFields(OrderFileFields(), FieldSource.Post()) val incomingFile = fs.file.value() if (Al.anyFieldErrors(fs)) return run { val frc2 = FormRenderingContext2() frc2.shouldRestoreFilePickerValue = true // TODO:vgrechka Remove from context AlCommands2.addEval {s -> s.replaceElement( AlDomid.modalContent.name, renderFileModalContent(frc2, file, FieldSource.Post()), Supplier {frc2.initAndOnShowScripts()} )} } if (Alk.isPreflight()) return run { rctx().keepAdHocServantWithSameUUIDForNextRequest = true AlCommands2.addEval(AlJS.invokeLastBackendCallTemplate(false, 0)) } if (file == null) { val cab = ContentAndBytesFromBase64(incomingFile.base64) AlDB.insertEntity(cab.bytes) AlDB.insertEntity(AlUAOrderFile_Builder.begin() .uuid(Al.longUUID()) .orderID(juan.entity.id) .state(AlUAOrderFileState.UNKNOWN) .name(incomingFile.name) .size(cab.content.size) .title(fs.title.sanitized()) .details(fs.details.sanitized()) .bytesID(cab.bytes.getId()) .end()) // TODO:vgrechka Operations // AlOperation operation = new AlOperationData_Rudimentary_V1(AlBasicOperationData_V1.make("Creating file")).toOperation(); AlCommands2.addCloseModal() juan.reload() } else { object : Al2.UpdateEntityParams() { override fun entity() = file override fun fields() = fs override fun shortOperationDescription() = "Editing freaking file" }.dance() AlCommands2.addCloseModal() imf("Replace shit") // JSScriptBuilder script = new JSScriptBuilder(); // rctx().commands.add(also(new AlBackToFrontCommandPile(), o -> { // o.opcode = AlBackToFrontCommandOpcode.ReplaceElement; // o.domid = AlDomid.item; // o.domidIndex = rctx().fileWithParams.get().entity.uuid; // o.initCommands = new ArrayList<>(); // o.html = OrderPile2.renderOrderFileItem(script, rctx().fileWithParams.get(), true).render(); // })); // rctx().addCommand(AlCommands2.eval(script.getCode())); } } } override fun canEditParams() = when { juan.initialParams.impersonate.get() == AlUserKind.Admin -> true else -> juan.entity.state in setOf( AlUAOrderState.CustomerDraft, AlUAOrderState.ReturnedToCustomerForFixing) } override fun pageTitle() = t("TOTE", "Заказ №") + juan.entity.id override fun pageSubTitle() = juan.entity.documentTitle override fun renderActionBannerBelowTitle() = when { AlUAOrderState.CustomerDraft == juan.entity.state -> { if (rctx().pretending.get() == AlUserKind.Customer) ActionBanner() .message(t("TOTE", "Убедись, что все верно. Подредактируй, если нужно. Возможно, добавь файлы. А затем...")) .backgroundColor(Color.BLUE_GRAY_50) .leftBorderColor(Color.BLUE_GRAY_300) .accept {banner -> banner.addButton(MinimalButtonShit( t("TOTE", "Отправить на проверку"), AlButtonLevel2.Primary, Servant { juan.changeEntityStateAndReload("Send order for approval", null, {p -> // 2a949363-293d-445f-a9f0-95ef1612b51e p.state = AlUAOrderState.WaitingAdminApproval; }) } )) } else div() } AlUAOrderState.ReturnedToCustomerForFixing == juan.entity.state -> object : RejectedBanner() { override fun entityKindTitle() = "этот заказ" override fun rejectionReason() = juan.entity.rejectionReason override fun sendForReviewServant() = object : Servant { override fun checkPermissions() = imf() override fun ignite() = imf() } }.dance() AlUAOrderState.WaitingAdminApproval == juan.entity.state -> object : RenderApprovalBanner() { override fun performRejection(fs: RejectionFields) = imf() override fun acceptButtonTitle() = t("TOTE", "В стор") override fun entityKindTitle() = "заказ" override fun rejectButtonTitle() = t("TOTE", "Завернуть") override fun acceptServant() = imf() override fun messageForUser() = t("TOTE", "Мы проверяем заказ и скоро с тобой свяжемся") override fun questionForAdmin() = t("TOTE", "Что решаем по этому порожняку?") override fun frc() = juan.frc override fun frc2() = juan.frc2 override fun wasRejectionReason() = juan.entity.wasRejectionReason }.dance() else -> div() } override fun shitToGetParams(p: AlGetParams) = p.uuid.set(juan.entity.uuid) override fun renderBelowActionBanner() = when { rctx().pretending.get() == AlUserKind.Admin && juan.entity.state == AlUAOrderState.WaitingAdminApproval && !juan.entity.rejectionReason.isNullOrBlank() -> renderRejectionReason(AlConst.Text.potentialRejectionReason) else -> div() } override fun renderParamsTab(rpp: RenderingParamsPile): Renderable { val order = juan.entity var className: String? = null if (rpp.orderParamsClazz != null) className = rpp.orderParamsClazz return div().domid(AlDomid.orderParams).style("position: relative;").className(className).with { oo(Row().with { oo(AlRender.createdAtCol(3, order.createdAt)) oo(AlRender.renderOrderStateColumn(order)) }) oo(Row().with { oo(col(3, AlConst.Text.Order.contactName, order.contactName)) oo(col(3, AlConst.Text.Order.email, order.email)) oo(col(3, AlConst.Text.Order.phone, order.phone)) }) oo(Row().with { oo(AlRender.orderDocumentTypeColumn(order)) oo(AlRender.orderDocumentCategoryColumn(order)) }) oo(AlRender.renderOrderNumsRow(order)) oo(DetailsRow().content(order.documentDetails)) if (rctx().pretending.get() == AlUserKind.Admin) { if (!order.adminNotes.isNullOrBlank()) oo(DetailsRow().title(AlConst.Text.adminNotes).content(order.adminNotes)) } } } override fun shouldStopRenderingWithMessage() = when { rctx().pretending.get() == AlUserKind.Writer -> t("TOTE", "Никаким писателям этот заказ не виден") else -> null } fun renderRejectionReason(title: String) = AlRender.detailsWithUnderlinedTitle(title, juan.entity.rejectionReason) override fun shouldSkipField(fields: BunchOfFields, field: FormField<*>): Boolean { // TODO:vgrechka ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ return false } override fun isPagePrivate() = AlGetParams().uuid.get() == null override fun getUUIDSupported() = true override fun checkPermissionsForEntityAccessedViaIDIfNotAdmin(entity: AlUAOrder) = when (rctx().userWP().kind) { AlUserKind.Customer -> imf("Check that this customer is the one who created the order") AlUserKind.Writer -> imf("Check that this writer is assigned to the order") AlUserKind.Admin -> wtf() } } return t.build(pedro) } }
apache-2.0
60225da648ad84fc17f67f93fd40b8f0
46.023669
147
0.504467
5.137039
false
false
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/host/recycle/RecycleHostFactory.kt
2
1581
package com.github.kerubistan.kerub.planner.steps.host.recycle import com.github.kerubistan.kerub.model.Expectation import com.github.kerubistan.kerub.model.Host import com.github.kerubistan.kerub.model.dynamic.HostDynamic import com.github.kerubistan.kerub.model.dynamic.HostStatus import com.github.kerubistan.kerub.planner.OperationalState import com.github.kerubistan.kerub.planner.issues.problems.hosts.RecyclingHost import com.github.kerubistan.kerub.planner.steps.AbstractOperationalStepFactory import kotlin.reflect.KClass object RecycleHostFactory : AbstractOperationalStepFactory<RecycleHost>() { override val problemHints = setOf(RecyclingHost::class) override val expectationHints = setOf<KClass<out Expectation>>() override fun produce(state: OperationalState): List<RecycleHost> = state.hosts.values.filter { (host, dyn) -> //the host is being recycled host.recycling && isHostFree(host, state) && canDropFreeHost(host, dyn) }.map { RecycleHost(it.stat) } private fun canDropFreeHost( host: Host, dyn: HostDynamic? ) = //it is either dedicated and shut down, or not dedicated ((host.dedicated && (dyn == null || dyn.status == HostStatus.Down)) || !host.dedicated) private fun isHostFree(host: Host, state: OperationalState) = //no more disk allocations on it state.vStorage.values.none { it.dynamic?.allocations?.any { allocation -> allocation.hostId == host.id } ?: false } && //no vms running on it state.index.runningVms.none { it.dynamic?.hostId == host.id } }
apache-2.0
7ab583fb817c70ff926f2a1b0cc601d7
33.391304
79
0.740038
3.72
false
false
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/host/distros/Cygwin.kt
2
3875
package com.github.kerubistan.kerub.host.distros import com.github.kerubistan.kerub.data.dynamic.HostDynamicDao import com.github.kerubistan.kerub.data.dynamic.VirtualStorageDeviceDynamicDao import com.github.kerubistan.kerub.data.dynamic.doWithDyn import com.github.kerubistan.kerub.host.FireWall import com.github.kerubistan.kerub.host.PackageManager import com.github.kerubistan.kerub.host.ServiceManager import com.github.kerubistan.kerub.host.packman.CygwinPackageManager import com.github.kerubistan.kerub.model.Host import com.github.kerubistan.kerub.model.HostCapabilities import com.github.kerubistan.kerub.model.OperatingSystem import com.github.kerubistan.kerub.model.SoftwarePackage import com.github.kerubistan.kerub.model.StorageCapability import com.github.kerubistan.kerub.model.Version import com.github.kerubistan.kerub.model.controller.config.ControllerConfig import com.github.kerubistan.kerub.model.dynamic.HostStatus import com.github.kerubistan.kerub.model.hardware.BlockDevice import com.github.kerubistan.kerub.model.lom.PowerManagementInfo import com.github.kerubistan.kerub.utils.asPercentOf import com.github.kerubistan.kerub.utils.junix.common.OsCommand import com.github.kerubistan.kerub.utils.junix.procfs.MemInfo import com.github.kerubistan.kerub.utils.junix.procfs.Stat import com.github.kerubistan.kerub.utils.junix.uname.UName import io.github.kerubistan.kroki.time.now import org.apache.sshd.client.session.ClientSession import java.math.BigInteger class Cygwin : Distribution { override fun listBlockDevices(session: ClientSession): List<BlockDevice> // TODO : find a way to get block device list from windows - wmic maybe? = listOf() override fun getVersion(session: ClientSession) = Version.fromVersionString(UName.kernelVersion(session).substringBefore("(")) override fun name(): String = "Cygwin" override fun handlesVersion(version: Version): Boolean = version.major.toInt() >= 2 override fun detect(session: ClientSession): Boolean = UName.operatingSystem(session) == "Cygwin" override fun getPackageManager(session: ClientSession): PackageManager = CygwinPackageManager(session) override fun installMonitorPackages(session: ClientSession, host: Host) { // do nothing, cygwin can not install, try to work with what is installed } override fun startMonitorProcesses( session: ClientSession, host: Host, hostDynDao: HostDynamicDao, vStorageDeviceDynamicDao: VirtualStorageDeviceDynamicDao, controllerConfig: ControllerConfig ) { Stat.cpuLoadMonitorIncremental(session) { cpus -> val idle = cpus["cpu"]?.idle ?: 0 val user = cpus["cpu"]?.user ?: 0 val system = cpus["cpu"]?.system ?: 0 val sum = system + idle + user hostDynDao.doWithDyn(host.id) { dyn -> dyn.copy( status = HostStatus.Up, idleCpu = idle.asPercentOf(sum).toByte(), systemCpu = system.asPercentOf(sum).toByte(), userCpu = user.asPercentOf(sum).toByte(), lastUpdated = now() ) } } } override fun getRequiredPackages(osCommand: OsCommand, capabilities: HostCapabilities?): List<String> = listOf() override fun detectStorageCapabilities( session: ClientSession, osVersion: SoftwarePackage, packages: List<SoftwarePackage> ): List<StorageCapability> = listOf() override fun detectPowerManagement(session: ClientSession): List<PowerManagementInfo> = listOf() // TODO override fun detectHostCpuType(session: ClientSession): String = UName.processorType(session).toUpperCase() override fun getTotalMemory(session: ClientSession): BigInteger = MemInfo.total(session) override fun getFireWall(session: ClientSession): FireWall { TODO() } override fun getServiceManager(session: ClientSession): ServiceManager { TODO() } override fun getHostOs(): OperatingSystem = operatingSystem override val operatingSystem = OperatingSystem.Windows }
apache-2.0
d2356ee296a97bf86258531e56092335
37.75
113
0.789677
3.938008
false
false
false
false
vovagrechka/fucking-everything
phizdets/phizdets-idea/src/vgrechka/phizdetsidea/phizdets/run/PyVirtualEnvReader.kt
1
4457
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package vgrechka.phizdetsidea.phizdets.run import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.util.EnvironmentUtil import com.intellij.util.LineSeparator import vgrechka.phizdetsidea.phizdets.sdk.PhizdetsSdkType import java.io.File /** * @author traff */ class PyVirtualEnvReader(val virtualEnvSdkPath: String) : EnvironmentUtil.ShellEnvReader() { private val LOG = Logger.getInstance("#vgrechka.phizdetsidea.phizdets.run.PyVirtualEnvReader") companion object { val virtualEnvVars = listOf("PATH", "PS1", "VIRTUAL_ENV", "PYTHONHOME", "PROMPT", "_OLD_VIRTUAL_PROMPT", "_OLD_VIRTUAL_PYTHONHOME", "_OLD_VIRTUAL_PATH") } // in case of Conda we need to pass an argument to an activate script that tells which exactly environment to activate val activate: Pair<String, String?>? = findActivateScript(virtualEnvSdkPath, shell) override fun getShell(): String? { if (File("/bin/bash").exists()) { return "/bin/bash"; } else if (File("/bin/sh").exists()) { return "/bin/sh"; } else { return super.getShell(); } } override fun readShellEnv(): MutableMap<String, String> { if (SystemInfo.isUnix) { return super.readShellEnv() } else { if (activate != null) { return readVirtualEnvOnWindows(activate); } else { LOG.error("Can't find activate script for $virtualEnvSdkPath") return mutableMapOf(); } } } private fun readVirtualEnvOnWindows(activate: Pair<String, String?>): MutableMap<String, String> { val activateFile = FileUtil.createTempFile("pycharm-virualenv-activate.", ".bat", false) val envFile = FileUtil.createTempFile("pycharm-virualenv-envs.", ".tmp", false) try { FileUtil.copy(File(activate.first), activateFile); FileUtil.appendToFile(activateFile, "\n\nset >" + envFile.absoluteFile) val command = if (activate.second != null) listOf<String>(activateFile.path, activate.second!!) else listOf<String>(activateFile.path) return runProcessAndReadEnvs(command, envFile, LineSeparator.CRLF.separatorString) } finally { FileUtil.delete(activateFile) FileUtil.delete(envFile) } } override fun getShellProcessCommand(): MutableList<String> { val shellPath = shell if (shellPath == null || !File(shellPath).canExecute()) { throw Exception("shell:" + shellPath) } return if (activate != null) { val activateArg = if (activate.second != null) "'${activate.first}' '${activate.second}'" else "'${activate.first}'" mutableListOf(shellPath, "-c", ". $activateArg") } else super.getShellProcessCommand() } } fun findActivateScript(path: String?, shellPath: String?): Pair<String, String?>? { val shellName = if (shellPath != null) File(shellPath).name else null val activate = if (SystemInfo.isWindows) findActivateOnWindows(path) else if (shellName == "fish" || shellName == "csh") File(File(path).parentFile, "activate." + shellName) else File(File(path).parentFile, "activate") return if (activate != null && activate.exists()) { val sdk = PhizdetsSdkType.findSdkByPath(path) if (sdk != null && PhizdetsSdkType.isCondaVirtualEnv(sdk)) Pair(activate.absolutePath, condaEnvFolder(path)) else Pair(activate.absolutePath, null) } else null } private fun condaEnvFolder(path: String?) = if (SystemInfo.isWindows) File(path).parent else File(path).parentFile.parent private fun findActivateOnWindows(path: String?): File? { for (location in arrayListOf("activate.bat", "Scripts/activate.bat")) { val file = File(File(path).parentFile, location) if (file.exists()) { return file } } return null }
apache-2.0
68eda61036d8de1e130ef923be21971f
33.292308
135
0.69217
4.055505
false
false
false
false
kingargyle/serenity-android
emby-lib/src/main/kotlin/us/nineworlds/serenity/emby/server/api/FilterService.kt
2
603
package us.nineworlds.serenity.emby.server.api import retrofit2.Call import retrofit2.http.GET import retrofit2.http.HeaderMap import retrofit2.http.Query import us.nineworlds.serenity.emby.server.model.QueryFilters interface FilterService { @GET("/emby/Genres?EnableUserData=false&SortBy=SortName&SortOrder=Ascending&EnableTotalRecordCount=false&EnableImages=false") fun availableFilters( @HeaderMap headerMap: Map<String, String>, @Query("userId") userId: String, @Query("ParentId") itemId: String? = null, @Query("Recursive") recursive: Boolean = true ): Call<QueryFilters> }
mit
a5546cb189b02ec2c9fd9725053485e4
32.555556
127
0.779436
3.745342
false
false
false
false
Atsky/haskell-idea-plugin
plugin/src/org/jetbrains/cabal/psi/Section.kt
1
1069
package org.jetbrains.cabal.psi import com.intellij.lang.ASTNode import com.intellij.extapi.psi.ASTDelegatePsiElement import com.intellij.psi.tree.IElementType import com.intellij.psi.PsiElement import com.intellij.psi.impl.source.tree.SharedImplUtil import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.cabal.psi.PropertyField import org.jetbrains.cabal.psi.Checkable import org.jetbrains.cabal.highlight.ErrorMessage import java.util.ArrayList open class Section(node: ASTNode): Field(node), FieldContainer, Checkable { override fun check(): List<ErrorMessage> = listOf() fun getSectChildren(): List<PsiElement> = children.filter { it is Field } fun getSectTypeNode(): PsiElement = (children.firstOrNull { it is SectionType }) ?: throw IllegalStateException() fun getSectType(): String = getSectTypeNode().text!! protected open fun getSectName(): String? { var node = firstChild while ((node != null) && (node !is Name)) { node = node.nextSibling } return (node as? Name)?.text } }
apache-2.0
efa22630c5cafcc5925d6a0ed17aea85
31.424242
117
0.73246
4.095785
false
false
false
false
androidx/androidx
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/KotlinPoetExt.kt
3
3973
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.compiler.processing import androidx.room.compiler.codegen.XTypeName import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.OriginatingElementsHolder import com.squareup.kotlinpoet.ParameterizedTypeName import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.javapoet.KClassName internal val KOTLIN_NONE_TYPE_NAME: KClassName = KClassName("androidx.room.compiler.processing.error", "NotAType") /** * Adds the given element as an originating element for compilation. * see [OriginatingElementsHolder.Builder.addOriginatingElement]. */ fun <T : OriginatingElementsHolder.Builder<T>> T.addOriginatingElement( element: XElement ): T { element.originatingElementForPoet()?.let(this::addOriginatingElement) return this } internal fun TypeName.rawTypeName(): TypeName { return if (this is ParameterizedTypeName) { this.rawType } else { this } } object FunSpecHelper { fun overriding( elm: XMethodElement, owner: XType ): FunSpec.Builder { val asMember = elm.asMemberOf(owner) return overriding( executableElement = elm, resolvedType = asMember ) } private fun overriding( executableElement: XMethodElement, resolvedType: XMethodType ): FunSpec.Builder { return FunSpec.builder(executableElement.name).apply { addModifiers(KModifier.OVERRIDE) if (executableElement.isPublic()) { addModifiers(KModifier.PUBLIC) } else if (executableElement.isProtected()) { addModifiers(KModifier.PROTECTED) } if (executableElement.isSuspendFunction()) { addModifiers(KModifier.SUSPEND) } // TODO(b/251316420): Add type variable names val isVarArgs = executableElement.isVarArgs() resolvedType.parameterTypes.let { // Drop the synthetic Continuation param of suspend functions, always at the last // position. // TODO(b/254135327): Revisit with the introduction of a target language. if (resolvedType.isSuspendFunction()) it.dropLast(1) else it }.forEachIndexed { index, paramType -> val typeName: XTypeName val modifiers: Array<KModifier> // TODO(b/253268357): In Kotlin the vararg is not always the last param if (isVarArgs && index == resolvedType.parameterTypes.size - 1) { typeName = (paramType as XArrayType).componentType.asTypeName() modifiers = arrayOf(KModifier.VARARG) } else { typeName = paramType.asTypeName() modifiers = emptyArray() } addParameter( executableElement.parameters[index].name, typeName.kotlin, *modifiers ) } returns( if (resolvedType.isSuspendFunction()) { resolvedType.getSuspendFunctionReturnType() } else { resolvedType.returnType }.asTypeName().kotlin ) } } }
apache-2.0
2b88483e42d3ef3194a4ca4a1a70fdf5
35.796296
97
0.631009
5.106684
false
false
false
false
androidx/androidx
core/core-ktx/src/androidTest/java/androidx/core/util/SparseIntArrayTest.kt
3
5584
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.core.util import android.util.SparseIntArray import androidx.test.filters.SmallTest import androidx.testutils.fail import com.google.common.truth.Truth.assertThat import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test @SmallTest class SparseIntArrayTest { @Test fun sizeProperty() { val array = SparseIntArray() assertEquals(0, array.size) array.put(1, 11) assertEquals(1, array.size) } @Test fun containsOperator() { val array = SparseIntArray() assertFalse(1 in array) array.put(1, 11) assertTrue(1 in array) } @Test fun containsOperatorWithValue() { val array = SparseIntArray() array.put(1, 11) assertFalse(2 in array) array.put(2, 22) assertTrue(2 in array) } @Test fun setOperator() { val array = SparseIntArray() array[1] = 11 assertEquals(11, array.get(1)) } @Test fun plusOperator() { val first = SparseIntArray().apply { put(1, 11) } val second = SparseIntArray().apply { put(2, 22) } val combined = first + second assertEquals(2, combined.size()) assertEquals(1, combined.keyAt(0)) assertEquals(11, combined.valueAt(0)) assertEquals(2, combined.keyAt(1)) assertEquals(22, combined.valueAt(1)) } @Test fun containsKey() { val array = SparseIntArray() assertFalse(array.containsKey(1)) array.put(1, 11) assertTrue(array.containsKey(1)) } @Test fun containsKeyWithValue() { val array = SparseIntArray() array.put(1, 11) assertFalse(array.containsKey(2)) array.put(2, 22) assertTrue(array.containsKey(2)) } @Test fun containsValue() { val array = SparseIntArray() assertFalse(array.containsValue(11)) array.put(1, 11) assertTrue(array.containsValue(11)) } @Test fun getOrDefault() { val array = SparseIntArray() assertEquals(22, array.getOrDefault(1, 22)) array.put(1, 11) assertEquals(11, array.getOrDefault(1, 22)) } @Test fun getOrElse() { val array = SparseIntArray() assertEquals(22, array.getOrElse(1) { 22 }) array.put(1, 11) assertEquals(11, array.getOrElse(1) { fail() }) assertEquals(33, array.getOrElse(2) { 33 }) } @Test fun isEmpty() { val array = SparseIntArray() assertTrue(array.isEmpty()) array.put(1, 11) assertFalse(array.isEmpty()) } @Test fun isNotEmpty() { val array = SparseIntArray() assertFalse(array.isNotEmpty()) array.put(1, 11) assertTrue(array.isNotEmpty()) } @Test fun removeValue() { val array = SparseIntArray() array.put(1, 11) assertFalse(array.remove(2, 11)) assertEquals(1, array.size()) assertFalse(array.remove(1, 22)) assertEquals(1, array.size()) assertTrue(array.remove(1, 11)) assertEquals(0, array.size()) } @Test fun putAll() { val dest = SparseIntArray() val source = SparseIntArray() source.put(1, 11) assertEquals(0, dest.size()) dest.putAll(source) assertEquals(1, dest.size()) } @Test fun forEach() { val array = SparseIntArray() array.forEach { _, _ -> fail() } array.put(1, 11) array.put(2, 22) array.put(6, 66) val keys = mutableListOf<Int>() val values = mutableListOf<Int>() array.forEach { key, value -> keys.add(key) values.add(value) } assertThat(keys).containsExactly(1, 2, 6) assertThat(values).containsExactly(11, 22, 66) } @Test fun keyIterator() { val array = SparseIntArray() assertFalse(array.keyIterator().hasNext()) array.put(1, 11) array.put(2, 22) array.put(6, 66) val iterator = array.keyIterator() assertTrue(iterator.hasNext()) assertEquals(1, iterator.nextInt()) assertTrue(iterator.hasNext()) assertEquals(2, iterator.nextInt()) assertTrue(iterator.hasNext()) assertEquals(6, iterator.nextInt()) assertFalse(iterator.hasNext()) } @Test fun valueIterator() { val array = SparseIntArray() assertFalse(array.valueIterator().hasNext()) array.put(1, 11) array.put(2, 22) array.put(6, 66) val iterator = array.valueIterator() assertTrue(iterator.hasNext()) assertEquals(11, iterator.nextInt()) assertTrue(iterator.hasNext()) assertEquals(22, iterator.nextInt()) assertTrue(iterator.hasNext()) assertEquals(66, iterator.nextInt()) assertFalse(iterator.hasNext()) } }
apache-2.0
b14c1dcf78235c1fd0f418ca06843b44
27.20202
75
0.607092
4.23351
false
true
false
false
GunoH/intellij-community
plugins/kotlin/completion/impl-shared/src/org/jetbrains/kotlin/idea/completion/implCommon/handlers/WithTailInsertHandler.kt
4
4169
// 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.completion.handlers import com.intellij.codeInsight.AutoPopupController import com.intellij.codeInsight.completion.InsertHandler import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.lookup.LookupElement import com.intellij.openapi.components.serviceOrNull import com.intellij.openapi.editor.Document import com.intellij.psi.PsiDocumentManager abstract class SmartCompletionTailOffsetProvider { abstract fun getTailOffset(context: InsertionContext, item: LookupElement): Int } class WithTailInsertHandler( val tailText: String, val spaceBefore: Boolean, val spaceAfter: Boolean, val overwriteText: Boolean = true ) : InsertHandler<LookupElement> { override fun handleInsert(context: InsertionContext, item: LookupElement) { item.handleInsert(context) postHandleInsert(context, item) } val asPostInsertHandler: InsertHandler<LookupElement> get() = InsertHandler { context, item -> postHandleInsert(context, item) } fun postHandleInsert(context: InsertionContext, item: LookupElement) { val completionChar = context.completionChar if (completionChar == tailText.singleOrNull() || (spaceAfter && completionChar == ' ')) { context.setAddCompletionChar(false) } //TODO: what if completion char is different? val document = context.document PsiDocumentManager.getInstance(context.project).doPostponedOperationsAndUnblockDocument(document) var tailOffset = serviceOrNull<SmartCompletionTailOffsetProvider>()?.getTailOffset(context, item) ?:context.tailOffset val moveCaret = context.editor.caretModel.offset == tailOffset //TODO: analyze parenthesis balance to decide whether to replace or not var insert = true if (overwriteText) { var offset = tailOffset if (tailText != " ") { offset = document.charsSequence.skipSpacesAndLineBreaks(offset) } if (shouldOverwriteChar(document, offset)) { insert = false offset += tailText.length tailOffset = offset if (spaceAfter && document.charsSequence.isCharAt(offset, ' ')) { document.deleteString(offset, offset + 1) } } } var textToInsert = "" if (insert) { textToInsert = tailText if (spaceBefore) textToInsert = " " + textToInsert } if (spaceAfter) textToInsert += " " document.insertString(tailOffset, textToInsert) if (moveCaret) { context.editor.caretModel.moveToOffset(tailOffset + textToInsert.length) if (tailText == ",") { AutoPopupController.getInstance(context.project)?.autoPopupParameterInfo(context.editor, null) } } } private fun shouldOverwriteChar(document: Document, offset: Int): Boolean { if (!document.isTextAt(offset, tailText)) return false if (tailText == " " && document.charsSequence.isCharAt(offset + 1, '}')) return false // do not overwrite last space before '}' return true } companion object { val COMMA = WithTailInsertHandler(",", spaceBefore = false, spaceAfter = true /*TODO: use code style option*/) val RPARENTH = WithTailInsertHandler(")", spaceBefore = false, spaceAfter = false) val RBRACKET = WithTailInsertHandler("]", spaceBefore = false, spaceAfter = false) val RBRACE = WithTailInsertHandler("}", spaceBefore = true, spaceAfter = false) val ELSE = WithTailInsertHandler("else", spaceBefore = true, spaceAfter = true) val EQ = WithTailInsertHandler("=", spaceBefore = true, spaceAfter = true) /*TODO: use code style options*/ val SPACE = WithTailInsertHandler(" ", spaceBefore = false, spaceAfter = false, overwriteText = true) } }
apache-2.0
055cfaff411ed12d1a3bbb64fbee9c4a
40.7
158
0.669705
5.028951
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/testData/findUsages/java/findJavaClassUsages/JKAliasedClassAllUsages.1.kt
4
510
import AAA as A public class X(bar: String? = A.BAR): A() { var next: A? = A() val myBar: String? = A.BAR init { A.BAR = "" AAA.foos() } fun foo(a: A) { val aa: AAA = a aa.bar = "" } fun getNext(): A? { return next } public override fun foo() { super<A>.foo() } companion object: AAA() { } } object O: A() { } fun X.bar(a: A = A()) { } fun Any.toA(): A? { return if (this is A) this as A else null }
apache-2.0
ecbeb1283be5df9e531df16b2ad317bd
12.102564
45
0.447059
2.914286
false
false
false
false
PaleoCrafter/VanillaImmersion
src/main/kotlin/de/mineformers/vanillaimmersion/network/CraftingDrag.kt
1
2006
package de.mineformers.vanillaimmersion.network import de.mineformers.vanillaimmersion.immersion.CraftingHandler import de.mineformers.vanillaimmersion.tileentity.CraftingTableLogic import io.netty.buffer.ByteBuf import net.minecraft.util.math.BlockPos import net.minecraftforge.fml.common.network.simpleimpl.IMessage import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler import net.minecraftforge.fml.common.network.simpleimpl.MessageContext /** * Message and handler for notifying the server about a dragging operation on a crafting table. */ object CraftingDrag { /** * The message just holds the table's position and the list of slots affected by the operation. */ data class Message(var pos: BlockPos = BlockPos.ORIGIN, var slots: MutableList<Int> = mutableListOf()) : IMessage { override fun toBytes(buf: ByteBuf) { buf.writeLong(pos.toLong()) buf.writeInt(slots.size) for (i in slots) buf.writeInt(i) } override fun fromBytes(buf: ByteBuf) { pos = BlockPos.fromLong(buf.readLong()) val count = buf.readInt() for (i in 1..count) slots.add(buf.readInt()) } } object Handler : IMessageHandler<Message, IMessage> { override fun onMessage(msg: Message, ctx: MessageContext): IMessage? { val player = ctx.serverHandler.player // We interact with the world, hence schedule our action player.serverWorld.addScheduledTask { if (!player.world.isBlockLoaded(msg.pos)) return@addScheduledTask val tile = player.world.getTileEntity(msg.pos) if (tile is CraftingTableLogic) { // Delegate the dragging to the dedicated method CraftingHandler.performDrag(tile, player, msg.slots) } } return null } } }
mit
703ac4cad925e5f9dc7ee57f78095b8e
38.333333
99
0.639083
4.857143
false
false
false
false
GunoH/intellij-community
platform/util/src/com/intellij/util/io/sanitize-name.kt
3
1160
package com.intellij.util.io import java.util.function.Predicate import kotlin.math.min private val illegalChars = hashSetOf('/', '\\', '?', '<', '>', ':', '*', '|', '"') // https://github.com/parshap/node-sanitize-filename/blob/master/index.js fun sanitizeFileName(name: String, replacement: String? = "_", truncateIfNeeded: Boolean = true, extraIllegalChars: Predicate<Char>? = null): String { var result: StringBuilder? = null var last = 0 val length = name.length for (i in 0 until length) { val c = name[i] if (!illegalChars.contains(c) && !c.isISOControl() && (extraIllegalChars == null || !extraIllegalChars.test(c))) { continue } if (result == null) { result = StringBuilder() } if (last < i) { result.append(name, last, i) } if (replacement != null) { result.append(replacement) } last = i + 1 } fun truncateFileName(s: String) = if (truncateIfNeeded) s.substring(0, min(length, 255)) else s if (result == null) { return truncateFileName(name) } if (last < length) { result.append(name, last, length) } return truncateFileName(result.toString()) }
apache-2.0
1cc97195f4de1513ad43afa785a79548
25.976744
150
0.631034
3.625
false
false
false
false
android/compose-samples
Jetcaster/app/src/main/java/com/example/jetcaster/data/room/PodcastsDao.kt
1
4321
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.jetcaster.data.room import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Transaction import androidx.room.Update import com.example.jetcaster.data.Podcast import com.example.jetcaster.data.PodcastWithExtraInfo import kotlinx.coroutines.flow.Flow /** * [Room] DAO for [Podcast] related operations. */ @Dao abstract class PodcastsDao { @Query("SELECT * FROM podcasts WHERE uri = :uri") abstract fun podcastWithUri(uri: String): Flow<Podcast> @Transaction @Query( """ SELECT podcasts.*, last_episode_date, (followed_entries.podcast_uri IS NOT NULL) AS is_followed FROM podcasts INNER JOIN ( SELECT podcast_uri, MAX(published) AS last_episode_date FROM episodes GROUP BY podcast_uri ) episodes ON podcasts.uri = episodes.podcast_uri LEFT JOIN podcast_followed_entries AS followed_entries ON followed_entries.podcast_uri = episodes.podcast_uri ORDER BY datetime(last_episode_date) DESC LIMIT :limit """ ) abstract fun podcastsSortedByLastEpisode( limit: Int ): Flow<List<PodcastWithExtraInfo>> @Transaction @Query( """ SELECT podcasts.*, last_episode_date, (followed_entries.podcast_uri IS NOT NULL) AS is_followed FROM podcasts INNER JOIN ( SELECT episodes.podcast_uri, MAX(published) AS last_episode_date FROM episodes INNER JOIN podcast_category_entries ON episodes.podcast_uri = podcast_category_entries.podcast_uri WHERE category_id = :categoryId GROUP BY episodes.podcast_uri ) inner_query ON podcasts.uri = inner_query.podcast_uri LEFT JOIN podcast_followed_entries AS followed_entries ON followed_entries.podcast_uri = inner_query.podcast_uri ORDER BY datetime(last_episode_date) DESC LIMIT :limit """ ) abstract fun podcastsInCategorySortedByLastEpisode( categoryId: Long, limit: Int ): Flow<List<PodcastWithExtraInfo>> @Transaction @Query( """ SELECT podcasts.*, last_episode_date, (followed_entries.podcast_uri IS NOT NULL) AS is_followed FROM podcasts INNER JOIN ( SELECT podcast_uri, MAX(published) AS last_episode_date FROM episodes GROUP BY podcast_uri ) episodes ON podcasts.uri = episodes.podcast_uri INNER JOIN podcast_followed_entries AS followed_entries ON followed_entries.podcast_uri = episodes.podcast_uri ORDER BY datetime(last_episode_date) DESC LIMIT :limit """ ) abstract fun followedPodcastsSortedByLastEpisode( limit: Int ): Flow<List<PodcastWithExtraInfo>> @Query("SELECT COUNT(*) FROM podcasts") abstract suspend fun count(): Int /** * The following methods should really live in a base interface. Unfortunately the Kotlin * Compiler which we need to use for Compose doesn't work with that. * TODO: remove this once we move to a more recent Kotlin compiler */ @Insert(onConflict = OnConflictStrategy.REPLACE) abstract suspend fun insert(entity: Podcast): Long @Insert(onConflict = OnConflictStrategy.REPLACE) abstract suspend fun insertAll(vararg entity: Podcast) @Insert(onConflict = OnConflictStrategy.REPLACE) abstract suspend fun insertAll(entities: Collection<Podcast>) @Update(onConflict = OnConflictStrategy.REPLACE) abstract suspend fun update(entity: Podcast) @Delete abstract suspend fun delete(entity: Podcast): Int }
apache-2.0
78c13f3b4bed794d494ef950361775af
35.310924
120
0.697061
4.450051
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/diagnostic/hprof/analysis/LiveInstanceStats.kt
12
1858
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diagnostic.hprof.analysis import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.ProjectManager internal class LiveInstanceStats { fun createReport(): String { val result = StringBuilder() // Count open projects val openProjects = ProjectManager.getInstance().openProjects val projectsOpenCount = openProjects.size result.appendln("Projects open: $projectsOpenCount") openProjects.forEachIndexed { projectIndex, project -> result.appendln("Project ${projectIndex + 1}:") val modulesCount = ModuleManager.getInstance(project).modules.count() result.appendln(" Module count: $modulesCount") val allEditors = FileEditorManager.getInstance(project).allEditors val typeToCount = allEditors.groupingBy { "${it.javaClass.name}[${it.file?.fileType?.javaClass?.name}]" }.eachCount() result.appendln(" Editors opened: ${allEditors.size}. Counts by type:") typeToCount.entries.sortedByDescending { it.value }.forEach { (typeString, count) -> result.appendln(" * $count $typeString") } result.appendln() } return result.toString() } }
apache-2.0
0ebeb80df9d6a3181ff6d84c35d9ddca
38.553191
123
0.729817
4.565111
false
false
false
false
AMARJITVS/NoteDirector
app/src/main/kotlin/com/amar/notesapp/dialogs/ChangeSortingDialog.kt
1
3706
package com.amar.NoteDirector.dialogs import android.content.DialogInterface import android.support.v7.app.AlertDialog import android.view.LayoutInflater import android.view.View import com.simplemobiletools.commons.extensions.beVisibleIf import com.simplemobiletools.commons.extensions.setupDialogStuff import com.simplemobiletools.commons.helpers.* import com.amar.NoteDirector.activities.SimpleActivity import com.amar.NoteDirector.extensions.config import kotlinx.android.synthetic.main.dialog_change_sorting.view.* class ChangeSortingDialog(val activity: SimpleActivity, val isDirectorySorting: Boolean, showFolderCheckbox: Boolean, val path: String = "", val callback: () -> Unit) : DialogInterface.OnClickListener { private var currSorting = 0 private var config = activity.config private var view: View init { view = LayoutInflater.from(activity).inflate(com.amar.NoteDirector.R.layout.dialog_change_sorting, null).apply { use_for_this_folder_divider.beVisibleIf(showFolderCheckbox) sorting_dialog_use_for_this_folder.beVisibleIf(showFolderCheckbox) sorting_dialog_use_for_this_folder.isChecked = config.hasCustomSorting(path) } AlertDialog.Builder(activity) .setPositiveButton(com.amar.NoteDirector.R.string.ok, this) .setNegativeButton(com.amar.NoteDirector.R.string.cancel, null) .create().apply { activity.setupDialogStuff(view, this, com.amar.NoteDirector.R.string.sort_by) } currSorting = if (isDirectorySorting) config.directorySorting else config.getFileSorting(path) setupSortRadio() setupOrderRadio() } private fun setupSortRadio() { val sortingRadio = view.sorting_dialog_radio_sorting var sortBtn = sortingRadio.sorting_dialog_radio_name if (currSorting and SORT_BY_SIZE != 0) { sortBtn = sortingRadio.sorting_dialog_radio_size } else if (currSorting and SORT_BY_DATE_MODIFIED != 0) { sortBtn = sortingRadio.sorting_dialog_radio_last_modified } else if (currSorting and SORT_BY_DATE_TAKEN != 0) sortBtn = sortingRadio.sorting_dialog_radio_date_taken sortBtn.isChecked = true } private fun setupOrderRadio() { val orderRadio = view.sorting_dialog_radio_order var orderBtn = orderRadio.sorting_dialog_radio_ascending if (currSorting and SORT_DESCENDING != 0) { orderBtn = orderRadio.sorting_dialog_radio_descending } orderBtn.isChecked = true } override fun onClick(dialog: DialogInterface, which: Int) { val sortingRadio = view.sorting_dialog_radio_sorting var sorting = when (sortingRadio.checkedRadioButtonId) { com.amar.NoteDirector.R.id.sorting_dialog_radio_name -> SORT_BY_NAME com.amar.NoteDirector.R.id.sorting_dialog_radio_size -> SORT_BY_SIZE com.amar.NoteDirector.R.id.sorting_dialog_radio_last_modified -> SORT_BY_DATE_MODIFIED else -> SORT_BY_DATE_TAKEN } if (view.sorting_dialog_radio_order.checkedRadioButtonId == com.amar.NoteDirector.R.id.sorting_dialog_radio_descending) { sorting = sorting or SORT_DESCENDING } if (isDirectorySorting) { config.directorySorting = sorting } else { if (view.sorting_dialog_use_for_this_folder.isChecked) { config.saveFileSorting(path, sorting) } else { config.removeFileSorting(path) config.fileSorting = sorting } } callback() } }
apache-2.0
9aea721a267cfbfad6b61ec794554a57
41.113636
129
0.675391
4.36
false
true
false
false
DuckDeck/AndroidDemo
app/src/main/java/stan/androiddemo/project/petal/Module/UserInfo/PetalUserLikeFragment.kt
1
7082
package stan.androiddemo.project.petal.Module.UserInfo import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.RecyclerView import android.support.v7.widget.StaggeredGridLayoutManager import android.view.View import android.widget.FrameLayout import android.widget.ImageButton import android.widget.LinearLayout import android.widget.TextView import com.chad.library.adapter.base.BaseViewHolder import com.facebook.drawee.view.SimpleDraweeView import org.greenrobot.eventbus.EventBus import rx.Observable import rx.Subscriber import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import stan.androiddemo.R import stan.androiddemo.UI.BasePetalRecyclerFragment import stan.androiddemo.project.petal.API.ListPinsBean import stan.androiddemo.project.petal.API.UserAPI import stan.androiddemo.project.petal.Config.Config import stan.androiddemo.project.petal.Event.OnPinsFragmentInteractionListener import stan.androiddemo.project.petal.HttpUtiles.RetrofitClient import stan.androiddemo.project.petal.Model.PinsMainInfo import stan.androiddemo.tool.CompatUtils import stan.androiddemo.tool.ImageLoad.ImageLoadBuilder /** * A simple [Fragment] subclass. */ class PetalUserLikeFragment : BasePetalRecyclerFragment<PinsMainInfo>() { private var isMe: Boolean = false var mLimit = Config.LIMIT var maxId = 0 private var mListener: OnPinsFragmentInteractionListener? = null override fun getTheTAG(): String { return this.toString() } companion object { fun newInstance(key:String):PetalUserLikeFragment{ val fragment = PetalUserLikeFragment() val bundle = Bundle() bundle.putString("key",key) fragment.arguments = bundle return fragment } } override fun onAttach(context: Context?) { super.onAttach(context) if (context is OnPinsFragmentInteractionListener){ mListener = context } if (context is PetalUserInfoActivity){ isMe = context.isMe } } override fun getLayoutManager(): RecyclerView.LayoutManager { return StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL) } override fun getItemLayoutId(): Int { return R.layout.petal_cardview_image_item } override fun itemLayoutConvert(helper: BaseViewHolder, t: PinsMainInfo) { val img = helper.getView<SimpleDraweeView>(R.id.img_card_main) val txtGather = helper.getView<TextView>(R.id.txt_card_gather) var txtLike = helper.getView<TextView>(R.id.txt_card_like) val linearlayoutTitleInfo = helper.getView<LinearLayout>(R.id.linearLayout_image_title_info) //只能在这里设置TextView的drawable了 txtGather.setCompoundDrawablesRelativeWithIntrinsicBounds(CompatUtils.getTintListDrawable(context, R.drawable.ic_favorite_black_18dp,R.color.tint_list_grey),null,null,null) txtLike.setCompoundDrawablesRelativeWithIntrinsicBounds(CompatUtils.getTintListDrawable(context, R.drawable.ic_camera_black_18dp,R.color.tint_list_grey),null,null,null) val imgUrl = String.format(mUrlGeneralFormat,t.file!!.key) img.aspectRatio = t.imgRatio helper.getView<FrameLayout>(R.id.frame_layout_card_image).setOnClickListener { EventBus.getDefault().postSticky(t) mListener?.onClickPinsItemImage(t,it) } linearlayoutTitleInfo.setOnClickListener { EventBus.getDefault().postSticky(t) mListener?.onClickPinsItemText(t,it) } txtGather.setOnClickListener { //不做like操作了, t.repin_count ++ txtGather.text = t.repin_count.toString() txtGather.setCompoundDrawablesRelativeWithIntrinsicBounds(CompatUtils.getTintListDrawable(context, R.drawable.ic_favorite_black_18dp,R.color.tint_list_pink),null,null,null) } txtLike.setOnClickListener { //不做like操作了, t.like_count ++ helper.setText(R.id.txt_card_like,t.like_count.toString()) txtLike.setCompoundDrawablesRelativeWithIntrinsicBounds(CompatUtils.getTintListDrawable(context, R.drawable.ic_camera_black_18dp,R.color.tint_list_pink),null,null,null) } if (t.raw_text.isNullOrEmpty() && t.like_count <= 0 && t.repin_count <= 0){ linearlayoutTitleInfo.visibility = View.GONE } else{ linearlayoutTitleInfo.visibility = View.VISIBLE if (!t.raw_text.isNullOrEmpty()){ helper.getView<TextView>(R.id.txt_card_title).text = t.raw_text!! helper.getView<TextView>(R.id.txt_card_title).visibility = View.VISIBLE } else{ helper.getView<TextView>(R.id.txt_card_title).visibility = View.GONE } helper.setText(R.id.txt_card_gather,t.repin_count.toString()) helper.setText(R.id.txt_card_like,t.like_count.toString()) } var imgType = t.file?.type if (!imgType.isNullOrEmpty()){ if (imgType!!.toLowerCase().contains("gif") ) { helper.getView<ImageButton>(R.id.imgbtn_card_gif).visibility = View.VISIBLE } else{ helper.getView<ImageButton>(R.id.imgbtn_card_gif).visibility = View.INVISIBLE } } ImageLoadBuilder.Start(context,img,imgUrl).setProgressBarImage(progressLoading).build() } override fun requestListData(page: Int): Subscription { val request = RetrofitClient.createService(UserAPI::class.java) var result : Observable<ListPinsBean> if (page == 0){ result = request.httpsUserLikePinsRx(mAuthorization!!,mKey,mLimit) } else{ result = request.httpsUserLikePinsMaxRx(mAuthorization!!,mKey,maxId, mLimit) } return result.map { it.pins }.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(object: Subscriber<List<PinsMainInfo>>(){ override fun onCompleted() { } override fun onError(e: Throwable?) { e?.printStackTrace() loadError() checkException(e) } override fun onNext(t: List<PinsMainInfo>?) { if (t == null){ loadError() return } if( t!!.size > 0 ){ maxId = t!!.last()!!.pin_id } loadSuccess(t!!) if (t!!.size < mLimit){ setNoMoreData() } } }) } }
mit
3c1dc90313043af9eb6ffc01ad49480e
36.849462
110
0.634659
4.580351
false
false
false
false
sksamuel/ktest
kotest-assertions/kotest-assertions-core/src/commonMain/kotlin/io/kotest/matchers/collections/decreasing.kt
1
6138
package io.kotest.matchers.collections import io.kotest.assertions.show.show import io.kotest.matchers.Matcher import io.kotest.matchers.MatcherResult import io.kotest.matchers.should import io.kotest.matchers.shouldNot fun <T : Comparable<T>> Iterable<T>.shouldBeMonotonicallyDecreasing(): Iterable<T> { toList().shouldBeMonotonicallyDecreasing() return this } fun <T : Comparable<T>> Array<T>.shouldBeMonotonicallyDecreasing(): Array<T> { asList().shouldBeMonotonicallyDecreasing() return this } fun <T : Comparable<T>> List<T>.shouldBeMonotonicallyDecreasing(): List<T> { this should beMonotonicallyDecreasing() return this } fun <T : Comparable<T>> Iterable<T>.shouldNotBeMonotonicallyDecreasing(): Iterable<T> { toList().shouldNotBeMonotonicallyDecreasing() return this } fun <T : Comparable<T>> Array<T>.shouldNotBeMonotonicallyDecreasing(): Array<T> { asList().shouldNotBeMonotonicallyDecreasing() return this } fun <T : Comparable<T>> List<T>.shouldNotBeMonotonicallyDecreasing(): List<T> { this shouldNot beMonotonicallyDecreasing<T>() return this } fun <T> List<T>.shouldBeMonotonicallyDecreasingWith(comparator: Comparator<in T>): List<T> { this should beMonotonicallyDecreasingWith(comparator) return this } fun <T> Iterable<T>.shouldBeMonotonicallyDecreasingWith(comparator: Comparator<in T>): Iterable<T> { toList().shouldBeMonotonicallyDecreasingWith(comparator) return this } fun <T> Array<T>.shouldBeMonotonicallyDecreasingWith(comparator: Comparator<in T>): Array<T> { asList().shouldBeMonotonicallyDecreasingWith(comparator) return this } fun <T> List<T>.shouldNotBeMonotonicallyDecreasingWith(comparator: Comparator<in T>): List<T> { this shouldNot beMonotonicallyDecreasingWith(comparator) return this } fun <T> Iterable<T>.shouldNotBeMonotonicallyDecreasingWith(comparator: Comparator<in T>): Iterable<T> { toList().shouldNotBeMonotonicallyDecreasingWith(comparator) return this } fun <T> Array<T>.shouldNotBeMonotonicallyDecreasingWith(comparator: Comparator<in T>): Array<T> { asList().shouldNotBeMonotonicallyDecreasingWith(comparator) return this } fun <T : Comparable<T>> Iterable<T>.shouldBeStrictlyDecreasing() = toList().shouldBeStrictlyDecreasing() fun <T : Comparable<T>> List<T>.shouldBeStrictlyDecreasing() = this should beStrictlyDecreasing<T>() fun <T : Comparable<T>> Iterable<T>.shouldNotBeStrictlyDecreasing() = toList().shouldNotBeStrictlyDecreasing() fun <T : Comparable<T>> List<T>.shouldNotBeStrictlyDecreasing() = this shouldNot beStrictlyDecreasing<T>() fun <T> List<T>.shouldBeStrictlyDecreasingWith(comparator: Comparator<in T>) = this should beStrictlyDecreasingWith(comparator) fun <T> Iterable<T>.shouldBeStrictlyDecreasingWith(comparator: Comparator<in T>) = toList().shouldBeStrictlyDecreasingWith(comparator) fun <T> Array<T>.shouldBeStrictlyDecreasingWith(comparator: Comparator<in T>): Array<T> { asList().shouldBeStrictlyDecreasingWith(comparator) return this } fun <T> List<T>.shouldNotBeStrictlyDecreasingWith(comparator: Comparator<in T>) = this shouldNot beStrictlyDecreasingWith(comparator) fun <T> Iterable<T>.shouldNotBeStrictlyDecreasingWith(comparator: Comparator<in T>) = toList().shouldNotBeStrictlyDecreasingWith(comparator) fun <T> Array<T>.shouldNotBeStrictlyDecreasingWith(comparator: Comparator<in T>) = asList().shouldNotBeStrictlyDecreasingWith(comparator) fun <T : Comparable<T>> beMonotonicallyDecreasing(): Matcher<List<T>> = monotonicallyDecreasing() fun <T : Comparable<T>> monotonicallyDecreasing(): Matcher<List<T>> = object : Matcher<List<T>> { override fun test(value: List<T>): MatcherResult { return testMonotonicallyDecreasingWith(value) { a, b -> a.compareTo(b) } } } fun <T> beMonotonicallyDecreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = monotonicallyDecreasingWith(comparator) fun <T> monotonicallyDecreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = object : Matcher<List<T>> { override fun test(value: List<T>): MatcherResult { return testMonotonicallyDecreasingWith(value, comparator) } } private fun <T> testMonotonicallyDecreasingWith(value: List<T>, comparator: Comparator<in T>): MatcherResult { val failure = value.zipWithNext().withIndex().find { (_, pair) -> comparator.compare(pair.first, pair.second) < 0 } val snippet = value.show().value val elementMessage = when (failure) { null -> "" else -> ". Element ${failure.value.second} at index ${failure.index + 1} was not monotonically decreased from previous element." } return MatcherResult( failure == null, { "List [$snippet] should be monotonically decreasing$elementMessage" }, { "List [$snippet] should not be monotonically decreasing" } ) } fun <T : Comparable<T>> beStrictlyDecreasing(): Matcher<List<T>> = strictlyDecreasing() fun <T : Comparable<T>> strictlyDecreasing(): Matcher<List<T>> = object : Matcher<List<T>> { override fun test(value: List<T>): MatcherResult { return testStrictlyDecreasingWith(value) { a, b -> a.compareTo(b) } } } fun <T> beStrictlyDecreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = strictlyDecreasingWith(comparator) fun <T> strictlyDecreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = object : Matcher<List<T>> { override fun test(value: List<T>): MatcherResult { return testStrictlyDecreasingWith(value, comparator) } } private fun <T> testStrictlyDecreasingWith(value: List<T>, comparator: Comparator<in T>): MatcherResult { val failure = value.zipWithNext().withIndex().find { (_, pair) -> comparator.compare(pair.first, pair.second) <= 0 } val snippet = value.show().value val elementMessage = when (failure) { null -> "" else -> ". Element ${failure.value.second} at index ${failure.index + 1} was not strictly decreased from previous element." } return MatcherResult( failure == null, { "List [$snippet] should be strictly decreasing$elementMessage" }, { "List [$snippet] should not be strictly decreasing" } ) }
mit
07dccfa3b5532ee336d791677afe7174
38.6
134
0.743565
4.286313
false
true
false
false
kirimin/mitsumine
app/src/main/java/me/kirimin/mitsumine/feed/FeedUseCase.kt
1
2531
package me.kirimin.mitsumine.feed import android.content.Context import android.preference.PreferenceManager import me.kirimin.mitsumine.R import me.kirimin.mitsumine._common.database.FeedDAO import me.kirimin.mitsumine._common.database.NGWordDAO import me.kirimin.mitsumine._common.domain.model.Feed import me.kirimin.mitsumine._common.domain.enums.Category import me.kirimin.mitsumine._common.domain.enums.Type import me.kirimin.mitsumine._common.network.repository.BookmarkCountRepository import me.kirimin.mitsumine._common.network.repository.EntryRepository import me.kirimin.mitsumine._common.network.repository.FeedRepository import rx.Observable import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import javax.inject.Inject class FeedUseCase @Inject constructor(val context: Context, val feedRepository: FeedRepository, val entryRepository: EntryRepository, val bookmarkCountRepository: BookmarkCountRepository) { val isUseBrowserSettingEnable: Boolean get() = PreferenceManager.getDefaultSharedPreferences(context).getBoolean(context.getString(R.string.key_use_browser_to_comment_list), false) val isShareWithTitleSettingEnable: Boolean get() = PreferenceManager.getDefaultSharedPreferences(context).getBoolean(context.getString(R.string.key_is_share_with_title), false) val ngWordList: List<String> get() = NGWordDAO.findAll() var isFirstBoot get() = PreferenceManager.getDefaultSharedPreferences(context).getBoolean(context.getString(R.string.key_is_first_boot), true) set(value) = PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(context.getString(R.string.key_is_first_boot), value).apply() fun requestMainFeed(category: Category, type: Type) = feedRepository.requestFeed(category, type) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread())!! fun requestKeywordFeed(keyword: String) = feedRepository.requestKeywordFeed(keyword) fun requestUserFeed(user: String) = feedRepository.requestUserFeed(user) fun requestReadFeed() = feedRepository.requestReadFeed() fun requestReadLatterFeed() = feedRepository.requestReadLatterFeed() fun requestTagList(url: String) = entryRepository.requestEntryInfo(url).map { it.tagListString }!! fun requestBookmarkCount(url: String) = bookmarkCountRepository.requestBookmarkCount(url) fun saveFeed(feed: Feed) { FeedDAO.save(feed) } }
apache-2.0
003c442d8dfa41d2a55e8399d7746be7
43.421053
155
0.781509
4.363793
false
false
false
false
aosp-mirror/platform_frameworks_support
room/compiler/src/main/kotlin/androidx/room/processor/ProcessorErrors.kt
1
26729
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.processor import androidx.room.Delete import androidx.room.Insert import androidx.room.Query import androidx.room.RawQuery import androidx.room.Update import androidx.room.ext.RoomTypeNames import androidx.room.ext.SupportDbTypeNames import androidx.room.parser.SQLTypeAffinity import androidx.room.vo.CustomTypeConverter import androidx.room.vo.Field import com.squareup.javapoet.TypeName object ProcessorErrors { private fun String.trim(): String { return this.trimIndent().replace("\n", " ") } val MISSING_QUERY_ANNOTATION = "Query methods must be annotated with ${Query::class.java}" val MISSING_INSERT_ANNOTATION = "Insertion methods must be annotated with ${Insert::class.java}" val MISSING_DELETE_ANNOTATION = "Deletion methods must be annotated with ${Delete::class.java}" val MISSING_UPDATE_ANNOTATION = "Update methods must be annotated with ${Update::class.java}" val MISSING_RAWQUERY_ANNOTATION = "RawQuery methods must be annotated with" + " ${RawQuery::class.java}" val INVALID_ON_CONFLICT_VALUE = "On conflict value must be one of @OnConflictStrategy values." val INVALID_INSERTION_METHOD_RETURN_TYPE = "Methods annotated with @Insert can return either" + " void, long, Long, long[], Long[] or List<Long>." val TRANSACTION_REFERENCE_DOCS = "https://developer.android.com/reference/android/arch/" + "persistence/room/Transaction.html" fun insertionMethodReturnTypeMismatch(definedReturn: TypeName, expectedReturnTypes: List<TypeName>): String { return "Method returns $definedReturn but it should return one of the following: `" + expectedReturnTypes.joinToString(", ") + "`. If you want to return the list of" + " row ids from the query, your insertion method can receive only 1 parameter." } val ABSTRACT_METHOD_IN_DAO_MISSING_ANY_ANNOTATION = "Abstract method in DAO must be annotated" + " with ${Query::class.java} AND ${Insert::class.java}" val INVALID_ANNOTATION_COUNT_IN_DAO_METHOD = "An abstract DAO method must be" + " annotated with one and only one of the following annotations: " + DaoProcessor.PROCESSED_ANNOTATIONS.joinToString(",") { it.java.simpleName } val CANNOT_RESOLVE_RETURN_TYPE = "Cannot resolve return type for %s" val CANNOT_USE_UNBOUND_GENERICS_IN_QUERY_METHODS = "Cannot use unbound generics in query" + " methods. It must be bound to a type through base Dao class." val CANNOT_USE_UNBOUND_GENERICS_IN_INSERTION_METHODS = "Cannot use unbound generics in" + " insertion methods. It must be bound to a type through base Dao class." val CANNOT_USE_UNBOUND_GENERICS_IN_ENTITY_FIELDS = "Cannot use unbound fields in entities." val CANNOT_USE_UNBOUND_GENERICS_IN_DAO_CLASSES = "Cannot use unbound generics in Dao classes." + " If you are trying to create a base DAO, create a normal class, extend it with type" + " params then mark the subclass with @Dao." val CANNOT_FIND_GETTER_FOR_FIELD = "Cannot find getter for field." val CANNOT_FIND_SETTER_FOR_FIELD = "Cannot find setter for field." val MISSING_PRIMARY_KEY = "An entity must have at least 1 field annotated with @PrimaryKey" val AUTO_INCREMENTED_PRIMARY_KEY_IS_NOT_INT = "If a primary key is annotated with" + " autoGenerate, its type must be int, Integer, long or Long." val AUTO_INCREMENT_EMBEDDED_HAS_MULTIPLE_FIELDS = "When @PrimaryKey annotation is used on a" + " field annotated with @Embedded, the embedded class should have only 1 field." fun multiplePrimaryKeyAnnotations(primaryKeys: List<String>): String { return """ You cannot have multiple primary keys defined in an Entity. If you want to declare a composite primary key, you should use @Entity#primaryKeys and not use @PrimaryKey. Defined Primary Keys: ${primaryKeys.joinToString(", ")}""".trim() } fun primaryKeyColumnDoesNotExist(columnName: String, allColumns: List<String>): String { return "$columnName referenced in the primary key does not exists in the Entity." + " Available column names:${allColumns.joinToString(", ")}" } val DAO_MUST_BE_AN_ABSTRACT_CLASS_OR_AN_INTERFACE = "Dao class must be an abstract class or" + " an interface" val DATABASE_MUST_BE_ANNOTATED_WITH_DATABASE = "Database must be annotated with @Database" val DAO_MUST_BE_ANNOTATED_WITH_DAO = "Dao class must be annotated with @Dao" fun daoMustHaveMatchingConstructor(daoName: String, dbName: String): String { return """ $daoName needs to have either an empty constructor or a constructor that takes $dbName as its only parameter. """.trim() } val ENTITY_MUST_BE_ANNOTATED_WITH_ENTITY = "Entity class must be annotated with @Entity" val DATABASE_ANNOTATION_MUST_HAVE_LIST_OF_ENTITIES = "@Database annotation must specify list" + " of entities" val COLUMN_NAME_CANNOT_BE_EMPTY = "Column name cannot be blank. If you don't want to set it" + ", just remove the @ColumnInfo annotation or use @ColumnInfo.INHERIT_FIELD_NAME." val ENTITY_TABLE_NAME_CANNOT_BE_EMPTY = "Entity table name cannot be blank. If you don't want" + " to set it, just remove the tableName property." val CANNOT_BIND_QUERY_PARAMETER_INTO_STMT = "Query method parameters should either be a" + " type that can be converted into a database column or a List / Array that contains" + " such type. You can consider adding a Type Adapter for this." val QUERY_PARAMETERS_CANNOT_START_WITH_UNDERSCORE = "Query/Insert method parameters cannot " + "start with underscore (_)." val CANNOT_FIND_QUERY_RESULT_ADAPTER = "Not sure how to convert a Cursor to this method's " + "return type" val INSERTION_DOES_NOT_HAVE_ANY_PARAMETERS_TO_INSERT = "Method annotated with" + " @Insert but does not have any parameters to insert." val DELETION_MISSING_PARAMS = "Method annotated with" + " @Delete but does not have any parameters to delete." val UPDATE_MISSING_PARAMS = "Method annotated with" + " @Update but does not have any parameters to update." val TRANSACTION_METHOD_MODIFIERS = "Method annotated with @Transaction must not be " + "private, final, or abstract. It can be abstract only if the method is also" + " annotated with @Query." val TRANSACTION_MISSING_ON_RELATION = "The return value includes a Pojo with a @Relation." + " It is usually desired to annotate this method with @Transaction to avoid" + " possibility of inconsistent results between the Pojo and its relations. See " + TRANSACTION_REFERENCE_DOCS + " for details." val CANNOT_FIND_ENTITY_FOR_SHORTCUT_QUERY_PARAMETER = "Type of the parameter must be a class " + "annotated with @Entity or a collection/array of it." val DB_MUST_EXTEND_ROOM_DB = "Classes annotated with @Database should extend " + RoomTypeNames.ROOM_DB val LIVE_DATA_QUERY_WITHOUT_SELECT = "LiveData return type can only be used with SELECT" + " queries." val OBSERVABLE_QUERY_NOTHING_TO_OBSERVE = "Observable query return type (LiveData, Flowable" + ", DataSource, DataSourceFactory etc) can only be used with SELECT queries that" + " directly or indirectly (via @Relation, for example) access at least one table. For" + " @RawQuery, you should specify the list of tables to be observed via the" + " observedEntities field." val RECURSIVE_REFERENCE_DETECTED = "Recursive referencing through @Embedded and/or @Relation " + "detected: %s" private val TOO_MANY_MATCHING_GETTERS = "Ambiguous getter for %s. All of the following " + "match: %s. You can @Ignore the ones that you don't want to match." fun tooManyMatchingGetters(field: Field, methodNames: List<String>): String { return TOO_MANY_MATCHING_GETTERS.format(field, methodNames.joinToString(", ")) } private val TOO_MANY_MATCHING_SETTERS = "Ambiguous setter for %s. All of the following " + "match: %s. You can @Ignore the ones that you don't want to match." fun tooManyMatchingSetter(field: Field, methodNames: List<String>): String { return TOO_MANY_MATCHING_SETTERS.format(field, methodNames.joinToString(", ")) } val CANNOT_FIND_COLUMN_TYPE_ADAPTER = "Cannot figure out how to save this field into" + " database. You can consider adding a type converter for it." val CANNOT_FIND_STMT_BINDER = "Cannot figure out how to bind this field into a statement." val CANNOT_FIND_CURSOR_READER = "Cannot figure out how to read this field from a cursor." private val MISSING_PARAMETER_FOR_BIND = "Each bind variable in the query must have a" + " matching method parameter. Cannot find method parameters for %s." fun missingParameterForBindVariable(bindVarName: List<String>): String { return MISSING_PARAMETER_FOR_BIND.format(bindVarName.joinToString(", ")) } private val UNUSED_QUERY_METHOD_PARAMETER = "Unused parameter%s: %s" fun unusedQueryMethodParameter(unusedParams: List<String>): String { return UNUSED_QUERY_METHOD_PARAMETER.format( if (unusedParams.size > 1) "s" else "", unusedParams.joinToString(",")) } private val DUPLICATE_TABLES = "Table name \"%s\" is used by multiple entities: %s" fun duplicateTableNames(tableName: String, entityNames: List<String>): String { return DUPLICATE_TABLES.format(tableName, entityNames.joinToString(", ")) } val DELETION_METHODS_MUST_RETURN_VOID_OR_INT = "Deletion methods must either return void or" + " return int (the number of deleted rows)." val UPDATE_METHODS_MUST_RETURN_VOID_OR_INT = "Update methods must either return void or" + " return int (the number of updated rows)." val DAO_METHOD_CONFLICTS_WITH_OTHERS = "Dao method has conflicts." fun duplicateDao(dao: TypeName, methodNames: List<String>): String { return """ All of these functions [${methodNames.joinToString(", ")}] return the same DAO class [$dao]. A database can use a DAO only once so you should remove ${methodNames.size - 1} of these conflicting DAO methods. If you are implementing any of these to fulfill an interface, don't make it abstract, instead, implement the code that calls the other one. """.trim() } fun pojoMissingNonNull(pojoTypeName: TypeName, missingPojoFields: List<String>, allQueryColumns: List<String>): String { return """ The columns returned by the query does not have the fields [${missingPojoFields.joinToString(",")}] in $pojoTypeName even though they are annotated as non-null or primitive. Columns returned by the query: [${allQueryColumns.joinToString(",")}] """.trim() } fun cursorPojoMismatch(pojoTypeName: TypeName, unusedColumns: List<String>, allColumns: List<String>, unusedFields: List<Field>, allFields: List<Field>): String { val unusedColumnsWarning = if (unusedColumns.isNotEmpty()) { """ The query returns some columns [${unusedColumns.joinToString(", ")}] which are not use by $pojoTypeName. You can use @ColumnInfo annotation on the fields to specify the mapping. """.trim() } else { "" } val unusedFieldsWarning = if (unusedFields.isNotEmpty()) { """ $pojoTypeName has some fields [${unusedFields.joinToString(", ") { it.columnName }}] which are not returned by the query. If they are not supposed to be read from the result, you can mark them with @Ignore annotation. """.trim() } else { "" } return """ $unusedColumnsWarning $unusedFieldsWarning You can suppress this warning by annotating the method with @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH). Columns returned by the query: ${allColumns.joinToString(", ")}. Fields in $pojoTypeName: ${allFields.joinToString(", ") { it.columnName }}. """.trim() } val TYPE_CONVERTER_UNBOUND_GENERIC = "Cannot use unbound generics in Type Converters." val TYPE_CONVERTER_BAD_RETURN_TYPE = "Invalid return type for a type converter." val TYPE_CONVERTER_MUST_RECEIVE_1_PARAM = "Type converters must receive 1 parameter." val TYPE_CONVERTER_EMPTY_CLASS = "Class is referenced as a converter but it does not have any" + " converter methods." val TYPE_CONVERTER_MISSING_NOARG_CONSTRUCTOR = "Classes that are used as TypeConverters must" + " have no-argument public constructors." val TYPE_CONVERTER_MUST_BE_PUBLIC = "Type converters must be public." fun duplicateTypeConverters(converters: List<CustomTypeConverter>): String { return "Multiple methods define the same conversion. Conflicts with these:" + " ${converters.joinToString(", ") { it.toString() }}" } // TODO must print field paths. val POJO_FIELD_HAS_DUPLICATE_COLUMN_NAME = "Field has non-unique column name." fun pojoDuplicateFieldNames(columnName: String, fieldPaths: List<String>): String { return "Multiple fields have the same columnName: $columnName." + " Field names: ${fieldPaths.joinToString(", ")}." } fun embeddedPrimaryKeyIsDropped(entityQName: String, fieldName: String): String { return "Primary key constraint on $fieldName is ignored when being merged into " + entityQName } val INDEX_COLUMNS_CANNOT_BE_EMPTY = "List of columns in an index cannot be empty" fun indexColumnDoesNotExist(columnName: String, allColumns: List<String>): String { return "$columnName referenced in the index does not exists in the Entity." + " Available column names:${allColumns.joinToString(", ")}" } fun duplicateIndexInEntity(indexName: String): String { return "There are multiple indices with name $indexName. This happen if you've declared" + " the same index multiple times or different indices have the same name. See" + " @Index documentation for details." } fun duplicateIndexInDatabase(indexName: String, indexPaths: List<String>): String { return "There are multiple indices with name $indexName. You should rename " + "${indexPaths.size - 1} of these to avoid the conflict:" + "${indexPaths.joinToString(", ")}." } fun droppedEmbeddedFieldIndex(fieldPath: String, grandParent: String): String { return "The index will be dropped when being merged into $grandParent" + "($fieldPath). You must re-declare it in $grandParent if you want to index this" + " field in $grandParent." } fun droppedEmbeddedIndex(entityName: String, fieldPath: String, grandParent: String): String { return "Indices defined in $entityName will be dropped when it is merged into" + " $grandParent ($fieldPath). You can re-declare them in $grandParent." } fun droppedSuperClassIndex(childEntity: String, superEntity: String): String { return "Indices defined in $superEntity will NOT be re-used in $childEntity. If you want" + " to inherit them, you must re-declare them in $childEntity." + " Alternatively, you can set inheritSuperIndices to true in the @Entity annotation." } fun droppedSuperClassFieldIndex(fieldName: String, childEntity: String, superEntity: String): String { return "Index defined on field `$fieldName` in $superEntity will NOT be re-used in" + " $childEntity. " + "If you want to inherit it, you must re-declare it in $childEntity." + " Alternatively, you can set inheritSuperIndices to true in the @Entity annotation." } val RELATION_NOT_COLLECTION = "Fields annotated with @Relation must be a List or Set." fun relationCannotFindEntityField(entityName: String, columnName: String, availableColumns: List<String>): String { return "Cannot find the child entity column `$columnName` in $entityName." + " Options: ${availableColumns.joinToString(", ")}" } fun relationCannotFindParentEntityField(entityName: String, columnName: String, availableColumns: List<String>): String { return "Cannot find the parent entity column `$columnName` in $entityName." + " Options: ${availableColumns.joinToString(", ")}" } val RELATION_IN_ENTITY = "Entities cannot have relations." val CANNOT_FIND_TYPE = "Cannot find type." fun relationAffinityMismatch(parentColumn: String, childColumn: String, parentAffinity: SQLTypeAffinity?, childAffinity: SQLTypeAffinity?): String { return """ The affinity of parent column ($parentColumn : $parentAffinity) does not match the type affinity of the child column ($childColumn : $childAffinity). """.trim() } val CANNOT_USE_MORE_THAN_ONE_POJO_FIELD_ANNOTATION = "A field can be annotated with only" + " one of the following:" + PojoProcessor.PROCESSED_ANNOTATIONS.joinToString(",") { it.java.simpleName } fun relationBadProject(entityQName: String, missingColumnNames: List<String>, availableColumnNames: List<String>): String { return """ $entityQName does not have the following columns: ${missingColumnNames.joinToString(",")}. Available columns are: ${availableColumnNames.joinToString(",")} """.trim() } val MISSING_SCHEMA_EXPORT_DIRECTORY = "Schema export directory is not provided to the" + " annotation processor so we cannot export the schema. You can either provide" + " `room.schemaLocation` annotation processor argument OR set exportSchema to false." val INVALID_FOREIGN_KEY_ACTION = "Invalid foreign key action. It must be one of the constants" + " defined in ForeignKey.Action" fun foreignKeyNotAnEntity(className: String): String { return """ Classes referenced in Foreign Key annotations must be @Entity classes. $className is not an entity """.trim() } val FOREIGN_KEY_CANNOT_FIND_PARENT = "Cannot find parent entity class." fun foreignKeyChildColumnDoesNotExist(columnName: String, allColumns: List<String>): String { return "($columnName) referenced in the foreign key does not exists in the Entity." + " Available column names:${allColumns.joinToString(", ")}" } fun foreignKeyParentColumnDoesNotExist(parentEntity: String, missingColumn: String, allColumns: List<String>): String { return "($missingColumn) does not exist in $parentEntity. Available columns are" + " ${allColumns.joinToString(",")}" } val FOREIGN_KEY_EMPTY_CHILD_COLUMN_LIST = "Must specify at least 1 column name for the child" val FOREIGN_KEY_EMPTY_PARENT_COLUMN_LIST = "Must specify at least 1 column name for the parent" fun foreignKeyColumnNumberMismatch( childColumns: List<String>, parentColumns: List<String>): String { return """ Number of child columns in foreign key must match number of parent columns. Child reference has ${childColumns.joinToString(",")} and parent reference has ${parentColumns.joinToString(",")} """.trim() } fun foreignKeyMissingParentEntityInDatabase(parentTable: String, childEntity: String): String { return """ $parentTable table referenced in the foreign keys of $childEntity does not exist in the database. Maybe you forgot to add the referenced entity in the entities list of the @Database annotation?""".trim() } fun foreignKeyMissingIndexInParent(parentEntity: String, parentColumns: List<String>, childEntity: String, childColumns: List<String>): String { return """ $childEntity has a foreign key (${childColumns.joinToString(",")}) that references $parentEntity (${parentColumns.joinToString(",")}) but $parentEntity does not have a unique index on those columns nor the columns are its primary key. SQLite requires having a unique constraint on referenced parent columns so you must add a unique index to $parentEntity that has (${parentColumns.joinToString(",")}) column(s). """.trim() } fun foreignKeyMissingIndexInChildColumns(childColumns: List<String>): String { return """ (${childColumns.joinToString(",")}) column(s) reference a foreign key but they are not part of an index. This may trigger full table scans whenever parent table is modified so you are highly advised to create an index that covers these columns. """.trim() } fun foreignKeyMissingIndexInChildColumn(childColumn: String): String { return """ $childColumn column references a foreign key but it is not part of an index. This may trigger full table scans whenever parent table is modified so you are highly advised to create an index that covers this column. """.trim() } fun shortcutEntityIsNotInDatabase(database: String, dao: String, entity: String): String { return """ $dao is part of $database but this entity is not in the database. Maybe you forgot to add $entity to the entities section of the @Database? """.trim() } val MISSING_ROOM_GUAVA_ARTIFACT = "To use Guava features, you must add `guava`" + " artifact from Room as a dependency. androidx.room:guava:<version>" val MISSING_ROOM_RXJAVA2_ARTIFACT = "To use RxJava2 features, you must add `rxjava2`" + " artifact from Room as a dependency. androidx.room:rxjava2:<version>" fun ambigiousConstructor( pojo: String, paramName: String, matchingFields: List<String>): String { return """ Ambiguous constructor. The parameter ($paramName) in $pojo matches multiple fields: [${matchingFields.joinToString(",")}]. If you don't want to use this constructor, you can annotate it with @Ignore. If you want Room to use this constructor, you can rename the parameters to exactly match the field name to fix the ambiguity. """.trim() } val MISSING_POJO_CONSTRUCTOR = """ Entities and Pojos must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type). """.trim() val TOO_MANY_POJO_CONSTRUCTORS = """ Room cannot pick a constructor since multiple constructors are suitable. Try to annotate unwanted constructors with @Ignore. """.trim() val TOO_MANY_POJO_CONSTRUCTORS_CHOOSING_NO_ARG = """ There are multiple good constructors and Room will pick the no-arg constructor. You can use the @Ignore annotation to eliminate unwanted constructors. """.trim() val RELATION_CANNOT_BE_CONSTRUCTOR_PARAMETER = """ Fields annotated with @Relation cannot be constructor parameters. These values are fetched after the object is constructed. """.trim() val PAGING_SPECIFY_DATA_SOURCE_TYPE = "For now, Room only supports PositionalDataSource class." fun primaryKeyNull(field: String): String { return "You must annotate primary keys with @NonNull. \"$field\" is nullable. SQLite " + "considers this a " + "bug and Room does not allow it. See SQLite docs for details: " + "https://www.sqlite.org/lang_createtable.html" } val INVALID_COLUMN_NAME = "Invalid column name. Room does not allow using ` or \" in column" + " names" val INVALID_TABLE_NAME = "Invalid table name. Room does not allow using ` or \" in table names" val RAW_QUERY_BAD_PARAMS = "RawQuery methods should have 1 and only 1 parameter with type" + " String or SupportSQLiteQuery" val RAW_QUERY_BAD_RETURN_TYPE = "RawQuery methods must return a non-void type." fun rawQueryBadEntity(typeName: TypeName): String { return """ observedEntities field in RawQuery must either reference a class that is annotated with @Entity or it should reference a Pojo that either contains @Embedded fields that are annotated with @Entity or @Relation fields. $typeName does not have these properties, did you mean another class? """.trim() } val RAW_QUERY_STRING_PARAMETER_REMOVED = "RawQuery does not allow passing a string anymore." + " Please use ${SupportDbTypeNames.QUERY}." }
apache-2.0
bee846c32797bab2b87bf222c3d6f0f9
50.401923
100
0.65255
4.797021
false
false
false
false
koma-im/koma
src/main/kotlin/link/continuum/desktop/gui/icon/avatar/initial.kt
1
3768
package link.continuum.desktop.gui.icon.avatar import javafx.geometry.Insets import javafx.geometry.Pos import javafx.scene.layout.Background import javafx.scene.layout.BackgroundFill import javafx.scene.layout.CornerRadii import javafx.scene.paint.Color import javafx.scene.text.Text import link.continuum.desktop.gui.* import link.continuum.desktop.util.debugAssertUiThread import mu.KotlinLogging import java.util.* import kotlin.streams.toList private val logger = KotlinLogging.logger {} class InitialIcon( ) { private val radii = CornerRadii( 0.2, true) private val charL = Text().apply { fill = Color.WHITE } private val charR = Text().apply { fill = Color.WHITE } private val charC = Text().apply { fill = Color.WHITE } private val two = HBox().apply { style { fontSize = 1.em } alignment = Pos.CENTER vbox { alignment = Pos.CENTER_RIGHT add(charL) } vbox { style { prefWidth = 0.1.em } } vbox { alignment = Pos.CENTER_LEFT add(charR) } } private val one = HBox().apply { alignment = Pos.CENTER children.add(charC) style { fontSize = 1.8.em } } val root = StackPane().apply { style = avStyle } fun show() { debugAssertUiThread() this.root.isManaged = true this.root.isVisible = true } fun hide() { this.root.isManaged = false this.root.isVisible = false } fun updateColor(color: Color) { debugAssertUiThread() root.background = backgrounds.computeIfAbsent(color) { logger.debug { "initial icon $charL $charR $color" } Background(BackgroundFill(it, radii, Insets.EMPTY)) } } fun updateItem(charL: String, charR: String, color: Color) { updateColor(color) updateCharPair(charL, charR) } fun updateCharPair(charL: String, charR: String) { debugAssertUiThread() this.charL.text = charL this.charR.text = charR root.children.setAll(two) } fun updateCenter(char: String, color: Color) { updateColor(color) updateCharSingle(char) } fun updateCharSingle(char: String) { debugAssertUiThread() charC.text = char root.children.setAll(one) } fun updateString(input: String) { val (c1, c2) = extractKeyChar(input) if (c2 != null) { updateCharPair(c1, c2) } else { updateCharSingle(c1) } } fun updateItem(input: String, color: Color) { val (c1, c2) = extractKeyChar(input) if (c2 != null) { updateItem(c1, c2, color) } else { updateCenter(c1, color) } } companion object { private val backgrounds = WeakHashMap<Color, Background>() private val avStyle = StyleBuilder().apply { val s = 2.em prefHeight = s prefWidth = s fontFamily = GenericFontFamily.sansSerif }.toString() } } internal fun extractKeyChar(input: String): Pair<String, String?> { val trim = input.replace("(IRC)", "").trim() val cps = trim.codePoints().toList() val ideo = cps.find { Character.isIdeographic(it) } if (ideo != null) { return String(Character.toChars(ideo)) to null } val first = cps.firstOrNull()?.let { String(Character.toChars(it)) } ?: "" val i2 = cps.indexOfFirst { Character.isSpaceChar(it) }.let { if (it < 0) null else it + 1} ?: 1 val second = cps.getOrNull(i2)?.let { String(Character.toChars(it)) } return first to second }
gpl-3.0
243e2de17760ff7b392d4ef8a589b453
26.50365
101
0.589172
3.896587
false
false
false
false
hazuki0x0/YuzuBrowser
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/reader/Decoder.kt
1
2696
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.legacy.reader import android.content.Context import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.os.Build import android.text.Html import android.text.Spanned import android.text.TextUtils import android.webkit.WebSettings import jp.hazuki.yuzubrowser.core.utility.log.Logger import jp.hazuki.yuzubrowser.core.utility.utils.ImageUtils import jp.hazuki.yuzubrowser.download.getImage import jp.hazuki.yuzubrowser.legacy.reader.snacktory.HtmlFetcher import okhttp3.OkHttpClient import java.util.* fun OkHttpClient.decodeToReaderData(context: Context, url: String, userAgent: String?): ReaderData? { val fetcher = HtmlFetcher() if (userAgent.isNullOrEmpty()) { fetcher.userAgent = WebSettings.getDefaultUserAgent(context) } else { fetcher.userAgent = userAgent } fetcher.referrer = url val locale = Locale.getDefault() val language = locale.language + "-" + locale.country if (language.length >= 5) { fetcher.language = language } try { val result = fetcher.fetchAndExtract(this, url, 2500, true) if (!TextUtils.isEmpty(result.text)) { val html: Spanned = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Html.fromHtml(result.text, Html.FROM_HTML_MODE_LEGACY, Html.ImageGetter { getImage(context, it, url, userAgent) }, null) } else { @Suppress("DEPRECATION") Html.fromHtml(result.text, Html.ImageGetter { getImage(context, it, url, userAgent) }, null) } return ReaderData(result.title, html) } } catch (e: Exception) { e.printStackTrace() } catch (e: OutOfMemoryError) { System.gc() Logger.w("reader", e, "Out of memory") } return null } private fun OkHttpClient.getImage(context: Context, imageUrl: String, url: String, userAgent: String?): Drawable { val drawable = ImageUtils.getDrawable(context, getImage(imageUrl, userAgent, url)) return drawable ?: ColorDrawable(0) }
apache-2.0
37656b29115a63bbc8930f5ed3aadc4e
35.931507
136
0.702151
4.166924
false
false
false
false
hazuki0x0/YuzuBrowser
module/bookmark/src/main/java/jp/hazuki/yuzubrowser/bookmark/view/BookmarkActivity.kt
1
2737
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.bookmark.view import android.content.Intent import android.os.Build import android.os.Bundle import android.view.MenuItem import android.view.WindowInsets import android.view.WindowManager import androidx.fragment.app.commit import dagger.hilt.android.AndroidEntryPoint import jp.hazuki.bookmark.R import jp.hazuki.yuzubrowser.ui.INTENT_EXTRA_MODE_FULLSCREEN import jp.hazuki.yuzubrowser.ui.INTENT_EXTRA_MODE_ORIENTATION import jp.hazuki.yuzubrowser.ui.app.LongPressFixActivity import jp.hazuki.yuzubrowser.ui.settings.AppPrefs @AndroidEntryPoint class BookmarkActivity : LongPressFixActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.fragment_base) val intent = intent var pickMode = false var itemId: Long = -1 var fullscreen = AppPrefs.fullscreen.get() var orientation = AppPrefs.oritentation.get() if (intent != null) { pickMode = Intent.ACTION_PICK == intent.action itemId = intent.getLongExtra("id", -1) fullscreen = intent.getBooleanExtra(INTENT_EXTRA_MODE_FULLSCREEN, fullscreen) orientation = intent.getIntExtra(INTENT_EXTRA_MODE_ORIENTATION, orientation) } if (fullscreen) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { window.insetsController?.hide(WindowInsets.Type.statusBars()) } else { @Suppress("DEPRECATION") window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) } } requestedOrientation = orientation supportFragmentManager.commit { replace(R.id.container, BookmarkFragment(pickMode, itemId)) } } override fun onBackKeyLongPressed() { finish() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { finish() return true } } return super.onOptionsItemSelected(item) } }
apache-2.0
1f3f1585837be562aab7435463ed9411
32.378049
89
0.680307
4.554077
false
false
false
false
dtretyakov/teamcity-rust
plugin-rust-agent/src/main/kotlin/jetbrains/buildServer/rust/RustupToolchainBuildService.kt
1
2616
/* * Copyright 2000-2021 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"). * See LICENSE in the project root for license information. */ package jetbrains.buildServer.rust import jetbrains.buildServer.RunBuildException import jetbrains.buildServer.agent.ToolCannotBeFoundException import jetbrains.buildServer.agent.runner.BuildServiceAdapter import jetbrains.buildServer.agent.runner.ProcessListener import jetbrains.buildServer.agent.runner.ProcessListenerAdapter import jetbrains.buildServer.agent.runner.ProgramCommandLine import jetbrains.buildServer.rust.logging.BlockListener /** * Rustup runner service. */ class RustupToolchainBuildService(private val action: String) : BuildServiceAdapter() { val errors = arrayListOf<String>() var foundVersion: String? = null val version: String get() = foundVersion ?: runnerParameters[CargoConstants.PARAM_TOOLCHAIN]!! override fun makeProgramCommandLine(): ProgramCommandLine { val toolchainVersion = runnerParameters[CargoConstants.PARAM_TOOLCHAIN]!!.trim() val rustupPath = getPath(CargoConstants.RUSTUP_CONFIG_NAME) return createProgramCommandline(rustupPath, arrayListOf("toolchain", action, toolchainVersion)) } private fun getPath(toolName: String): String { try { return getToolPath(toolName) } catch (e: ToolCannotBeFoundException) { val buildException = RunBuildException(e) buildException.isLogStacktrace = false throw buildException } } override fun isCommandLineLoggingEnabled() = false override fun getListeners(): MutableList<ProcessListener> { return arrayListOf<ProcessListener>().apply { val blockName = "$action toolchain: ${runnerParameters[CargoConstants.PARAM_TOOLCHAIN]}" this.add(BlockListener(blockName, logger)) this.add(object : ProcessListenerAdapter() { override fun onStandardOutput(text: String) { processOutput(text) } override fun onErrorOutput(text: String) { processOutput(text) } }) } } fun processOutput(text: String) { if (text.startsWith("error:")) { errors.add(text) } toolchainVersion.matchEntire(text)?.let { foundVersion = it.groupValues.last() } logger.message(text) } companion object { val toolchainVersion = Regex("info: syncing channel updates for '([^']+)'") } }
apache-2.0
692fb0eed3ef03fcf0fa648bee4f32cb
32.113924
103
0.673547
5.079612
false
false
false
false
rfcx/rfcx-guardian-android
role-guardian/src/main/java/org/rfcx/guardian/guardian/manager/PreferenceManager.kt
1
3041
package org.rfcx.guardian.guardian.manager import android.content.Context import android.content.SharedPreferences import java.util.* class PreferenceManager(context: Context){ private var sharedPreferences: SharedPreferences companion object { @Volatile private var INSTANCE: PreferenceManager? = null fun getInstance(context: Context): PreferenceManager = INSTANCE ?: synchronized(this) { INSTANCE ?: PreferenceManager(context).also { INSTANCE = it } } private const val PREFERENCES_NAME = "Rfcx.Guardian" private const val PREFIX = "org.rfcx.guardian:" const val ID_TOKEN = "${PREFIX}ID_TOKEN" const val ACCESS_TOKEN = "${PREFIX}ACCESS_TOKEN" const val REFRESH_TOKEN = "${PREFIX}REFRESH_TOKEN" const val USER_GUID = "${PREFIX}USER_GUID" const val EMAIL = "${PREFIX}EMAIL" const val NICKNAME = "${PREFIX}NICKNAME" const val ROLES = "${PREFIX}ROLES" const val ACCESSIBLE_SITES = "${PREFIX}ACCESSIBLE_SITES" const val DEFAULT_SITE = "${PREFIX}SITE" const val TOKEN_EXPIRED_AT = "${PREFIX}EXPIRED_AT" } init { sharedPreferences = context.applicationContext.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE) } fun getBoolean(key: String, defaultValue: Boolean = false): Boolean { return sharedPreferences.getBoolean(key, defaultValue) } fun putBoolean(key: String, value: Boolean) { sharedPreferences.edit().putBoolean(key, value).apply() } fun getString(key: String, defValue: String): String { return sharedPreferences.getString(key, defValue) ?: defValue } fun getString(key: String): String? { return sharedPreferences.getString(key, null) } fun putString(key: String, value: String) { sharedPreferences.edit().putString(key, value).apply() } fun getDate(key: String): Date? { val secondsSinceEpoch = sharedPreferences.getLong(key, 0L) if (secondsSinceEpoch == 0L) { return null } return Date(secondsSinceEpoch) } fun putDate(key: String, date: Date) { sharedPreferences.edit().putLong(key, date.time).apply() } fun getLong(key: String, defValue: Long): Long { return sharedPreferences.getLong(key, defValue) } fun putLong(key: String, long: Long) { sharedPreferences.edit().putLong(key, long).apply() } fun getStringSet(key: String): Set<String> { return sharedPreferences.getStringSet(key, setOf()) ?: setOf() } fun putStringSet(key: String, value: Set<String>) { sharedPreferences.edit().putStringSet(key, value).apply() } fun remove(key: String) { sharedPreferences.edit().remove(key).apply() } fun clear() { sharedPreferences.edit().clear().apply() } fun isTokenExpired(): Boolean{ return System.currentTimeMillis() > getLong(TOKEN_EXPIRED_AT, 0L) } }
apache-2.0
b2030a900f33925edeeeb41ce05db10d
29.717172
115
0.643867
4.478645
false
false
false
false
cretz/asmble
compiler/src/main/kotlin/asmble/compile/jvm/ClsContext.kt
1
6143
package asmble.compile.jvm import asmble.ast.Node import asmble.util.Either import asmble.util.Logger import org.objectweb.asm.Opcodes import org.objectweb.asm.Type import org.objectweb.asm.tree.ClassNode import org.objectweb.asm.tree.MethodInsnNode import org.objectweb.asm.tree.MethodNode import java.util.* data class ClsContext( val packageName: String, val className: String, val mod: Node.Module, val cls: ClassNode = ClassNode().also { it.name = (packageName.replace('.', '/') + "/$className").trimStart('/') }, val mem: Mem = ByteBufferMem, val modName: String? = null, val reworker: InsnReworker = InsnReworker, val logger: Logger = Logger.Print(Logger.Level.OFF), val funcBuilder: FuncBuilder = FuncBuilder, val syntheticFuncBuilder: SyntheticFuncBuilder = SyntheticFuncBuilder, val checkTruncOverflow: Boolean = true, val nonAdjacentMemAccessesRequiringLocalVar: Int = 3, val eagerFailLargeMemOffset: Boolean = true, val preventMemIndexOverflow: Boolean = false, val accurateNanBits: Boolean = true, val checkSignedDivIntegerOverflow: Boolean = true, val jumpTableChunkSize: Int = 5000, val includeBinary: Boolean = false ) : Logger by logger { val importFuncs: List<Node.Import> by lazy { mod.imports.filter { it.kind is Node.Import.Kind.Func } } val importGlobals: List<Node.Import> by lazy { mod.imports.filter { it.kind is Node.Import.Kind.Global } } val thisRef = TypeRef(Type.getObjectType((packageName.replace('.', '/') + "/$className").trimStart('/'))) val hasMemory: Boolean by lazy { mod.memories.isNotEmpty() || mod.imports.any { it.kind is Node.Import.Kind.Memory } } val hasTable: Boolean by lazy { mod.tables.isNotEmpty() || mod.imports.any { it.kind is Node.Import.Kind.Table } } val dedupedFuncNames: Map<Int, String>? by lazy { // Consider all exports as seen val seen = mod.exports.flatMap { export -> when { export.kind == Node.ExternalKind.FUNCTION -> listOf(export.field.javaIdent) // Just to make it easy, consider all globals as having setters export.kind == Node.ExternalKind.GLOBAL -> export.field.javaIdent.capitalize().let { listOf("get$it", "set$it") } else -> listOf("get" + export.field.javaIdent.capitalize()) } }.toMutableSet() mod.names?.funcNames?.toList()?.sortedBy { it.first }?.map { (index, origName) -> var name = origName.javaIdent var nameIndex = 0 while (!seen.add(name)) name = origName.javaIdent + (nameIndex++) index to name }?.toMap() } fun assertHasMemory() { if (!hasMemory) throw CompileErr.UnknownMemory(0) } fun typeAtIndex(index: Int) = mod.types.getOrNull(index) ?: throw CompileErr.UnknownType(index) fun funcAtIndex(index: Int) = importFuncs.getOrNull(index).let { when (it) { null -> Either.Right(mod.funcs.getOrNull(index - importFuncs.size) ?: throw CompileErr.UnknownFunc(index)) else -> Either.Left(it) } } fun funcTypeAtIndex(index: Int) = funcAtIndex(index).let { when (it) { is Either.Left -> typeAtIndex((it.v.kind as Node.Import.Kind.Func).typeIndex) is Either.Right -> it.v.type } } fun globalAtIndex(index: Int) = importGlobals.getOrNull(index).let { when (it) { null -> Either.Right(mod.globals.getOrNull(index - importGlobals.size) ?: throw CompileErr.UnknownGlobal(index)) else -> Either.Left(it) } } fun importGlobalGetterFieldName(index: Int) = "import\$get" + globalName(index) fun importGlobalSetterFieldName(index: Int) = "import\$set" + globalName(index) fun globalName(index: Int) = "\$global$index" fun funcName(index: Int) = dedupedFuncNames?.get(index) ?: "\$func$index" private fun syntheticFunc( nameSuffix: String, fn: SyntheticFuncBuilder.(ClsContext, String) -> MethodNode ): MethodInsnNode { val name = "\$\$$nameSuffix" val method = cls.methods.find { (it as MethodNode).name == name }?.let { it as MethodNode } ?: fn(syntheticFuncBuilder, this, name).also { cls.methods.add(it) } return MethodInsnNode(Opcodes.INVOKESTATIC, thisRef.asmName, method.name, method.desc, false) } val truncAssertF2SI get() = syntheticFunc("assertF2SI", SyntheticFuncBuilder::buildF2SIAssertion) val truncAssertF2UI get() = syntheticFunc("assertF2UI", SyntheticFuncBuilder::buildF2UIAssertion) val truncAssertF2SL get() = syntheticFunc("assertF2SL", SyntheticFuncBuilder::buildF2SLAssertion) val truncAssertF2UL get() = syntheticFunc("assertF2UL", SyntheticFuncBuilder::buildF2ULAssertion) val truncAssertD2SI get() = syntheticFunc("assertD2SI", SyntheticFuncBuilder::buildD2SIAssertion) val truncAssertD2UI get() = syntheticFunc("assertD2UI", SyntheticFuncBuilder::buildD2UIAssertion) val truncAssertD2SL get() = syntheticFunc("assertD2SL", SyntheticFuncBuilder::buildD2SLAssertion) val truncAssertD2UL get() = syntheticFunc("assertD2UL", SyntheticFuncBuilder::buildD2ULAssertion) val divAssertI get() = syntheticFunc("assertIDiv", SyntheticFuncBuilder::buildIDivAssertion) val divAssertL get() = syntheticFunc("assertLDiv", SyntheticFuncBuilder::buildLDivAssertion) val indirectBootstrap get() = syntheticFunc("indirectBootstrap", SyntheticFuncBuilder::buildIndirectBootstrap) // Builds a method that takes an int and returns a depth int fun largeTableJumpCall(table: Node.Instr.BrTable): MethodInsnNode { val namePrefix = "largeTable" + UUID.randomUUID().toString().replace("-", "") val methods = syntheticFuncBuilder.buildLargeTableJumps(this, namePrefix, table) cls.methods.addAll(methods) return methods.first().let { method -> MethodInsnNode(Opcodes.INVOKESTATIC, thisRef.asmName, method.name, method.desc, false) } } }
mit
361ae1c730bcbc5a505b5a6375d62289
47.377953
119
0.675891
4.017659
false
false
false
false
NephyProject/Penicillin
src/main/kotlin/jp/nephy/penicillin/endpoints/directmessages/List.kt
1
2547
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * 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. */ @file:Suppress("UNUSED", "PublicApiImplicitType") package jp.nephy.penicillin.endpoints.directmessages import jp.nephy.penicillin.core.request.action.JsonObjectApiAction import jp.nephy.penicillin.core.request.parameters import jp.nephy.penicillin.core.session.get import jp.nephy.penicillin.endpoints.DirectMessages import jp.nephy.penicillin.endpoints.Option import jp.nephy.penicillin.endpoints.directMessageDeprecatedMessage import jp.nephy.penicillin.models.DirectMessage /** * Abolished endpoint. * * @param options Optional. Custom parameters of this request. * @receiver [DirectMessages] endpoint instance. * @return [JsonObjectApiAction] for [DirectMessage] model. */ @Deprecated(directMessageDeprecatedMessage, replaceWith = ReplaceWith("directMessageEvent.list", "jp.nephy.penicillin.endpoints.directMessageEvent", "jp.nephy.penicillin.endpoints.directmessages.events.list")) fun DirectMessages.list( sinceId: Long? = null, maxId: Long? = null, count: Int? = null, includeEntities: Boolean? = null, skipStatus: Boolean? = null, vararg options: Option ) = client.session.get("/1.1/direct_messages.json") { parameters( "since_id" to sinceId, "max_id" to maxId, "count" to count, "include_entities" to includeEntities, "skip_status" to skipStatus, *options ) }.jsonArray<DirectMessage>()
mit
66f1d3fa3eb0710c5f0c70a36bce761c
40.754098
209
0.751472
4.245
false
false
false
false
UweTrottmann/SeriesGuide
app/src/test/java/com/battlelancer/seriesguide/thetvdbapi/ImageToolsTest.kt
1
2244
package com.battlelancer.seriesguide.thetvdbapi import android.content.Context import androidx.test.core.app.ApplicationProvider import com.battlelancer.seriesguide.EmptyTestApplication import com.battlelancer.seriesguide.util.ImageTools import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(application = EmptyTestApplication::class) class ImageToolsTest { private val context = ApplicationProvider.getApplicationContext<Context>() @Test fun posterUrl() { // Note: TMDB image paths start with / whereas TVDB paths do not. val tmdbUrl = ImageTools.tmdbOrTvdbPosterUrl("/example.jpg", context) val tmdbUrlOriginal = ImageTools.tmdbOrTvdbPosterUrl("/example.jpg", context, true) val tvdbUrl = ImageTools.tmdbOrTvdbPosterUrl("posters/example.jpg", context) println("TMDB URL: $tmdbUrl") println("TMDB original URL: $tmdbUrlOriginal") println("TVDB URL: $tvdbUrl") assertThat(tmdbUrl).isNotEmpty() assertThat(tmdbUrl).endsWith("https://image.tmdb.org/t/p/w154/example.jpg") assertThat(tmdbUrlOriginal).isNotEmpty() assertThat(tmdbUrlOriginal).endsWith("https://image.tmdb.org/t/p/original/example.jpg") assertThat(tvdbUrl).isNotEmpty() assertThat(tvdbUrl).endsWith("https://artworks.thetvdb.com/banners/posters/example.jpg") } @Test fun posterUrl_withLegacyCachePath() { val url = ImageTools.tmdbOrTvdbPosterUrl("_cache/posters/example.jpg", context) println("TVDB legacy URL: $url") assertThat(url).isNotEmpty() assertThat(url).endsWith("https://www.thetvdb.com/banners/_cache/posters/example.jpg") } @Test fun posterUrlOrResolve() { val url = ImageTools.posterUrlOrResolve(null, 42, null, context) assertThat(url).isNotEmpty() assertThat(url).isEqualTo("showtmdb://42") val urlLang = ImageTools.posterUrlOrResolve(null, 42, "de", context) assertThat(urlLang).isNotEmpty() assertThat(urlLang).isEqualTo("showtmdb://42?language=de") } }
apache-2.0
b10650611e1de1438eeed16564e6739f
41.339623
96
0.722816
4.021505
false
true
false
false
UweTrottmann/SeriesGuide
app/src/main/java/com/battlelancer/seriesguide/stats/StatsFragment.kt
1
14985
package com.battlelancer.seriesguide.stats import android.os.Bundle import android.text.format.DateUtils import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.core.view.MenuProvider import androidx.core.view.isGone import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Lifecycle import androidx.preference.PreferenceManager import com.battlelancer.seriesguide.R import com.battlelancer.seriesguide.databinding.FragmentStatsBinding import com.battlelancer.seriesguide.settings.DisplaySettings import com.battlelancer.seriesguide.util.ShareUtils import com.battlelancer.seriesguide.util.copyTextToClipboardOnLongClick import java.text.NumberFormat /** * Displays some statistics about the users show database, e.g. number of shows, episodes, share of * watched episodes, etc. */ class StatsFragment : Fragment() { private var binding: FragmentStatsBinding? = null private val model by viewModels<StatsViewModel>() private var currentStats: Stats? = null private var hasFinalValues: Boolean = false override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentStatsBinding.inflate(inflater, container, false) return binding!!.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val binding = binding!! binding.errorView.visibility = View.GONE binding.errorView.setButtonClickListener { loadStats() } // set some views invisible so they can be animated in once stats are computed binding.textViewShowsFinished.visibility = View.INVISIBLE binding.progressBarShowsFinished.visibility = View.INVISIBLE binding.textViewShowsWithNextEpisode.visibility = View.INVISIBLE binding.progressBarShowsWithNextEpisode.visibility = View.INVISIBLE binding.textViewShowsContinuing.visibility = View.INVISIBLE binding.progressBarShowsContinuing.visibility = View.INVISIBLE binding.textViewEpisodesWatched.visibility = View.INVISIBLE binding.progressBarEpisodesWatched.visibility = View.INVISIBLE binding.textViewEpisodesRuntime.visibility = View.INVISIBLE binding.textViewMoviesWatchlist.visibility = View.INVISIBLE binding.textViewMoviesWatchlistRuntime.visibility = View.INVISIBLE binding.progressBarMoviesWatched.visibility = View.INVISIBLE binding.textViewMoviesWatched.visibility = View.INVISIBLE binding.textViewMoviesWatchedRuntime.visibility = View.INVISIBLE binding.progressBarMoviesCollection.visibility = View.INVISIBLE binding.textViewMoviesCollection.visibility = View.INVISIBLE binding.textViewMoviesCollectionRuntime.visibility = View.INVISIBLE // set up long-press to copy text to clipboard (d-pad friendly vs text selection) binding.textViewShows.copyTextToClipboardOnLongClick() binding.textViewShowsFinished.copyTextToClipboardOnLongClick() binding.textViewShowsWithNextEpisode.copyTextToClipboardOnLongClick() binding.textViewShowsContinuing.copyTextToClipboardOnLongClick() binding.textViewEpisodes.copyTextToClipboardOnLongClick() binding.textViewEpisodesWatched.copyTextToClipboardOnLongClick() binding.textViewEpisodesRuntime.copyTextToClipboardOnLongClick() binding.textViewMovies.copyTextToClipboardOnLongClick() binding.textViewMoviesWatchlist.copyTextToClipboardOnLongClick() binding.textViewMoviesWatchlistRuntime.copyTextToClipboardOnLongClick() binding.textViewMoviesWatched.copyTextToClipboardOnLongClick() binding.textViewMoviesWatchedRuntime.copyTextToClipboardOnLongClick() binding.textViewMoviesCollection.copyTextToClipboardOnLongClick() binding.textViewMoviesCollectionRuntime.copyTextToClipboardOnLongClick() model.statsData.observe(viewLifecycleOwner) { this.handleStatsUpdate(it) } requireActivity().addMenuProvider( optionsMenuProvider, viewLifecycleOwner, Lifecycle.State.RESUMED ) } override fun onDestroyView() { super.onDestroyView() binding = null } private val optionsMenuProvider = object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.stats_menu, menu) menu.findItem(R.id.menu_action_stats_filter_specials).isChecked = DisplaySettings.isHidingSpecials(requireContext()) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { when (menuItem.itemId) { R.id.menu_action_stats_share -> { shareStats() return true } R.id.menu_action_stats_filter_specials -> { PreferenceManager.getDefaultSharedPreferences(requireContext()).edit() .putBoolean(DisplaySettings.KEY_HIDE_SPECIALS, !menuItem.isChecked) .apply() requireActivity().invalidateOptionsMenu() loadStats() return true } else -> return false } } } private fun loadStats() { model.hideSpecials.value = DisplaySettings.isHidingSpecials(requireContext()) } private fun handleStatsUpdate(event: StatsUpdateEvent) { if (!isAdded) { return } currentStats = event.stats hasFinalValues = event.finalValues updateStats(event.stats, event.finalValues, event.successful) } private fun updateStats( stats: Stats, hasFinalValues: Boolean, successful: Boolean ) { val binding = binding ?: return // display error if not all stats could be calculated binding.errorView.isGone = successful val format = NumberFormat.getIntegerInstance() // all shows binding.textViewShows.text = format.format(stats.shows.toLong()) // shows finished binding.progressBarShowsFinished.apply { max = stats.shows progress = stats.showsFinished visibility = View.VISIBLE } binding.textViewShowsFinished.apply { text = getString( R.string.shows_finished, format.format(stats.showsFinished.toLong()) ) visibility = View.VISIBLE } // shows with next episodes binding.progressBarShowsWithNextEpisode.apply { max = stats.shows progress = stats.showsWithNextEpisodes visibility = View.VISIBLE } binding.textViewShowsWithNextEpisode.apply { text = getString( R.string.shows_with_next, format.format(stats.showsWithNextEpisodes.toLong()) ) visibility = View.VISIBLE } // continuing shows binding.progressBarShowsContinuing.apply { max = stats.shows progress = stats.showsContinuing visibility = View.VISIBLE } binding.textViewShowsContinuing.text = getString( R.string.shows_continuing, format.format(stats.showsContinuing.toLong()) ) binding.textViewShowsContinuing.visibility = View.VISIBLE // all episodes binding.textViewEpisodes.text = format.format(stats.episodes.toLong()) // watched episodes binding.progressBarEpisodesWatched.max = stats.episodes binding.progressBarEpisodesWatched.progress = stats.episodesWatched binding.progressBarEpisodesWatched.visibility = View.VISIBLE binding.textViewEpisodesWatched.text = getString( R.string.episodes_watched, format.format(stats.episodesWatched.toLong()) ) binding.textViewEpisodesWatched.visibility = View.VISIBLE // episode runtime var watchedDuration = getTimeDuration(stats.episodesWatchedRuntime) if (!hasFinalValues) { // showing minimum (= not the final value) watchedDuration = "> $watchedDuration" } binding.textViewEpisodesRuntime.text = watchedDuration binding.textViewEpisodesRuntime.visibility = View.VISIBLE binding.progressBarEpisodesRuntime.visibility = if (successful) if (hasFinalValues) View.GONE else View.VISIBLE else View.GONE // movies binding.textViewMovies.text = format.format(stats.movies.toLong()) // watched movies binding.progressBarMoviesWatched.apply { max = stats.movies progress = stats.moviesWatched visibility = View.VISIBLE } binding.textViewMoviesWatched.apply { text = getString( R.string.movies_watched_format, format.format(stats.moviesWatched.toLong()) ) visibility = View.VISIBLE } binding.textViewMoviesWatchedRuntime.apply { text = getTimeDuration(stats.moviesWatchedRuntime) visibility = View.VISIBLE } // movies in watchlist binding.textViewMoviesWatchlist.apply { text = getString( R.string.movies_on_watchlist, format.format(stats.moviesWatchlist.toLong()) ) visibility = View.VISIBLE } binding.textViewMoviesWatchlistRuntime.apply { text = getTimeDuration(stats.moviesWatchlistRuntime) visibility = View.VISIBLE } // movies in collection binding.progressBarMoviesCollection.apply { max = stats.movies progress = stats.moviesCollection visibility = View.VISIBLE } binding.textViewMoviesCollection.apply { text = getString(R.string.stats_in_collection_format, stats.moviesCollection) visibility = View.VISIBLE } binding.textViewMoviesCollectionRuntime.apply { text = getTimeDuration(stats.moviesCollectionRuntime) visibility = View.VISIBLE } } private fun getTimeDuration(duration: Long): String { var durationCalc = duration val days = durationCalc / DateUtils.DAY_IN_MILLIS durationCalc %= DateUtils.DAY_IN_MILLIS val hours = durationCalc / DateUtils.HOUR_IN_MILLIS durationCalc %= DateUtils.HOUR_IN_MILLIS val minutes = durationCalc / DateUtils.MINUTE_IN_MILLIS val result = StringBuilder() if (days != 0L) { result.append( resources.getQuantityString( R.plurals.days_plural, days.toInt(), days.toInt() ) ) } if (hours != 0L) { if (days != 0L) { result.append(" ") } result.append( resources.getQuantityString( R.plurals.hours_plural, hours.toInt(), hours.toInt() ) ) } if (minutes != 0L || days == 0L && hours == 0L) { if (days != 0L || hours != 0L) { result.append(" ") } result.append( resources.getQuantityString( R.plurals.minutes_plural, minutes.toInt(), minutes.toInt() ) ) } return result.toString() } private fun shareStats() { val currentStats = this.currentStats ?: return val format = NumberFormat.getIntegerInstance() val shows = format.format(currentStats.shows.toLong()) val showsWithNext = getString( R.string.shows_with_next, format.format(currentStats.showsWithNextEpisodes.toLong()) ) val showsContinuing = getString( R.string.shows_continuing, format.format(currentStats.showsContinuing.toLong()) ) val showsFinished = getString( R.string.shows_finished, format.format(currentStats.showsFinished.toLong()) ) val episodes = format.format(currentStats.episodes.toLong()) val episodesWatched = getString( R.string.episodes_watched, format.format(currentStats.episodesWatched.toLong()) ) val showStats = "${getString(R.string.app_name)} ${getString(R.string.statistics)}\n\n" + "${getString(R.string.shows)}\n" + "$shows\n" + "$showsWithNext\n" + "$showsContinuing\n" + "$showsFinished\n\n" + "${getString(R.string.episodes)}\n" + "$episodes\n" + "$episodesWatched\n" val statsString = StringBuilder(showStats) if (currentStats.episodesWatchedRuntime != 0L) { var watchedDuration = getTimeDuration(currentStats.episodesWatchedRuntime) if (!hasFinalValues) { // showing minimum (= not the final value) watchedDuration = "> $watchedDuration" } statsString.append("$watchedDuration\n") } statsString.append("\n") // movies val movies = format.format(currentStats.movies.toLong()) val moviesWatchlist = getString( R.string.movies_on_watchlist, format.format(currentStats.moviesWatchlist.toLong()) ) val moviesWatched = getString( R.string.movies_watched_format, format.format(currentStats.moviesWatched.toLong()) ) val moviesCollection = getString( R.string.stats_in_collection_format, currentStats.moviesCollection ) val moviesWatchlistRuntime = getTimeDuration(currentStats.moviesWatchlistRuntime) val moviesWatchedRuntime = getTimeDuration(currentStats.moviesWatchedRuntime) val moviesCollectionRuntime = getTimeDuration(currentStats.moviesCollectionRuntime) val movieStats = "${getString(R.string.movies)}\n" + "$movies\n" + "$moviesWatched\n" + "$moviesWatchedRuntime\n" + "$moviesWatchlist\n" + "$moviesWatchlistRuntime\n" + "$moviesCollection\n" + "$moviesCollectionRuntime\n" statsString.append(movieStats) ShareUtils.startShareIntentChooser(activity, statsString.toString(), R.string.share) } }
apache-2.0
a8a333e0af3e4e22774ab281fd4becbe
36.4625
99
0.634301
5.257895
false
false
false
false
premnirmal/StockTicker
app/src/main/kotlin/com/github/premnirmal/ticker/news/NewsFeedViewModel.kt
1
1635
package com.github.premnirmal.ticker.news import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.github.premnirmal.ticker.model.FetchResult import com.github.premnirmal.ticker.network.NewsProvider import com.github.premnirmal.ticker.news.NewsFeedItem.ArticleNewsFeed import com.github.premnirmal.ticker.news.NewsFeedItem.TrendingStockNewsFeed import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject @HiltViewModel class NewsFeedViewModel @Inject constructor( private val newsProvider: NewsProvider ): ViewModel() { val newsFeed: LiveData<FetchResult<List<NewsFeedItem>>> get() = _newsFeed private val _newsFeed = MutableLiveData<FetchResult<List<NewsFeedItem>>>() fun fetchNews(forceRefresh: Boolean = false) { viewModelScope.launch { val news = newsProvider.fetchMarketNews(useCache = !forceRefresh) val trending = newsProvider.fetchTrendingStocks(useCache = !forceRefresh) if (news.wasSuccessful) { val data = ArrayList<NewsFeedItem>() withContext(Dispatchers.Default) { data.addAll(news.data.map { ArticleNewsFeed(it) }) if (trending.wasSuccessful) { val taken = trending.data.take(6) data.add(0, TrendingStockNewsFeed(taken)) } } _newsFeed.value = FetchResult.success(data) } else { _newsFeed.value = FetchResult.failure(news.error) } } } }
gpl-3.0
934d7b905aa9a00c7983779718fc5d3c
35.355556
79
0.749235
4.348404
false
false
false
false
wizardofos/Protozoo
server/repo/src/main/kotlin/org/protozoo/server/repo/RepoResource.kt
1
2362
package org.protozoo.server.repo import org.osgi.service.component.annotations.* import org.protozoo.server.api.RestService import org.protozoo.system.repo.Repository import javax.ws.rs.GET import javax.ws.rs.OPTIONS import javax.ws.rs.Produces import javax.ws.rs.core.MediaType import javax.ws.rs.core.Response /** * This REST service represents the Protozoo * component repository and only gets activated * when the reference can be resolved */ @Component( name = "RepositoryResource", service = arrayOf(RestService), scope = ServiceScope.PROTOTYPE, enabled = true, immediate = false ) @Produces(MediaType.APPLICATION_JSON) class RepoResource : RestService { private var repo: Repository? = null @GET fun getAll(): Response { println("Components: " + this + ", " + this.repo) if (repo != null) { return Response .ok() .entity(repo?.getAll()) .header("Access-Control-Allow-Origin", "*") .build() } else { return Response .serverError() .entity("Repository not initialized") .build() } } @OPTIONS fun getCors(): Response { return Response .ok() .header("Access-Control-Allow-Origin", "*") .header("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, DELETE") .header("Access-Control-Allow-Headers", "Access-Control-Allow-Origin, Content-Type") .header("Access-Control-Max-Age", 86400) .type("text/plain") .build() } @Activate fun activate() { println("Repository resource activated " + this) } @Deactivate fun deactivate() { println("Repository resource deactivated " + this) } @Reference( name = "repo", service = Repository::class, policy = ReferencePolicy.DYNAMIC ) fun bindRepo(repo: Repository) { println("Bind repository resource " + this) println("Setting reference to repository " + repo) this.repo = repo } fun unbindRepo(repo: Repository) { println("Unbind repository resource " + this) this.repo = repo } }
mit
83145db69de2672138f6d38e25a90794
26.476744
100
0.574936
4.507634
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-classes-bukkit/src/main/kotlin/com/rpkit/classes/bukkit/listener/RPKCharacterSwitchListener.kt
1
1117
package com.rpkit.classes.bukkit.listener import com.rpkit.characters.bukkit.event.character.RPKBukkitCharacterSwitchEvent import com.rpkit.classes.bukkit.classes.RPKClassService import com.rpkit.core.service.Services import org.bukkit.event.EventHandler import org.bukkit.event.Listener class RPKCharacterSwitchListener : Listener { @EventHandler fun onCharacterSwitch(event: RPKBukkitCharacterSwitchEvent) { val classService = Services[RPKClassService::class.java] ?: return val newCharacter = event.character if (newCharacter != null) { val `class` = classService.loadClass(newCharacter).join() if (`class` != null) { classService.loadExperience(newCharacter, `class`).join() } } val oldCharacter = event.fromCharacter if (oldCharacter != null) { val `class` = classService.getClass(oldCharacter).join() if (`class` != null) { classService.unloadExperience(oldCharacter, `class`) } classService.unloadClass(oldCharacter) } } }
apache-2.0
aadf338142e08830b05ee0b8d7c23dd0
35.064516
80
0.666965
4.485944
false
false
false
false
itachi1706/CheesecakeUtilities
app/src/main/java/com/itachi1706/cheesecakeutilities/modules/gpaCalculator/fragment/ModuleListFragment.kt
1
8851
package com.itachi1706.cheesecakeutilities.modules.gpaCalculator.fragment import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import com.google.android.material.snackbar.Snackbar import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseReference import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.AddModuleActivity import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.GpaCalcFirebaseUtils import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.GpaRecyclerAdapter import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.MainViewActivity import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.objects.GpaInstitution import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.objects.GpaModule import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.objects.GpaRecycler import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.objects.GpaScoring import com.itachi1706.cheesecakeutilities.R import com.itachi1706.cheesecakeutilities.util.FirebaseValueEventListener import com.itachi1706.helperlib.helpers.LogHelper /** * Semester List View */ class ModuleListFragment : BaseGpaFragment() { private val state = MainViewActivity.STATE_MODULE private val modules: ArrayList<GpaModule> = ArrayList() private var selectedInstitutionString: String? = null private var selectedInstitutionType: String? = null private var selectedSemesterKey: String? = null private var selectedInstitution: GpaInstitution? = null private var scoreObject: GpaScoring? = null override fun getLogTag(): String { return TAG } override fun getState(): Int { return state } override fun evaluateToCont(v: View): Boolean { selectedInstitutionString = arguments?.getString("selection") selectedSemesterKey = arguments?.getString("semester") if (selectedInstitutionString == null || selectedSemesterKey == null) { LogHelper.e(TAG, "Institution/Semester not selected!") Snackbar.make(v, "An error has occurred. (Institution/Semester not found)", Snackbar.LENGTH_LONG).show() callback?.goBack() return false } selectedInstitutionType = arguments?.getString("type") return true } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val v = super.onCreateView(inflater, container, savedInstanceState) adapter.setOnClickListener(View.OnClickListener { view -> val viewHolder = view.tag as GpaRecyclerAdapter.GpaViewHolder val pos = viewHolder.adapterPosition val moduleSelected = modules[pos] // FUTURE_TODO: Maybe swap edit to a screen with all the module information startActivity(Intent(context, AddModuleActivity::class.java).apply { putExtra("userid", callback?.getUserId()) putExtra("institute", selectedInstitutionString) putExtra("key", selectedSemesterKey) putExtra("editmode", moduleSelected.courseCode) }) }) adapter.setOnCreateContextMenuListener(View.OnCreateContextMenuListener { menu, view, _ -> // Get selected institution val viewHolder = view.tag as GpaRecyclerAdapter.GpaViewHolder if (!initContextSelectMode(viewHolder.adapterPosition)) return@OnCreateContextMenuListener // Do nothing menu.setHeaderTitle("${moduleContextSel!!.name} [${moduleContextSel!!.courseCode}]") activity?.menuInflater?.inflate(R.menu.context_menu_editdelete, menu) }) // Get institution name to update title selectedInstitution = callback?.getInstitution() updateActionBar() return v } private var moduleContextSel: GpaModule? = null override fun onContextItemSelected(item: MenuItem): Boolean { LogHelper.d(TAG, "Context Item Selected") if (moduleContextSel == null) return false return when (item.itemId) { R.id.menu_edit -> edit(null) R.id.menu_delete -> delete(null) else -> super.onContextItemSelected(item) } } override fun initContextSelectMode(position: Int): Boolean { moduleContextSel = modules[position] if (moduleContextSel == null) return false return true } override fun edit(position: Int?): Boolean { if (position != null) if (!initContextSelectMode(position)) return false startActivity(Intent(context, AddModuleActivity::class.java).apply { putExtra("userid", callback?.getUserId()) putExtra("institute", selectedInstitutionString) putExtra("key", selectedSemesterKey) putExtra("editmode", moduleContextSel!!.courseCode) }) return true } override fun delete(position: Int?): Boolean { if (position != null) if (!initContextSelectMode(position)) return false val moduleToDelete = moduleContextSel!!.copy() val data = getPath() ?: return false data.child(moduleToDelete.courseCode).removeValue() Snackbar.make(view!!, "Module Deleted", Snackbar.LENGTH_LONG).setAction("Undo") { v -> data.child(moduleToDelete.courseCode).setValue(moduleToDelete) Snackbar.make(v, "Delete undone", Snackbar.LENGTH_SHORT).show() }.show() return true } private fun getPath(): DatabaseReference? { return callback?.getUserData()?.child(selectedInstitutionString!!)?.child(GpaCalcFirebaseUtils.FB_REC_SEMESTER) ?.child(selectedSemesterKey!!)?.child(GpaCalcFirebaseUtils.FB_REC_MODULE) } override fun onStart() { super.onStart() if (selectedInstitutionString == null) return // Don't do anything, an error had occurred already scoreObject = callback?.getScoreMap()!![selectedInstitutionType] updateActionBar() LogHelper.i(TAG, "Registering Module Firebase DB Listener") listener = getPath()?.addValueEventListener(object: FirebaseValueEventListener(TAG, "loadModuleList"){ override fun onDataChange(dataSnapshot: DataSnapshot) { if (callback?.getCurrentState() != state) return LogHelper.i(TAG, "Processing updated modules...") modules.clear() if (!dataSnapshot.hasChildren()) return dataSnapshot.children.forEach { modules.add(it.getValue(GpaModule::class.java)!!) } LogHelper.i(TAG, "Number of Modules ($selectedInstitutionString:$selectedSemesterKey): ${modules.size}") modules.sortBy { it.courseCode } modulesProcessAndUpdate() } }) } private fun modulesProcessAndUpdate() { val list: ArrayList<GpaRecycler> = ArrayList() modules.forEach { val score = when { it.gradeTier == -1 -> "-" scoreObject == null -> "???" it.passFail -> scoreObject!!.passtier!![it.gradeTier].name else -> scoreObject!!.gradetier[it.gradeTier].name } val finalGrade = if (it.gradeTier == -1) "???" else if (!it.passFail) scoreObject!!.gradetier[it.gradeTier].value.toString() else if (scoreObject!!.passtier!![it.gradeTier].value > 0) "P" else "F" list.add(GpaRecycler(it.name, if (scoreObject?.type == "gpa") "${it.courseCode} | Credits: ${it.credits} ${selectedInstitution?.creditName}" else it.courseCode, grade=score, gradeColor = GpaCalcFirebaseUtils.getGpaColor(finalGrade, scoreObject, context), color = it.color)) } updateActionBar() adapter.update(list) adapter.notifyDataSetChanged() } private fun updateActionBar() { LogHelper.d(TAG, "updateActionBar()") var subtitle: String? = null var title: String? = null if (scoreObject != null) { subtitle = if (selectedInstitution != null) "${selectedInstitution!!.semester[selectedSemesterKey]?.name} | " else "Unknown Semester | " subtitle += if (scoreObject!!.type == "count") "Score" else "GPA" subtitle += ": ${if (selectedInstitution != null) selectedInstitution!!.semester[selectedSemesterKey]?.gpa else "Unknown"}" } if (selectedInstitution != null) title = "${selectedInstitution!!.name} (${selectedInstitution!!.shortName})" callback?.updateActionBar(title, subtitle) } companion object { private const val TAG = "GpaCalcModuleList" } }
mit
e234cc3bd22fe8f5e6eb2c0f727a6264
44.860104
172
0.673935
4.695491
false
false
false
false
quarck/CalendarNotification
app/src/main/java/com/github/quarck/calnotify/notification/NotificationActionSnoozeService.kt
1
4736
// // Calendar Notifications Plus // Copyright (C) 2016 Sergey Parshin ([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, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // package com.github.quarck.calnotify.notification import android.app.IntentService import android.content.Context import android.content.Intent import android.os.Handler import android.widget.Toast import com.github.quarck.calnotify.Consts import com.github.quarck.calnotify.R import com.github.quarck.calnotify.Settings import com.github.quarck.calnotify.app.ApplicationController import com.github.quarck.calnotify.logs.DevLog import com.github.quarck.calnotify.textutils.EventFormatter //import com.github.quarck.calnotify.logs.Logger import com.github.quarck.calnotify.ui.UINotifier class DisplayToast(private val context: Context, internal var text: String) : Runnable { override fun run() { Toast.makeText(context, text, Toast.LENGTH_LONG).show() } } class NotificationActionSnoozeService : IntentService("NotificationActionSnoozeService") { var handler = Handler() override fun onHandleIntent(intent: Intent?) { DevLog.debug(LOG_TAG, "onHandleIntent") if (intent != null) { val isSnoozeAll = intent.getBooleanExtra(Consts.INTENT_SNOOZE_ALL_KEY, false) val isSnoozeAllCollapsed = intent.getBooleanExtra(Consts.INTENT_SNOOZE_ALL_COLLAPSED_KEY, false) if (isSnoozeAll){ DevLog.info(LOG_TAG, "Snooze all from notification request") val snoozeDelay = intent.getLongExtra(Consts.INTENT_SNOOZE_PRESET, Settings(this).snoozePresets[0]) if (ApplicationController.snoozeAllEvents(this, snoozeDelay, false, true) != null) { DevLog.info(LOG_TAG, "all visible snoozed by $snoozeDelay") onSnoozedBy(snoozeDelay) } UINotifier.notify(this, true) } else if (isSnoozeAllCollapsed) { DevLog.info(LOG_TAG, "Snooze all collapsed from notification request") val snoozeDelay = intent.getLongExtra(Consts.INTENT_SNOOZE_PRESET, Settings(this).snoozePresets[0]) if (ApplicationController.snoozeAllCollapsedEvents(this, snoozeDelay, false, true) != null) { DevLog.info(LOG_TAG, "all collapsed snoozed by $snoozeDelay") onSnoozedBy(snoozeDelay) } UINotifier.notify(this, true) } else { val notificationId = intent.getIntExtra(Consts.INTENT_NOTIFICATION_ID_KEY, -1) val eventId = intent.getLongExtra(Consts.INTENT_EVENT_ID_KEY, -1) val instanceStartTime = intent.getLongExtra(Consts.INTENT_INSTANCE_START_TIME_KEY, -1) val snoozeDelay = intent.getLongExtra(Consts.INTENT_SNOOZE_PRESET, Settings(this).snoozePresets[0]) if (notificationId != -1 && eventId != -1L && instanceStartTime != -1L) { if (ApplicationController.snoozeEvent(this, eventId, instanceStartTime, snoozeDelay) != null) { DevLog.info(LOG_TAG, "event $eventId / $instanceStartTime snoozed by $snoozeDelay") onSnoozedBy(snoozeDelay) } UINotifier.notify(this, true) } else { DevLog.error(LOG_TAG, "notificationId=$notificationId, eventId=$eventId, or type is null") } } } else { DevLog.error(LOG_TAG, "Intent is null!") } ApplicationController.cleanupEventReminder(this) } private fun onSnoozedBy(duration: Long) { val formatter = EventFormatter(this) val format = getString(R.string.event_snoozed_by) val text = String.format(format, formatter.formatTimeDuration(duration, 60L)) handler.post(DisplayToast(this, text)) } companion object { private const val LOG_TAG = "NotificationActionSnoozeService" } }
gpl-3.0
68699b1c082bf3b0d479d468ddf8fd23
40.54386
115
0.659628
4.282098
false
false
false
false
ujpv/intellij-rust
src/main/kotlin/org/rust/utils/Utils.kt
1
2686
package org.rust.utils import com.intellij.openapi.Disposable import com.intellij.openapi.util.component1 import com.intellij.openapi.util.component2 import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiElement import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.util.download.DownloadableFileService import kotlin.reflect.KProperty /** * Helper disposing [d] upon completing the execution of the [block] * * @d Target `Disposable` to be disposed upon completion of the @block * @block Target block to be run prior to disposal of @d */ fun <T> using(d: Disposable, block: () -> T): T { try { return block() } finally { d.dispose() } } /** * Helper disposing [d] upon completing the execution of the [block] (under the [d]) * * @d Target `Disposable` to be disposed upon completion of the @block * @block Target block to be run prior to disposal of @d */ fun <D : Disposable, T> usingWith(d: D, block: (D) -> T): T { try { return block(d) } finally { d.dispose() } } /** * Cached value invalidated on any PSI modification */ fun <E : PsiElement, T> psiCached(provider: E.() -> CachedValueProvider<T>): PsiCacheDelegate<E, T> = PsiCacheDelegate(provider) class PsiCacheDelegate<E : PsiElement, T>(val provider: E.() -> CachedValueProvider<T>) { operator fun getValue(element: E, property: KProperty<*>): T { return CachedValuesManager.getCachedValue(element, element.provider()) } } /** * Extramarital son of `sequenceOf` & `listOfNotNull` */ fun <T : Any> sequenceOfNotNull(vararg elements: T): Sequence<T> = listOfNotNull(*elements).asSequence() fun <T : Any> sequenceOfNotNull(element: T?): Sequence<T> = if (element != null) sequenceOf(element) else emptySequence() /** * Downloads file residing at [url] with the name [fileName] and saves it to [destination] folder */ fun download(url: String, fileName: String, destination: VirtualFile): VirtualFile? { val downloadService = DownloadableFileService.getInstance() val downloader = downloadService.createDownloader(listOf(downloadService.createFileDescription(url, fileName)), fileName) val downloadTo = VfsUtilCore.virtualToIoFile(destination) val (file, @Suppress("UNUSED_VARIABLE") d) = downloader.download(downloadTo).single() return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file) } /** * XXX */ fun <T> safely(run: () -> T, finally: () -> Unit): T = usingWith(Disposable { finally() }) { run() }
mit
e036ed2cc4fabd6ccaf8dc7bc4ee5a4d
32.575
128
0.711467
3.938416
false
false
false
false
CPRTeam/CCIP-Android
app/src/main/java/app/opass/ccip/util/ConfScheduleDeserializer.kt
1
2539
package app.opass.ccip.util import app.opass.ccip.model.* import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.reflect.TypeToken import org.intellij.lang.annotations.Language import java.lang.reflect.Type class ConfScheduleDeserializer : JsonDeserializer<ConfSchedule> { override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext): ConfSchedule? { json ?: return null val obj = json.asJsonObject if (obj.size() == 0) return null val speakers = deserializeList<Speaker>(obj["speakers"], context) val sessionTypes = deserializeList<SessionType>(obj["session_types"], context) val rooms = deserializeList<Room>(obj["rooms"], context) val sessionTags = deserializeList<SessionTag>(obj["tags"], context) val sessions = deserializeList<SessionTemp>(obj["sessions"], context).map { session -> Session( id = session.id, type = sessionTypes.find { session.type == it.id }, room = rooms.find { session.room == it.id }!!, speakers = session.speakers.mapNotNull { id -> speakers.find { it.id == id } }, tags = session.tags.mapNotNull { id -> sessionTags.find { it.id == id } }, start = session.start, end = session.end, zh = session.zh, en = session.en, qa = session.qa, slide = session.slide, broadcast = session.broadcast, coWrite = session.coWrite, live = session.live, record = session.record, language = session.language ) } return ConfSchedule(sessions, speakers, sessionTypes, rooms, sessionTags) } private inline fun <reified T> deserializeList(json: JsonElement, context: JsonDeserializationContext): List<T> { return context.deserialize(json, TypeToken.getParameterized(List::class.java, T::class.java).type) } } data class SessionTemp( val id: String, val type: String, val room: String, val start: String, val end: String, val zh: Zh, val en: En, val speakers: List<String>, val tags: List<String>, val qa: String?, val slide: String?, val broadcast: List<String>?, val coWrite: String?, val live: String?, val record: String?, val language: String? )
gpl-3.0
dec5aab6c12ee08eb061cf6f1be404fb
36.895522
118
0.621505
4.407986
false
false
false
false
JakeWharton/RxBinding
rxbinding/src/main/java/com/jakewharton/rxbinding4/view/ViewVisibilityConsumer.kt
1
968
@file:JvmName("RxView") @file:JvmMultifileClass package com.jakewharton.rxbinding4.view import androidx.annotation.CheckResult import android.view.View import io.reactivex.rxjava3.functions.Consumer /** * An action which sets the visibility property of `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe to free this * reference. * * @param visibilityWhenFalse Visibility to set on a `false` value (`View.INVISIBLE` or * `View.GONE`). */ @CheckResult @JvmOverloads fun View.visibility(visibilityWhenFalse: Int = View.GONE): Consumer<in Boolean> { require(visibilityWhenFalse != View.VISIBLE) { "Setting visibility to VISIBLE when false would have no effect." } require(visibilityWhenFalse == View.INVISIBLE || visibilityWhenFalse == View.GONE) { "Must set visibility to INVISIBLE or GONE when false." } return Consumer { value -> visibility = if (value) View.VISIBLE else visibilityWhenFalse } }
apache-2.0
182a906aa9b39f143a269f11bfb89242
32.37931
97
0.752066
4.084388
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/modules/AutomodModule.kt
1
10732
package net.perfectdreams.loritta.morenitta.modules import com.github.benmanes.caffeine.cache.Caffeine import com.google.common.collect.EvictingQueue import com.google.common.collect.Queues import dev.kord.common.entity.Snowflake import net.perfectdreams.loritta.morenitta.commands.vanilla.administration.AdminUtils import net.perfectdreams.loritta.morenitta.commands.vanilla.administration.BanCommand import net.perfectdreams.loritta.morenitta.dao.Profile import net.perfectdreams.loritta.morenitta.dao.ServerConfig import net.perfectdreams.loritta.morenitta.events.LorittaMessageEvent import net.perfectdreams.loritta.morenitta.utils.Constants import net.perfectdreams.loritta.morenitta.utils.LorittaPermission import net.perfectdreams.loritta.morenitta.utils.LorittaUser import net.perfectdreams.loritta.morenitta.utils.config.EnvironmentType import net.perfectdreams.loritta.common.locale.BaseLocale import mu.KotlinLogging import net.dv8tion.jda.api.entities.Message import net.dv8tion.jda.api.entities.User import net.perfectdreams.loritta.morenitta.LorittaBot import org.apache.commons.text.similarity.LevenshteinDistance import java.util.* import java.util.concurrent.TimeUnit class AutomodModule(val loritta: LorittaBot) : MessageReceivedModule { companion object { val MESSAGES = Caffeine.newBuilder().expireAfterWrite(5L, TimeUnit.MINUTES).build<String, Queue<Message>>().asMap() const val FRESH_ACCOUNT_TIMEOUT = 604_800_000L var ANTIRAID_ENABLED = true var SIMILAR_MESSAGE_MULTIPLIER = 0.0020 var SIMILARITY_THRESHOLD = 7 var IN_ROW_SAME_USER_SIMILAR_SCORE = 0.064 var IN_ROW_DIFFERENT_USER_SIMILAR_SCORE = 0.056 var DISTANCE_MULTIPLIER = 0.02 var ATTACHED_IMAGE_SCORE = 0.015 var SAME_LINK_SCORE = 0.005 var SIMILAR_SAME_AUTHOR_MESSAGE_MULTIPLIER = 0.024 var NO_AVATAR_SCORE = 0.04 var MUTUAL_GUILDS_MULTIPLIER = 0.01 var FRESH_ACCOUNT_DISCORD_MULTIPLIER = 0.00000000004 var FRESH_ACCOUNT_JOINED_MULTIPLIER = 0.00000000013 var QUEUE_SIZE = 50 var BAN_THRESHOLD = 0.75 val COMMON_EMOTES = listOf( ";-;", ";w;", "uwu", "owo", "-.-", "'-'", "'='", ";=;", "-w-", "e.e", "e_e", "p-p", "q-q", "p-q", "q-p", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "oi", "olá", "oie", "oin", "eu" ) private val logger = KotlinLogging.logger {} } override suspend fun matches(event: LorittaMessageEvent, lorittaUser: LorittaUser, lorittaProfile: Profile?, serverConfig: ServerConfig, locale: BaseLocale): Boolean { if (lorittaUser.hasPermission(LorittaPermission.BYPASS_AUTO_MOD)) return false return true } override suspend fun handle(event: LorittaMessageEvent, lorittaUser: LorittaUser, lorittaProfile: Profile?, serverConfig: ServerConfig, locale: BaseLocale): Boolean { if (ANTIRAID_ENABLED && (loritta.config.loritta.antiRaidIds.contains(Snowflake(event.channel.id))) && loritta.config.loritta.environment == EnvironmentType.CANARY) { val messages = MESSAGES.getOrPut(event.textChannel!!.id) { Queues.synchronizedQueue(EvictingQueue.create<Message>(50)) } fun calculateRaidingPercentage(wrapper: Message): Double { var content = wrapper.contentRaw.toLowerCase() for (emote in AutomodModule.COMMON_EMOTES) content = content.replace(emote, "") val pattern = Constants.HTTP_URL_PATTERN val matcher = pattern.matcher(wrapper.contentRaw) val urlsDetected = mutableSetOf<String>() while (matcher.find()) urlsDetected.add(matcher.group(0)) val raider = wrapper.author var raidingPercentage = 0.0 val verySimilarMessages = mutableListOf<Message>() var streamFloodCounter = 0 messageLoop@for ((index, message) in messages.reversed().withIndex()) { val distanceMultiplier = ((AutomodModule.QUEUE_SIZE - index) * AutomodModule.DISTANCE_MULTIPLIER) if (message.contentRaw.isNotBlank()) { var compareContent = message.contentRaw.toLowerCase() for (emote in AutomodModule.COMMON_EMOTES) compareContent = compareContent.replace(emote, "") val contentIsBlank = compareContent.isBlank() val withoutEmoteBlankMultiplier = if (contentIsBlank) 0.3 else 1.0 if (0 > streamFloodCounter) streamFloodCounter = 0 val isStreamFlood = 3 > streamFloodCounter val threshold = LevenshteinDistance.getDefaultInstance().apply(compareContent.toLowerCase(), content.toLowerCase()) if (3 >= threshold && wrapper.author.id == message.author.id) { // Vamos melhorar caso exista alguns "one person raider" verySimilarMessages.add(message) } if (5 >= threshold && isStreamFlood) { // Vamos aumentar os pontos caso sejam mensagens parecidas em seguida // threshold = 0..5 // vamos aumentar as chances caso o conteúdo seja similar // 0 == * 1 // 1 == * 0.75 // etc // 5 - 0 = 5 // 5 - 1 = 4 val similarityMultiplier = (5 - Math.min(5, threshold)) raidingPercentage += if (wrapper.author.id == message.author.id) { AutomodModule.IN_ROW_SAME_USER_SIMILAR_SCORE } else { AutomodModule.IN_ROW_DIFFERENT_USER_SIMILAR_SCORE } * distanceMultiplier * withoutEmoteBlankMultiplier * (similarityMultiplier * 0.2) // analysis(analysis, "+ Stream Flood (mesmo usuário: ${(wrapper.author.id == message.author.id)}) - Valor atual é $raidingPercentage") streamFloodCounter-- } else { streamFloodCounter++ } val similarMessageScore = distanceMultiplier * AutomodModule.SIMILAR_MESSAGE_MULTIPLIER * (Math.max(0, AutomodModule.SIMILARITY_THRESHOLD - threshold)) raidingPercentage += similarMessageScore } if (wrapper.attachments.isNotEmpty() && message.attachments.isNotEmpty()) { raidingPercentage += AutomodModule.ATTACHED_IMAGE_SCORE * distanceMultiplier // analysis(analysis, "+ Possui attachments ~ ${AutomodModule.ATTACHED_IMAGE_SCORE} - Valor atual é $raidingPercentage") // println(">>> ${wrapper.author.id}: ATTACHED_IMAGE_SCORE ${raidingPercentage}") } val matcher2 = pattern.matcher(wrapper.contentRaw) while (matcher2.find()) { if (urlsDetected.contains(matcher2.group(0))) { // analysis(analysis, "+ Mesmo link ~ ${AutomodModule.SAME_LINK_SCORE} - Valor atual é $raidingPercentage") raidingPercentage += distanceMultiplier * AutomodModule.SAME_LINK_SCORE continue@messageLoop } } } val similarSameAuthorScore = AutomodModule.SIMILAR_SAME_AUTHOR_MESSAGE_MULTIPLIER * verySimilarMessages.size // analysis(analysis, "+ similarSameAuthorScore é $similarSameAuthorScore - Valor atual é $raidingPercentage") raidingPercentage += similarSameAuthorScore // Caso o usuário não tenha avatar if (wrapper.author.avatarUrl == null) { raidingPercentage += AutomodModule.NO_AVATAR_SCORE // analysis(analysis, "+ Usuário não possui avatar, então iremos adicionar ${AutomodModule.NO_AVATAR_SCORE} a porcentagem - Valor atual é $raidingPercentage") } // Caso o usuário esteja em poucos servidores compartilhados, a chance de ser raider é maior val nonMutualGuildsScore = AutomodModule.MUTUAL_GUILDS_MULTIPLIER * Math.max(5 - raider.mutualGuilds.size, 1) // analysis(analysis, "+ nonMutualGuildsScore é $nonMutualGuildsScore - Valor atual é $raidingPercentage") raidingPercentage += nonMutualGuildsScore // Conta nova no Discord val newAccountScore = AutomodModule.FRESH_ACCOUNT_DISCORD_MULTIPLIER * Math.max(0, AutomodModule.FRESH_ACCOUNT_TIMEOUT - (System.currentTimeMillis() - wrapper.author.timeCreated.toInstant().toEpochMilli())) // analysis(analysis, "+ newAccountScore é $nonMutualGuildsScore - Valor atual é $raidingPercentage") raidingPercentage += newAccountScore // Conta nova que entrou no servidor val member = event.member if (member != null) { val recentlyJoinedScore = AutomodModule.FRESH_ACCOUNT_JOINED_MULTIPLIER * Math.max(0, AutomodModule.FRESH_ACCOUNT_TIMEOUT - (System.currentTimeMillis() - member.timeJoined.toInstant().toEpochMilli())) // analysis(analysis, "+ recentlyJoinedScore é $recentlyJoinedScore - Valor atual é $raidingPercentage") raidingPercentage += recentlyJoinedScore } return raidingPercentage } val raidingPercentage = calculateRaidingPercentage(event.message) logger.info("[${event.guild!!.name} -> ${event.channel.name}] ${event.author.id} (${raidingPercentage}% chance de ser raider: ${event.message.contentRaw}") if (raidingPercentage >= 0.5) { logger.warn("[${event.guild.name} -> ${event.channel.name}] ${event.author.id} (${raidingPercentage}% chance de ser raider (CHANCE ALTA DEMAIS!): ${event.message.contentRaw}") } if (raidingPercentage >= BAN_THRESHOLD) { logger.info("Aplicando punimentos em ${event.guild.name} -> ${event.channel.name}, causado por ${event.author.id}!") val settings = AdminUtils.retrieveModerationInfo(loritta, serverConfig) synchronized(event.guild) { val alreadyBanned = mutableListOf<User>() for (storedMessage in messages) { if (!event.guild.isMember(event.author) || alreadyBanned.contains(storedMessage.author)) // O usuário já pode estar banido continue val percentage = calculateRaidingPercentage(storedMessage) if (percentage >= BAN_THRESHOLD) { alreadyBanned.add(storedMessage.author) if (event.guild.selfMember.canInteract(event.member!!)) { logger.info("Punindo ${storedMessage.author.id} em ${event.guild.name} -> ${event.channel.name} por tentativa de raid! ($percentage%)!") BanCommand.ban(loritta, settings, event.guild, event.guild.selfMember.user, locale, storedMessage.author, "Tentativa de Raid (Spam/Flood)! Que feio, para que fazer isto? Vá procurar algo melhor para fazer em vez de incomodar outros servidores. ᕙ(⇀‸↼‶)ᕗ", false, 7) } } } if (!event.guild.isMember(event.author) || alreadyBanned.contains(event.author)) // O usuário já pode estar banido return true if (event.guild.selfMember.canInteract(event.member!!)) { logger.info("Punindo ${event.author.id} em ${event.guild.name} -> ${event.channel.name} por tentativa de raid! ($raidingPercentage%)!") BanCommand.ban(loritta, settings, event.guild, event.guild.selfMember.user, locale, event.author, "Tentativa de Raid (Spam/Flood)! Que feio, para que fazer isto? Vá procurar algo melhor para fazer em vez de incomodar outros servidores. ᕙ(⇀‸↼‶)ᕗ", false, 7) } } return true } messages.add(event.message) } return false } }
agpl-3.0
ffe9c457b0426fb5e4883b0d1188213e
41.553785
272
0.7147
3.452958
false
false
false
false
chrsep/Kingfish
app/src/main/java/com/directdev/portal/models/SessionModel.kt
1
1516
package com.directdev.portal.models import com.squareup.moshi.Json import io.realm.RealmObject open class SessionModel( @Json(name = "CLASS_SECTION") open var classId: String = "N/A", //"LB02" @Json(name = "COURSE_TITLE_LONG") open var courseName: String = "N/A", //"Character Building: Agama" @Json(name = "CRSE_CODE") open var courseId: String = "N/A", //""COMP6060"" @Json(name = "START_DT") open var date: String = "N/A", //""2014-09-23 00:00:00.000"" @Json(name = "LOCATION") open var locationId: String = "N/A", //""COMP6060"" @Json(name = "LOCATION_DESCR") open var locationName: String = "N/A", //""COMP6060"" @Json(name = "MEETING_TIME_START") open var startTime: String = "N/A", //""COMP6060"" @Json(name = "MEETING_TIME_END") open var endTime: String = "N/A", //""COMP6060"" @Json(name = "N_DELIVERY_MODE") open var deliveryMode: String = "N/A", //""COMP6060"" @Json(name = "N_WEEK_SESSION") open var weekCount: String = "N/A", //""COMP6060"" @Json(name = "ROOM") open var room: String = "N/A", //""COMP6060"" @Json(name = "SSR_COMPONENT") open var typeId: String = "N/A", //""COMP6060"" @Json(name = "SSR_DESCR") open var typeName: String = "N/A", //""COMP6060"" @Json(name = "SessionIDNum") open var sessionCount: String = "N/A" //""COMP6060"" ) : RealmObject()
gpl-3.0
a49ce769006c4b12cf7719b056a3ff67
29.32
74
0.55277
3.267241
false
false
false
false
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/HistoryLastReadPutResolver.kt
6
2298
package eu.kanade.tachiyomi.data.database.resolvers import android.content.ContentValues import android.support.annotation.NonNull import com.pushtorefresh.storio.sqlite.StorIOSQLite import com.pushtorefresh.storio.sqlite.operations.put.PutResult import com.pushtorefresh.storio.sqlite.queries.Query import com.pushtorefresh.storio.sqlite.queries.UpdateQuery import eu.kanade.tachiyomi.data.database.inTransactionReturn import eu.kanade.tachiyomi.data.database.mappers.HistoryPutResolver import eu.kanade.tachiyomi.data.database.models.History import eu.kanade.tachiyomi.data.database.tables.HistoryTable class HistoryLastReadPutResolver : HistoryPutResolver() { /** * Updates last_read time of chapter */ override fun performPut(@NonNull db: StorIOSQLite, @NonNull history: History): PutResult = db.inTransactionReturn { val updateQuery = mapToUpdateQuery(history) val cursor = db.lowLevel().query(Query.builder() .table(updateQuery.table()) .where(updateQuery.where()) .whereArgs(updateQuery.whereArgs()) .build()) val putResult: PutResult try { if (cursor.count == 0) { val insertQuery = mapToInsertQuery(history) val insertedId = db.lowLevel().insert(insertQuery, mapToContentValues(history)) putResult = PutResult.newInsertResult(insertedId, insertQuery.table()) } else { val numberOfRowsUpdated = db.lowLevel().update(updateQuery, mapToUpdateContentValues(history)) putResult = PutResult.newUpdateResult(numberOfRowsUpdated, updateQuery.table()) } } finally { cursor.close() } putResult } /** * Creates update query * @param obj history object */ override fun mapToUpdateQuery(obj: History) = UpdateQuery.builder() .table(HistoryTable.TABLE) .where("${HistoryTable.COL_CHAPTER_ID} = ?") .whereArgs(obj.chapter_id) .build() /** * Create content query * @param history object */ fun mapToUpdateContentValues(history: History) = ContentValues(1).apply { put(HistoryTable.COL_LAST_READ, history.last_read) } }
apache-2.0
128e2e4f36691bf46b465ddea94d0388
34.90625
119
0.667972
4.568588
false
false
false
false
rectangle-dbmi/Realtime-Port-Authority
app/src/main/java/rectangledbmi/com/pittsburghrealtimetracker/selection/Route.kt
1
3278
package rectangledbmi.com.pittsburghrealtimetracker.selection import android.graphics.Color /** * This is the object container that contains all information of the buses * * Created by epicstar on 9/5/14. * * @author Jeremy Jao * @author Michael Antonacci */ class Route /** * The main route constructor * @param route the route number * @param routeInfo the route info * @param routeColor the color of the route as an int */ ( /** * This is the route number */ val route: String?, /** * This is the route's general 3 word summary */ val routeInfo: String?, /** * This is the color of the route as an int */ var routeColor: Int, /** * Position of the route in the list * * @since 43 */ private val listPosition: Int, /** * Whether or not the route is selected */ var isSelected: Boolean) { /** * Gets the int color as a hex string from: * http://stackoverflow.com/questions/4506708/android-convert-color-int-to-hexa-string * * @return color as hex-string */ val colorAsString: String get() = String.format("#%06X", 0xFFFFFF and routeColor) /** * The non-null constructor of the route and color as a string or hex-string * @param route the route number * @param routeInfo the route info * @param routeColor the color of the route as a string or string-hex */ constructor(route: String, routeInfo: String, routeColor: String, listPosition: Int, isSelected: Boolean) : this(route, routeInfo, Color.parseColor(routeColor), listPosition, isSelected) /** * Copy constructor for Route objects * @param route */ constructor(route: Route) : this(route.route, route.routeInfo, route.routeColor, route.listPosition, route.isSelected) /** * set the route color if a String is fed * @param routeColor the route color as a String */ fun setRouteColor(routeColor: String) { this.routeColor = Color.parseColor(routeColor) } /** * * @return true if state is changed to selected * @since 58 */ private fun selectRoute(): Boolean { if (!isSelected) { isSelected = true return true } return false } /** * * @return true if state is changed to deselected * @since 58 */ private fun deselectRoute(): Boolean { if (isSelected) { isSelected = false return true } return false } /** * Toggles the selection to change the state of the route's selection. * * @return true if the route becomes selected; false if it becomes unselected * @since 58 */ @Suppress("LiftReturnOrAssignment") fun toggleSelection(): Boolean { if (isSelected) { deselectRoute() return false } else { selectRoute() return true } } /** * Auto-Generated by Android Studio * @return String of Route */ override fun toString(): String = "$route - $routeInfo\ncolor: $routeColor - $colorAsString" }
gpl-3.0
435be7ec729a4d773a5e0890556da793
25.650407
190
0.589689
4.394102
false
false
false
false
cketti/okhttp
okhttp/src/main/kotlin/okhttp3/Cache.kt
1
26484
/* * Copyright (C) 2010 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 okhttp3 import java.io.Closeable import java.io.File import java.io.Flushable import java.io.IOException import java.security.cert.Certificate import java.security.cert.CertificateEncodingException import java.security.cert.CertificateException import java.security.cert.CertificateFactory import java.util.NoSuchElementException import java.util.TreeSet import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.internal.EMPTY_HEADERS import okhttp3.internal.cache.CacheRequest import okhttp3.internal.cache.CacheStrategy import okhttp3.internal.cache.DiskLruCache import okhttp3.internal.closeQuietly import okhttp3.internal.concurrent.TaskRunner import okhttp3.internal.http.HttpMethod import okhttp3.internal.http.StatusLine import okhttp3.internal.io.FileSystem import okhttp3.internal.platform.Platform import okhttp3.internal.toLongOrDefault import okio.Buffer import okio.BufferedSink import okio.BufferedSource import okio.ByteString.Companion.decodeBase64 import okio.ByteString.Companion.encodeUtf8 import okio.ByteString.Companion.toByteString import okio.ForwardingSink import okio.ForwardingSource import okio.Sink import okio.Source import okio.buffer /** * Caches HTTP and HTTPS responses to the filesystem so they may be reused, saving time and * bandwidth. * * ## Cache Optimization * * To measure cache effectiveness, this class tracks three statistics: * * * **[Request Count:][requestCount]** the number of HTTP requests issued since this cache was * created. * * **[Network Count:][networkCount]** the number of those requests that required network use. * * **[Hit Count:][hitCount]** the number of those requests whose responses were served by the * cache. * * Sometimes a request will result in a conditional cache hit. If the cache contains a stale copy of * the response, the client will issue a conditional `GET`. The server will then send either * the updated response if it has changed, or a short 'not modified' response if the client's copy * is still valid. Such responses increment both the network count and hit count. * * The best way to improve the cache hit rate is by configuring the web server to return cacheable * responses. Although this client honors all [HTTP/1.1 (RFC 7234)][rfc_7234] cache headers, it * doesn't cache partial responses. * * ## Force a Network Response * * In some situations, such as after a user clicks a 'refresh' button, it may be necessary to skip * the cache, and fetch data directly from the server. To force a full refresh, add the `no-cache` * directive: * * ``` * Request request = new Request.Builder() * .cacheControl(new CacheControl.Builder().noCache().build()) * .url("http://publicobject.com/helloworld.txt") * .build(); * ``` * * If it is only necessary to force a cached response to be validated by the server, use the more * efficient `max-age=0` directive instead: * * ``` * Request request = new Request.Builder() * .cacheControl(new CacheControl.Builder() * .maxAge(0, TimeUnit.SECONDS) * .build()) * .url("http://publicobject.com/helloworld.txt") * .build(); * ``` * * ## Force a Cache Response * * Sometimes you'll want to show resources if they are available immediately, but not otherwise. * This can be used so your application can show *something* while waiting for the latest data to be * downloaded. To restrict a request to locally-cached resources, add the `only-if-cached` * directive: * * ``` * Request request = new Request.Builder() * .cacheControl(new CacheControl.Builder() * .onlyIfCached() * .build()) * .url("http://publicobject.com/helloworld.txt") * .build(); * Response forceCacheResponse = client.newCall(request).execute(); * if (forceCacheResponse.code() != 504) { * // The resource was cached! Show it. * } else { * // The resource was not cached. * } * ``` * * This technique works even better in situations where a stale response is better than no response. * To permit stale cached responses, use the `max-stale` directive with the maximum staleness in * seconds: * * ``` * Request request = new Request.Builder() * .cacheControl(new CacheControl.Builder() * .maxStale(365, TimeUnit.DAYS) * .build()) * .url("http://publicobject.com/helloworld.txt") * .build(); * ``` * * The [CacheControl] class can configure request caching directives and parse response caching * directives. It even offers convenient constants [CacheControl.FORCE_NETWORK] and * [CacheControl.FORCE_CACHE] that address the use cases above. * * [rfc_7234]: http://tools.ietf.org/html/rfc7234 */ class Cache internal constructor( directory: File, maxSize: Long, fileSystem: FileSystem ) : Closeable, Flushable { internal val cache = DiskLruCache( fileSystem = fileSystem, directory = directory, appVersion = VERSION, valueCount = ENTRY_COUNT, maxSize = maxSize, taskRunner = TaskRunner.INSTANCE ) // read and write statistics, all guarded by 'this'. internal var writeSuccessCount = 0 internal var writeAbortCount = 0 private var networkCount = 0 private var hitCount = 0 private var requestCount = 0 val isClosed: Boolean get() = cache.isClosed() /** Create a cache of at most [maxSize] bytes in [directory]. */ constructor(directory: File, maxSize: Long) : this(directory, maxSize, FileSystem.SYSTEM) internal fun get(request: Request): Response? { val key = key(request.url) val snapshot: DiskLruCache.Snapshot = try { cache[key] ?: return null } catch (_: IOException) { return null // Give up because the cache cannot be read. } val entry: Entry = try { Entry(snapshot.getSource(ENTRY_METADATA)) } catch (_: IOException) { snapshot.closeQuietly() return null } val response = entry.response(snapshot) if (!entry.matches(request, response)) { response.body?.closeQuietly() return null } return response } internal fun put(response: Response): CacheRequest? { val requestMethod = response.request.method if (HttpMethod.invalidatesCache(response.request.method)) { try { remove(response.request) } catch (_: IOException) { // The cache cannot be written. } return null } if (requestMethod != "GET") { // Don't cache non-GET responses. We're technically allowed to cache HEAD requests and some // POST requests, but the complexity of doing so is high and the benefit is low. return null } if (response.hasVaryAll()) { return null } val entry = Entry(response) var editor: DiskLruCache.Editor? = null try { editor = cache.edit(key(response.request.url)) ?: return null entry.writeTo(editor) return RealCacheRequest(editor) } catch (_: IOException) { abortQuietly(editor) return null } } @Throws(IOException::class) internal fun remove(request: Request) { cache.remove(key(request.url)) } internal fun update(cached: Response, network: Response) { val entry = Entry(network) val snapshot = (cached.body as CacheResponseBody).snapshot var editor: DiskLruCache.Editor? = null try { editor = snapshot.edit() ?: return // edit() returns null if snapshot is not current. entry.writeTo(editor) editor.commit() } catch (_: IOException) { abortQuietly(editor) } } private fun abortQuietly(editor: DiskLruCache.Editor?) { // Give up because the cache cannot be written. try { editor?.abort() } catch (_: IOException) { } } /** * Initialize the cache. This will include reading the journal files from the storage and building * up the necessary in-memory cache information. * * The initialization time may vary depending on the journal file size and the current actual * cache size. The application needs to be aware of calling this function during the * initialization phase and preferably in a background worker thread. * * Note that if the application chooses to not call this method to initialize the cache. By * default, OkHttp will perform lazy initialization upon the first usage of the cache. */ @Throws(IOException::class) fun initialize() { cache.initialize() } /** * Closes the cache and deletes all of its stored values. This will delete all files in the cache * directory including files that weren't created by the cache. */ @Throws(IOException::class) fun delete() { cache.delete() } /** * Deletes all values stored in the cache. In-flight writes to the cache will complete normally, * but the corresponding responses will not be stored. */ @Throws(IOException::class) fun evictAll() { cache.evictAll() } /** * Returns an iterator over the URLs in this cache. This iterator doesn't throw * `ConcurrentModificationException`, but if new responses are added while iterating, their URLs * will not be returned. If existing responses are evicted during iteration, they will be absent * (unless they were already returned). * * The iterator supports [MutableIterator.remove]. Removing a URL from the iterator evicts the * corresponding response from the cache. Use this to evict selected responses. */ @Throws(IOException::class) fun urls(): MutableIterator<String> { return object : MutableIterator<String> { private val delegate: MutableIterator<DiskLruCache.Snapshot> = cache.snapshots() private var nextUrl: String? = null private var canRemove = false override fun hasNext(): Boolean { if (nextUrl != null) return true canRemove = false // Prevent delegate.remove() on the wrong item! while (delegate.hasNext()) { try { delegate.next().use { snapshot -> val metadata = snapshot.getSource(ENTRY_METADATA).buffer() nextUrl = metadata.readUtf8LineStrict() return true } } catch (_: IOException) { // We couldn't read the metadata for this snapshot; possibly because the host filesystem // has disappeared! Skip it. } } return false } override fun next(): String { if (!hasNext()) throw NoSuchElementException() val result = nextUrl!! nextUrl = null canRemove = true return result } override fun remove() { check(canRemove) { "remove() before next()" } delegate.remove() } } } @Synchronized fun writeAbortCount(): Int = writeAbortCount @Synchronized fun writeSuccessCount(): Int = writeSuccessCount @Throws(IOException::class) fun size(): Long = cache.size() /** Max size of the cache (in bytes). */ fun maxSize(): Long = cache.maxSize @Throws(IOException::class) override fun flush() { cache.flush() } @Throws(IOException::class) override fun close() { cache.close() } @get:JvmName("directory") val directory: File get() = cache.directory @JvmName("-deprecated_directory") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "directory"), level = DeprecationLevel.ERROR) fun directory(): File = cache.directory @Synchronized internal fun trackResponse(cacheStrategy: CacheStrategy) { requestCount++ if (cacheStrategy.networkRequest != null) { // If this is a conditional request, we'll increment hitCount if/when it hits. networkCount++ } else if (cacheStrategy.cacheResponse != null) { // This response uses the cache and not the network. That's a cache hit. hitCount++ } } @Synchronized internal fun trackConditionalCacheHit() { hitCount++ } @Synchronized fun networkCount(): Int = networkCount @Synchronized fun hitCount(): Int = hitCount @Synchronized fun requestCount(): Int = requestCount private inner class RealCacheRequest internal constructor( private val editor: DiskLruCache.Editor ) : CacheRequest { private val cacheOut: Sink = editor.newSink(ENTRY_BODY) private val body: Sink internal var done = false init { this.body = object : ForwardingSink(cacheOut) { @Throws(IOException::class) override fun close() { synchronized(this@Cache) { if (done) return done = true writeSuccessCount++ } super.close() editor.commit() } } } override fun abort() { synchronized(this@Cache) { if (done) return done = true writeAbortCount++ } cacheOut.closeQuietly() try { editor.abort() } catch (_: IOException) { } } override fun body(): Sink = body } private class Entry { private val url: String private val varyHeaders: Headers private val requestMethod: String private val protocol: Protocol private val code: Int private val message: String private val responseHeaders: Headers private val handshake: Handshake? private val sentRequestMillis: Long private val receivedResponseMillis: Long private val isHttps: Boolean get() = url.startsWith("https://") /** * Reads an entry from an input stream. A typical entry looks like this: * * ``` * http://google.com/foo * GET * 2 * Accept-Language: fr-CA * Accept-Charset: UTF-8 * HTTP/1.1 200 OK * 3 * Content-Type: image/png * Content-Length: 100 * Cache-Control: max-age=600 * ``` * * A typical HTTPS file looks like this: * * ``` * https://google.com/foo * GET * 2 * Accept-Language: fr-CA * Accept-Charset: UTF-8 * HTTP/1.1 200 OK * 3 * Content-Type: image/png * Content-Length: 100 * Cache-Control: max-age=600 * * AES_256_WITH_MD5 * 2 * base64-encoded peerCertificate[0] * base64-encoded peerCertificate[1] * -1 * TLSv1.2 * ``` * * The file is newline separated. The first two lines are the URL and the request method. Next * is the number of HTTP Vary request header lines, followed by those lines. * * Next is the response status line, followed by the number of HTTP response header lines, * followed by those lines. * * HTTPS responses also contain SSL session information. This begins with a blank line, and then * a line containing the cipher suite. Next is the length of the peer certificate chain. These * certificates are base64-encoded and appear each on their own line. The next line contains the * length of the local certificate chain. These certificates are also base64-encoded and appear * each on their own line. A length of -1 is used to encode a null array. The last line is * optional. If present, it contains the TLS version. */ @Throws(IOException::class) internal constructor(rawSource: Source) { try { val source = rawSource.buffer() url = source.readUtf8LineStrict() requestMethod = source.readUtf8LineStrict() val varyHeadersBuilder = Headers.Builder() val varyRequestHeaderLineCount = readInt(source) for (i in 0 until varyRequestHeaderLineCount) { varyHeadersBuilder.addLenient(source.readUtf8LineStrict()) } varyHeaders = varyHeadersBuilder.build() val statusLine = StatusLine.parse(source.readUtf8LineStrict()) protocol = statusLine.protocol code = statusLine.code message = statusLine.message val responseHeadersBuilder = Headers.Builder() val responseHeaderLineCount = readInt(source) for (i in 0 until responseHeaderLineCount) { responseHeadersBuilder.addLenient(source.readUtf8LineStrict()) } val sendRequestMillisString = responseHeadersBuilder[SENT_MILLIS] val receivedResponseMillisString = responseHeadersBuilder[RECEIVED_MILLIS] responseHeadersBuilder.removeAll(SENT_MILLIS) responseHeadersBuilder.removeAll(RECEIVED_MILLIS) sentRequestMillis = sendRequestMillisString?.toLong() ?: 0L receivedResponseMillis = receivedResponseMillisString?.toLong() ?: 0L responseHeaders = responseHeadersBuilder.build() if (isHttps) { val blank = source.readUtf8LineStrict() if (blank.isNotEmpty()) { throw IOException("expected \"\" but was \"$blank\"") } val cipherSuiteString = source.readUtf8LineStrict() val cipherSuite = CipherSuite.forJavaName(cipherSuiteString) val peerCertificates = readCertificateList(source) val localCertificates = readCertificateList(source) val tlsVersion = if (!source.exhausted()) { TlsVersion.forJavaName(source.readUtf8LineStrict()) } else { TlsVersion.SSL_3_0 } handshake = Handshake.get(tlsVersion, cipherSuite, peerCertificates, localCertificates) } else { handshake = null } } finally { rawSource.close() } } internal constructor(response: Response) { this.url = response.request.url.toString() this.varyHeaders = response.varyHeaders() this.requestMethod = response.request.method this.protocol = response.protocol this.code = response.code this.message = response.message this.responseHeaders = response.headers this.handshake = response.handshake this.sentRequestMillis = response.sentRequestAtMillis this.receivedResponseMillis = response.receivedResponseAtMillis } @Throws(IOException::class) fun writeTo(editor: DiskLruCache.Editor) { editor.newSink(ENTRY_METADATA).buffer().use { sink -> sink.writeUtf8(url).writeByte('\n'.toInt()) sink.writeUtf8(requestMethod).writeByte('\n'.toInt()) sink.writeDecimalLong(varyHeaders.size.toLong()).writeByte('\n'.toInt()) for (i in 0 until varyHeaders.size) { sink.writeUtf8(varyHeaders.name(i)) .writeUtf8(": ") .writeUtf8(varyHeaders.value(i)) .writeByte('\n'.toInt()) } sink.writeUtf8(StatusLine(protocol, code, message).toString()).writeByte('\n'.toInt()) sink.writeDecimalLong((responseHeaders.size + 2).toLong()).writeByte('\n'.toInt()) for (i in 0 until responseHeaders.size) { sink.writeUtf8(responseHeaders.name(i)) .writeUtf8(": ") .writeUtf8(responseHeaders.value(i)) .writeByte('\n'.toInt()) } sink.writeUtf8(SENT_MILLIS) .writeUtf8(": ") .writeDecimalLong(sentRequestMillis) .writeByte('\n'.toInt()) sink.writeUtf8(RECEIVED_MILLIS) .writeUtf8(": ") .writeDecimalLong(receivedResponseMillis) .writeByte('\n'.toInt()) if (isHttps) { sink.writeByte('\n'.toInt()) sink.writeUtf8(handshake!!.cipherSuite.javaName).writeByte('\n'.toInt()) writeCertList(sink, handshake.peerCertificates) writeCertList(sink, handshake.localCertificates) sink.writeUtf8(handshake.tlsVersion.javaName).writeByte('\n'.toInt()) } } } @Throws(IOException::class) private fun readCertificateList(source: BufferedSource): List<Certificate> { val length = readInt(source) if (length == -1) return emptyList() // OkHttp v1.2 used -1 to indicate null. try { val certificateFactory = CertificateFactory.getInstance("X.509") val result = ArrayList<Certificate>(length) for (i in 0 until length) { val line = source.readUtf8LineStrict() val bytes = Buffer() bytes.write(line.decodeBase64()!!) result.add(certificateFactory.generateCertificate(bytes.inputStream())) } return result } catch (e: CertificateException) { throw IOException(e.message) } } @Throws(IOException::class) private fun writeCertList(sink: BufferedSink, certificates: List<Certificate>) { try { sink.writeDecimalLong(certificates.size.toLong()).writeByte('\n'.toInt()) for (i in 0 until certificates.size) { val bytes = certificates[i].encoded val line = bytes.toByteString().base64() sink.writeUtf8(line).writeByte('\n'.toInt()) } } catch (e: CertificateEncodingException) { throw IOException(e.message) } } fun matches(request: Request, response: Response): Boolean { return url == request.url.toString() && requestMethod == request.method && varyMatches(response, varyHeaders, request) } fun response(snapshot: DiskLruCache.Snapshot): Response { val contentType = responseHeaders["Content-Type"] val contentLength = responseHeaders["Content-Length"] val cacheRequest = Request.Builder() .url(url) .method(requestMethod, null) .headers(varyHeaders) .build() return Response.Builder() .request(cacheRequest) .protocol(protocol) .code(code) .message(message) .headers(responseHeaders) .body(CacheResponseBody(snapshot, contentType, contentLength)) .handshake(handshake) .sentRequestAtMillis(sentRequestMillis) .receivedResponseAtMillis(receivedResponseMillis) .build() } companion object { /** Synthetic response header: the local time when the request was sent. */ private val SENT_MILLIS = "${Platform.get().getPrefix()}-Sent-Millis" /** Synthetic response header: the local time when the response was received. */ private val RECEIVED_MILLIS = "${Platform.get().getPrefix()}-Received-Millis" } } private class CacheResponseBody internal constructor( internal val snapshot: DiskLruCache.Snapshot, private val contentType: String?, private val contentLength: String? ) : ResponseBody() { private val bodySource: BufferedSource init { val source = snapshot.getSource(ENTRY_BODY) bodySource = object : ForwardingSource(source) { @Throws(IOException::class) override fun close() { snapshot.close() super.close() } }.buffer() } override fun contentType(): MediaType? = contentType?.toMediaTypeOrNull() override fun contentLength(): Long = contentLength?.toLongOrDefault(-1L) ?: -1L override fun source(): BufferedSource = bodySource } companion object { private const val VERSION = 201105 private const val ENTRY_METADATA = 0 private const val ENTRY_BODY = 1 private const val ENTRY_COUNT = 2 @JvmStatic fun key(url: HttpUrl): String = url.toString().encodeUtf8().md5().hex() @Throws(IOException::class) internal fun readInt(source: BufferedSource): Int { try { val result = source.readDecimalLong() val line = source.readUtf8LineStrict() if (result < 0L || result > Integer.MAX_VALUE || line.isNotEmpty()) { throw IOException("expected an int but was \"$result$line\"") } return result.toInt() } catch (e: NumberFormatException) { throw IOException(e.message) } } /** * Returns true if none of the Vary headers have changed between [cachedRequest] and * [newRequest]. */ fun varyMatches( cachedResponse: Response, cachedRequest: Headers, newRequest: Request ): Boolean { return cachedResponse.headers.varyFields().none { cachedRequest.values(it) != newRequest.headers(it) } } /** Returns true if a Vary header contains an asterisk. Such responses cannot be cached. */ fun Response.hasVaryAll() = "*" in headers.varyFields() /** * Returns the names of the request headers that need to be checked for equality when caching. */ private fun Headers.varyFields(): Set<String> { var result: MutableSet<String>? = null for (i in 0 until size) { if (!"Vary".equals(name(i), ignoreCase = true)) { continue } val value = value(i) if (result == null) { result = TreeSet(String.CASE_INSENSITIVE_ORDER) } for (varyField in value.split(',')) { result.add(varyField.trim()) } } return result ?: emptySet() } /** * Returns the subset of the headers in this's request that impact the content of this's body. */ fun Response.varyHeaders(): Headers { // Use the request headers sent over the network, since that's what the response varies on. // Otherwise OkHttp-supplied headers like "Accept-Encoding: gzip" may be lost. val requestHeaders = networkResponse!!.request.headers val responseHeaders = headers return varyHeaders(requestHeaders, responseHeaders) } /** * Returns the subset of the headers in [requestHeaders] that impact the content of the * response's body. */ private fun varyHeaders(requestHeaders: Headers, responseHeaders: Headers): Headers { val varyFields = responseHeaders.varyFields() if (varyFields.isEmpty()) return EMPTY_HEADERS val result = Headers.Builder() for (i in 0 until requestHeaders.size) { val fieldName = requestHeaders.name(i) if (fieldName in varyFields) { result.add(fieldName, requestHeaders.value(i)) } } return result.build() } } }
apache-2.0
5773d01a2db4c4ca66202881964d8485
32.823755
100
0.65919
4.488053
false
false
false
false
astromme/classify-handwritten-characters
android/app/src/main/java/com/dokibo/characterclassification/DrawCharacterView.kt
1
3988
package com.dokibo.characterclassification import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Paint import android.graphics.Path import android.util.AttributeSet import android.util.Log import android.view.MotionEvent import android.view.View import android.view.ViewConfiguration import androidx.core.content.res.ResourcesCompat private const val STROKE_WIDTH = 40f class DrawCharacterView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : View(context, attrs, defStyle) { private lateinit var extraCanvas: Canvas private lateinit var extraBitmap: Bitmap private val backgroundColor = ResourcesCompat.getColor(resources, R.color.white, null) private val drawColor = ResourcesCompat.getColor(resources, R.color.black, null) private val paint = Paint().apply { color = drawColor isAntiAlias = true isDither = true style = Paint.Style.STROKE strokeJoin = Paint.Join.ROUND strokeCap = Paint.Cap.ROUND strokeWidth = STROKE_WIDTH } private var strokes: MutableList<Path> = mutableListOf(Path()) private val currentPath: Path get() { return strokes.last() } private var motionTouchEventX = 0f private var motionTouchEventY = 0f private var currentX = 0f private var currentY = 0f private val touchTolerance = ViewConfiguration.get(context).scaledTouchSlop private val onDrawingUpdatedListeners: MutableList<(bitmap: Bitmap) -> Unit?> = mutableListOf() fun setOnDrawingUpdatedListener(listener: (bitmap: Bitmap) -> Unit?) { onDrawingUpdatedListeners.add(listener) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) if (::extraBitmap.isInitialized) extraBitmap.recycle() extraBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888) extraCanvas = Canvas(extraBitmap) extraCanvas.drawColor(backgroundColor) strokes = mutableListOf(Path()) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) canvas.drawBitmap(extraBitmap, 0f, 0f, null) } override fun onTouchEvent(event: MotionEvent): Boolean { motionTouchEventX = event.x motionTouchEventY = event.y when (event.action) { MotionEvent.ACTION_DOWN -> touchStart() MotionEvent.ACTION_MOVE -> touchMove() MotionEvent.ACTION_UP -> touchUp() } return true } private fun touchStart() { // TODO: handle multi-touch currentPath.moveTo(motionTouchEventX, motionTouchEventY) currentX = motionTouchEventX currentY = motionTouchEventY } private fun touchMove() { val dx = Math.abs(motionTouchEventX - currentX) val dy = Math.abs(motionTouchEventY - currentY) if (dx >= touchTolerance || dy >= touchTolerance) { currentPath.quadTo( currentX, currentY, (motionTouchEventX + currentX) / 2, (motionTouchEventY + currentY) / 2) currentX = motionTouchEventX currentY = motionTouchEventY extraCanvas.drawPath(currentPath, paint) } invalidate() } private fun touchUp() { // finish the path by adding a new one strokes.add(Path()) onDrawingUpdatedListeners.forEach { it(extraBitmap) } } fun undoStroke() { Log.d("DrawCharacterView", "Strokes: ${strokes.size} ${strokes}") if (strokes.size < 2) { return } strokes.removeAt(strokes.size - 2) extraCanvas.drawColor(backgroundColor) for (path in strokes) { extraCanvas.drawPath(path, paint) } invalidate() onDrawingUpdatedListeners.forEach { it(extraBitmap) } } }
mit
4ad0315e16cba095711c7b9118af89d9
29.684615
99
0.654463
4.583908
false
false
false
false
toastkidjp/Jitte
app/src/main/java/jp/toastkid/yobidashi/editor/usecase/MenuActionInvokerUseCase.kt
1
6255
/* * Copyright (c) 2021 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.editor.usecase import android.content.Context import android.net.Uri import android.widget.EditText import androidx.annotation.IdRes import androidx.core.net.toUri import jp.toastkid.lib.BrowserViewModel import jp.toastkid.lib.ContentViewModel import jp.toastkid.lib.input.Inputs import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.search.SearchCategory import jp.toastkid.search.UrlFactory import jp.toastkid.yobidashi.R import jp.toastkid.yobidashi.editor.CurrentLineDuplicatorUseCase import jp.toastkid.yobidashi.editor.ListHeadAdder import jp.toastkid.yobidashi.editor.OrderedListHeadAdder import jp.toastkid.yobidashi.editor.StringSurroundingUseCase import jp.toastkid.yobidashi.editor.TableConverter import jp.toastkid.yobidashi.libs.clip.Clipboard import jp.toastkid.yobidashi.libs.speech.SpeechMaker /** * @author toastkidjp */ class MenuActionInvokerUseCase( private val editText: EditText, private val speechMaker: SpeechMaker?, private val browserViewModel: BrowserViewModel?, private val contentViewModel: ContentViewModel?, private val listHeadAdder: ListHeadAdder = ListHeadAdder() ) { operator fun invoke(@IdRes itemId: Int, text: String): Boolean { val context = editText.context when (itemId) { R.id.context_edit_insert_as_plain -> { val primary = Clipboard.getPrimary(context) if (primary.isNullOrEmpty()) { return true } editText.text.insert(editText.selectionStart, primary) return true } R.id.context_edit_paste_as_quotation -> { contentViewModel ?: return true PasteAsQuotationUseCase(editText, contentViewModel).invoke() return true } R.id.context_edit_paste_url_with_title -> { contentViewModel ?: return true LinkFormInsertionUseCase( editText, contentViewModel ).invoke() return true } R.id.context_edit_horizontal_rule -> { editText.text.insert( editText.selectionStart, "----${System.lineSeparator()}" ) return true } R.id.context_edit_duplicate_current_line -> { CurrentLineDuplicatorUseCase().invoke(editText) return true } R.id.context_edit_select_current_line -> { CurrentLineSelectionUseCase().invoke(editText) return true } R.id.context_edit_speech -> { val speechText = if (text.isBlank()) editText.text.toString() else text speechMaker?.invoke(speechText) return true } R.id.context_edit_add_order -> { OrderedListHeadAdder().invoke(editText) return true } R.id.context_edit_unordered_list -> { listHeadAdder(editText, "-") return true } R.id.context_edit_task_list -> { listHeadAdder(editText, "- [ ]") return true } R.id.context_edit_convert_to_table -> { TableConverter().invoke(editText) return true } R.id.context_edit_add_quote -> { listHeadAdder(editText, ">") return true } R.id.context_edit_code_block -> { CodeBlockUseCase().invoke(editText, text) return true } R.id.context_edit_double_quote -> { StringSurroundingUseCase()(editText, '"') return true } R.id.context_edit_bold -> { StringSurroundingUseCase()(editText, "**") return true } R.id.context_edit_italic -> { StringSurroundingUseCase()(editText, "*") return true } R.id.context_edit_strikethrough -> { StringSurroundingUseCase()(editText, "~~") return true } R.id.context_edit_url_open_new -> { browserViewModel?.open(text.toUri()) return true } R.id.context_edit_url_open_background -> { browserViewModel?.openBackground(text.toUri()) return true } R.id.context_edit_url_preview -> { browserViewModel?.preview(text.toUri()) Inputs.hideKeyboard(editText) return true } R.id.context_edit_preview_search -> { browserViewModel?.preview(makeSearchResultUrl(context, text)) return true } R.id.context_edit_web_search -> { browserViewModel?.open(makeSearchResultUrl(context, text)) return true } R.id.context_edit_delete_line -> { CurrentLineDeletionUseCase().invoke(editText) return true } R.id.context_edit_count -> { TextCountUseCase().invoke(editText, contentViewModel) return true } R.id.context_edit_insert_thousand_separator -> { ThousandSeparatorInsertionUseCase().invoke(editText, text) return true } else -> Unit } return false } private fun makeSearchResultUrl(context: Context, text: String): Uri = UrlFactory().invoke( PreferenceApplier(context).getDefaultSearchEngine() ?: SearchCategory.getDefaultCategoryName(), text ) }
epl-1.0
28a04d11c2147dc17e46b8962027a06c
35.584795
95
0.563229
5.07711
false
false
false
false
square/leakcanary
shark-android/src/main/java/shark/AndroidServices.kt
2
941
package shark object AndroidServices { val HeapGraph.aliveAndroidServiceObjectIds: List<Long> get() { return context.getOrPut(AndroidServices::class.java.name) { val activityThreadClass = findClassByName("android.app.ActivityThread")!! val currentActivityThread = activityThreadClass .readStaticField("sCurrentActivityThread")!! .valueAsInstance!! val mServices = currentActivityThread["android.app.ActivityThread", "mServices"]!! .valueAsInstance!! val servicesArray = mServices["android.util.ArrayMap", "mArray"]!!.valueAsObjectArray!! servicesArray.readElements() .filterIndexed { index, heapValue -> // ArrayMap<IBinder, Service> // even: key, odd: value index % 2 == 1 && heapValue.isNonNullReference } .map { it.asNonNullObjectId!! } .toList() } } }
apache-2.0
8d0a839ee68481cd8fab08a0a6b44183
32.642857
95
0.62593
4.728643
false
false
false
false
xfournet/intellij-community
python/src/com/jetbrains/python/codeInsight/stdlib/PyNamedTuplesTypeProvider.kt
1
14575
// 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.jetbrains.python.codeInsight.stdlib import com.intellij.openapi.util.Ref import com.intellij.psi.PsiElement import com.intellij.psi.util.QualifiedName import com.intellij.util.ArrayUtil import com.jetbrains.python.PyNames import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider import com.jetbrains.python.psi.* import com.jetbrains.python.psi.impl.PyCallExpressionNavigator import com.jetbrains.python.psi.impl.stubs.PyNamedTupleStubImpl import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.resolve.fromFoothold import com.jetbrains.python.psi.resolve.resolveTopLevelMember import com.jetbrains.python.psi.stubs.PyNamedTupleStub import com.jetbrains.python.psi.types.* import one.util.streamex.StreamEx import java.util.* import java.util.stream.Collectors private typealias NTFields = LinkedHashMap<String, PyNamedTupleType.FieldTypeAndDefaultValue> private typealias ImmutableNTFields = Map<String, PyNamedTupleType.FieldTypeAndDefaultValue> class PyNamedTuplesTypeProvider : PyTypeProviderBase() { override fun getReferenceType(referenceTarget: PsiElement, context: TypeEvalContext, anchor: PsiElement?): PyType? { return getNamedTupleTypeForResolvedCallee(referenceTarget, context, anchor) } override fun getReferenceExpressionType(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyType? { val fieldTypeForNamedTuple = getFieldTypeForNamedTupleAsTarget(referenceExpression, context) if (fieldTypeForNamedTuple != null) { return fieldTypeForNamedTuple } val namedTupleTypeForCallee = getNamedTupleTypeForCallee(referenceExpression, context) if (namedTupleTypeForCallee != null) { return namedTupleTypeForCallee } val namedTupleReplaceType = getNamedTupleReplaceType(referenceExpression, context) if (namedTupleReplaceType != null) { return namedTupleReplaceType } return null } override fun getCallType(function: PyFunction, callSite: PyCallSiteExpression?, context: TypeEvalContext): Ref<PyType?>? { if (callSite != null && function.qualifiedName == PyTypingTypeProvider.NAMEDTUPLE + "._make") { val receiverType = callSite.getReceiver(function)?.let { context.getType(it) } if (receiverType is PyInstantiableType<*> && isNamedTuple(receiverType, context)) { return Ref.create(receiverType.toInstance()) } } return null } companion object { fun isNamedTuple(type: PyType?, context: TypeEvalContext): Boolean { if (type is PyNamedTupleType) return true val isNT = { t: PyClassLikeType? -> t is PyNamedTupleType || t != null && PyTypingTypeProvider.NAMEDTUPLE == t.classQName } return type is PyClassLikeType && type.getAncestorTypes(context).any(isNT) } fun isTypingNamedTupleDirectInheritor(cls: PyClass, context: TypeEvalContext): Boolean { val isTypingNT = { type: PyClassLikeType? -> type != null && type !is PyNamedTupleType && PyTypingTypeProvider.NAMEDTUPLE == type.classQName } return cls.getSuperClassTypes(context).any(isTypingNT) } internal fun getNamedTupleTypeForResolvedCallee(referenceTarget: PsiElement, context: TypeEvalContext, anchor: PsiElement?): PyNamedTupleType? { return when { referenceTarget is PyFunction && anchor is PyCallExpression -> getNamedTupleFunctionType(referenceTarget, context, anchor) referenceTarget is PyTargetExpression -> getNamedTupleTypeForTarget(referenceTarget, context) else -> null } } internal fun getNamedTupleReplaceType(referenceTarget: PsiElement, context: TypeEvalContext, anchor: PsiElement?): PyCallableType? { if (referenceTarget is PyFunction && anchor is PyCallExpression && PyTypingTypeProvider.NAMEDTUPLE == referenceTarget.containingClass?.qualifiedName) { val callee = anchor.callee as? PyReferenceExpression ?: return null return getNamedTupleReplaceType(callee, context) } return null } private fun getFieldTypeForNamedTupleAsTarget(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyType? { val qualifierNTType = referenceExpression.qualifier?.let { context.getType(it) } as? PyNamedTupleType ?: return null return qualifierNTType.fields[referenceExpression.name]?.type } private fun getNamedTupleTypeForCallee(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyNamedTupleType? { if (PyCallExpressionNavigator.getPyCallExpressionByCallee(referenceExpression) == null) return null val resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(context) val resolveResults = referenceExpression.getReference(resolveContext).multiResolve(false) for (element in PyUtil.filterTopPriorityResults(resolveResults)) { if (element is PyTargetExpression) { val result = getNamedTupleTypeForTarget(element, context) if (result != null) { return result } } if (element is PyClass) { val result = getNamedTupleTypeForTypingNTInheritorAsCallee(element, context) if (result != null) { return result } } if (element is PyTypedElement) { val type = context.getType(element) if (type is PyClassLikeType) { val superClassTypes = type.getSuperClassTypes(context) val superNTType = superClassTypes.asSequence().filterIsInstance<PyNamedTupleType>().firstOrNull() if (superNTType != null) { return superNTType } } } } return null } private fun getNamedTupleReplaceType(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyCallableType? { val call = PyCallExpressionNavigator.getPyCallExpressionByCallee(referenceExpression) ?: return null val qualifier = referenceExpression.qualifier if (qualifier != null && "_replace" == referenceExpression.referencedName) { val qualifierType = context.getType(qualifier) as? PyClassLikeType ?: return null val namedTupleType = StreamEx .of<PyType>(qualifierType) .append(qualifierType.getSuperClassTypes(context)) .select(PyNamedTupleType::class.java) .findFirst() .orElse(null) if (namedTupleType != null) { return if (namedTupleType.isTyped) createTypedNamedTupleReplaceType(referenceExpression, namedTupleType.fields, qualifierType) else createUntypedNamedTupleReplaceType(call, namedTupleType.fields, qualifierType, context) } if (qualifierType is PyClassType) { val cls = qualifierType.pyClass if (isTypingNamedTupleDirectInheritor(cls, context)) { return createTypedNamedTupleReplaceType(referenceExpression, collectTypingNTInheritorFields(cls, context), qualifierType) } } } return null } private fun getNamedTupleFunctionType(function: PyFunction, context: TypeEvalContext, call: PyCallExpression): PyNamedTupleType? { if (ArrayUtil.contains(function.qualifiedName, PyNames.COLLECTIONS_NAMEDTUPLE_PY2, PyNames.COLLECTIONS_NAMEDTUPLE_PY3) || PyUtil.isInit(function) && PyTypingTypeProvider.NAMEDTUPLE == function.containingClass?.qualifiedName) { return getNamedTupleTypeFromAST(call, context, PyNamedTupleType.DefinitionLevel.NT_FUNCTION) } return null } private fun getNamedTupleTypeForTarget(target: PyTargetExpression, context: TypeEvalContext): PyNamedTupleType? { val stub = target.stub return if (stub != null) { getNamedTupleTypeFromStub(target, stub.getCustomStub(PyNamedTupleStub::class.java), context, PyNamedTupleType.DefinitionLevel.NEW_TYPE) } else getNamedTupleTypeFromAST(target, context, PyNamedTupleType.DefinitionLevel.NEW_TYPE) } private fun getNamedTupleTypeForTypingNTInheritorAsCallee(cls: PyClass, context: TypeEvalContext): PyNamedTupleType? { if (isTypingNamedTupleDirectInheritor(cls, context)) { val name = cls.name ?: return null val typingNT = resolveTopLevelMember(QualifiedName.fromDottedString(PyTypingTypeProvider.NAMEDTUPLE), fromFoothold(cls)) val tupleClass = typingNT as? PyClass ?: return null return PyNamedTupleType(tupleClass, name, collectTypingNTInheritorFields(cls, context), PyNamedTupleType.DefinitionLevel.NEW_TYPE, true) } return null } private fun getNamedTupleTypeFromStub(referenceTarget: PsiElement, stub: PyNamedTupleStub?, context: TypeEvalContext, definitionLevel: PyNamedTupleType.DefinitionLevel): PyNamedTupleType? { if (stub == null) return null val typingNT = resolveTopLevelMember(QualifiedName.fromDottedString(PyTypingTypeProvider.NAMEDTUPLE), fromFoothold(referenceTarget)) val tupleClass = typingNT as? PyClass ?: return null val fields = stub.fields return PyNamedTupleType(tupleClass, stub.name, parseNamedTupleFields(referenceTarget, fields, context), definitionLevel, fields.values.any { it.isPresent }, referenceTarget as? PyTargetExpression) } private fun getNamedTupleTypeFromAST(expression: PyTargetExpression, context: TypeEvalContext, definitionLevel: PyNamedTupleType.DefinitionLevel): PyNamedTupleType? { return if (context.maySwitchToAST(expression)) { getNamedTupleTypeFromStub(expression, PyNamedTupleStubImpl.create(expression), context, definitionLevel) } else null } private fun createTypedNamedTupleReplaceType(anchor: PsiElement, fields: ImmutableNTFields, resultType: PyType): PyCallableType { val parameters = mutableListOf<PyCallableParameter>() val elementGenerator = PyElementGenerator.getInstance(anchor.project) parameters.add(PyCallableParameterImpl.psi(elementGenerator.createSingleStarParameter())) val ellipsis = elementGenerator.createEllipsis() for ((name, typeAndValue) in fields) { parameters.add(PyCallableParameterImpl.nonPsi(name, typeAndValue.type, typeAndValue.defaultValue ?: ellipsis)) } return PyCallableTypeImpl(parameters, resultType) } private fun createUntypedNamedTupleReplaceType(call: PyCallExpression, fields: ImmutableNTFields, resultType: PyType, context: TypeEvalContext): PyCallableType { val parameters = mutableListOf<PyCallableParameter>() val elementGenerator = PyElementGenerator.getInstance(call.project) parameters.add(PyCallableParameterImpl.psi(elementGenerator.createSingleStarParameter())) val ellipsis = elementGenerator.createEllipsis() fields.keys.mapTo(parameters) { PyCallableParameterImpl.nonPsi(it, null, ellipsis) } return if (resultType is PyNamedTupleType) { val newFields = mutableMapOf<String?, PyType?>() for (argument in call.arguments) { if (argument is PyKeywordArgument) { val value = argument.valueExpression if (value != null) { newFields[argument.keyword] = context.getType(value) } } } PyCallableTypeImpl(parameters, resultType.clarifyFields(newFields)) } else PyCallableTypeImpl(parameters, resultType) } private fun collectTypingNTInheritorFields(cls: PyClass, context: TypeEvalContext): NTFields { val fields = mutableListOf<PyTargetExpression>() cls.processClassLevelDeclarations { element, _ -> if (element is PyTargetExpression && element.annotationValue != null) { fields.add(element) } true } val ellipsis = PyElementGenerator.getInstance(cls.project).createEllipsis() val toNTFields = Collectors.toMap<PyTargetExpression, String, PyNamedTupleType.FieldTypeAndDefaultValue, NTFields>( { it.name }, { field -> val value = when { context.maySwitchToAST(field) -> field.findAssignedValue() field.hasAssignedValue() -> ellipsis else -> null } PyNamedTupleType.FieldTypeAndDefaultValue(context.getType(field), value) }, { _, v2 -> v2 }, { NTFields() }) return fields.stream().collect(toNTFields) } private fun getNamedTupleTypeFromAST(expression: PyCallExpression, context: TypeEvalContext, definitionLevel: PyNamedTupleType.DefinitionLevel): PyNamedTupleType? { return if (context.maySwitchToAST(expression)) { getNamedTupleTypeFromStub(expression, PyNamedTupleStubImpl.create(expression), context, definitionLevel) } else null } private fun parseNamedTupleFields(anchor: PsiElement, fields: Map<String, Optional<String>>, context: TypeEvalContext): NTFields { val result = NTFields() for ((name, type) in fields) { result[name] = parseNamedTupleField(anchor, type.orElse(null), context) } return result } private fun parseNamedTupleField(anchor: PsiElement, type: String?, context: TypeEvalContext): PyNamedTupleType.FieldTypeAndDefaultValue { if (type == null) return PyNamedTupleType.FieldTypeAndDefaultValue(null, null) val pyType = Ref.deref(PyTypingTypeProvider.getStringBasedType(type, anchor, context)) return PyNamedTupleType.FieldTypeAndDefaultValue(pyType, null) } } }
apache-2.0
a2eda38ab9375bd36c897a7f961c6451
42.380952
140
0.679931
5.80215
false
false
false
false
googleapis/gax-kotlin
examples-android/app/src/main/java/com/google/api/kgax/examples/grpc/SpeechStreamingActivity.kt
1
5309
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.kgax.examples.grpc import android.Manifest import android.content.pm.PackageManager import android.os.Bundle import android.support.test.espresso.idling.CountingIdlingResource import android.support.v4.app.ActivityCompat import android.util.Log import com.google.api.kgax.examples.grpc.util.AudioEmitter import com.google.api.kgax.grpc.StreamingCall import com.google.api.kgax.grpc.StubFactory import com.google.cloud.speech.v1.RecognitionConfig import com.google.cloud.speech.v1.SpeechGrpc import com.google.cloud.speech.v1.StreamingRecognitionConfig import com.google.cloud.speech.v1.StreamingRecognizeRequest import com.google.cloud.speech.v1.StreamingRecognizeResponse import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlin.coroutines.CoroutineContext private const val TAG = "APITest" private const val REQUEST_RECORD_AUDIO_PERMISSION = 200 private val PERMISSIONS = arrayOf(Manifest.permission.RECORD_AUDIO) /** * Kotlin example showcasing streaming APIs using KGax with gRPC and the Google Speech API. */ @ExperimentalCoroutinesApi class SpeechStreamingActivity : AbstractExampleActivity<SpeechGrpc.SpeechStub>( CountingIdlingResource("SpeechStreaming") ) { lateinit var job: Job override val coroutineContext: CoroutineContext get() = Dispatchers.Main + job private var permissionToRecord = false private val audioEmitter: AudioEmitter = AudioEmitter() private var streams: SpeechStreams? = null override val factory = StubFactory( SpeechGrpc.SpeechStub::class, "speech.googleapis.com", 443 ) override val stub by lazy { applicationContext.resources.openRawResource(R.raw.sa).use { factory.fromServiceAccount( it, listOf("https://www.googleapis.com/auth/cloud-platform") ) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // get permissions ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_RECORD_AUDIO_PERMISSION) } override fun onResume() { super.onResume() job = Job() // kick-off recording process, if we're allowed if (permissionToRecord) { launch { streams = transcribe() } } } override fun onPause() { super.onPause() // ensure mic data stops launch { audioEmitter.stop() streams?.responses?.cancel() job.cancel() } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { REQUEST_RECORD_AUDIO_PERMISSION -> permissionToRecord = grantResults[0] == PackageManager.PERMISSION_GRANTED } if (!permissionToRecord) { Log.e(TAG, "No permission to record - please grant and retry!") finish() } } private suspend fun transcribe(): SpeechStreams { // start streaming the data to the server and collect responses val streams = stub.prepare { withInitialRequest(StreamingRecognizeRequest.newBuilder().apply { streamingConfig = StreamingRecognitionConfig.newBuilder().apply { config = RecognitionConfig.newBuilder().apply { languageCode = "en-US" encoding = RecognitionConfig.AudioEncoding.LINEAR16 sampleRateHertz = 16000 }.build() interimResults = false singleUtterance = false }.build() }.build()) }.executeStreaming { it::streamingRecognize } // monitor the input stream and send requests as audio data becomes available launch(Dispatchers.IO) { for (bytes in audioEmitter.start(this)) { streams.requests.send( StreamingRecognizeRequest.newBuilder().apply { audioContent = bytes }.build() ) } } // handle incoming responses launch(Dispatchers.Main) { for (response in streams.responses) { updateUIWithExampleResult(response.toString()) } } return streams } } private typealias SpeechStreams = StreamingCall<StreamingRecognizeRequest, StreamingRecognizeResponse>
apache-2.0
a6d9439f535a1270c204d0b337ca0789
33.251613
102
0.664909
4.920297
false
false
false
false
kibotu/RecyclerViewPresenter
lib/src/main/java/net/kibotu/android/recyclerviewpresenter/cirkle/MutableCircularList.kt
1
5624
/* * MIT License * * Copyright (c) 2017 Todd Ginsberg * * 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 net.kibotu.android.recyclerviewpresenter.cirkle import kotlin.math.absoluteValue /** * Implementation of a Circularly-addressable [kotlin.collections.MutableList], allowing negative * indexes and positive indexes that are larger than the size of the List. */ class MutableCircularList<T>(private val list: MutableList<T>) : MutableList<T> by list { /** * Add the [element] at the specified [index]. * * If the [index] is negative it is interpreted as an offset from the end of * the list. If the [index] is positive and beyond the bounds of the underlying list, * it wraps around again from the start of the list. * * @sample samples.Cirkle.MutableCircularList.add */ override fun add(index: Int, element: T) = list.add(index.safely(), element) /** * Add all of the [elements] starting at the specified [index]. * * If the [index] is negative it is interpreted as an offset from the end of * the list. If the [index] is positive and beyond the bounds of the underlying list, * it wraps around again from the start of the list. * * @sample samples.Cirkle.MutableCircularList.addAll */ override fun addAll(index: Int, elements: Collection<T>): Boolean = list.addAll(index.safely(), elements) /** * Get the element at the specified [index]. * * If the [index] is negative it is interpreted as an offset from the end of * the list. If the [index] is positive and beyond the bounds of the underlying list, * it wraps around again from the start of the list. * * @sample samples.Cirkle.MutableCircularList.get */ override operator fun get(index: Int): T = list[index.safely()] /** * Get a [kotlin.collections.ListIterator] starting at the specified [index] * * If the [index] is negative it is interpreted as an offset from the end of * the list. If the [index] is positive and beyond the bounds of the underlying list, * it wraps around again from the start of the list. * * @sample samples.Cirkle.MutableCircularList.listIterator */ override fun listIterator(index: Int): MutableListIterator<T> = list.listIterator(index.safely()) /** * Remove the element at the specified [index]. * * If the [index] is negative it is interpreted as an offset from the end of * the list. If the [index] is positive and beyond the bounds of the underlying list, * it wraps around again from the start of the list. * * @sample samples.Cirkle.MutableCircularList.removeAt */ override fun removeAt(index: Int): T = list.removeAt(index.safely()) /** * Replace the existing element at the specified [index] with the given [element]. * * If the [index] is negative it is interpreted as an offset from the end of * the list. If the [index] is positive and beyond the bounds of the underlying list, * it wraps around again from the start of the list. * * @sample samples.Cirkle.MutableCircularList.set */ override fun set(index: Int, element: T): T = list.set(index.safely(), element) /** * Get a List bound by [fromIndex] inclusive to [toIndex] exclusive * * If [fromIndex] or [toIndex] is negative they are interpreted as an offset from the end of * the list. If the [fromIndex] or [toIndex] is positive and beyond the bounds of the underlying list, * it wraps around again from the start of the list. * * @sample samples.Cirkle.MutableCircularList.subList */ override fun subList(fromIndex: Int, toIndex: Int): MutableList<T> { val result = mutableListOf<T>() var rest = (toIndex - fromIndex).absoluteValue val list = if (toIndex < fromIndex) list.asReversed() else list while (rest > 0) { if (rest > list.size) { result.addAll(list.subList(0, list.size)) rest -= list.size } else { result.addAll(list.subList(0, rest)) rest = 0 } } return result } /** * Returns a String representation of the object. */ override fun toString(): String = list.toString() private fun Int.safely(): Int = if (this < 0) (this % lastIndex + lastIndex) % lastIndex else this % lastIndex }
apache-2.0
e60fbdf37b119d7922b6a1d77904ce22
36.006579
106
0.660917
4.326154
false
false
false
false
Commit451/LabCoat
app/src/main/java/com/commit451/gitlab/fragment/MergeRequestDiscussionFragment.kt
2
6487
package com.commit451.gitlab.fragment import android.app.Activity.RESULT_OK import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.commit451.addendum.design.snackbar import com.commit451.gitlab.App import com.commit451.gitlab.R import com.commit451.gitlab.activity.AttachActivity import com.commit451.gitlab.adapter.BaseAdapter import com.commit451.gitlab.api.response.FileUploadResponse import com.commit451.gitlab.event.MergeRequestChangedEvent import com.commit451.gitlab.extension.mapResponseSuccessResponse import com.commit451.gitlab.extension.with import com.commit451.gitlab.model.api.MergeRequest import com.commit451.gitlab.model.api.Note import com.commit451.gitlab.model.api.Project import com.commit451.gitlab.navigation.TransitionFactory import com.commit451.gitlab.util.LoadHelper import com.commit451.gitlab.view.SendMessageView import com.commit451.gitlab.viewHolder.NoteViewHolder import com.commit451.teleprinter.Teleprinter import kotlinx.android.synthetic.main.fragment_merge_request_discussion.* import kotlinx.android.synthetic.main.progress_fullscreen.* import org.greenrobot.eventbus.Subscribe import timber.log.Timber /** * Shows the discussion of a merge request */ class MergeRequestDiscussionFragment : BaseFragment() { companion object { private const val KEY_PROJECT = "project" private const val KEY_MERGE_REQUEST = "merge_request" private const val REQUEST_ATTACH = 1 fun newInstance(project: Project, mergeRequest: MergeRequest): MergeRequestDiscussionFragment { val fragment = MergeRequestDiscussionFragment() val args = Bundle() args.putParcelable(KEY_PROJECT, project) args.putParcelable(KEY_MERGE_REQUEST, mergeRequest) fragment.arguments = args return fragment } } private lateinit var adapter: BaseAdapter<Note, NoteViewHolder> private lateinit var loadHelper: LoadHelper<Note> private lateinit var teleprinter: Teleprinter private lateinit var project: Project private lateinit var mergeRequest: MergeRequest override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) project = arguments?.getParcelable(KEY_PROJECT)!! mergeRequest = arguments?.getParcelable(KEY_MERGE_REQUEST)!! } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_merge_request_discussion, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) teleprinter = Teleprinter(baseActivty) val layoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, true) adapter = BaseAdapter( onCreateViewHolder = { parent, _ -> NoteViewHolder.inflate(parent) }, onBindViewHolder = { viewHolder, _, item -> viewHolder.bind(item, project) } ) loadHelper = LoadHelper( lifecycleOwner = this, recyclerView = listNotes, baseAdapter = adapter, layoutManager = layoutManager, swipeRefreshLayout = swipeRefreshLayout, errorOrEmptyTextView = textMessage, loadInitial = { gitLab.getMergeRequestNotes(project.id, mergeRequest.iid) }, loadMore = { gitLab.loadAnyList(it) } ) sendMessageView.callback = object : SendMessageView.Callback { override fun onSendClicked(message: String) { postNote(message) } override fun onAttachmentClicked() { val intent = AttachActivity.newIntent(baseActivty, project) val activityOptions = TransitionFactory.createFadeInOptions(baseActivty) startActivityForResult(intent, REQUEST_ATTACH, activityOptions.toBundle()) } } load() App.bus().register(this) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { REQUEST_ATTACH -> { if (resultCode == RESULT_OK) { val response = data?.getParcelableExtra<FileUploadResponse>(AttachActivity.KEY_FILE_UPLOAD_RESPONSE)!! fullscreenProgress.visibility = View.GONE sendMessageView.appendText(response.markdown) } else { root.snackbar(R.string.failed_to_upload_file) } } } } override fun onDestroyView() { App.bus().unregister(this) super.onDestroyView() } private fun load() { loadHelper.load() } fun postNote(message: String) { if (message.isBlank()) { return } fullscreenProgress.visibility = View.VISIBLE fullscreenProgress.alpha = 0.0f fullscreenProgress.animate().alpha(1.0f) // Clear text & collapse keyboard teleprinter.hideKeyboard() sendMessageView.clearText() App.get().gitLab.addMergeRequestNote(project.id, mergeRequest.iid, message) .mapResponseSuccessResponse() .with(this) .subscribe({ if (it.first.code() == 202) { load() } else { fullscreenProgress.visibility = View.GONE textMessage.isVisible = false adapter.add(it.second, 0) listNotes.smoothScrollToPosition(0) } }, { Timber.e(it) fullscreenProgress.visibility = View.GONE root.snackbar(getString(R.string.connection_error)) }) } @Suppress("unused") @Subscribe fun onMergeRequestChangedEvent(event: MergeRequestChangedEvent) { if (mergeRequest.id == event.mergeRequest.id) { mergeRequest = event.mergeRequest load() } } }
apache-2.0
c0e533ab61bb5bbc873fb42a7ec54215
36.49711
122
0.655002
4.986164
false
false
false
false
ntemplon/legends-of-omterra
core/src/com/jupiter/europa/entity/stats/SkillSet.kt
1
3627
/* * The MIT License * * Copyright 2015 Nathan Templon. * * 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.jupiter.europa.entity.stats import com.badlogic.gdx.utils.Json import com.badlogic.gdx.utils.JsonValue import java.util.EnumMap import kotlin.properties.Delegates public class SkillSet : Json.Serializable { public enum class Skills : Comparable<Skills> { BLUFF, CRAFT, DIPLOMACY, DISABLE_DEVICE, HEAL, INTIMIDATE, LOCKPICKING, PERCEPTION, SENSE_MOTIVE, SPELLCRAFT, STEALTH, USE_MAGIC_DEVICE; public val displayName: String init { val words: List<String> = this.toString().splitBy("_") val sb = StringBuilder() for ((index, word) in words.withIndex()) { sb.append(word.substring(0, 1).toUpperCase()).append(word.substring(1).toLowerCase()) if (index < words.size() - 1) { sb.append(" ") } } this.displayName = sb.toString() } companion object { private val displayNameMap: Map<String, Skills> by Delegates.lazy { Skills.values().map { skill -> Pair(skill.displayName, skill) }.toMap() } public fun getByDisplayName(displayName: String): Skills? { return if (this.displayNameMap.containsKey(displayName)) { this.displayNameMap[displayName] } else { null } } } } // Properties private val skills: MutableMap<Skills, Int> = EnumMap<Skills, Int>(javaClass<Skills>()) // Initialization init { for (skill in Skills.values()) { this.skills[skill] = 0 } } // Public Methods public fun getSkill(skill: Skills): Int { if (this.skills.containsKey(skill)) { return this.skills[skill] ?: 0 } return 0 } public fun setSkill(skill: Skills, value: Int) { this.skills[skill] = value } // Serializable (Json) Implementation override fun write(json: Json) { this.skills.keySet().forEach { skill -> json.writeValue(skill.toString(), this.skills[skill]) } } override fun read(json: Json, jsonData: JsonValue) { jsonData.forEach { value -> val skill = Skills.valueOf(value.name()) this.skills[skill] = value.asInt() } } }
mit
93dad6124584aee0f436d7c46309675d
29.487395
101
0.607389
4.539424
false
false
false
false
quarkusio/quarkus
integration-tests/mongodb-panache-kotlin/src/main/kotlin/io/quarkus/it/mongodb/panache/reactive/book/ReactiveBookEntityResource.kt
1
4701
package io.quarkus.it.mongodb.panache.reactive.book import io.quarkus.panache.common.Parameters.with import io.quarkus.panache.common.Sort import io.smallrye.mutiny.Uni import org.bson.types.ObjectId import org.jboss.logging.Logger import org.jboss.resteasy.annotations.SseElementType import org.reactivestreams.Publisher import java.net.URI import java.time.LocalDate.parse import javax.annotation.PostConstruct import javax.ws.rs.DELETE import javax.ws.rs.GET import javax.ws.rs.NotFoundException import javax.ws.rs.PATCH import javax.ws.rs.POST import javax.ws.rs.PUT import javax.ws.rs.Path import javax.ws.rs.PathParam import javax.ws.rs.Produces import javax.ws.rs.QueryParam import javax.ws.rs.core.MediaType import javax.ws.rs.core.Response @Path("/reactive/books/entity") class ReactiveBookEntityResource { @PostConstruct fun init() { val databaseName: String = ReactiveBookEntity.mongoDatabase().name val collectionName: String = ReactiveBookEntity.mongoCollection().namespace.collectionName LOGGER.infov("Using BookEntity[database={0}, collection={1}]", databaseName, collectionName) } @GET fun getBooks(@QueryParam("sort") sort: String?): Uni<List<ReactiveBookEntity>> { return if (sort != null) { ReactiveBookEntity.listAll(Sort.ascending(sort)) } else ReactiveBookEntity.listAll() } @GET @Path("/stream") @Produces(MediaType.SERVER_SENT_EVENTS) @SseElementType(MediaType.APPLICATION_JSON) fun streamBooks(@QueryParam("sort") sort: String?): Publisher<ReactiveBookEntity> { return if (sort != null) { ReactiveBookEntity.streamAll(Sort.ascending(sort)) } else ReactiveBookEntity.streamAll() } @POST fun addBook(book: ReactiveBookEntity): Uni<Response> { return book.persist<ReactiveBookEntity>().map { // the ID is populated before sending it to the database Response.created(URI.create("/books/entity${book.id}")).build() } } @PUT fun updateBook(book: ReactiveBookEntity): Uni<Response> = book.update<ReactiveBookEntity>().map { Response.accepted().build() } // PATCH is not correct here but it allows to test persistOrUpdate without a specific subpath @PATCH fun upsertBook(book: ReactiveBookEntity): Uni<Response> = book.persistOrUpdate<ReactiveBookEntity>().map { Response.accepted().build() } @DELETE @Path("/{id}") fun deleteBook(@PathParam("id") id: String?): Uni<Void> { return ReactiveBookEntity.deleteById(ObjectId(id)) .map { d -> if (d) { return@map null } throw NotFoundException() } } @GET @Path("/{id}") fun getBook(@PathParam("id") id: String?): Uni<ReactiveBookEntity?> = ReactiveBookEntity.findById(ObjectId(id)) @GET @Path("/search/{author}") fun getBooksByAuthor(@PathParam("author") author: String): Uni<List<ReactiveBookEntity>> = ReactiveBookEntity.list("author", author) @GET @Path("/search") fun search( @QueryParam("author") author: String?, @QueryParam("title") title: String?, @QueryParam("dateFrom") dateFrom: String?, @QueryParam("dateTo") dateTo: String? ): Uni<ReactiveBookEntity?> { return if (author != null) { ReactiveBookEntity.find("{'author': ?1,'bookTitle': ?2}", author, title!!).firstResult() } else ReactiveBookEntity .find( "{'creationDate': {\$gte: ?1}, 'creationDate': {\$lte: ?2}}", parse(dateFrom), parse(dateTo) ) .firstResult() } @GET @Path("/search2") fun search2( @QueryParam("author") author: String?, @QueryParam("title") title: String?, @QueryParam("dateFrom") dateFrom: String?, @QueryParam("dateTo") dateTo: String? ): Uni<ReactiveBookEntity?> = if (author != null) { ReactiveBookEntity.find( "{'author': :author,'bookTitle': :title}", with("author", author).and("title", title) ).firstResult() } else { ReactiveBookEntity.find( "{'creationDate': {\$gte: :dateFrom}, 'creationDate': {\$lte: :dateTo}}", with("dateFrom", parse(dateFrom)).and("dateTo", parse(dateTo)) ) .firstResult() } @DELETE fun deleteAll(): Uni<Void> = ReactiveBookEntity.deleteAll().map { null } companion object { private val LOGGER: Logger = Logger.getLogger(ReactiveBookEntityResource::class.java) } }
apache-2.0
4f0b167de8b0df65aec5e9fc00f6907c
33.822222
131
0.633695
4.258152
false
false
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/features/tournament/TournamentTabsView.kt
1
2626
package com.garpr.android.features.tournament import android.content.Context import android.util.AttributeSet import android.view.View import android.view.View.OnClickListener import androidx.constraintlayout.widget.ConstraintLayout import com.garpr.android.R import com.garpr.android.data.models.TournamentMode import com.garpr.android.extensions.getAttrColor import com.garpr.android.extensions.layoutInflater import com.garpr.android.misc.Refreshable import kotlinx.android.synthetic.main.view_tournament_tabs.view.* class TournamentTabsView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : ConstraintLayout(context, attrs), Refreshable { private val matchesTabClickListener = OnClickListener { tournamentMode = TournamentMode.MATCHES onTabClickListener?.onTabClick(this) } private val playersTabClickListener = OnClickListener { tournamentMode = TournamentMode.PLAYERS onTabClickListener?.onTabClick(this) } var onTabClickListener: OnTabClickListener? = null var tournamentMode: TournamentMode = TournamentMode.MATCHES set(value) { field = value refresh() } interface OnTabClickListener { fun onTabClick(v: TournamentTabsView) } init { @Suppress("LeakingThis") layoutInflater.inflate(R.layout.view_tournament_tabs, this) val ta = context.obtainStyledAttributes(attrs, R.styleable.TournamentTabsView) val indicatorLineColor = ta.getColor(R.styleable.TournamentTabsView_indicatorLineColor, context.getAttrColor(R.attr.colorAccent)) ta.recycle() matchesTab.setOnClickListener(matchesTabClickListener) playersTab.setOnClickListener(playersTabClickListener) indicatorLine.setBackgroundColor(indicatorLineColor) } override fun onAttachedToWindow() { super.onAttachedToWindow() refresh() } override fun refresh() { val layoutParams = indicatorLine.layoutParams as? LayoutParams? ?: return when (tournamentMode) { TournamentMode.MATCHES -> { layoutParams.endToEnd = matchesTab.id layoutParams.startToStart = matchesTab.id indicatorLine.visibility = View.VISIBLE } TournamentMode.PLAYERS -> { layoutParams.endToEnd = playersTab.id layoutParams.startToStart = playersTab.id indicatorLine.visibility = View.VISIBLE } } indicatorLine.layoutParams = layoutParams } }
unlicense
ca2d07cfde5a25f2a72ce98318df29ff
31.419753
95
0.696877
5.079304
false
false
false
false
JimSeker/ui
Advanced/GuiDemo_kt/app/src/main/java/edu/cs4730/guidemo_kt/Input_Fragment.kt
1
2262
package edu.cs4730.guidemo_kt import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.ViewGroup import android.widget.Toast import android.widget.EditText import android.text.TextWatcher import android.text.Editable import android.util.Log import android.view.View import android.widget.Button import androidx.fragment.app.Fragment class Input_Fragment : Fragment(), View.OnClickListener { var TAG = "Input_fragment" lateinit var myContext: Context lateinit var et_single: EditText lateinit var et_mutli: EditText lateinit var et_pwd: EditText lateinit var btn: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d(TAG, "OnCreate") } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.input_fragment, container, false) et_single = view.findViewById(R.id.et_single) et_pwd = view.findViewById(R.id.et_pwd) et_pwd.addTextChangedListener( object : TextWatcher { override fun beforeTextChanged( s: CharSequence, start: Int, count: Int, after: Int ) { //doing nothing. } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { // do nothing here. } override fun afterTextChanged(s: Editable) { // When the text is changed. Toast.makeText(myContext, et_pwd.getText(), Toast.LENGTH_SHORT).show() } } ) btn = view.findViewById(R.id.button) btn.setOnClickListener(this) return view } override fun onAttach(context: Context) { super.onAttach(context) myContext = context Log.d(TAG, "onAttach") } override fun onClick(v: View) { Toast.makeText(myContext, et_single!!.text, Toast.LENGTH_LONG).show() } }
apache-2.0
5efcaf2dbf2c753c99d17fad67f6e489
30.430556
98
0.610522
4.663918
false
false
false
false
Vakosta/Chapper
app/src/main/java/org/chapper/chapper/data/database/AppDatabase.kt
1
1521
package org.chapper.chapper.data.database import com.raizlabs.android.dbflow.annotation.Database import com.raizlabs.android.dbflow.annotation.Migration import com.raizlabs.android.dbflow.sql.SQLiteType import com.raizlabs.android.dbflow.sql.migration.AlterTableMigration import org.chapper.chapper.data.model.Chat import org.chapper.chapper.data.model.Settings @Database(name = AppDatabase.NAME, version = AppDatabase.VERSION) class AppDatabase { companion object { const val NAME = "Chapper" const val VERSION = 4 } @Migration(database = AppDatabase::class, version = 4) class Migration4Chat : AlterTableMigration<Chat>(Chat::class.java) { override fun onPreMigrate() { addColumn(SQLiteType.TEXT, "photoId") } } @Migration(database = AppDatabase::class, version = 4) class Migration4Settings : AlterTableMigration<Settings>(Settings::class.java) { override fun onPreMigrate() { addColumn(SQLiteType.TEXT, "photoId") } } @Migration(database = AppDatabase::class, version = 3) class Migration3 : AlterTableMigration<Settings>(Settings::class.java) { override fun onPreMigrate() { addColumn(SQLiteType.INTEGER, "isSendByEnter") } } @Migration(database = AppDatabase::class, version = 2) class Migration2 : AlterTableMigration<Chat>(Chat::class.java) { override fun onPreMigrate() { addColumn(SQLiteType.TEXT, "lastConnection") } } }
gpl-2.0
72de1d508cad9c885060dab5e39c041e
33.590909
84
0.693623
4.167123
false
false
false
false
backpaper0/syobotsum
core/src/syobotsum/actor/Counter.kt
1
746
package syobotsum.actor import com.badlogic.gdx.scenes.scene2d.Action import com.badlogic.gdx.scenes.scene2d.actions.Actions import com.badlogic.gdx.scenes.scene2d.ui.Label import com.badlogic.gdx.scenes.scene2d.ui.Skin class Counter(skin: Skin) : Label("00", skin, "counter") { var count: Int = 0 set(value) { field = value setText(String.format("%02d", value)) } var callback: Runnable? = null fun start() { val decrement = Actions.run(Runnable { count = count - 1 }) val delay = Actions.delay(1f, decrement) val repeat = Actions.repeat(count, delay) val run = callback.let { Actions.run(it) } addAction(Actions.sequence(repeat, run)) } }
apache-2.0
14c574bd8b25e9da81c0a3eea913d5df
26.62963
58
0.640751
3.569378
false
false
false
false
gantsign/restrulz-jvm
com.gantsign.restrulz.validation/src/test/kotlin/com/gantsign/restrulz/validation/ByteValidatorTest.kt
1
6343
/*- * #%L * Restrulz * %% * Copyright (C) 2017 GantSign Ltd. * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.gantsign.restrulz.validation import org.junit.Rule import org.junit.Test import org.junit.rules.ExpectedException import org.mockito.Mockito.mock import org.mockito.Mockito.verify import org.mockito.Mockito.verifyZeroInteractions import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue class ByteValidatorTest { @Rule @JvmField val thrown: ExpectedException = ExpectedException.none() @Test fun testNewByteValidatorInvalidArgs() { thrown.expect(IllegalArgumentException::class.java) thrown.expectMessage("Parameter 'minimumValue' (41) must be less than or equal to parameter 'maximumValue' (40)") TestByteValidator(minimumValue = 41, maximumValue = 40) } @Test fun testRequireValidValue() { val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40) assertEquals(expected = 20, actual = testValidator.requireValidValue("test1", 20)) assertEquals(expected = 21, actual = testValidator.requireValidValue("test1", 21)) assertEquals(expected = 40, actual = testValidator.requireValidValue("test1", 40)) } @Test fun testRequireValidValueTooLow() { thrown.expect(InvalidArgumentException::class.java) thrown.expectMessage("19 is less than the minimum permitted value of 20") val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40) testValidator.requireValidValue("test1", 19) } @Test fun testRequireValidValueTooHigh() { thrown.expect(InvalidArgumentException::class.java) thrown.expectMessage("41 is greater than the maximum permitted value of 40") val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40) testValidator.requireValidValue("test1", 41) } @Test fun testRequireValidValueOrNull() { val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40) assertEquals(expected = 20, actual = testValidator.requireValidValueOrNull("test1", 20)) assertEquals(expected = 21, actual = testValidator.requireValidValueOrNull("test1", 21)) assertEquals(expected = 40, actual = testValidator.requireValidValueOrNull("test1", 40)) assertNull(testValidator.requireValidValueOrNull("test1", null)) } @Test fun testRequireValidValueOrNullTooLow() { thrown.expect(InvalidArgumentException::class.java) thrown.expectMessage("19 is less than the minimum permitted value of 20") val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40) testValidator.requireValidValueOrNull("test1", 19) } @Test fun testRequireValidValueOrNullTooHigh() { thrown.expect(InvalidArgumentException::class.java) thrown.expectMessage("41 is greater than the maximum permitted value of 40") val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40) testValidator.requireValidValueOrNull("test1", 41) } @Test fun testValidateValue() { val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40) val validationHandler = mock(ValidationHandler::class.java) assertTrue(testValidator.validateValue(20, validationHandler)) assertTrue(testValidator.validateValue(21, validationHandler)) assertTrue(testValidator.validateValue(40, validationHandler)) verifyZeroInteractions(validationHandler) } @Test fun testValidateValueTooLow() { val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40) val validationHandler = mock(ValidationHandler::class.java) assertFalse(testValidator.validateValue(19, validationHandler)) verify(validationHandler).handleValidationFailure("19 is less than the minimum permitted value of 20") } @Test fun testValidateValueTooHigh() { val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40) val validationHandler = mock(ValidationHandler::class.java) assertFalse(testValidator.validateValue(41, validationHandler)) verify(validationHandler).handleValidationFailure("41 is greater than the maximum permitted value of 40") } @Test fun testValidateValueOrNull() { val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40) val validationHandler = mock(ValidationHandler::class.java) assertTrue(testValidator.validateValueOrNull(20, validationHandler)) assertTrue(testValidator.validateValueOrNull(21, validationHandler)) assertTrue(testValidator.validateValueOrNull(40, validationHandler)) assertTrue(testValidator.validateValueOrNull(null, validationHandler)) verifyZeroInteractions(validationHandler) } @Test fun testValidateValueOrNullTooLow() { val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40) val validationHandler = mock(ValidationHandler::class.java) assertFalse(testValidator.validateValueOrNull(19, validationHandler)) verify(validationHandler).handleValidationFailure("19 is less than the minimum permitted value of 20") } @Test fun testValidateValueOrNullTooHigh() { val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40) val validationHandler = mock(ValidationHandler::class.java) assertFalse(testValidator.validateValueOrNull(41, validationHandler)) verify(validationHandler).handleValidationFailure("41 is greater than the maximum permitted value of 40") } }
apache-2.0
014b918bc60f23149804c889c0f89b70
37.676829
121
0.727731
5.165309
false
true
false
false
androidthings/endtoend-base
app/src/main/java/com/example/androidthings/endtoend/MainActivity.kt
1
3572
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androidthings.endtoend import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.localbroadcastmanager.content.LocalBroadcastManager import com.example.androidthings.endtoend.auth.FirebaseDeviceAuthenticator import org.json.JSONObject class MainActivity : AppCompatActivity() { private val TAG: String = "MainActivity" lateinit var gpioManager: GpioManager lateinit var fcmReceiver: BroadcastReceiver lateinit var firebaseAuth: FirebaseDeviceAuthenticator val listener = object : OnLedStateChangedListener { override fun onStateChanged() { updateFirestore() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) gpioManager = GpioManager(lifecycle, listener) gpioManager.initGpio() firebaseAuth = FirebaseDeviceAuthenticator() firebaseAuth.initAuth(this) FirestoreManager.init(this) } fun updateFirestore() { val newStates = arrayOf(gpioManager.leds[0].value, gpioManager.leds[1].value, gpioManager.leds[2].value) FirestoreManager.updateGizmoDocState(newStates) } fun initFcmReceiver() { fcmReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if (intent != null) { val jsonCommandStr = intent.getStringExtra(FcmContract.COMMAND_KEY) var cmds = JSONObject(jsonCommandStr) .getJSONArray("inputs") .getJSONObject(0) .getJSONObject("payload") .getJSONArray("commands") .getJSONObject(0) .getJSONArray("execution") .getJSONObject(0) .getJSONObject("params") .getJSONObject("updateToggleSettings") cmds.keys().forEach { key -> val newState = cmds.getBoolean(key) val ledIndex= FcmContract.LEDS.indexOf(key) gpioManager.setLed(ledIndex, newState) } updateFirestore() } } } LocalBroadcastManager.getInstance(this).registerReceiver( fcmReceiver, IntentFilter(FcmContract.FCM_INTENT_ACTION) ) } override fun onResume() { super.onResume() initFcmReceiver() } override fun onPause() { LocalBroadcastManager.getInstance(this).unregisterReceiver(fcmReceiver) super.onPause() } override fun onStart() { super.onStart() firebaseAuth.initAuth(this) } }
apache-2.0
8ad333084970ecbecc8cc5a60826a61b
29.271186
87
0.629339
5.184325
false
false
false
false
icanit/mangafeed
app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/LibraryMangaGetResolver.kt
1
818
package eu.kanade.tachiyomi.data.database.resolvers import android.database.Cursor import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.database.models.MangaStorIOSQLiteGetResolver import eu.kanade.tachiyomi.data.database.tables.MangaTable class LibraryMangaGetResolver : MangaStorIOSQLiteGetResolver() { companion object { val INSTANCE = LibraryMangaGetResolver() } override fun mapFromCursor(cursor: Cursor): Manga { val manga = super.mapFromCursor(cursor) val unreadColumn = cursor.getColumnIndex(MangaTable.COLUMN_UNREAD) manga.unread = cursor.getInt(unreadColumn) val categoryColumn = cursor.getColumnIndex(MangaTable.COLUMN_CATEGORY) manga.category = cursor.getInt(categoryColumn) return manga } }
apache-2.0
7d1bcc098c338e74f80a5fc0477b1b9e
29.296296
78
0.756724
4.445652
false
false
false
false