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
FFlorien/AmpachePlayer
app/src/main/java/be/florien/anyflow/data/view/Filter.kt
1
2598
package be.florien.anyflow.data.view import be.florien.anyflow.data.DataRepository sealed class Filter<T>( val argument: T, val displayText: String, val displayImage: String? = null) { suspend fun contains(song: SongInfo, dataRepository: DataRepository): Boolean { return when (this) { is TitleIs -> song.title == argument is AlbumArtistIs -> song.albumArtistId == argument is AlbumIs -> song.albumId == argument is ArtistIs -> song.artistId == argument is GenreIs -> song.genre == argument is Search -> song.title.contains(argument, ignoreCase = true) || song.artistName.contains(argument, ignoreCase = true) || song.albumName.contains(argument, ignoreCase = true) || song.genre.contains(argument, ignoreCase = true) is SongIs -> song.id == argument is TitleContain -> song.title.contains(argument, ignoreCase = true) is PlaylistIs -> dataRepository.isPlaylistContainingSong(argument, song.id) is DownloadedStatusIs -> dataRepository.hasDownloaded(song) } } override fun equals(other: Any?): Boolean { return other is Filter<*> && argument == other.argument } override fun hashCode(): Int { var result = argument.hashCode() + javaClass.name.hashCode() result = 31 * result + (argument?.hashCode() ?: 0) return result } /** * String filters */ class TitleIs(argument: String) : Filter<String>(argument, argument) class TitleContain(argument: String) : Filter<String>(argument, argument) class GenreIs(argument: String) : Filter<String>(argument, argument) class Search(argument: String) : Filter<String>(argument, argument) /** * Long filters */ class SongIs(argument: Long, displayValue: String, displayImage: String?) : Filter<Long>(argument, displayValue, displayImage) class ArtistIs(argument: Long, displayValue: String, displayImage: String?) : Filter<Long>(argument, displayValue, displayImage) class AlbumArtistIs(argument: Long, displayValue: String, displayImage: String?) : Filter<Long>(argument, displayValue, displayImage) class AlbumIs(argument: Long, displayValue: String, displayImage: String?) : Filter<Long>(argument, displayValue, displayImage) class PlaylistIs(argument: Long, displayValue: String) : Filter<Long>(argument, displayValue, null) /** * Boolean filters */ class DownloadedStatusIs(argument: Boolean) : Filter<Boolean>(argument, argument.toString()) }
gpl-3.0
df1637b59ab95f15d0c5fac67f6b5546
38.984615
238
0.67244
4.59823
false
false
false
false
laomou/LogDog
src/main/kotlin/model/DisplayLogModel.kt
1
1563
package model import bean.LogInfo import event.ObservableSubject import event.Observer import utils.DefaultConfig class DisplayLogModel : ObservableSubject<LogInfo> { private val observers = arrayListOf<Observer<LogInfo>>() private var data = arrayListOf<LogInfo>() override fun registerObserver(o: Observer<LogInfo>) { observers.add(o) } override fun removeObserver(o: Observer<LogInfo>) { observers.remove(o) } override fun notifyAllObservers() { observers.forEach { it.update(this) } } @Synchronized fun markDataHide() { data.forEach { it.show = false } } @Synchronized fun markDataShow() { data.forEach { it.show = true it.filterColor = DefaultConfig.DEFAULT_BG_COLOR } } @Synchronized fun getData(): List<LogInfo> { return data } @Synchronized fun getDisplayData(): List<LogInfo> { return data.filter { it.show } } @Synchronized fun addLogInfo(logInfo: LogInfo) { data.add(logInfo) } fun updateData() { notifyAllObservers() } @Synchronized fun cleanData() { data.forEach { it.filters.clear() } data.clear() } @Synchronized fun getItemData(index: Int): LogInfo? { if (index >= data.size) { return null } return data[index] } @Synchronized fun getDataSize(): Int { return data.size } }
apache-2.0
a09a4f9b7c3681c414d6a3b2bc7dbd6d
18.308642
60
0.575176
4.465714
false
false
false
false
edsilfer/star-wars-wiki
app/src/main/java/br/com/edsilfer/android/starwarswiki/commons/util/Utils.kt
1
802
package br.com.edsilfer.android.starwarswiki.commons.util import android.content.Context import java.util.* /** * Created by ferna on 2/20/2017. */ object Utils { private const val ARG_PROPERTIES_CONFIGURATION_FILE = "config.properties" private val mCachedProperties = mutableMapOf<String, String>() fun readProperty(context : Context, key: String): String { if (!mCachedProperties.containsKey(key)) { val properties = Properties() val inputStream = context.assets.open(ARG_PROPERTIES_CONFIGURATION_FILE) properties.load(inputStream); val value = properties.getProperty(key) mCachedProperties.put(key, value) return value } else { return mCachedProperties[key]!! } } }
apache-2.0
a3235b7db8a96cd5749b55bd7b0031a4
26.655172
84
0.653367
4.455556
false
true
false
false
eviltak/adb-nmap
src/test/kotlin/net/eviltak/adbnmap/net/protocol/AdbTransportProtocolTest.kt
1
5328
/* * adb-nmap: An ADB network device discovery and connection library * Copyright (C) 2017-present Arav Singhal and adb-nmap contributors * * 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. * * The full license can be found in LICENSE.md. */ package net.eviltak.adbnmap.net.protocol import com.nhaarman.mockito_kotlin.* import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test import org.junit.experimental.runners.Enclosed import org.junit.runner.RunWith import java.io.* import java.net.Socket import java.net.SocketTimeoutException import java.nio.ByteBuffer import java.nio.ByteOrder @RunWith(Enclosed::class) class AdbTransportProtocolTest { class SendTestMessage { @Test fun sendTestMessageTest() { val byteArrayOutputStream = ByteArrayOutputStream() val mockedSocket = mock<Socket> { on { getOutputStream() } doReturn byteArrayOutputStream } val adbProtocol = AdbTransportProtocol(mockedSocket) adbProtocol.sendTestMessage() val expectedBuffer = ByteBuffer.allocate(4 * 6).order(ByteOrder.LITTLE_ENDIAN) expectedBuffer.putInt(0x4e584e43) expectedBuffer.putInt(0x01000000) expectedBuffer.putInt(256 * 1024) expectedBuffer.putInt(0) expectedBuffer.putInt(0) expectedBuffer.putInt(0x4e584e43 xor -1) assertTrue("Data written to socket output stream was invalid", byteArrayOutputStream.toByteArray() contentEquals expectedBuffer.array()) } } class HostUsesProtocol { @Test fun hostDoesUseProtocolTest() { val inputBuffer = ByteBuffer.allocate(4 * 6).order(ByteOrder.LITTLE_ENDIAN) // Only the command and magic bytes are considered inputBuffer.putInt(0x48545541) inputBuffer.putInt(0) inputBuffer.putInt(0) inputBuffer.putInt(0) inputBuffer.putInt(0) inputBuffer.putInt(0x48545541 xor -1) val byteArrayInputStream = ByteArrayInputStream(inputBuffer.array()) val byteArrayOutputStream = ByteArrayOutputStream() val mockedSocket = mock<Socket> { on { getInputStream() } doReturn byteArrayInputStream on { getOutputStream() } doReturn byteArrayOutputStream } val adbProtocol = AdbTransportProtocol(mockedSocket) assertTrue("hostUsesProtocol returned false", adbProtocol.hostUsesProtocol()) } @Test fun invalidDataReceivedTest() { val inputBuffer = ByteBuffer.allocate(4 * 2).order(ByteOrder.LITTLE_ENDIAN) inputBuffer.putInt(0x18561531) inputBuffer.putInt(0x32) val byteArrayInputStream = ByteArrayInputStream(inputBuffer.array()) val byteArrayOutputStream = ByteArrayOutputStream() val mockedSocket = mock<Socket> { on { getInputStream() } doReturn byteArrayInputStream on { getOutputStream() } doReturn byteArrayOutputStream } val adbProtocol = AdbTransportProtocol(mockedSocket) assertFalse("hostUsesProtocol returned true", adbProtocol.hostUsesProtocol()) } @Test fun incompleteDataReceivedTest() { val inputBuffer = ByteBuffer.allocate(4 * 5).order(ByteOrder.LITTLE_ENDIAN) inputBuffer.putInt(0x48545541) inputBuffer.putInt(0) inputBuffer.putInt(0) inputBuffer.putInt(0) inputBuffer.putInt(0) val byteArrayInputStream = ByteArrayInputStream(inputBuffer.array()) val byteArrayOutputStream = ByteArrayOutputStream() val mockedSocket = mock<Socket> { on { getInputStream() } doReturn byteArrayInputStream on { getOutputStream() } doReturn byteArrayOutputStream } val adbProtocol = AdbTransportProtocol(mockedSocket) assertFalse("hostUsesProtocol returned true", adbProtocol.hostUsesProtocol()) } @Test fun dataReceiveTimeoutTest() { val blockingInputStream = mock<InputStream> { on { read(any()) } doAnswer doAnswer@ { throw SocketTimeoutException() } } val byteArrayOutputStream = ByteArrayOutputStream() val mockedSocket = mock<Socket> { on { getInputStream() } doReturn blockingInputStream on { getOutputStream() } doReturn byteArrayOutputStream } val adbProtocol = AdbTransportProtocol(mockedSocket) assertFalse("hostUsesProtocol returned true", adbProtocol.hostUsesProtocol()) } } }
gpl-3.0
0b0f4d2e5a1a919d79931a0d88360127
35
96
0.650526
5.113244
false
true
false
false
BilledTrain380/sporttag-psa
app/shared/src/main/kotlin/ch/schulealtendorf/psa/shared/rulebook/SprintRuleSet.kt
1
2894
/* * Copyright (c) 2019 by Nicolas Märchy * * This file is part of Sporttag PSA. * * Sporttag PSA 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. * * Sporttag PSA 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 Sporttag PSA. If not, see <http://www.gnu.org/licenses/>. * * Diese Datei ist Teil von Sporttag PSA. * * Sporttag PSA ist Freie Software: Sie können es unter den Bedingungen * der GNU General Public License, wie von der Free Software Foundation, * Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren * veröffentlichten Version, weiterverbreiten und/oder modifizieren. * * Sporttag PSA wird in der Hoffnung, dass es nützlich sein wird, aber * OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite * Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. * Siehe die GNU General Public License für weitere Details. * * Sie sollten eine Kopie der GNU General Public License zusammen mit diesem * Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>. * * */ package ch.schulealtendorf.psa.shared.rulebook import ch.schulealtendorf.psa.dto.participation.GenderDto import ch.schulealtendorf.psa.dto.participation.athletics.SCHNELLLAUF import ch.schulealtendorf.psa.shared.rulebook.rules.RuleSet /** * Defines all the rules that can be applied to a sprint. * * @author nmaerchy * @version 1.0.0 */ class SprintRuleSet : RuleSet<FormulaModel, Int>() { /** * @return true if the rules of this rule set can be used, otherwise false */ override val whenever: (FormulaModel) -> Boolean = { it.discipline == SCHNELLLAUF } init { addRule( object : FormulaRule() { override val formula: (Double) -> Int = { if (it > 13.83) 1 else (19.742424 * (((1417 - (it * 100)) / 100) pow 2.1)).toInt() } override var whenever: (FormulaModel) -> Boolean = { it.gender == GenderDto.FEMALE && it.distance == "60m" } } ) addRule( object : FormulaRule() { override val formula: (Double) -> Int = { if (it > 13.61) 1 else (17.686955 * (((1397 - (it * 100)) / 100) pow 2.1)).toInt() } override val whenever: (FormulaModel) -> Boolean = { it.gender == GenderDto.MALE && it.distance == "60m" } } ) } }
gpl-3.0
ce2b5dec29c88d480eae0dcfebbf120d
35.974359
106
0.659501
4.185776
false
false
false
false
SapuSeven/BetterUntis
weekview/src/main/java/com/sapuseven/untis/views/weekview/WeekViewEvent.kt
1
3379
package com.sapuseven.untis.views.weekview import android.graphics.Color import org.joda.time.DateTime import java.util.* open class WeekViewEvent<T>( var id: Long = 0, var title: CharSequence = "", var top: CharSequence = "", var bottom: CharSequence = "", var startTime: DateTime, var endTime: DateTime, var color: Int = 0, var pastColor: Int = 0, var data: T? = null, var hasIndicator: Boolean = false ) : WeekViewDisplayable<T>, Comparable<WeekViewEvent<*>> { companion object { private val DEFAULT_COLOR = Color.parseColor("#9fc6e7") // TODO: Different default color, but this is good for testing } internal val colorOrDefault: Int get() = if (color != 0) color else DEFAULT_COLOR internal val pastColorOrDefault: Int get() = if (pastColor != 0) pastColor else DEFAULT_COLOR internal fun isSameDay(other: DateTime?) = if (other == null) false else DateUtils.isSameDay(startTime, other) internal fun isSameDay(other: WeekViewEvent<*>) = DateUtils.isSameDay(startTime, other.startTime) internal fun collidesWith(other: WeekViewEvent<*>): Boolean { val thisStart = startTime.millis val thisEnd = endTime.millis val otherStart = other.startTime.millis val otherEnd = other.endTime.millis return !(thisStart >= otherEnd || thisEnd <= otherStart) } override fun compareTo(other: WeekViewEvent<*>): Int { val thisStart = this.startTime.millis val otherStart = other.startTime.millis var comparator = thisStart.compareTo(otherStart) if (comparator == 0) { val thisEnd = this.endTime.millis val otherEnd = other.endTime.millis comparator = thisEnd.compareTo(otherEnd) } return comparator } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val that = other as WeekViewEvent<*>? return id == that!!.id } override fun hashCode(): Int { return (id xor id.ushr(32)).toInt() } /** * Splits the [WeekViewEvent] by day into a list of [WeekViewEvent]s * * @return A list of [WeekViewEvent] */ internal fun splitWeekViewEvents(): List<WeekViewEvent<T>> { val events = ArrayList<WeekViewEvent<T>>() // The first millisecond of the next day is still the same day - no need to split events for this var endTime = this.endTime.minusMillis(1) if (!isSameDay(endTime)) { endTime = startTime.withTime(23, 59, 0, 0) val event1 = WeekViewEvent<T>(id, title, top, bottom, startTime, endTime) event1.color = color event1.pastColor = pastColor events.add(event1) // Add other days. var otherDay = startTime.plusDays(1) while (!DateUtils.isSameDay(otherDay, this.endTime)) { val overDay = otherDay.withTime(0, 0, 0, 0) val endOfOverDay = overDay.withTime(23, 59, 0, 0) val eventMore = WeekViewEvent<T>(id, title, top, bottom, overDay, endOfOverDay) eventMore.color = color eventMore.pastColor = pastColor events.add(eventMore) // Add next day. otherDay = otherDay.plusDays(1) } // Add last day. val startTime = this.endTime.withTime(0, 0, 0, 0) val event2 = WeekViewEvent<T>(id, title, top, bottom, startTime, endTime) event2.color = color event2.pastColor = pastColor events.add(event2) } else { events.add(this) } return events } override fun toWeekViewEvent(): WeekViewEvent<T> { return this } }
gpl-3.0
3ac3175a879cd865a23b0faf1cac8717
27.158333
120
0.698431
3.416582
false
false
false
false
stripe/stripe-android
stripecardscan/src/main/java/com/stripe/android/stripecardscan/payment/card/PanValidator.kt
1
1633
package com.stripe.android.stripecardscan.payment.card /** * A class that provides a method to determine if a PAN is valid. */ interface PanValidator { fun isValidPan(pan: String): Boolean operator fun plus(other: PanValidator): PanValidator = CompositePanValidator(this, other) } /** * A [PanValidator] comprised of two separate validators. */ private class CompositePanValidator( private val validator1: PanValidator, private val validator2: PanValidator ) : PanValidator { override fun isValidPan(pan: String): Boolean = validator1.isValidPan(pan) && validator2.isValidPan(pan) } /** * A [PanValidator] that ensures the PAN is of a valid length. */ object LengthPanValidator : PanValidator { override fun isValidPan(pan: String): Boolean { val iinData = getIssuerData(pan) ?: return false return pan.length in iinData.panLengths } } /** * A [PanValidator] that performs the Luhn check for validation. * * see https://en.wikipedia.org/wiki/Luhn_algorithm */ object LuhnPanValidator : PanValidator { override fun isValidPan(pan: String): Boolean { if (pan.isEmpty()) { return false } fun doubleDigit(digit: Int) = if (digit * 2 > 9) digit * 2 - 9 else digit * 2 var sum = pan.takeLast(1).toInt() val parity = pan.length % 2 for (i in 0 until pan.length - 1) { sum += if (i % 2 == parity) { doubleDigit(Character.getNumericValue(pan[i])) } else { Character.getNumericValue(pan[i]) } } return sum % 10 == 0 } }
mit
88a666ef5b78f99b3520b88d7aaec8cc
26.677966
93
0.636252
3.944444
false
false
false
false
stripe/stripe-android
payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/AddressSpec.kt
1
3742
package com.stripe.android.ui.core.elements import androidx.annotation.RestrictTo import com.stripe.android.ui.core.R import com.stripe.android.ui.core.address.AddressRepository import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.Transient @Serializable enum class DisplayField { @SerialName("country") Country } @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX) sealed class AddressType { abstract val phoneNumberState: PhoneNumberState data class ShippingCondensed( val googleApiKey: String?, val autocompleteCountries: Set<String>?, override val phoneNumberState: PhoneNumberState, val onNavigation: () -> Unit ) : AddressType() data class ShippingExpanded( override val phoneNumberState: PhoneNumberState ) : AddressType() data class Normal( override val phoneNumberState: PhoneNumberState = PhoneNumberState.HIDDEN ) : AddressType() } @Serializable enum class PhoneNumberState { @SerialName("hidden") HIDDEN, @SerialName("optional") OPTIONAL, @SerialName("required") REQUIRED } @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX) @Serializable data class AddressSpec( @SerialName("api_path") override val apiPath: IdentifierSpec = IdentifierSpec.Generic("billing_details[address]"), @SerialName("allowed_country_codes") val allowedCountryCodes: Set<String> = supportedBillingCountries, @SerialName("display_fields") val displayFields: Set<DisplayField> = emptySet(), @SerialName("show_label") val showLabel: Boolean = true, /** * This field is not deserialized, this field is used for the Address Element */ @Transient val type: AddressType = AddressType.Normal() ) : FormItemSpec() { fun transform( initialValues: Map<IdentifierSpec, String?>, addressRepository: AddressRepository, shippingValues: Map<IdentifierSpec, String?>? ): SectionElement { val label = if (showLabel) R.string.billing_details else null return if (displayFields.size == 1 && displayFields.first() == DisplayField.Country) { createSectionElement( sectionFieldElement = CountryElement( identifier = IdentifierSpec.Generic("billing_details[address][country]"), controller = DropdownFieldController( CountryConfig(this.allowedCountryCodes), initialValue = initialValues[this.apiPath] ) ), label = label ) } else { val sameAsShippingElement = shippingValues?.get(IdentifierSpec.SameAsShipping) ?.toBooleanStrictOrNull() ?.let { SameAsShippingElement( identifier = IdentifierSpec.SameAsShipping, controller = SameAsShippingController(it) ) } val addressElement = AddressElement( _identifier = apiPath, addressRepository = addressRepository, rawValuesMap = initialValues, countryCodes = allowedCountryCodes, addressType = type, sameAsShippingElement = sameAsShippingElement, shippingValuesMap = shippingValues ) createSectionElement( sectionFieldElements = listOfNotNull( addressElement, sameAsShippingElement ), label = label ) } } }
mit
a6ee6d9ff10d7b8829957455547e3381
31.53913
94
0.619722
5.511046
false
false
false
false
joeygibson/raspimorse
src/main/kotlin/com/joeygibson/raspimorse/decoder/DefaultMorseCodeDecoder.kt
1
3646
package com.joeygibson.raspimorse.decoder import com.joeygibson.raspimorse.decoder.DotOrDash.DASH import com.joeygibson.raspimorse.decoder.DotOrDash.DOT import com.joeygibson.raspimorse.reader.Input import com.joeygibson.raspimorse.util.genRange import com.joeygibson.raspimorse.util.isBetween import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.fixedRateTimer /* * MIT License * * Copyright (c) 2017 Joey Gibson * * 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. */ class DefaultMorseCodeDecoder(val inputSequence: Sequence<Input>, val dotDuration: Long, val dashDuration: Long, val tolerance: Int) : MorseCodeDecoder { private val interLetterSilenceDuration = (dotDuration * 3).genRange(tolerance) private val interWordSilenceDuration = (dotDuration * 7).genRange(tolerance) private val workingList = mutableListOf<DotOrDash>() private val chars = mutableListOf<Char>() private val lock = ReentrantLock() override fun go() { fixedRateTimer(name = "Decoder Thread", initialDelay = 10, period = 100, daemon = true) { for (input in inputSequence) { if (isInterLetterSilence(input) || isInterWordSilence(input)) { val letter = decodeWorkingList(workingList) if (letter != null) { workingList.clear() synchronized(lock) { chars.add(letter) } } } else { val dod = convertToDotOrDash(input.duration) workingList.add(dod) } } } } override fun hasDecodedChars() = !chars.isEmpty() override fun decodedChars(): List<Char> { val copiedChars = synchronized(lock) { val slice = chars.slice(0..chars.size - 1) chars.clear() slice } return copiedChars } fun convertToDotOrDash(duration: Long) = if (duration.isBetween(dotDuration.genRange(tolerance))) { DOT } else { DASH } fun decodeWorkingList(list: List<DotOrDash>) = morseCodeMap[list] fun isInterLetterSilence(input: Input) = input.isSilence() && input.duration.isBetween(interLetterSilenceDuration) fun isInterWordSilence(input: Input) = input.isSilence() && input.duration.isBetween(interWordSilenceDuration) }
mit
f681bae4c6339478a811d5bb3d9770c6
36.597938
82
0.642622
4.47362
false
false
false
false
stripe/stripe-android
payments-core/src/main/java/com/stripe/android/model/PaymentMethodCreateParams.kt
1
31245
package com.stripe.android.model import android.os.Parcelable import androidx.annotation.RestrictTo import com.stripe.android.CardUtils import com.stripe.android.ObjectBuilder import com.stripe.android.Stripe import kotlinx.parcelize.Parcelize import kotlinx.parcelize.RawValue import org.json.JSONException import org.json.JSONObject /** * Model for PaymentMethod creation parameters. * * Used by [Stripe.createPaymentMethod] and [Stripe.createPaymentMethodSynchronous]. * * See [Create a PaymentMethod](https://stripe.com/docs/api/payment_methods/create). * * See [PaymentMethod] for API object. */ @Parcelize data class PaymentMethodCreateParams internal constructor( internal val code: PaymentMethodCode, internal val requiresMandate: Boolean, val card: Card? = null, private val ideal: Ideal? = null, private val fpx: Fpx? = null, private val sepaDebit: SepaDebit? = null, private val auBecsDebit: AuBecsDebit? = null, private val bacsDebit: BacsDebit? = null, private val sofort: Sofort? = null, private val upi: Upi? = null, private val netbanking: Netbanking? = null, private val usBankAccount: USBankAccount? = null, private val link: Link? = null, val billingDetails: PaymentMethod.BillingDetails? = null, private val metadata: Map<String, String>? = null, private val productUsage: Set<String> = emptySet(), /** * If provided, will be used as the representation of this object when calling the Stripe API, * instead of generating the map from its content. * * The map should be valid according to the * [PaymentMethod creation API](https://stripe.com/docs/api/payment_methods/create) * documentation, including a required `type` entry. * * The values of the map must be any of the types supported by [android.os.Parcel.writeValue]. */ private val overrideParamMap: Map<String, @RawValue Any>? = null ) : StripeParamsModel, Parcelable { internal constructor( type: PaymentMethod.Type, card: Card? = null, ideal: Ideal? = null, fpx: Fpx? = null, sepaDebit: SepaDebit? = null, auBecsDebit: AuBecsDebit? = null, bacsDebit: BacsDebit? = null, sofort: Sofort? = null, upi: Upi? = null, netbanking: Netbanking? = null, usBankAccount: USBankAccount? = null, link: Link? = null, billingDetails: PaymentMethod.BillingDetails? = null, metadata: Map<String, String>? = null, productUsage: Set<String> = emptySet(), overrideParamMap: Map<String, @RawValue Any>? = null ) : this( type.code, type.requiresMandate, card, ideal, fpx, sepaDebit, auBecsDebit, bacsDebit, sofort, upi, netbanking, usBankAccount, link, billingDetails, metadata, productUsage, overrideParamMap ) val typeCode: String get() = code internal val attribution: Set<String> @JvmSynthetic get() { return when (code) { PaymentMethod.Type.Card.code -> (card?.attribution ?: emptySet()).plus(productUsage) else -> productUsage } } private constructor( card: Card, billingDetails: PaymentMethod.BillingDetails?, metadata: Map<String, String>? ) : this( type = PaymentMethod.Type.Card, card = card, billingDetails = billingDetails, metadata = metadata ) private constructor( ideal: Ideal, billingDetails: PaymentMethod.BillingDetails?, metadata: Map<String, String>? ) : this( type = PaymentMethod.Type.Ideal, ideal = ideal, billingDetails = billingDetails, metadata = metadata ) private constructor( fpx: Fpx, billingDetails: PaymentMethod.BillingDetails?, metadata: Map<String, String>? ) : this( type = PaymentMethod.Type.Fpx, fpx = fpx, billingDetails = billingDetails, metadata = metadata ) private constructor( sepaDebit: SepaDebit, billingDetails: PaymentMethod.BillingDetails?, metadata: Map<String, String>? ) : this( type = PaymentMethod.Type.SepaDebit, sepaDebit = sepaDebit, billingDetails = billingDetails, metadata = metadata ) private constructor( auBecsDebit: AuBecsDebit, billingDetails: PaymentMethod.BillingDetails, metadata: Map<String, String>? ) : this( type = PaymentMethod.Type.AuBecsDebit, auBecsDebit = auBecsDebit, billingDetails = billingDetails, metadata = metadata ) private constructor( bacsDebit: BacsDebit, billingDetails: PaymentMethod.BillingDetails, metadata: Map<String, String>? ) : this( type = PaymentMethod.Type.BacsDebit, bacsDebit = bacsDebit, billingDetails = billingDetails, metadata = metadata ) private constructor( sofort: Sofort, billingDetails: PaymentMethod.BillingDetails?, metadata: Map<String, String>? ) : this( type = PaymentMethod.Type.Sofort, sofort = sofort, billingDetails = billingDetails, metadata = metadata ) private constructor( upi: Upi, billingDetails: PaymentMethod.BillingDetails?, metadata: Map<String, String>? ) : this( type = PaymentMethod.Type.Upi, upi = upi, billingDetails = billingDetails, metadata = metadata ) private constructor( netbanking: Netbanking, billingDetails: PaymentMethod.BillingDetails?, metadata: Map<String, String>? ) : this( type = PaymentMethod.Type.Netbanking, netbanking = netbanking, billingDetails = billingDetails, metadata = metadata ) private constructor( usBankAccount: USBankAccount, billingDetails: PaymentMethod.BillingDetails?, metadata: Map<String, String>? ) : this( type = PaymentMethod.Type.USBankAccount, usBankAccount = usBankAccount, billingDetails = billingDetails, metadata = metadata ) override fun toParamMap(): Map<String, Any> { return overrideParamMap ?: mapOf( PARAM_TYPE to code ).plus( billingDetails?.let { mapOf(PARAM_BILLING_DETAILS to it.toParamMap()) }.orEmpty() ).plus(typeParams).plus( metadata?.let { mapOf(PARAM_METADATA to it) }.orEmpty() ) } private val typeParams: Map<String, Any> get() { return when (code) { PaymentMethod.Type.Card.code -> card?.toParamMap() PaymentMethod.Type.Ideal.code -> ideal?.toParamMap() PaymentMethod.Type.Fpx.code -> fpx?.toParamMap() PaymentMethod.Type.SepaDebit.code -> sepaDebit?.toParamMap() PaymentMethod.Type.AuBecsDebit.code -> auBecsDebit?.toParamMap() PaymentMethod.Type.BacsDebit.code -> bacsDebit?.toParamMap() PaymentMethod.Type.Sofort.code -> sofort?.toParamMap() PaymentMethod.Type.Upi.code -> upi?.toParamMap() PaymentMethod.Type.Netbanking.code -> netbanking?.toParamMap() PaymentMethod.Type.USBankAccount.code -> usBankAccount?.toParamMap() PaymentMethod.Type.Link.code -> link?.toParamMap() else -> null }.takeUnless { it.isNullOrEmpty() }?.let { mapOf(code to it) }.orEmpty() } @Parcelize data class Card @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) constructor( internal val number: String? = null, internal val expiryMonth: Int? = null, internal val expiryYear: Int? = null, internal val cvc: String? = null, private val token: String? = null, internal val attribution: Set<String>? = null ) : StripeParamsModel, Parcelable { internal val brand: CardBrand get() = CardUtils.getPossibleCardBrand(number) internal val last4: String? get() = number?.takeLast(4) @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) // For paymentsheet fun getLast4() = last4 override fun toParamMap(): Map<String, Any> { return listOf( PARAM_NUMBER to number, PARAM_EXP_MONTH to expiryMonth, PARAM_EXP_YEAR to expiryYear, PARAM_CVC to cvc, PARAM_TOKEN to token ).mapNotNull { it.second?.let { value -> it.first to value } }.toMap() } /** * Used to create a [Card] object with the user's card details. To create a * [Card] with a Stripe token (e.g. for Google Pay), use [Card.create]. */ class Builder : ObjectBuilder<Card> { private var number: String? = null private var expiryMonth: Int? = null private var expiryYear: Int? = null private var cvc: String? = null fun setNumber(number: String?): Builder = apply { this.number = number } fun setExpiryMonth(expiryMonth: Int?): Builder = apply { this.expiryMonth = expiryMonth } fun setExpiryYear(expiryYear: Int?): Builder = apply { this.expiryYear = expiryYear } fun setCvc(cvc: String?): Builder = apply { this.cvc = cvc } override fun build(): Card { return Card( number = number, expiryMonth = expiryMonth, expiryYear = expiryYear, cvc = cvc ) } } companion object { private const val PARAM_NUMBER: String = "number" private const val PARAM_EXP_MONTH: String = "exp_month" private const val PARAM_EXP_YEAR: String = "exp_year" private const val PARAM_CVC: String = "cvc" private const val PARAM_TOKEN: String = "token" /** * Create a [Card] from a Card token. */ @JvmStatic fun create(token: String): Card { return Card(token = token, number = null) } } } @Parcelize data class Ideal( var bank: String? ) : StripeParamsModel, Parcelable { override fun toParamMap(): Map<String, Any> { return bank?.let { mapOf(PARAM_BANK to it) }.orEmpty() } private companion object { private const val PARAM_BANK: String = "bank" } } @Parcelize data class Fpx( var bank: String? ) : StripeParamsModel, Parcelable { override fun toParamMap(): Map<String, Any> { return bank?.let { mapOf(PARAM_BANK to it) }.orEmpty() } private companion object { private const val PARAM_BANK: String = "bank" } } @Parcelize data class Upi( private val vpa: String? ) : StripeParamsModel, Parcelable { override fun toParamMap(): Map<String, Any> { return vpa?.let { mapOf(PARAM_VPA to it) }.orEmpty() } private companion object { private const val PARAM_VPA: String = "vpa" } } @Parcelize data class SepaDebit( var iban: String? ) : StripeParamsModel, Parcelable { override fun toParamMap(): Map<String, Any> { return iban?.let { mapOf(PARAM_IBAN to it) }.orEmpty() } private companion object { private const val PARAM_IBAN: String = "iban" } } @Parcelize data class AuBecsDebit( var bsbNumber: String, var accountNumber: String ) : StripeParamsModel, Parcelable { override fun toParamMap(): Map<String, Any> { return mapOf( PARAM_BSB_NUMBER to bsbNumber, PARAM_ACCOUNT_NUMBER to accountNumber ) } private companion object { private const val PARAM_BSB_NUMBER: String = "bsb_number" private const val PARAM_ACCOUNT_NUMBER: String = "account_number" } } /** * BACS bank account details * * See [https://stripe.com/docs/api/payment_methods/create#create_payment_method-bacs_debit](https://stripe.com/docs/api/payment_methods/create#create_payment_method-bacs_debit) */ @Parcelize data class BacsDebit( /** * The bank account number (e.g. 00012345) */ var accountNumber: String, /** * The sort code of the bank account (e.g. 10-88-00) */ var sortCode: String ) : StripeParamsModel, Parcelable { override fun toParamMap(): Map<String, Any> { return mapOf( PARAM_ACCOUNT_NUMBER to accountNumber, PARAM_SORT_CODE to sortCode ) } private companion object { private const val PARAM_ACCOUNT_NUMBER: String = "account_number" private const val PARAM_SORT_CODE: String = "sort_code" } } @Parcelize data class Sofort( internal var country: String ) : StripeParamsModel, Parcelable { override fun toParamMap(): Map<String, Any> { return mapOf( PARAM_COUNTRY to country.uppercase() ) } private companion object { private const val PARAM_COUNTRY = "country" } } @Parcelize data class Netbanking( internal var bank: String ) : StripeParamsModel, Parcelable { override fun toParamMap(): Map<String, Any> { return mapOf( PARAM_BANK to bank.lowercase() ) } private companion object { private const val PARAM_BANK = "bank" } } @Parcelize @Suppress("DataClassPrivateConstructor") data class USBankAccount private constructor( internal var linkAccountSessionId: String? = null, internal var accountNumber: String? = null, internal var routingNumber: String? = null, internal var accountType: PaymentMethod.USBankAccount.USBankAccountType? = null, internal var accountHolderType: PaymentMethod.USBankAccount.USBankAccountHolderType? = null ) : StripeParamsModel, Parcelable { constructor( linkAccountSessionId: String ) : this( linkAccountSessionId, null, null, null, null ) constructor( accountNumber: String, routingNumber: String, accountType: PaymentMethod.USBankAccount.USBankAccountType, accountHolderType: PaymentMethod.USBankAccount.USBankAccountHolderType ) : this( linkAccountSessionId = null, accountNumber = accountNumber, routingNumber = routingNumber, accountType = accountType, accountHolderType = accountHolderType ) override fun toParamMap(): Map<String, Any> { return if (linkAccountSessionId != null) { mapOf( PARAM_LINKED_ACCOUNT_SESSION_ID to linkAccountSessionId!! ) } else { mapOf( PARAM_ACCOUNT_NUMBER to accountNumber!!, PARAM_ROUTING_NUMBER to routingNumber!!, PARAM_ACCOUNT_TYPE to accountType!!.value, PARAM_ACCOUNT_HOLDER_TYPE to accountHolderType!!.value ) } } private companion object { private const val PARAM_LINKED_ACCOUNT_SESSION_ID = "link_account_session" private const val PARAM_ACCOUNT_NUMBER = "account_number" private const val PARAM_ROUTING_NUMBER = "routing_number" private const val PARAM_ACCOUNT_TYPE = "account_type" private const val PARAM_ACCOUNT_HOLDER_TYPE = "account_holder_type" } } @Parcelize data class Link( internal var paymentDetailsId: String, internal var consumerSessionClientSecret: String, internal var extraParams: Map<String, @RawValue Any>? = null ) : StripeParamsModel, Parcelable { override fun toParamMap(): Map<String, Any> { return mapOf( PARAM_PAYMENT_DETAILS_ID to paymentDetailsId, PARAM_CREDENTIALS to mapOf( PARAM_CONSUMER_SESSION_CLIENT_SECRET to consumerSessionClientSecret ) ).plus( extraParams ?: emptyMap() ) } private companion object { private const val PARAM_PAYMENT_DETAILS_ID = "payment_details_id" private const val PARAM_CREDENTIALS = "credentials" private const val PARAM_CONSUMER_SESSION_CLIENT_SECRET = "consumer_session_client_secret" } } companion object { private const val PARAM_TYPE = "type" private const val PARAM_BILLING_DETAILS = "billing_details" private const val PARAM_METADATA = "metadata" /** * @return params for creating a [PaymentMethod.Type.Card] payment method */ @JvmStatic fun createCard( cardParams: CardParams ): PaymentMethodCreateParams { return create( card = Card( number = cardParams.number, expiryMonth = cardParams.expMonth, expiryYear = cardParams.expYear, cvc = cardParams.cvc, attribution = cardParams.attribution ), billingDetails = PaymentMethod.BillingDetails( name = cardParams.name, address = cardParams.address ), metadata = cardParams.metadata ) } /** * @return params for creating a [PaymentMethod.Type.Card] payment method */ @JvmStatic @JvmOverloads fun create( card: Card, billingDetails: PaymentMethod.BillingDetails? = null, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams(card, billingDetails, metadata) } /** * @return params for creating a [PaymentMethod.Type.Ideal] payment method */ @JvmStatic @JvmOverloads fun create( ideal: Ideal, billingDetails: PaymentMethod.BillingDetails? = null, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams(ideal, billingDetails, metadata) } /** * @return params for creating a [PaymentMethod.Type.Fpx] payment method */ @JvmStatic @JvmOverloads fun create( fpx: Fpx, billingDetails: PaymentMethod.BillingDetails? = null, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams(fpx, billingDetails, metadata) } /** * @return params for creating a [PaymentMethod.Type.SepaDebit] payment method */ @JvmStatic @JvmOverloads fun create( sepaDebit: SepaDebit, billingDetails: PaymentMethod.BillingDetails? = null, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams(sepaDebit, billingDetails, metadata) } /** * @return params for creating a [PaymentMethod.Type.AuBecsDebit] payment method */ @JvmStatic @JvmOverloads fun create( auBecsDebit: AuBecsDebit, billingDetails: PaymentMethod.BillingDetails, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams(auBecsDebit, billingDetails, metadata) } /** * @return params for creating a [PaymentMethod.Type.BacsDebit] payment method */ @JvmStatic @JvmOverloads fun create( bacsDebit: BacsDebit, billingDetails: PaymentMethod.BillingDetails, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams(bacsDebit, billingDetails, metadata) } /** * @return params for creating a [PaymentMethod.Type.Sofort] payment method */ @JvmStatic @JvmOverloads fun create( sofort: Sofort, billingDetails: PaymentMethod.BillingDetails? = null, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams(sofort, billingDetails, metadata) } @JvmStatic @JvmOverloads fun create( upi: Upi, billingDetails: PaymentMethod.BillingDetails? = null, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams(upi, billingDetails, metadata) } @JvmStatic @JvmOverloads fun create( usBankAccount: USBankAccount, billingDetails: PaymentMethod.BillingDetails? = null, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams(usBankAccount, billingDetails, metadata) } /** * @return params for creating a [PaymentMethod.Type.Netbanking] payment method */ @JvmStatic @JvmOverloads fun create( netbanking: Netbanking, billingDetails: PaymentMethod.BillingDetails? = null, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams(netbanking, billingDetails, metadata) } /** * @return params for creating a [PaymentMethod.Type.P24] payment method */ @JvmStatic @JvmOverloads fun createP24( billingDetails: PaymentMethod.BillingDetails, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams( type = PaymentMethod.Type.P24, billingDetails = billingDetails, metadata = metadata ) } /** * @return params for creating a [PaymentMethod.Type.Bancontact] payment method */ @JvmStatic @JvmOverloads fun createBancontact( billingDetails: PaymentMethod.BillingDetails, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams( type = PaymentMethod.Type.Bancontact, billingDetails = billingDetails, metadata = metadata ) } /** * @return params for creating a [PaymentMethod.Type.Giropay] payment method */ @JvmStatic @JvmOverloads fun createGiropay( billingDetails: PaymentMethod.BillingDetails, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams( type = PaymentMethod.Type.Giropay, billingDetails = billingDetails, metadata = metadata ) } /** * @return params for creating a [PaymentMethod.Type.GrabPay] payment method */ @JvmStatic @JvmOverloads fun createGrabPay( billingDetails: PaymentMethod.BillingDetails, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams( type = PaymentMethod.Type.GrabPay, billingDetails = billingDetails, metadata = metadata ) } /** * @return params for creating a [PaymentMethod.Type.Eps] payment method */ @JvmStatic @JvmOverloads fun createEps( billingDetails: PaymentMethod.BillingDetails, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams( type = PaymentMethod.Type.Eps, billingDetails = billingDetails, metadata = metadata ) } @JvmStatic @JvmOverloads fun createOxxo( billingDetails: PaymentMethod.BillingDetails, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams( type = PaymentMethod.Type.Oxxo, billingDetails = billingDetails, metadata = metadata ) } @JvmStatic @JvmOverloads fun createAlipay( metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams( type = PaymentMethod.Type.Alipay, metadata = metadata ) } @JvmStatic @JvmOverloads fun createPayPal( metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams( type = PaymentMethod.Type.PayPal, metadata = metadata ) } @JvmStatic @JvmOverloads fun createAfterpayClearpay( billingDetails: PaymentMethod.BillingDetails? = null, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams( type = PaymentMethod.Type.AfterpayClearpay, billingDetails = billingDetails, metadata = metadata ) } /** * @param googlePayPaymentData a [JSONObject] derived from Google Pay's * [PaymentData#toJson()](https://developers.google.com/pay/api/android/reference/client#tojson) */ @Throws(JSONException::class) @JvmStatic fun createFromGooglePay(googlePayPaymentData: JSONObject): PaymentMethodCreateParams { val googlePayResult = GooglePayResult.fromJson(googlePayPaymentData) val token = googlePayResult.token val tokenId = token?.id.orEmpty() return create( Card( token = tokenId, attribution = setOfNotNull(token?.card?.tokenizationMethod?.toString()) ), PaymentMethod.BillingDetails( address = googlePayResult.address, name = googlePayResult.name, email = googlePayResult.email, phone = googlePayResult.phoneNumber ) ) } @JvmStatic @JvmOverloads fun createBlik( billingDetails: PaymentMethod.BillingDetails? = null, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams( type = PaymentMethod.Type.Blik, billingDetails = billingDetails, metadata = metadata ) } @JvmStatic @JvmOverloads fun createWeChatPay( billingDetails: PaymentMethod.BillingDetails? = null, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams( type = PaymentMethod.Type.WeChatPay, billingDetails = billingDetails, metadata = metadata ) } @JvmStatic @JvmOverloads fun createKlarna( billingDetails: PaymentMethod.BillingDetails? = null, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams( type = PaymentMethod.Type.Klarna, billingDetails = billingDetails, metadata = metadata ) } @JvmStatic @JvmOverloads fun createAffirm( billingDetails: PaymentMethod.BillingDetails? = null, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams( type = PaymentMethod.Type.Affirm, billingDetails = billingDetails, metadata = metadata ) } @JvmStatic @JvmOverloads fun createUSBankAccount( billingDetails: PaymentMethod.BillingDetails? = null, metadata: Map<String, String>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams( type = PaymentMethod.Type.USBankAccount, billingDetails = billingDetails, metadata = metadata ) } @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun createLink( paymentDetailsId: String, consumerSessionClientSecret: String, extraParams: Map<String, @RawValue Any>? = null ): PaymentMethodCreateParams { return PaymentMethodCreateParams( type = PaymentMethod.Type.Link, link = Link( paymentDetailsId, consumerSessionClientSecret, extraParams ) ) } @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) // For paymentsheet fun createWithOverride( code: PaymentMethodCode, requiresMandate: Boolean, overrideParamMap: Map<String, @RawValue Any>?, productUsage: Set<String> ): PaymentMethodCreateParams { return PaymentMethodCreateParams( code = code, requiresMandate = requiresMandate, overrideParamMap = overrideParamMap, productUsage = productUsage ) } } }
mit
a2297fd08c39515f9e8ef66565a814e5
31.85489
181
0.569339
5.17387
false
false
false
false
AndroidX/androidx
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/node/DelegatingNode.kt
3
3116
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.node import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier /** * A [Modifier.Node] which is able to delegate work to other [Modifier.Node] instances. * * This can be useful to compose multiple node implementations into one. * * @sample androidx.compose.ui.samples.DelegatedNodeSample * * @see DelegatingNode */ @ExperimentalComposeUiApi abstract class DelegatingNode : Modifier.Node() { override fun updateCoordinator(coordinator: NodeCoordinator?) { super.updateCoordinator(coordinator) forEachDelegate { it.updateCoordinator(coordinator) } } private var delegate: Modifier.Node? = null /** * In order to properly delegate work to another [Modifier.Node], the delegated instance must * be created and returned inside of a [delegated] call. Doing this will * ensure that the created node instance follows all of the right lifecycles and is properly * discoverable in this position of the node tree. * * By using [delegated], the [fn] parameter is executed synchronously, and the result is * returned from this function for immediate use. * * This method can be called from within an `init` block, however the returned delegated node * will not be attached until the delegating node is attached. If [delegated] is called after * the delegating node is already attached, the returned delegated node will be attached. */ fun <T : Modifier.Node> delegated(fn: () -> T): T { val owner = node val delegate = fn() delegate.setAsDelegateTo(owner) if (isAttached) { updateCoordinator(owner.coordinator) delegate.attach() } addDelegate(delegate) return delegate } private fun addDelegate(node: Modifier.Node) { val tail = delegate if (tail != null) { node.parent = tail } delegate = node } private inline fun forEachDelegate(block: (Modifier.Node) -> Unit) { var node: Modifier.Node? = delegate while (node != null) { block(node) node = node.parent } } override fun onAttach() { super.onAttach() forEachDelegate { it.updateCoordinator(coordinator) it.attach() } } override fun onDetach() { forEachDelegate { it.detach() } super.onDetach() } }
apache-2.0
5e15a094983236d9ca0a9d9361d46f7d
31.8
97
0.662709
4.575624
false
false
false
false
mightyfrog/S4FD
app/src/main/java/org/mightyfrog/android/s4fd/data/MovementDatum.kt
1
925
package org.mightyfrog.android.s4fd.data import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName import com.raizlabs.android.dbflow.annotation.Column import com.raizlabs.android.dbflow.annotation.PrimaryKey import com.raizlabs.android.dbflow.annotation.Table import com.raizlabs.android.dbflow.structure.BaseModel /** * @author Shigehiro Soejima */ @Table(database = AppDatabase::class) class MovementDatum : BaseModel() { @Column @SerializedName("name") @Expose var name: String? = null @Column @SerializedName("ownerId") @Expose var ownerId: Int = 0 @PrimaryKey @Column @SerializedName("id") @Expose var id: Int = 0 @Column @SerializedName("value") @Expose var value: String? = null override fun toString(): String { return "MovementDatum(id=$id, name=$name, ownerId=$ownerId, value=$value)" } }
apache-2.0
6da943706ba381bd21d78515e1f6e9ef
22.74359
82
0.704865
3.93617
false
false
false
false
markusressel/TypedPreferences
app/src/main/java/de/markusressel/typedpreferencesdemo/PreferenceHandler.kt
1
1585
/* * Copyright (c) 2017 Markus Ressel * * 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 de.markusressel.typedpreferencesdemo import android.content.Context import de.markusressel.typedpreferences.PreferenceItem import de.markusressel.typedpreferences.PreferencesHandlerBase import javax.inject.Inject import javax.inject.Singleton /** * Created by Markus on 18.07.2017. */ @Singleton class PreferenceHandler @Inject constructor(context: Context) : PreferencesHandlerBase(context) { // be sure to override the get() method override var sharedPreferencesName: String? = null get() = "preferences" override val allPreferenceItems: Set<PreferenceItem<*>> = hashSetOf( THEME, BOOLEAN_SETTING, COMPLEX_SETTING ) companion object { val THEME = PreferenceItem(R.string.key_theme, 0) val BOOLEAN_SETTING = PreferenceItem(R.string.key_boolean_setting, true) val COMPLEX_SETTING = PreferenceItem(R.string.key_complex_setting, ComplexClass("Complex ^", 10, listOf(1, 2, 3))) } }
apache-2.0
81d91e8de5d0c8fcfb92ad3cfa13f732
32.020833
122
0.726814
4.237968
false
false
false
false
Soya93/Extract-Refactoring
platform/script-debugger/debugger-ui/src/com/jetbrains/javascript/debugger/NameMapper.kt
1
4479
/* * 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 com.jetbrains.javascript.debugger import com.google.common.base.CharMatcher import com.intellij.openapi.editor.Document import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import gnu.trove.THashMap import org.jetbrains.debugger.sourcemap.MappingEntry import org.jetbrains.debugger.sourcemap.MappingList import org.jetbrains.debugger.sourcemap.SourceMap import org.jetbrains.rpc.LOG private val S1 = ",()[]{}=" // don't trim trailing .&: - could be part of expression private val OPERATOR_TRIMMER = CharMatcher.INVISIBLE.or(CharMatcher.anyOf(S1)) val NAME_TRIMMER = CharMatcher.INVISIBLE.or(CharMatcher.anyOf(S1 + ".&:")) // generateVirtualFile only for debug purposes open class NameMapper(private val document: Document, private val transpiledDocument: Document, private val sourceMappings: MappingList, private val sourceMap: SourceMap, private val transpiledFile: VirtualFile? = null) { var rawNameToSource: MutableMap<String, String>? = null private set // PsiNamedElement, JSVariable for example // returns generated name fun map(identifierOrNamedElement: PsiElement): String? { val offset = identifierOrNamedElement.textOffset val line = document.getLineNumber(offset) val sourceEntryIndex = sourceMappings.indexOf(line, offset - document.getLineStartOffset(line)) if (sourceEntryIndex == -1) { return null } val sourceEntry = sourceMappings.get(sourceEntryIndex) val next = sourceMappings.getNextOnTheSameLine(sourceEntryIndex, false) if (next != null && sourceMappings.getColumn(next) == sourceMappings.getColumn(sourceEntry)) { warnSeveralMapping(identifierOrNamedElement) return null } if (sourceEntry.generatedLine > document.lineCount) { LOG.warn("Cannot get generated name: source entry line ${sourceEntry.generatedLine} > ${document.lineCount}. Transpiled File: " + transpiledFile?.path) return null } val generatedName = extractName(getGeneratedName(transpiledDocument, sourceMap, sourceEntry)) if (generatedName.isEmpty()) { return null } var sourceName = sourceEntry.name if (sourceName == null || Registry.`is`("js.debugger.name.mappings.by.source.code", false)) { sourceName = (identifierOrNamedElement as? PsiNamedElement)?.name ?: identifierOrNamedElement.text ?: sourceName ?: return null } if (rawNameToSource == null) { rawNameToSource = THashMap<String, String>() } rawNameToSource!!.put(generatedName, sourceName) return generatedName } protected open fun extractName(rawGeneratedName: CharSequence) = NAME_TRIMMER.trimFrom(rawGeneratedName) companion object { fun trimName(rawGeneratedName: CharSequence, isLastToken: Boolean) = (if (isLastToken) NAME_TRIMMER else OPERATOR_TRIMMER).trimFrom(rawGeneratedName) } } fun warnSeveralMapping(element: PsiElement) { // see https://dl.dropboxusercontent.com/u/43511007/s/Screen%20Shot%202015-01-21%20at%2020.33.44.png // var1 mapped to the whole "var c, notes, templates, ..." expression text + unrelated text " ;" LOG.warn("incorrect sourcemap, several mappings for named element ${element.text}") } private fun getGeneratedName(document: Document, sourceMap: SourceMap, sourceEntry: MappingEntry): CharSequence { val lineStartOffset = document.getLineStartOffset(sourceEntry.generatedLine) val nextGeneratedMapping = sourceMap.mappings.getNextOnTheSameLine(sourceEntry) val endOffset: Int if (nextGeneratedMapping == null) { endOffset = document.getLineEndOffset(sourceEntry.generatedLine) } else { endOffset = lineStartOffset + nextGeneratedMapping.generatedColumn } return document.immutableCharSequence.subSequence(lineStartOffset + sourceEntry.generatedColumn, endOffset) }
apache-2.0
e50db79304b7d30e037cb40ba0a7661d
41.666667
221
0.762
4.269781
false
false
false
false
hidroh/tldroid
app/src/main/kotlin/io/github/hidroh/tldroid/MainActivity.kt
1
6405
package io.github.hidroh.tldroid import android.content.Context import android.content.Intent import android.database.Cursor import android.databinding.DataBindingUtil import android.databinding.ViewDataBinding import android.os.Bundle import android.preference.PreferenceManager import android.provider.BaseColumns import android.support.design.widget.BottomSheetDialog import android.support.v4.widget.ResourceCursorAdapter import android.support.v7.widget.PopupMenu import android.text.TextUtils import android.text.format.DateUtils import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputMethodManager import android.widget.* class MainActivity : ThemedActivity() { private var mEditText: AutoCompleteTextView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView() } private fun setContentView() { DataBindingUtil.setContentView<ViewDataBinding>(this, R.layout.activity_main) findViewById(R.id.info_button)!!.setOnClickListener { showInfo() } findViewById(R.id.list_button)!!.setOnClickListener { showList() } findViewById(R.id.settings_button)!!.setOnClickListener { showThemeOptions() } mEditText = findViewById(R.id.edit_text) as AutoCompleteTextView? mEditText!!.setOnEditorActionListener { v, actionId, _ -> actionId == EditorInfo.IME_ACTION_SEARCH && search(v.text.toString(), null) } mEditText!!.setAdapter(CursorAdapter(this)) mEditText!!.onItemClickListener = AdapterView.OnItemClickListener { _, view, _, _ -> val text = (view.findViewById(android.R.id.text1) as TextView).text val platform = (view.findViewById(android.R.id.text2) as TextView).text search(text.toString(), platform) } } private fun search(query: CharSequence, platform: CharSequence?): Boolean { if (TextUtils.isEmpty(query)) { return false } mEditText!!.setText(query) mEditText!!.setSelection(query.length) startActivity(Intent(this, CommandActivity::class.java) .putExtra(CommandActivity.EXTRA_QUERY, query) .putExtra(CommandActivity.EXTRA_PLATFORM, platform)) return true } private fun showInfo() { closeSoftKeyboard() val binding = DataBindingUtil.inflate<ViewDataBinding>(layoutInflater, R.layout.web_view, null, false) val lastRefreshed = PreferenceManager.getDefaultSharedPreferences(this) .getLong(SyncService.PREF_LAST_REFRESHED, 0L) val lastRefreshedText = if (lastRefreshed > 0) DateUtils.getRelativeDateTimeString(this, lastRefreshed, DateUtils.HOUR_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, 0) else getString(R.string.never) val totalCommands = PreferenceManager.getDefaultSharedPreferences(this) .getInt(SyncService.PREF_COMMAND_COUNT, 0) binding.setVariable(io.github.hidroh.tldroid.BR.content, getString(R.string.info_html, lastRefreshedText, totalCommands) + getString(R.string.about_html)) binding.root.id = R.id.web_view val dialog = BottomSheetDialog(this) dialog.setContentView(binding.root) dialog.show() } private fun showList() { closeSoftKeyboard() val dialog = BottomSheetDialog(this) val view = layoutInflater.inflate(R.layout.dialog_commands, null, false) val listView = view.findViewById(android.R.id.list) as ListView val adapter = CursorAdapter(this) adapter.filter.filter("") listView.adapter = adapter listView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ -> val cursor = adapter.getItem(position) as Cursor? ?: return@OnItemClickListener search(cursor.getString(cursor.getColumnIndex(TldrProvider.CommandEntry.COLUMN_NAME)), cursor.getString(cursor.getColumnIndex(TldrProvider.CommandEntry.COLUMN_PLATFORM))) } dialog.setContentView(view) dialog.show() } private fun showThemeOptions() { val popupMenu = PopupMenu(this, findViewById(R.id.settings_button), Gravity.NO_GRAVITY) popupMenu.inflate(R.menu.menu_theme) popupMenu.setOnMenuItemClickListener { item -> Utils.saveTheme(this, when (item.itemId) { R.id.menu_afterglow -> R.style.AppTheme_Afterglow R.id.menu_tomorrow -> R.style.AppTheme_Tomorrow else -> R.style.AppTheme }) setContentView() true } popupMenu.show() } private fun closeSoftKeyboard() { (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager) .hideSoftInputFromWindow(mEditText!!.windowToken, 0) } private class CursorAdapter(context: Context) : ResourceCursorAdapter(context, R.layout.dropdown_item, null, false) { private val mInflater: LayoutInflater = LayoutInflater.from(context) private var mQueryString: String? = null init { filterQueryProvider = FilterQueryProvider { constraint -> mQueryString = constraint?.toString() ?: "" context.contentResolver.query(TldrProvider.URI_COMMAND, arrayOf(BaseColumns._ID, TldrProvider.CommandEntry.COLUMN_NAME, TldrProvider.CommandEntry.COLUMN_PLATFORM), "${TldrProvider.CommandEntry.COLUMN_NAME} LIKE ?", arrayOf("%$mQueryString%"), null) } } override fun newView(context: Context?, cursor: Cursor?, parent: ViewGroup): View { return newDropDownView(context, cursor, parent) } override fun newDropDownView(context: Context?, cursor: Cursor?, parent: ViewGroup): View { val holder = DataBindingUtil.inflate<ViewDataBinding>(mInflater, R.layout.dropdown_item, parent, false) val view = holder.root view.setTag(R.id.dataBinding, holder) return view } override fun bindView(view: View, context: Context, cursor: Cursor) { val binding = view.getTag(R.id.dataBinding) as ViewDataBinding binding.setVariable(io.github.hidroh.tldroid.BR.command, Bindings.Command.fromProvider(cursor)) binding.setVariable(io.github.hidroh.tldroid.BR.highlight, mQueryString) } override fun convertToString(cursor: Cursor?): CharSequence { return cursor!!.getString(cursor.getColumnIndexOrThrow( TldrProvider.CommandEntry.COLUMN_NAME)) } } }
apache-2.0
8dd24fb43ecbbbcebdf50007ecb675be
37.818182
95
0.721936
4.42029
false
false
false
false
inorichi/tachiyomi-extensions
multisrc/overrides/webtoons/dongmanmanhua/src/DongmanManhua.kt
1
2414
package eu.kanade.tachiyomi.extension.zh.dongmanmanhua import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.multisrc.webtoons.Webtoons import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.util.asJsoup import okhttp3.Headers import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.text.SimpleDateFormat import java.util.Locale class DongmanManhua : Webtoons("Dongman Manhua", "https://www.dongmanmanhua.cn", "zh", "", dateFormat = SimpleDateFormat("yyyy-M-d", Locale.ENGLISH)) { override fun headersBuilder(): Headers.Builder = super.headersBuilder() .removeAll("Referer") .add("Referer", baseUrl) override fun popularMangaRequest(page: Int) = GET("$baseUrl/dailySchedule", headers) override fun latestUpdatesRequest(page: Int) = GET("$baseUrl/dailySchedule?sortOrder=UPDATE&webtoonCompleteType=ONGOING", headers) override fun parseDetailsThumbnail(document: Document): String? { return document.select("div.detail_body").attr("style").substringAfter("(").substringBefore(")") } override fun chapterListRequest(manga: SManga): Request = GET(baseUrl + manga.url, headers) override fun chapterListSelector() = "ul#_listUl li" override fun chapterListParse(response: Response): List<SChapter> { var document = response.asJsoup() var continueParsing = true val chapters = mutableListOf<SChapter>() while (continueParsing) { document.select(chapterListSelector()).map { chapters.add(chapterFromElement(it)) } document.select("div.paginate a[onclick] + a").let { element -> if (element.isNotEmpty()) document = client.newCall(GET(element.attr("abs:href"), headers)).execute().asJsoup() else continueParsing = false } } return chapters } override fun chapterFromElement(element: Element): SChapter { return SChapter.create().apply { name = element.select("span.subj span").text() url = element.select("a").attr("href").substringAfter(".cn") date_upload = chapterParseDate(element.select("span.date").text()) } } override fun getFilterList(): FilterList = FilterList() }
apache-2.0
7cefa65acc8867ba9d99b5b61a783eee
39.915254
151
0.702568
4.405109
false
false
false
false
y2k/JoyReactor
core/src/main/kotlin/y2k/joyreactor/services/BroadcastService.kt
1
2209
package y2k.joyreactor.services import y2k.joyreactor.common.ForegroundScheduler import y2k.joyreactor.common.Notifications import y2k.joyreactor.model.Group import java.util.* /** * Created by y2k on 2/3/16. */ object BroadcastService { private val observers = HashMap<Any, Observable>() private val registrations = HashMap<ActionObserver<*>, Any>() fun broadcast(message: Notifications) { broadcast(message, message) } fun broadcastType(message: Any) { broadcast(message.javaClass, message) } fun broadcast(message: Any) { broadcast(message, message) } fun broadcast(token: Any, message: Any) { ForegroundScheduler.instance.createWorker().schedule { val observable = observers[token] observable?.notifyObservers(message) } } fun <T : Any> register(receiver: Any, token: Any, callback: (T) -> Unit) { var observable = observers[token] if (observable == null) { observable = ObservableImpl() observers.put(token, observable) } val o = ActionObserver(callback) observable.addObserver(o) registrations.put(o, receiver) } fun unregisterToken(token: Any) { var observable = observers.remove(token) if (observable != null) observable.deleteObservers() } fun unregister(receiver: Any) { for (key in registrations.keys.toList()) if (registrations[key] === receiver) { registrations.remove(key) for (o in observers.values) o.deleteObserver(key) } } abstract class SubscriptionChangeMessage<T>(val newValue: T) class TagSelected(var group: Group) : SubscriptionChangeMessage<Group>(group) private class ActionObserver<T>(private val callback: (T) -> Unit) : Observer { @Suppress("UNCHECKED_CAST") override fun update(o: Observable, arg: Any) { callback(arg as T) } } private class ObservableImpl : Observable() { override fun notifyObservers(arg: Any) { setChanged() super.notifyObservers(arg) } } }
gpl-2.0
b5fc475b3b27aa669dbb44620183aeaf
26.625
83
0.621096
4.409182
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/dashboard/feedback/FeedbackModelImpl.kt
1
3337
package com.intfocus.template.dashboard.feedback import android.content.Context import com.intfocus.template.SYPApplication.globalContext import com.intfocus.template.constant.Params.USER_BEAN import com.intfocus.template.constant.Params.USER_NUM import com.intfocus.template.general.net.ApiException import com.intfocus.template.general.net.CodeHandledSubscriber import com.intfocus.template.general.net.RetrofitUtil import com.intfocus.template.model.callback.LoadDataCallback import com.intfocus.template.model.response.mine_page.FeedbackContent import com.intfocus.template.model.response.mine_page.FeedbackList import rx.Subscription /** * @author liuruilin * @data 2017/11/28 * @describe 问题反馈 Model 实现类 */ class FeedbackModelImpl: FeedbackModel{ private var mUserSP = globalContext.getSharedPreferences(USER_BEAN, Context.MODE_PRIVATE) companion object { private val TAG = "FeedbackModelImpl" private var INSTANCE: FeedbackModelImpl? = null private var observable: Subscription? = null /** * Returns the single instance of this class, creating it if necessary. */ @JvmStatic fun getInstance(): FeedbackModelImpl { return INSTANCE ?: FeedbackModelImpl() .apply { INSTANCE = this } } /** * Used to force [getInstance] to create a new instance * next time it's called. */ @JvmStatic fun destroyInstance() { unSubscribe() INSTANCE = null } /** * 取消订阅 */ private fun unSubscribe() { observable?.unsubscribe() ?: return } } override fun getList(callback: LoadDataCallback<FeedbackList>) { RetrofitUtil.getHttpService(globalContext).getFeedbackList(mUserSP.getString(USER_NUM, "")) .compose(RetrofitUtil.CommonOptions<FeedbackList>()) .subscribe(object : CodeHandledSubscriber<FeedbackList>() { override fun onError(apiException: ApiException?) { apiException?.let { callback.onError(it) } } override fun onCompleted() { } override fun onBusinessNext(data: FeedbackList?) { data?.let { callback.onSuccess(it) } } }) } override fun getContent(id: Int, callback: LoadDataCallback<FeedbackContent>) { RetrofitUtil.getHttpService(globalContext).getFeedbackContent(id) .compose(RetrofitUtil.CommonOptions<FeedbackContent>()) .subscribe(object : CodeHandledSubscriber<FeedbackContent>() { override fun onError(apiException: ApiException?) { } override fun onCompleted() { } override fun onBusinessNext(data: FeedbackContent?) { callback.onSuccess(data!!) } }) } override fun submit() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }
gpl-3.0
9f869580763ce877be326c5ae38cf972
33.894737
107
0.59457
5.261905
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/tumui/calendar/CalendarDao.kt
1
5041
package de.tum.`in`.tumcampusapp.component.tumui.calendar import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import de.tum.`in`.tumcampusapp.component.tumui.calendar.model.CalendarItem import de.tum.`in`.tumcampusapp.component.tumui.calendar.model.EventSeriesMapping import org.joda.time.DateTime @Dao interface CalendarDao { @get:Query("SELECT c.* FROM calendar c WHERE status != 'CANCEL'") val allNotCancelled: List<CalendarItem> @get:Query("SELECT c.* FROM calendar c WHERE datetime('now', 'localtime') BETWEEN dtstart AND dtend AND status != 'CANCEL' ORDER BY title") val currentLectures: List<CalendarItem> @get:Query("SELECT c.* " + "FROM calendar c LEFT JOIN room_locations r ON " + "c.location=r.title " + "WHERE coalesce(r.latitude, '') = '' " + "GROUP BY c.location") val lecturesWithoutCoordinates: List<CalendarItem> @get:Query("SELECT c.* FROM calendar c JOIN " + "(SELECT dtstart AS maxstart FROM calendar WHERE status!='CANCEL' AND datetime('now', 'localtime')<dtstart " + "ORDER BY dtstart LIMIT 1) ON status!='CANCEL' AND datetime('now', 'localtime')<dtend AND dtstart<=maxstart " + "ORDER BY dtend, dtstart LIMIT 4") val nextCalendarItems: List<CalendarItem> @get:Query("SELECT * FROM calendar " + "WHERE status!='CANCEL' " + "AND dtstart > datetime('now', 'localtime') " + "GROUP BY title, dtstart, dtend " + "ORDER BY dtstart LIMIT 4") val nextUniqueCalendarItems: List<CalendarItem> @Query("SELECT c.* FROM calendar c WHERE dtstart LIKE '%' || :date || '%' ORDER BY dtstart ASC") fun getAllByDate(date: DateTime): List<CalendarItem> @Query("SELECT c.* FROM calendar c WHERE dtend BETWEEN :from AND :to " + "ORDER BY dtstart, title, location ASC") fun getAllBetweenDates(from: DateTime, to: DateTime): List<CalendarItem> @Query("SELECT c.* FROM calendar c WHERE dtend BETWEEN :from AND :to " + "AND STATUS != 'CANCEL'" + "ORDER BY dtstart, title, location ASC") fun getAllNotCancelledBetweenDates(from: DateTime, to: DateTime): List<CalendarItem> @Query("SELECT c.* FROM calendar c WHERE dtend BETWEEN :from AND :to " + "AND STATUS != 'CANCEL'" + "AND NOT EXISTS (SELECT * FROM widgets_timetable_blacklist WHERE widget_id = :widgetId" + " AND lecture_title = c.title)" + "ORDER BY dtstart ASC") fun getNextDays(from: DateTime, to: DateTime, widgetId: String): List<CalendarItem> @Query("SELECT COUNT(*) FROM calendar") fun hasLectures(): Boolean @Query("SELECT c.* FROM calendar c, widgets_timetable_blacklist " + "WHERE widget_id=:widgetId AND lecture_title=title " + "GROUP BY title") fun getLecturesInBlacklist(widgetId: String): List<CalendarItem> @Query("SELECT c.* FROM calendar c " + "WHERE NOT EXISTS (SELECT * FROM widgets_timetable_blacklist " + "WHERE widget_id=:widgetId AND c.title=lecture_title) " + "GROUP BY c.title") fun getLecturesNotInBlacklist(widgetId: String): List<CalendarItem> @Query("DELETE FROM calendar") fun flush() @Query("DELETE FROM calendar WHERE nr=:eventNr") fun delete(eventNr: String) @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(vararg cal: CalendarItem) @Query("SELECT location FROM calendar " + "WHERE title = (SELECT title FROM calendar WHERE nr=:id) " + "AND dtstart = (SELECT dtstart FROM calendar WHERE nr=:id) " + "AND dtend = (SELECT dtend FROM calendar WHERE nr=:id) " + "AND status != 'CANCEL' " + "ORDER BY location ASC") fun getNonCancelledLocationsById(id: String): List<String> @Query("SELECT * FROM calendar WHERE nr=:id" + " UNION " + "SELECT * FROM calendar " + "WHERE title = (SELECT title FROM calendar WHERE nr=:id) " + "AND dtstart = (SELECT dtstart FROM calendar WHERE nr=:id) " + "AND dtend = (SELECT dtend FROM calendar WHERE nr=:id) " + "AND nr != :id " + "ORDER BY location ASC") fun getCalendarItemsById(id: String): List<CalendarItem> @Query("SELECT * FROM calendar WHERE nr=:id") fun getCalendarItemById(id: String): CalendarItem @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(vararg cal: EventSeriesMapping) @Query("SELECT calendar.* FROM calendar " + "LEFT JOIN eventSeriesMappings ON eventSeriesMappings.eventId=calendar.nr " + "WHERE eventSeriesMappings.seriesId=:seriesId") fun getCalendarItemsInSeries(seriesId: String): List<CalendarItem> @Query("SELECT eventSeriesMappings.seriesId FROM eventSeriesMappings WHERE eventSeriesMappings.eventId=:eventId LIMIT 1") fun getSeriesIdForEvent(eventId: String): String? }
gpl-3.0
eaaf6c309c27903ed986629f4426e85d
44.414414
143
0.654632
4.176471
false
false
false
false
rhdunn/xquery-intellij-plugin
src/plugin-api/main/uk/co/reecedunn/intellij/plugin/processor/profile/execution/ui/FlatProfileTableView.kt
1
6273
/* * Copyright (C) 2019-2020 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.processor.profile.execution.ui import com.intellij.execution.process.ProcessHandler import com.intellij.execution.ui.ConsoleView import com.intellij.execution.ui.RunnerLayoutUi import com.intellij.icons.AllIcons import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.application.runUndoTransparentWriteAction import com.intellij.openapi.fileChooser.FileSaverDescriptor import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.components.JBScrollPane import com.intellij.ui.content.Content import com.intellij.util.Consumer import com.intellij.util.ui.ListTableModel import uk.co.reecedunn.intellij.plugin.core.execution.ui.ContentProvider import uk.co.reecedunn.intellij.plugin.processor.profile.FlatProfileEntry import uk.co.reecedunn.intellij.plugin.processor.profile.FlatProfileReport import uk.co.reecedunn.intellij.plugin.processor.profile.execution.process.ProfileReportListener import uk.co.reecedunn.intellij.plugin.processor.profile.execution.process.ProfileableQueryProcessHandler import uk.co.reecedunn.intellij.plugin.processor.resources.PluginApiBundle import uk.co.reecedunn.intellij.plugin.processor.run.execution.ui.QueryConsoleView import uk.co.reecedunn.intellij.plugin.processor.run.execution.ui.QueryTable import java.text.DateFormat import java.text.SimpleDateFormat import javax.swing.JComponent import javax.swing.JTable private val ISO_DATE_FORMAT = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss") private val FILE_DATE_FORMAT = SimpleDateFormat("yyyy-MM-dd'T'HHmmss") private fun formatDate(date: String, dateFormat: DateFormat = SimpleDateFormat.getDateTimeInstance()): String { return try { val d = ISO_DATE_FORMAT.parse(date.replace("""\\.[0-9]+Z""".toRegex(), "")) dateFormat.format(d) } catch (e: Exception) { date } } class FlatProfileTableView(val project: Project) : ContentProvider, Disposable, ProfileReportListener { // region UI private var report: FlatProfileReport? = null private var save: SaveAction? = null private var component: JComponent? = null private var results: JTable? = null private fun createComponent(): JComponent { results = FlatProfileTable() results!!.selectionModel.addListSelectionListener { val row = results!!.selectedRow if (row >= 0) { val index = results!!.convertRowIndexToModel(row) val item = (results!!.model as ListTableModel<*>).getItem(index) as FlatProfileEntry val navigatable = item.frame.sourcePosition?.createNavigatable(project) if (navigatable?.canNavigate() == true) { navigatable.navigate(true) } } } component = JBScrollPane(results) return component!! } // endregion // region ContentProvider private var queryProcessHandler: ProfileableQueryProcessHandler? = null override val contentId: String = "FlatProfile" override fun getContent(ui: RunnerLayoutUi): Content { val consoleTitle: String = PluginApiBundle.message("console.tab.flat-profile.label") val content = ui.createContent(contentId, getComponent(), consoleTitle, AllIcons.Debugger.Overhead, null) content.isCloseable = false return content } private fun getComponent(): JComponent = component ?: createComponent() override fun clear() { report = null results!!.removeAll() } override fun createRunnerLayoutActions(): Array<AnAction> { val descriptor = FileSaverDescriptor( PluginApiBundle.message("console.action.save.profile.title"), PluginApiBundle.message("console.action.save.profile.description"), "xml" ) save = SaveAction( descriptor, getComponent(), project, Consumer { onSaveProfileReport(it) }) save?.isEnabled = report?.xml != null return arrayOf(save!!) } override fun attachToProcess(processHandler: ProcessHandler) { queryProcessHandler = processHandler as? ProfileableQueryProcessHandler queryProcessHandler?.addProfileReportListener(this) } override fun attachToConsole(consoleView: ConsoleView) { (consoleView as? QueryConsoleView)?.registerQueryTable(results as QueryTable) } // endregion // region Disposable override fun dispose() { queryProcessHandler?.removeProfileReportListener(this) } // endregion // region ProfileReportListener override fun onProfileReport(result: FlatProfileReport) { report = result save?.isEnabled = report?.xml != null (results as FlatProfileTable).let { it.elapsed = result.elapsed it.removeAll() result.results.forEach { entry -> it.addRow(entry) } } } // endregion // region Actions private fun onSaveProfileReport(file: VirtualFile) { when { report?.xml == null -> return file.isDirectory -> { val name = "profile-report-${ formatDate(report!!.created, FILE_DATE_FORMAT) }.xml" runUndoTransparentWriteAction { onSaveProfileReport(file.createChildData(this, name)) } } else -> file.getOutputStream(this).use { it.write(report?.xml!!.toByteArray()) } } } // endregion }
apache-2.0
43d27581459af6c7f10a194b6d835d47
35.051724
113
0.689941
4.705926
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/map/tangram/KtMapController.kt
1
16155
package de.westnordost.streetcomplete.map.tangram import android.animation.TimeAnimator import android.content.ContentResolver import android.graphics.Bitmap import android.graphics.PointF import android.graphics.RectF import android.os.Handler import android.os.Looper import android.view.animation.AccelerateDecelerateInterpolator import android.view.animation.Interpolator import com.mapzen.tangram.* import com.mapzen.tangram.networking.HttpHandler import com.mapzen.tangram.viewholder.GLSurfaceViewHolderFactory import com.mapzen.tangram.viewholder.GLViewHolder import com.mapzen.tangram.viewholder.GLViewHolderFactory import de.westnordost.osmapi.map.data.BoundingBox import de.westnordost.osmapi.map.data.LatLon import de.westnordost.streetcomplete.util.* import java.util.* import java.util.concurrent.ConcurrentLinkedQueue import kotlin.coroutines.Continuation import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine import kotlin.math.log10 import kotlin.math.max import kotlin.math.min import kotlin.math.pow /** Wrapper around the Tangram MapController. Features over the Tangram MapController (0.12.0): * <br><br> * <ul> * <li>Markers survive a scene updates</li> * <li>Simultaneous camera animations are possible with a short and easy interface</li> * <li>A simpler interface to touchInput - easy defaulting to default touch gesture behavior</li> * <li>Uses suspend functions instead of callbacks (Kotlin coroutines)</li> * <li>Use LatLon instead of LngLat</li> * </ul> * */ class KtMapController(private val c: MapController, contentResolver: ContentResolver) { private val cameraManager = CameraManager(c, contentResolver) private val markerManager = MarkerManager(c) private val gestureManager = TouchGestureManager(c) private val defaultInterpolator = AccelerateDecelerateInterpolator() private val sceneUpdateContinuations = mutableMapOf<Int, Continuation<Int>>() private val pickLabelContinuations = ConcurrentLinkedQueue<Continuation<LabelPickResult?>>() private val featurePickContinuations = ConcurrentLinkedQueue<Continuation<FeaturePickResult?>>() private val mainHandler = Handler(Looper.getMainLooper()) private var mapChangingListener: MapChangingListener? = null private val flingAnimator: TimeAnimator = TimeAnimator() init { c.setSceneLoadListener { sceneId, sceneError -> val cont = sceneUpdateContinuations.remove(sceneId) if (sceneError != null) { cont?.resumeWithException(sceneError.toException()) } else { markerManager.recreateMarkers() cont?.resume(sceneId) } } c.setLabelPickListener { labelPickResult: LabelPickResult? -> pickLabelContinuations.poll()?.resume(labelPickResult) } c.setFeaturePickListener { featurePickResult: FeaturePickResult? -> featurePickContinuations.poll()?.resume(featurePickResult) } flingAnimator.setTimeListener { _, _, _ -> mapChangingListener?.onMapIsChanging() } cameraManager.listener = object : CameraManager.AnimationsListener { override fun onAnimationsStarted() { mapChangingListener?.onMapWillChange() } override fun onAnimating() { mapChangingListener?.onMapIsChanging() } override fun onAnimationsEnded() { mapChangingListener?.onMapDidChange() } } c.setMapChangeListener(object : MapChangeListener { private var calledOnMapIsChangingOnce = false override fun onViewComplete() { /* not interested*/ } override fun onRegionWillChange(animated: Boolean) { // may not be called on ui thread, see https://github.com/tangrams/tangram-es/issues/2157 mainHandler.post { calledOnMapIsChangingOnce = false if (!cameraManager.isAnimating) { mapChangingListener?.onMapWillChange() if (animated) flingAnimator.start() } } } override fun onRegionIsChanging() { mainHandler.post { if (!cameraManager.isAnimating) mapChangingListener?.onMapIsChanging() calledOnMapIsChangingOnce = true } } override fun onRegionDidChange(animated: Boolean) { mainHandler.post { if (!cameraManager.isAnimating) { if (!calledOnMapIsChangingOnce) mapChangingListener?.onMapIsChanging() mapChangingListener?.onMapDidChange() if (animated) flingAnimator.end() } } } }) } /* ----------------------------- Loading and Updating Scene --------------------------------- */ suspend fun loadSceneFile( path: String, sceneUpdates: List<SceneUpdate>? = null ): Int = suspendCoroutine { cont -> markerManager.invalidateMarkers() val sceneId = c.loadSceneFileAsync(path, sceneUpdates) sceneUpdateContinuations[sceneId] = cont } suspend fun loadSceneYaml( yaml: String, resourceRoot: String, sceneUpdates: List<SceneUpdate>? = null ): Int = suspendCoroutine { cont -> markerManager.invalidateMarkers() val sceneId = c.loadSceneYamlAsync(yaml, resourceRoot, sceneUpdates) sceneUpdateContinuations[sceneId] = cont } /* ----------------------------------------- Camera ----------------------------------------- */ val cameraPosition: CameraPosition get() = cameraManager.camera fun updateCameraPosition(duration: Long = 0, interpolator: Interpolator = defaultInterpolator, builder: CameraUpdate.() -> Unit) { updateCameraPosition(duration, interpolator, CameraUpdate().apply(builder)) } fun updateCameraPosition(duration: Long = 0, interpolator: Interpolator = defaultInterpolator, update: CameraUpdate) { cameraManager.updateCamera(duration, interpolator, update) } fun setCameraPosition(camera: CameraPosition) { val update = CameraUpdate() update.position = camera.position update.rotation = camera.rotation update.tilt = camera.tilt update.zoom = camera.zoom updateCameraPosition(0L, defaultInterpolator, update) } fun cancelAllCameraAnimations() = cameraManager.cancelAllCameraAnimations() var cameraType: MapController.CameraType set(value) { c.cameraType = value } get() = c.cameraType var minimumZoomLevel: Float set(value) { c.minimumZoomLevel = value } get() = c.minimumZoomLevel var maximumZoomLevel: Float set(value) { c.maximumZoomLevel = value } get() = c.maximumZoomLevel fun screenPositionToLatLon(screenPosition: PointF): LatLon? = c.screenPositionToLngLat(screenPosition)?.toLatLon() fun latLonToScreenPosition(latLon: LatLon): PointF = c.lngLatToScreenPosition(latLon.toLngLat()) fun latLonToScreenPosition(latLon: LatLon, screenPositionOut: PointF, clipToViewport: Boolean) = c.lngLatToScreenPosition(latLon.toLngLat(), screenPositionOut, clipToViewport) fun screenCenterToLatLon(padding: RectF): LatLon? { val view = glViewHolder?.view ?: return null val w = view.width val h = view.height if (w == 0 || h == 0) return null return screenPositionToLatLon(PointF( padding.left + (w - padding.left - padding.right)/2f, padding.top + (h - padding.top - padding.bottom)/2f )) } fun screenAreaToBoundingBox(padding: RectF): BoundingBox? { val view = glViewHolder?.view ?: return null val w = view.width val h = view.height if (w == 0 || h == 0) return null val size = PointF(w - padding.left - padding.right, h - padding.top - padding.bottom) // the special cases here are: map tilt and map rotation: // * map tilt makes the screen area -> world map area into a trapezoid // * map rotation makes the screen area -> world map area into a rotated rectangle // dealing with tilt: this method is just not defined if the tilt is above a certain limit if (cameraPosition.tilt > Math.PI / 4f) return null // 45° val positions = arrayOf( screenPositionToLatLon(PointF(padding.left, padding.top)), screenPositionToLatLon(PointF(padding.left + size.x, padding.top)), screenPositionToLatLon(PointF(padding.left, padding.top + size.y)), screenPositionToLatLon(PointF(padding.left + size.x, padding.top + size.y)) ).filterNotNull() return positions.enclosingBoundingBox() } fun getEnclosingCameraPosition(bounds: BoundingBox, padding: RectF): CameraPosition? { val zoom = getMaxZoomThatContainsBounds(bounds, padding) ?: return null val boundsCenter = listOf(bounds.min, bounds.max).centerPointOfPolyline() val pos = getLatLonThatCentersLatLon(boundsCenter, padding, zoom) ?: return null val camera = cameraPosition return CameraPosition(pos, camera.rotation, camera.tilt, zoom) } private fun getMaxZoomThatContainsBounds(bounds: BoundingBox, padding: RectF): Float? { val screenBounds: BoundingBox val currentZoom: Float synchronized(c) { screenBounds = screenAreaToBoundingBox(padding) ?: return null currentZoom = cameraPosition.zoom } val screenWidth = normalizeLongitude(screenBounds.maxLongitude - screenBounds.minLongitude) val screenHeight = screenBounds.maxLatitude - screenBounds.minLatitude val objectWidth = normalizeLongitude(bounds.maxLongitude - bounds.minLongitude) val objectHeight = bounds.maxLatitude - bounds.minLatitude val zoomDeltaX = log10(screenWidth / objectWidth) / log10(2.0) val zoomDeltaY = log10(screenHeight / objectHeight) / log10(2.0) val zoomDelta = min(zoomDeltaX, zoomDeltaY) return max( 1.0, min(currentZoom + zoomDelta, 21.0)).toFloat() } fun getLatLonThatCentersLatLon(position: LatLon, padding: RectF, zoom: Float = cameraPosition.zoom): LatLon? { val view = glViewHolder?.view ?: return null val w = view.width val h = view.height if (w == 0 || h == 0) return null val screenCenter = screenPositionToLatLon(PointF(w / 2f, h / 2f)) ?: return null val offsetScreenCenter = screenPositionToLatLon( PointF( padding.left + (w - padding.left - padding.right) / 2, padding.top + (h - padding.top - padding.bottom) / 2 ) ) ?: return null val zoomDelta = zoom.toDouble() - cameraPosition.zoom val distance = offsetScreenCenter.distanceTo(screenCenter) val angle = offsetScreenCenter.initialBearingTo(screenCenter) val distanceAfterZoom = distance * (2.0).pow(-zoomDelta) return position.translate(distanceAfterZoom, angle) } /* -------------------------------------- Data Layers --------------------------------------- */ fun addDataLayer(name: String, generateCentroid: Boolean = false): MapData = c.addDataLayer(name, generateCentroid) /* ---------------------------------------- Markers ----------------------------------------- */ fun addMarker(): Marker = markerManager.addMarker() fun removeMarker(marker: Marker): Boolean = removeMarker(marker.markerId) fun removeMarker(markerId: Long): Boolean = markerManager.removeMarker(markerId) fun removeAllMarkers() = markerManager.removeAllMarkers() /* ------------------------------------ Map interaction ------------------------------------- */ fun setPickRadius(radius: Float) = c.setPickRadius(radius) suspend fun pickLabel(posX: Float, posY: Float): LabelPickResult? = suspendCoroutine { cont -> pickLabelContinuations.offer(cont) c.pickLabel(posX, posY) } suspend fun pickMarker(posX: Float, posY: Float): MarkerPickResult? = markerManager.pickMarker(posX, posY) suspend fun pickFeature(posX: Float, posY: Float): FeaturePickResult? = suspendCoroutine { cont -> featurePickContinuations.offer(cont) c.pickFeature(posX, posY) } fun setMapChangingListener(listener: MapChangingListener?) { mapChangingListener = listener } /* -------------------------------------- Touch input --------------------------------------- */ fun setShoveResponder(responder: TouchInput.ShoveResponder?) { gestureManager.setShoveResponder(responder) } fun setScaleResponder(responder: TouchInput.ScaleResponder?) { gestureManager.setScaleResponder(responder) } fun setRotateResponder(responder: TouchInput.RotateResponder?) { gestureManager.setRotateResponder(responder) } fun setPanResponder(responder: TouchInput.PanResponder?) { gestureManager.setPanResponder(responder) } fun setTapResponder(responder: TouchInput.TapResponder?) { c.touchInput.setTapResponder(responder) } fun setDoubleTapResponder(responder: TouchInput.DoubleTapResponder?) { c.touchInput.setDoubleTapResponder(responder) } fun setLongPressResponder(responder: TouchInput.LongPressResponder?) { c.touchInput.setLongPressResponder(responder) } fun isGestureEnabled(g: TouchInput.Gestures): Boolean = c.touchInput.isGestureEnabled(g) fun setGestureEnabled(g: TouchInput.Gestures) { c.touchInput.setGestureEnabled(g) } fun setGestureDisabled(g: TouchInput.Gestures) { c.touchInput.setGestureDisabled(g) } fun setAllGesturesEnabled() { c.touchInput.setAllGesturesEnabled() } fun setAllGesturesDisabled() { c.touchInput.setAllGesturesDisabled() } fun setSimultaneousDetectionEnabled(first: TouchInput.Gestures, second: TouchInput.Gestures) { c.touchInput.setSimultaneousDetectionEnabled(first, second) } fun setSimultaneousDetectionDisabled(first: TouchInput.Gestures, second: TouchInput.Gestures) { c.touchInput.setSimultaneousDetectionDisabled(first, second) } fun isSimultaneousDetectionAllowed(first: TouchInput.Gestures, second: TouchInput.Gestures): Boolean = c.touchInput.isSimultaneousDetectionAllowed(first, second) /* ------------------------------------------ Misc ------------------------------------------ */ suspend fun captureFrame(waitForCompleteView: Boolean): Bitmap = suspendCoroutine { cont -> c.captureFrame({ bitmap -> cont.resume(bitmap) }, waitForCompleteView) } fun requestRender() = c.requestRender() fun setRenderMode(renderMode: Int) = c.setRenderMode(renderMode) fun queueEvent(block: () -> Unit) = c.queueEvent(block) val glViewHolder: GLViewHolder? get() = c.glViewHolder fun setDebugFlag(flag: MapController.DebugFlag, on: Boolean) = c.setDebugFlag(flag, on) fun useCachedGlState(use: Boolean) = c.useCachedGlState(use) fun setDefaultBackgroundColor(red: Float, green: Float, blue: Float) = c.setDefaultBackgroundColor(red, green, blue) } class LoadSceneException(message: String, val sceneUpdate: SceneUpdate) : RuntimeException(message) private fun SceneError.toException() = LoadSceneException(error.name.toLowerCase(Locale.US).replace("_", " "), sceneUpdate) suspend fun MapView.initMap( httpHandler: HttpHandler? = null, glViewHolderFactory: GLViewHolderFactory = GLSurfaceViewHolderFactory()) = suspendCoroutine<KtMapController?> { cont -> getMapAsync(MapView.MapReadyCallback { mapController -> cont.resume(mapController?.let { KtMapController(it, context.contentResolver) }) }, glViewHolderFactory, httpHandler) } interface MapChangingListener { fun onMapWillChange() fun onMapIsChanging() fun onMapDidChange() }
gpl-3.0
6af47ac8d349ef48d1fbd531e5aba798
42.541779
134
0.665717
4.689115
false
false
false
false
seratch/kotliquery
src/main/kotlin/kotliquery/Session.kt
1
11532
package kotliquery import kotliquery.LoanPattern.using import kotliquery.action.* import org.slf4j.LoggerFactory import java.io.Closeable import java.io.InputStream import java.math.BigDecimal import java.net.URL import java.sql.PreparedStatement import java.sql.SQLException import java.sql.Statement import java.time.* /** * Database Session. */ open class Session( open val connection: Connection, open val returnGeneratedKeys: Boolean = true, open val autoGeneratedKeys: List<String> = listOf(), var transactional: Boolean = false, open val strict: Boolean = false, open val queryTimeout: Int? = null ) : Closeable { override fun close() { transactional = false connection.close() } private val logger = LoggerFactory.getLogger(Session::class.java) private inline fun <reified T> PreparedStatement.setTypedParam(idx: Int, param: Parameter<T>) { if (param.value == null) { this.setNull(idx, param.sqlType()) } else { setParam(idx, param.value) } } private fun PreparedStatement.setParam(idx: Int, v: Any?) { if (v == null) { this.setObject(idx, null) } else { when (v) { is String -> this.setString(idx, v) is Byte -> this.setByte(idx, v) is Boolean -> this.setBoolean(idx, v) is Int -> this.setInt(idx, v) is Long -> this.setLong(idx, v) is Short -> this.setShort(idx, v) is Double -> this.setDouble(idx, v) is Float -> this.setFloat(idx, v) is ZonedDateTime -> this.setTimestamp(idx, java.sql.Timestamp.from(v.toInstant())) is OffsetDateTime -> this.setTimestamp(idx, java.sql.Timestamp.from(v.toInstant())) is Instant -> this.setTimestamp(idx, java.sql.Timestamp.from(v)) is LocalDateTime -> this.setTimestamp(idx, java.sql.Timestamp.valueOf(v)) is LocalDate -> this.setDate(idx, java.sql.Date.valueOf(v)) is LocalTime -> this.setTime(idx, java.sql.Time.valueOf(v)) is org.joda.time.DateTime -> this.setTimestamp(idx, java.sql.Timestamp(v.millis)) is org.joda.time.LocalDateTime -> this.setTimestamp(idx, java.sql.Timestamp(v.toDateTime().millis)) is org.joda.time.LocalDate -> this.setDate(idx, java.sql.Date(v.toDateTimeAtStartOfDay().millis)) is org.joda.time.LocalTime -> this.setTime(idx, java.sql.Time(v.toDateTimeToday().millis)) is java.sql.Timestamp -> this.setTimestamp(idx, v) // extends java.util.Date is java.sql.Time -> this.setTime(idx, v) is java.sql.Date -> this.setDate(idx, v) is java.sql.SQLXML -> this.setSQLXML(idx, v) is java.util.Date -> this.setTimestamp(idx, java.sql.Timestamp(v.time)) is ByteArray -> this.setBytes(idx, v) is InputStream -> this.setBinaryStream(idx, v) is BigDecimal -> this.setBigDecimal(idx, v) is java.sql.Array -> this.setArray(idx, v) is URL -> this.setURL(idx, v) // java.util.UUID should be set via setObject else -> this.setObject(idx, v) } } } fun createArrayOf(typeName: String, items: Collection<Any>): java.sql.Array = connection.underlying.createArrayOf(typeName, items.toTypedArray()) fun populateParams(query: Query, stmt: PreparedStatement): PreparedStatement { if (query.replacementMap.isNotEmpty()) { query.replacementMap.forEach { paramName, occurrences -> occurrences.forEach { stmt.setTypedParam(it + 1, query.paramMap[paramName].param()) } } } else { query.params.forEachIndexed { index, value -> stmt.setTypedParam(index + 1, value.param()) } } return stmt } fun createPreparedStatement(query: Query): PreparedStatement { val stmt = if (returnGeneratedKeys) { if (connection.driverName == "oracle.jdbc.driver.OracleDriver") { connection.underlying.prepareStatement(query.cleanStatement, autoGeneratedKeys.toTypedArray()) } else { connection.underlying.prepareStatement(query.cleanStatement, Statement.RETURN_GENERATED_KEYS) } } else { connection.underlying.prepareStatement(query.cleanStatement) } if (queryTimeout != null) { stmt.queryTimeout = queryTimeout!! } return populateParams(query, stmt) } private fun <A> rows(query: Query, extractor: (Row) -> A?): List<A> { return using(createPreparedStatement(query)) { stmt -> using(stmt.executeQuery()) { rs -> val rows = Row(rs).map { row -> extractor.invoke(row) } rows.filter { r -> r != null }.map { r -> r!! }.toList() } } } private fun rowsBatched( statement: String, params: Collection<Collection<Any?>>, namedParams: Collection<Map<String, Any?>> ): List<Int> { return using(connection.underlying.prepareStatement(Query(statement).cleanStatement)) { stmt -> if (queryTimeout != null) { stmt.queryTimeout = queryTimeout!! } batchUpdates(namedParams, statement, stmt, params) stmt.executeBatch().toList() } } private fun rowsBatchedReturningGeneratedKeys( statement: String, params: Collection<Collection<Any?>>, namedParams: Collection<Map<String, Any?>> ): List<Long> { return using( connection.underlying.prepareStatement( Query(statement).cleanStatement, Statement.RETURN_GENERATED_KEYS ) ) { stmt -> batchUpdates(namedParams, statement, stmt, params) if (queryTimeout != null) { stmt.queryTimeout = queryTimeout!! } stmt.executeBatch() val generatedKeysRs = stmt.generatedKeys val keys = mutableListOf<Long>() while (generatedKeysRs.next()) { keys.add(generatedKeysRs.getLong(1)) } if (keys.isEmpty()) { logger.warn("Unexpectedly, Statement#getGeneratedKeys doesn't have any elements for $statement") } keys.toList() } } private fun batchUpdates( namedParams: Collection<Map<String, Any?>>, statement: String, stmt: PreparedStatement, params: Collection<Collection<Any?>> ) { if (namedParams.isNotEmpty()) { val extracted = Query.extractNamedParamsIndexed(statement) namedParams.forEach { paramRow -> extracted.forEach { paramName, occurrences -> occurrences.forEach { stmt.setTypedParam(it + 1, paramRow[paramName].param()) } } stmt.addBatch() } } else { params.forEach { paramsRow -> paramsRow.forEachIndexed { idx, value -> stmt.setTypedParam(idx + 1, value.param()) } stmt.addBatch() } } } private fun warningForTransactionMode() { if (transactional) { logger.warn("Use TransactionalSession instead. The `tx` of `session.transaction { tx -> ... }`") } } fun <A> single(query: Query, extractor: (Row) -> A?): A? { warningForTransactionMode() val rs = rows(query, extractor) return if (strict) { when (rs.size) { 1 -> rs.first() 0 -> null else -> throw SQLException("Expected 1 row but received ${rs.size}.") } } else { if (rs.isNotEmpty()) rs.first() else null } } fun <A> list(query: Query, extractor: (Row) -> A?): List<A> { warningForTransactionMode() return rows(query, extractor).toList() } fun batchPreparedNamedStatement(statement: String, params: Collection<Map<String, Any?>>): List<Int> { warningForTransactionMode() return rowsBatched(statement, emptyList(), params) } fun batchPreparedNamedStatementAndReturnGeneratedKeys( statement: String, params: Collection<Map<String, Any?>> ): List<Long> { warningForTransactionMode() return rowsBatchedReturningGeneratedKeys(statement, emptyList(), params) } fun batchPreparedStatement(statement: String, params: Collection<Collection<Any?>>): List<Int> { warningForTransactionMode() return rowsBatched(statement, params, emptyList()) } fun batchPreparedStatementAndReturnGeneratedKeys( statement: String, params: Collection<Collection<Any?>> ): List<Long> { warningForTransactionMode() return rowsBatchedReturningGeneratedKeys(statement, params, emptyList()) } fun forEach(query: Query, operator: (Row) -> Unit) { warningForTransactionMode() using(createPreparedStatement(query)) { stmt -> using(stmt.executeQuery()) { rs -> Row(rs).forEach { row -> operator.invoke(row) } } } } fun execute(query: Query): Boolean { warningForTransactionMode() return using(createPreparedStatement(query)) { stmt -> stmt.execute() } } fun update(query: Query): Int { warningForTransactionMode() return using(createPreparedStatement(query)) { stmt -> stmt.executeUpdate() } } fun updateAndReturnGeneratedKey(query: Query): Long? { warningForTransactionMode() return using(createPreparedStatement(query)) { stmt -> if (stmt.executeUpdate() > 0) { val rs = stmt.generatedKeys val hasNext = rs.next() if (!hasNext) { logger.warn("Unexpectedly, Statement#getGeneratedKeys doesn't have any elements for " + query.statement) } rs.getLong(1) } else null } } fun run(action: ExecuteQueryAction): Boolean { return action.runWithSession(this) } fun run(action: UpdateQueryAction): Int { return action.runWithSession(this) } fun run(action: UpdateAndReturnGeneratedKeyQueryAction): Long? { return action.runWithSession(this) } fun <A> run(action: ListResultQueryAction<A>): List<A> { return action.runWithSession(this) } fun <A> run(action: NullableResultQueryAction<A>): A? { return action.runWithSession(this) } inline fun <A> transaction(operation: (TransactionalSession) -> A): A { try { connection.begin() transactional = true val tx = TransactionalSession(connection, returnGeneratedKeys, autoGeneratedKeys, strict) val result: A = operation.invoke(tx) connection.commit() return result } catch (e: Exception) { connection.rollback() throw e } finally { transactional = false } } }
mit
5b5e01d03a5463464c2a5fc969b5cb26
34.813665
124
0.57813
4.623897
false
false
false
false
huy-vuong/streamr
app/src/main/java/com/huyvuong/streamr/ui/activity/SettingsActivity.kt
1
1725
package com.huyvuong.streamr.ui.activity import android.app.FragmentTransaction import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.preference.PreferenceFragmentCompat import android.support.v7.preference.PreferenceScreen import android.view.MenuItem import com.huyvuong.streamr.ui.component.SettingsActivityComponent import com.huyvuong.streamr.util.consumeEvent import org.jetbrains.anko.setContentView class SettingsActivity : AppCompatActivity(), PreferenceFragmentCompat.OnPreferenceStartScreenCallback { private val ui = SettingsActivityComponent() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ui.setContentView(this) supportActionBar?.title = "Settings" supportActionBar?.setDisplayHomeAsUpEnabled(true) } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { android.R.id.home -> consumeEvent(this::onBackPressed) else -> super.onOptionsItemSelected(item) } override fun onPreferenceStartScreen( caller: PreferenceFragmentCompat?, pref: PreferenceScreen? ): Boolean { val fragment = SettingsFragment() fragment.arguments = Bundle().apply { putString(PreferenceFragmentCompat.ARG_PREFERENCE_ROOT, pref?.key) } supportFragmentManager.beginTransaction().apply { setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) add(ui.settingsFragment.id, fragment, pref?.key) addToBackStack(pref?.key) commitAllowingStateLoss() } return true } }
gpl-3.0
22f9a8c10cfc13ff9476f202857adac8
34.22449
78
0.711304
5.424528
false
false
false
false
GKZX-HN/MyGithub
app/src/main/java/com/gkzxhn/mygithub/ui/adapter/ActivityAdapter.kt
1
5962
package com.gkzxhn.mygithub.ui.adapter import android.view.View import android.widget.ImageView import android.widget.TextView import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.BaseViewHolder import com.gkzxhn.mygithub.R import com.gkzxhn.mygithub.bean.info.Event import com.gkzxhn.mygithub.extension.load import com.gkzxhn.mygithub.extension.loadRoundConner import com.gkzxhn.mygithub.utils.Utils.getDiffTime import com.gkzxhn.mygithub.utils.Utils.parseDate /** * Created by Xuezhi on 2017/11/19. */ class ActivityAdapter(datas: List<Event>?) : BaseQuickAdapter<Event, BaseViewHolder>(R.layout.item_notifacation, datas) { override fun convert(helper: BaseViewHolder?, item: Event?) { var did: String var creatTiem = parseDate(item!!.created_at, "yyyy-MM-dd'T'HH:mm:ss'Z'") + 8 * 60 * 60 * 1000 /*这里拿到的时间是世界标准时间,所以要加上8*60*60*1000转化成中国东八区的时间*/ var toNow = getDiffTime(creatTiem) when (item!!.type) { "PushEvent" -> { did = " pushed to " helper!!.setText(R.id.tv_new_data_notification, item!!.actor.login + did + item!!.repo.name) helper!!.getView<ImageView>(R.id.iv_state_icon).let { it.load(it.context, R.drawable.push_icon) } helper.getView<TextView>(R.id.tv_detail_data_notification).let { it.visibility = View.GONE } } "WatchEvent" -> { did = " Starred " helper!!.setText(R.id.tv_new_data_notification, item!!.actor.login + did + item!!.repo.name) helper!!.getView<ImageView>(R.id.iv_state_icon).let { it.load(it.context, R.drawable.stared_icon) } helper.getView<TextView>(R.id.tv_detail_data_notification).let { it.visibility = View.GONE } } "MemberEvent" -> { did = " added member to " helper!!.setText(R.id.tv_new_data_notification, item!!.actor.login + did + item!!.repo.name) helper!!.getView<ImageView>(R.id.iv_state_icon).let { it.load(it.context, R.drawable.company) } helper.getView<TextView>(R.id.tv_detail_data_notification).let { it.visibility = View.GONE } } "PullRequestEvent" -> { did = " opened pull request " helper!!.setText(R.id.tv_new_data_notification, item!!.actor.login + did + item!!.repo.name) helper!!.getView<ImageView>(R.id.iv_state_icon).let { it.load(it.context, R.drawable.open_icon) } helper.getView<TextView>(R.id.tv_detail_data_notification).let { it.visibility = View.GONE } } "DeleteEvent" -> { did = " delete branch at " helper!!.setText(R.id.tv_new_data_notification, item!!.actor.login + did + item!!.repo.name) helper!!.getView<ImageView>(R.id.iv_state_icon).let { it.load(it.context, R.drawable.close_icon) } helper.getView<TextView>(R.id.tv_detail_data_notification).let { it.visibility = View.GONE } } /*"IssueCommentEvent" -> { did = " created comment on issue in " helper!!.setText(R.id.tv_new_data_notification, item!!.actor.login + did + item!!.repo.name) helper!!.getView<ImageView>(R.id.iv_state_icon).let { it.load(it.context, R.drawable.public_activity) } helper!!.setText(R.id.tv_detail_data_notification, item!!.payload.comment.body) helper.getView<TextView>(R.id.tv_detail_data_notification).let { it.visibility = View.VISIBLE } } "IssuesEvent" -> { did = " created issus in " helper!!.setText(R.id.tv_new_data_notification, item!!.actor.login + did + item!!.repo.name) helper!!.getView<ImageView>(R.id.iv_state_icon).let { it.load(it.context, R.drawable.public_activity) } helper!!.setText(R.id.tv_detail_data_notification, item!!.payload.issue.title) helper.getView<TextView>(R.id.tv_detail_data_notification).let { it.visibility = View.VISIBLE } }*/ "ForkEvent" -> { did = " forked " helper!!.setText(R.id.tv_new_data_notification, item!!.actor.login + did + item!!.repo.name) helper!!.getView<ImageView>(R.id.iv_state_icon).let { it.load(it.context, R.drawable.open_icon) } helper.getView<TextView>(R.id.tv_detail_data_notification).let { it.visibility = View.GONE } } "PullRequestReviewCommentEvent" -> { did = " pull request review comment in " helper!!.setText(R.id.tv_new_data_notification, item!!.actor.login + did + item!!.repo.name) helper!!.getView<ImageView>(R.id.iv_state_icon).let { it.load(it.context, R.drawable.public_activity) } helper.getView<TextView>(R.id.tv_detail_data_notification).let { it.visibility = View.GONE } } "PublicEvent" -> { helper!!.setText(R.id.tv_new_data_notification, item!!.actor.login + " leted" + item!!.repo.name + " public") helper!!.getView<ImageView>(R.id.iv_state_icon).let { it.load(it.context, R.drawable.public_activity) } helper.getView<TextView>(R.id.tv_detail_data_notification).let { it.visibility = View.GONE } } else -> { helper!!.setText(R.id.tv_new_data_notification, " 请提交log给开发小哥确定Event类型 O(∩_∩)O ") helper.getView<TextView>(R.id.tv_detail_data_notification).let { it.visibility = View.GONE } } } helper!!.setText(R.id.tv_new_date_notification, toNow) helper!!.getView<ImageView>(R.id.iv_avatar) .let { it.loadRoundConner(it.context, item.actor.avatar_url) } } }
gpl-3.0
e5ac2081e951159d6aad103c7a98a0cf
57.73
125
0.60235
3.644941
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/queue/CommandQueueImplementation.kt
1
26653
package info.nightscout.androidaps.queue import android.content.Context import android.content.Intent import android.os.SystemClock import android.text.Spanned import androidx.appcompat.app.AppCompatActivity import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.BolusProgressHelperActivity import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.annotations.OpenForTesting import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.data.ProfileSealed import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.ValueWrapper import info.nightscout.androidaps.database.entities.EffectiveProfileSwitch import info.nightscout.androidaps.database.entities.ProfileSwitch import info.nightscout.androidaps.database.interfaces.end import info.nightscout.androidaps.dialogs.BolusProgressDialog import info.nightscout.androidaps.events.EventMobileToWear import info.nightscout.androidaps.events.EventProfileSwitchChanged import info.nightscout.androidaps.extensions.getCustomizedName import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusProgressIfRunning import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.queue.commands.* import info.nightscout.androidaps.queue.commands.Command.CommandType import info.nightscout.androidaps.utils.AndroidPermission import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.interfaces.BuildHelper import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.weardata.EventData import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import io.reactivex.rxjava3.kotlin.subscribeBy import java.util.* import java.util.concurrent.TimeUnit import javax.inject.Inject import javax.inject.Singleton @OpenForTesting @Singleton class CommandQueueImplementation @Inject constructor( private val injector: HasAndroidInjector, private val aapsLogger: AAPSLogger, private val rxBus: RxBus, private val aapsSchedulers: AapsSchedulers, private val rh: ResourceHelper, private val constraintChecker: ConstraintChecker, private val profileFunction: ProfileFunction, private val activePlugin: ActivePlugin, private val context: Context, private val sp: SP, private val buildHelper: BuildHelper, private val dateUtil: DateUtil, private val repository: AppRepository, private val fabricPrivacy: FabricPrivacy, private val config: Config, private val androidPermission: AndroidPermission ) : CommandQueue { private val disposable = CompositeDisposable() private val queue = LinkedList<Command>() @Volatile private var thread: QueueThread? = null @Volatile var performing: Command? = null init { disposable += rxBus .toObservable(EventProfileSwitchChanged::class.java) .observeOn(aapsSchedulers.io) .throttleLatest(3L, TimeUnit.SECONDS) .subscribe({ if (config.NSCLIENT) { // Effective profileswitch should be synced over NS, do not create EffectiveProfileSwitch here return@subscribe } aapsLogger.debug(LTag.PROFILE, "onEventProfileSwitchChanged") profileFunction.getRequestedProfile()?.let { setProfile(ProfileSealed.PS(it), it.interfaceIDs.nightscoutId != null, object : Callback() { override fun run() { if (!result.success) { ErrorHelperActivity.runAlarm(context, result.comment, rh.gs(R.string.failedupdatebasalprofile), R.raw.boluserror) } else { val nonCustomized = ProfileSealed.PS(it).convertToNonCustomizedProfile(dateUtil) EffectiveProfileSwitch( timestamp = dateUtil.now(), basalBlocks = nonCustomized.basalBlocks, isfBlocks = nonCustomized.isfBlocks, icBlocks = nonCustomized.icBlocks, targetBlocks = nonCustomized.targetBlocks, glucoseUnit = if (it.glucoseUnit == ProfileSwitch.GlucoseUnit.MGDL) EffectiveProfileSwitch.GlucoseUnit.MGDL else EffectiveProfileSwitch.GlucoseUnit.MMOL, originalProfileName = it.profileName, originalCustomizedName = it.getCustomizedName(), originalTimeshift = it.timeshift, originalPercentage = it.percentage, originalDuration = it.duration, originalEnd = it.end, insulinConfiguration = it.insulinConfiguration ).also { eps -> repository.createEffectiveProfileSwitch(eps) aapsLogger.debug(LTag.DATABASE, "Inserted EffectiveProfileSwitch $eps") } } } }) } }, fabricPrivacy::logException) } private fun executingNowError(): PumpEnactResult = PumpEnactResult(injector).success(false).enacted(false).comment(R.string.executingrightnow) override fun isRunning(type: CommandType): Boolean = performing?.commandType == type @Synchronized private fun removeAll(type: CommandType) { synchronized(queue) { for (i in queue.indices.reversed()) { if (queue[i].commandType == type) { queue.removeAt(i) } } } } @Suppress("SameParameterValue") @Synchronized fun isLastScheduled(type: CommandType): Boolean { synchronized(queue) { if (queue.size > 0 && queue[queue.size - 1].commandType == type) { return true } } return false } @Synchronized private fun add(command: Command) { aapsLogger.debug(LTag.PUMPQUEUE, "Adding: " + command.javaClass.simpleName + " - " + command.log()) synchronized(queue) { queue.add(command) } } @Synchronized override fun pickup() { synchronized(queue) { performing = queue.poll() } } @Synchronized override fun clear() { performing = null synchronized(queue) { for (i in queue.indices) { queue[i].cancel() } queue.clear() } } override fun size(): Int = queue.size override fun performing(): Command? = performing override fun resetPerforming() { performing = null } // After new command added to the queue // start thread again if not already running @Synchronized fun notifyAboutNewCommand() { waitForFinishedThread() if (thread == null || thread!!.state == Thread.State.TERMINATED) { thread = QueueThread(this, context, aapsLogger, rxBus, activePlugin, rh, sp, androidPermission, config) thread!!.start() aapsLogger.debug(LTag.PUMPQUEUE, "Starting new thread") } else { aapsLogger.debug(LTag.PUMPQUEUE, "Thread is already running") } } fun waitForFinishedThread() { thread?.let { thread -> while (thread.state != Thread.State.TERMINATED && thread.waitingForDisconnect) { aapsLogger.debug(LTag.PUMPQUEUE, "Waiting for previous thread finish") SystemClock.sleep(500) } } } override fun independentConnect(reason: String, callback: Callback?) { aapsLogger.debug(LTag.PUMPQUEUE, "Starting new queue") val tempCommandQueue = CommandQueueImplementation( injector, aapsLogger, rxBus, aapsSchedulers, rh, constraintChecker, profileFunction, activePlugin, context, sp, buildHelper, dateUtil, repository, fabricPrivacy, config, androidPermission ) tempCommandQueue.readStatus(reason, callback) tempCommandQueue.disposable.clear() } @Synchronized override fun bolusInQueue(): Boolean { if (isRunning(CommandType.BOLUS)) return true if (isRunning(CommandType.SMB_BOLUS)) return true synchronized(queue) { for (i in queue.indices) { if (queue[i].commandType == CommandType.BOLUS) return true if (queue[i].commandType == CommandType.SMB_BOLUS) return true } } return false } // returns true if command is queued @Synchronized override fun bolus(detailedBolusInfo: DetailedBolusInfo, callback: Callback?): Boolean { // Check if pump store carbs // If not, it's not necessary add command to the queue and initiate connection // Assuming carbs in the future and carbs with duration are NOT stores anyway var carbsRunnable = Runnable { } val originalCarbs = detailedBolusInfo.carbs if ((detailedBolusInfo.carbs > 0) && (!activePlugin.activePump.pumpDescription.storesCarbInfo || detailedBolusInfo.carbsDuration != 0L || (detailedBolusInfo.carbsTimestamp ?: detailedBolusInfo.timestamp) > dateUtil.now()) ) { carbsRunnable = Runnable { aapsLogger.debug(LTag.PUMPQUEUE, "Going to store carbs") detailedBolusInfo.carbs = originalCarbs disposable += repository.runTransactionForResult(detailedBolusInfo.insertCarbsTransaction()) .subscribeBy( onSuccess = { result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted carbs $it") } callback?.result(PumpEnactResult(injector).enacted(false).success(true))?.run() }, onError = { aapsLogger.error(LTag.DATABASE, "Error while saving carbs", it) callback?.result(PumpEnactResult(injector).enacted(false).success(false))?.run() } ) } // Do not process carbs anymore detailedBolusInfo.carbs = 0.0 // if no insulin just exit if (detailedBolusInfo.insulin == 0.0) { carbsRunnable.run() // store carbs return true } } var type = if (detailedBolusInfo.bolusType == DetailedBolusInfo.BolusType.SMB) CommandType.SMB_BOLUS else CommandType.BOLUS if (type == CommandType.SMB_BOLUS) { if (bolusInQueue()) { aapsLogger.debug(LTag.PUMPQUEUE, "Rejecting SMB since a bolus is queue/running") callback?.result(PumpEnactResult(injector).enacted(false).success(false))?.run() return false } val lastBolusTime = repository.getLastBolusRecord()?.timestamp ?: 0L if (detailedBolusInfo.lastKnownBolusTime < lastBolusTime) { aapsLogger.debug(LTag.PUMPQUEUE, "Rejecting bolus, another bolus was issued since request time") callback?.result(PumpEnactResult(injector).enacted(false).success(false))?.run() return false } removeAll(CommandType.SMB_BOLUS) } if (type == CommandType.BOLUS && detailedBolusInfo.carbs > 0 && detailedBolusInfo.insulin == 0.0) { type = CommandType.CARBS_ONLY_TREATMENT //Carbs only can be added in parallel as they can be "in the future". } else { if (isRunning(type)) { callback?.result(executingNowError())?.run() return false } // remove all unfinished boluses removeAll(type) } // apply constraints detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(Constraint(detailedBolusInfo.insulin)).value() detailedBolusInfo.carbs = constraintChecker.applyCarbsConstraints(Constraint(detailedBolusInfo.carbs.toInt())).value().toDouble() // add new command to queue if (detailedBolusInfo.bolusType == DetailedBolusInfo.BolusType.SMB) { add(CommandSMBBolus(injector, detailedBolusInfo, callback)) } else { add(CommandBolus(injector, detailedBolusInfo, callback, type, carbsRunnable)) if (type == CommandType.BOLUS) { // Bring up bolus progress dialog (start here, so the dialog is shown when the bolus is requested, // not when the Bolus command is starting. The command closes the dialog upon completion). showBolusProgressDialog(detailedBolusInfo) // Notify Wear about upcoming bolus rxBus.send(EventMobileToWear(EventData.BolusProgress(percent = 0, status = rh.gs(R.string.bolusrequested, detailedBolusInfo.insulin)))) } } notifyAboutNewCommand() return true } override fun stopPump(callback: Callback?) { add(CommandStopPump(injector, callback)) notifyAboutNewCommand() } override fun startPump(callback: Callback?) { add(CommandStartPump(injector, callback)) notifyAboutNewCommand() } override fun setTBROverNotification(callback: Callback?, enable: Boolean) { add(CommandInsightSetTBROverNotification(injector, enable, callback)) notifyAboutNewCommand() } @Synchronized override fun cancelAllBoluses(id: Long) { if (!isRunning(CommandType.BOLUS)) { rxBus.send(EventDismissBolusProgressIfRunning(PumpEnactResult(injector).success(true).enacted(false), id)) } removeAll(CommandType.BOLUS) removeAll(CommandType.SMB_BOLUS) Thread { activePlugin.activePump.stopBolusDelivering() }.start() } // returns true if command is queued override fun tempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, enforceNew: Boolean, profile: Profile, tbrType: PumpSync.TemporaryBasalType, callback: Callback?): Boolean { if (!enforceNew && isRunning(CommandType.TEMPBASAL)) { callback?.result(executingNowError())?.run() return false } // remove all unfinished removeAll(CommandType.TEMPBASAL) val rateAfterConstraints = constraintChecker.applyBasalConstraints(Constraint(absoluteRate), profile).value() // add new command to queue add(CommandTempBasalAbsolute(injector, rateAfterConstraints, durationInMinutes, enforceNew, profile, tbrType, callback)) notifyAboutNewCommand() return true } // returns true if command is queued override fun tempBasalPercent(percent: Int, durationInMinutes: Int, enforceNew: Boolean, profile: Profile, tbrType: PumpSync.TemporaryBasalType, callback: Callback?): Boolean { if (!enforceNew && isRunning(CommandType.TEMPBASAL)) { callback?.result(executingNowError())?.run() return false } // remove all unfinished removeAll(CommandType.TEMPBASAL) val percentAfterConstraints = constraintChecker.applyBasalPercentConstraints(Constraint(percent), profile).value() // add new command to queue add(CommandTempBasalPercent(injector, percentAfterConstraints, durationInMinutes, enforceNew, profile, tbrType, callback)) notifyAboutNewCommand() return true } // returns true if command is queued override fun extendedBolus(insulin: Double, durationInMinutes: Int, callback: Callback?): Boolean { if (isRunning(CommandType.EXTENDEDBOLUS)) { callback?.result(executingNowError())?.run() return false } val rateAfterConstraints = constraintChecker.applyExtendedBolusConstraints(Constraint(insulin)).value() // remove all unfinished removeAll(CommandType.EXTENDEDBOLUS) // add new command to queue add(CommandExtendedBolus(injector, rateAfterConstraints, durationInMinutes, callback)) notifyAboutNewCommand() return true } // returns true if command is queued override fun cancelTempBasal(enforceNew: Boolean, callback: Callback?): Boolean { if (!enforceNew && isRunning(CommandType.TEMPBASAL)) { callback?.result(executingNowError())?.run() return false } // remove all unfinished removeAll(CommandType.TEMPBASAL) // add new command to queue add(CommandCancelTempBasal(injector, enforceNew, callback)) notifyAboutNewCommand() return true } // returns true if command is queued override fun cancelExtended(callback: Callback?): Boolean { if (isRunning(CommandType.EXTENDEDBOLUS)) { callback?.result(executingNowError())?.run() return false } // remove all unfinished removeAll(CommandType.EXTENDEDBOLUS) // add new command to queue add(CommandCancelExtendedBolus(injector, callback)) notifyAboutNewCommand() return true } // returns true if command is queued override fun setProfile(profile: Profile, hasNsId: Boolean, callback: Callback?): Boolean { if (isRunning(CommandType.BASAL_PROFILE)) { aapsLogger.debug(LTag.PUMPQUEUE, "Command is already executed") callback?.result(PumpEnactResult(injector).success(true).enacted(false))?.run() return false } if (isThisProfileSet(profile) && repository.getEffectiveProfileSwitchActiveAt(dateUtil.now()).blockingGet() is ValueWrapper.Existing) { aapsLogger.debug(LTag.PUMPQUEUE, "Correct profile already set") callback?.result(PumpEnactResult(injector).success(true).enacted(false))?.run() return false } // Compare with pump limits val basalValues = profile.getBasalValues() for (basalValue in basalValues) { if (basalValue.value < activePlugin.activePump.pumpDescription.basalMinimumRate) { val notification = Notification(Notification.BASAL_VALUE_BELOW_MINIMUM, rh.gs(R.string.basalvaluebelowminimum), Notification.URGENT) rxBus.send(EventNewNotification(notification)) callback?.result(PumpEnactResult(injector).success(false).enacted(false).comment(R.string.basalvaluebelowminimum))?.run() return false } } rxBus.send(EventDismissNotification(Notification.BASAL_VALUE_BELOW_MINIMUM)) // remove all unfinished removeAll(CommandType.BASAL_PROFILE) // add new command to queue add(CommandSetProfile(injector, profile, hasNsId, callback)) notifyAboutNewCommand() return true } // returns true if command is queued override fun readStatus(reason: String, callback: Callback?): Boolean { if (isLastScheduled(CommandType.READSTATUS)) { aapsLogger.debug(LTag.PUMPQUEUE, "READSTATUS $reason ignored as duplicated") callback?.result(executingNowError())?.run() return false } // add new command to queue add(CommandReadStatus(injector, reason, callback)) notifyAboutNewCommand() return true } @Synchronized override fun statusInQueue(): Boolean { if (isRunning(CommandType.READSTATUS)) return true synchronized(queue) { for (i in queue.indices) { if (queue[i].commandType == CommandType.READSTATUS) { return true } } } return false } // returns true if command is queued override fun loadHistory(type: Byte, callback: Callback?): Boolean { if (isRunning(CommandType.LOAD_HISTORY)) { callback?.result(executingNowError())?.run() return false } // remove all unfinished removeAll(CommandType.LOAD_HISTORY) // add new command to queue add(CommandLoadHistory(injector, type, callback)) notifyAboutNewCommand() return true } // returns true if command is queued override fun setUserOptions(callback: Callback?): Boolean { if (isRunning(CommandType.SET_USER_SETTINGS)) { callback?.result(executingNowError())?.run() return false } // remove all unfinished removeAll(CommandType.SET_USER_SETTINGS) // add new command to queue add(CommandSetUserSettings(injector, callback)) notifyAboutNewCommand() return true } // returns true if command is queued override fun loadTDDs(callback: Callback?): Boolean { if (isRunning(CommandType.LOAD_TDD)) { callback?.result(executingNowError())?.run() return false } // remove all unfinished removeAll(CommandType.LOAD_TDD) // add new command to queue add(CommandLoadTDDs(injector, callback)) notifyAboutNewCommand() return true } // returns true if command is queued override fun loadEvents(callback: Callback?): Boolean { if (isRunning(CommandType.LOAD_EVENTS)) { callback?.result(executingNowError())?.run() return false } // remove all unfinished removeAll(CommandType.LOAD_EVENTS) // add new command to queue add(CommandLoadEvents(injector, callback)) notifyAboutNewCommand() return true } override fun customCommand(customCommand: CustomCommand, callback: Callback?): Boolean { if (isCustomCommandInQueue(customCommand.javaClass)) { callback?.result(executingNowError())?.run() return false } // remove all unfinished removeAllCustomCommands(customCommand.javaClass) // add new command to queue add(CommandCustomCommand(injector, customCommand, callback)) notifyAboutNewCommand() return true } @Synchronized override fun isCustomCommandInQueue(customCommandType: Class<out CustomCommand>): Boolean { if (isCustomCommandRunning(customCommandType)) { return true } synchronized(queue) { for (i in queue.indices) { val command = queue[i] if (command is CommandCustomCommand && customCommandType.isInstance(command.customCommand)) { return true } } } return false } override fun isCustomCommandRunning(customCommandType: Class<out CustomCommand>): Boolean { val performing = this.performing if (performing is CommandCustomCommand && customCommandType.isInstance(performing.customCommand)) { return true } return false } @Synchronized private fun removeAllCustomCommands(targetType: Class<out CustomCommand>) { synchronized(queue) { for (i in queue.indices.reversed()) { val command = queue[i] if (command is CustomCommand && targetType.isInstance(command.commandType)) { queue.removeAt(i) } } } } override fun spannedStatus(): Spanned { var s = "" var line = 0 val perf = performing if (perf != null) { s += "<b>" + perf.status() + "</b>" line++ } synchronized(queue) { for (i in queue.indices) { if (line != 0) s += "<br>" s += queue[i].status() line++ } } return HtmlHelper.fromHtml(s) } override fun isThisProfileSet(requestedProfile: Profile): Boolean { val runningProfile = profileFunction.getProfile() ?: return false val result = activePlugin.activePump.isThisProfileSet(requestedProfile) && requestedProfile.isEqual(runningProfile) if (!result) { aapsLogger.debug(LTag.PUMPQUEUE, "Current profile: ${profileFunction.getProfile()}") aapsLogger.debug(LTag.PUMPQUEUE, "New profile: $requestedProfile") } return result } private fun showBolusProgressDialog(detailedBolusInfo: DetailedBolusInfo) { if (detailedBolusInfo.context != null) { val bolusProgressDialog = BolusProgressDialog() bolusProgressDialog.setInsulin(detailedBolusInfo.insulin) bolusProgressDialog.setId(detailedBolusInfo.id) bolusProgressDialog.show((detailedBolusInfo.context as AppCompatActivity).supportFragmentManager, "BolusProgress") } else { val i = Intent() i.putExtra("insulin", detailedBolusInfo.insulin) i.putExtra("id", detailedBolusInfo.id) i.setClass(context, BolusProgressHelperActivity::class.java) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(i) } } }
agpl-3.0
c8a45e513af08d82f6451c876c71a322
42.410423
200
0.632612
5.3306
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt
1
22688
package info.nightscout.androidaps.activities import android.annotation.SuppressLint import android.content.Context import android.content.SharedPreferences import android.content.SharedPreferences.OnSharedPreferenceChangeListener import android.os.Bundle import androidx.annotation.XmlRes import androidx.preference.* import dagger.android.support.AndroidSupportInjection import info.nightscout.androidaps.R import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin import info.nightscout.androidaps.danaRv2.DanaRv2Plugin import info.nightscout.androidaps.danar.DanaRPlugin import info.nightscout.androidaps.danars.DanaRSPlugin import info.nightscout.androidaps.diaconn.DiaconnG8Plugin import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.events.EventRebuildTabs import info.nightscout.androidaps.interfaces.Config import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugin.general.openhumans.OpenHumansUploader import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.configBuilder.PluginStore import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin import info.nightscout.androidaps.plugins.general.autotune.AutotunePlugin import info.nightscout.androidaps.plugins.general.maintenance.MaintenancePlugin import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin import info.nightscout.androidaps.plugins.general.tidepool.TidepoolPlugin import info.nightscout.androidaps.plugins.general.wear.WearPlugin import info.nightscout.androidaps.plugins.general.xdripStatusline.StatusLinePlugin import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin import info.nightscout.androidaps.plugins.source.* import info.nightscout.androidaps.utils.alertDialogs.OKDialog.show import info.nightscout.androidaps.utils.protection.PasswordCheck import info.nightscout.androidaps.utils.protection.ProtectionCheck.ProtectionType.* import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.plugins.aps.openAPSSMBDynamicISF.OpenAPSSMBDynamicISFPlugin import info.nightscout.shared.SafeParse import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChangeListener { private var pluginId = -1 private var filter = "" @Inject lateinit var rxBus: RxBus @Inject lateinit var rh: ResourceHelper @Inject lateinit var sp: SP @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var pluginStore: PluginStore @Inject lateinit var config: Config @Inject lateinit var automationPlugin: AutomationPlugin @Inject lateinit var autotunePlugin: AutotunePlugin @Inject lateinit var danaRPlugin: DanaRPlugin @Inject lateinit var danaRKoreanPlugin: DanaRKoreanPlugin @Inject lateinit var danaRv2Plugin: DanaRv2Plugin @Inject lateinit var danaRSPlugin: DanaRSPlugin @Inject lateinit var comboPlugin: ComboPlugin @Inject lateinit var insulinOrefFreePeakPlugin: InsulinOrefFreePeakPlugin @Inject lateinit var loopPlugin: LoopPlugin @Inject lateinit var localInsightPlugin: LocalInsightPlugin @Inject lateinit var medtronicPumpPlugin: MedtronicPumpPlugin @Inject lateinit var nsClientPlugin: NSClientPlugin @Inject lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin @Inject lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin @Inject lateinit var openAPSSMBDynamicISFPlugin: OpenAPSSMBDynamicISFPlugin @Inject lateinit var safetyPlugin: SafetyPlugin @Inject lateinit var sensitivityAAPSPlugin: SensitivityAAPSPlugin @Inject lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin @Inject lateinit var sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin @Inject lateinit var dexcomPlugin: DexcomPlugin @Inject lateinit var eversensePlugin: EversensePlugin @Inject lateinit var glimpPlugin: GlimpPlugin @Inject lateinit var poctechPlugin: PoctechPlugin @Inject lateinit var tomatoPlugin: TomatoPlugin @Inject lateinit var glunovoPlugin: GlunovoPlugin @Inject lateinit var aidexPlugin: AidexPlugin @Inject lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin @Inject lateinit var statusLinePlugin: StatusLinePlugin @Inject lateinit var tidepoolPlugin: TidepoolPlugin @Inject lateinit var virtualPumpPlugin: VirtualPumpPlugin @Inject lateinit var wearPlugin: WearPlugin @Inject lateinit var maintenancePlugin: MaintenancePlugin @Inject lateinit var passwordCheck: PasswordCheck @Inject lateinit var nsSettingStatus: NSSettingsStatus @Inject lateinit var openHumansUploader: OpenHumansUploader @Inject lateinit var diaconnG8Plugin: DiaconnG8Plugin override fun onAttach(context: Context) { AndroidSupportInjection.inject(this) super.onAttach(context) } override fun setArguments(args: Bundle?) { super.setArguments(args) pluginId = args?.getInt("id") ?: -1 filter = args?.getString("filter") ?: "" } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putInt("id", pluginId) outState.putString("filter", filter) } override fun onDestroy() { super.onDestroy() context?.let { context -> PreferenceManager .getDefaultSharedPreferences(context) .unregisterOnSharedPreferenceChangeListener(this) } } private fun addPreferencesFromResourceIfEnabled(p: PluginBase?, rootKey: String?, enabled: Boolean) { if (enabled) addPreferencesFromResourceIfEnabled(p, rootKey) } private fun addPreferencesFromResourceIfEnabled(p: PluginBase?, rootKey: String?) { if (p!!.isEnabled() && p.preferencesId != -1) addPreferencesFromResource(p.preferencesId, rootKey) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) context?.let { context -> PreferenceManager .getDefaultSharedPreferences(context) .registerOnSharedPreferenceChangeListener(this) } } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { (savedInstanceState ?: arguments)?.let { bundle -> if (bundle.containsKey("id")) { pluginId = bundle.getInt("id") } if (bundle.containsKey("filter")) { filter = bundle.getString("filter") ?: "" } } if (pluginId != -1) { addPreferencesFromResource(pluginId, rootKey) } else { addPreferencesFromResource(R.xml.pref_general, rootKey) addPreferencesFromResource(R.xml.pref_overview, rootKey) addPreferencesFromResourceIfEnabled(safetyPlugin, rootKey) addPreferencesFromResourceIfEnabled(eversensePlugin, rootKey) addPreferencesFromResourceIfEnabled(dexcomPlugin, rootKey) addPreferencesFromResourceIfEnabled(tomatoPlugin, rootKey) addPreferencesFromResourceIfEnabled(glunovoPlugin, rootKey) addPreferencesFromResourceIfEnabled(poctechPlugin, rootKey) addPreferencesFromResourceIfEnabled(aidexPlugin, rootKey) addPreferencesFromResourceIfEnabled(glimpPlugin, rootKey) addPreferencesFromResourceIfEnabled(loopPlugin, rootKey, config.APS) addPreferencesFromResourceIfEnabled(openAPSAMAPlugin, rootKey, config.APS) addPreferencesFromResourceIfEnabled(openAPSSMBPlugin, rootKey, config.APS) addPreferencesFromResourceIfEnabled(openAPSSMBDynamicISFPlugin, rootKey, config.APS) addPreferencesFromResourceIfEnabled(sensitivityAAPSPlugin, rootKey) addPreferencesFromResourceIfEnabled(sensitivityWeightedAveragePlugin, rootKey) addPreferencesFromResourceIfEnabled(sensitivityOref1Plugin, rootKey) addPreferencesFromResourceIfEnabled(danaRPlugin, rootKey, config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(danaRKoreanPlugin, rootKey, config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(danaRv2Plugin, rootKey, config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(danaRSPlugin, rootKey, config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(localInsightPlugin, rootKey, config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(comboPlugin, rootKey, config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(medtronicPumpPlugin, rootKey, config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(diaconnG8Plugin, rootKey, config.PUMPDRIVERS) addPreferencesFromResource(R.xml.pref_pump, rootKey, config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(virtualPumpPlugin, rootKey) addPreferencesFromResourceIfEnabled(insulinOrefFreePeakPlugin, rootKey) addPreferencesFromResourceIfEnabled(nsClientPlugin, rootKey) addPreferencesFromResourceIfEnabled(tidepoolPlugin, rootKey) addPreferencesFromResourceIfEnabled(smsCommunicatorPlugin, rootKey) addPreferencesFromResourceIfEnabled(automationPlugin, rootKey) addPreferencesFromResourceIfEnabled(autotunePlugin, rootKey) addPreferencesFromResourceIfEnabled(wearPlugin, rootKey) addPreferencesFromResourceIfEnabled(statusLinePlugin, rootKey) addPreferencesFromResource(R.xml.pref_alerts, rootKey) addPreferencesFromResource(R.xml.pref_datachoices, rootKey) addPreferencesFromResourceIfEnabled(maintenancePlugin, rootKey) addPreferencesFromResourceIfEnabled(openHumansUploader, rootKey) } initSummary(preferenceScreen, pluginId != -1) preprocessPreferences() if (filter != "") updateFilterVisibility(filter, preferenceScreen) } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { rxBus.send(EventPreferenceChange(key)) if (key == rh.gs(R.string.key_language)) { rxBus.send(EventRebuildTabs(true)) //recreate() does not update language so better close settings activity?.finish() } if (key == rh.gs(R.string.key_short_tabtitles)) { rxBus.send(EventRebuildTabs()) } if (key == rh.gs(R.string.key_units)) { activity?.recreate() return } if (key == rh.gs(R.string.key_openapsama_useautosens) && sp.getBoolean(R.string.key_openapsama_useautosens, false)) { activity?.let { show(it, rh.gs(R.string.configbuilder_sensitivity), rh.gs(R.string.sensitivity_warning)) } } checkForBiometricFallback(key) updatePrefSummary(findPreference(key)) preprocessPreferences() } private fun preprocessPreferences() { for (plugin in pluginStore.plugins) { plugin.preprocessPreferences(this) } } private fun checkForBiometricFallback(key: String) { // Biometric protection activated without set master password if ((rh.gs(R.string.key_settings_protection) == key || rh.gs(R.string.key_application_protection) == key || rh.gs(R.string.key_bolus_protection) == key) && sp.getString(R.string.key_master_password, "") == "" && sp.getInt(key, NONE.ordinal) == BIOMETRIC.ordinal ) { activity?.let { val title = rh.gs(R.string.unsecure_fallback_biometric) val message = rh.gs(R.string.master_password_missing, rh.gs(R.string.configbuilder_general), rh.gs(R.string.protection)) show(it, title = title, message = message) } } // Master password erased with activated Biometric protection val isBiometricActivated = sp.getInt(R.string.key_settings_protection, NONE.ordinal) == BIOMETRIC.ordinal || sp.getInt(R.string.key_application_protection, NONE.ordinal) == BIOMETRIC.ordinal || sp.getInt(R.string.key_bolus_protection, NONE.ordinal) == BIOMETRIC.ordinal if (rh.gs(R.string.key_master_password) == key && sp.getString(key, "") == "" && isBiometricActivated) { activity?.let { val title = rh.gs(R.string.unsecure_fallback_biometric) val message = rh.gs(R.string.unsecure_fallback_descriotion_biometric) show(it, title = title, message = message) } } } private fun addPreferencesFromResource(@Suppress("SameParameterValue") @XmlRes preferencesResId: Int, key: String?, enabled: Boolean) { if (enabled) addPreferencesFromResource(preferencesResId, key) } @SuppressLint("RestrictedApi") private fun addPreferencesFromResource(@XmlRes preferencesResId: Int, key: String?) { context?.let { context -> val xmlRoot = preferenceManager.inflateFromResource(context, preferencesResId, null) val root: Preference? if (key != null) { root = xmlRoot.findPreference(key) if (root == null) return require(root is PreferenceScreen) { ("Preference object with key $key is not a PreferenceScreen") } preferenceScreen = root } else { addPreferencesFromResource(preferencesResId) } } } private fun adjustUnitDependentPrefs(pref: Preference) { // convert preferences values to current units val unitDependent = arrayOf( rh.gs(R.string.key_hypo_target), rh.gs(R.string.key_activity_target), rh.gs(R.string.key_eatingsoon_target), rh.gs(R.string.key_high_mark), rh.gs(R.string.key_low_mark) ) if (unitDependent.toList().contains(pref.key) && pref is EditTextPreference) { val converted = Profile.toCurrentUnits(profileFunction, SafeParse.stringToDouble(pref.text)) pref.summary = converted.toString() } } private fun updateFilterVisibility(filter: String, p: Preference): Boolean { var visible = false if (p is PreferenceGroup) { for (i in 0 until p.preferenceCount) { visible = updateFilterVisibility(filter, p.getPreference(i)) || visible } if (visible && p is PreferenceCategory) { p.initialExpandedChildrenCount = Int.MAX_VALUE } } else { visible = visible || p.key?.contains(filter, true) == true visible = visible || p.title?.contains(filter, true) == true visible = visible || p.summary?.contains(filter, true) == true } p.isVisible = visible return visible } private fun updatePrefSummary(pref: Preference?) { if (pref is ListPreference) { pref.setSummary(pref.entry) // Preferences if (pref.getKey() == rh.gs(R.string.key_settings_protection)) { val pass: Preference? = findPreference(rh.gs(R.string.key_settings_password)) val usePassword = pref.value == CUSTOM_PASSWORD.ordinal.toString() pass?.let { it.isVisible = usePassword } val pin: Preference? = findPreference(rh.gs(R.string.key_settings_pin)) val usePin = pref.value == CUSTOM_PIN.ordinal.toString() pin?.let { it.isVisible = usePin } } // Application if (pref.getKey() == rh.gs(R.string.key_application_protection)) { val pass: Preference? = findPreference(rh.gs(R.string.key_application_password)) val usePassword = pref.value == CUSTOM_PASSWORD.ordinal.toString() pass?.let { it.isVisible = usePassword } val pin: Preference? = findPreference(rh.gs(R.string.key_application_pin)) val usePin = pref.value == CUSTOM_PIN.ordinal.toString() pin?.let { it.isVisible = usePin } } // Bolus if (pref.getKey() == rh.gs(R.string.key_bolus_protection)) { val pass: Preference? = findPreference(rh.gs(R.string.key_bolus_password)) val usePassword = pref.value == CUSTOM_PASSWORD.ordinal.toString() pass?.let { it.isVisible = usePassword } val pin: Preference? = findPreference(rh.gs(R.string.key_bolus_pin)) val usePin = pref.value == CUSTOM_PIN.ordinal.toString() pin?.let { it.isVisible = usePin } } } if (pref is EditTextPreference) { if (pref.getKey().contains("password") || pref.getKey().contains("pin") || pref.getKey().contains("secret") || pref.getKey().contains("token")) { pref.setSummary("******") } else if (pref.text != null) { pref.dialogMessage = pref.dialogMessage pref.setSummary(pref.text) } } for (plugin in pluginStore.plugins) { pref?.let { it.key?.let { plugin.updatePreferenceSummary(pref) } } } val hmacPasswords = arrayOf( rh.gs(R.string.key_bolus_password), rh.gs(R.string.key_master_password), rh.gs(R.string.key_application_password), rh.gs(R.string.key_settings_password), rh.gs(R.string.key_bolus_pin), rh.gs(R.string.key_application_pin), rh.gs(R.string.key_settings_pin) ) if (pref is Preference) { if ((pref.key != null) && (hmacPasswords.contains(pref.key))) { if (sp.getString(pref.key, "").startsWith("hmac:")) { pref.summary = "******" } else { if (pref.key.contains("pin")) { pref.summary = rh.gs(R.string.pin_not_set) }else { pref.summary = rh.gs(R.string.password_not_set) } } } } pref?.let { adjustUnitDependentPrefs(it) } } private fun initSummary(p: Preference, isSinglePreference: Boolean) { p.isIconSpaceReserved = false // remove extra spacing on left after migration to androidx // expand single plugin preference by default if (p is PreferenceScreen && isSinglePreference) { if (p.size > 0 && p.getPreference(0) is PreferenceCategory) (p.getPreference(0) as PreferenceCategory).initialExpandedChildrenCount = Int.MAX_VALUE } if (p is PreferenceGroup) { for (i in 0 until p.preferenceCount) { initSummary(p.getPreference(i), isSinglePreference) } } else { updatePrefSummary(p) } } // We use Preference and custom editor instead of EditTextPreference // to hash password while it is saved and never have to show it, even hashed override fun onPreferenceTreeClick(preference: Preference): Boolean { context?.let { context -> if (preference.key == rh.gs(R.string.key_master_password)) { passwordCheck.queryPassword(context, R.string.current_master_password, R.string.key_master_password, { passwordCheck.setPassword(context, R.string.master_password, R.string.key_master_password) }) return true } if (preference.key == rh.gs(R.string.key_settings_password)) { passwordCheck.setPassword(context, R.string.settings_password, R.string.key_settings_password) return true } if (preference.key == rh.gs(R.string.key_bolus_password)) { passwordCheck.setPassword(context, R.string.bolus_password, R.string.key_bolus_password) return true } if (preference.key == rh.gs(R.string.key_application_password)) { passwordCheck.setPassword(context, R.string.application_password, R.string.key_application_password) return true } if (preference.key == rh.gs(R.string.key_settings_pin)) { passwordCheck.setPassword(context, R.string.settings_pin, R.string.key_settings_pin, pinInput = true) return true } if (preference.key == rh.gs(R.string.key_bolus_pin)) { passwordCheck.setPassword(context, R.string.bolus_pin, R.string.key_bolus_pin, pinInput = true) return true } if (preference.key == rh.gs(R.string.key_application_pin)) { passwordCheck.setPassword(context, R.string.application_pin, R.string.key_application_pin, pinInput = true) return true } // NSClient copy settings if (preference.key == rh.gs(R.string.key_statuslights_copy_ns)) { nsSettingStatus.copyStatusLightsNsSettings(context) return true } } return super.onPreferenceTreeClick(preference) } fun setFilter(filter: String) { this.filter = filter preferenceManager?.preferenceScreen?.let { updateFilterVisibility(filter, it) } } }
agpl-3.0
1f62faa1901d77eb9e9029cd06a9ebd2
48.537118
157
0.67939
4.782462
false
false
false
false
Unpublished/AmazeFileManager
app/src/main/java/com/amaze/filemanager/adapters/holders/ItemViewHolder.kt
2
2718
/* * Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager 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.amaze.filemanager.adapters.holders import android.view.View import android.widget.ImageButton import android.widget.ImageView import android.widget.RelativeLayout import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.amaze.filemanager.R import com.amaze.filemanager.ui.views.ThemedTextView /** * Check RecyclerAdapter's doc. TODO load everything related to this item here instead of in * RecyclerAdapter. */ class ItemViewHolder(view: View) : RecyclerView.ViewHolder(view) { // each data item is just a string in this case @JvmField val pictureIcon: ImageView? = view.findViewById(R.id.picture_icon) @JvmField val genericIcon: ImageView = view.findViewById(R.id.generic_icon) @JvmField val apkIcon: ImageView? = view.findViewById(R.id.apk_icon) @JvmField val imageView1: ImageView? = view.findViewById(R.id.icon_thumb) @JvmField val txtTitle: ThemedTextView = view.findViewById(R.id.firstline) @JvmField val txtDesc: TextView = view.findViewById(R.id.secondLine) @JvmField val date: TextView = view.findViewById(R.id.date) @JvmField val perm: TextView = view.findViewById(R.id.permis) @JvmField val rl: View = view.findViewById(R.id.second) @JvmField val genericText: TextView? = view.findViewById(R.id.generictext) @JvmField val about: ImageButton = view.findViewById(R.id.properties) @JvmField val checkImageView: ImageView? = view.findViewById(R.id.check_icon) @JvmField val checkImageViewGrid: ImageView? = view.findViewById(R.id.check_icon_grid) @JvmField val iconLayout: RelativeLayout? = view.findViewById(R.id.icon_frame_grid) @JvmField val dummyView: View? = view.findViewById(R.id.dummy_view) }
gpl-3.0
0656691806f352397bc56c87ed4baa1d
32.146341
107
0.740618
3.944848
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/component/SliderBuilder.kt
1
1134
package org.hexworks.zircon.api.builder.component import org.hexworks.zircon.api.component.Slider import org.hexworks.zircon.api.component.builder.base.BaseComponentBuilder import org.hexworks.zircon.api.component.renderer.ComponentRenderer abstract class SliderBuilder<T : Slider, B : BaseComponentBuilder<T, B>>( initialRenderer: ComponentRenderer<out T> ) : BaseComponentBuilder<T, B>(initialRenderer) { var minValue: Int = 0 set(value) { require(value >= 0) { "Min value must be equal to or greater than 0" } require(value < maxValue) { "Min value must be smaller than max value" } field = value } var maxValue: Int = 100 set(value) { require(value > minValue) { "Max value must be greater than min value" } field = value } abstract var numberOfSteps: Int fun withMinValue(minValue: Int) = also { this.minValue = minValue } fun withMaxValue(maxValue: Int) = also { this.maxValue = maxValue } fun withNumberOfSteps(steps: Int) = also { this.numberOfSteps = steps } }
apache-2.0
839005d0dd06251933483879293678f1
29.648649
84
0.654321
4.169118
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/test/java/org/wordpress/android/viewmodel/WPWebViewViewModelTest.kt
1
12948
package org.wordpress.android.viewmodel import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import org.assertj.core.api.AssertionsForClassTypes.assertThat import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.whenever import org.wordpress.android.test import org.wordpress.android.ui.PreviewMode import org.wordpress.android.ui.PreviewMode.DESKTOP import org.wordpress.android.ui.PreviewMode.MOBILE import org.wordpress.android.ui.PreviewMode.TABLET import org.wordpress.android.ui.WPWebViewUsageCategory import org.wordpress.android.util.DisplayUtilsWrapper import org.wordpress.android.util.NetworkUtilsWrapper import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper import org.wordpress.android.viewmodel.helpers.ConnectionStatus import org.wordpress.android.viewmodel.wpwebview.WPWebViewViewModel import org.wordpress.android.viewmodel.wpwebview.WPWebViewViewModel.PreviewModeSelectorStatus import org.wordpress.android.viewmodel.wpwebview.WPWebViewViewModel.WebPreviewUiState import org.wordpress.android.viewmodel.wpwebview.WPWebViewViewModel.WebPreviewUiState.WebPreviewContentUiState import org.wordpress.android.viewmodel.wpwebview.WPWebViewViewModel.WebPreviewUiState.WebPreviewFullscreenProgressUiState import org.wordpress.android.viewmodel.wpwebview.WPWebViewViewModel.WebPreviewUiState.WebPreviewFullscreenUiState.WebPreviewFullscreenErrorUiState import org.wordpress.android.viewmodel.wpwebview.WPWebViewViewModel.WebPreviewUiState.WebPreviewFullscreenUiState.WebPreviewFullscreenNotAvailableUiState @RunWith(MockitoJUnitRunner::class) class WPWebViewViewModelTest { @Rule @JvmField val rule = InstantTaskExecutorRule() @Mock private lateinit var connectionStatus: LiveData<ConnectionStatus> @Mock private lateinit var networkUtils: NetworkUtilsWrapper @Mock private lateinit var uiStateObserver: Observer<WebPreviewUiState> @Mock lateinit var displayUtilsWrapper: DisplayUtilsWrapper @Mock lateinit var analyticsTrackerWrapper: AnalyticsTrackerWrapper private lateinit var viewModel: WPWebViewViewModel @Before fun setUp() { viewModel = WPWebViewViewModel(displayUtilsWrapper, networkUtils, analyticsTrackerWrapper, connectionStatus) viewModel.uiState.observeForever(uiStateObserver) whenever(networkUtils.isNetworkAvailable()).thenReturn(true) } @Test fun `progress shown on start`() = test { viewModel.start(WPWebViewUsageCategory.WEBVIEW_STANDARD) assertThat(viewModel.uiState.value).isInstanceOf(WebPreviewFullscreenProgressUiState::class.java) } @Test fun `error shown on start when internet access not available`() = test { whenever(networkUtils.isNetworkAvailable()).thenReturn(false) viewModel.start(WPWebViewUsageCategory.WEBVIEW_STANDARD) assertThat(viewModel.uiState.value).isInstanceOf(WebPreviewFullscreenErrorUiState::class.java) } @Test fun `error shown on error failure`() { viewModel.start(WPWebViewUsageCategory.WEBVIEW_STANDARD) viewModel.onReceivedError() assertThat(viewModel.uiState.value).isInstanceOf(WebPreviewFullscreenErrorUiState::class.java) } @Test fun `show content on UrlLoaded and enable preview mode switch`() { viewModel.start(WPWebViewUsageCategory.WEBVIEW_STANDARD) viewModel.onUrlLoaded() assertThat(viewModel.uiState.value).isInstanceOf(WebPreviewContentUiState::class.java) assertThat(viewModel.previewModeSelector.value!!.isEnabled).isTrue() } @Test fun `show progress screen on retry clicked`() { viewModel.start(WPWebViewUsageCategory.WEBVIEW_STANDARD) viewModel.loadIfNecessary() assertThat(viewModel.uiState.value).isInstanceOf(WebPreviewFullscreenProgressUiState::class.java) } @Test fun `on mobile initially navigation is not enabled and preview mode is set to mobile and disabled`() { whenever(displayUtilsWrapper.isTablet()).thenReturn(false) viewModel.start(WPWebViewUsageCategory.WEBVIEW_STANDARD) assertThat(viewModel.navbarUiState.value).isNotNull() assertThat(viewModel.navbarUiState.value!!.backNavigationEnabled).isFalse() assertThat(viewModel.navbarUiState.value!!.forwardNavigationEnabled).isFalse() assertThat(viewModel.navbarUiState.value!!.previewModeHintVisible).isFalse() assertThat(viewModel.previewMode.value).isEqualTo(MOBILE) assertThat(viewModel.previewModeSelector.value).isNotNull() assertThat(viewModel.previewModeSelector.value!!.isVisible).isFalse() assertThat(viewModel.previewModeSelector.value!!.isEnabled).isFalse() assertThat(viewModel.previewModeSelector.value!!.selectedPreviewMode).isEqualTo(MOBILE) } @Test fun `on tablet initially navigation is not enabled and preview mode is set to tablet and disabled`() { whenever(displayUtilsWrapper.isTablet()).thenReturn(true) viewModel.start(WPWebViewUsageCategory.WEBVIEW_STANDARD) assertThat(viewModel.navbarUiState.value).isNotNull() assertThat(viewModel.navbarUiState.value!!.backNavigationEnabled).isFalse() assertThat(viewModel.navbarUiState.value!!.forwardNavigationEnabled).isFalse() assertThat(viewModel.navbarUiState.value!!.previewModeHintVisible).isFalse() assertThat(viewModel.previewMode.value).isEqualTo(TABLET) assertThat(viewModel.previewModeSelector.value).isNotNull() assertThat(viewModel.previewModeSelector.value!!.isVisible).isFalse() assertThat(viewModel.previewModeSelector.value!!.isEnabled).isFalse() assertThat(viewModel.previewModeSelector.value!!.selectedPreviewMode).isEqualTo(TABLET) } @Test fun `clicking on nav buttons navigates back and forward`() { viewModel.start(WPWebViewUsageCategory.WEBVIEW_STANDARD) // navigate forward var forwardNavigationWasCalled = false viewModel.navigateForward.observeForever { forwardNavigationWasCalled = true } assertThat(forwardNavigationWasCalled).isFalse() viewModel.navigateForward() assertThat(forwardNavigationWasCalled).isTrue() // navigate back var backNavigationWasCalled = false viewModel.navigateBack.observeForever { backNavigationWasCalled = true } assertThat(backNavigationWasCalled).isFalse() viewModel.navigateBack() assertThat(backNavigationWasCalled).isTrue() } @Test fun `toggling nav buttons enabled state enables and disables them`() { viewModel.start(WPWebViewUsageCategory.WEBVIEW_STANDARD) var isForwardButtonEnabled = false var isBackButtonEnabled = false viewModel.navbarUiState.observeForever { isForwardButtonEnabled = it.forwardNavigationEnabled isBackButtonEnabled = it.backNavigationEnabled } assertThat(isForwardButtonEnabled).isFalse() assertThat(isBackButtonEnabled).isFalse() viewModel.toggleBackNavigation(true) assertThat(isForwardButtonEnabled).isFalse() assertThat(isBackButtonEnabled).isTrue() viewModel.toggleBackNavigation(false) assertThat(isForwardButtonEnabled).isFalse() assertThat(isBackButtonEnabled).isFalse() viewModel.toggleForwardNavigation(true) assertThat(isForwardButtonEnabled).isTrue() assertThat(isBackButtonEnabled).isFalse() viewModel.toggleForwardNavigation(false) assertThat(isForwardButtonEnabled).isFalse() assertThat(isBackButtonEnabled).isFalse() } @Test fun `clicking on share button starts sharing`() { viewModel.start(WPWebViewUsageCategory.WEBVIEW_STANDARD) var shareWasCalled = false viewModel.share.observeForever { shareWasCalled = true } assertThat(shareWasCalled).isFalse() viewModel.share() assertThat(shareWasCalled).isTrue() } @Test fun `clicking on external browser button opens page in external browser`() { viewModel.start(WPWebViewUsageCategory.WEBVIEW_STANDARD) var externalBrowserOpened = false viewModel.openExternalBrowser.observeForever { externalBrowserOpened = true } assertThat(externalBrowserOpened).isFalse() viewModel.openPageInExternalBrowser() assertThat(externalBrowserOpened).isTrue() } @Test fun `clicking on preview mode button toggles preview mode selector`() { viewModel.start(WPWebViewUsageCategory.WEBVIEW_STANDARD) var previewModeSelectorStatus: PreviewModeSelectorStatus? = null viewModel.previewModeSelector.observeForever { previewModeSelectorStatus = it } assertThat(previewModeSelectorStatus).isNotNull() assertThat(previewModeSelectorStatus!!.isVisible).isFalse() viewModel.togglePreviewModeSelectorVisibility(true) assertThat(previewModeSelectorStatus).isNotNull() assertThat(previewModeSelectorStatus!!.isVisible).isTrue() viewModel.togglePreviewModeSelectorVisibility(false) assertThat(previewModeSelectorStatus).isNotNull() assertThat(previewModeSelectorStatus!!.isVisible).isFalse() } @Test fun `selected preview mode is reflected in preview mode selector`() { whenever(displayUtilsWrapper.isTablet()).thenReturn(false) viewModel.start(WPWebViewUsageCategory.WEBVIEW_STANDARD) var previewModeSelectorStatus: PreviewModeSelectorStatus? = null viewModel.previewModeSelector.observeForever { previewModeSelectorStatus = it } assertThat(previewModeSelectorStatus).isNotNull() assertThat(previewModeSelectorStatus!!.isVisible).isFalse() assertThat(previewModeSelectorStatus!!.selectedPreviewMode).isEqualTo(MOBILE) viewModel.selectPreviewMode(DESKTOP) viewModel.togglePreviewModeSelectorVisibility(true) assertThat(previewModeSelectorStatus).isNotNull() assertThat(previewModeSelectorStatus!!.isVisible).isTrue() assertThat(previewModeSelectorStatus!!.selectedPreviewMode).isEqualTo(DESKTOP) } @Test fun `selecting preview mode triggers progress indicator`() { viewModel.start(WPWebViewUsageCategory.WEBVIEW_STANDARD) viewModel.selectPreviewMode(DESKTOP) assertThat(viewModel.uiState.value).isInstanceOf(WebPreviewFullscreenProgressUiState::class.java) viewModel.onUrlLoaded() assertThat(viewModel.uiState.value).isInstanceOf(WebPreviewContentUiState::class.java) } @Test fun `selecting a preview mode changes it if it's not already selected`() { whenever(displayUtilsWrapper.isTablet()).thenReturn(false) viewModel.start(WPWebViewUsageCategory.WEBVIEW_STANDARD) val selectedPreviewModes: ArrayList<PreviewMode> = ArrayList() viewModel.previewMode.observeForever { selectedPreviewModes.add(it) } // initial state assertThat(selectedPreviewModes.size).isEqualTo(1) assertThat(selectedPreviewModes[0]).isEqualTo(MOBILE) viewModel.selectPreviewMode(MOBILE) assertThat(selectedPreviewModes.size).isEqualTo(1) assertThat(selectedPreviewModes[0]).isEqualTo(MOBILE) viewModel.selectPreviewMode(DESKTOP) assertThat(selectedPreviewModes.size).isEqualTo(2) assertThat(selectedPreviewModes[1]).isEqualTo(DESKTOP) } @Test fun `selecting desktop preview mode shows hint label`() { viewModel.start(WPWebViewUsageCategory.WEBVIEW_STANDARD) var isDesktopPreviewModeHintVisible = false viewModel.navbarUiState.observeForever { isDesktopPreviewModeHintVisible = it.previewModeHintVisible } assertThat(isDesktopPreviewModeHintVisible).isFalse() viewModel.selectPreviewMode(DESKTOP) assertThat(isDesktopPreviewModeHintVisible).isTrue() viewModel.selectPreviewMode(MOBILE) assertThat(isDesktopPreviewModeHintVisible).isFalse() } @Test fun `preview not available actionable shown when asked`() = test { viewModel.start(WPWebViewUsageCategory.REMOTE_PREVIEW_NOT_AVAILABLE) assertThat(viewModel.uiState.value).isInstanceOf(WebPreviewFullscreenNotAvailableUiState::class.java) } @Test fun `network not available actionable shown when asked`() = test { viewModel.start(WPWebViewUsageCategory.REMOTE_PREVIEW_NO_NETWORK) assertThat(viewModel.uiState.value).isInstanceOf(WebPreviewFullscreenErrorUiState::class.java) } }
gpl-2.0
aaab17b9f0705edf719e8c3ae2ed8440
40.367412
153
0.750232
5.17506
false
true
false
false
himikof/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/ext/PsiElement.kt
1
2606
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.psi.ext import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtilCore import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.tree.IElementType import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtilCore import org.rust.lang.core.psi.RsFile import org.rust.lang.core.stubs.RsFileStub /** * Returns module for this PsiElement. * * If the element is in a library, returns the module which depends on * the library. */ val PsiElement.module: Module? get() { // It's important to look the module for `containingFile` file // and not the element itself. Otherwise this will break for // elements in libraries. return ModuleUtilCore.findModuleForPsiElement(containingFile) } val PsiElement.ancestors: Sequence<PsiElement> get() = generateSequence(this) { it.parent } /** * Extracts node's element type */ val PsiElement.elementType: IElementType // XXX: be careful not to switch to AST get() = if (this is RsFile) RsFileStub.Type else PsiUtilCore.getElementType(this) inline fun <reified T : PsiElement> PsiElement.parentOfType(strict: Boolean = true, minStartOffset: Int = -1): T? = PsiTreeUtil.getParentOfType(this, T::class.java, strict, minStartOffset) inline fun <reified T : PsiElement> PsiElement.parentOfType(strict: Boolean = true, stopAt: Class<out PsiElement>): T? = PsiTreeUtil.getParentOfType(this, T::class.java, strict, stopAt) inline fun <reified T : PsiElement> PsiElement.contextOfType(strict: Boolean = true): T? = PsiTreeUtil.getContextOfType(this, T::class.java, strict) inline fun <reified T : PsiElement> PsiElement.childOfType(strict: Boolean = true): T? = PsiTreeUtil.findChildOfType(this, T::class.java, strict) inline fun <reified T : PsiElement> PsiElement.descendantsOfType(): Collection<T> = PsiTreeUtil.findChildrenOfType(this, T::class.java) /** * Finds first sibling that is neither comment, nor whitespace before given element. */ fun PsiElement?.getPrevNonCommentSibling(): PsiElement? = PsiTreeUtil.skipSiblingsBackward(this, PsiWhiteSpace::class.java, PsiComment::class.java) /** * Finds first sibling that is neither comment, nor whitespace after given element. */ fun PsiElement?.getNextNonCommentSibling(): PsiElement? = PsiTreeUtil.skipSiblingsForward(this, PsiWhiteSpace::class.java, PsiComment::class.java)
mit
065cadabf7663a4d20c109045e89a664
37.323529
120
0.754413
4.1696
false
false
false
false
cfieber/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/StartExecutionHandlerTest.kt
1
10890
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.netflix.spinnaker.orca.ExecutionStatus.* import com.netflix.spinnaker.orca.events.ExecutionComplete import com.netflix.spinnaker.orca.events.ExecutionStarted import com.netflix.spinnaker.orca.fixture.pipeline import com.netflix.spinnaker.orca.fixture.stage import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.q.CancelExecution import com.netflix.spinnaker.orca.q.StartExecution import com.netflix.spinnaker.orca.q.StartStage import com.netflix.spinnaker.orca.q.pending.PendingExecutionService import com.netflix.spinnaker.orca.q.singleTaskStage import com.netflix.spinnaker.q.Queue import com.netflix.spinnaker.spek.and import com.netflix.spinnaker.time.fixedClock import com.nhaarman.mockito_kotlin.* import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.dsl.* import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP import org.jetbrains.spek.subject.SubjectSpek import org.springframework.context.ApplicationEventPublisher import rx.Observable.just import java.util.* object StartExecutionHandlerTest : SubjectSpek<StartExecutionHandler>({ val queue: Queue = mock() val repository: ExecutionRepository = mock() val pendingExecutionService: PendingExecutionService = mock() val publisher: ApplicationEventPublisher = mock() val clock = fixedClock() subject(GROUP) { StartExecutionHandler(queue, repository, pendingExecutionService, publisher, clock) } fun resetMocks() = reset(queue, repository, publisher) describe("starting an execution") { given("a pipeline with a single initial stage") { val pipeline = pipeline { stage { type = singleTaskStage.type } } val message = StartExecution(pipeline) beforeGroup { whenever(repository.retrieve(message.executionType, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving a message") { subject.handle(message) } it("marks the execution as running") { verify(repository).updateStatus(PIPELINE, message.executionId, RUNNING) } it("starts the first stage") { verify(queue).push(StartStage(pipeline.stages.first())) } it("publishes an event") { verify(publisher).publishEvent(check<ExecutionStarted> { assertThat(it.executionType).isEqualTo(message.executionType) assertThat(it.executionId).isEqualTo(message.executionId) }) } } given("a pipeline that was previously canceled and status is CANCELED") { val pipeline = pipeline { stage { type = singleTaskStage.type } status = CANCELED } val message = StartExecution(pipeline) beforeGroup { whenever(repository.retrieve(message.executionType, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving a message") { subject.handle(message) } it("publishes an event") { verify(publisher).publishEvent(check<ExecutionComplete> { assertThat(it.executionType).isEqualTo(message.executionType) assertThat(it.executionId).isEqualTo(message.executionId) assertThat(it.status).isEqualTo(CANCELED) }) } it("pushes no messages to the queue") { verifyNoMoreInteractions(queue) } } given("a pipeline that was previously canceled and status is NOT_STARTED") { val pipeline = pipeline { stage { type = singleTaskStage.type } isCanceled = true } val message = StartExecution(pipeline) beforeGroup { whenever(repository.retrieve(message.executionType, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving a message") { subject.handle(message) } it("publishes an event") { verify(publisher).publishEvent(check<ExecutionComplete> { assertThat(it.executionType).isEqualTo(message.executionType) assertThat(it.executionId).isEqualTo(message.executionId) assertThat(it.status).isEqualTo(NOT_STARTED) }) } it("pushes no messages to the queue") { verifyNoMoreInteractions(queue) } } given("a pipeline with multiple initial stages") { val pipeline = pipeline { stage { type = singleTaskStage.type } stage { type = singleTaskStage.type } } val message = StartExecution(pipeline) beforeGroup { whenever(repository.retrieve(message.executionType, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving a message") { subject.handle(message) } it("starts all the initial stages") { argumentCaptor<StartStage>().apply { verify(queue, times(2)).push(capture()) assertThat(allValues) .extracting("stageId") .containsExactlyInAnyOrderElementsOf(pipeline.stages.map { it.id }) } } } given("a pipeline with no initial stages") { val pipeline = pipeline { stage { type = singleTaskStage.type requisiteStageRefIds = listOf("1") } stage { type = singleTaskStage.type requisiteStageRefIds = listOf("1") } } val message = StartExecution(pipeline) beforeGroup { whenever(repository.retrieve(message.executionType, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving a message") { subject.handle(message) } it("marks the execution as TERMINAL") { verify(repository, times(1)).updateStatus(PIPELINE, pipeline.id, TERMINAL) } it("publishes an event with TERMINAL status") { verify(publisher).publishEvent(check<ExecutionComplete> { assertThat(it.executionType).isEqualTo(message.executionType) assertThat(it.executionId).isEqualTo(message.executionId) assertThat(it.status).isEqualTo(TERMINAL) }) } } given("a start time after ttl") { val pipeline = pipeline { stage { type = singleTaskStage.type } startTimeExpiry = clock.instant().minusSeconds(30).toEpochMilli() } val message = StartExecution(pipeline) beforeGroup { whenever(repository.retrieve(message.executionType, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives the message") { subject.handle(message) } it("cancels the execution") { verify(queue).push(CancelExecution( pipeline, "spinnaker", "Could not begin execution before start time expiry" )) } } given("a pipeline with another instance already running") { val configId = UUID.randomUUID().toString() val runningPipeline = pipeline { pipelineConfigId = configId isLimitConcurrent = true status = RUNNING stage { type = singleTaskStage.type status = RUNNING } } val pipeline = pipeline { pipelineConfigId = configId isLimitConcurrent = true stage { type = singleTaskStage.type } } val message = StartExecution(pipeline.type, pipeline.id, pipeline.application) and("the pipeline should not run multiple executions concurrently") { beforeGroup { pipeline.isLimitConcurrent = true runningPipeline.isLimitConcurrent = true whenever( repository.retrievePipelinesForPipelineConfigId(eq(configId), any()) ) doReturn just(runningPipeline) whenever( repository.retrieve(message.executionType, message.executionId) ) doReturn pipeline } afterGroup(::resetMocks) on("receiving a message") { subject.handle(message) } it("does not start the new pipeline") { verify(repository, never()).updateStatus(PIPELINE, message.executionId, RUNNING) verify(queue, never()).push(isA<StartStage>()) } it("does not push any messages to the queue") { verifyNoMoreInteractions(queue) } it("does not publish any events") { verifyNoMoreInteractions(publisher) } } and("the pipeline is allowed to run multiple executions concurrently") { beforeGroup { pipeline.isLimitConcurrent = false runningPipeline.isLimitConcurrent = false whenever( repository.retrievePipelinesForPipelineConfigId(eq(configId), any()) ) doReturn just(runningPipeline) whenever( repository.retrieve(message.executionType, message.executionId) ) doReturn pipeline } afterGroup(::resetMocks) on("receiving a message") { subject.handle(message) } it("starts the new pipeline") { verify(repository).updateStatus(PIPELINE, message.executionId, RUNNING) verify(queue).push(isA<StartStage>()) } } and("the pipeline is not allowed to run concurrently but the only pipeline already running is the same one") { beforeGroup { pipeline.isLimitConcurrent = true runningPipeline.isLimitConcurrent = true whenever( repository.retrievePipelinesForPipelineConfigId(eq(configId), any()) ) doReturn just(pipeline) whenever( repository.retrieve(message.executionType, message.executionId) ) doReturn pipeline } afterGroup(::resetMocks) on("receiving a message") { subject.handle(message) } it("starts the new pipeline") { verify(repository).updateStatus(PIPELINE, message.executionId, RUNNING) verify(queue).push(isA<StartStage>()) } } } } })
apache-2.0
d15460138b329070d886c4fb15241ff3
29.25
116
0.650689
5.115078
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/opengles/src/templates/kotlin/opengles/templates/ANGLE_texture_compression_dxt.kt
4
1636
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengles.templates import org.lwjgl.generator.* import opengles.* val ANGLE_texture_compression_dxt1 = "ANGLETextureCompressionDXT1".nativeClassGLES("ANGLE_texture_compression_dxt1", postfix = ANGLE) { documentation = "Native bindings to the ${registryLink("ANGLE_texture_compression_dxt")} extension." IntConstant( "Accepted by the {@code internalformat} parameter of CompressedTexImage2D and the {@code format} parameter of CompressedTexSubImage2D.", "COMPRESSED_RGB_S3TC_DXT1_ANGLE"..0x83F0, "COMPRESSED_RGBA_S3TC_DXT1_ANGLE"..0x83F1 ) } val ANGLE_texture_compression_dxt3 = "ANGLETextureCompressionDXT3".nativeClassGLES("ANGLE_texture_compression_dxt3", postfix = ANGLE) { documentation = "Native bindings to the ${registryLink("ANGLE_texture_compression_dxt")} extension." IntConstant( "Accepted by the {@code internalformat} parameter of CompressedTexImage2D and the {@code format} parameter of CompressedTexSubImage2D.", "COMPRESSED_RGBA_S3TC_DXT3_ANGLE"..0x83F2 ) } val ANGLE_texture_compression_dxt5 = "ANGLETextureCompressionDXT5".nativeClassGLES("ANGLE_texture_compression_dxt5", postfix = ANGLE) { documentation = "Native bindings to the ${registryLink("ANGLE_texture_compression_dxt")} extension." IntConstant( "Accepted by the {@code internalformat} parameter of CompressedTexImage2D and the {@code format} parameter of CompressedTexSubImage2D.", "COMPRESSED_RGBA_S3TC_DXT5_ANGLE"..0x83F3 ) }
bsd-3-clause
0c060c693ca21cf8bad60ecd6693d9ba
37.97619
144
0.731663
3.990244
false
false
false
false
333fred/kotlin_lisp
src/com/fsilberberg/lisp/Environment.kt
1
1519
package com.fsilberberg.lisp import com.fsilberberg.lisp.builtins.builtIns import java.util.* /** * The environment that holds all defined atom->value mappings for the current scope. */ class Environment { constructor() { env = HashMap() } protected constructor(startingEnv: Map<Atom, Value>) { env = startingEnv } private val env: Map<Atom, Value> /** * Looks up the given atom in the environment, returning the value if defined * @param atom The atom to look up * @return The bound value in the environment */ fun lookup(atom: Atom): Value? = env[atom] /** * Creates a copy of the current environment, extended with the given bindings, overriding as necessary. The current * object is not modified by this operation. * * @param bindings The new bindings to introduce into the environment * @return The extended environment */ fun extendEnv(bindings: Collection<Pair<Atom, Value>>): Environment { // Make a new environment with a copy of the existing environment val newMap = HashMap<Atom, Value>(env) for ((key, value) in bindings) { newMap[key] = value } return Environment(newMap) } override fun toString(): String { return "com.fsilberberg.lisp.Environment: ${env.entries.joinToString { pair -> "${pair.key} -> ${pair.value}" }}" } } val emptyEnv = Environment() val builtInEnv = emptyEnv.extendEnv(builtIns)
mit
b5ce91577d8c4bc6cb22b4e462d8af95
28.211538
120
0.64582
4.266854
false
false
false
false
jovr/imgui
core/src/main/kotlin/imgui/internal/api/tablesCandidatesForPublicAPI.kt
1
10836
package imgui.internal.api import glm_.has import glm_.max import imgui.* import imgui.ImGui.calcTextSize import imgui.api.g import imgui.internal.hashStr import imgui.ImGui.openPopupEx import imgui.ImGui.setWindowClipRectBeforeSetChannel import imgui.ImGui.style import imgui.ImGui.tableGetColumnCount import imgui.ImGui.tableGetColumnFlags import imgui.ImGui.tableGetColumnName import imgui.internal.classes.TableColumnIdx import imgui.TableColumnFlag as Tcf import imgui.TableFlag as Tf // Tables: Candidates for public API interface tablesCandidatesForPublicAPI { //------------------------------------------------------------------------- // [SECTION] Tables: Context Menu //------------------------------------------------------------------------- // - TableOpenContextMenu() [Internal] // - TableDrawContextMenu() [Internal] //------------------------------------------------------------------------- /** Use -1 to open menu not specific to a given column. */ fun tableOpenContextMenu(columnN_: Int = -1) { var columnN = columnN_ val table = g.currentTable!! if (columnN == -1 && table.currentColumn != -1) // When called within a column automatically use this one (for consistency) columnN = table.currentColumn if (columnN == table.columnsCount) // To facilitate using with TableGetHoveredColumn() columnN = -1 assert(columnN >= -1 && columnN < table.columnsCount) if (table.flags has (Tf.Resizable or Tf.Reorderable or Tf.Hideable)) { table.isContextPopupOpen = true table.contextPopupColumn = columnN table.instanceInteracted = table.instanceCurrent val contextMenuId = hashStr("##ContextMenu", 0, table.id) openPopupEx(contextMenuId, PopupFlag.None.i) } } /** 'width' = inner column width, without padding */ fun tableSetColumnWidth(columnN: Int, width: Float) { val table = g.currentTable check(table != null && !table.isLayoutLocked) assert(columnN >= 0 && columnN < table.columnsCount) val column0 = table.columns[columnN] var column0Width = width // Apply constraints early // Compare both requested and actual given width to avoid overwriting requested width when column is stuck (minimum size, bounded) assert(table.minColumnWidth > 0f) val minWidth = table.minColumnWidth val maxWidth = minWidth max (table getMaxColumnWidth columnN) column0Width = clamp(column0Width, minWidth, maxWidth) if (column0.widthGiven == column0Width || column0.widthRequest == column0Width) return //IMGUI_DEBUG_LOG("TableSetColumnWidth(%d, %.1f->%.1f)\n", column_0_idx, column_0->WidthGiven, column_0_width); var column1 = table.columns.getOrNull(column0.nextEnabledColumn) // In this surprisingly not simple because of how we support mixing Fixed and multiple Stretch columns. // - All fixed: easy. // - All stretch: easy. // - One or more fixed + one stretch: easy. // - One or more fixed + more than one stretch: tricky. // // Qt when manual resize is enabled only support a single _trailing_ stretch column. // When forwarding resize from Wn| to Fn+1| we need to be considerate of the _NoResize flag on Fn+1. // FIXME-TABLE: Find a way to rewrite all of this so interactions feel more consistent for the user. // Scenarios: // - F1 F2 F3 resize from F1| or F2| --> ok: alter ->WidthRequested of Fixed column. Subsequent columns will be offset. // - F1 F2 F3 resize from F3| --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered. // - F1 F2 W3 resize from F1| or F2| --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered, but it doesn't make much sense as the Stretch column will always be minimal size. // - F1 F2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1) // - W1 W2 W3 resize from W1| or W2| --> ij // - W1 W2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1) // - W1 F2 F3 resize from F3| --> ok: no-op (disabled by Resize Rule 1) // - W1 F2 resize from F2| --> ok: no-op (disabled by Resize Rule 1) // - W1 W2 F3 resize from W1| or W2| --> ok // - W1 F2 W3 resize from W1| or F2| --> ok // - F1 W2 F3 resize from W2| --> ok // - F1 W3 F2 resize from W3| --> ok // - W1 F2 F3 resize from W1| --> ok: equivalent to resizing |F2. F3 will not move. // - W1 F2 F3 resize from F2| --> ok // All resizes from a Wx columns are locking other columns. // Possible improvements: // - W1 W2 W3 resize W1| --> to not be stuck, both W2 and W3 would stretch down. Seems possible to fix. Would be most beneficial to simplify resize of all-weighted columns. // - W3 F1 F2 resize W3| --> to not be stuck past F1|, both F1 and F2 would need to stretch down, which would be lossy or ambiguous. Seems hard to fix. // [Resize Rule 1] Can't resize from right of right-most visible column if there is any Stretch column. Implemented in TableUpdateLayout(). // If we have all Fixed columns OR resizing a Fixed column that doesn't come after a Stretch one, we can do an offsetting resize. // This is the preferred resize path if (column0.flags has Tcf.WidthFixed) if (column1 == null || table.leftMostStretchedColumn == -1 || table.columns[table.leftMostStretchedColumn].displayOrder >= column0.displayOrder) { column0.widthRequest = column0Width table.isSettingsDirty = true return } // We can also use previous column if there's no next one (this is used when doing an auto-fit on the right-most stretch column) if (column1 == null) column1 = table.columns.getOrNull(column0.prevEnabledColumn) ?: return // Resizing from right-side of a Stretch column before a Fixed column forward sizing to left-side of fixed column. // (old_a + old_b == new_a + new_b) --> (new_a == old_a + old_b - new_b) val column1Width = (column1.widthRequest - (column0Width - column0.widthRequest)) max minWidth column0Width = column0.widthRequest + column1.widthRequest - column1Width assert(column0Width > 0f && column1Width > 0f) column0.widthRequest = column0Width column1.widthRequest = column1Width if ((column0.flags or column1.flags) has Tcf.WidthStretch) table.updateColumnsWeightFromWidth() table.isSettingsDirty = true } /** Note that the NoSortAscending/NoSortDescending flags are processed in TableSortSpecsSanitize(), and they may change/revert * the value of SortDirection. We could technically also do it here but it would be unnecessary and duplicate code. */ fun tableSetColumnSortDirection(columnN: Int, sortDirection: SortDirection, appendToSortSpecs_: Boolean) { var appendToSortSpecs = appendToSortSpecs_ val table = g.currentTable!! if (table.flags hasnt Tf.SortMulti) appendToSortSpecs = false if (table.flags hasnt Tf.SortTristate) assert(sortDirection != SortDirection.None) var sortOrderMax: TableColumnIdx = 0 if (appendToSortSpecs) for (otherColumnN in 0 until table.columnsCount) sortOrderMax = sortOrderMax max table.columns[otherColumnN].sortOrder val column = table.columns[columnN] column.sortDirection = sortDirection if (column.sortDirection == SortDirection.None) column.sortOrder = -1 else if (column.sortOrder == -1 || !appendToSortSpecs) column.sortOrder = if(appendToSortSpecs) sortOrderMax + 1 else 0 for (otherColumnN in 0 until table.columnsCount) { val otherColumn = table.columns[otherColumnN] if (otherColumn !== column && !appendToSortSpecs) otherColumn.sortOrder = -1 table fixColumnSortDirection otherColumn } table.isSettingsDirty = true table.isSortSpecsDirty = true } /** May use (TableGetColumnFlags() & ImGuiTableColumnFlags_IsHovered) instead. Return hovered column. return -1 when table is not hovered. return columns_count if the unused space at the right of visible columns is hovered. * * Return -1 when table is not hovered. return columns_count if the unused space at the right of visible columns is hovered. */ fun tableGetHoveredColumn(): Int = g.currentTable?.hoveredColumnBody ?: -1 fun tableGetHeaderRowHeight(): Float { // Caring for a minor edge case: // Calculate row height, for the unlikely case that some labels may be taller than others. // If we didn't do that, uneven header height would highlight but smaller one before the tallest wouldn't catch input for all height. // In your custom header row you may omit this all together and just call TableNextRow() without a height... var rowHeight = ImGui.textLineHeight val columnsCount = tableGetColumnCount() for (columnN in 0 until columnsCount) if (tableGetColumnFlags(columnN) has Tcf.IsEnabled) rowHeight = rowHeight max calcTextSize(tableGetColumnName(columnN)!!).y rowHeight += style.cellPadding.y * 2f return rowHeight } /** Bg2 is used by Selectable (and possibly other widgets) to render to the background. * Unlike our Bg0/1 channel which we uses for RowBg/CellBg/Borders and where we guarantee all shapes to be CPU-clipped, the Bg2 channel being widgets-facing will rely on regular ClipRect. */ fun tablePushBackgroundChannel() { val window = g.currentWindow!! val table = g.currentTable!! // Optimization: avoid SetCurrentChannel() + PushClipRect() table.hostBackupInnerClipRect put window.clipRect setWindowClipRectBeforeSetChannel(window, table.bg2ClipRectForDrawCmd) table.drawSplitter.setCurrentChannel(window.drawList, table.bg2DrawChannelCurrent) } fun tablePopBackgroundChannel() { val window = g.currentWindow!! val table = g.currentTable!! val column = table.columns[table.currentColumn] // Optimization: avoid PopClipRect() + SetCurrentChannel() setWindowClipRectBeforeSetChannel(window, table.hostBackupInnerClipRect) table.drawSplitter.setCurrentChannel(window.drawList, column.drawChannelCurrent) } }
mit
ee93ccc82f3b6a40d094e1ed4253b194
53.732323
227
0.649686
4.201629
false
false
false
false
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/features/bows/EditBowListFragment.kt
1
4302
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets 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. */ package de.dreier.mytargets.features.bows import androidx.databinding.DataBindingUtil import android.os.Bundle import androidx.annotation.CallSuper import android.util.SparseArray import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import de.dreier.mytargets.R import de.dreier.mytargets.app.ApplicationInstance import de.dreier.mytargets.base.adapters.SimpleListAdapterBase import de.dreier.mytargets.base.fragments.EditableListFragmentBase import de.dreier.mytargets.base.fragments.ItemActionModeCallback import de.dreier.mytargets.base.fragments.LoaderUICallback import de.dreier.mytargets.databinding.FragmentBowsBinding import de.dreier.mytargets.shared.models.EBowType import de.dreier.mytargets.shared.models.EBowType.* import de.dreier.mytargets.shared.models.db.Bow import de.dreier.mytargets.utils.DividerItemDecoration import de.dreier.mytargets.utils.SlideInItemAnimator class EditBowListFragment : EditableListFragmentBase<Bow, SimpleListAdapterBase<Bow>>() { private lateinit var binding: FragmentBowsBinding private val bowDAO = ApplicationInstance.db.bowDAO() init { itemTypeDelRes = R.plurals.bow_deleted actionModeCallback = ItemActionModeCallback( this, selector, R.plurals.bow_selected ) actionModeCallback?.setEditCallback(this::onEdit) actionModeCallback?.setDeleteCallback(this::onDelete) } override fun onResume() { super.onResume() binding.fabSpeedDial.closeMenu() } @CallSuper override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_bows, container, false) binding.recyclerView.setHasFixedSize(true) binding.recyclerView.addItemDecoration( DividerItemDecoration(context!!, R.drawable.full_divider) ) adapter = BowAdapter(selector, this, this) binding.recyclerView.itemAnimator = SlideInItemAnimator() binding.recyclerView.adapter = adapter binding.fabSpeedDial.setMenuListener { menuItem -> val itemId = menuItem.itemId val bowType = bowTypeMap.get(itemId) val fab = binding.fabSpeedDial.getFabFromMenuId(itemId) navigationController.navigateToCreateBow(bowType) .fromFab(fab, R.color.fabBow, bowType.drawable) .start() false } return binding.root } override fun onLoad(args: Bundle?): LoaderUICallback { val bows = bowDAO.loadBows() return { adapter!!.setList(bows) binding.emptyState.root.visibility = if (bows.isEmpty()) View.VISIBLE else View.GONE } } private fun onEdit(itemId: Long) { navigationController.navigateToEditBow(itemId) } override fun onSelected(item: Bow) { navigationController.navigateToEditBow(item.id) } override fun deleteItem(item: Bow): () -> Bow { val images = bowDAO.loadBowImages(item.id) val sightMarks = bowDAO.loadSightMarks(item.id) bowDAO.deleteBow(item) return { bowDAO.saveBow(item, images, sightMarks) item } } companion object { internal var bowTypeMap = SparseArray<EBowType>() init { bowTypeMap.put(R.id.fabBowRecurve, RECURVE_BOW) bowTypeMap.put(R.id.fabBowCompound, COMPOUND_BOW) bowTypeMap.put(R.id.fabBowBare, BARE_BOW) bowTypeMap.put(R.id.fabBowLong, LONG_BOW) bowTypeMap.put(R.id.fabBowHorse, HORSE_BOW) bowTypeMap.put(R.id.fabBowYumi, YUMI) } } }
gpl-2.0
0ec64372dce2ceb1909bfe19112784f1
33.416
96
0.697118
4.302
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/codepipeline/src/main/kotlin/com/kotlin/pipeline/ListPipelineExecutions.kt
1
1612
// snippet-sourcedescription:[ListPipelineExecutions.kt demonstrates how to all executions for a specific pipeline.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[AWS CodePipeline] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.pipeline // snippet-start:[pipeline.kotlin.list_pipeline_exe.import] import aws.sdk.kotlin.services.codepipeline.CodePipelineClient import aws.sdk.kotlin.services.codepipeline.model.ListPipelineExecutionsRequest import kotlin.system.exitProcess // snippet-end:[pipeline.kotlin.list_pipeline_exe.import] suspend fun main(args: Array<String>) { val usage = """ Usage: <name> Where: name - the name of the pipeline. """ if (args.size != 1) { println(usage) exitProcess(1) } val name = args[0] listExecutions(name) } // snippet-start:[pipeline.kotlin.list_pipeline_exe.main] suspend fun listExecutions(name: String?) { val request = ListPipelineExecutionsRequest { maxResults = 10 pipelineName = name } CodePipelineClient { region = "us-east-1" }.use { pipelineClient -> val response = pipelineClient.listPipelineExecutions(request) response.pipelineExecutionSummaries?.forEach { exe -> println("The pipeline execution id is ${exe.pipelineExecutionId}") println("The execution status is ${exe.status}") } } } // snippet-end:[pipeline.kotlin.list_pipeline_exe.main]
apache-2.0
25466fef2f8a1a230c844362f418d80a
29
116
0.666873
4.081013
false
false
false
false
BreakOutEvent/breakout-backend
src/main/java/backend/view/challenge/ChallengeView.kt
1
2636
package backend.view.challenge import backend.model.challenges.Challenge import backend.view.MediaView import backend.view.UnregisteredSponsorView import org.hibernate.validator.constraints.SafeHtml import org.hibernate.validator.constraints.SafeHtml.WhiteListType.NONE import javax.validation.Valid import javax.validation.constraints.NotNull import javax.validation.constraints.Size class ChallengeView { var id: Long? = null var eventId: Long? = null var status: String? = null var teamId: Long? = null var team: String? = null var sponsorId: Long? = null var userId: Long? = null var sponsorIsHidden: Boolean = false @Valid var unregisteredSponsor: UnregisteredSponsorView? = null @NotNull var amount: Double? = null var billableAmount: Double? = null @NotNull @Size(max = 1000) @SafeHtml(whitelistType = NONE) var description: String? = null var contract: MediaView? = null var fulfilledCount: Int = 0 var maximumCount: Int? = 1 /** * no-args constructor for Jackson */ constructor() constructor(challenge: Challenge) { this.id = challenge.id!! this.eventId = challenge.team!!.event.id!! this.description = challenge.description this.amount = challenge.amount.numberStripped.toDouble() this.teamId = challenge.team!!.id!! this.team = challenge.team!!.name this.status = challenge.status.toString().toUpperCase() this.contract = challenge.contract?.let(::MediaView) this.billableAmount = challenge.billableAmount().numberStripped.toDouble() this.fulfilledCount = challenge.fulfilledCount this.maximumCount = challenge.maximumCount // Add information about registered sponsor // if he exists and isHidden is false challenge.sponsor?.registeredSponsor?.isHidden?.let { if (it) { this.sponsorIsHidden = true this.contract = null } else { this.userId = challenge.sponsor?.registeredSponsor?.account?.id this.sponsorId = challenge.sponsor?.registeredSponsor?.id } } // Add information about unregistered sponsor // if he exists and isHidden is false challenge.sponsor?.unregisteredSponsor?.isHidden?.let { if (it) { this.sponsorIsHidden = true this.contract = null } else { this.unregisteredSponsor = UnregisteredSponsorView(challenge.sponsor?.unregisteredSponsor!!) } } } }
agpl-3.0
73f3658ae0a77d87c1cc2ea44ca1e6b5
28.617978
108
0.650607
4.707143
false
false
false
false
georocket/georocket
src/main/kotlin/io/georocket/output/xml/XMLMerger.kt
1
2205
package io.georocket.output.xml import io.georocket.output.Merger import io.georocket.storage.XmlChunkMeta import io.vertx.core.buffer.Buffer import io.vertx.core.streams.WriteStream /** * Merges XML chunks using various strategies to create a valid XML document * @param optimistic `true` if chunks should be merged optimistically * without prior initialization * @author Michel Kraemer */ class XMLMerger(private val optimistic: Boolean) : Merger<XmlChunkMeta> { /** * The merger strategy determined by [init] */ private var strategy: MergeStrategy = AllSameStrategy() /** * `true` if [init] has been called at least once */ private var initialized = false /** * `true` if [merge] has been called at least once */ private var mergeStarted = false /** * Returns the next merge strategy (depending on the current one) */ private fun nextStrategy(): MergeStrategy { if (strategy is AllSameStrategy) { return MergeNamespacesStrategy() } throw UnsupportedOperationException( "Cannot merge chunks. No valid " + "strategy available." ) } override fun init(chunkMetadata: XmlChunkMeta) { if (mergeStarted) { throw IllegalStateException( "You cannot initialize the merger anymore " + "after merging has begun" ) } while (!strategy.canMerge(chunkMetadata)) { // current strategy cannot merge the chunk val ns = nextStrategy() ns.parents = strategy.parents strategy = ns } // current strategy is able to handle the chunk initialized = true strategy.init(chunkMetadata) } override suspend fun merge( chunk: Buffer, chunkMetadata: XmlChunkMeta, outputStream: WriteStream<Buffer> ) { mergeStarted = true if (!initialized) { if (optimistic) { strategy = AllSameStrategy() strategy.init(chunkMetadata) initialized = true } else { throw IllegalStateException("You must call init() at least once") } } strategy.merge(chunk, chunkMetadata, outputStream) } override fun finish(outputStream: WriteStream<Buffer>) { strategy.finish(outputStream) } }
apache-2.0
daa30c7ef0798701473dc38fa2d1e848
25.25
76
0.675283
4.546392
false
false
false
false
google/intellij-community
python/src/com/jetbrains/python/debugger/variablesview/usertyperenderers/PyUserNodeRenderer.kt
6
3309
// 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 com.jetbrains.python.debugger.variablesview.usertyperenderers import com.jetbrains.python.PyBundle import com.jetbrains.python.debugger.PyUserTypeRenderer import java.io.Serializable class PyUserNodeRenderer(var isEnabled: Boolean, existingNames: List<String>?) { var name: String = getNewRendererName(existingNames) var toType: String = "object" var typeCanonicalImportPath = "" var typeQualifiedName: String = "" var typeSourceFile: String = "" var moduleRootHasOneTypeWithSameName: Boolean = false val valueRenderer = PyNodeValueRenderer() val childrenRenderer = PyNodeChildrenRenderer() fun clone(): PyUserNodeRenderer { val renderer = PyUserNodeRenderer(isEnabled, null) renderer.name = name renderer.toType = toType renderer.typeCanonicalImportPath = typeCanonicalImportPath renderer.typeQualifiedName = typeQualifiedName renderer.typeSourceFile = typeSourceFile renderer.moduleRootHasOneTypeWithSameName = moduleRootHasOneTypeWithSameName renderer.valueRenderer.isDefault = valueRenderer.isDefault renderer.valueRenderer.expression = valueRenderer.expression renderer.childrenRenderer.isDefault = childrenRenderer.isDefault renderer.childrenRenderer.children = childrenRenderer.children renderer.childrenRenderer.appendDefaultChildren = childrenRenderer.appendDefaultChildren return renderer } data class PyNodeValueRenderer( var isDefault: Boolean = true, var expression: String = "" ) : Serializable data class PyNodeChildrenRenderer( var isDefault: Boolean = true, var children: List<ChildInfo> = listOf(), var appendDefaultChildren: Boolean = false ) : Serializable data class ChildInfo(var expression: String = "") : Serializable fun isDefault() = valueRenderer.isDefault && childrenRenderer.isDefault fun hasNoEmptyTypeInfo() = typeQualifiedName != "" || typeCanonicalImportPath != "" fun isApplicable() = hasNoEmptyTypeInfo() && isEnabled fun equalTo(other: PyUserNodeRenderer): Boolean { return other.isEnabled == isEnabled && other.name == name && other.toType == toType && other.valueRenderer == valueRenderer && other.childrenRenderer == childrenRenderer } override fun toString() = name fun convertRenderer(): PyUserTypeRenderer { val children = childrenRenderer.children.map { PyUserTypeRenderer.ChildInfo(it.expression) } return PyUserTypeRenderer( toType, typeCanonicalImportPath, typeQualifiedName, typeSourceFile, moduleRootHasOneTypeWithSameName, valueRenderer.isDefault, valueRenderer.expression, childrenRenderer.isDefault, childrenRenderer.appendDefaultChildren, children ) } } fun getNewRendererName(existingNames: List<String>?): String { val default = PyBundle.message("form.debugger.variables.view.user.type.renderers.unnamed") if (existingNames.isNullOrEmpty()) return default val duplicatedNames = existingNames.filter { it.startsWith(default) }.size return if (duplicatedNames > 0) { "$default ($duplicatedNames)" } else { default } }
apache-2.0
7a812bdb10764cfeff9c8fbe65dca85c
35.777778
158
0.750982
4.680339
false
false
false
false
google/intellij-community
plugins/github/src/org/jetbrains/plugins/github/authentication/ui/AddAccountWithToken.kt
3
2680
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.authentication.ui import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformCoreDataKeys.CONTEXT_COMPONENT import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts import git4idea.i18n.GitBundle import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.GithubServerPath import org.jetbrains.plugins.github.i18n.GithubBundle.message import java.awt.Component import javax.swing.JComponent class AddGHAccountWithTokenAction : BaseAddAccountWithTokenAction() { override val defaultServer: String get() = GithubServerPath.DEFAULT_HOST } class AddGHEAccountAction : BaseAddAccountWithTokenAction() { override val defaultServer: String get() = "" } abstract class BaseAddAccountWithTokenAction : DumbAwareAction() { abstract val defaultServer: String override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = e.getData(GHAccountsHost.KEY) != null } override fun actionPerformed(e: AnActionEvent) { val accountsHost = e.getData(GHAccountsHost.KEY)!! val dialog = newAddAccountDialog(e.project, e.getData(CONTEXT_COMPONENT), accountsHost::isAccountUnique) dialog.setServer(defaultServer, defaultServer != GithubServerPath.DEFAULT_HOST) if (dialog.showAndGet()) { accountsHost.addAccount(dialog.server, dialog.login, dialog.token) } } } private fun newAddAccountDialog(project: Project?, parent: Component?, isAccountUnique: UniqueLoginPredicate): BaseLoginDialog = GHTokenLoginDialog(project, parent, isAccountUnique).apply { title = message("dialog.title.add.github.account") setLoginButtonText(message("accounts.add.button")) } internal class GHTokenLoginDialog(project: Project?, parent: Component?, isAccountUnique: UniqueLoginPredicate) : BaseLoginDialog(project, parent, GithubApiRequestExecutor.Factory.getInstance(), isAccountUnique) { init { title = message("login.to.github") setLoginButtonText(GitBundle.message("login.dialog.button.login")) loginPanel.setTokenUi() init() } internal fun setLoginButtonText(@NlsContexts.Button text: String) = setOKButtonText(text) override fun createCenterPanel(): JComponent = loginPanel.setPaddingCompensated() }
apache-2.0
42ae74d9ad25738b04360f4cebe47fc8
39.014925
140
0.797015
4.496644
false
false
false
false
google/intellij-community
jvm/jvm-analysis-impl/src/com/intellij/codeInspection/test/junit/JUnitAssertEqualsMayBeAssertSameInspection.kt
5
2444
// 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.codeInspection.test.junit import com.intellij.analysis.JvmAnalysisBundle import com.intellij.codeInspection.* import com.intellij.psi.CommonClassNames import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiModifier import com.intellij.psi.util.PsiUtil import com.intellij.uast.UastHintedVisitorAdapter import com.siyeh.ig.testFrameworks.UAssertHint import org.jetbrains.uast.UCallExpression import org.jetbrains.uast.UExpression import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor class JUnitAssertEqualsMayBeAssertSameInspection : AbstractBaseUastLocalInspectionTool(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor = UastHintedVisitorAdapter.create( holder.file.language, JUnitAssertEqualsMayBeAssertSameVisitor(holder), arrayOf(UCallExpression::class.java), directOnly = true ) } private class JUnitAssertEqualsMayBeAssertSameVisitor(private val holder: ProblemsHolder) : AbstractUastNonRecursiveVisitor() { override fun visitCallExpression(node: UCallExpression): Boolean { val assertHint = UAssertHint.createAssertEqualsUHint(node) ?: return true if (!couldBeAssertSameArgument(assertHint.firstArgument)) return true if (!couldBeAssertSameArgument(assertHint.secondArgument)) return true val message = JvmAnalysisBundle.message("jvm.inspections.junit.assertequals.may.be.assertsame.problem.descriptor") holder.registerUProblem(node, message, ReplaceMethodCallFix("assertSame")) return true } private fun couldBeAssertSameArgument(expression: UExpression): Boolean { val argumentClass = PsiUtil.resolveClassInClassTypeOnly(expression.getExpressionType()) ?: return false if (!argumentClass.hasModifierProperty(PsiModifier.FINAL)) return false val methods = argumentClass.findMethodsByName("equals", true) val project = expression.sourcePsi?.project ?: return false val objectClass = JavaPsiFacade.getInstance(project).findClass(CommonClassNames.JAVA_LANG_OBJECT, argumentClass.resolveScope) ?: return false for (method in methods) if (objectClass != method.containingClass) return false return true } }
apache-2.0
455c39461c2eb072bda9027d023b8f13
51.021277
130
0.805646
4.997955
false
false
false
false
google/intellij-community
plugins/kotlin/code-insight/intentions-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/intentions/AddWhenRemainingBranchesIntention.kt
3
1372
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.k2.codeinsight.intentions import org.jetbrains.kotlin.diagnostics.WhenMissingCase import org.jetbrains.kotlin.idea.codeinsight.api.applicators.AbstractKotlinApplicatorBasedIntention import org.jetbrains.kotlin.idea.codeinsight.api.applicators.inputProvider import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.AddRemainingWhenBranchesApplicator import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.ApplicabilityRanges import org.jetbrains.kotlin.psi.KtWhenExpression internal class AddWhenRemainingBranchesIntention : AbstractKotlinApplicatorBasedIntention<KtWhenExpression, AddRemainingWhenBranchesApplicator.Input>(KtWhenExpression::class) { override fun getApplicator() = AddRemainingWhenBranchesApplicator.applicator override fun getApplicabilityRange() = ApplicabilityRanges.SELF override fun getInputProvider() = inputProvider { whenExpression: KtWhenExpression -> val whenMissingCases = whenExpression.getMissingCases().takeIf { it.isNotEmpty() && it.singleOrNull() != WhenMissingCase.Unknown } ?: return@inputProvider null AddRemainingWhenBranchesApplicator.Input(whenMissingCases, enumToStarImport = null) } }
apache-2.0
da043411380f4c84bf1b689f1121f113
53.92
131
0.815598
5.276923
false
false
false
false
vhromada/Catalog
web/src/main/kotlin/com/github/vhromada/catalog/web/controller/GenreController.kt
1
7625
package com.github.vhromada.catalog.web.controller import com.github.vhromada.catalog.web.connector.GenreConnector import com.github.vhromada.catalog.web.fo.GenreFO import com.github.vhromada.catalog.web.fo.NameFilterFO import com.github.vhromada.catalog.web.mapper.FilterMapper import com.github.vhromada.catalog.web.mapper.GenreMapper import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.validation.Errors import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.ModelAttribute import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import java.util.Optional import javax.validation.Valid /** * A class represents controller for genres. * * @author Vladimir Hromada */ @Controller("genreController") @RequestMapping("/genres") class GenreController( /** * Connector for genres */ private val connector: GenreConnector, /** * Mapper for genres */ private val genreMapper: GenreMapper, /** * Mapper for filters */ private val filterMapper: FilterMapper ) { /** * Count of items shown on page */ @Value("\${catalog.items_per_page:20}") private val itemsPerPage: Int? = null /** * Shows page with list of genres. * * @param model model * @param name name * @param page index of page * @return view for page with list of genres */ @GetMapping fun showList(model: Model, @RequestParam("name") name: Optional<String>, @RequestParam("page") page: Optional<Int>): String { return createListView(model = model, filter = NameFilterFO(name = name.orElse(null)), page = page) } /** * Shows page with filtered list of genres. * * @param model model * @param filter FO for filter for names * @param page index of page * @return view for page with filtered list of genres */ @PostMapping fun filteredList(model: Model, @ModelAttribute("filter") filter: NameFilterFO, @RequestParam("page") page: Optional<Int>): String { return createListView(model = model, filter = filter, page = page) } /** * Shows page for adding genre. * * @param model model * @return view for page for adding genre */ @GetMapping("/add") fun showAdd(model: Model): String { return createFormView(model = model, genre = GenreFO(uuid = null, name = null), title = "Add genre", action = "add") } /** * Process adding genre. * * @param model model * @param genre FO for genre * @param errors errors * @return view for redirect to page with list of genres (no errors) or view for page for adding genre (errors) * @throws IllegalArgumentException if UUID isn't null */ @PostMapping(value = ["/add"], params = ["create"]) fun processAdd(model: Model, @ModelAttribute("genre") @Valid genre: GenreFO, errors: Errors): String { require(genre.uuid == null) { "UUID must be null." } if (errors.hasErrors()) { return createFormView(model = model, genre = genre, title = "Add genre", action = "add") } connector.add(request = genreMapper.mapRequest(source = genre)) return LIST_REDIRECT_URL } /** * Cancel adding genre. * * @return view for redirect to page with list of genres */ @PostMapping(value = ["/add"], params = ["cancel"]) fun cancelAdd(): String { return LIST_REDIRECT_URL } /** * Shows page for editing genre. * * @param model model * @param uuid UUID of editing genre * @return view for page for editing genre */ @GetMapping("/edit/{uuid}") fun showEdit(model: Model, @PathVariable("uuid") uuid: String): String { val genre = connector.get(uuid = uuid) return createFormView(model = model, genre = genreMapper.map(source = genre), title = "Edit genre", action = "edit") } /** * Process editing genre. * * @param model model * @param genre FO for genre * @param errors errors * @return view for redirect to page with list of genres (no errors) or view for page for editing genre (errors) * @throws IllegalArgumentException if UUID is null */ @PostMapping(value = ["/edit"], params = ["update"]) fun processEdit(model: Model, @ModelAttribute("genre") @Valid genre: GenreFO, errors: Errors): String { require(genre.uuid != null) { "UUID mustn't be null." } if (errors.hasErrors()) { return createFormView(model = model, genre = genre, title = "Edit genre", action = "edit") } connector.update(uuid = genre.uuid, request = genreMapper.mapRequest(source = genre)) return LIST_REDIRECT_URL } /** * Cancel editing genre. * * @return view for redirect to page with list of genres */ @PostMapping(value = ["/edit"], params = ["cancel"]) fun cancelEdit(): String { return LIST_REDIRECT_URL } /** * Process duplicating genre. * * @param uuid UUID of duplicating genre * @return view for redirect to page with list of genres */ @GetMapping("/duplicate/{uuid}") fun processDuplicate(@PathVariable("uuid") uuid: String): String { connector.duplicate(uuid = uuid) return LIST_REDIRECT_URL } /** * Process removing genre. * * @param uuid UUID of removing genre * @return view for redirect to page with list of genres */ @GetMapping("/remove/{uuid}") fun processRemove(@PathVariable("uuid") uuid: String): String { connector.remove(uuid = uuid) return LIST_REDIRECT_URL } /** * Shows page's view with list of genres. * * @param model model * @param filter FO for filter for names * @param page index of page * @return page's view with list of genres */ private fun createListView(model: Model, filter: NameFilterFO, page: Optional<Int>): String { val genreFilter = filterMapper.mapNameFilter(source = filter) genreFilter.page = page.orElse(1) genreFilter.limit = itemsPerPage val genres = connector.search(filter = genreFilter) model.addAttribute("genres", genres.data) model.addAttribute("totalPages", genres.pagesCount) model.addAttribute("currentPage", genres.pageNumber) model.addAttribute("filter", filter) model.addAttribute("query", filter.getQuery()) model.addAttribute("title", "Genres") model.addAttribute("statistics", connector.getStatistics()) return "genre/index" } /** * Returns page's view with form. * * @param model model * @param genre FO for genre * @param title page's title * @param action action * @return page's view with form */ private fun createFormView(model: Model, genre: GenreFO, title: String, action: String): String { model.addAttribute("genre", genre) model.addAttribute("title", title) model.addAttribute("action", action) return "genre/form" } companion object { /** * Redirect URL to list */ private const val LIST_REDIRECT_URL = "redirect:/genres" } }
mit
6cab93f63c36cd763dd183ff422413dc
30.770833
135
0.642623
4.295775
false
false
false
false
vhromada/Catalog
web/src/main/kotlin/com/github/vhromada/catalog/web/connector/impl/GameConnectorImpl.kt
1
4020
package com.github.vhromada.catalog.web.connector.impl import com.github.vhromada.catalog.common.entity.Page import com.github.vhromada.catalog.web.connector.GameConnector import com.github.vhromada.catalog.web.connector.common.ConnectorConfig import com.github.vhromada.catalog.web.connector.common.RestConnector import com.github.vhromada.catalog.web.connector.common.RestLoggingInterceptor import com.github.vhromada.catalog.web.connector.common.RestRequest import com.github.vhromada.catalog.web.connector.common.UserInterceptor import com.github.vhromada.catalog.web.connector.common.error.ResponseErrorHandler import com.github.vhromada.catalog.web.connector.entity.ChangeGameRequest import com.github.vhromada.catalog.web.connector.entity.Game import com.github.vhromada.catalog.web.connector.entity.GameStatistics import com.github.vhromada.catalog.web.connector.filter.NameFilter import org.springframework.core.ParameterizedTypeReference import org.springframework.http.HttpMethod import org.springframework.stereotype.Component import org.springframework.web.util.UriComponentsBuilder /** * A class represents implementation of connector for games. * * @author Vladimir Hromada */ @Component("gameConnector") class GameConnectorImpl( /** * Configuration for connector */ connectorConfig: ConnectorConfig, /** * Error handler */ errorHandler: ResponseErrorHandler, /** * Interceptor for logging */ loggingInterceptor: RestLoggingInterceptor, /** * Interceptor for processing header X-User */ userInterceptor: UserInterceptor ) : RestConnector( system = "CatalogWebSpring", config = connectorConfig, errorHandler = errorHandler, loggingInterceptor = loggingInterceptor, userInterceptor = userInterceptor ), GameConnector { override fun search(filter: NameFilter): Page<Game> { val url = UriComponentsBuilder.fromUriString(getUrl()) filter.createUrl(builder = url) return exchange(request = RestRequest(method = HttpMethod.GET, url = url.build().toUriString(), parameterizedType = object : ParameterizedTypeReference<Page<Game>>() {})) .throwExceptionIfAny() .get() } override fun get(uuid: String): Game { return exchange(request = RestRequest(method = HttpMethod.GET, url = getUrl(uuid = uuid), responseType = Game::class.java)) .throwExceptionIfAny() .get() } override fun add(request: ChangeGameRequest): Game { return exchange(request = RestRequest(method = HttpMethod.PUT, url = getUrl(), entity = request, responseType = Game::class.java)) .throwExceptionIfAny() .get() } override fun update(uuid: String, request: ChangeGameRequest): Game { return exchange(request = RestRequest(method = HttpMethod.POST, url = getUrl(uuid = uuid), entity = request, responseType = Game::class.java)) .throwExceptionIfAny() .get() } override fun remove(uuid: String) { exchange(request = RestRequest(method = HttpMethod.DELETE, url = getUrl(uuid = uuid), responseType = Unit::class.java)) .throwExceptionIfAny() } override fun duplicate(uuid: String): Game { return exchange(request = RestRequest(method = HttpMethod.POST, url = "${getUrl(uuid = uuid)}/duplicate", responseType = Game::class.java)) .throwExceptionIfAny() .get() } override fun getStatistics(): GameStatistics { return exchange(request = RestRequest(method = HttpMethod.GET, url = "${getUrl()}/statistics", responseType = GameStatistics::class.java)) .throwExceptionIfAny() .get() } override fun getUrl(): String { return super.getUrl() + "/rest/games" } /** * Returns URL UUID. * * @param uuid UUID * @return URL for UUID */ private fun getUrl(uuid: String): String { return "${getUrl()}/${uuid}" } }
mit
34b0cd7fdc37fe7bba20f5ca6ac24123
36.222222
178
0.699005
4.658169
false
true
false
false
JetBrains/intellij-community
platform/external-system-api/src/com/intellij/openapi/externalSystem/model/serialization.kt
1
3570
// 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.openapi.externalSystem.model import com.intellij.diagnostic.PluginException import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.externalSystem.ExternalSystemManager import com.intellij.openapi.externalSystem.service.project.ProjectDataManager import com.intellij.serialization.NonDefaultConstructorInfo import com.intellij.serialization.ReadConfiguration import com.intellij.serialization.WriteConfiguration // do not use SkipNullAndEmptySerializationFilter for now because can lead to issues fun createCacheWriteConfiguration() = WriteConfiguration(allowAnySubTypes = true) private fun createDataClassResolver(log: Logger): (name: String, hostObject: DataNode<*>?) -> Class<*>? { val projectDataManager = ProjectDataManager.getInstance() val managerClassLoaders = ExternalSystemManager.EP_NAME.lazySequence() .map { it.javaClass.classLoader } .toSet() return fun(name: String, hostObject: DataNode<*>?): Class<*>? { var classLoadersToSearch = managerClassLoaders val services = if (hostObject == null) emptyList() else projectDataManager!!.findService(hostObject.key) if (!services.isNullOrEmpty()) { val set = LinkedHashSet<ClassLoader>(managerClassLoaders.size + services.size) set.addAll(managerClassLoaders) services.mapTo(set) { it.javaClass.classLoader } classLoadersToSearch = set } var pe: PluginException? = null for (classLoader in classLoadersToSearch) { try { return classLoader.loadClass(name) } catch (e: PluginException) { pe?.let(e::addSuppressed) pe = e } catch (_: ClassNotFoundException) { } } log.warn("Cannot find class `$name`", pe) throw pe ?: return null } } @JvmOverloads fun createCacheReadConfiguration(log: Logger, testOnlyClassLoader: ClassLoader? = null): ReadConfiguration { val dataNodeResolver = if (testOnlyClassLoader == null) createDataClassResolver(log) else null return createDataNodeReadConfiguration(fun(name: String, hostObject: Any): Class<*>? { return when { hostObject !is DataNode<*> -> { val hostObjectClass = hostObject.javaClass try { hostObjectClass.classLoader.loadClass(name) } catch (e: ClassNotFoundException) { log.debug("cannot find class $name using class loader of class ${hostObjectClass.name} (classLoader=${hostObjectClass.classLoader})", e) // let's try system manager class loaders dataNodeResolver?.invoke(name, null) ?: throw e } } dataNodeResolver == null -> testOnlyClassLoader!!.loadClass(name) else -> dataNodeResolver(name, hostObject) } }) } fun createDataNodeReadConfiguration(loadClass: ((name: String, hostObject: Any) -> Class<*>?)): ReadConfiguration { return ReadConfiguration(allowAnySubTypes = true, resolvePropertyMapping = { beanClass -> when (beanClass.name) { "org.jetbrains.kotlin.idea.configuration.KotlinTargetData" -> NonDefaultConstructorInfo(listOf("externalName"), beanClass.getDeclaredConstructor(String::class.java)) "org.jetbrains.kotlin.idea.configuration.KotlinAndroidSourceSetData" -> NonDefaultConstructorInfo(listOf("sourceSetInfos"), beanClass.constructors.first()) else -> null } }, loadClass = loadClass, beanConstructed = { if (it is ProjectSystemId) { it.intern() } else { it } }) }
apache-2.0
3b5302baaa7eb2bee0f7b6d66b122485
41.011765
171
0.722689
4.785523
false
true
false
false
google/iosched
test-shared/src/main/java/com/google/samples/apps/iosched/test/data/TestData.kt
3
12196
/* * 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.samples.apps.iosched.test.data import com.google.samples.apps.iosched.model.Announcement import com.google.samples.apps.iosched.model.Block import com.google.samples.apps.iosched.model.Codelab import com.google.samples.apps.iosched.model.ConferenceData import com.google.samples.apps.iosched.model.ConferenceDay import com.google.samples.apps.iosched.model.Moment import com.google.samples.apps.iosched.model.Room import com.google.samples.apps.iosched.model.Session import com.google.samples.apps.iosched.model.Speaker import com.google.samples.apps.iosched.model.Tag import com.google.samples.apps.iosched.model.reservations.ReservationRequestResult import com.google.samples.apps.iosched.model.reservations.ReservationRequestResult.ReservationRequestStatus.RESERVE_DENIED_CUTOFF import com.google.samples.apps.iosched.model.reservations.ReservationRequestResult.ReservationRequestStatus.RESERVE_DENIED_UNKNOWN import com.google.samples.apps.iosched.model.reservations.ReservationRequestResult.ReservationRequestStatus.RESERVE_SUCCEEDED import com.google.samples.apps.iosched.model.reservations.ReservationRequestResult.ReservationRequestStatus.RESERVE_WAITLISTED import com.google.samples.apps.iosched.model.userdata.UserEvent import com.google.samples.apps.iosched.model.userdata.UserEvent.ReservationStatus.NONE import com.google.samples.apps.iosched.model.userdata.UserSession import org.threeten.bp.ZonedDateTime /** * Test data for unit tests. */ object TestData { private const val CONFERENCE_DAY1_START = "2019-05-07T07:00:00-07:00" private const val CONFERENCE_DAY1_END = "2019-05-07T22:00:01-07:00" private const val CONFERENCE_DAY2_END = "2019-05-08T22:00:01-07:00" private const val CONFERENCE_DAY2_START = "2019-05-08T08:00:00-07:00" private const val CONFERENCE_DAY3_END = "2019-05-09T22:00:00-07:00" private const val CONFERENCE_DAY3_START = "2019-05-09T08:00:00-07:00" val TestConferenceDays = listOf( ConferenceDay( ZonedDateTime.parse(CONFERENCE_DAY1_START), ZonedDateTime.parse(CONFERENCE_DAY1_END) ), ConferenceDay( ZonedDateTime.parse(CONFERENCE_DAY2_START), ZonedDateTime.parse(CONFERENCE_DAY2_END) ), ConferenceDay( ZonedDateTime.parse(CONFERENCE_DAY3_START), ZonedDateTime.parse(CONFERENCE_DAY3_END) ) ) // region Declarations val androidTag = Tag("1", Tag.CATEGORY_TOPIC, "track_android", 0, "Android", 0xFFAED581.toInt()) val cloudTag = Tag("2", Tag.CATEGORY_TOPIC, "track_cloud", 1, "Cloud", 0xFFFFF176.toInt()) val webTag = Tag("3", Tag.CATEGORY_TOPIC, "track_web", 2, "Web", 0xFFFFF176.toInt()) val sessionsTag = Tag("101", Tag.CATEGORY_TYPE, "type_sessions", 0, "Sessions", 0) val codelabsTag = Tag("102", Tag.CATEGORY_TYPE, "type_codelabs", 1, "Codelabs", 0) val beginnerTag = Tag("201", Tag.CATEGORY_LEVEL, "level_beginner", 0, "Beginner", 0) val intermediateTag = Tag("202", Tag.CATEGORY_LEVEL, "level_intermediate", 1, "Intermediate", 0) val advancedTag = Tag("203", Tag.CATEGORY_LEVEL, "level_advanced", 2, "Advanced", 0) val themeTag = Tag("301", Tag.CATEGORY_THEME, "theme_future", 0, "THE FUTURE", 0) val tagsList = listOf( androidTag, cloudTag, webTag, sessionsTag, codelabsTag, beginnerTag, intermediateTag, advancedTag, themeTag ) val speaker1 = Speaker( id = "1", name = "Troy McClure", imageUrl = "", company = "", biography = "" ) val speaker2 = Speaker( id = "2", name = "Disco Stu", imageUrl = "", company = "", biography = "" ) val speaker3 = Speaker( id = "3", name = "Hans Moleman", imageUrl = "", company = "", biography = "" ) val room = Room(id = "1", name = "Tent 1") val session0 = Session( id = "0", title = "Session 0", description = "This session is awesome", startTime = TestConferenceDays[0].start, endTime = TestConferenceDays[0].end, isLivestream = false, room = room, sessionUrl = "", youTubeUrl = "", photoUrl = "", doryLink = "", tags = listOf(androidTag, webTag, sessionsTag), displayTags = listOf(androidTag, webTag), speakers = setOf(speaker1), relatedSessions = emptySet() ) val session1 = Session( id = "1", title = "Session 1", description = "", startTime = TestConferenceDays[0].start, endTime = TestConferenceDays[0].end, isLivestream = false, room = room, sessionUrl = "", youTubeUrl = "", photoUrl = "", doryLink = "", tags = listOf(androidTag, cloudTag, codelabsTag), displayTags = listOf(androidTag, webTag), speakers = setOf(speaker2), relatedSessions = emptySet() ) val session2 = Session( id = "2", title = "Session 2", description = "", startTime = TestConferenceDays[1].start, endTime = TestConferenceDays[1].end, isLivestream = false, room = room, sessionUrl = "", youTubeUrl = "", photoUrl = "", doryLink = "", tags = listOf(androidTag, sessionsTag, beginnerTag), displayTags = listOf(androidTag), speakers = setOf(speaker3), relatedSessions = emptySet() ) val session3 = Session( id = "3", title = "Session 3", description = "", startTime = TestConferenceDays[2].start, endTime = TestConferenceDays[2].end, isLivestream = false, room = room, sessionUrl = "", youTubeUrl = "", photoUrl = "", doryLink = "", tags = listOf(webTag, sessionsTag, intermediateTag), displayTags = listOf(webTag), speakers = setOf(speaker1, speaker2), relatedSessions = emptySet() ) val sessionWithYoutubeUrl = Session( id = "4", title = "Session 4", description = "", startTime = TestConferenceDays[2].start.plusMinutes(1), endTime = TestConferenceDays[2].end, isLivestream = true, room = room, sessionUrl = "", youTubeUrl = "\"https://www.youtube.com/watch?v=dQw4w9WgXcQ\"", photoUrl = "", doryLink = "", tags = listOf(webTag, advancedTag), displayTags = listOf(webTag), speakers = setOf(speaker1), relatedSessions = emptySet() ) val sessionsList = listOf(session0, session1, session2, session3, sessionWithYoutubeUrl) val sessionIDs = sessionsList.map { it.id }.toList() val block1 = Block( title = "Keynote", type = "keynote", color = 0xffff00ff.toInt(), startTime = TestConferenceDays[0].start, endTime = TestConferenceDays[0].start.plusHours(1L) ) val block2 = Block( title = "Breakfast", type = "meal", color = 0xffff00ff.toInt(), startTime = TestConferenceDays[0].start.plusHours(1L), endTime = TestConferenceDays[0].start.plusHours(2L) ) val agenda = listOf(block1, block2) private val userEvent0 = UserEvent( sessionIDs[0], isStarred = false, isReviewed = false, reservationStatus = UserEvent.ReservationStatus.RESERVED, reservationRequestResult = ReservationRequestResult( RESERVE_SUCCEEDED, "123", System.currentTimeMillis() ) ) private val userEvent1 = UserEvent( sessionIDs[1], isStarred = true, isReviewed = true, reservationStatus = UserEvent.ReservationStatus.WAITLISTED, reservationRequestResult = ReservationRequestResult( RESERVE_WAITLISTED, "123", System.currentTimeMillis() ) ) private val userEvent2 = UserEvent( sessionIDs[2], isStarred = true, isReviewed = false, reservationStatus = NONE, reservationRequestResult = ReservationRequestResult( RESERVE_DENIED_CUTOFF, "123", System.currentTimeMillis() ) ) private val userEvent3 = UserEvent( sessionIDs[3], isStarred = false, isReviewed = true, reservationStatus = NONE, reservationRequestResult = ReservationRequestResult( RESERVE_DENIED_UNKNOWN, "123", System.currentTimeMillis() ) ) private val userEvent4 = UserEvent( sessionIDs[4], isStarred = false, isReviewed = true, reservationRequest = null ) val userSession0 = UserSession(session0, userEvent0) val userSession1 = UserSession(session1, userEvent1) val userSession2 = UserSession(session2, userEvent2) val userSession3 = UserSession(session3, userEvent3) val userSession4 = UserSession(sessionWithYoutubeUrl, userEvent4) val userSessionList = listOf( userSession0, userSession1, userSession2, userSession3, userSession4 ) val starredOrReservedSessions = listOf( userSession0, userSession1, userSession2 ) val userEvents = listOf(userEvent0, userEvent1, userEvent2, userEvent3, userEvent4) val codelab0 = Codelab( id = "codelab0", title = "Android is Cool", description = "Make Android apps in 5 minutes!", durationMinutes = 6, iconUrl = null, codelabUrl = "", sortPriority = 0, tags = listOf(androidTag) ) val codelab1 = Codelab( id = "codelab1", title = "HTML 6", description = "Webs aren't just for spiders anymore.", durationMinutes = 37, iconUrl = null, codelabUrl = "", sortPriority = 0, tags = listOf(webTag) ) val codelab2 = Codelab( id = "codelab2", title = "Martian Learning", description = "Machine Learning in Space", durationMinutes = 20, iconUrl = null, codelabUrl = "", sortPriority = 1, tags = listOf(cloudTag) ) val codelabs = listOf(codelab0, codelab1, codelab2) val codelabsSorted = listOf(codelab2, codelab0, codelab1) // endregion Declarations val conferenceData = ConferenceData( sessions = sessionsList, speakers = listOf(speaker1, speaker2, speaker3), rooms = listOf(room), codelabs = codelabs, tags = tagsList, version = 42 ) val feedItem1 = Announcement( id = "0", title = "Item 1", message = "", timestamp = TestConferenceDays[0].start, imageUrl = "", color = 0, category = "", priority = true, emergency = true ) val feedItem2 = Announcement( id = "1", title = "Item 2", message = "", timestamp = TestConferenceDays[0].end, imageUrl = "", color = 0, category = "", priority = true, emergency = false ) val feedItem3 = Announcement( id = "2", title = "Item 3", message = "", timestamp = TestConferenceDays[1].start, imageUrl = "", color = 0, category = "", priority = false, emergency = false ) val feedItem4 = Announcement( id = "3", title = "Item 4", message = "", timestamp = TestConferenceDays[1].end, imageUrl = "", color = 0, category = "", priority = false, emergency = false ) val announcements = listOf(feedItem1, feedItem2, feedItem3, feedItem4) val moment1 = Moment( id = "1", title = "KeyNote: Day 1", streamUrl = "https://www.youtube.com", startTime = TestConferenceDays[0].start, endTime = TestConferenceDays[0].end, textColor = 123, ctaType = Moment.CTA_LIVE_STREAM, imageUrl = "", imageUrlDarkTheme = "", attendeeRequired = false, timeVisible = false, featureId = "", featureName = "" ) val moments = listOf(moment1) }
apache-2.0
7e7c243f1e88dc3cec7cb091c98c265e
37.840764
130
0.650459
4.137042
false
true
false
false
nathanj/ogsdroid
app/src/main/java/com/ogsdroid/FindAGameFragment.kt
1
3216
package com.ogsdroid import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.app.AlertDialog import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ListView import com.ogs.Challenge import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable class FindAGameFragment : Fragment() { val subscribers = CompositeDisposable() override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { Log.d(TAG, "onCreateView") val activity = activity as TabbedActivity val rootView = inflater!!.inflate(R.layout.fragment_tabbed, container, false) val lv = rootView.findViewById<ListView>(R.id.my_listview) lv.adapter = activity.challengeAdapter lv.onItemClickListener = AdapterView.OnItemClickListener { adapterView, view, i, l -> val c = activity.challengeList[i] AlertDialog.Builder(activity) .setMessage(String.format("Are you sure you want to accept the challenge %s?", c)) .setCancelable(true) .setPositiveButton("Yes") { dialog, id -> acceptChallenge(c) } .setNegativeButton("No", null) .show() } return rootView } override fun onDestroy() { Log.d(TAG, "onDestroy") super.onDestroy() subscribers.clear() } fun acceptChallenge(c: Challenge) { subscribers.add(Globals.ogsService.acceptChallenge(c.challengeId) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { resp -> if (resp.game == 0) { AlertDialog.Builder(activity) .setMessage(String.format("Error accepting challenge. Maybe someone else accepted it first.")) .setCancelable(true) .setPositiveButton("Ok", null) .show() } else { val intent = Intent(activity, Main3Activity::class.java) intent.putExtra("id", resp.game) startActivity(intent) } }, { e -> Log.e(TAG, "error while accepting challenge", e) AlertDialog.Builder(activity) .setMessage(String.format("Error accepting challenge. Maybe someone else accepted it first.")) .setCancelable(true) .setPositiveButton("Ok", null) .show() }, { } )) } companion object { val TAG = "FindAGameFragment" } }
mit
f22caf110cf6bd4973f8f20d55487347
40.230769
134
0.531716
5.602787
false
false
false
false
pzhangleo/android-base
base/src/main/java/hope/base/utils/GzipUtil.kt
1
1316
@file:JvmName("GzipUtil") package hope.base.utils import java.io.BufferedReader import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.IOException import java.io.InputStreamReader import java.io.StringWriter import java.util.zip.GZIPInputStream import java.util.zip.GZIPOutputStream fun String.compress(): ByteArray? { try { ByteArrayOutputStream().use { baos -> GZIPOutputStream(baos).use { gzipOutput -> gzipOutput.write(this.toByteArray(Charsets.UTF_8)) gzipOutput.finish() return baos.toByteArray() } } } catch (e: IOException) { e.printStackTrace() return null } } fun ByteArray.decompress(): String? { try { GZIPInputStream(ByteArrayInputStream(this)).use { gzipInput -> StringWriter().use { val bf = BufferedReader(InputStreamReader(gzipInput, Charsets.UTF_8)) var result = "" var line = bf.readLine() while (!line.isNullOrEmpty()) { result += line line = bf.readLine() } return result } } } catch (e: IOException) { e.printStackTrace() return null } }
lgpl-3.0
64aaf3e953182b31f3cf60af938078a5
27.608696
85
0.580547
4.874074
false
false
false
false
bitsydarel/DBWeather
app/src/main/java/com/dbeginc/dbweather/articles/ArticlesFragment.kt
1
7301
/* * Copyright (C) 2017 Darel Bitsy * 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.dbeginc.dbweather.articles import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.databinding.DataBindingUtil import android.os.Bundle import android.support.design.widget.AppBarLayout import android.support.design.widget.Snackbar import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.view.ContextThemeWrapper import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bumptech.glide.integration.recyclerview.RecyclerViewPreloader import com.bumptech.glide.util.ViewPreloadSizeProvider import com.dbeginc.dbweather.R import com.dbeginc.dbweather.base.BaseFragment import com.dbeginc.dbweather.databinding.FragmentArticlesBinding import com.dbeginc.dbweather.utils.utility.LOADING_PERIOD import com.dbeginc.dbweather.utils.utility.goToArticleDetailScreen import com.dbeginc.dbweathercommon.utils.RequestState import com.dbeginc.dbweathercommon.view.MVMPVView import com.dbeginc.dbweathernews.articles.ArticlesViewModel import com.dbeginc.dbweathernews.viewmodels.ArticleModel /** * Created by darel on 10.10.17. * * Articles Page Fragment */ class ArticlesFragment : BaseFragment(), MVMPVView, ArticleActionBridge, SwipeRefreshLayout.OnRefreshListener, AppBarLayout.OnOffsetChangedListener { companion object { private const val NEWSPAPER_ID = "newspaper_id" private const val NEWSPAPER_NAME = "newspaper_name" private const val PRELOAD_AHEAD_ITEMS = 5 fun newInstance(newspaperId: String, newspaperName: String): ArticlesFragment { val fragment = ArticlesFragment() fragment.arguments = Bundle().apply { putString(NEWSPAPER_ID, newspaperId) putString(NEWSPAPER_NAME, newspaperName) } return fragment } } lateinit var newsPaperId: String private lateinit var newsPaperName: String private lateinit var binding: FragmentArticlesBinding private val sizeProvider = ViewPreloadSizeProvider<String>() private val viewModel: ArticlesViewModel by lazy { return@lazy ViewModelProviders.of(this, factory.get())[ArticlesViewModel::class.java] } private val preloader: RecyclerViewPreloader<String> by lazy { return@lazy RecyclerViewPreloader( this, articlesAdapter, sizeProvider, PRELOAD_AHEAD_ITEMS ) } private val articlesAdapter: ArticleAdapter by lazy { return@lazy ArticleAdapter(containerBridge = this, sizeProvider = sizeProvider) } private val articlesObserver: Observer<List<ArticleModel>> = Observer { articles -> articles?.let { articlesAdapter.updateData(newData = it) } } override val stateObserver: Observer<RequestState> = Observer { state -> state?.let { onStateChanged(state = it) } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel.getRequestState().observe(this, stateObserver) viewModel.getArticles().observe(this, articlesObserver) onRefresh() } override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) if (savedState == null) { newsPaperId = arguments!!.getString(NEWSPAPER_ID) newsPaperName = arguments!!.getString(NEWSPAPER_NAME) } else { newsPaperId = savedState.getString(NEWSPAPER_ID) newsPaperName = savedState.getString(NEWSPAPER_NAME) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(NEWSPAPER_ID, newsPaperId) outState.putString(NEWSPAPER_NAME, newsPaperName) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = DataBindingUtil.inflate( inflater.cloneInContext(ContextThemeWrapper(activity, R.style.AppTheme)), R.layout.fragment_articles, container, false ) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupView() } override fun goToArticleDetail(article: ArticleModel) { activity?.let { goToArticleDetailScreen( container = it, article = article ) } } override fun onRefresh() { if (preferences.get().isNewsTranslationOn()) viewModel.loadTranslatedArticles(newspaperId = newsPaperId, newspaperName = newsPaperName) else viewModel.loadArticles(newspaperId = newsPaperId, newspaperName = newsPaperName) } override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) { binding.articlesLayout.isEnabled = verticalOffset == 0 } override fun setupView() { binding.articlesLayout.setOnRefreshListener(this) binding.articlesList.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) binding.articlesList.adapter = articlesAdapter binding.articlesList.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) binding.articlesList.addOnScrollListener(preloader) binding.articlesLayout.isEnabled = false } override fun onStateChanged(state: RequestState) { when (state) { RequestState.LOADING -> binding.articlesLayout.postDelayed(this::showLoadingStatus, LOADING_PERIOD) RequestState.COMPLETED -> binding.articlesLayout.postDelayed(this::hideLoadingStatus, LOADING_PERIOD) RequestState.ERROR -> binding.articlesLayout.postDelayed(this::onRequestFailed, LOADING_PERIOD) } } override fun toString(): String = super.toString() + "@${arguments!!.getString(NEWSPAPER_ID)}" private fun showLoadingStatus() { binding.articlesLayout.isRefreshing = true } private fun hideLoadingStatus() { binding.articlesLayout.isRefreshing = false } private fun onRequestFailed() { hideLoadingStatus() Snackbar.make(binding.articlesLayout, R.string.error_could_not_load_articles, Snackbar.LENGTH_LONG) .setAction(R.string.retry) { viewModel.loadArticles(newspaperId = newsPaperId, newspaperName = newsPaperName) } .show() } }
gpl-3.0
e9286b3f68cc5bc045c8256e51591134
35.148515
149
0.71004
4.750163
false
false
false
false
code-helix/slatekit
src/ext/kotlin/slatekit-providers-kafka/src/main/kotlin/slatekit/providers/kafka/KafkaConstants.kt
1
461
package slatekit.providers.kafka object KafkaConstants { val LOCALHOST = "localhost" val KAFKA_ROOT = "kafka" val KAFKA_HOST = "$KAFKA_ROOT.hosts" val KAFKA_USERNAME = "$KAFKA_ROOT.username" val KAFKA_PASSWORD = "$KAFKA_ROOT.password" val SASL_ENABLED = "$KAFKA_ROOT.sasl.enabled" val KAFKA_FEATURE_ENABLED = "$KAFKA_ROOT.feature.enabled" }
apache-2.0
daf71b44441f804f9bc708aa68c59c65
41
66
0.559653
3.519084
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/data/IDb.kt
1
6828
package slatekit.common.data import org.threeten.bp.LocalDate import org.threeten.bp.LocalDateTime import org.threeten.bp.LocalTime import slatekit.common.DateTime import slatekit.common.DateTimes import slatekit.common.values.Record import java.sql.ResultSet /** * Interface to abstract away JDBC. * This is used for 2 purposes: * 1. Facilitate Unit Testing * 2. Facilitate support for the Entities / ORM ( SqlFramework ) project * to abstract away JDBC for Android */ interface IDb : ProcSupport { val errHandler: (Exception) -> Unit /** * JDBC driver */ val driver:String /** * registers the jdbc driver * * @return */ fun open(): IDb /** * Executes the sql provided */ fun execute(sql: String) /** * executes an insert using the sql or stored proc and gets the id * * @param sql : The sql or stored proc * @param inputs : The inputs for the sql or stored proc * @return : The id ( primary key ) */ fun insert(sql: String, inputs: List<Value>? = null): Long /** * executes an insert using the sql or stored proc and gets the id * * @param sql : The sql or stored proc * @param inputs : The inputs for the sql or stored proc * @return : The id ( primary key ) */ fun insertGetId(sql: String, inputs: List<Value>? = null): String /** * executes the update sql using prepared statements * * @param sql : The sql or stored proc * @param inputs : The inputs for the sql or stored proc * @return : The number of affected records */ fun update(sql: String, inputs: List<Value>? = null): Int /** * executes the update sql for stored proc * * @param sql : The sql or stored proc * @param inputs : The inputs for the sql or stored proc * @return : The number of affected records */ fun call(sql: String, inputs: List<Value>?): Int /** * Executes a sql query * @param sql : The sql to query * @param callback : The callback to handle the resultset * @param moveNext : Whether or not to automatically move the resultset to the next/first row * @param inputs : The parameters for the stored proc. The types will be auto-converted my-sql types. */ fun <T> query( sql: String, callback: (ResultSet) -> T?, moveNext: Boolean = true, inputs: List<Value>? = null ): T? /** * maps a single item using the sql supplied * * @param sql : The sql * @param mapper : THe mapper to map the item of type T * @tparam T : The type of the item * @return */ @Suppress("UNCHECKED_CAST") fun <T> mapOne(sql: String, inputs: List<Value>?, mapper: (Record) -> T?): T? /** * maps multiple items using the sql supplied * * @param sql : The sql * @param mapper : THe mapper to map the item of type T * @tparam T : The type of the item * @return */ @Suppress("UNCHECKED_CAST") fun <T> mapAll(sql: String, inputs: List<Value>?, mapper: (Record) -> T?): List<T>? fun errorHandler(ex: Exception) /** * gets a scalar string value using the sql provided * * @param sql : The sql text * @return */ fun <T> getScalar(sql: String, typ: DataType, inputs: List<Value>? = listOf()): T = getScalarOrNull<T>(sql, typ, inputs)!! /** * gets a scalar string value using the sql provided * * @param sql : The sql text * @return */ fun <T> getScalarOrNull(sql: String, typ: DataType, inputs: List<Value>? = listOf()): T? /** * gets a scalar bool value using the sql provided * * @param sql : The sql text * @return */ fun getScalarBool(sql: String, inputs: List<Value>? = listOf()): Boolean = getScalarOrNull(sql, DataType.DTBool, inputs) ?: false /** * gets a scalar string value using the sql provided * * @param sql : The sql text * @return */ fun getScalarString(sql: String, inputs: List<Value>? = listOf()): String = getScalarOrNull<String>(sql, DataType.DTString, inputs) ?: "" /** * gets a scalar int value using the sql provided * * @param sql : The sql text * @return */ fun getScalarShort(sql: String, inputs: List<Value>? = listOf()): Short = getScalarOrNull(sql, DataType.DTShort, inputs) ?: 0.toShort() /** * gets a scalar int value using the sql provided * * @param sql : The sql text * @return */ fun getScalarInt(sql: String, inputs: List<Value>? = listOf()): Int = getScalarOrNull(sql, DataType.DTInt, inputs) ?: 0 /** * gets a scalar long value using the sql provided * * @param sql : The sql text * @return */ fun getScalarLong(sql: String, inputs: List<Value>? = listOf()): Long = getScalarOrNull(sql, DataType.DTLong, inputs) ?: 0L /** * gets a scalar double value using the sql provided * * @param sql : The sql text * @return */ fun getScalarFloat(sql: String, inputs: List<Value>? = listOf()): Float = getScalarOrNull(sql, DataType.DTFloat, inputs) ?: 0.0f /** * gets a scalar double value using the sql provided * * @param sql : The sql text * @return */ fun getScalarDouble(sql: String, inputs: List<Value>? = listOf()): Double = getScalarOrNull(sql, DataType.DTDouble, inputs) ?: 0.0 /** * gets a scalar local date value using the sql provided * * @param sql : The sql text * @return */ fun getScalarLocalDate(sql: String, inputs: List<Value>? = listOf()): LocalDate = getScalarOrNull(sql, DataType.DTLocalDate, inputs) ?: LocalDate.MIN /** * gets a scalar local time value using the sql provided * * @param sql : The sql text * @return */ fun getScalarLocalTime(sql: String, inputs: List<Value>? = listOf()): LocalTime = getScalarOrNull(sql, DataType.DTLocalTime, inputs) ?: LocalTime.MIN /** * gets a scalar local datetime value using the sql provided * * @param sql : The sql text * @return */ fun getScalarLocalDateTime(sql: String, inputs: List<Value>? = listOf()): LocalDateTime = getScalarOrNull(sql, DataType.DTLocalDateTime, inputs) ?: LocalDateTime.MIN /** * gets a scalar local datetime value using the sql provided * * @param sql : The sql text * @return */ fun getScalarZonedDateTime(sql: String, inputs: List<Value>? = listOf()): DateTime = getScalarOrNull(sql, DataType.DTZonedDateTime, inputs) ?: DateTimes.MIN }
apache-2.0
da7452de3f75a74773cf91d3c56c0892
28.820961
105
0.600029
4.083732
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/arrays/primitiveArrays.kt
1
12210
// WITH_RUNTIME import kotlin.test.* fun box(): String { assertTrue(eqBoolean(booleanArrayOf(false), BooleanArray(1))) assertTrue(eqBoolean(booleanArrayOf(false, true, false), BooleanArray(3) { it % 2 != 0 })) assertTrue(eqBoolean(booleanArrayOf(true), booleanArrayOf(true).copyOf())) assertTrue(eqBoolean(booleanArrayOf(true, false), booleanArrayOf(true).copyOf(2))) assertTrue(eqBoolean(booleanArrayOf(true), booleanArrayOf(true, true).copyOf(1))) assertTrue(eqBoolean(booleanArrayOf(false, true), booleanArrayOf(false) + true)) assertTrue(eqBoolean(booleanArrayOf(false, true, false), booleanArrayOf(false) + listOf(true, false))) assertTrue(eqBoolean(booleanArrayOf(true, false), booleanArrayOf(false, true, false, true).copyOfRange(1, 3))) assertTrue(eqBoolean(booleanArrayOf(false, true, false, true), customBooleanArrayOf(false, *booleanArrayOf(true, false), true))) assertTrue(booleanArrayOf(true).iterator() is BooleanIterator) assertEquals(true, booleanArrayOf(true).iterator().nextBoolean()) assertEquals(true, booleanArrayOf(true).iterator().next()) assertFalse(booleanArrayOf().iterator().hasNext()) assertTrue(assertFails { booleanArrayOf().iterator().next() } is NoSuchElementException) assertTrue(eqByte(byteArrayOf(0), ByteArray(1))) assertTrue(eqByte(byteArrayOf(1, 2, 3), ByteArray(3) { (it + 1).toByte() })) assertTrue(eqByte(byteArrayOf(1), byteArrayOf(1).copyOf())) assertTrue(eqByte(byteArrayOf(1, 0), byteArrayOf(1).copyOf(2))) assertTrue(eqByte(byteArrayOf(1), byteArrayOf(1, 2).copyOf(1))) assertTrue(eqByte(byteArrayOf(1, 2), byteArrayOf(1) + 2)) assertTrue(eqByte(byteArrayOf(1, 2, 3), byteArrayOf(1) + listOf(2.toByte(), 3.toByte()))) assertTrue(eqByte(byteArrayOf(2, 3), byteArrayOf(1, 2, 3, 4).copyOfRange(1, 3))) assertTrue(eqByte(byteArrayOf(1, 2, 3, 4), customByteArrayOf(1.toByte(), *byteArrayOf(2, 3), 4.toByte()))) assertTrue(byteArrayOf(1).iterator() is ByteIterator) assertEquals(1, byteArrayOf(1).iterator().nextByte()) assertEquals(1, byteArrayOf(1).iterator().next()) assertFalse(byteArrayOf().iterator().hasNext()) assertTrue(assertFails { byteArrayOf().iterator().next() } is NoSuchElementException) assertTrue(eqShort(shortArrayOf(0), ShortArray(1))) assertTrue(eqShort(shortArrayOf(1, 2, 3), ShortArray(3) { (it + 1).toShort() })) assertTrue(eqShort(shortArrayOf(1), shortArrayOf(1).copyOf())) assertTrue(eqShort(shortArrayOf(1, 0), shortArrayOf(1).copyOf(2))) assertTrue(eqShort(shortArrayOf(1), shortArrayOf(1, 2).copyOf(1))) assertTrue(eqShort(shortArrayOf(1, 2), shortArrayOf(1) + 2)) assertTrue(eqShort(shortArrayOf(1, 2, 3), shortArrayOf(1) + listOf(2.toShort(), 3.toShort()))) assertTrue(eqShort(shortArrayOf(2, 3), shortArrayOf(1, 2, 3, 4).copyOfRange(1, 3))) assertTrue(eqShort(shortArrayOf(1, 2, 3, 4), customShortArrayOf(1.toShort(), *shortArrayOf(2, 3), 4.toShort()))) assertTrue(shortArrayOf(1).iterator() is ShortIterator) assertEquals(1, shortArrayOf(1).iterator().nextShort()) assertEquals(1, shortArrayOf(1).iterator().next()) assertFalse(shortArrayOf().iterator().hasNext()) assertTrue(assertFails { shortArrayOf().iterator().next() } is NoSuchElementException) assertTrue(eqChar(charArrayOf(0.toChar()), CharArray(1))) assertTrue(eqChar(charArrayOf('a', 'b', 'c'), CharArray(3) { 'a' + it })) assertTrue(eqChar(charArrayOf('a'), charArrayOf('a').copyOf())) assertTrue(eqChar(charArrayOf('a', 0.toChar()), charArrayOf('a').copyOf(2))) assertTrue(eqChar(charArrayOf('a'), charArrayOf('a', 'b').copyOf(1))) assertTrue(eqChar(charArrayOf('a', 'b'), charArrayOf('a') + 'b')) assertTrue(eqChar(charArrayOf('a', 'b', 'c'), charArrayOf('a') + listOf('b', 'c'))) assertTrue(eqChar(charArrayOf('b', 'c'), charArrayOf('a', 'b', 'c', 'd').copyOfRange(1, 3))) assertTrue(eqChar(charArrayOf('a', 'b', 'c', 'd'), customCharArrayOf('a', *charArrayOf('b', 'c'), 'd'))) assertTrue(charArrayOf('a').iterator() is CharIterator) assertEquals('a', charArrayOf('a').iterator().nextChar()) assertEquals('a', charArrayOf('a').iterator().next()) assertFalse(charArrayOf().iterator().hasNext()) assertTrue(assertFails { charArrayOf().iterator().next() } is NoSuchElementException) assertTrue(eqInt(intArrayOf(0), IntArray(1))) assertTrue(eqInt(intArrayOf(1, 2, 3), IntArray(3) { it + 1 })) assertTrue(eqInt(intArrayOf(1), intArrayOf(1).copyOf())) assertTrue(eqInt(intArrayOf(1, 0), intArrayOf(1).copyOf(2))) assertTrue(eqInt(intArrayOf(1), intArrayOf(1, 2).copyOf(1))) assertTrue(eqInt(intArrayOf(1, 2), intArrayOf(1) + 2)) assertTrue(eqInt(intArrayOf(1, 2, 3), intArrayOf(1) + listOf(2, 3))) assertTrue(eqInt(intArrayOf(2, 3), intArrayOf(1, 2, 3, 4).copyOfRange(1, 3))) assertTrue(eqInt(intArrayOf(1, 2, 3, 4), customIntArrayOf(1, *intArrayOf(2, 3), 4))) assertTrue(intArrayOf(1).iterator() is IntIterator) assertEquals(1, intArrayOf(1).iterator().nextInt()) assertEquals(1, intArrayOf(1).iterator().next()) assertFalse(intArrayOf().iterator().hasNext()) assertTrue(assertFails { intArrayOf().iterator().next() } is NoSuchElementException) assertTrue(eqFloat(floatArrayOf(0f), FloatArray(1))) assertTrue(eqFloat(floatArrayOf(1f, 2f, 3f), FloatArray(3) { (it + 1).toFloat() })) assertTrue(eqFloat(floatArrayOf(1f), floatArrayOf(1f).copyOf())) assertTrue(eqFloat(floatArrayOf(1f, 0f), floatArrayOf(1f).copyOf(2))) assertTrue(eqFloat(floatArrayOf(1f), floatArrayOf(1f, 2f).copyOf(1))) assertTrue(eqFloat(floatArrayOf(1f, 2f), floatArrayOf(1f) + 2f)) assertTrue(eqFloat(floatArrayOf(1f, 2f, 3f), floatArrayOf(1f) + listOf(2f, 3f))) assertTrue(eqFloat(floatArrayOf(2f, 3f), floatArrayOf(1f, 2f, 3f, 4f).copyOfRange(1, 3))) assertTrue(eqFloat(floatArrayOf(1f, 2f, 3f, 4f), customFloatArrayOf(1f, *floatArrayOf(2f, 3f), 4f))) assertTrue(floatArrayOf(1f).iterator() is FloatIterator) assertEquals(1f, floatArrayOf(1f).iterator().nextFloat()) assertEquals(1f, floatArrayOf(1f).iterator().next()) assertFalse(floatArrayOf().iterator().hasNext()) assertTrue(assertFails { floatArrayOf().iterator().next() } is NoSuchElementException) assertTrue(eqDouble(doubleArrayOf(0.0), DoubleArray(1))) assertTrue(eqDouble(doubleArrayOf(1.0, 2.0, 3.0), DoubleArray(3) { (it + 1).toDouble() })) assertTrue(eqDouble(doubleArrayOf(1.0), doubleArrayOf(1.0).copyOf())) assertTrue(eqDouble(doubleArrayOf(1.0, 0.0), doubleArrayOf(1.0).copyOf(2))) assertTrue(eqDouble(doubleArrayOf(1.0), doubleArrayOf(1.0, 2.0).copyOf(1))) assertTrue(eqDouble(doubleArrayOf(1.0, 2.0), doubleArrayOf(1.0) + 2.0)) assertTrue(eqDouble(doubleArrayOf(1.0, 2.0, 3.0), doubleArrayOf(1.0) + listOf(2.0, 3.0))) assertTrue(eqDouble(doubleArrayOf(2.0, 3.0), doubleArrayOf(1.0, 2.0, 3.0, 4.0).copyOfRange(1, 3))) assertTrue(eqDouble(doubleArrayOf(1.0, 2.0, 3.0, 4.0), customDoubleArrayOf(1.0, *doubleArrayOf(2.0, 3.0), 4.0))) assertTrue(doubleArrayOf(1.0).iterator() is DoubleIterator) assertEquals(1.0, doubleArrayOf(1.0).iterator().nextDouble()) assertEquals(1.0, doubleArrayOf(1.0).iterator().next()) assertFalse(doubleArrayOf().iterator().hasNext()) assertTrue(assertFails { doubleArrayOf().iterator().next() } is NoSuchElementException) assertTrue(eqLong(longArrayOf(0), LongArray(1))) assertTrue(eqLong(longArrayOf(1, 2, 3), LongArray(3) { it + 1L })) assertTrue(eqLong(longArrayOf(1), longArrayOf(1).copyOf())) assertTrue(eqLong(longArrayOf(1, 0), longArrayOf(1).copyOf(2))) assertTrue(eqLong(longArrayOf(1), longArrayOf(1, 2).copyOf(1))) assertTrue(eqLong(longArrayOf(1, 2), longArrayOf(1) + 2)) assertTrue(eqLong(longArrayOf(1, 2, 3), longArrayOf(1) + listOf(2L, 3L))) assertTrue(eqLong(longArrayOf(2, 3), longArrayOf(1, 2, 3, 4).copyOfRange(1, 3))) assertTrue(eqLong(longArrayOf(1, 2, 3, 4), customLongArrayOf(1L, *longArrayOf(2, 3), 4L))) assertTrue(longArrayOf(1).iterator() is LongIterator) assertEquals(1L, longArrayOf(1).iterator().nextLong()) assertEquals(1L, longArrayOf(1).iterator().next()) assertFalse(longArrayOf().iterator().hasNext()) assertTrue(assertFails { longArrayOf().iterator().next() } is NoSuchElementException) // If `is` checks work... if (intArrayOf() is IntArray) { assertTrue(booleanArrayOf(false) is BooleanArray) assertTrue(byteArrayOf(0) is ByteArray) assertTrue(shortArrayOf(0) is ShortArray) assertTrue(charArrayOf('a') is CharArray) assertTrue(intArrayOf(0) is IntArray) assertTrue(floatArrayOf(0f) is FloatArray) assertTrue(doubleArrayOf(0.0) is DoubleArray) assertTrue(longArrayOf(0) is LongArray) } // Rhino `instanceof` fails to distinguish TypedArray's if (intArrayOf() is IntArray && (byteArrayOf() as Any) !is IntArray) { assertTrue(checkExactArrayType(booleanArrayOf(false), booleanArray = true)) assertTrue(checkExactArrayType(byteArrayOf(0), byteArray = true)) assertTrue(checkExactArrayType(shortArrayOf(0), shortArray = true)) assertTrue(checkExactArrayType(charArrayOf('a'), charArray = true)) assertTrue(checkExactArrayType(intArrayOf(0), intArray = true)) assertTrue(checkExactArrayType(floatArrayOf(0f), floatArray = true)) assertTrue(checkExactArrayType(doubleArrayOf(0.0), doubleArray = true)) assertTrue(checkExactArrayType(longArrayOf(0), longArray = true)) assertTrue(checkExactArrayType(arrayOf<Any?>(), array = true)) } return "OK" } fun eqBoolean(expected: BooleanArray, actual: BooleanArray): Boolean = actual.size == expected.size && actual.foldIndexed(true) { i, r, v -> r && expected[i] == v } fun eqByte(expected: ByteArray, actual: ByteArray): Boolean = actual.size == expected.size && actual.foldIndexed(true) { i, r, v -> r && expected[i] == v } fun eqShort(expected: ShortArray, actual: ShortArray): Boolean = actual.size == expected.size && actual.foldIndexed(true) { i, r, v -> r && expected[i] == v } fun eqChar(expected: CharArray, actual: CharArray): Boolean = actual.size == expected.size && actual.foldIndexed(true) { i, r, v -> r && expected[i] == v } fun eqInt(expected: IntArray, actual: IntArray): Boolean = actual.size == expected.size && actual.foldIndexed(true) { i, r, v -> r && expected[i] == v } fun eqLong(expected: LongArray, actual: LongArray): Boolean = actual.size == expected.size && actual.foldIndexed(true) { i, r, v -> r && expected[i] == v } fun eqFloat(expected: FloatArray, actual: FloatArray): Boolean = actual.size == expected.size && actual.foldIndexed(true) { i, r, v -> r && expected[i] == v } fun eqDouble(expected: DoubleArray, actual: DoubleArray): Boolean = actual.size == expected.size && actual.foldIndexed(true) { i, r, v -> r && expected[i] == v } fun customBooleanArrayOf(vararg arr: Boolean): BooleanArray = arr fun customByteArrayOf(vararg arr: Byte): ByteArray = arr fun customShortArrayOf(vararg arr: Short): ShortArray = arr fun customCharArrayOf(vararg arr: Char): CharArray = arr fun customIntArrayOf(vararg arr: Int): IntArray = arr fun customFloatArrayOf(vararg arr: Float): FloatArray = arr fun customDoubleArrayOf(vararg arr: Double): DoubleArray = arr fun customLongArrayOf(vararg arr: Long): LongArray = arr fun checkExactArrayType( a: Any?, booleanArray: Boolean = false, byteArray: Boolean = false, shortArray: Boolean = false, charArray: Boolean = false, intArray: Boolean = false, longArray: Boolean = false, floatArray: Boolean = false, doubleArray: Boolean = false, array: Boolean = false ): Boolean { return a is BooleanArray == booleanArray && a is ByteArray == byteArray && a is ShortArray == shortArray && a is CharArray == charArray && a is IntArray == intArray && a is LongArray == longArray && a is FloatArray == floatArray && a is DoubleArray == doubleArray && a is Array<*> == array }
apache-2.0
982e28b87c8f29b19b79826f2bf1b1d5
62.26943
164
0.6914
3.808484
false
false
false
false
windchopper/password-drop
src/main/kotlin/com/github/windchopper/tools/password/drop/book/Book.kt
1
5354
@file:Suppress("unused", "UNUSED_PARAMETER") package com.github.windchopper.tools.password.drop.book import com.github.windchopper.tools.password.drop.Application import com.github.windchopper.tools.password.drop.crypto.CryptoEngine import jakarta.xml.bind.Unmarshaller import jakarta.xml.bind.annotation.* import java.nio.file.Path import java.util.* @XmlAccessorType(XmlAccessType.FIELD) abstract class BookPart { @XmlAttribute var name: String? = null abstract val type: String? override fun toString(): String { return name?:"?" } } abstract class InternalBookPart<ParentType>: BookPart() where ParentType: BookPart { @XmlTransient var parent: ParentType? = null abstract fun removeFromParent() } @XmlType @XmlAccessorType(XmlAccessType.FIELD) class Page: InternalBookPart<Book>() { @XmlTransient override val type: String? = Application.messages["page.type"] @XmlElement(name = "paragraph") var paragraphs: MutableList<Paragraph> = ArrayList() fun newParagraph(): Paragraph { return Paragraph() .also { paragraphs.add(it) it.name = Application.messages["paragraph.unnamed"] it.parent = this } } fun afterUnmarshal(unmarshaller: Unmarshaller, parent: Any) { this.parent = parent as Book } override fun removeFromParent() { parent?.pages?.remove(this) } } @XmlType @XmlAccessorType(XmlAccessType.FIELD) class Paragraph: InternalBookPart<Page>() { @XmlTransient override val type: String? = Application.messages["paragraph.type"] @XmlElement(name = "word") var phrases: MutableList<Phrase> = ArrayList() fun afterUnmarshal(unmarshaller: Unmarshaller, parent: Any) { this.parent = parent as Page } fun newPhrase(): Phrase { return Phrase() .also { phrases.add(it) it.name = Application.messages["phrase.unnamed"] it.parent = this } } override fun removeFromParent() { parent?.paragraphs?.remove(this) } } @XmlType @XmlAccessorType(XmlAccessType.FIELD) class Phrase: InternalBookPart<Paragraph>() { companion object { const val ENCRYPTED_PREFIX = "{ENCRYPTED}" } @XmlTransient override val type: String? = Application.messages["phrase.type"] @XmlElement var text: String? = null get() = field?.let { return field ?.let { text -> val cleanText = if (text.startsWith(ENCRYPTED_PREFIX)) { text.substring(ENCRYPTED_PREFIX.length) } else { text } parent?.parent?.parent?.cryptoEngine ?.decrypt(cleanText) ?:throw RuntimeException(Application.messages["error.couldNotDecrypt"]) } } set(value) { field = value ?.let { text -> parent?.parent?.parent?.cryptoEngine ?.let { encryptEngine -> ENCRYPTED_PREFIX + encryptEngine.encrypt(text) } ?:text } } fun afterUnmarshal(unmarshaller: Unmarshaller, parent: Any) { this.parent = parent as Paragraph } override fun removeFromParent() { parent?.phrases?.remove(this) } } @XmlType @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) open class Book: BookPart() { @XmlTransient override val type: String? = Application.messages["book.type"] @XmlAttribute(name = "salt") @XmlSchemaType(name = "base64Binary") var saltRaw: ByteArray? = null @XmlElement(name = "page") var pages: MutableList<Page> = ArrayList() @XmlTransient var path: Path? = null @XmlTransient var cryptoEngine: CryptoEngine? = null @XmlTransient var dirty: Boolean = false fun newPage(): Page { return Page() .also { pages.add(it) it.name = Application.messages["page.unnamed"] it.parent = this } } open fun copy(bookSupplier: () -> Book): Book { return bookSupplier.invoke().also { newBook -> newBook.name = name newBook.saltRaw = saltRaw pages.forEach { page -> newBook.pages.add(Page().also { newPage -> newPage.parent = newBook newPage.name = page.name page.paragraphs.forEach { paragraph -> newPage.paragraphs.add(Paragraph().also { newParagraph -> newParagraph.parent = newPage newParagraph.name = paragraph.name paragraph.phrases.forEach { phrase -> newParagraph.phrases.add(Phrase().also { newPhrase -> newPhrase.parent = newParagraph newPhrase.name = phrase.name newPhrase.text = phrase.text }) } }) } }) } } } }
apache-2.0
622e16fb7111a1fc5e965a6129011361
29.947977
101
0.556593
4.858439
false
false
false
false
JuliusKunze/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/StaticData.kt
1
6881
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.backend.konan.llvm import llvm.* import org.jetbrains.kotlin.backend.konan.Context import org.jetbrains.kotlin.ir.expressions.IrConst import org.jetbrains.kotlin.types.KotlinType /** * Provides utilities to create static data. */ internal class StaticData(override val context: Context): ContextUtils { /** * Represents the LLVM global variable. */ class Global private constructor(val staticData: StaticData, val llvmGlobal: LLVMValueRef) { companion object { private fun createLlvmGlobal(module: LLVMModuleRef, type: LLVMTypeRef, name: String, isExported: Boolean ): LLVMValueRef { if (isExported && LLVMGetNamedGlobal(module, name) != null) { throw IllegalArgumentException("Global '$name' already exists") } // Globals created with this API are *not* thread local. val llvmGlobal = LLVMAddGlobal(module, type, name)!! if (!isExported) { LLVMSetLinkage(llvmGlobal, LLVMLinkage.LLVMInternalLinkage) } return llvmGlobal } fun create(staticData: StaticData, type: LLVMTypeRef, name: String, isExported: Boolean): Global { val module = staticData.context.llvmModule val isUnnamed = (name == "") // LLVM will select the unique index and represent the global as `@idx`. if (isUnnamed && isExported) { throw IllegalArgumentException("unnamed global can't be exported") } val llvmGlobal = createLlvmGlobal(module!!, type, name, isExported) return Global(staticData, llvmGlobal) } } val type get() = getGlobalType(this.llvmGlobal) fun setInitializer(value: ConstValue) { LLVMSetInitializer(llvmGlobal, value.llvm) } fun setZeroInitializer() { LLVMSetInitializer(llvmGlobal, LLVMConstNull(this.type)!!) } fun setConstant(value: Boolean) { LLVMSetGlobalConstant(llvmGlobal, if (value) 1 else 0) } fun setLinkage(value: LLVMLinkage) { LLVMSetLinkage(llvmGlobal, value) } fun setAlignment(value: Int) { LLVMSetAlignment(llvmGlobal, value) } fun setSection(name: String) { LLVMSetSection(llvmGlobal, name) } val pointer = Pointer.to(this) } /** * Represents the pointer to static data. * It can be a pointer to either a global or any its element. * * TODO: this class is probably should be implemented more optimally */ class Pointer private constructor(val global: Global, private val delegate: ConstPointer, val offsetInGlobal: Long) : ConstPointer by delegate { companion object { fun to(global: Global) = Pointer(global, constPointer(global.llvmGlobal), 0L) } private fun getElementOffset(index: Int): Long { val llvmTargetData = global.staticData.llvmTargetData val type = LLVMGetElementType(delegate.llvmType) return when (LLVMGetTypeKind(type)) { LLVMTypeKind.LLVMStructTypeKind -> LLVMOffsetOfElement(llvmTargetData, type, index) LLVMTypeKind.LLVMArrayTypeKind -> LLVMABISizeOfType(llvmTargetData, LLVMGetElementType(type)) * index else -> TODO() } } override fun getElementPtr(index: Int): Pointer { return Pointer(global, delegate.getElementPtr(index), offsetInGlobal + this.getElementOffset(index)) } /** * @return the distance from other pointer to this. * * @throws UnsupportedOperationException if it is not possible to represent the distance as [Int] value */ fun sub(other: Pointer): Int { if (this.global != other.global) { throw UnsupportedOperationException("pointers must belong to the same global") } val res = this.offsetInGlobal - other.offsetInGlobal if (res.toInt().toLong() != res) { throw UnsupportedOperationException("result doesn't fit into Int") } return res.toInt() } } /** * Creates [Global] with given type and name. * * It is external until explicitly initialized with [Global.setInitializer]. */ fun createGlobal(type: LLVMTypeRef, name: String, isExported: Boolean = false): Global { return Global.create(this, type, name, isExported) } /** * Creates [Global] with given name and value. */ fun placeGlobal(name: String, initializer: ConstValue, isExported: Boolean = false): Global { val global = createGlobal(initializer.llvmType, name, isExported) global.setInitializer(initializer) return global } /** * Creates array-typed global with given name and value. */ fun placeGlobalArray(name: String, elemType: LLVMTypeRef?, elements: List<ConstValue>): Global { val initializer = ConstArray(elemType, elements) val global = placeGlobal(name, initializer) return global } private val stringLiterals = mutableMapOf<String, ConstPointer>() private val cStringLiterals = mutableMapOf<String, ConstPointer>() fun cStringLiteral(value: String) = cStringLiterals.getOrPut(value) { placeCStringLiteral(value) } fun kotlinStringLiteral(value: String) = stringLiterals.getOrPut(value) { createKotlinStringLiteral(value) } } /** * Creates static instance of `konan.ImmutableByteArray` with given values of elements. * * @param args data for constant creation. */ internal fun StaticData.createImmutableBinaryBlob(value: IrConst<String>): LLVMValueRef { val args = value.value.map { Int8(it.toByte()).llvm } return createKotlinArray(context.ir.symbols.immutableBinaryBlob.descriptor.defaultType, args) }
apache-2.0
02259639ca1a0cf1b0e7f568d27a5073
35.221053
117
0.625345
4.907989
false
false
false
false
thanksmister/androidthings-mqtt-alarm-panel
app/src/main/java/com/thanksmister/iot/mqtt/alarmpanel/ui/modules/CameraModule.kt
1
6941
package com.thanksmister.iot.mqtt.alarmpanel.ui.modules import android.annotation.SuppressLint import android.arch.lifecycle.Lifecycle import android.arch.lifecycle.LifecycleObserver import android.arch.lifecycle.OnLifecycleEvent import android.content.Context import android.content.ContextWrapper import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.ImageFormat import android.graphics.Matrix import android.hardware.camera2.* import android.hardware.camera2.CameraAccessException.CAMERA_ERROR import android.media.ImageReader import android.os.Handler import android.view.SurfaceHolder import android.view.SurfaceView import com.thanksmister.iot.mqtt.alarmpanel.R import timber.log.Timber import android.hardware.camera2.CameraCharacteristics import android.hardware.camera2.CameraManager import android.util.Rational /** * Module to take photo and email when alarm is disabled if camera available. */ class CameraModule(base: Context?, private var backgroundHandler: Handler, private var callback: CallbackListener?) : ContextWrapper(base), LifecycleObserver { private var mImageReader: ImageReader? = null private var mCameraDevice: CameraDevice? = null private var mCaptureSession: CameraCaptureSession? = null private var hasCamera:Boolean = false private var rotation:Float = 0f private var cameraId:String? = null interface CallbackListener { fun onCameraComplete(bitmap: Bitmap) fun onCameraException(message: String) } //TODO(we need to implement permission dialog for Android) @OnLifecycleEvent(Lifecycle.Event.ON_START) @SuppressLint("MissingPermission") fun onStart() { val manager = getSystemService(Context.CAMERA_SERVICE) as CameraManager val camIds: Array<String> try { camIds = manager.cameraIdList } catch (e: CameraAccessException) { Timber.e("Cam access exception getting ids: " + e.message) hasCamera = false return } if (camIds.isEmpty()) { Timber.e("No cameras found") hasCamera = false return } cameraId = camIds[0] mImageReader = ImageReader.newInstance(IMAGE_WIDTH, IMAGE_HEIGHT, ImageFormat.JPEG, MAX_IMAGES) mImageReader?.setOnImageAvailableListener(imageAvailableListener, backgroundHandler) try { manager.openCamera(cameraId, mStateCallback, backgroundHandler) hasCamera = true; } catch (cae: Exception) { Timber.d("Camera access exception" + cae) if(callback != null) { callback!!.onCameraException("Camera access exception" + cae); } hasCamera = false; } } private val imageAvailableListener = ImageReader.OnImageAvailableListener { reader -> val image = reader.acquireLatestImage() val imageBuffer = image.planes[0].buffer val imageBytes = ByteArray(imageBuffer.remaining()) imageBuffer.get(imageBytes) image.close() val bitmap = getBitmapFromByteArray(imageBytes) callback?.onCameraComplete(bitmap); } fun takePicture(rotation: Float) { this.rotation = rotation; Timber.d("takePicture mCameraDevice" + mCameraDevice) if(hasCamera) { mCameraDevice?.createCaptureSession( arrayListOf(mImageReader?.surface), mSessionCallback, null) } } // TODO this had to be moved to background thread private fun getBitmapFromByteArray(imageBytes: ByteArray): Bitmap { val bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size) val matrix = Matrix() matrix.postRotate(rotation) return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true) } private fun triggerImageCapture() { if(hasCamera) { val captureBuilder = mCameraDevice?.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE) captureBuilder?.addTarget(mImageReader!!.surface) captureBuilder?.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON) captureBuilder?.set(CaptureRequest.CONTROL_AWB_MODE, CaptureRequest.CONTROL_AWB_MODE_AUTO) mCaptureSession?.capture(captureBuilder?.build(), mCaptureCallback, null) } } private val mCaptureCallback = object : CameraCaptureSession.CaptureCallback() { override fun onCaptureProgressed(session: CameraCaptureSession?, request: CaptureRequest?, partialResult: CaptureResult?) { Timber.d("Partial result") } override fun onCaptureFailed(session: CameraCaptureSession?, request: CaptureRequest?, failure: CaptureFailure?) { Timber.d("Capture session failed") if(callback != null) { callback!!.onCameraException(getString(R.string.text_camera_failed_session)); } } override fun onCaptureCompleted(session: CameraCaptureSession?, request: CaptureRequest?, result: TotalCaptureResult?) { session?.close() mCaptureSession = null Timber.d("Capture session closed") } } private val mSessionCallback = object : CameraCaptureSession.StateCallback() { override fun onConfigureFailed(cameraCaptureSession: CameraCaptureSession?) { Timber.d("Failed to configure camera") callback!!.onCameraException(getString(R.string.text_camera_failed_configuration)); } override fun onConfigured(cameraCaptureSession: CameraCaptureSession?) { if (mCameraDevice == null) { return } mCaptureSession = cameraCaptureSession triggerImageCapture() } } private val mStateCallback = object : CameraDevice.StateCallback() { override fun onError(cameraDevice: CameraDevice, code: Int) { Timber.d("Camera device error, closing") cameraDevice.close() callback!!.onCameraException(getString(R.string.text_error_camera_device)); } override fun onOpened(cameraDevice: CameraDevice) { Timber.d("Opened camera.") mCameraDevice = cameraDevice } override fun onDisconnected(cameraDevice: CameraDevice) { Timber.d("Camera disconnected, closing") cameraDevice.close() } override fun onClosed(camera: CameraDevice) { Timber.d("Closed camera, releasing") mCameraDevice = null } } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun stop() { mCameraDevice?.close() } companion object InstanceHolder { val IMAGE_WIDTH = 640 val IMAGE_HEIGHT = 480 val MAX_IMAGES = 1 } }
apache-2.0
5caebcbfd85500442b935a049f1b56b5
36.322581
159
0.668924
5.096182
false
false
false
false
codeka/wwmmo
client/src/main/kotlin/au/com/codeka/warworlds/client/util/eventbus/EventHandlerInfo.kt
1
1980
package au.com.codeka.warworlds.client.util.eventbus import au.com.codeka.warworlds.client.concurrency.Threads import au.com.codeka.warworlds.common.Log import java.lang.ref.WeakReference import java.lang.reflect.Method /** * Holds all the details about a single event handler. */ internal class EventHandlerInfo(private val eventClass: Class<*>, private val method: Method, subscriber: Any, callOnThread: Threads) { private val subscriber: WeakReference<*> private val callOnThread: Threads private var registerCount: Int fun handles(event: Any?): Boolean { return eventClass.isInstance(event) } fun register(): Int { return ++registerCount } fun unregister(): Int { return --registerCount } /** Gets the subscriber object, may be null. */ fun getSubscriber(): Any? { return subscriber.get() } /** * Calls the subscriber's method with the given event object, on the UI thread if needed. */ fun call(event: Any?) { val callLocation = Exception("Location of EventHandlerInfo.call()") val runnable = Runnable { val subscriber = subscriber.get() if (subscriber != null) { try { method.invoke(subscriber, event) } catch (e: Exception) { log.error("Exception caught handling event.", e) log.error("Call location.", callLocation) } } } // If it's meant to run on the current thread (and *not* a background thread) then just run it // directly. If it's meant to run on a background thread, we'll want it to run on a *different* // background thread. if (callOnThread.isCurrentThread && callOnThread != Threads.BACKGROUND) { runnable.run() } else { callOnThread.run(runnable) } } companion object { private val log = Log("EventHandlerInfo") } init { this.subscriber = WeakReference(subscriber) this.callOnThread = callOnThread registerCount = 1 } }
mit
db9ac9888c83aa328ea2f3c0ac4a58f4
27.710145
110
0.662626
4.304348
false
false
false
false
android/compose-samples
JetNews/app/src/main/java/com/example/jetnews/data/posts/impl/PostsData.kt
1
41694
/* * 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. */ @file:Suppress("ktlint:max-line-length") // String constants read better package com.example.jetnews.data.posts.impl import com.example.jetnews.R import com.example.jetnews.model.Markup import com.example.jetnews.model.MarkupType import com.example.jetnews.model.Metadata import com.example.jetnews.model.Paragraph import com.example.jetnews.model.ParagraphType import com.example.jetnews.model.Post import com.example.jetnews.model.PostAuthor import com.example.jetnews.model.PostsFeed import com.example.jetnews.model.Publication /** * Define hardcoded posts to avoid handling any non-ui operations. */ val pietro = PostAuthor("Pietro Maggi", "https://medium.com/@pmaggi") val manuel = PostAuthor("Manuel Vivo", "https://medium.com/@manuelvicnt") val florina = PostAuthor( "Florina Muntenescu", "https://medium.com/@florina.muntenescu" ) val jose = PostAuthor("Jose Alcérreca", "https://medium.com/@JoseAlcerreca") val publication = Publication( "Android Developers", "https://cdn-images-1.medium.com/max/258/1*[email protected]" ) val paragraphsPost1 = listOf( Paragraph( ParagraphType.Text, "Working to make our Android application more modular, I ended up with a sample that included a set of on-demand features grouped inside a folder:" ), Paragraph( ParagraphType.Text, "Pretty standard setup, all the on-demand modules, inside a “features” folder; clean." ), Paragraph( ParagraphType.Text, "These modules are included in the settings.gradle file as:" ), Paragraph( ParagraphType.CodeBlock, "include ':app'\n" + "include ':features:module1'\n" + "include ':features:module2'\n" + "include ':features:module3'\n" + "include ':features:module4'" ), Paragraph( ParagraphType.Text, "These setup works nicely with a single “minor” issue: an empty module named features in the Android view in Android Studio:" ), Paragraph( ParagraphType.Text, "I can live with that, but I would much prefer to remove that empty module from my project!" ), Paragraph( ParagraphType.Header, "If you cannot remove it, just rename it!" ), Paragraph( ParagraphType.Text, "At I/O I was lucky enough to attend the “Android Studio: Tips and Tricks” talk where Ivan Gravilovic, from Google, shared some amazing tips. One of these was a possible solution for my problem: setting a custom path for my modules.", listOf( Markup( MarkupType.Italic, 41, 72 ) ) ), Paragraph( ParagraphType.Text, "In this particular case our settings.gradle becomes:", listOf(Markup(MarkupType.Code, 28, 43)) ), Paragraph( ParagraphType.CodeBlock, """ include ':app' include ':module1' include ':module1' include ':module1' include ':module1' """.trimIndent() ), Paragraph( ParagraphType.CodeBlock, """ // Set a custom path for the four features modules. // This avoid to have an empty "features" module in Android Studio. project(":module1").projectDir=new File(rootDir, "features/module1") project(":module2").projectDir=new File(rootDir, "features/module2") project(":module3").projectDir=new File(rootDir, "features/module3") project(":module4").projectDir=new File(rootDir, "features/module4") """.trimIndent() ), Paragraph( ParagraphType.Text, "And the layout in Android Studio is now:" ), Paragraph( ParagraphType.Header, "Conclusion" ), Paragraph( ParagraphType.Text, "As the title says, this is really a small thing, but it helps keep my project in order and it shows how a small Gradle configuration can help keep your project tidy." ), Paragraph( ParagraphType.Quote, "You can find this update in the latest version of the on-demand modules codelab.", listOf( Markup( MarkupType.Link, 54, 79, "https://codelabs.developers.google.com/codelabs/on-demand-dynamic-delivery/index.html" ) ) ), Paragraph( ParagraphType.Header, "Resources" ), Paragraph( ParagraphType.Bullet, "Android Studio: Tips and Tricks (Google I/O’19)", listOf( Markup( MarkupType.Link, 0, 47, "https://www.youtube.com/watch?v=ihF-PwDfRZ4&list=PLWz5rJ2EKKc9FfSQIRXEWyWpHD6TtwxMM&index=32&t=0s" ) ) ), Paragraph( ParagraphType.Bullet, "On Demand module codelab", listOf( Markup( MarkupType.Link, 0, 24, "https://codelabs.developers.google.com/codelabs/on-demand-dynamic-delivery/index.html" ) ) ), Paragraph( ParagraphType.Bullet, "Patchwork Plaid — A modularization story", listOf( Markup( MarkupType.Link, 0, 40, "https://medium.com/androiddevelopers/a-patchwork-plaid-monolith-to-modularized-app-60235d9f212e" ) ) ) ) val paragraphsPost2 = listOf( Paragraph( ParagraphType.Text, "Dagger is a popular Dependency Injection framework commonly used in Android. It provides fully static and compile-time dependencies addressing many of the development and performance issues that have reflection-based solutions.", listOf( Markup( MarkupType.Link, 0, 6, "https://dagger.dev/" ) ) ), Paragraph( ParagraphType.Text, "This month, a new tutorial was released to help you better understand how it works. This article focuses on using Dagger with Kotlin, including best practices to optimize your build time and gotchas you might encounter.", listOf( Markup( MarkupType.Link, 14, 26, "https://dagger.dev/tutorial/" ), Markup(MarkupType.Bold, 114, 132), Markup(MarkupType.Bold, 144, 159), Markup(MarkupType.Bold, 191, 198) ) ), Paragraph( ParagraphType.Text, "Dagger is implemented using Java’s annotations model and annotations in Kotlin are not always directly parallel with how equivalent Java code would be written. This post will highlight areas where they differ and how you can use Dagger with Kotlin without having a headache." ), Paragraph( ParagraphType.Text, "This post was inspired by some of the suggestions in this Dagger issue that goes through best practices and pain points of Dagger in Kotlin. Thanks to all of the contributors that commented there!", listOf( Markup( MarkupType.Link, 58, 70, "https://github.com/google/dagger/issues/900" ) ) ), Paragraph( ParagraphType.Header, "kapt build improvements" ), Paragraph( ParagraphType.Text, "To improve your build time, Dagger added support for gradle’s incremental annotation processing in v2.18! This is enabled by default in Dagger v2.24. In case you’re using a lower version, you need to add a few lines of code (as shown below) if you want to benefit from it.", listOf( Markup( MarkupType.Link, 99, 104, "https://github.com/google/dagger/releases/tag/dagger-2.18" ), Markup( MarkupType.Link, 143, 148, "https://github.com/google/dagger/releases/tag/dagger-2.24" ), Markup(MarkupType.Bold, 53, 95) ) ), Paragraph( ParagraphType.Text, "Also, you can tell Dagger not to format the generated code. This option was added in Dagger v2.18 and it’s the default behavior (doesn’t generate formatted code) in v2.23. If you’re using a lower version, disable code formatting to improve your build time (see code below).", listOf( Markup( MarkupType.Link, 92, 97, "https://github.com/google/dagger/releases/tag/dagger-2.18" ), Markup( MarkupType.Link, 165, 170, "https://github.com/google/dagger/releases/tag/dagger-2.23" ) ) ), Paragraph( ParagraphType.Text, "Include these compiler arguments in your build.gradle file to make Dagger more performant at build time:", listOf(Markup(MarkupType.Code, 41, 53)) ), Paragraph( ParagraphType.Text, "Alternatively, if you use Kotlin DSL script files, include them like this in the build.gradle.kts file of the modules that use Dagger:", listOf(Markup(MarkupType.Code, 81, 97)) ), Paragraph( ParagraphType.Text, "Qualifiers for field attributes" ), Paragraph( ParagraphType.Text, "", listOf(Markup(MarkupType.Link, 0, 0)) ), Paragraph( ParagraphType.Text, "When an annotation is placed on a property in Kotlin, it’s not clear whether Java will see that annotation on the field of the property or the method for that property. Setting the field: prefix on the annotation ensures that the qualifier ends up in the right place (See documentation for more details).", listOf( Markup(MarkupType.Code, 181, 187), Markup( MarkupType.Link, 268, 285, "http://frogermcs.github.io/dependency-injection-with-dagger-2-custom-scopes/" ), Markup(MarkupType.Italic, 114, 119), Markup(MarkupType.Italic, 143, 149) ) ), Paragraph( ParagraphType.Text, "✅ The way to apply qualifiers on an injected field is:" ), Paragraph( ParagraphType.CodeBlock, "@Inject @field:MinimumBalance lateinit var minimumBalance: BigDecimal", listOf(Markup(MarkupType.Bold, 8, 29)) ), Paragraph( ParagraphType.Text, "❌ As opposed to:" ), Paragraph( ParagraphType.CodeBlock, """ @Inject @MinimumBalance lateinit var minimumBalance: BigDecimal // @MinimumBalance is ignored! """.trimIndent(), listOf(Markup(MarkupType.Bold, 65, 95)) ), Paragraph( ParagraphType.Text, "Forgetting to add field: could lead to injecting the wrong object if there’s an unqualified instance of that type available in the Dagger graph.", listOf(Markup(MarkupType.Code, 18, 24)) ), Paragraph( ParagraphType.Header, "Static @Provides functions optimization" ), Paragraph( ParagraphType.Text, "Dagger’s generated code will be more performant if @Provides methods are static. To achieve this in Kotlin, use a Kotlin object instead of a class and annotate your methods with @JvmStatic. This is a best practice that you should follow as much as possible.", listOf( Markup(MarkupType.Code, 51, 60), Markup(MarkupType.Code, 73, 79), Markup(MarkupType.Code, 121, 127), Markup(MarkupType.Code, 141, 146), Markup(MarkupType.Code, 178, 188), Markup(MarkupType.Bold, 200, 213), Markup(MarkupType.Italic, 200, 213) ) ), Paragraph( ParagraphType.Text, "In case you need an abstract method, you’ll need to add the @JvmStatic method to a companion object and annotate it with @Module too.", listOf( Markup(MarkupType.Code, 60, 70), Markup(MarkupType.Code, 121, 128) ) ), Paragraph( ParagraphType.Text, "Alternatively, you can extract the object module out and include it in the abstract one:" ), Paragraph( ParagraphType.Header, "Injecting Generics" ), Paragraph( ParagraphType.Text, "Kotlin compiles generics with wildcards to make Kotlin APIs work with Java. These are generated when a type appears as a parameter (more info here) or as fields. For example, a Kotlin List<Foo> parameter shows up as List<? super Foo> in Java.", listOf( Markup(MarkupType.Code, 184, 193), Markup(MarkupType.Code, 216, 233), Markup( MarkupType.Link, 132, 146, "https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#variant-generics" ) ) ), Paragraph( ParagraphType.Text, "This causes problems with Dagger because it expects an exact (aka invariant) type match. Using @JvmSuppressWildcards will ensure that Dagger sees the type without wildcards.", listOf( Markup(MarkupType.Code, 95, 116), Markup( MarkupType.Link, 66, 75, "https://en.wikipedia.org/wiki/Class_invariant" ), Markup( MarkupType.Link, 96, 116, "https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/-jvm-suppress-wildcards/index.html" ) ) ), Paragraph( ParagraphType.Text, "This is a common issue when you inject collections using Dagger’s multibinding feature, for example:", listOf( Markup( MarkupType.Link, 57, 86, "https://dagger.dev/multibindings.html" ) ) ), Paragraph( ParagraphType.CodeBlock, """ class MyVMFactory @Inject constructor( private val vmMap: Map<String, @JvmSuppressWildcards Provider<ViewModel>> ) { ... } """.trimIndent(), listOf(Markup(MarkupType.Bold, 72, 93)) ), Paragraph( ParagraphType.Header, "Inline method bodies" ), Paragraph( ParagraphType.Text, "Dagger determines the types that are configured by @Provides methods by inspecting the return type. Specifying the return type in Kotlin functions is optional and even the IDE sometimes encourages you to refactor your code to have inline method bodies that hide the return type declaration.", listOf(Markup(MarkupType.Code, 51, 60)) ), Paragraph( ParagraphType.Text, "This can lead to bugs if the inferred type is different from the one you meant. Let’s see some examples:" ), Paragraph( ParagraphType.Text, "If you want to add a specific type to the graph, inlining works as expected. See the different ways to do the same in Kotlin:" ), Paragraph( ParagraphType.Text, "If you want to provide an implementation of an interface, then you must explicitly specify the return type. Not doing it can lead to problems and bugs:" ), Paragraph( ParagraphType.Text, "Dagger mostly works with Kotlin out of the box. However, you have to watch out for a few things just to make sure you’re doing what you really mean to do: @field: for qualifiers on field attributes, inline method bodies, and @JvmSuppressWildcards when injecting collections.", listOf( Markup(MarkupType.Code, 155, 162), Markup(MarkupType.Code, 225, 246) ) ), Paragraph( ParagraphType.Text, "Dagger optimizations come with no cost, add them and follow best practices to improve your build time: enabling incremental annotation processing, disabling formatting and using static @Provides methods in your Dagger modules.", listOf( Markup( MarkupType.Code, 185, 194 ) ) ) ) val paragraphsPost3 = listOf( Paragraph( ParagraphType.Text, "Learn how to get started converting Java Programming Language code to Kotlin, making it more idiomatic and avoid common pitfalls, by following our new Refactoring to Kotlin codelab, available in English \uD83C\uDDEC\uD83C\uDDE7, Chinese \uD83C\uDDE8\uD83C\uDDF3 and Brazilian Portuguese \uD83C\uDDE7\uD83C\uDDF7.", listOf( Markup( MarkupType.Link, 151, 172, "https://codelabs.developers.google.com/codelabs/java-to-kotlin/#0" ), Markup( MarkupType.Link, 209, 216, "https://clmirror.storage.googleapis.com/codelabs/java-to-kotlin-zh/index.html#0" ), Markup( MarkupType.Link, 226, 246, "https://codelabs.developers.google.com/codelabs/java-to-kotlin-pt-br/#0" ) ) ), Paragraph( ParagraphType.Text, "When you first get started writing Kotlin code, you tend to follow Java Programming Language idioms. The automatic converter, part of both Android Studio and Intellij IDEA, can do a pretty good job of automatically refactoring your code, but sometimes, it needs a little help. This is where our new Refactoring to Kotlin codelab comes in.", listOf( Markup( MarkupType.Link, 105, 124, "https://www.jetbrains.com/help/idea/converting-a-java-file-to-kotlin-file.html" ) ) ), Paragraph( ParagraphType.Text, "We’ll take two classes (a User and a Repository) in Java Programming Language and convert them to Kotlin, check out what the automatic converter did and why. Then we go to the next level — make it idiomatic, teaching best practices and useful tips along the way.", listOf( Markup(MarkupType.Code, 26, 30), Markup(MarkupType.Code, 37, 47) ) ), Paragraph( ParagraphType.Text, "The Refactoring to Kotlin codelab starts with basic topics — understand how nullability is declared in Kotlin, what types of equality are defined or how to best handle classes whose role is just to hold data. We then continue with how to handle static fields and functions in Kotlin and how to apply the Singleton pattern, with the help of one handy keyword: object. We’ll see how Kotlin helps us model our classes better, how it differentiates between a property of a class and an action the class can do. Finally, we’ll learn how to execute code only in the context of a specific object with the scope functions.", listOf( Markup(MarkupType.Code, 245, 251), Markup(MarkupType.Code, 359, 365), Markup( MarkupType.Link, 4, 25, "https://codelabs.developers.google.com/codelabs/java-to-kotlin/#0" ) ) ), Paragraph( ParagraphType.Text, "Thanks to Walmyr Carvalho and Nelson Glauber for translating the codelab in Brazilian Portuguese!", listOf( Markup( MarkupType.Link, 21, 42, "https://codelabs.developers.google.com/codelabs/java-to-kotlin/#0" ) ) ), Paragraph( ParagraphType.Text, "", listOf( Markup( MarkupType.Link, 76, 96, "https://codelabs.developers.google.com/codelabs/java-to-kotlin-pt-br/#0" ) ) ) ) val paragraphsPost4 = listOf( Paragraph( ParagraphType.Text, "TL;DR: Expose resource IDs from ViewModels to avoid showing obsolete data." ), Paragraph( ParagraphType.Text, "In a ViewModel, if you’re exposing data coming from resources (strings, drawables, colors…), you have to take into account that ViewModel objects ignore configuration changes such as locale changes. When the user changes their locale, activities are recreated but the ViewModel objects are not.", listOf( Markup( MarkupType.Bold, 183, 197 ) ) ), Paragraph( ParagraphType.Text, "AndroidViewModel is a subclass of ViewModel that is aware of the Application context. However, having access to a context can be dangerous if you’re not observing or reacting to the lifecycle of that context. The recommended practice is to avoid dealing with objects that have a lifecycle in ViewModels.", listOf( Markup(MarkupType.Code, 0, 16), Markup(MarkupType.Code, 34, 43), Markup(MarkupType.Bold, 209, 303) ) ), Paragraph( ParagraphType.Text, "Let’s look at an example based on this issue in the tracker: Updating ViewModel on system locale change.", listOf( Markup( MarkupType.Link, 61, 103, "https://issuetracker.google.com/issues/111961971" ), Markup(MarkupType.Italic, 61, 104) ) ), Paragraph( ParagraphType.Text, "The problem is that the string is resolved in the constructor only once. If there’s a locale change, the ViewModel won’t be recreated. This will result in our app showing obsolete data and therefore being only partially localized.", listOf(Markup(MarkupType.Bold, 73, 133)) ), Paragraph( ParagraphType.Text, "As Sergey points out in the comments to the issue, the recommended approach is to expose the ID of the resource you want to load and do so in the view. As the view (activity, fragment, etc.) is lifecycle-aware it will be recreated after a configuration change so the resource will be reloaded correctly.", listOf( Markup( MarkupType.Link, 3, 9, "https://twitter.com/ZelenetS" ), Markup( MarkupType.Link, 28, 36, "https://issuetracker.google.com/issues/111961971#comment2" ), Markup(MarkupType.Bold, 82, 150) ) ), Paragraph( ParagraphType.Text, "Even if you don’t plan to localize your app, it makes testing much easier and cleans up your ViewModel objects so there’s no reason not to future-proof." ), Paragraph( ParagraphType.Text, "We fixed this issue in the android-architecture repository in the Java and Kotlin branches and we offloaded resource loading to the Data Binding layout.", listOf( Markup( MarkupType.Link, 66, 70, "https://github.com/googlesamples/android-architecture/pull/631" ), Markup( MarkupType.Link, 75, 81, "https://github.com/googlesamples/android-architecture/pull/635" ), Markup( MarkupType.Link, 128, 151, "https://github.com/googlesamples/android-architecture/pull/635/files#diff-7eb5d85ec3ea4e05ecddb7dc8ae20aa1R62" ) ) ) ) val paragraphsPost5 = listOf( Paragraph( ParagraphType.Text, "Working with collections is a common task and the Kotlin Standard Library offers many great utility functions. It also offers two ways of working with collections based on how they’re evaluated: eagerly — with Collections, and lazily — with Sequences. Continue reading to find out what’s the difference between the two, which one you should use and when, and what the performance implications of each are.", listOf( Markup(MarkupType.Code, 210, 220), Markup(MarkupType.Code, 241, 249), Markup( MarkupType.Link, 210, 221, "https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/index.html" ), Markup( MarkupType.Link, 241, 250, "https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/index.html" ), Markup(MarkupType.Bold, 130, 134), Markup(MarkupType.Bold, 195, 202), Markup(MarkupType.Bold, 227, 233), Markup(MarkupType.Italic, 130, 134) ) ), Paragraph( ParagraphType.Header, "Collections vs sequences" ), Paragraph( ParagraphType.Text, "The difference between eager and lazy evaluation lies in when each transformation on the collection is performed.", listOf( Markup( MarkupType.Italic, 57, 61 ) ) ), Paragraph( ParagraphType.Text, "Collections are eagerly evaluated — each operation is performed when it’s called and the result of the operation is stored in a new collection. The transformations on collections are inline functions. For example, looking at how map is implemented, we can see that it’s an inline function, that creates a new ArrayList:", listOf( Markup(MarkupType.Code, 229, 232), Markup(MarkupType.Code, 273, 279), Markup(MarkupType.Code, 309, 318), Markup( MarkupType.Link, 183, 199, "https://kotlinlang.org/docs/reference/inline-functions.html" ), Markup( MarkupType.Link, 229, 232, "https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/common/src/generated/_Collections.kt#L1312" ), Markup(MarkupType.Bold, 0, 12), Markup(MarkupType.Italic, 16, 23) ) ), Paragraph( ParagraphType.CodeBlock, "public inline fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R> {\n" + " return mapTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)\n" + "}", listOf( Markup(MarkupType.Bold, 7, 13), Markup(MarkupType.Bold, 88, 97) ) ), Paragraph( ParagraphType.Text, "Sequences are lazily evaluated. They have two types of operations: intermediate and terminal. Intermediate operations are not performed on the spot; they’re just stored. Only when a terminal operation is called, the intermediate operations are triggered on each element in a row and finally, the terminal operation is applied. Intermediate operations (like map, distinct, groupBy etc) return another sequence whereas terminal operations (like first, toList, count etc) don’t.", listOf( Markup(MarkupType.Code, 357, 360), Markup(MarkupType.Code, 362, 370), Markup(MarkupType.Code, 372, 379), Markup(MarkupType.Code, 443, 448), Markup(MarkupType.Code, 450, 456), Markup(MarkupType.Code, 458, 463), Markup(MarkupType.Bold, 0, 9), Markup(MarkupType.Bold, 67, 79), Markup(MarkupType.Bold, 84, 92), Markup(MarkupType.Bold, 254, 269), Markup(MarkupType.Italic, 14, 20) ) ), Paragraph( ParagraphType.Text, "Sequences don’t hold a reference to the items of the collection. They’re created based on the iterator of the original collection and keep a reference to all the intermediate operations that need to be performed." ), Paragraph( ParagraphType.Text, "Unlike transformations on collections, intermediate transformations on sequences are not inline functions — inline functions cannot be stored and sequences need to store them. Looking at how an intermediate operation like map is implemented, we can see that the transform function is kept in a new instance of a Sequence:", listOf( Markup(MarkupType.Code, 222, 225), Markup(MarkupType.Code, 312, 320), Markup( MarkupType.Link, 222, 225, "https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/common/src/generated/_Sequences.kt#L860" ) ) ), Paragraph( ParagraphType.CodeBlock, "public fun <T, R> Sequence<T>.map(transform: (T) -> R): Sequence<R>{ \n" + " return TransformingSequence(this, transform)\n" + "}", listOf(Markup(MarkupType.Bold, 85, 105)) ), Paragraph( ParagraphType.Text, "A terminal operation, like first, iterates through the elements of the sequence until the predicate condition is matched.", listOf( Markup(MarkupType.Code, 27, 32), Markup( MarkupType.Link, 27, 32, "https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/common/src/generated/_Sequences.kt#L117" ) ) ), Paragraph( ParagraphType.CodeBlock, "public inline fun <T> Sequence<T>.first(predicate: (T) -> Boolean): T {\n" + " for (element in this) if (predicate(element)) return element\n" + " throw NoSuchElementException(“Sequence contains no element matching the predicate.”)\n" + "}" ), Paragraph( ParagraphType.Text, "If we look at how a sequence like TransformingSequence (used in the map above) is implemented, we’ll see that when next is called on the sequence iterator, the transformation stored is also applied.", listOf( Markup(MarkupType.Code, 34, 54), Markup(MarkupType.Code, 68, 71) ) ), Paragraph( ParagraphType.CodeBlock, "internal class TransformingIndexedSequence<T, R> \n" + "constructor(private val sequence: Sequence<T>, private val transformer: (Int, T) -> R) : Sequence<R> {", listOf( Markup( MarkupType.Bold, 109, 120 ) ) ), Paragraph( ParagraphType.CodeBlock, "override fun iterator(): Iterator<R> = object : Iterator<R> {\n" + " …\n" + " override fun next(): R {\n" + " return transformer(checkIndexOverflow(index++), iterator.next())\n" + " }\n" + " …\n" + "}", listOf( Markup(MarkupType.Bold, 83, 89), Markup(MarkupType.Bold, 107, 118) ) ), Paragraph( ParagraphType.Text, "Independent on whether you’re using collections or sequences, the Kotlin Standard Library offers quite a wide range of operations for both, like find, filter, groupBy and others. Make sure you check them out, before implementing your own version of these.", listOf( Markup(MarkupType.Code, 145, 149), Markup(MarkupType.Code, 151, 157), Markup(MarkupType.Code, 159, 166), Markup( MarkupType.Link, 193, 207, "https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/#functions" ) ) ), Paragraph( ParagraphType.Header, "Collections and sequences" ), Paragraph( ParagraphType.Text, "Let’s say that we have a list of objects of different shapes. We want to make the shapes yellow and then take the first square shape." ), Paragraph( ParagraphType.Text, "Let’s see how and when each operation is applied for collections and when for sequences" ), Paragraph( ParagraphType.Subhead, "Collections" ), Paragraph( ParagraphType.Text, "map is called — a new ArrayList is created. We iterate through all items of the initial collection, transform it by copying the original object and changing the color, then add it to the new list.", listOf(Markup(MarkupType.Code, 0, 3)) ), Paragraph( ParagraphType.Text, "first is called — we iterate through each item until the first square is found", listOf(Markup(MarkupType.Code, 0, 5)) ), Paragraph( ParagraphType.Subhead, "Sequences" ), Paragraph( ParagraphType.Bullet, "asSequence — a sequence is created based on the Iterator of the original collection", listOf(Markup(MarkupType.Code, 0, 10)) ), Paragraph( ParagraphType.Bullet, "map is called — the transformation is added to the list of operations needed to be performed by the sequence but the operation is NOT performed", listOf( Markup(MarkupType.Code, 0, 3), Markup(MarkupType.Bold, 130, 133) ) ), Paragraph( ParagraphType.Bullet, "first is called — this is a terminal operation, so, all the intermediate operations are triggered, on each element of the collection. We iterate through the initial collection applying map and then first on each of them. Since the condition from first is satisfied by the 2nd element, then we no longer apply the map on the rest of the collection.", listOf(Markup(MarkupType.Code, 0, 5)) ), Paragraph( ParagraphType.Text, "When working with sequences no intermediate collection is created and since items are evaluated one by one, map is only performed on some of the inputs." ), Paragraph( ParagraphType.Header, "Performance" ), Paragraph( ParagraphType.Subhead, "Order of transformations" ), Paragraph( ParagraphType.Text, "Independent of whether you’re using collections or sequences, the order of transformations matters. In the example above, first doesn’t need to happen after map since it’s not a consequence of the map transformation. If we reverse the order of our business logic and call first on the collection and then transform the result, then we only create one new object — the yellow square. When using sequences — we avoid creating 2 new objects, when using collections, we avoid creating an entire new list.", listOf( Markup(MarkupType.Code, 122, 127), Markup(MarkupType.Code, 157, 160), Markup(MarkupType.Code, 197, 200) ) ), Paragraph( ParagraphType.Text, "Because terminal operations can finish processing early, and intermediate operations are evaluated lazily, sequences can, in some cases, help you avoid doing unnecessary work compared to collections. Make sure you always check the order of the transformations and the dependencies between them!" ), Paragraph( ParagraphType.Subhead, "Inlining and large data sets consequences" ), Paragraph( ParagraphType.Text, "Collection operations use inline functions, so the bytecode of the operation, together with the bytecode of the lambda passed to it will be inlined. Sequences don’t use inline functions, therefore, new Function objects are created for each operation.", listOf( Markup( MarkupType.Code, 202, 210 ) ) ), Paragraph( ParagraphType.Text, "On the other hand, collections create a new list for every transformation while sequences just keep a reference to the transformation function." ), Paragraph( ParagraphType.Text, "When working with small collections, with 1–2 operators, these differences don’t have big implications so working with collections should be ok. But, when working with large lists the intermediate collection creation can become expensive; in such cases, use sequences.", listOf( Markup(MarkupType.Bold, 18, 35), Markup(MarkupType.Bold, 119, 130), Markup(MarkupType.Bold, 168, 179), Markup(MarkupType.Bold, 258, 267) ) ), Paragraph( ParagraphType.Text, "Unfortunately, I’m not aware of any benchmarking study done that would help us get a better understanding on how the performance of collections vs sequences is affected with different sizes of collections or operation chains." ), Paragraph( ParagraphType.Text, "Collections eagerly evaluate your data while sequences do so lazily. Depending on the size of your data, pick the one that fits best: collections — for small lists or sequences — for larger ones, and pay attention to the order of the transformations." ) ) val post1 = Post( id = "dc523f0ed25c", title = "A Little Thing about Android Module Paths", subtitle = "How to configure your module paths, instead of using Gradle’s default.", url = "https://medium.com/androiddevelopers/gradle-path-configuration-dc523f0ed25c", publication = publication, metadata = Metadata( author = pietro, date = "August 02", readTimeMinutes = 1 ), paragraphs = paragraphsPost1, imageId = R.drawable.post_1, imageThumbId = R.drawable.post_1_thumb ) val post2 = Post( id = "7446d8dfd7dc", title = "Dagger in Kotlin: Gotchas and Optimizations", subtitle = "Use Dagger in Kotlin! This article includes best practices to optimize your build time and gotchas you might encounter.", url = "https://medium.com/androiddevelopers/dagger-in-kotlin-gotchas-and-optimizations-7446d8dfd7dc", publication = publication, metadata = Metadata( author = manuel, date = "July 30", readTimeMinutes = 3 ), paragraphs = paragraphsPost2, imageId = R.drawable.post_2, imageThumbId = R.drawable.post_2_thumb ) val post3 = Post( id = "ac552dcc1741", title = "From Java Programming Language to Kotlin — the idiomatic way", subtitle = "Learn how to get started converting Java Programming Language code to Kotlin, making it more idiomatic and avoid common pitfalls, by…", url = "https://medium.com/androiddevelopers/from-java-programming-language-to-kotlin-the-idiomatic-way-ac552dcc1741", publication = publication, metadata = Metadata( author = florina, date = "July 09", readTimeMinutes = 1 ), paragraphs = paragraphsPost3, imageId = R.drawable.post_3, imageThumbId = R.drawable.post_3_thumb ) val post4 = Post( id = "84eb677660d9", title = "Locale changes and the AndroidViewModel antipattern", subtitle = "TL;DR: Expose resource IDs from ViewModels to avoid showing obsolete data.", url = "https://medium.com/androiddevelopers/locale-changes-and-the-androidviewmodel-antipattern-84eb677660d9", publication = publication, metadata = Metadata( author = jose, date = "April 02", readTimeMinutes = 1 ), paragraphs = paragraphsPost4, imageId = R.drawable.post_4, imageThumbId = R.drawable.post_4_thumb ) val post5 = Post( id = "55db18283aca", title = "Collections and sequences in Kotlin", subtitle = "Working with collections is a common task and the Kotlin Standard Library offers many great utility functions. It also offers two ways of…", url = "https://medium.com/androiddevelopers/collections-and-sequences-in-kotlin-55db18283aca", publication = publication, metadata = Metadata( author = florina, date = "July 24", readTimeMinutes = 4 ), paragraphs = paragraphsPost5, imageId = R.drawable.post_5, imageThumbId = R.drawable.post_5_thumb ) val posts: PostsFeed = PostsFeed( highlightedPost = post4, recommendedPosts = listOf(post1, post2, post3), popularPosts = listOf( post5, post1.copy(id = "post6"), post2.copy(id = "post7") ), recentPosts = listOf( post3.copy(id = "post8"), post4.copy(id = "post9"), post5.copy(id = "post10") ) )
apache-2.0
572d10e5754b1c63971c3702e522324e
39.28807
625
0.61066
4.51391
false
false
false
false
smmribeiro/intellij-community
plugins/stream-debugger/src/com/intellij/debugger/streams/lib/impl/JBIterableSupportProvider.kt
13
3262
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.debugger.streams.lib.impl import com.intellij.debugger.streams.lib.LibrarySupport import com.intellij.debugger.streams.lib.LibrarySupportProvider import com.intellij.debugger.streams.psi.impl.InheritanceBasedChainDetector import com.intellij.debugger.streams.psi.impl.JavaChainTransformerImpl import com.intellij.debugger.streams.psi.impl.JavaStreamChainBuilder import com.intellij.debugger.streams.trace.TraceExpressionBuilder import com.intellij.debugger.streams.trace.dsl.Lambda import com.intellij.debugger.streams.trace.dsl.impl.DslImpl import com.intellij.debugger.streams.trace.dsl.impl.TextExpression import com.intellij.debugger.streams.trace.dsl.impl.java.JavaStatementFactory import com.intellij.debugger.streams.trace.impl.JavaTraceExpressionBuilder import com.intellij.debugger.streams.trace.impl.handler.type.GenericType import com.intellij.debugger.streams.wrapper.CallArgument import com.intellij.debugger.streams.wrapper.IntermediateStreamCall import com.intellij.debugger.streams.wrapper.StreamCallType import com.intellij.debugger.streams.wrapper.StreamChainBuilder import com.intellij.debugger.streams.wrapper.impl.CallArgumentImpl import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.CommonClassNames /** * @author Vitaliy.Bibaev */ internal class JBIterableSupportProvider : LibrarySupportProvider { private companion object { const val CLASS_NAME = "com.intellij.util.containers.JBIterable" } private val librarySupport = JBIterableSupport() private val dsl = DslImpl(JBIterableJavaStatementFactory()) override fun getLanguageId(): String = "JAVA" override fun getChainBuilder(): StreamChainBuilder { return JavaStreamChainBuilder(JavaChainTransformerImpl(), InheritanceBasedChainDetector(CLASS_NAME)) } override fun getExpressionBuilder(project: Project): TraceExpressionBuilder { return JavaTraceExpressionBuilder(project, librarySupport.createHandlerFactory(dsl), dsl) } override fun getLibrarySupport(): LibrarySupport = librarySupport private class JBIterableJavaStatementFactory : JavaStatementFactory() { override fun createPeekCall(elementsType: GenericType, lambda: Lambda): IntermediateStreamCall { val lambdaBody = createEmptyLambdaBody(lambda.variableName).apply { add(lambda.body) doReturn(TextExpression("true")) } val newLambda = createLambda(lambda.variableName, lambdaBody) return JBIterablePeekCall(elementsType, newLambda.toCode()) } } private class JBIterablePeekCall(private val elementsType: GenericType, private val argText: String) : IntermediateStreamCall { override fun getName(): String = "filter" override fun getArguments(): List<CallArgument> = listOf(CallArgumentImpl(CommonClassNames.JAVA_LANG_OBJECT, argText)) override fun getType(): StreamCallType = StreamCallType.INTERMEDIATE override fun getTextRange(): TextRange = TextRange.EMPTY_RANGE override fun getTypeBefore(): GenericType = elementsType override fun getTypeAfter(): GenericType = elementsType } }
apache-2.0
1bd5620ed4d25e93c924541eaeda5f30
44.957746
140
0.810852
4.707071
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/fir-low-level-api/src/org/jetbrains/kotlin/idea/fir/low/level/api/providers/FirThreadSafeSymbolProviderWrapper.kt
2
3996
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.fir.low.level.api.providers import org.jetbrains.kotlin.fir.resolve.providers.FirSymbolProvider import org.jetbrains.kotlin.fir.resolve.providers.FirSymbolProviderInternals import org.jetbrains.kotlin.fir.symbols.CallableId import org.jetbrains.kotlin.fir.symbols.impl.FirCallableSymbol import org.jetbrains.kotlin.fir.symbols.impl.FirClassLikeSymbol import org.jetbrains.kotlin.fir.symbols.impl.FirNamedFunctionSymbol import org.jetbrains.kotlin.fir.symbols.impl.FirPropertySymbol import org.jetbrains.kotlin.idea.fir.low.level.api.annotations.PrivateForInline import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import java.util.concurrent.locks.ReadWriteLock import java.util.concurrent.locks.ReentrantReadWriteLock import kotlin.concurrent.withLock internal class FirThreadSafeSymbolProviderWrapper(private val provider: FirSymbolProvider) : FirSymbolProvider(provider.session) { private val lock = ReentrantReadWriteLock() private val classesCache = ThreadSafeCache<ClassId, FirClassLikeSymbol<*>>(lock) private val topLevelCache = ThreadSafeCache<CallableId, List<FirCallableSymbol<*>>>(lock) private val packages = ThreadSafeCache<FqName, FqName>(lock) override fun getClassLikeSymbolByFqName(classId: ClassId): FirClassLikeSymbol<*>? = classesCache.getOrCompute(classId) { provider.getClassLikeSymbolByFqName(classId) } override fun getTopLevelCallableSymbols(packageFqName: FqName, name: Name): List<FirCallableSymbol<*>> = topLevelCache.getOrCompute(CallableId(packageFqName, name)) { provider.getTopLevelCallableSymbols(packageFqName, name) } ?: emptyList() override fun getTopLevelFunctionSymbols(packageFqName: FqName, name: Name): List<FirNamedFunctionSymbol> { return getTopLevelCallableSymbols(packageFqName, name).filterIsInstance<FirNamedFunctionSymbol>() } override fun getTopLevelPropertySymbols(packageFqName: FqName, name: Name): List<FirPropertySymbol> { return getTopLevelCallableSymbols(packageFqName, name).filterIsInstance<FirPropertySymbol>() } @FirSymbolProviderInternals override fun getTopLevelCallableSymbolsTo(destination: MutableList<FirCallableSymbol<*>>, packageFqName: FqName, name: Name) { error("Should not be called for wrapper") } @FirSymbolProviderInternals override fun getTopLevelFunctionSymbolsTo(destination: MutableList<FirNamedFunctionSymbol>, packageFqName: FqName, name: Name) { destination += getTopLevelFunctionSymbols(packageFqName, name) } @FirSymbolProviderInternals override fun getTopLevelPropertySymbolsTo(destination: MutableList<FirPropertySymbol>, packageFqName: FqName, name: Name) { destination += getTopLevelPropertySymbols(packageFqName, name) } override fun getPackage(fqName: FqName): FqName? = packages.getOrCompute(fqName) { provider.getPackage(fqName) } } private class ThreadSafeCache<KEY, VALUE : Any>(private val lock: ReadWriteLock) { private val map = HashMap<KEY, Any>() @OptIn(PrivateForInline::class) inline fun getOrCompute(key: KEY, compute: () -> VALUE?): VALUE? { var value = lock.readLock().withLock { map[key] } if (value == null) { lock.writeLock().withLock { value = compute() ?: NULLABLE_VALUE map[key] = value!! } } @Suppress("UNCHECKED_CAST") return when (value) { NULLABLE_VALUE -> null null -> error("We should not read null from map here") else -> value as VALUE } } } @Suppress("ClassName") @PrivateForInline internal object NULLABLE_VALUE
apache-2.0
34e78fe1182daa743a80011309439e5b
43.910112
132
0.745746
4.690141
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantLambdaArrowInspection.kt
1
6453
// 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.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.refactoring.replaceWithCopyWithResolveCheck import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.isSingleUnderscore class RedundantLambdaArrowInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return lambdaExpressionVisitor(fun(lambdaExpression: KtLambdaExpression) { val functionLiteral = lambdaExpression.functionLiteral val arrow = functionLiteral.arrow ?: return val parameters = functionLiteral.valueParameters val singleParameter = parameters.singleOrNull() if (parameters.isNotEmpty() && singleParameter?.isSingleUnderscore != true && singleParameter?.name != "it") { return } if (lambdaExpression.getStrictParentOfType<KtWhenEntry>()?.expression == lambdaExpression) return if (lambdaExpression.getStrictParentOfType<KtContainerNodeForControlStructureBody>()?.let { it.node.elementType in listOf(KtNodeTypes.THEN, KtNodeTypes.ELSE) && it.expression == lambdaExpression } == true) return val callExpression = lambdaExpression.parent?.parent as? KtCallExpression if (callExpression != null) { val callee = callExpression.calleeExpression as? KtNameReferenceExpression if (callee != null && callee.getReferencedName() == "forEach" && singleParameter?.name != "it") return } val lambdaContext = lambdaExpression.analyze() if (parameters.isNotEmpty() && lambdaContext[BindingContext.EXPECTED_EXPRESSION_TYPE, lambdaExpression] == null) return val valueArgument = lambdaExpression.getStrictParentOfType() as? KtValueArgument val valueArgumentCalls = valueArgument?.parentCallExpressions().orEmpty() if (valueArgumentCalls.any { !it.isApplicableCall(lambdaExpression, lambdaContext) }) return val functionLiteralDescriptor = functionLiteral.descriptor if (functionLiteralDescriptor != null) { if (functionLiteral.anyDescendantOfType<KtNameReferenceExpression> { it.text == "it" && it.resolveToCall()?.resultingDescriptor?.containingDeclaration != functionLiteralDescriptor }) return } val startOffset = functionLiteral.startOffset holder.registerProblem( holder.manager.createProblemDescriptor( functionLiteral, TextRange((singleParameter?.startOffset ?: arrow.startOffset) - startOffset, arrow.endOffset - startOffset), KotlinBundle.message("redundant.lambda.arrow"), ProblemHighlightType.LIKE_UNUSED_SYMBOL, isOnTheFly, DeleteFix() ) ) }) } class DeleteFix : LocalQuickFix { override fun getFamilyName() = KotlinBundle.message("delete.fix.family.name") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as? KtFunctionLiteral ?: return element.removeArrow() } } } private fun KtCallExpression.isApplicableCall(lambdaExpression: KtLambdaExpression, lambdaContext: BindingContext): Boolean { val dotQualifiedExpression = parent as? KtDotQualifiedExpression return if (dotQualifiedExpression == null) { val offset = lambdaExpression.textOffset - textOffset replaceWithCopyWithResolveCheck( resolveStrategy = { expr, context -> expr.getResolvedCall(context)?.resultingDescriptor }, context = lambdaContext, preHook = { findLambdaExpressionByOffset(offset)?.functionLiteral?.removeArrow() } ) } else { val offset = lambdaExpression.textOffset - dotQualifiedExpression.textOffset dotQualifiedExpression.replaceWithCopyWithResolveCheck( resolveStrategy = { expr, context -> expr.selectorExpression.getResolvedCall(context)?.resultingDescriptor }, context = lambdaContext, preHook = { findLambdaExpressionByOffset(offset)?.functionLiteral?.removeArrow() } ) } != null } private fun KtFunctionLiteral.removeArrow() { valueParameterList?.delete() arrow?.delete() } private fun KtExpression.findLambdaExpressionByOffset(offset: Int): KtLambdaExpression? { val lbrace = findElementAt(offset)?.takeIf { it.node.elementType == KtTokens.LBRACE } ?: return null val functionLiteral = lbrace.parent as? KtFunctionLiteral ?: return null return functionLiteral.parent as? KtLambdaExpression } private fun KtValueArgument.parentCallExpressions(): List<KtCallExpression> { val calls = mutableListOf<KtCallExpression>() var argument = this while (true) { val call = argument.getStrictParentOfType<KtCallExpression>() ?: break calls.add(call) argument = call.getStrictParentOfType() ?: break } return calls }
apache-2.0
950626297ccc9e6a54b1a061999b7fc9
46.8
158
0.701689
5.715678
false
false
false
false
smmribeiro/intellij-community
platform/built-in-server/src/org/jetbrains/io/SubServer.kt
8
3290
// 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.io import com.intellij.openapi.Disposable import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Disposer import com.intellij.util.io.serverBootstrap import com.intellij.util.net.loopbackSocketAddress import io.netty.channel.Channel import io.netty.channel.ChannelHandler import io.netty.channel.ChannelHandlerContext import io.netty.channel.ChannelInitializer import io.netty.handler.codec.http.FullHttpRequest import io.netty.handler.codec.http.HttpMethod import io.netty.handler.codec.http.QueryStringDecoder import org.jetbrains.ide.CustomPortServerManager import org.jetbrains.ide.XmlRpcServerImpl import java.net.InetSocketAddress internal class SubServer(private val user: CustomPortServerManager, private val server: BuiltInServer) : CustomPortServerManager.CustomPortService, Disposable { private var channelRegistrar: ChannelRegistrar? = null override val isBound: Boolean get() = channelRegistrar != null && !channelRegistrar!!.isEmpty init { user.setManager(this) } fun bind(port: Int): Boolean { if (port == server.port || port == -1) { return true } if (channelRegistrar == null) { Disposer.register(server, this) channelRegistrar = ChannelRegistrar() } val bootstrap = serverBootstrap(server.eventLoopGroup) val xmlRpcHandlers = user.createXmlRpcHandlers() if (xmlRpcHandlers == null) { BuiltInServer.configureChildHandler(bootstrap, channelRegistrar!!, null) } else { val handler = XmlRpcDelegatingHttpRequestHandler(xmlRpcHandlers) bootstrap.childHandler(object : ChannelInitializer<Channel>() { override fun initChannel(channel: Channel) { channel.pipeline().addLast(channelRegistrar!!) NettyUtil.addHttpServerCodec(channel.pipeline()) channel.pipeline().addLast(handler) } }) } try { bootstrap.localAddress(if (user.isAvailableExternally) InetSocketAddress(port) else loopbackSocketAddress(port)) channelRegistrar!!.setServerChannel(bootstrap.bind().syncUninterruptibly().channel(), false) return true } catch (e: Exception) { try { NettyUtil.log(e, Logger.getInstance(BuiltInServer::class.java)) } finally { user.cannotBind(e, port) } return false } } private fun stop() { channelRegistrar?.close() } override fun rebind(): Boolean { stop() return bind(user.port) } override fun dispose() { stop() user.setManager(null) } } @ChannelHandler.Sharable private class XmlRpcDelegatingHttpRequestHandler internal constructor(private val handlers: Map<String, Any>) : DelegatingHttpRequestHandlerBase() { override fun process(context: ChannelHandlerContext, request: FullHttpRequest, urlDecoder: QueryStringDecoder): Boolean { if (handlers.isEmpty()) { // not yet initialized, for example, P2PTransport could add handlers after we bound. return false } return request.method() === HttpMethod.POST && XmlRpcServerImpl.getInstance().process(urlDecoder.path(), request, context, handlers) } }
apache-2.0
f97a81991919c9f11b56b3759def3996
32.927835
160
0.731611
4.470109
false
false
false
false
smmribeiro/intellij-community
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/RootModelBridgeImpl.kt
3
7179
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots import com.intellij.configurationStore.deserializeAndLoadState import com.intellij.openapi.Disposable import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.roots.ModuleExtension import com.intellij.openapi.roots.ModuleRootManagerEx import com.intellij.openapi.roots.OrderEntry import com.intellij.openapi.roots.OrderEnumerator import com.intellij.openapi.roots.impl.ModuleOrderEnumerator import com.intellij.openapi.roots.impl.RootModelBase import com.intellij.openapi.util.Comparing import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.JDOMUtil import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.findModuleEntity import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge import com.intellij.workspaceModel.ide.legacyBridge.ModuleExtensionBridgeFactory import com.intellij.workspaceModel.storage.VersionedEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntityStorageDiffBuilder import com.intellij.workspaceModel.storage.bridgeEntities.ContentRootEntity import com.intellij.workspaceModel.storage.bridgeEntities.ModuleDependencyItem import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity import org.jdom.Element import org.jetbrains.annotations.NotNull import java.util.* import java.util.concurrent.atomic.AtomicBoolean internal class RootModelBridgeImpl(internal val moduleEntity: ModuleEntity?, private val storage: VersionedEntityStorage, private val itemUpdater: ((Int, (ModuleDependencyItem) -> ModuleDependencyItem) -> Unit)?, private val rootModel: ModuleRootModelBridge, internal val updater: (((WorkspaceEntityStorageDiffBuilder) -> Unit) -> Unit)?) : RootModelBase(), Disposable { private val module: ModuleBridge = rootModel.moduleBridge private val extensions by lazy { loadExtensions(storage = storage, module = module, writable = false, diff = null, parentDisposable = this) } private val orderEntriesArray: Array<OrderEntry> by lazy { val moduleEntity = moduleEntity ?: return@lazy emptyArray<OrderEntry>() moduleEntity.dependencies.mapIndexed { index, e -> toOrderEntry(e, index, rootModel, itemUpdater) }.toTypedArray() } val contentEntities: List<ContentRootEntity> by lazy { val moduleEntity = moduleEntity ?: return@lazy emptyList<ContentRootEntity>() return@lazy moduleEntity.contentRoots.toList() } private val contentEntriesList by lazy { val moduleEntity = moduleEntity ?: return@lazy emptyList<ContentEntryBridge>() val contentEntries = moduleEntity.contentRoots.toMutableList() contentEntries.sortBy { it.url.url } contentEntries.map { contentRoot -> ContentEntryBridge(rootModel, contentRoot.sourceRoots.toList(), contentRoot, updater) } } private var disposedStackTrace: Throwable? = null private val isDisposed = AtomicBoolean(false) override fun dispose() { val alreadyDisposed = isDisposed.getAndSet(true) if (alreadyDisposed) { val trace = disposedStackTrace if (trace != null) { throw IllegalStateException("${javaClass.name} was already disposed", trace) } else throw IllegalStateException("${javaClass.name} was already disposed") } else if (Disposer.isDebugMode()) { disposedStackTrace = Throwable() } } override fun getModule(): ModuleBridge = module override fun <T : Any?> getModuleExtension(klass: Class<T>): T? { return extensions.filterIsInstance(klass).firstOrNull() } override fun getOrderEntries() = orderEntriesArray override fun getContent() = contentEntriesList override fun orderEntries(): OrderEnumerator = ModuleOrderEnumerator(this, null) companion object { private val MODULE_EXTENSION_BRIDGE_FACTORY_EP = ExtensionPointName<ModuleExtensionBridgeFactory<*>>("com.intellij.workspaceModel.moduleExtensionBridgeFactory") internal fun toOrderEntry( item: ModuleDependencyItem, index: Int, rootModelBridge: ModuleRootModelBridge, updater: ((Int, (ModuleDependencyItem) -> ModuleDependencyItem) -> Unit)? ): OrderEntryBridge { return when (item) { is ModuleDependencyItem.Exportable.ModuleDependency -> ModuleOrderEntryBridge(rootModelBridge, index, item, updater) is ModuleDependencyItem.Exportable.LibraryDependency -> { LibraryOrderEntryBridge(rootModelBridge, index, item, updater) } is ModuleDependencyItem.SdkDependency -> SdkOrderEntryBridge(rootModelBridge, index, item) is ModuleDependencyItem.InheritedSdkDependency -> InheritedSdkOrderEntryBridge(rootModelBridge, index, item) is ModuleDependencyItem.ModuleSourceDependency -> ModuleSourceOrderEntryBridge(rootModelBridge, index, item) } } internal fun loadExtensions(storage: VersionedEntityStorage, module: ModuleBridge, writable: Boolean, diff: WorkspaceEntityStorageDiffBuilder?, parentDisposable: Disposable): Set<ModuleExtension> { val result = TreeSet<ModuleExtension> { o1, o2 -> Comparing.compare(o1.javaClass.name, o2.javaClass.name) } MODULE_EXTENSION_BRIDGE_FACTORY_EP.extensionList.mapTo(result) { it.createExtension(module, storage, diff) } val moduleEntity = storage.current.findModuleEntity(module) val rootManagerElement = moduleEntity?.customImlData?.rootManagerTagCustomData?.let { JDOMUtil.load(it) } for (extension in ModuleRootManagerEx.MODULE_EXTENSION_NAME.getExtensions(module)) { val readOnlyExtension = loadExtension(extension, parentDisposable, rootManagerElement) if (writable) { val modifiableExtension = readOnlyExtension.getModifiableModel(true).also { Disposer.register(parentDisposable, it) } result.add(modifiableExtension) } else { result.add(readOnlyExtension) } } return result } private fun loadExtension(extension: ModuleExtension, parentDisposable: Disposable, rootManagerElement: @NotNull Element?): @NotNull ModuleExtension { val readOnlyExtension = extension.getModifiableModel(false).also { Disposer.register(parentDisposable, it) } if (rootManagerElement != null) { if (readOnlyExtension is PersistentStateComponent<*>) { deserializeAndLoadState(readOnlyExtension, rootManagerElement) } else { @Suppress("DEPRECATION") readOnlyExtension.readExternal(rootManagerElement) } } return readOnlyExtension } } }
apache-2.0
37c994804caf238e065e9f66685dbdef
42.509091
164
0.725031
5.484339
false
false
false
false
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/services/LocationServiceHelper.kt
1
2668
package info.nightscout.androidaps.services import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.IBinder import info.nightscout.androidaps.interfaces.NotificationHolderInterface import javax.inject.Inject import javax.inject.Singleton /* This code replaces following val intent = Intent(context, LocationService::class.java) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(intent) else context.startService(intent) it fails randomly with error Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{e317f7e u0 info.nightscout.nsclient/info.nightscout.androidaps.services.LocationService} */ @Singleton class LocationServiceHelper @Inject constructor( private val notificationHolder: NotificationHolderInterface ) { fun startService(context: Context) { val connection = object : ServiceConnection { override fun onServiceConnected(name: ComponentName?, service: IBinder?) { // The binder of the service that returns the instance that is created. val binder = service as LocationService.LocalBinder val locationService: LocationService = binder.getService() context.startForegroundService(Intent(context, LocationService::class.java)) // This is the key: Without waiting Android Framework to call this method // inside Service.onCreate(), immediately call here to post the notification. locationService.startForeground(notificationHolder.notificationID, notificationHolder.notification) // Release the connection to prevent leaks. context.unbindService(this) } override fun onServiceDisconnected(name: ComponentName?) { } } try { context.bindService(Intent(context, LocationService::class.java), connection, Context.BIND_AUTO_CREATE) } catch (ignored: RuntimeException) { // This is probably a broadcast receiver context even though we are calling getApplicationContext(). // Just call startForegroundService instead since we cannot bind a service to a // broadcast receiver context. The service also have to call startForeground in // this case. context.startForegroundService(Intent(context, LocationService::class.java)) } } fun stopService(context: Context) = context.stopService(Intent(context, LocationService::class.java)) }
agpl-3.0
a978cb61653f6e7ff39d6c2b01574ec2
42.048387
184
0.713643
5.501031
false
false
false
false
kohesive/kohesive-iac
model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/clients/DeferredAmazonSnowball.kt
1
1669
package uy.kohesive.iac.model.aws.clients import com.amazonaws.services.snowball.AbstractAmazonSnowball import com.amazonaws.services.snowball.AmazonSnowball import com.amazonaws.services.snowball.model.* import uy.kohesive.iac.model.aws.IacContext import uy.kohesive.iac.model.aws.proxy.makeProxy open class BaseDeferredAmazonSnowball(val context: IacContext) : AbstractAmazonSnowball(), AmazonSnowball { override fun createAddress(request: CreateAddressRequest): CreateAddressResult { return with (context) { request.registerWithAutoName() makeProxy<CreateAddressRequest, CreateAddressResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } override fun createCluster(request: CreateClusterRequest): CreateClusterResult { return with (context) { request.registerWithAutoName() makeProxy<CreateClusterRequest, CreateClusterResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } override fun createJob(request: CreateJobRequest): CreateJobResult { return with (context) { request.registerWithAutoName() makeProxy<CreateJobRequest, CreateJobResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } } class DeferredAmazonSnowball(context: IacContext) : BaseDeferredAmazonSnowball(context)
mit
72015d047b2e9a2a93064053d2efcf6b
34.510638
107
0.65009
5.315287
false
false
false
false
ingokegel/intellij-community
platform/testFramework/src/com/intellij/project/TestProjectManager.kt
1
9941
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplacePutWithAssignment") package com.intellij.project import com.intellij.ide.AppLifecycleListener import com.intellij.ide.impl.OpenProjectTask import com.intellij.ide.impl.ProjectUtil import com.intellij.ide.impl.runUnderModalProgressIfIsEdt import com.intellij.ide.startup.StartupManagerEx import com.intellij.ide.startup.impl.StartupManagerImpl import com.intellij.openapi.Disposable import com.intellij.openapi.application.AccessToken import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.command.impl.DummyProject import com.intellij.openapi.command.impl.UndoManagerImpl import com.intellij.openapi.command.undo.UndoManager import com.intellij.openapi.components.StorageScheme import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.Project import com.intellij.openapi.project.ex.ProjectEx import com.intellij.openapi.project.impl.ProjectImpl import com.intellij.openapi.project.impl.ProjectManagerImpl import com.intellij.openapi.project.impl.runInitProjectActivities import com.intellij.openapi.startup.StartupManager import com.intellij.openapi.util.Disposer import com.intellij.testFramework.LeakHunter import com.intellij.testFramework.TestApplicationManager.Companion.publishHeapDump import com.intellij.util.ModalityUiUtil import com.intellij.util.containers.UnsafeWeakList import com.intellij.util.ref.GCUtil import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.runBlocking import org.jetbrains.annotations.ApiStatus import java.nio.file.Path import java.util.* import java.util.concurrent.TimeUnit private const val MAX_LEAKY_PROJECTS = 5 private val LEAK_CHECK_INTERVAL = TimeUnit.MINUTES.toMillis(30) private var CHECK_START = System.currentTimeMillis() private val LOG_PROJECT_LEAKAGE = System.getProperty("idea.log.leaked.projects.in.tests", "true")!!.toBoolean() var totalCreatedProjectsCount = 0 @ApiStatus.Internal open class TestProjectManager : ProjectManagerImpl() { companion object { @Deprecated( message = "moved to LeakHunter", replaceWith = ReplaceWith("LeakHunter.getCreationPlace(project)", "com.intellij.testFramework.LeakHunter") ) @JvmStatic fun getCreationPlace(project: Project): String { return LeakHunter.getCreationPlace(project) } suspend fun loadAndOpenProject(path: Path, parent: Disposable): Project { check(!ApplicationManager.getApplication().isDispatchThread) val project = getInstanceEx().openProjectAsync(path, OpenProjectTask {})!! Disposer.register(parent) { check(!ApplicationManager.getApplication().isDispatchThread) runBlocking { getInstanceEx().forceCloseProjectAsync(project) } } return project } } private var totalCreatedProjectCount = 0 private val projects = WeakHashMap<Project, String>() @Volatile private var isTracking = false private val trackingProjects = UnsafeWeakList<Project>() override fun newProject(file: Path, options: OpenProjectTask): Project? { checkProjectLeaksInTests() val project = super.newProject(file, options) if (project != null && LOG_PROJECT_LEAKAGE) { projects.put(project, null) } return project } override fun handleErrorOnNewProject(t: Throwable) { throw t } fun openProject(project: Project): Boolean { if (project is ProjectImpl && project.isLight) { project.setTemporarilyDisposed(false) val isInitialized = StartupManagerEx.getInstanceEx(project).startupActivityPassed() if (isInitialized) { addToOpened(project) // events already fired return true } } val store = if (project is ProjectStoreOwner) (project as ProjectStoreOwner).componentStore else null if (store != null) { val projectFilePath = if (store.storageScheme == StorageScheme.DIRECTORY_BASED) store.directoryStorePath!! else store.projectFilePath for (p in openProjects) { if (ProjectUtil.isSameProject(projectFilePath, p)) { ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL) { ProjectUtil.focusProjectWindow(p, false) } return false } } } if (!addToOpened(project)) { return false } val app = ApplicationManager.getApplication() try { runUnderModalProgressIfIsEdt { coroutineScope { runInitProjectActivities(project = project) } if (isRunStartUpActivitiesEnabled(project)) { (StartupManager.getInstance(project) as StartupManagerImpl).runStartupActivities() } } } catch (e: ProcessCanceledException) { app.invokeAndWait { closeProject(project, saveProject = false, checkCanClose = false) } app.messageBus.syncPublisher(AppLifecycleListener.TOPIC).projectOpenFailed() return false } return true } // method is not used and will be deprecated soon but still have to ensure that every created Project instance is tracked override fun loadProject(path: Path): Project { val project = super.loadProject(path) trackProject(project) return project } private fun trackProject(project: Project) { if (isTracking) { synchronized(this) { if (isTracking) { trackingProjects.add(project) } } } } override fun instantiateProject(projectStoreBaseDir: Path, options: OpenProjectTask): ProjectImpl { val project = super.instantiateProject(projectStoreBaseDir, options) totalCreatedProjectCount++ trackProject(project) return project } override fun closeProject(project: Project, saveProject: Boolean, dispose: Boolean, checkCanClose: Boolean): Boolean { if (isTracking) { synchronized(this) { if (isTracking) { trackingProjects.remove(project) } } } val result = super.closeProject(project, saveProject, dispose, checkCanClose) val undoManager = UndoManager.getGlobalInstance() as UndoManagerImpl // test may use WrapInCommand (it is ok - in this case HeavyPlatformTestCase will call dropHistoryInTests) if (!undoManager.isInsideCommand) { undoManager.dropHistoryInTests() } return result } /** * Start tracking of created projects. Call [AccessToken.finish] to stop tracking and assert that no leaked projects. */ @Synchronized fun startTracking(): AccessToken { if (isTracking) { throw IllegalStateException("Tracking is already started") } return object : AccessToken() { override fun finish() { synchronized(this@TestProjectManager) { isTracking = false var error: StringBuilder? = null for (project in trackingProjects) { if (error == null) { error = StringBuilder() } error.append(project.toString()) error.append("\nCreation trace: ") error.append((project as ProjectEx).creationTrace) } trackingProjects.clear() if (error != null) { throw IllegalStateException(error.toString()) } } } } } private fun getLeakedProjectCount() = getLeakedProjects().count() private fun getLeakedProjects(): Sequence<Project> { // process queue projects.remove(DummyProject.getInstance()) return projects.keys.asSequence() } private fun checkProjectLeaksInTests() { if (!LOG_PROJECT_LEAKAGE || getLeakedProjectCount() < MAX_LEAKY_PROJECTS) { return } val currentTime = System.currentTimeMillis() if ((currentTime - CHECK_START) < LEAK_CHECK_INTERVAL) { // check every N minutes return } var i = 0 while (i < 3 && getLeakedProjectCount() >= MAX_LEAKY_PROJECTS) { GCUtil.tryGcSoftlyReachableObjects() i++ } CHECK_START = currentTime if (getLeakedProjectCount() >= MAX_LEAKY_PROJECTS) { System.gc() val copy = getLeakedProjects().toCollection(UnsafeWeakList()) projects.clear() if (copy.iterator().asSequence().count() >= MAX_LEAKY_PROJECTS) { reportLeakedProjects(copy) throw AssertionError("Too many projects leaked, again.") } } } override fun isRunStartUpActivitiesEnabled(project: Project): Boolean { val runStartUpActivitiesFlag = project.getUserData(ProjectImpl.RUN_START_UP_ACTIVITIES) return runStartUpActivitiesFlag == null || runStartUpActivitiesFlag } } private fun reportLeakedProjects(leakedProjects: Iterable<Project>) { val hashCodes = HashSet<Int>() for (project in leakedProjects) { hashCodes.add(System.identityHashCode(project)) } val dumpPath = publishHeapDump("leakedProjects") val leakers = StringBuilder() leakers.append("Too many projects leaked (hashCodes=$hashCodes): \n") LeakHunter.processLeaks(LeakHunter.allRoots(), ProjectImpl::class.java, { hashCodes.contains(System.identityHashCode(it)) }, { leaked: ProjectImpl?, backLink: Any? -> val hashCode = System.identityHashCode(leaked) leakers.append("Leaked project found:").append(leaked) .append(", hash=").append(hashCode) .append(", place=").append(LeakHunter.getCreationPlace(leaked!!)).append('\n') .append(backLink).append('\n') .append("-----\n") hashCodes.remove(hashCode) !hashCodes.isEmpty() }) leakers.append("\nPlease see `").append(dumpPath).append("` for a memory dump") throw AssertionError(leakers.toString()) }
apache-2.0
3991fabe673031d1e70fd247b43942be
34.888087
139
0.696308
4.825728
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractFunction/ExtractKotlinFunctionHandler.kt
1
3690
// 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.introduce.extractFunction import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.refactoring.RefactoringActionHandler import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils import org.jetbrains.kotlin.idea.refactoring.getExtractionContainers import org.jetbrains.kotlin.idea.refactoring.introduce.extractFunction.ui.KotlinExtractFunctionDialog import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.* import org.jetbrains.kotlin.idea.refactoring.introduce.selectElementsWithTargetSibling import org.jetbrains.kotlin.idea.refactoring.introduce.validateExpressionElements import org.jetbrains.kotlin.idea.util.nonBlocking import org.jetbrains.kotlin.idea.util.psi.patternMatching.toRange import org.jetbrains.kotlin.psi.KtBlockExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.utils.addToStdlib.safeAs class ExtractKotlinFunctionHandler( private val allContainersEnabled: Boolean = false, private val helper: ExtractionEngineHelper = InteractiveExtractionHelper ) : RefactoringActionHandler { object InteractiveExtractionHelper : ExtractionEngineHelper(EXTRACT_FUNCTION) { override fun configureAndRun( project: Project, editor: Editor, descriptorWithConflicts: ExtractableCodeDescriptorWithConflicts, onFinish: (ExtractionResult) -> Unit ) { KotlinExtractFunctionDialog(descriptorWithConflicts.descriptor.extractionData.project, descriptorWithConflicts) { doRefactor(it.currentConfiguration, onFinish) }.show() } } fun doInvoke( editor: Editor, file: KtFile, elements: List<PsiElement>, targetSibling: PsiElement ) { nonBlocking(file.project, { val adjustedElements = elements.singleOrNull().safeAs<KtBlockExpression>()?.statements ?: elements ExtractionData(file, adjustedElements.toRange(false), targetSibling) }) { extractionData -> ExtractionEngine(helper).run(editor, extractionData) { processDuplicates(it.duplicateReplacers, file.project, editor) } } } fun selectElements(editor: Editor, file: KtFile, continuation: (elements: List<PsiElement>, targetSibling: PsiElement) -> Unit) { selectElementsWithTargetSibling( EXTRACT_FUNCTION, editor, file, KotlinBundle.message("title.select.target.code.block"), listOf(CodeInsightUtils.ElementKind.EXPRESSION), ::validateExpressionElements, { elements, parent -> parent.getExtractionContainers(elements.size == 1, allContainersEnabled) }, continuation ) } override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext?) { if (file !is KtFile) return selectElements(editor, file) { elements, targetSibling -> doInvoke(editor, file, elements, targetSibling) } } override fun invoke(project: Project, elements: Array<out PsiElement>, dataContext: DataContext?) { throw AssertionError("Extract Function can only be invoked from editor") } } val EXTRACT_FUNCTION: String = KotlinBundle.message("extract.function")
apache-2.0
4cfff12feb80e96ed5f67195d921a453
44.555556
158
0.73523
4.986486
false
false
false
false
siosio/intellij-community
plugins/kotlin/uast/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUBinaryExpression.kt
2
4512
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.kotlin import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtBinaryExpression import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.uast.* import org.jetbrains.uast.kotlin.declarations.KotlinUIdentifier class KotlinUBinaryExpression( override val sourcePsi: KtBinaryExpression, givenParent: UElement? ) : KotlinAbstractUExpression(givenParent), UBinaryExpression, KotlinUElementWithType, KotlinEvaluatableUElement { private companion object { val BITWISE_OPERATORS = mapOf( "or" to UastBinaryOperator.BITWISE_OR, "and" to UastBinaryOperator.BITWISE_AND, "xor" to UastBinaryOperator.BITWISE_XOR, "shl" to UastBinaryOperator.SHIFT_LEFT, "shr" to UastBinaryOperator.SHIFT_RIGHT, "ushr" to UastBinaryOperator.UNSIGNED_SHIFT_RIGHT ) } override val leftOperand by lz { KotlinConverter.convertOrEmpty(sourcePsi.left, this) } override val rightOperand by lz { KotlinConverter.convertOrEmpty(sourcePsi.right, this) } override val operatorIdentifier: UIdentifier? get() = KotlinUIdentifier(sourcePsi.operationReference.getReferencedNameElement(), this) override fun resolveOperator(): PsiMethod? = resolveToPsiMethod(sourcePsi) override val operator = when (sourcePsi.operationToken) { KtTokens.EQ -> UastBinaryOperator.ASSIGN KtTokens.PLUS -> UastBinaryOperator.PLUS KtTokens.MINUS -> UastBinaryOperator.MINUS KtTokens.MUL -> UastBinaryOperator.MULTIPLY KtTokens.DIV -> UastBinaryOperator.DIV KtTokens.PERC -> UastBinaryOperator.MOD KtTokens.OROR -> UastBinaryOperator.LOGICAL_OR KtTokens.ANDAND -> UastBinaryOperator.LOGICAL_AND KtTokens.EQEQ -> UastBinaryOperator.EQUALS KtTokens.EXCLEQ -> UastBinaryOperator.NOT_EQUALS KtTokens.EQEQEQ -> UastBinaryOperator.IDENTITY_EQUALS KtTokens.EXCLEQEQEQ -> UastBinaryOperator.IDENTITY_NOT_EQUALS KtTokens.GT -> UastBinaryOperator.GREATER KtTokens.GTEQ -> UastBinaryOperator.GREATER_OR_EQUALS KtTokens.LT -> UastBinaryOperator.LESS KtTokens.LTEQ -> UastBinaryOperator.LESS_OR_EQUALS KtTokens.PLUSEQ -> UastBinaryOperator.PLUS_ASSIGN KtTokens.MINUSEQ -> UastBinaryOperator.MINUS_ASSIGN KtTokens.MULTEQ -> UastBinaryOperator.MULTIPLY_ASSIGN KtTokens.DIVEQ -> UastBinaryOperator.DIVIDE_ASSIGN KtTokens.PERCEQ -> UastBinaryOperator.REMAINDER_ASSIGN KtTokens.IN_KEYWORD -> KotlinBinaryOperators.IN KtTokens.NOT_IN -> KotlinBinaryOperators.NOT_IN KtTokens.RANGE -> KotlinBinaryOperators.RANGE_TO else -> run { // Handle bitwise operators val other = UastBinaryOperator.OTHER val ref = sourcePsi.operationReference val resolvedCall = sourcePsi.operationReference.getResolvedCall(ref.analyze()) ?: return@run other val resultingDescriptor = resolvedCall.resultingDescriptor as? FunctionDescriptor ?: return@run other val applicableOperator = BITWISE_OPERATORS[resultingDescriptor.name.asString()] ?: return@run other val containingClass = resultingDescriptor.containingDeclaration as? ClassDescriptor ?: return@run other if (containingClass.typeConstructor.supertypes.any { it.constructor.declarationDescriptor?.fqNameSafe?.asString() == "kotlin.Number" }) applicableOperator else other } } } class KotlinCustomUBinaryExpression( override val psi: PsiElement, givenParent: UElement? ) : KotlinAbstractUExpression(givenParent), UBinaryExpression { lateinit override var leftOperand: UExpression internal set lateinit override var operator: UastBinaryOperator internal set lateinit override var rightOperand: UExpression internal set override val operatorIdentifier: UIdentifier? get() = null override fun resolveOperator() = null }
apache-2.0
7ba12ebd06cb9ca63ef497fbf3e536ad
46.010417
158
0.728723
5.522644
false
false
false
false
jwren/intellij-community
plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/classLoading/ClassLoadingAdapter.kt
1
4579
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.evaluate.classLoading import com.sun.jdi.ArrayReference import com.sun.jdi.ArrayType import com.sun.jdi.ClassLoaderReference import com.sun.jdi.Value import org.jetbrains.kotlin.idea.debugger.evaluate.ExecutionContext import org.jetbrains.org.objectweb.asm.ClassReader import org.jetbrains.org.objectweb.asm.Label import org.jetbrains.org.objectweb.asm.Opcodes import org.jetbrains.org.objectweb.asm.tree.* import kotlin.math.min interface ClassLoadingAdapter { companion object { private const val CHUNK_SIZE = 4096 private val ADAPTERS = listOf( AndroidOClassLoadingAdapter(), OrdinaryClassLoadingAdapter() ) fun loadClasses(context: ExecutionContext, classes: Collection<ClassToLoad>): ClassLoaderReference? { val mainClass = classes.firstOrNull { it.isMainClass } ?: return null var info = ClassInfoForEvaluator(containsAdditionalClasses = classes.size > 1) if (!info.containsAdditionalClasses) { info = analyzeClass(mainClass, info) } for (adapter in ADAPTERS) { if (adapter.isApplicable(context, info)) { return adapter.loadClasses(context, classes) } } return null } data class ClassInfoForEvaluator( val containsLoops: Boolean = false, val containsCodeUnsupportedInEval4J: Boolean = false, val containsAdditionalClasses: Boolean = false ) { val isCompilingEvaluatorPreferred: Boolean get() = containsLoops || containsCodeUnsupportedInEval4J || containsAdditionalClasses } private fun analyzeClass(classToLoad: ClassToLoad, info: ClassInfoForEvaluator): ClassInfoForEvaluator { val classNode = ClassNode().apply { ClassReader(classToLoad.bytes).accept(this, 0) } for (method in classNode.methods) { if ((method.access and Opcodes.ACC_SYNCHRONIZED) != 0) { return info.copy(containsCodeUnsupportedInEval4J = true) } } val methodToRun = classNode.methods.single { it.name == GENERATED_FUNCTION_NAME } val visitedLabels = hashSetOf<Label>() tailrec fun analyzeInsn(insn: AbstractInsnNode, info: ClassInfoForEvaluator): ClassInfoForEvaluator { when (insn) { is LabelNode -> visitedLabels += insn.label is JumpInsnNode -> { if (insn.label.label in visitedLabels) { return info.copy(containsLoops = true) } } is TableSwitchInsnNode, is LookupSwitchInsnNode -> { return info.copy(containsCodeUnsupportedInEval4J = true) } is InsnNode -> { if (insn.opcode == Opcodes.MONITORENTER || insn.opcode == Opcodes.MONITOREXIT) { return info.copy(containsCodeUnsupportedInEval4J = true) } } } val nextInsn = insn.next ?: return info return analyzeInsn(nextInsn, info) } val firstInsn = methodToRun.instructions?.first ?: return info return analyzeInsn(firstInsn, info) } } fun isApplicable(context: ExecutionContext, info: ClassInfoForEvaluator): Boolean fun loadClasses(context: ExecutionContext, classes: Collection<ClassToLoad>): ClassLoaderReference fun mirrorOfByteArray(bytes: ByteArray, context: ExecutionContext): ArrayReference { val classLoader = context.classLoader val arrayClass = context.findClass("byte[]", classLoader) as ArrayType val reference = context.newInstance(arrayClass, bytes.size) context.keepReference(reference) val mirrors = ArrayList<Value>(bytes.size) for (byte in bytes) { mirrors += context.vm.mirrorOf(byte) } var loaded = 0 while (loaded < mirrors.size) { val chunkSize = min(CHUNK_SIZE, mirrors.size - loaded) reference.setValues(loaded, mirrors, loaded, chunkSize) loaded += chunkSize } return reference } }
apache-2.0
c872352d4abed03014b08d3ddf3f21de
39.166667
158
0.61651
5.087778
false
false
false
false
jwren/intellij-community
platform/platform-impl/src/com/intellij/ui/layout/migLayout/MigLayoutBuilder.kt
3
12309
// 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 com.intellij.ui.layout.migLayout import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.DialogWrapper.IS_VISUAL_PADDING_COMPENSATED_ON_COMPONENT_LEVEL_KEY import com.intellij.openapi.ui.ValidationInfo import com.intellij.ui.components.JBTextArea import com.intellij.ui.layout.* import com.intellij.ui.layout.migLayout.patched.* import com.intellij.ui.scale.JBUIScale import com.intellij.util.SmartList import com.intellij.util.containers.CollectionFactory import net.miginfocom.layout.* import java.awt.Component import java.awt.Container import javax.swing.* internal class MigLayoutBuilder(val spacing: SpacingConfiguration) : LayoutBuilderImpl { companion object { private var hRelatedGap = -1 private var vRelatedGap = -1 init { JBUIScale.addUserScaleChangeListener { updatePlatformDefaults() } } private fun updatePlatformDefaults() { if (hRelatedGap != -1 && vRelatedGap != -1) { PlatformDefaults.setRelatedGap(createUnitValue(hRelatedGap, true), createUnitValue(vRelatedGap, false)) } } private fun setRelatedGap(h: Int, v: Int) { if (hRelatedGap == h && vRelatedGap == v) { return } hRelatedGap = h vRelatedGap = v updatePlatformDefaults() } } init { setRelatedGap(spacing.horizontalGap, spacing.verticalGap) } /** * Map of component to constraints shared among rows (since components are unique) */ internal val componentConstraints: MutableMap<Component, CC> = CollectionFactory.createWeakIdentityMap(4, 0.8f) override val rootRow = MigLayoutRow(parent = null, builder = this, indent = 0) private val buttonGroupStack: MutableList<ButtonGroup> = mutableListOf() override var preferredFocusedComponent: JComponent? = null override var validateCallbacks: MutableList<() -> ValidationInfo?> = mutableListOf() override var componentValidateCallbacks: MutableMap<JComponent, () -> ValidationInfo?> = linkedMapOf() override var customValidationRequestors: MutableMap<JComponent, MutableList<(() -> Unit) -> Unit>> = linkedMapOf() override var applyCallbacks: MutableMap<JComponent?, MutableList<() -> Unit>> = linkedMapOf() override var resetCallbacks: MutableMap<JComponent?, MutableList<() -> Unit>> = linkedMapOf() override var isModifiedCallbacks: MutableMap<JComponent?, MutableList<() -> Boolean>> = linkedMapOf() val topButtonGroup: ButtonGroup? get() = buttonGroupStack.lastOrNull() internal var hideableRowNestingLevel = 0 override fun withButtonGroup(buttonGroup: ButtonGroup, body: () -> Unit) { buttonGroupStack.add(buttonGroup) try { body() resetCallbacks.getOrPut(null, { SmartList() }).add { selectRadioButtonInGroup(buttonGroup) } } finally { buttonGroupStack.removeAt(buttonGroupStack.size - 1) } } private fun selectRadioButtonInGroup(buttonGroup: ButtonGroup) { if (buttonGroup.selection == null && buttonGroup.buttonCount > 0) { val e = buttonGroup.elements while (e.hasMoreElements()) { val radioButton = e.nextElement() if (radioButton.getClientProperty(UNBOUND_RADIO_BUTTON) != null) { buttonGroup.setSelected(radioButton.model, true) return } } buttonGroup.setSelected(buttonGroup.elements.nextElement().model, true) } } val defaultComponentConstraintCreator = DefaultComponentConstraintCreator(spacing) // keep in mind - MigLayout always creates one more than need column constraints (i.e. for 2 will be 3) // it doesn't lead to any issue. val columnConstraints = AC() // MigLayout in any case always creates CC, so, create instance even if it is not required private val Component.constraints: CC get() = componentConstraints.getOrPut(this) { CC() } fun updateComponentConstraints(component: Component, callback: CC.() -> Unit) { component.constraints.callback() } override fun build(container: Container, layoutConstraints: Array<out LCFlags>) { val lc = createLayoutConstraints() lc.gridGapY = gapToBoundSize(spacing.verticalGap, false) if (layoutConstraints.isEmpty()) { lc.fillX() // not fillY because it leads to enormously large cells - we use cc `push` in addition to cc `grow` as a more robust and easy solution } else { lc.apply(layoutConstraints) } /** * On macOS input fields (text fields, checkboxes, buttons and so on) have focus ring that drawn outside of component border. * If reported component dimensions will be equals to visible (when unfocused) component dimensions, focus ring will be clipped. * * Since LaF cannot control component environment (host component), default safe strategy is to report component dimensions including focus ring. * But it leads to an issue - spacing specified for visible component borders, not to compensated. For example, if horizontal space must be 8px, * this 8px must be between one visible border of component to another visible border (in the case of macOS Light theme, gray 1px borders). * Exactly 8px. * * So, advanced layout engine, e.g. MigLayout, offers a way to compensate visual padding on the layout container level, not on component level, as a solution. */ lc.isVisualPadding = true lc.hideMode = 3 val rowConstraints = AC() (container as JComponent).putClientProperty(IS_VISUAL_PADDING_COMPENSATED_ON_COMPONENT_LEVEL_KEY, false) var isLayoutInsetsAdjusted = false container.layout = object : MigLayout(lc, columnConstraints, rowConstraints) { override fun layoutContainer(parent: Container) { if (!isLayoutInsetsAdjusted) { isLayoutInsetsAdjusted = true if (container.getClientProperty(DialogWrapper.DIALOG_CONTENT_PANEL_PROPERTY) != null) { // since we compensate visual padding, child components should be not clipped, so, we do not use content pane DialogWrapper border (returns null), // but instead set insets to our content panel (so, child components are not clipped) lc.setInsets(spacing.dialogTopBottom, spacing.dialogLeftRight) } } super.layoutContainer(parent) } } configureGapBetweenColumns(rootRow) val physicalRows = collectPhysicalRows(rootRow) configureGapsBetweenRows(physicalRows) val isNoGrid = layoutConstraints.contains(LCFlags.noGrid) if (isNoGrid) { physicalRows.flatMap { it.components }.forEach { component -> container.add(component, component.constraints) } } else { for ((rowIndex, row) in physicalRows.withIndex()) { val isLastRow = rowIndex == physicalRows.size - 1 row.rowConstraints = rowConstraints.index(rowIndex).constaints[rowIndex]; if (row.noGrid) { rowConstraints.noGrid(rowIndex) } else { if (row.gapAfter != null) { rowConstraints.gap(row.gapAfter, rowIndex) } else if (isLastRow) { // Do not append default gap to the last row rowConstraints.gap("0px!", rowIndex) } } // if constraint specified only for rows 0 and 1, MigLayout will use constraint 1 for any rows with index 1+ (see LayoutUtil.getIndexSafe - use last element if index > size) // so, we set for each row to make sure that constraints from previous row will be not applied rowConstraints.align("baseline", rowIndex) for ((index, component) in row.components.withIndex()) { val cc = component.constraints // we cannot use columnCount as an indicator of whether to use spanX/wrap or not because component can share cell with another component, // in any case MigLayout is smart enough and unnecessary spanX doesn't harm if (index == row.components.size - 1) { cc.spanX() cc.isWrap = true if (row.components.size > 1) { cc.hideMode = 2 // if hideMode is 3, the wrap constraint won't be processed } } if (index >= row.rightIndex) { cc.horizontal.gapBefore = BoundSize(null, null, null, true, null) } container.add(component, cc) } } } } private fun collectPhysicalRows(rootRow: MigLayoutRow): List<MigLayoutRow> { val result = mutableListOf<MigLayoutRow>() fun collect(subRows: List<MigLayoutRow>?) { subRows?.forEach { row -> // skip synthetic rows that don't have components (e.g. titled row that contains only sub rows) if (row.components.isNotEmpty()) { result.add(row) } collect(row.subRows) } } collect(rootRow.subRows) return result } private fun configureGapBetweenColumns(rootRow: MigLayoutRow) { var startColumnIndexToApplyHorizontalGap = 0 if (rootRow.isLabeledIncludingSubRows) { // using columnConstraints instead of component gap allows easy debug (proper painting of debug grid) columnConstraints.gap("${spacing.labelColumnHorizontalGap}px!", 0) columnConstraints.grow(0f, 0) startColumnIndexToApplyHorizontalGap = 1 } val gapAfter = "${spacing.horizontalGap}px!" for (i in startColumnIndexToApplyHorizontalGap until rootRow.columnIndexIncludingSubRows) { columnConstraints.gap(gapAfter, i) } } private fun configureGapsBetweenRows(physicalRows: List<MigLayoutRow>) { for (rowIndex in physicalRows.indices) { if (rowIndex == 0) continue val prevRow = physicalRows[rowIndex - 1] val nextRow = physicalRows[rowIndex] val prevRowType = getRowType(prevRow) val nextRowType = getRowType(nextRow) if (prevRowType.isCheckboxRow && nextRowType.isCheckboxRow && (prevRowType == RowType.CHECKBOX_TALL || nextRowType == RowType.CHECKBOX_TALL)) { // ugly patching to make UI pretty IDEA-234078 if (prevRow.gapAfter == null && prevRow.components.all { it.constraints.vertical.gapAfter == null } && nextRow.components.all { it.constraints.vertical.gapBefore == null }) { prevRow.gapAfter = "0px!" for ((index, component) in prevRow.components.withIndex()) { if (index == 0) { component.constraints.gapBottom("${spacing.componentVerticalGap}px!") } else { component.constraints.gapBottom("${component.insets.bottom}px!") } } for ((index, component) in nextRow.components.withIndex()) { if (index == 0) { component.constraints.gapTop("${spacing.componentVerticalGap}px!") } else { component.constraints.gapTop("${component.insets.top}px!") } } } } else if (prevRowType == RowType.NESTED_PANEL) { prevRow.gapAfter = "0px!" } } } private fun getRowType(row: MigLayoutRow): RowType { if (row.components[0] is JCheckBox) { if (row.components.all { it is JCheckBox || it is JLabel }) return RowType.CHECKBOX if (row.components.all { it is JCheckBox || it is JLabel || it is JTextField || it is JPasswordField || it is JBTextArea || it is JComboBox<*> }) return RowType.CHECKBOX_TALL } if (row.components.singleOrNull() is DialogPanel) { return RowType.NESTED_PANEL } return RowType.GENERIC } private enum class RowType { GENERIC, CHECKBOX, CHECKBOX_TALL, NESTED_PANEL; val isCheckboxRow get() = this == CHECKBOX || this == CHECKBOX_TALL } } private fun LC.apply(flags: Array<out LCFlags>): LC { for (flag in flags) { @Suppress("NON_EXHAUSTIVE_WHEN") when (flag) { LCFlags.noGrid -> isNoGrid = true LCFlags.flowY -> isFlowX = false LCFlags.fill -> fill() LCFlags.fillX -> isFillX = true LCFlags.fillY -> isFillY = true LCFlags.debug -> debug() } } return this }
apache-2.0
e5cdc5c23a65ae6cc46c5eb62c0d483e
36.760736
181
0.672354
4.467877
false
false
false
false
androidx/androidx
compose/ui/ui-graphics/src/commonMain/kotlin/androidx/compose/ui/graphics/ColorMatrix.kt
3
10082
/* * 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. */ @file:Suppress("NOTHING_TO_INLINE") package androidx.compose.ui.graphics import kotlin.math.PI import kotlin.math.cos import kotlin.math.sin /** * 4x5 matrix for transforming the color and alpha components of a source. * The matrix can be passed as single array, and is treated as follows: * * ``` * [ a, b, c, d, e, * f, g, h, i, j, * k, l, m, n, o, * p, q, r, s, t ] * ``` * * When applied to a color <code>[[R, G, B, A]]</code>, the resulting color * is computed as: * * ``` * R' = a*R + b*G + c*B + d*A + e; * G' = f*R + g*G + h*B + i*A + j; * B' = k*R + l*G + m*B + n*A + o; * A' = p*R + q*G + r*B + s*A + t;</pre> * * ``` * That resulting color <code>[[R', G', B', A']]</code> * then has each channel clamped to the <code>0</code> to <code>255</code> * range. * * The sample ColorMatrix below inverts incoming colors by scaling each * channel by <code>-1</code>, and then shifting the result up by * `255` to remain in the standard color space. * * ``` * [ -1, 0, 0, 0, 255, * 0, -1, 0, 0, 255, * 0, 0, -1, 0, 255, * 0, 0, 0, 1, 0 ] * ``` * * This is often used as input for [ColorFilter.colorMatrix] and applied at draw time * through [Paint.colorFilter] */ @kotlin.jvm.JvmInline value class ColorMatrix( val values: FloatArray = floatArrayOf( 1f, 0f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 0f, 1f, 0f ) ) { /** * Obtain an instance of the matrix value at the given [row] and [column]. * [ColorMatrix] follows row major order in regards to the * positions of matrix values within the flattened array. That is, content order goes * from left to right then top to bottom as opposed to column major order. * * @param row Row index to query the ColorMatrix value. Range is from 0 to 3 as [ColorMatrix] * is represented as a 4 x 5 matrix * @param column Column index to query the ColorMatrix value. Range is from 0 to 4 as * [ColorMatrix] is represented as a 4 x 5 matrix */ inline operator fun get(row: Int, column: Int) = values[(row * 5) + column] /** * Set the matrix value at the given [row] and [column]. [ColorMatrix] follows row major * order in regards to the positions of matrix values within the flattened array. That is, * content order goes from left to right then top to bottom as opposed to column major order. * * @param row Row index to query the ColorMatrix value. Range is from 0 to 3 as [ColorMatrix] * is represented as a 4 x 5 matrix * @param column Column index to query the ColorMatrix value. Range is from 0 to 4 as * [ColorMatrix] is represented as a 4 x 5 matrix */ inline operator fun set(row: Int, column: Int, v: Float) { values[(row * 5) + column] = v } /** * Set this colormatrix to identity: * ``` * [ 1 0 0 0 0 - red vector * 0 1 0 0 0 - green vector * 0 0 1 0 0 - blue vector * 0 0 0 1 0 ] - alpha vector * ``` */ fun reset() { values.fill(0f) this[0, 0] = 1f this[2, 2] = 1f this[1, 1] = 1f this[3, 3] = 1f } /** * Assign the [src] colormatrix into this matrix, copying all of its values. */ fun set(src: ColorMatrix) { src.values.copyInto(values) } /** * Internal helper method to handle rotation computation * and provides a callback used to apply the result to different * color rotation axes */ private inline fun rotateInternal( degrees: Float, block: (cosine: Float, sine: Float) -> Unit ) { reset() val radians = degrees * PI / 180.0 val cosine = cos(radians).toFloat() val sine = sin(radians).toFloat() block(cosine, sine) } /** * Multiply this matrix by [colorMatrix] and assign the result to this matrix. */ operator fun timesAssign(colorMatrix: ColorMatrix) { val v00 = dot(this, 0, colorMatrix, 0) val v01 = dot(this, 0, colorMatrix, 1) val v02 = dot(this, 0, colorMatrix, 2) val v03 = dot(this, 0, colorMatrix, 3) val v04 = this[0, 0] * colorMatrix[0, 4] + this[0, 1] * colorMatrix[1, 4] + this[0, 2] * colorMatrix[2, 4] + this[0, 3] * colorMatrix[3, 4] + this[0, 4] val v10 = dot(this, 1, colorMatrix, 0) val v11 = dot(this, 1, colorMatrix, 1) val v12 = dot(this, 1, colorMatrix, 2) val v13 = dot(this, 1, colorMatrix, 3) val v14 = this[1, 0] * colorMatrix[0, 4] + this[1, 1] * colorMatrix[1, 4] + this[1, 2] * colorMatrix[2, 4] + this[1, 3] * colorMatrix[3, 4] + this[1, 4] val v20 = dot(this, 2, colorMatrix, 0) val v21 = dot(this, 2, colorMatrix, 1) val v22 = dot(this, 2, colorMatrix, 2) val v23 = dot(this, 2, colorMatrix, 3) val v24 = this[2, 0] * colorMatrix[0, 4] + this[2, 1] * colorMatrix[1, 4] + this[2, 2] * colorMatrix[2, 4] + this[2, 3] * colorMatrix[3, 4] + this[2, 4] val v30 = dot(this, 3, colorMatrix, 0) val v31 = dot(this, 3, colorMatrix, 1) val v32 = dot(this, 3, colorMatrix, 2) val v33 = dot(this, 3, colorMatrix, 3) val v34 = this[3, 0] * colorMatrix[0, 4] + this[3, 1] * colorMatrix[1, 4] + this[3, 2] * colorMatrix[2, 4] + this[3, 3] * colorMatrix[3, 4] + this[3, 4] this[0, 0] = v00 this[0, 1] = v01 this[0, 2] = v02 this[0, 3] = v03 this[0, 4] = v04 this[1, 0] = v10 this[1, 1] = v11 this[1, 2] = v12 this[1, 3] = v13 this[1, 4] = v14 this[2, 0] = v20 this[2, 1] = v21 this[2, 2] = v22 this[2, 3] = v23 this[2, 4] = v24 this[3, 0] = v30 this[3, 1] = v31 this[3, 2] = v32 this[3, 3] = v33 this[3, 4] = v34 } /** * Helper method that returns the dot product of the top left 4 x 4 matrix * of [ColorMatrix] used in [timesAssign] */ private fun dot(m1: ColorMatrix, row: Int, m2: ColorMatrix, column: Int): Float { return m1[row, 0] * m2[0, column] + m1[row, 1] * m2[1, column] + m1[row, 2] * m2[2, column] + m1[row, 3] * m2[3, column] } /** * Set the matrix to affect the saturation of colors. * * @param sat A value of 0 maps the color to gray-scale. 1 is identity. */ fun setToSaturation(sat: Float) { reset() val invSat = 1 - sat val R = 0.213f * invSat val G = 0.715f * invSat val B = 0.072f * invSat this[0, 0] = R + sat this[0, 1] = G this[0, 2] = B this[1, 0] = R this[1, 1] = G + sat this[1, 2] = B this[2, 0] = R this[2, 1] = G this[2, 2] = B + sat } /** * Create a [ColorMatrix] with the corresponding scale parameters * for the red, green, blue and alpha axes * * @param redScale Desired scale parameter for the red channel * @param greenScale Desired scale parameter for the green channel * @param blueScale Desired scale parameter for the blue channel * @param alphaScale Desired scale parameter for the alpha channel */ fun setToScale( redScale: Float, greenScale: Float, blueScale: Float, alphaScale: Float ) { reset() this[0, 0] = redScale this[1, 1] = greenScale this[2, 2] = blueScale this[3, 3] = alphaScale } /** * Rotate by [degrees] along the red color axis */ fun setToRotateRed(degrees: Float) { rotateInternal(degrees) { cosine, sine -> this[2, 2] = cosine this[1, 1] = cosine this[1, 2] = sine this[2, 1] = -sine } } /** * Rotate by [degrees] along the green color axis */ fun setToRotateGreen(degrees: Float) { rotateInternal(degrees) { cosine, sine -> this[2, 2] = cosine this[0, 0] = cosine this[0, 2] = -sine this[2, 0] = sine } } /** * Rotate by [degrees] along the blue color axis */ fun setToRotateBlue(degrees: Float) { rotateInternal(degrees) { cosine, sine -> this[1, 1] = cosine this[0, 0] = cosine this[0, 1] = sine this[1, 0] = -sine } } /** * Set the matrix to convert RGB to YUV */ fun convertRgbToYuv() { reset() // these coefficients match those in libjpeg this[0, 0] = 0.299f this[0, 1] = 0.587f this[0, 2] = 0.114f this[1, 0] = -0.16874f this[1, 1] = -0.33126f this[1, 2] = 0.5f this[2, 0] = 0.5f this[2, 1] = -0.41869f this[2, 2] = -0.08131f } /** * Set the matrix to convert from YUV to RGB */ fun convertYuvToRgb() { reset() // these coefficients match those in libjpeg this[0, 2] = 1.402f this[1, 0] = 1f this[1, 1] = -0.34414f this[1, 2] = -0.71414f this[2, 0] = 1f this[2, 1] = 1.772f this[2, 2] = 0f } }
apache-2.0
4485d264b1eb00c7010179f6ce70db11
29.740854
97
0.539476
3.236597
false
false
false
false
scenerygraphics/SciView
src/main/kotlin/sc/iview/ui/SwingNodePropertyTreeCellRenderer.kt
1
10254
/*- * #%L * Scenery-backed 3D visualization package for ImageJ. * %% * Copyright (C) 2016 - 2021 SciView developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package sc.iview.ui import graphics.scenery.* import graphics.scenery.primitives.TextBoard import graphics.scenery.volumes.Volume import org.joml.Vector3f import java.awt.* import java.awt.font.TextAttribute import java.awt.geom.Line2D import java.io.IOException import javax.imageio.ImageIO import javax.swing.* import javax.swing.tree.DefaultMutableTreeNode import javax.swing.tree.DefaultTreeCellRenderer /** * Class to render Node Property Tree with custom icons, depending on node type. * * @author Ulrik Guenther */ internal class SwingNodePropertyTreeCellRenderer : DefaultTreeCellRenderer() { private var nodeBackground: Color? = null private var overrideColor = false override fun getBackground(): Color { val bg = nodeBackground return if (overrideColor && bg != null) { bg } else { super.getBackground() ?: Color.WHITE } } override fun getBackgroundNonSelectionColor(): Color { val bg = nodeBackground return if (overrideColor && bg != null) { bg } else { super.getBackgroundNonSelectionColor() ?: Color.WHITE } } /** * Custom component renderer that puts icons on each cell dependent on Node type, and colors * the foreground and background of PointLights accordingly. */ override fun getTreeCellRendererComponent(tree: JTree, value: Any, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean): Component { val component = super.getTreeCellRendererComponent( tree, value, selected, expanded, leaf, row, hasFocus) as JLabel val node = value as DefaultMutableTreeNode val active = false val n = node.userObject as? Node overrideColor = false component.foreground = Color.BLACK var iconIndex = 0 if (n != null && !n.visible) { iconIndex = 1 } if (n is Camera) { icon = cameraIcon[iconIndex] setOpenIcon(cameraIcon[iconIndex]) setClosedIcon(cameraIcon[iconIndex]) text = if (active && n.getScene()!!.findObserver() === n) { n.name + " (active)" } else { n.name } } else if (n is Light) { icon = lightIcon[iconIndex] setOpenIcon(lightIcon[iconIndex]) setClosedIcon(lightIcon[iconIndex]) // Here, we set the background of the point light to its emission color. // First, we convert the emission color of the light to // HSL to determine whether a light or dark font color is needed: val emissionColor = n.emissionColor val awtEmissionColor = Color( emissionColor.x(), emissionColor.y(), emissionColor.z()) val hslEmissionColor = convertRGBtoHSL(emissionColor) isOpaque = true overrideColor = true nodeBackground = awtEmissionColor // if lightness is below 0.5, we use a light font, // if above, a dark font. if (hslEmissionColor.z() <= 0.5f) { component.foreground = Color.LIGHT_GRAY } else { component.foreground = Color.BLACK } } else if (n is TextBoard) { icon = textIcon[iconIndex] setOpenIcon(textIcon[iconIndex]) setClosedIcon(textIcon[iconIndex]) } else if (n is Volume) { icon = volumeIcon[iconIndex] setOpenIcon(volumeIcon[iconIndex]) setClosedIcon(volumeIcon[iconIndex]) } else if (n is Mesh) { icon = meshIcon[iconIndex] setOpenIcon(meshIcon[iconIndex]) setClosedIcon(meshIcon[iconIndex]) } else if (n is Scene) { icon = sceneIcon[iconIndex] setOpenIcon(sceneIcon[iconIndex]) setClosedIcon(sceneIcon[iconIndex]) } else { if (!leaf && n == null) { icon = sceneIcon[iconIndex] setOpenIcon(sceneIcon[iconIndex]) setClosedIcon(sceneIcon[iconIndex]) } else { icon = nodeIcon[iconIndex] setOpenIcon(nodeIcon[iconIndex]) setClosedIcon(nodeIcon[iconIndex]) } } var font = component.font val attributes = font.attributes val map = HashMap<TextAttribute, Any>(attributes.size) attributes.forEach { (t, v: Any?) -> if(v != null) { map[t] = v }} map[TextAttribute.FONT] = font map[TextAttribute.UNDERLINE] = -1 if (selected) { map[TextAttribute.FONT] = font map[TextAttribute.UNDERLINE] = TextAttribute.UNDERLINE_LOW_DOTTED } if (active) { map[TextAttribute.FONT] = font map[TextAttribute.WEIGHT] = TextAttribute.WEIGHT_BOLD } font = Font.getFont(map) component.font = font return this } companion object { private val cameraIcon = getImageIcons("camera.png") private val lightIcon = getImageIcons("light.png") private val meshIcon = getImageIcons("mesh.png") private val nodeIcon = getImageIcons("node.png") private val sceneIcon = getImageIcons("scene.png") private val textIcon = getImageIcons("text.png") private val volumeIcon = getImageIcons("volume.png") private fun getImageIcons(name: String): Array<Icon> { var icon: ImageIcon var disabledIcon: ImageIcon try { val iconImage = ImageIO.read(SwingNodePropertyTreeCellRenderer::class.java.getResourceAsStream(name)) val disabledIconImage = ImageIO.read(SwingNodePropertyTreeCellRenderer::class.java.getResourceAsStream(name)) icon = ImageIcon(iconImage.getScaledInstance(16, 16, Image.SCALE_SMOOTH)) val width = disabledIconImage.width val height = disabledIconImage.height val g2 = disabledIconImage.createGraphics() val l: Line2D = Line2D.Float(0.0f, height.toFloat(), width.toFloat(), 0.0f) g2.color = Color.RED g2.stroke = BasicStroke(4.0f) g2.draw(l) g2.dispose() disabledIcon = ImageIcon(disabledIconImage.getScaledInstance(16, 16, Image.SCALE_SMOOTH)) } catch (npe: NullPointerException) { System.err.println("Could not load image $name as it was not found, returning default.") icon = UIManager.get("Tree.leafIcon") as ImageIcon disabledIcon = UIManager.get("Tree.leafIcon") as ImageIcon } catch (e: IOException) { System.err.println("Could not load image $name because of IO error, returning default.") icon = UIManager.get("Tree.leafIcon") as ImageIcon disabledIcon = UIManager.get("Tree.leafIcon") as ImageIcon } return arrayOf(icon, disabledIcon) } /** * Converts a GLVector containing an RGB color to a GLVector containing * the color converted to HSL space. The RGB colors are assumed to be within [0, 1], * which is scenery's convention. Divide by 255 before otherwise. * * The conversion algorithm follows https://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_RGB_to_HSL/HSV_used_commonly_in_software_programming * * @param rgb RGB color, with each channel in [0, 1]. * @return converted color in HSL space */ fun convertRGBtoHSL(rgb: Vector3f): Vector3f { val max = Math.max(rgb.x(), Math.max(rgb.y(), rgb.z())) val min = Math.min(rgb.x(), Math.min(rgb.y(), rgb.z())) var h: Float val s: Float val l = (max + min) / 2.0f if (max == min) { h = 0.0f s = 0.0f } else { val diff = max - min s = if (l > 0.5f) { diff / (2 - max - min) } else { diff / (max + min) } h = if (max == rgb.x()) { (rgb.y() - rgb.z()) / diff + if (rgb.y() < rgb.z()) 6.0f else 0.0f } else if (max == rgb.y()) { (rgb.z() - rgb.x()) / diff + 2.0f } else { (rgb.x() - rgb.y()) / diff + 4.0f } h /= 6.0f } return Vector3f(h, s, l) } } init { isOpaque = true } }
bsd-2-clause
1ae95e97d91f0772522cff60bd2c31a7
40.016
149
0.589819
4.491459
false
false
false
false
GunoH/intellij-community
plugins/kotlin/compiler-plugins/allopen/maven/src/org/jetbrains/kotlin/idea/compilerPlugin/allopen/maven/AllOpenMavenProjectImportHandler.kt
4
2154
// 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.compilerPlugin.allopen.maven import org.jetbrains.idea.maven.project.MavenProject import org.jetbrains.kotlin.allopen.AllOpenPluginNames.ANNOTATION_OPTION_NAME import org.jetbrains.kotlin.allopen.AllOpenPluginNames.PLUGIN_ID import org.jetbrains.kotlin.allopen.AllOpenPluginNames.SUPPORTED_PRESETS import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifacts import org.jetbrains.kotlin.idea.compilerPlugin.CompilerPluginSetup.PluginOption import org.jetbrains.kotlin.idea.compilerPlugin.toJpsVersionAgnosticKotlinBundledPath import org.jetbrains.kotlin.idea.maven.compilerPlugin.AbstractMavenImportHandler class AllOpenMavenProjectImportHandler : AbstractMavenImportHandler() { private companion object { val ANNOTATION_PARAMETER_PREFIX = "all-open:$ANNOTATION_OPTION_NAME=" } override val compilerPluginId = PLUGIN_ID override val pluginName = "allopen" override val mavenPluginArtifactName = "kotlin-maven-allopen" override val pluginJarFileFromIdea = KotlinArtifacts.allopenCompilerPlugin.toJpsVersionAgnosticKotlinBundledPath() override fun getOptions( mavenProject: MavenProject, enabledCompilerPlugins: List<String>, compilerPluginOptions: List<String> ): List<PluginOption>? { if ("all-open" !in enabledCompilerPlugins && "spring" !in enabledCompilerPlugins) { return null } val annotations = mutableListOf<String>() for ((presetName, presetAnnotations) in SUPPORTED_PRESETS) { if (presetName in enabledCompilerPlugins) { annotations.addAll(presetAnnotations) } } annotations.addAll(compilerPluginOptions.mapNotNull { text -> if (!text.startsWith(ANNOTATION_PARAMETER_PREFIX)) return@mapNotNull null text.substring(ANNOTATION_PARAMETER_PREFIX.length) }) return annotations.map { PluginOption(ANNOTATION_OPTION_NAME, it) } } }
apache-2.0
2b6b961f5004452d6a22d8b4b32a93dc
43.875
158
0.752553
4.951724
false
false
false
false
GunoH/intellij-community
plugins/eclipse/src/org/jetbrains/idea/eclipse/config/EmlFileSaver.kt
2
8709
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.idea.eclipse.config import com.intellij.openapi.components.PathMacroMap import com.intellij.openapi.roots.JavadocOrderRootType import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.vfs.JarFileSystem import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryNameGenerator import com.intellij.workspaceModel.ide.impl.virtualFile import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.bridgeEntities.LibraryEntity import com.intellij.workspaceModel.storage.bridgeEntities.LibraryTableId import com.intellij.workspaceModel.storage.bridgeEntities.ModuleDependencyItem import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity import com.intellij.workspaceModel.storage.bridgeEntities.asJavaSourceRoot import org.jdom.Element import org.jetbrains.annotations.NonNls import org.jetbrains.idea.eclipse.IdeaXml.* import org.jetbrains.idea.eclipse.conversion.EPathUtil import org.jetbrains.idea.eclipse.conversion.IdeaSpecificSettings import org.jetbrains.jps.model.serialization.java.JpsJavaModelSerializerExtension import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer /** * Saves additional module configuration from [ModuleEntity] to *.eml file */ internal class EmlFileSaver(private val module: ModuleEntity, private val entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>, private val pathShortener: ModulePathShortener, private val moduleReplacePathMacroMap: PathMacroMap, private val projectReplacePathMacroMap: PathMacroMap) { fun saveEml(): Element? { val root = Element(COMPONENT_TAG) saveCustomJavaSettings(root) saveContentRoots(root) @Suppress("UNCHECKED_CAST") val moduleLibraries = (entities[LibraryEntity::class.java] as List<LibraryEntity>? ?: emptyList()).associateBy { it.name } val libLevels = LinkedHashMap<String, String>() module.dependencies.forEach { dep -> when (dep) { is ModuleDependencyItem.Exportable.ModuleDependency -> { if (dep.scope != ModuleDependencyItem.DependencyScope.COMPILE) { root.addContent(Element("module").setAttribute("name", dep.module.name).setAttribute("scope", dep.scope.name)) } } is ModuleDependencyItem.InheritedSdkDependency -> { root.setAttribute(IdeaSpecificSettings.INHERIT_JDK, true.toString()) } is ModuleDependencyItem.SdkDependency -> { root.setAttribute("jdk", dep.sdkName) root.setAttribute("jdk_type", dep.sdkType) } is ModuleDependencyItem.Exportable.LibraryDependency -> { val libTag = Element("lib") val library = moduleLibraries[dep.library.name] val libName = LibraryNameGenerator.getLegacyLibraryName(dep.library) ?: generateLibName(library) libTag.setAttribute("name", libName) libTag.setAttribute("scope", dep.scope.name) when (val tableId = dep.library.tableId) { is LibraryTableId.ModuleLibraryTableId -> { if (library != null) { val srcRoots = library.roots.filter { it.type.name == OrderRootType.SOURCES.name() } val eclipseUrl = srcRoots.firstOrNull()?.url?.url?.substringBefore(JarFileSystem.JAR_SEPARATOR) srcRoots.forEach { val url = it.url.url val srcTag = Element(IdeaSpecificSettings.SRCROOT_ATTR).setAttribute("url", url) if (!EPathUtil.areUrlsPointTheSame(url, eclipseUrl)) { srcTag.setAttribute(IdeaSpecificSettings.SRCROOT_BIND_ATTR, false.toString()) } libTag.addContent(srcTag) } library.roots.filter { it.type.name == "JAVADOC" }.drop(1).forEach { libTag.addContent(Element(IdeaSpecificSettings.JAVADOCROOT_ATTR).setAttribute("url", it.url.url)) } saveModuleRelatedRoots(libTag, library, OrderRootType.SOURCES, IdeaSpecificSettings.RELATIVE_MODULE_SRC) saveModuleRelatedRoots(libTag, library, OrderRootType.CLASSES, IdeaSpecificSettings.RELATIVE_MODULE_CLS) saveModuleRelatedRoots(libTag, library, JavadocOrderRootType.getInstance(), IdeaSpecificSettings.RELATIVE_MODULE_JAVADOC) } } is LibraryTableId.ProjectLibraryTableId -> libLevels[dep.library.name] = LibraryTablesRegistrar.PROJECT_LEVEL is LibraryTableId.GlobalLibraryTableId -> { if (tableId.level != LibraryTablesRegistrar.APPLICATION_LEVEL) { libLevels[dep.library.name] = tableId.level } } } if (libTag.children.isNotEmpty() || dep.scope != ModuleDependencyItem.DependencyScope.COMPILE) { root.addContent(libTag) } } else -> {} } } if (libLevels.isNotEmpty()) { val levelsTag = Element("levels") for ((name, level) in libLevels) { levelsTag.addContent(Element("level").setAttribute("name", name).setAttribute("value", level)) } root.addContent(levelsTag) } moduleReplacePathMacroMap.substitute(root, SystemInfo.isFileSystemCaseSensitive) return if (JDOMUtil.isEmpty(root)) null else root } private fun saveModuleRelatedRoots(libTag: Element, library: LibraryEntity, type: OrderRootType, tagName: @NonNls String) { library.roots.filter { it.type.name == type.name() }.forEach { val file = it.url.virtualFile val localFile = if (file?.fileSystem is JarFileSystem) JarFileSystem.getInstance().getVirtualFileForJar(file) else file if (localFile != null && pathShortener.isUnderContentRoots(localFile)) { libTag.addContent(Element(tagName).setAttribute(IdeaSpecificSettings.PROJECT_RELATED, projectReplacePathMacroMap.substitute(it.url.url, SystemInfo.isFileSystemCaseSensitive))) } } } private fun generateLibName(library: LibraryEntity?): String { val firstRoot = library?.roots?.firstOrNull { it.type.name == OrderRootType.CLASSES.name() }?.url val file = firstRoot?.virtualFile val fileForJar = JarFileSystem.getInstance().getVirtualFileForJar(file) if (fileForJar != null) return fileForJar.name return file?.name ?: "Empty Library" } private fun saveContentRoots(root: Element) { module.contentRoots.forEach { contentRoot -> val contentRootTag = Element(CONTENT_ENTRY_TAG).setAttribute(URL_ATTR, contentRoot.url.url) contentRoot.sourceRoots.forEach { sourceRoot -> if (sourceRoot.rootType == JpsModuleRootModelSerializer.JAVA_TEST_ROOT_TYPE_ID) { contentRootTag.addContent(Element(TEST_FOLDER_TAG).setAttribute(URL_ATTR, sourceRoot.url.url)) } val packagePrefix = sourceRoot.asJavaSourceRoot()?.packagePrefix if (!packagePrefix.isNullOrEmpty()) { contentRootTag.addContent(Element(PACKAGE_PREFIX_TAG).setAttribute(URL_ATTR, sourceRoot.url.url) .setAttribute(PACKAGE_PREFIX_VALUE_ATTR, packagePrefix)) } } val rootFile = contentRoot.url.virtualFile contentRoot.excludedUrls.forEach { excluded -> val excludedFile = excluded.url.virtualFile if (rootFile == null || excludedFile == null || VfsUtilCore.isAncestor(rootFile, excludedFile, false)) { contentRootTag.addContent(Element(EXCLUDE_FOLDER_TAG).setAttribute(URL_ATTR, excluded.url.url)) } } if (!JDOMUtil.isEmpty(contentRootTag)) { root.addContent(contentRootTag) } } } private fun saveCustomJavaSettings(root: Element) { module.javaSettings?.let { javaSettings -> javaSettings.compilerOutputForTests?.let { testOutput -> root.addContent(Element(OUTPUT_TEST_TAG).setAttribute(URL_ATTR, testOutput.url)) } if (javaSettings.inheritedCompilerOutput) { root.setAttribute(JpsJavaModelSerializerExtension.INHERIT_COMPILER_OUTPUT_ATTRIBUTE, true.toString()) } if (javaSettings.excludeOutput) { root.addContent(Element(EXCLUDE_OUTPUT_TAG)) } javaSettings.languageLevelId?.let { root.setAttribute("LANGUAGE_LEVEL", it) } } } }
apache-2.0
416768a30c0998efa91c02716a124a1c
49.639535
183
0.698243
4.798347
false
false
false
false
jwren/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/usagesSearch/operators/OperatorReferenceSearcher.kt
2
15071
// 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.search.usagesSearch.operators import com.intellij.openapi.progress.ProgressIndicatorProvider import com.intellij.openapi.progress.util.ProgressWrapper import com.intellij.psi.* import com.intellij.psi.search.* import com.intellij.util.Processor import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.asJava.namedUnwrappedElement import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.forceResolveReferences import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.getReceiverTypeSearcherInfo import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinRequestResultProcessor import org.jetbrains.kotlin.idea.search.isPotentiallyOperator import org.jetbrains.kotlin.idea.search.restrictToKotlinSources import org.jetbrains.kotlin.idea.search.usagesSearch.ExpressionsOfTypeProcessor import org.jetbrains.kotlin.idea.search.usagesSearch.ExpressionsOfTypeProcessor.Companion.logPresentation import org.jetbrains.kotlin.idea.search.usagesSearch.ExpressionsOfTypeProcessor.Companion.testLog import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.ifTrue import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.resolve.DataClassDescriptorResolver import org.jetbrains.kotlin.types.expressions.OperatorConventions import org.jetbrains.kotlin.util.OperatorNameConventions import org.jetbrains.kotlin.utils.addToStdlib.safeAs import java.util.* abstract class OperatorReferenceSearcher<TReferenceElement : KtElement>( protected val targetDeclaration: PsiElement, private val searchScope: SearchScope, private val consumer: Processor<in PsiReference>, private val optimizer: SearchRequestCollector, private val options: KotlinReferencesSearchOptions, private val wordsToSearch: List<String> ) { private val project = targetDeclaration.project /** * Invoked for all expressions that may have type matching receiver type of our operator */ protected abstract fun processPossibleReceiverExpression(expression: KtExpression) /** * Extract reference that may resolve to our operator (no actual resolve to be performed) */ protected abstract fun extractReference(element: KtElement): PsiReference? /** * Check if reference may potentially resolve to our operator (no actual resolve to be performed) */ protected abstract fun isReferenceToCheck(ref: PsiReference): Boolean protected fun processReferenceElement(element: TReferenceElement): Boolean { val reference = extractReference(element) ?: return true testLog { "Resolved ${logPresentation(element)}" } return if (reference.isReferenceTo(targetDeclaration)) { consumer.process(reference) } else { true } } companion object { fun create( declaration: PsiElement, searchScope: SearchScope, consumer: Processor<in PsiReference>, optimizer: SearchRequestCollector, options: KotlinReferencesSearchOptions ): OperatorReferenceSearcher<*>? = declaration.isValid.ifTrue { createInReadAction(declaration, searchScope, consumer, optimizer, options) } private fun createInReadAction( declaration: PsiElement, searchScope: SearchScope, consumer: Processor<in PsiReference>, optimizer: SearchRequestCollector, options: KotlinReferencesSearchOptions ): OperatorReferenceSearcher<*>? { val functionName = when (declaration) { is KtNamedFunction -> declaration.name is PsiMethod -> declaration.name else -> null } ?: return null if (!Name.isValidIdentifier(functionName)) return null val name = Name.identifier(functionName) val declarationToUse = if (declaration is KtLightMethod) { declaration.kotlinOrigin ?: return null } else { declaration } return createInReadAction(declarationToUse, name, consumer, optimizer, options, searchScope) } private fun createInReadAction( declaration: PsiElement, name: Name, consumer: Processor<in PsiReference>, optimizer: SearchRequestCollector, options: KotlinReferencesSearchOptions, searchScope: SearchScope ): OperatorReferenceSearcher<*>? { if (DataClassDescriptorResolver.isComponentLike(name)) { if (!options.searchForComponentConventions) return null val componentIndex = DataClassDescriptorResolver.getComponentIndex(name.asString()) return DestructuringDeclarationReferenceSearcher(declaration, componentIndex, searchScope, consumer, optimizer, options) } if (!options.searchForOperatorConventions) return null // Java has no operator modifier val operator = declaration !is KtElement || declaration.isPotentiallyOperator() val binaryOp = OperatorConventions.BINARY_OPERATION_NAMES.inverse()[name] val assignmentOp = OperatorConventions.ASSIGNMENT_OPERATIONS.inverse()[name] val unaryOp = OperatorConventions.UNARY_OPERATION_NAMES.inverse()[name] return when { operator && binaryOp != null -> { val counterpartAssignmentOp = OperatorConventions.ASSIGNMENT_OPERATION_COUNTERPARTS.inverse()[binaryOp] val operationTokens = listOfNotNull(binaryOp, counterpartAssignmentOp) BinaryOperatorReferenceSearcher(declaration, operationTokens, searchScope, consumer, optimizer, options) } operator && assignmentOp != null -> BinaryOperatorReferenceSearcher(declaration, listOf(assignmentOp), searchScope, consumer, optimizer, options) operator && unaryOp != null -> UnaryOperatorReferenceSearcher(declaration, unaryOp, searchScope, consumer, optimizer, options) operator && name == OperatorNameConventions.INVOKE -> InvokeOperatorReferenceSearcher(declaration, searchScope, consumer, optimizer, options) operator && name == OperatorNameConventions.GET -> IndexingOperatorReferenceSearcher(declaration, searchScope, consumer, optimizer, options, isSet = false) operator && name == OperatorNameConventions.SET -> IndexingOperatorReferenceSearcher(declaration, searchScope, consumer, optimizer, options, isSet = true) operator && name == OperatorNameConventions.CONTAINS -> ContainsOperatorReferenceSearcher(declaration, searchScope, consumer, optimizer, options) name == OperatorNameConventions.EQUALS -> BinaryOperatorReferenceSearcher( declaration, listOf(KtTokens.EQEQ, KtTokens.EXCLEQ), searchScope, consumer, optimizer, options ) operator && name == OperatorNameConventions.COMPARE_TO -> BinaryOperatorReferenceSearcher( declaration, listOf(KtTokens.LT, KtTokens.GT, KtTokens.LTEQ, KtTokens.GTEQ), searchScope, consumer, optimizer, options ) operator && name == OperatorNameConventions.ITERATOR -> IteratorOperatorReferenceSearcher(declaration, searchScope, consumer, optimizer, options) operator && (name == OperatorNameConventions.GET_VALUE || name == OperatorNameConventions.SET_VALUE || name == OperatorNameConventions.PROVIDE_DELEGATE) -> PropertyDelegationOperatorReferenceSearcher(declaration, searchScope, consumer, optimizer, options) else -> null } } private object SearchesInProgress : ThreadLocal<HashSet<PsiElement>>() { override fun initialValue() = HashSet<PsiElement>() } } fun run() { val (psiClass, containsTypeOrDerivedInside) = runReadAction { targetDeclaration.getReceiverTypeSearcherInfo(this is DestructuringDeclarationReferenceSearcher) } ?: return val inProgress = SearchesInProgress.get() if (psiClass != null) { if (!inProgress.add(psiClass)) { testLog { "ExpressionOfTypeProcessor is already started for ${runReadAction { psiClass.qualifiedName }}. Exit for operator ${logPresentation( targetDeclaration )}." } return } } else { if (!inProgress.add(targetDeclaration)) { testLog { "ExpressionOfTypeProcessor is already started for operator ${logPresentation(targetDeclaration)}. Exit." } return //TODO: it's not quite correct } } try { ExpressionsOfTypeProcessor( containsTypeOrDerivedInside, psiClass, searchScope, project, possibleMatchHandler = { expression -> processPossibleReceiverExpression(expression) }, possibleMatchesInScopeHandler = { searchScope -> doPlainSearch(searchScope) } ).run() } finally { inProgress.remove(psiClass ?: targetDeclaration) } } private fun doPlainSearch(scope: SearchScope) { testLog { "Used plain search of ${logPresentation(targetDeclaration)} in ${scope.logPresentation()}" } val progress = ProgressWrapper.unwrap(ProgressIndicatorProvider.getGlobalProgressIndicator()) if (scope is LocalSearchScope) { for (element in scope.scope) { if (element is KtElement) { runReadAction { if (element.isValid) { progress?.checkCanceled() val refs = ArrayList<PsiReference>() val elements = element.collectDescendantsOfType<KtElement> { val ref = extractReference(it) ?: return@collectDescendantsOfType false refs.add(ref) true }.ifEmpty { return@runReadAction } // resolve all references at once element.containingFile.safeAs<KtFile>()?.forceResolveReferences(elements) for (ref in refs) { progress?.checkCanceled() if (ref.isReferenceTo(targetDeclaration)) { consumer.process(ref) } } } } } } } else { scope as GlobalSearchScope if (wordsToSearch.isNotEmpty()) { val unwrappedElement = targetDeclaration.namedUnwrappedElement ?: return val resultProcessor = KotlinRequestResultProcessor( unwrappedElement, filter = { ref -> isReferenceToCheck(ref) }, options = options ) wordsToSearch.forEach { optimizer.searchWord( it, scope.restrictToKotlinSources(), UsageSearchContext.IN_CODE, true, unwrappedElement, resultProcessor ) } } else { val psiManager = PsiManager.getInstance(project) // we must unwrap progress indicator because ProgressWrapper does not do anything on changing text and fraction progress?.pushState() progress?.text = KotlinBundle.message("searching.for.implicit.usages") progress?.isIndeterminate = false try { val files = runReadAction { FileTypeIndex.getFiles(KotlinFileType.INSTANCE, scope) } for ((index, file) in files.withIndex()) { progress?.checkCanceled() runReadAction { if (file.isValid) { progress?.fraction = index / files.size.toDouble() progress?.text2 = file.path psiManager.findFile(file).safeAs<KtFile>()?.let { doPlainSearch(LocalSearchScope(it)) } } } } } finally { progress?.popState() } } } } private fun SearchScope.logPresentation(): String { return when (this) { searchScope -> "whole search scope" is LocalSearchScope -> { scope .map { element -> " " + runReadAction { when (element) { is KtFunctionLiteral -> element.text is KtWhenEntry -> { if (element.isElse) "KtWhenEntry \"else\"" else "KtWhenEntry \"" + element.conditions.joinToString(", ") { it.text } + "\"" } is KtNamedDeclaration -> element.node.elementType.toString() + ":" + element.name else -> element.toString() } } } .toList() .sorted() .joinToString("\n", "LocalSearchScope:\n") } else -> this.displayName } } }
apache-2.0
7bdbfa94e6952fbda192e406836de1fe
43.991045
171
0.586292
6.473797
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineNamedFunctionHandler.kt
3
2793
// 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.inline import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.refactoring.RefactoringBundle import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.isAnonymousFunction import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall class KotlinInlineNamedFunctionHandler : AbstractKotlinInlineFunctionHandler<KtNamedFunction>() { override fun canInlineKotlinFunction(function: KtFunction): Boolean = function is KtNamedFunction && !function.isAnonymousFunction override fun inlineKotlinFunction(project: Project, editor: Editor?, function: KtNamedFunction) { val nameReference = editor?.findSimpleNameReference() val recursive = function.isRecursive() if (recursive && nameReference == null) { val message = RefactoringBundle.getCannotRefactorMessage( KotlinBundle.message("text.inline.recursive.function.is.supported.only.on.references") ) return showErrorHint(project, editor, message) } val dialog = KotlinInlineNamedFunctionDialog( function, nameReference, allowToInlineThisOnly = recursive, editor = editor, ) if (!isUnitTestMode()) { dialog.show() } else { try { dialog.doAction() } finally { dialog.close(DialogWrapper.OK_EXIT_CODE, true) } } } private fun KtNamedFunction.isRecursive(): Boolean { val context = analyzeWithContent() return bodyExpression?.includesCallOf(context[BindingContext.FUNCTION, this] ?: return false, context) ?: false } private fun KtExpression.includesCallOf(descriptor: FunctionDescriptor, context: BindingContext): Boolean { val refDescriptor = getResolvedCall(context)?.resultingDescriptor return descriptor == refDescriptor || anyDescendantOfType<KtExpression> { it !== this && descriptor == it.getResolvedCall(context)?.resultingDescriptor } } }
apache-2.0
193d17d0cb8fb53e5d4901ed00d64724
42.640625
158
0.725743
5.124771
false
false
false
false
jwren/intellij-community
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/KeywordValues.kt
1
7884
// 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.completion import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.psi.PsiElement import com.intellij.psi.util.elementType import org.jetbrains.kotlin.builtins.ReflectionTypes import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference import org.jetbrains.kotlin.idea.completion.smart.ExpectedInfoMatch import org.jetbrains.kotlin.idea.completion.smart.SmartCompletionItemPriority import org.jetbrains.kotlin.idea.completion.smart.matchExpectedInfo import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.util.CallTypeAndReceiver import org.jetbrains.kotlin.idea.util.toFuzzyType import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtOperationReferenceExpression import org.jetbrains.kotlin.psi.KtValueArgument import org.jetbrains.kotlin.psi.psiUtil.getNextSiblingIgnoringWhitespaceAndComments import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.types.KotlinTypeFactory import org.jetbrains.kotlin.types.TypeAttributes import org.jetbrains.kotlin.types.TypeProjectionImpl import org.jetbrains.kotlin.types.TypeSubstitutor import org.jetbrains.kotlin.types.typeUtil.isBooleanOrNullableBoolean object KeywordValues { interface Consumer { /** * @param suitableOnPsiLevel together with [expectedInfoMatcher] the function is called to make a decision whether * [factory's][factory] output should be tagged with [priority]. Note that the function is used only as a fallback (in the case * where [expectedInfoMatcher] has no input data to process). * * Function receiver is a current position of the caret. */ fun consume( lookupString: String, expectedInfoMatcher: (ExpectedInfo) -> ExpectedInfoMatch, suitableOnPsiLevel: PsiElement.() -> Boolean = { false }, priority: SmartCompletionItemPriority, factory: () -> LookupElement ) } fun process( consumer: Consumer, callTypeAndReceiver: CallTypeAndReceiver<*, *>, bindingContext: BindingContext, resolutionFacade: ResolutionFacade, moduleDescriptor: ModuleDescriptor, isJvmModule: Boolean ) { if (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) { val booleanInfoMatcher = matcher@{ info: ExpectedInfo -> // no sense in true or false as if-condition or when entry for when with no subject val additionalData = info.additionalData val skipTrueFalse = when (additionalData) { is IfConditionAdditionalData -> true is WhenEntryAdditionalData -> !additionalData.whenWithSubject else -> false } if (skipTrueFalse) { return@matcher ExpectedInfoMatch.noMatch } if (info.fuzzyType?.type?.isBooleanOrNullableBoolean() ?: false) ExpectedInfoMatch.match(TypeSubstitutor.EMPTY) else ExpectedInfoMatch.noMatch } consumer.consume("true", booleanInfoMatcher, priority = SmartCompletionItemPriority.TRUE) { LookupElementBuilder.create(KeywordLookupObject(), "true").bold() } consumer.consume("false", booleanInfoMatcher, priority = SmartCompletionItemPriority.FALSE) { LookupElementBuilder.create(KeywordLookupObject(), "false").bold() } val nullMatcher = { info: ExpectedInfo -> when { (info.additionalData as? ComparisonOperandAdditionalData)?.suppressNullLiteral == true -> ExpectedInfoMatch.noMatch info.fuzzyType?.type?.isMarkedNullable == true -> ExpectedInfoMatch.match(TypeSubstitutor.EMPTY) else -> ExpectedInfoMatch.noMatch } } // Position (this) is suitable for 'null' when the caret points to a function argument (fun is not imported!) or // it's a part of a binary expression (left- or right- hand side) with unknown declarations. val positionIsSuitableForNull: PsiElement.() -> Boolean = { elementType == KtTokens.IDENTIFIER && (context?.parent is KtValueArgument || (context is KtExpression && ((context as KtExpression).getPrevSiblingIgnoringWhitespaceAndComments() is KtOperationReferenceExpression || (context as KtExpression).getNextSiblingIgnoringWhitespaceAndComments() is KtOperationReferenceExpression))) } consumer.consume("null", nullMatcher, positionIsSuitableForNull, SmartCompletionItemPriority.NULL) { LookupElementBuilder.create(KeywordLookupObject(), "null").bold() } } if (callTypeAndReceiver is CallTypeAndReceiver.CALLABLE_REFERENCE && callTypeAndReceiver.receiver != null) { val qualifierType = bindingContext.get(BindingContext.DOUBLE_COLON_LHS, callTypeAndReceiver.receiver!!)?.type if (qualifierType != null) { @OptIn(FrontendInternals::class) val kClassDescriptor = resolutionFacade.getFrontendService(ReflectionTypes::class.java).kClass val classLiteralType = KotlinTypeFactory.simpleNotNullType(TypeAttributes.Empty, kClassDescriptor, listOf(TypeProjectionImpl(qualifierType))) val kClassTypes = listOf(classLiteralType.toFuzzyType(emptyList())) val kClassMatcher = { info: ExpectedInfo -> kClassTypes.matchExpectedInfo(info) } consumer.consume("class", kClassMatcher, priority = SmartCompletionItemPriority.CLASS_LITERAL) { LookupElementBuilder.create(KeywordLookupObject(), "class").bold() } if (isJvmModule) { val javaLangClassDescriptor = resolutionFacade.resolveImportReference(moduleDescriptor, FqName("java.lang.Class")) .singleOrNull() as? ClassDescriptor if (javaLangClassDescriptor != null) { val javaLangClassType = KotlinTypeFactory.simpleNotNullType( TypeAttributes.Empty, javaLangClassDescriptor, listOf(TypeProjectionImpl(qualifierType)) ) val javaClassTypes = listOf(javaLangClassType.toFuzzyType(emptyList())) val javaClassMatcher = { info: ExpectedInfo -> javaClassTypes.matchExpectedInfo(info) } consumer.consume("class", javaClassMatcher, priority = SmartCompletionItemPriority.CLASS_LITERAL) { LookupElementBuilder.create(KeywordLookupObject(), "class.java") .withPresentableText("class") .withTailText(".java") .bold() } } } } } } }
apache-2.0
3b67396a149feb6db65b2e4deb1f247f
52.27027
158
0.662988
5.797059
false
false
false
false
Cognifide/gradle-aem-plugin
src/main/kotlin/com/cognifide/gradle/aem/pkg/tasks/compose/BundleInstalledBuilt.kt
1
1026
package com.cognifide.gradle.aem.pkg.tasks.compose import com.cognifide.gradle.aem.bundle.tasks.bundle import com.cognifide.gradle.aem.common.pkg.vault.FilterType import com.cognifide.gradle.aem.pkg.tasks.PackageCompose import org.gradle.api.tasks.TaskProvider import org.gradle.api.tasks.bundling.Jar class BundleInstalledBuilt(target: PackageCompose, private val task: TaskProvider<Jar>) : BundleInstalled { private val aem = target.aem override val file = aem.obj.file { convention(task.flatMap { it.archiveFile }) } override val dirPath = aem.obj.string { convention(task.flatMap { it.bundle.installPath }) } override val fileName = aem.obj.string { convention(task.flatMap { it.archiveFileName }) } override val vaultFilter = aem.obj.boolean { convention(task.flatMap { it.bundle.vaultFilter }) } override val vaultFilterType = aem.obj.typed<FilterType> { convention(FilterType.FILE) } override val runMode = aem.obj.string { convention(task.flatMap { it.bundle.installRunMode }) } }
apache-2.0
724e0b771608d81a0b2b5cdef056d698
41.75
107
0.764133
3.842697
false
false
false
false
NlRVANA/Unity
app/src/test/java/com/zwq65/unity/pattern/dynamic_proxy/Printer.kt
1
410
package com.zwq65.unity.pattern.dynamic_proxy /** * ================================================ * <p> * Created by NIRVANA on 2017/11/15 * Contact with <[email protected]> * ================================================ */ class Printer : IPrinter { override fun print() { println("打印文字") } override fun cancelPrint() { println("取消打印") } }
apache-2.0
1cf47a269559aa71cb5bc3b26053cf62
19.736842
51
0.449239
4.32967
false
false
false
false
trubitsyn/VisibleForTesting
src/main/kotlin/org/trubitsyn/visiblefortesting/ui/ChooseAnnotationTypeStep.kt
1
1850
/* * Copyright 2017, 2018 Nikola Trubitsyn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.trubitsyn.visiblefortesting.ui import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.psi.PsiClass class ChooseAnnotationTypeStep(psiClasses: List<PsiClass?>, private val project: Project, private val onSelected: (psiClass: PsiClass) -> Unit) : BaseListPopupStep<PsiClass>("Choose annotation type", psiClasses) { override fun isAutoSelectionEnabled() = false override fun isSpeedSearchEnabled() = true override fun onChosen(selectedValue: PsiClass?, finalChoice: Boolean): PopupStep<*>? { return when { selectedValue == null -> PopupStep.FINAL_CHOICE finalChoice -> doFinalStep { WriteCommandAction.runWriteCommandAction(project, { onSelected(selectedValue) }) } else -> super.onChosen(selectedValue, finalChoice) } } override fun hasSubstep(selectedValue: PsiClass?) = false override fun getTextFor(value: PsiClass?) = value!!.qualifiedName!! override fun getIconFor(value: PsiClass?) = value!!.getIcon(0) }
apache-2.0
b2cc00f1c1544b2411e99ee84c237a16
37.5625
213
0.717838
4.731458
false
false
false
false
rjhdby/motocitizen
Motocitizen/src/motocitizen/utils/PreferenceUtils.kt
1
875
package motocitizen.utils import android.preference.CheckBoxPreference import android.preference.Preference import android.preference.PreferenceFragment import motocitizen.datasources.preferences.Preferences fun Preference.onChangeListener(callback: (Preference, Any) -> Boolean) { onPreferenceChangeListener = Preference.OnPreferenceChangeListener(callback) } fun Preference.onClickListener(callback: (Preference) -> Boolean) { onPreferenceClickListener = Preference.OnPreferenceClickListener(callback) } private inline fun <reified T : Preference> PreferenceFragment.preferenceBinder(name: String) = lazy { findPreference(Preferences.getPreferenceName(name)) as T } fun PreferenceFragment.bindPreference(name: String) = preferenceBinder<Preference>(name) fun PreferenceFragment.bindCheckBoxPreference(name: String) = preferenceBinder<CheckBoxPreference>(name)
mit
2f179eb755949914bfee1ea62ec6a675
42.8
161
0.837714
5.208333
false
false
false
false
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/ui/dialogs/SimpleOneLinerDialog.kt
1
4406
package com.orgzly.android.ui.dialogs import android.app.Dialog import android.content.Context import android.content.DialogInterface import android.os.Bundle import android.text.TextUtils import android.view.View import android.widget.EditText import androidx.annotation.StringRes import androidx.core.os.bundleOf import androidx.fragment.app.DialogFragment import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.orgzly.R import com.orgzly.android.ui.util.KeyboardUtils class SimpleOneLinerDialog : DialogFragment() { private lateinit var requestKey: String private var title = 0 private var hint = 0 private var value: String? = null private var positiveButtonText = 0 private var negativeButtonText = 0 private var userData: Bundle? = null override fun onAttach(context: Context) { super.onAttach(context) arguments?.apply { requestKey = getString(ARG_REQUEST_ID, "") title = getInt(ARG_TITLE) hint = getInt(ARG_HINT) value = getString(ARG_VALUE) positiveButtonText = getInt(ARG_POSITIVE_BUTTON_TEXT) negativeButtonText = getInt(ARG_NEGATIVE_BUTTON_TEXT) userData = getBundle(ARG_USER_DATA) } } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val inflater = requireActivity().layoutInflater val view = inflater.inflate(R.layout.dialog_simple_one_liner, null, false) val input = view.findViewById<View>(R.id.dialog_input) as EditText if (hint != 0) { input.setHint(hint) } if (value != null) { input.setText(value) } val dialog = MaterialAlertDialogBuilder(requireContext()) .setTitle(title) .setView(view) .setPositiveButton(positiveButtonText) { _, _ -> if (!TextUtils.isEmpty(input.text)) { val result = input.text.toString().trim { it <= ' ' } parentFragmentManager.setFragmentResult( requestKey, bundleOf("value" to result, "user-data" to userData)) } // Closing due to used android:windowSoftInputMode="stateUnchanged" KeyboardUtils.closeSoftKeyboard(activity) } .setNegativeButton(negativeButtonText) { _, _ -> // Closing due to used android:windowSoftInputMode="stateUnchanged" KeyboardUtils.closeSoftKeyboard(activity) } .create() // Perform positive button click on keyboard's action press input.setOnEditorActionListener { _, _, _ -> dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick() true } dialog.setOnShowListener { KeyboardUtils.openSoftKeyboard(input) } return dialog } companion object { private const val ARG_REQUEST_ID = "id" private const val ARG_TITLE = "title" private const val ARG_HINT = "hint" private const val ARG_VALUE = "value" private const val ARG_POSITIVE_BUTTON_TEXT = "pos" private const val ARG_NEGATIVE_BUTTON_TEXT = "neg" private const val ARG_USER_DATA = "bundle" /** Name used for [android.app.FragmentManager]. */ @JvmField val FRAGMENT_TAG: String = SimpleOneLinerDialog::class.java.name @JvmStatic fun getInstance( requestKey: String, @StringRes title: Int, @StringRes positiveButtonText: Int, defaultValue: String?, userData: Bundle? = null ): SimpleOneLinerDialog { val bundle = Bundle().apply { putString(ARG_REQUEST_ID, requestKey) putInt(ARG_TITLE, title) putInt(ARG_HINT, R.string.name) if (defaultValue != null) { putString(ARG_VALUE, defaultValue) } putInt(ARG_POSITIVE_BUTTON_TEXT, positiveButtonText) putInt(ARG_NEGATIVE_BUTTON_TEXT, R.string.cancel) if (userData != null) { putBundle(ARG_USER_DATA, userData) } } return SimpleOneLinerDialog().apply { arguments = bundle } } } }
gpl-3.0
a26c8366a38e328172daa9e2038a67b3
33.162791
89
0.60236
4.945006
false
false
false
false
VoIPGRID/vialer-android
app/src/main/java/com/voipgrid/vialer/callrecord/importing/HistoricCallRecordsImporter.kt
1
5822
package com.voipgrid.vialer.callrecord.importing import android.content.Context import androidx.work.* import com.voipgrid.vialer.User import com.voipgrid.vialer.VialerApplication import com.voipgrid.vialer.api.VoipgridApi import com.voipgrid.vialer.callrecord.database.CallRecordsInserter import com.voipgrid.vialer.logging.Logger import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import org.joda.time.DateTime import java.util.concurrent.TimeUnit import javax.inject.Inject import kotlin.random.Random class HistoricCallRecordsImporter(fetcher: CallRecordsFetcher, inserter: CallRecordsInserter, api: VoipgridApi) : CallRecordsImporter(fetcher, inserter, api) { private val logger = Logger(this) /** * Import all historic call records into the database, this includes all months that we can find calls for. * */ suspend fun import() = withContext(Dispatchers.IO) { if (!User.isLoggedIn) { logger.i("Not beginning historic import as user is not yet logged in") return@withContext } relevantMonths().toList().reversed().forEach { date -> if (!User.isLoggedIn) { logger.i("User is no longer logged in, stopped importing.") return@withContext } logger.i("Importing call records for $date") try { types.forEach { type -> fetchAndInsert(type.key, type.value, date, toEndOfMonth(date)) } User.internal.callRecordMonthsImported.add(date) logger.i("Completed import for $date, starting next month in ${DELAY_BETWEEN_EACH_MONTH}ms") delay(DELAY_BETWEEN_EACH_MONTH) } catch (e: Exception) { logger.i("We have hit a rate limit, delaying for ${DELAY_IF_RATE_LIMIT_IS_HIT}ms") delay(DELAY_IF_RATE_LIMIT_IS_HIT) } } } private fun toEndOfMonth(date: DateTime) : DateTime = date.dayOfMonth().withMaximumValue().withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59) /** * We will attempt to find the months that need to be queried. * */ private fun relevantMonths() = sequence { var start = EARLIEST_DATE while (start.isBeforeNow) { if (requiresQuerying(start)) yield(start) start = start.plusMonths(1) } } /** * Check if we have already successfully imported all the records for this month, if we have * we will skip it. * * We will always check the current month, and the previous month, otherwise we only check months * that haven't yet been imported * */ private fun requiresQuerying(date: DateTime): Boolean { val current = DateTime() if (date.isAfter(current.minusMonths(RECENT_MONTHS_TO_ALWAYS_IMPORT))) return true return !User.internal.callRecordMonthsImported.contains(date) } companion object { /** * After each month we will wait a bit to prevent issues with rate limiting. */ val DELAY_BETWEEN_EACH_MONTH : Long = Random.nextInt(10 * 60, 60 * 60).toLong() * 1000 /** * If we ever hit a rate limit, we will wait this long before continuing. */ const val DELAY_IF_RATE_LIMIT_IS_HIT : Long = 15 * 60 * 1000 /** * The earliest date that will be imported, we will not try and find call records before * this date. * */ val EARLIEST_DATE: DateTime = DateTime() .minusMonths(12) .withDayOfMonth(1) .withHourOfDay(0) .withMinuteOfHour(0) .withSecondOfMinute(0) .withMillisOfSecond(0) /** * We will always query all call records from this many months ago. * */ const val RECENT_MONTHS_TO_ALWAYS_IMPORT = 3 } /** * Allows historic call records to be imported using Android's WorkManager API. * */ class Worker(appContext: Context, workerParameters: WorkerParameters) : CoroutineWorker(appContext, workerParameters) { @Inject lateinit var historicCallRecordsImporter: HistoricCallRecordsImporter override suspend fun doWork(): Result { VialerApplication.get().component().inject(this) historicCallRecordsImporter.import() return Result.success() } companion object { private val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() private val oneTime = OneTimeWorkRequestBuilder<Worker>() .setConstraints(constraints) .setBackoffCriteria(BackoffPolicy.LINEAR, OneTimeWorkRequest.MIN_BACKOFF_MILLIS, TimeUnit.MILLISECONDS) .setInitialDelay(1, TimeUnit.HOURS) .build() private val periodic = PeriodicWorkRequestBuilder<Worker>(3, TimeUnit.HOURS) .setConstraints(constraints) .build() /** * Begin working to import historic call records immediately. * */ fun start(context: Context) = WorkManager.getInstance(context).enqueueUniqueWork(Worker::class.java.name, ExistingWorkPolicy.REPLACE, oneTime) /** * Schedule the call records to be imported at regular intervals. * */ fun schedule(context: Context) = WorkManager.getInstance(context).enqueueUniquePeriodicWork(Worker::class.java.name, ExistingPeriodicWorkPolicy.KEEP, periodic) } } }
gpl-3.0
4a526eaf5d7fd10ce5476568c82b8bf0
34.938272
171
0.621951
4.823529
false
false
false
false
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/server/domain/RefreshPermissionsInteractor.kt
2
1297
package chat.rocket.android.server.domain import chat.rocket.android.server.infrastructure.RocketChatClientFactory import chat.rocket.android.util.retryIO import chat.rocket.core.internal.rest.permissions import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import timber.log.Timber import javax.inject.Inject /** * This class reloads the current logged server permission whenever its used. */ class RefreshPermissionsInteractor @Inject constructor( private val factory: RocketChatClientFactory, private val repository: PermissionsRepository ) { fun refreshAsync(server: String) { GlobalScope.launch(Dispatchers.IO) { try { factory.get(server).let { client -> val permissions = retryIO( description = "permissions", times = 5, maxDelay = 5000, initialDelay = 300 ) { client.permissions() } repository.save(server, permissions) } } catch (ex: Exception) { Timber.e(ex, "Error refreshing permissions for: $server") } } } }
mit
67bd5dd62bc2cc975db5a95bca7dc2c7
32.282051
77
0.603701
5.208835
false
false
false
false
proxer/ProxerLibAndroid
library/src/main/kotlin/me/proxer/library/enums/MessageAction.kt
2
629
package me.proxer.library.enums import com.serjltt.moshi.adapters.FallbackEnum import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import me.proxer.library.entity.messenger.Message /** * Enum holding the possible actions of a [Message]. * * @author Ruben Gees */ @JsonClass(generateAdapter = false) @FallbackEnum(name = "NONE") enum class MessageAction { @Json(name = "") NONE, @Json(name = "addUser") ADD_USER, @Json(name = "removeUser") REMOVE_USER, @Json(name = "setLeader") SET_LEADER, @Json(name = "setTopic") SET_TOPIC, @Json(name = "exit") EXIT }
gpl-3.0
b319a5747628999a8a8062ec0c67c959
17.5
52
0.669316
3.475138
false
false
false
false
sunghwanJo/workshop-jb
src/i_introduction/_3_Default_Arguments/DefaultAndNamedParams.kt
1
952
package i_introduction._3_Default_Arguments import util.* fun todoTask3(): Nothing = TODO( """ Task 3. Several overloads of 'JavaCode3.foo()' can be replaced with one function in Kotlin. Change the declaration of the function 'foo' in a way that makes the code using 'foo' compile. You have to add parameters and replace 'todoTask3()' with a real body. Uncomment the commented code and make it compile. """, documentation = doc2(), references = { name: String -> JavaCode3().foo(name); foo(name) }) fun foo(name: String, number: Int=42, toUpperCase: Boolean=false): String { // (toUpperCase ? name.toUpperCase() : name) + number return if(toUpperCase) name.toUpperCase()+number else name + number } fun task3(): String { return (foo("a") + foo("b", number = 1) + foo("c", toUpperCase = true) + foo(name = "d", number = 2, toUpperCase = true)) }
mit
516b93dfc9d301edccab99d6debfe092
35.615385
102
0.629202
4
false
false
false
false
myunusov/sofarc
sofarc-core/src/main/kotlin/org/maxur/sofarc/core/service/hk2/MicroServiceBuilder.kt
1
2556
@file:Suppress("unused") package org.maxur.sofarc.core.service.hk2 import org.glassfish.hk2.utilities.Binder import org.maxur.sofarc.core.domain.Factory import org.maxur.sofarc.core.service.ConfigSource import org.maxur.sofarc.core.service.EmbeddedService import org.maxur.sofarc.core.service.MicroService class MicroServiceBuilder(vararg binders: Binder) { @Suppress("CanBePrimaryConstructorProperty") private val binders: Array<out Binder> = binders lateinit private var configSource: ConfigSource lateinit private var nameCreator: Factory<String> private var serviceCreators: MutableList<Factory<EmbeddedService>> = mutableListOf() private var beforeStart: (MicroService) -> Unit = {} private var afterStop: (MicroService) -> Unit = {} private var onError: (MicroService, Exception) -> Unit = { microService: MicroService, exception: Exception -> } fun beforeStart(func: (MicroService) -> Unit): MicroServiceBuilder { beforeStart = func return this } fun afterStop(func: (MicroService) -> Unit): MicroServiceBuilder { afterStop = func return this } fun onError(func: (MicroService, Exception) -> Unit): MicroServiceBuilder { onError = func return this } fun name(value: String): MicroServiceBuilder { nameCreator = object: Factory<String> { override fun get() = value } return this } fun name(creator: Factory<String>): MicroServiceBuilder { nameCreator = creator return this } fun embedded(vararg value: EmbeddedService): MicroServiceBuilder { value.forEach { serviceCreators.add(object: Factory<EmbeddedService> { override fun get() = it}) } return this } fun embed(serviceCreator: Factory<EmbeddedService>): MicroServiceBuilder { serviceCreators.add(serviceCreator) return this } fun config(value: ConfigSource): MicroServiceBuilder { configSource = value return this } /** * Start Service */ fun start() { val locator = DSL.newLocator(configSource, *binders) val service = locator.getService<MicroService>(MicroService::class.java) service.name = nameCreator.get() service.config = locator.getService<Any>(configSource.structure) service.services = serviceCreators.map { it.get() } service.beforeStart = beforeStart service.afterStop = afterStop service.onError = onError service.start() } }
apache-2.0
63753647f125e0ef98acbc6fca097dbd
29.082353
116
0.678013
4.391753
false
true
false
false
gradle/gradle
subprojects/kotlin-dsl-plugins/src/integTest/kotlin/org/gradle/kotlin/dsl/plugins/precompiled/PrecompiledScriptPluginAccessorSettingEvaluationTest.kt
3
3999
/* * Copyright 2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.plugins.precompiled import org.gradle.kotlin.dsl.fixtures.normalisedPath import org.gradle.test.fixtures.file.LeaksFileHandles import org.hamcrest.CoreMatchers import org.hamcrest.MatcherAssert import org.junit.Test import java.io.File @LeaksFileHandles("Kotlin Compiler Daemon working directory") class PrecompiledScriptPluginAccessorSettingEvaluationTest : AbstractPrecompiledScriptPluginTest() { @Test fun `settings and init scripts are not evaluated when generating accessors`() { // given: val evaluationLog = file("evaluation.log") withFolders { // a precompiled script plugin contributing an extension "producer/src/main/kotlin" { withFile( "producer.plugin.gradle.kts", """extensions.add("answer", 42)""" ) } // a consumer of the precompiled script plugin extension "consumer/src/main/kotlin" { withFile( "consumer.plugin.gradle.kts", """ plugins { id("producer.plugin") } println(answer) """ ) } } withDefaultSettings().appendText( """ include("producer", "consumer") file("${evaluationLog.normalisedPath}").appendText("<settings>") """ ) withKotlinDslPlugin().appendText( """ subprojects { apply(plugin = "org.gradle.kotlin.kotlin-dsl") $repositoriesBlock } project(":consumer") { dependencies { implementation(project(":producer")) } } """ ) // and: a bunch of init scripts fun initScript(file: File, label: String) = file.apply { parentFile.mkdirs() writeText("file('${evaluationLog.normalisedPath}') << '$label'") } val gradleUserHome = newDir("gradle-user-home") // <user-home>/init.gradle initScript( gradleUserHome.resolve("init.gradle"), "<init>" ) // <user-home>/init.d/init.gradle initScript( gradleUserHome.resolve("init.d/init.gradle"), "<init.d>" ) // -I init.gradle val initScript = initScript( file("init.gradle"), "<command-line>" ) // when: precompiled script plugin accessors are generated buildWithGradleUserHome( gradleUserHome, "generatePrecompiledScriptPluginAccessors", "-I", initScript.absolutePath ).apply { // then: the settings and init scripts are only evaluated once by the outer build MatcherAssert.assertThat( evaluationLog.text, CoreMatchers.equalTo("<command-line><init><init.d><settings>") ) } } private fun buildWithGradleUserHome(gradleUserHomeDir: File, vararg arguments: String) = gradleExecuterFor(arguments) .withGradleUserHomeDir(gradleUserHomeDir) .withOwnUserHomeServices() .run() }
apache-2.0
81c5338fae501c55d9e9547ad6055a60
32.889831
100
0.568392
5.268775
false
false
false
false
Fondesa/RecyclerViewDivider
recycler-view-divider/src/main/kotlin/com/fondesa/recyclerviewdivider/StaggeredDividerBuilder.kt
1
8209
/* * Copyright (c) 2020 Giorgio Antonioli * * 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.fondesa.recyclerviewdivider import android.content.Context import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.util.TypedValue import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.annotation.Px import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.fondesa.recyclerviewdivider.drawable.getThemeDrawable import com.fondesa.recyclerviewdivider.drawable.isOpaque import com.fondesa.recyclerviewdivider.drawable.transparentDrawable import com.fondesa.recyclerviewdivider.log.logWarning import com.fondesa.recyclerviewdivider.offset.StaggeredDividerOffsetProvider import com.fondesa.recyclerviewdivider.size.getDefaultSize import com.fondesa.recyclerviewdivider.size.getThemeSize import com.fondesa.recyclerviewdivider.space.getThemeAsSpaceOrDefault /** * Builds a divider for a [StaggeredGridLayoutManager] or its subclasses. * The following properties of a divider can be configured: * * - asSpace * Makes the divider as a simple space, so the divider leaves the space between two cells but it is not rendered. * Since the rendering is totally skipped in this case, it's better than using a transparent color. * The asSpace property can be defined in the theme with the attribute "recyclerViewDividerAsSpace". * By default it's false. * * - color * Specifies the color of the divider used when it will be rendered. * The color of the divider can be defined in the theme with the attribute "recyclerViewDividerDrawable". * If it's not defined, it will be picked by the attribute "android:listDivider". * If the Android attribute's value is null, the divider won't be rendered and it will behave as a space. * There are two cases in which this builder can't ensure a correct rendering of a divider: * - If the value of "recyclerViewDividerDrawable" or "android:listDivider" is not a solid color. * - If the color of this divider is not completely opaque (contains some transparency). * * - size * Specifies the divider's size. * The size of the divider can be defined in the theme with the attribute "recyclerViewDividerSize". * If it's not defined, the divider size will be inherited from the divider's drawable. * If it can't be inherited from the divider's drawable (e.g. the drawable is a solid color), the default size of 1dp will be used. * The size of an horizontal divider is its height. * The size of a vertical divider is its width. * * - visibility * Specifies if a divider is visible or not. * When the divider isn't visible, it means the divider won't exist on the layout so its space between the two adjacent cells won't appear. * By default all the dividers are visible except the divider before the first items. * This happens because, apparently, it's not possible to understand which items will appear first in a [StaggeredGridLayoutManager] since * their positions can change. * * @param context the [Context] used to build the divider. */ public class StaggeredDividerBuilder(private val context: Context) { private var asSpace = false @ColorInt private var color: Int? = null @Px private var size: Int? = null private var areSideDividersVisible = true /** * Sets the divider as a simple space, so the divider leaves the space between two cells but it is not rendered. * Since the rendering is totally skipped in this case, it's better than using a transparent color. * * @return this [StaggeredDividerBuilder] instance. */ public fun asSpace(): StaggeredDividerBuilder = apply { asSpace = true } /** * Sets the divider's color. * If the color of this divider is not completely opaque (contains some transparency), this builder can't ensure a correct rendering. * * @param colorRes the resource of the color used for each divider. * @return this [StaggeredDividerBuilder] instance. */ public fun colorRes(@ColorRes colorRes: Int): StaggeredDividerBuilder = color(ContextCompat.getColor(context, colorRes)) /** * Sets the divider's color. * If the color of this divider is not completely opaque (contains some transparency), this builder can't ensure a correct rendering. * * @param color the color used for each divider. * @return this [StaggeredDividerBuilder] instance. */ public fun color(@ColorInt color: Int): StaggeredDividerBuilder = apply { this.color = color } /** * Sets the divider's size. * The size of an horizontal divider is its height. * The size of a vertical divider is its width. * * @param size the divider's size. * @param sizeUnit the divider's size measurement unit (e.g. [TypedValue.COMPLEX_UNIT_DIP]). By default pixels. * @return this [StaggeredDividerBuilder] instance. */ @JvmOverloads public fun size(size: Int, sizeUnit: Int = TypedValue.COMPLEX_UNIT_PX): StaggeredDividerBuilder = apply { this.size = context.resources.pxFromSize(size = size, sizeUnit = sizeUnit) } /** * Hides the side dividers of the grid. * The side dividers are the ones before the first column and after the last column. * * @return this [StaggeredDividerBuilder] instance. */ public fun hideSideDividers(): StaggeredDividerBuilder = apply { areSideDividersVisible = false } /** * Creates the [RecyclerView.ItemDecoration] using the configuration specified in this builder. * If this builder doesn't specify the configuration of some divider's properties, those properties will be picked from the theme * or their default will be used. * * @return a new [RecyclerView.ItemDecoration] which can be attached to the [RecyclerView]. */ public fun build(): BaseDividerItemDecoration { val asSpace = asSpace || context.getThemeAsSpaceOrDefault() return StaggeredDividerItemDecoration( asSpace = asSpace, drawable = color?.let { ColorDrawable(it) } ?: context.getThemeDrawableOrDefault(asSpace), size = size ?: context.getThemeSize() ?: context.getDefaultSize(), areSideDividersVisible = areSideDividersVisible, offsetProvider = StaggeredDividerOffsetProvider(areSideDividersVisible) ) } private fun Context.getThemeDrawableOrDefault(asSpace: Boolean): Drawable { val drawable = getThemeDrawable() // If the divider should be treated as a space, its drawable isn't necessary so the logs can be skipped. if (asSpace) return drawable ?: transparentDrawable() when { drawable == null -> { "Can't render the divider without a color. Specify \"recyclerViewDividerDrawable\" or \"android:listDivider\" " + "in the theme or set a color in this ${StaggeredDividerBuilder::class.java.simpleName}." } drawable !is ColorDrawable -> { "Can't ensure the correct rendering of a divider drawable which isn't a solid color in a " + "${StaggeredGridLayoutManager::class.java.simpleName}." } !drawable.isOpaque -> { "Can't ensure the correct rendering of a divider color which has alpha in a " + "${StaggeredGridLayoutManager::class.java.simpleName}." } else -> null }?.let { warningMsg -> logWarning(warningMsg) } return drawable ?: transparentDrawable() } }
apache-2.0
1caf93f1dc11945c250b3d049797bb3d
48.155689
139
0.72116
4.734141
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-classes-bukkit/src/main/kotlin/com/rpkit/classes/bukkit/command/class/ClassCommand.kt
1
1695
/* * Copyright 2020 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.classes.bukkit.command.`class` import com.rpkit.classes.bukkit.RPKClassesBukkit import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender class ClassCommand(private val plugin: RPKClassesBukkit) : CommandExecutor { private val classSetCommand = ClassSetCommand(plugin) private val classListCommand = ClassListCommand(plugin) override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (args.isNotEmpty()) { val newArgs = args.drop(1).toTypedArray() when { args[0].equals("set", ignoreCase = true) -> return classSetCommand.onCommand(sender, command, label, newArgs) args[0].equals("list", ignoreCase = true) -> return classListCommand.onCommand(sender, command, label, newArgs) else -> sender.sendMessage(plugin.messages["class-usage"]) } } else { sender.sendMessage(plugin.messages["class-usage"]) } return true } }
apache-2.0
9afb3d0e00208d4aa449ad36cf5395d2
37.545455
127
0.700885
4.414063
false
false
false
false
shchurov/gitter-kotlin-client
app/src/main/kotlin/com/github/shchurov/gitterclient/presentation/ui/activities/RoomActivity.kt
1
9568
package com.github.shchurov.gitterclient.presentation.ui.activities import android.animation.ObjectAnimator import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.SimpleItemAnimator import android.support.v7.widget.Toolbar import android.view.MenuItem import android.view.View import android.widget.* import com.github.shchurov.gitterclient.App import com.github.shchurov.gitterclient.R import com.github.shchurov.gitterclient.dagger.modules.RoomModule import com.github.shchurov.gitterclient.domain.models.Message import com.github.shchurov.gitterclient.presentation.presenters.RoomPresenter import com.github.shchurov.gitterclient.presentation.ui.RoomView import com.github.shchurov.gitterclient.presentation.ui.adapters.MessagesAdapter import com.github.shchurov.gitterclient.utils.* import com.github.shchurov.gitterclient.utils.animation_flow.AnimationFlow import javax.inject.Inject class RoomActivity : AppCompatActivity(), RoomView, MessagesAdapter.ActionListener { companion object { private const val EXTRA_ROOM_ID = "room_id" private const val EXTRA_ROOM_NAME = "room_name" private const val PAGING_THRESHOLD = 10 fun start(context: Context, roomId: String, roomName: String) { val intent = Intent(context, RoomActivity::class.java) intent.putExtra(EXTRA_ROOM_ID, roomId) intent.putExtra(EXTRA_ROOM_NAME, roomName) context.startActivity(intent) } } @Inject lateinit var presenter: RoomPresenter private lateinit var toolbar: Toolbar private lateinit var rvMessages: RecyclerView private lateinit var progressBarLoading: ProgressBar private lateinit var etNewMessage: EditText private lateinit var flSend: FrameLayout private lateinit var tvSend: TextView private lateinit var progressBarSending: ProgressBar private lateinit var ivError: ImageView private var adapter = MessagesAdapter(this) private var animation: AnimationFlow? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initDependencies() setupUi() presenter.attach(this) } private fun initDependencies() { App.component.createRoomComponent(RoomModule(getRoomId())) .inject(this) } private fun setupUi() { setContentView(R.layout.room_activity) initViews() setupToolbar() setupRecyclerView() tvSend.setOnClickListener { presenter.onSendClick(etNewMessage.text.toString()) } initSendTranslation() setupMessageTextChangedListener() } private fun initViews() { toolbar = findViewById(R.id.toolbar) as Toolbar rvMessages = findViewById(R.id.rvMessages) as RecyclerView progressBarLoading = findViewById(R.id.progressBarLoading) as ProgressBar etNewMessage = findViewById(R.id.etNewMessage) as EditText tvSend = findViewById(R.id.tvSend) as TextView flSend = findViewById(R.id.flSend) as FrameLayout progressBarSending = findViewById(R.id.progressBarSending) as ProgressBar ivError = findViewById(R.id.ivError) as ImageView } private fun setupToolbar() { setSupportActionBar(toolbar) supportActionBar!!.setDisplayHomeAsUpEnabled(true) } private fun setupRecyclerView() { with (rvMessages) { layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, true) setHasFixedSize(true) addItemDecoration(MessagesItemDecoration()) addOnScrollListener(pagingScrollListener) addOnScrollListener(readScrollListener) (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false } rvMessages.adapter = adapter } private val pagingScrollListener = object : PagingScrollListener(PAGING_THRESHOLD) { override fun onLoadMoreItems() { presenter.onLoadMoreItems() } } private val readScrollListener = object : VisiblePositionsScrollListener() { override fun onVisiblePositionsChanged(firstPosition: Int, lastPosition: Int) { val visibleMessages = adapter.getMessagesInRange(firstPosition, lastPosition) presenter.onVisibleMessagesChanged(visibleMessages) } } private fun initSendTranslation() { flSend.post { flSend.translationY = flSend.height.toFloat() } } private fun setupMessageTextChangedListener() { etNewMessage.addTextChangedListener(object : SimpleTextWatcher() { override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { if (before == 0 && s.length > 0) { showSendButton(); } else if (before > 0 && s.length == 0) { hideSendButton(); } } }) } private fun showSendButton() { animation?.cancel() animation = AnimationFlow.create() .play(sendContainerShowAnimation) .start() } private val sendContainerShowAnimation = SendContainerAnimation(0f) private fun hideSendButton() { animation?.cancel() animation = AnimationFlow.create() .play(sendContainerHideAnimation) .start() } private val sendContainerHideAnimation by lazy { SendContainerAnimation(flSend.height.toFloat()) } override fun onDestroy() { presenter.detach() super.onDestroy() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> finish() } return true } override fun getRoomId() = intent.getStringExtra(EXTRA_ROOM_ID) override fun getRoomName() = intent.getStringExtra(EXTRA_ROOM_NAME) override fun setToolbarTitle(title: String) { toolbar.title = title } override fun showInitLoading() { progressBarLoading.visibility = View.VISIBLE } override fun hideInitLoading() { progressBarLoading.visibility = View.GONE } override fun showLoadingMore() { adapter.loading = true } override fun hideLoadingMore() { adapter.loading = false } override fun addMessages(messages: List<Message>) { adapter.addMessages(messages.asReversed()) forceOnReadPositionsChangedCallback() } private fun forceOnReadPositionsChangedCallback() { rvMessages.postDelayed({ readScrollListener.forceCallback(rvMessages) }, 100) } override fun enablePagingListener() { pagingScrollListener.enabled = true } override fun disablePagingListener() { pagingScrollListener.enabled = false } override fun invalidateMessage(message: Message) { adapter.invalidateMessage(message) } override fun hideKeyboard() { hideSoftInputKeyboard() } override fun showSendingInProgress() { animation?.cancel() disableMessageEditText() animation = AnimationFlow.create() .play(sendContainerHideAnimation) .setup { tvSend.visibility = View.INVISIBLE progressBarSending.visibility = View.VISIBLE } .play(sendContainerShowAnimation) .start() } fun disableMessageEditText() { etNewMessage.isEnabled = false etNewMessage.isClickable = false } override fun showSendingError() { animation?.cancel() animation = AnimationFlow.create() .play(sendContainerHideAnimation) .setup { tvSend.visibility = View.INVISIBLE progressBarSending.visibility = View.GONE ivError.visibility = View.VISIBLE } .play(sendContainerShowAnimation) .wait(600) .play(sendContainerHideAnimation) .setup { ivError.visibility = View.GONE tvSend.visibility = View.VISIBLE enableMessageEditText() } .play(sendContainerShowAnimation) .start() } fun enableMessageEditText() { etNewMessage.isEnabled = true etNewMessage.isClickable = true } override fun hideSendingInProgress() { animation?.cancel() animation = AnimationFlow.create() .play(sendContainerHideAnimation) .setup { progressBarSending.visibility = View.GONE tvSend.visibility = View.VISIBLE enableMessageEditText() } .start() } override fun clearMessageEditText() { etNewMessage.setText("") } override fun addMessage(message: Message) { adapter.insertMessage(message) rvMessages.post { rvMessages.smoothScrollToPosition(0) } } private inner class SendContainerAnimation(private val endValue: Float) : AnimationFlow.Animation { override fun createAnimator() = ObjectAnimator.ofFloat(flSend, "translationY", flSend.translationY, endValue) override fun onCancel() { } } }
apache-2.0
a8a060e4776ab78a4bce7987eed448f3
32.812721
117
0.658027
5.124799
false
false
false
false
mos8502/karl
plugin/src/main/java/hu/nemi/karl/Resources.kt
1
4988
package hu.nemi.karl import com.squareup.kotlinpoet.* import java.util.* private val ANDROID_CONTEXT = ClassName.bestGuess("android.content.Context") private val RESOURCES = ClassName.bestGuess("Resources") private val CACHE = ParameterizedTypeName.get(WeakHashMap::class.asClassName(), ANDROID_CONTEXT, RESOURCES) private class Symbol(str: String) { private val parts = str.split(' ') val type by lazy { parts[1] } val name by lazy { parts[2] } val id by lazy { Integer.decode(parts[3]) } } private data class Receiver(val receiverClass: String, val contextAccessor: String) private data class ResourceType(val type: String, val resourceType: TypeName, val name: String, val initializer: String, val initializerArgs : Array<out Any> = emptyArray<Any>()) { val className = ClassName.bestGuess(name) private val typeSpecBuilder = TypeSpec.classBuilder(name) .addProperty(PropertySpec.builder("context", ANDROID_CONTEXT) .initializer("context") .build()) .primaryConstructor(FunSpec.constructorBuilder() .addParameter("context", ANDROID_CONTEXT) .build()) fun toTypeSpec(propertyNames: Iterable<String>) = with(typeSpecBuilder) { val properties = propertyNames.map { propertyName -> PropertySpec.builder(propertyName, resourceType) .delegate(CodeBlock.builder() .add("lazy { $initializer }", *initializerArgs, "R.$type.$propertyName") .build()) .build() } typeSpecBuilder.addProperties(properties).build() } } class Resources { private val symbols = mutableSetOf<Symbol>() private val receivers = mutableSetOf<Receiver>() private val resourceTypes = mutableSetOf<ResourceType>() fun resource(name: String, resourceType: ClassName, initializer: String, vararg args : Any) = apply { resourceTypes.add(ResourceType(name, resourceType, "${name.capitalize()}s", initializer, args)) } fun receiver(type: String, context: String) = apply { receivers.add(Receiver(type, context)) } fun symbol(symbol: String) = apply { symbols.add(Symbol(symbol)) } fun toKotlinFile(packageName: String, fileName: String): KotlinFile { val kotlinFile = KotlinFile.builder(packageName, fileName) with(TypeSpec.classBuilder("Resources")) { resourceTypes.forEach { resourceType -> val property = "${resourceType.type}s" addProperty(PropertySpec.builder(property, resourceType.className) .initializer("%T(context)", resourceType.className) .build()) kotlinFile.addType(resourceType.toTypeSpec(symbols.filter { it.type == resourceType.type }.map(Symbol::name))) receivers.forEach { (receiverClass, contextAccessor) -> kotlinFile.addProperty(PropertySpec.builder("$receiverClass.$property", resourceType.className) .getter(FunSpec.getterBuilder() .addCode(CodeBlock.builder() .add("%[return resourcesTls.getResources($contextAccessor).$property\n") .add("%]") .build()) .build()) .build()) } } primaryConstructor(FunSpec.constructorBuilder() .addParameter("context", ANDROID_CONTEXT) .build()) }.build().run { kotlinFile.addType(this) } TypeSpec.objectBuilder("resourcesTls") .addModifiers(KModifier.PRIVATE) .superclass(ParameterizedTypeName.get(ThreadLocal::class.asClassName(), CACHE)) .addFun(FunSpec.builder("initialValue") .addModifiers(KModifier.OVERRIDE) .returns(CACHE) .addCode("%[return %T()\n", CACHE) .addCode("%]") .build()) .addFun(FunSpec.builder("getResources") .addParameter("context", ANDROID_CONTEXT) .returns(RESOURCES) .addCode(CodeBlock.builder() .add("%[return with(get()) {\n") .add("%>get(context) ?: %T(context).also {\n", RESOURCES) .add("%>put(context, it)\n") .add("%<}\n") .add("%<}\n") .add("%]") .build()) .build()) .build().run { kotlinFile.addType(this) } return kotlinFile.build() } }
apache-2.0
ed8ceb8fb5a9d5d2d6d84ac295a2c65f
42.373913
180
0.545108
5.346195
false
false
false
false
Nagarajj/orca
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/StageDefinitionBuilders.kt
1
8069
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q import com.netflix.spinnaker.orca.pipeline.BranchingStageDefinitionBuilder import com.netflix.spinnaker.orca.pipeline.RestrictExecutionDuringTimeWindow import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilder import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilder.StageDefinitionBuilderSupport.newStage import com.netflix.spinnaker.orca.pipeline.TaskNode import com.netflix.spinnaker.orca.pipeline.TaskNode.TaskDefinition import com.netflix.spinnaker.orca.pipeline.TaskNode.TaskGraph import com.netflix.spinnaker.orca.pipeline.model.* import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_AFTER import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_BEFORE /** * Build and append the tasks for [stage]. */ fun StageDefinitionBuilder.buildTasks(stage: Stage<*>) { val taskGraph = if (this is BranchingStageDefinitionBuilder && (stage.getParentStageId() == null || stage.parent().getType() != stage.getType())) { buildPostGraph(stage) } else { buildTaskGraph(stage) } taskGraph .listIterator() .forEachWithMetadata { processTaskNode(stage, it) } } private fun processTaskNode( stage: Stage<*>, element: IteratorElement<TaskNode>, isSubGraph: Boolean = false ) { element.apply { when (value) { is TaskDefinition -> { val task = Task() task.id = (stage.getTasks().size + 1).toString() task.name = value.name task.implementingClass = value.implementingClass.name if (isSubGraph) { task.isLoopStart = isFirst task.isLoopEnd = isLast } else { task.isStageStart = isFirst task.isStageEnd = isLast } stage.getTasks().add(task) } is TaskGraph -> { value .listIterator() .forEachWithMetadata { processTaskNode(stage, it, isSubGraph = true) } } } } } /** * Build the synthetic stages for [stage] and inject them into the execution. */ fun StageDefinitionBuilder.buildSyntheticStages( stage: Stage<out Execution<*>>, callback: (Stage<*>) -> Unit = {} ): Unit { syntheticStages(stage).apply { buildBeforeStages(stage, callback) buildAfterStages(stage, callback) } buildParallelStages(stage, callback) } @Suppress("UNCHECKED_CAST") private fun BranchingStageDefinitionBuilder.parallelContexts(stage: Stage<*>) = when (stage.getExecution()) { is Pipeline -> parallelContexts(stage as Stage<Pipeline>) is Orchestration -> parallelContexts(stage as Stage<Orchestration>) else -> throw IllegalStateException() } @Suppress("UNCHECKED_CAST") private fun BranchingStageDefinitionBuilder.parallelStageName(stage: Stage<*>, hasParallelStages: Boolean) = when (stage.getExecution()) { is Pipeline -> parallelStageName(stage as Stage<Pipeline>, hasParallelStages) is Orchestration -> parallelStageName(stage as Stage<Orchestration>, hasParallelStages) else -> throw IllegalStateException() } private typealias SyntheticStages = Map<SyntheticStageOwner, List<Stage<*>>> @Suppress("UNCHECKED_CAST") private fun StageDefinitionBuilder.syntheticStages(stage: Stage<out Execution<*>>) = when (stage.getExecution()) { is Pipeline -> aroundStages(stage as Stage<Pipeline>) is Orchestration -> aroundStages(stage as Stage<Orchestration>) else -> throw IllegalStateException() } .groupBy { it.getSyntheticStageOwner() } private fun SyntheticStages.buildBeforeStages(stage: Stage<out Execution<*>>, callback: (Stage<*>) -> Unit) { val executionWindow = stage.buildExecutionWindow() val beforeStages = if (executionWindow == null) { this[STAGE_BEFORE].orEmpty() } else { listOf(executionWindow) + this[STAGE_BEFORE].orEmpty() } beforeStages.forEachIndexed { i, it -> it.setRefId("${stage.getRefId()}<${i + 1}") if (i > 0) { it.setRequisiteStageRefIds(setOf("${stage.getRefId()}<$i")) } else { it.setRequisiteStageRefIds(emptySet()) } stage.getExecution().apply { injectStage(getStages().indexOf(stage), it) callback.invoke(it) } } } private fun SyntheticStages.buildAfterStages(stage: Stage<out Execution<*>>, callback: (Stage<*>) -> Unit) { val afterStages = this[STAGE_AFTER].orEmpty() afterStages.forEachIndexed { i, it -> it.setRefId("${stage.getRefId()}>${i + 1}") if (i > 0) { it.setRequisiteStageRefIds(setOf("${stage.getRefId()}>$i")) } else { it.setRequisiteStageRefIds(emptySet()) } } stage.getExecution().apply { val index = getStages().indexOf(stage) + 1 afterStages.reversed().forEach { injectStage(index, it) callback.invoke(it) } } } private fun StageDefinitionBuilder.buildParallelStages(stage: Stage<out Execution<*>>, callback: (Stage<*>) -> Unit) { if (this is BranchingStageDefinitionBuilder && (stage.getParentStageId() == null || stage.parent().getType() != stage.getType())) { val parallelContexts = parallelContexts(stage) parallelContexts .map { context -> val execution = stage.getExecution() val stageType = context.getOrDefault("type", stage.getType()).toString() val stageName = context.getOrDefault("name", stage.getName()).toString() @Suppress("UNCHECKED_CAST") when (execution) { is Pipeline -> newStage(execution, stageType, stageName, context.filterKeys { it != "restrictExecutionDuringTimeWindow" }, stage as Stage<Pipeline>, STAGE_BEFORE) is Orchestration -> newStage(execution, stageType, stageName, context.filterKeys { it != "restrictExecutionDuringTimeWindow" }, stage as Stage<Orchestration>, STAGE_BEFORE) else -> throw IllegalStateException() } } .forEachIndexed { i, it -> it.setRefId("${stage.getRefId()}=${i + 1}") it.setRequisiteStageRefIds(emptySet()) stage.getExecution().apply { injectStage(getStages().indexOf(stage), it) callback.invoke(it) } } stage.setName(parallelStageName(stage, parallelContexts.size > 1)) stage.setInitializationStage(true) } } private fun Stage<out Execution<*>>.buildExecutionWindow(): Stage<*>? { if (getContext().getOrDefault("restrictExecutionDuringTimeWindow", false) as Boolean) { val execution = getExecution() val executionWindow = when (execution) { is Pipeline -> newStage( execution, RestrictExecutionDuringTimeWindow.TYPE, RestrictExecutionDuringTimeWindow.TYPE, // TODO: base on stage.name? getContext().filterKeys { it != "restrictExecutionDuringTimeWindow" }, this as Stage<Pipeline>, STAGE_BEFORE ) is Orchestration -> newStage( execution, RestrictExecutionDuringTimeWindow.TYPE, RestrictExecutionDuringTimeWindow.TYPE, // TODO: base on stage.name? getContext().filterKeys { it != "restrictExecutionDuringTimeWindow" }, this as Stage<Orchestration>, STAGE_BEFORE ) else -> throw IllegalStateException() } executionWindow.setRefId("${getRefId()}<0") return executionWindow } else { return null } } @Suppress("UNCHECKED_CAST") private fun Execution<*>.injectStage(index: Int, it: Stage<*>) { when (this) { is Pipeline -> stages.add(index, it as Stage<Pipeline>) is Orchestration -> stages.add(index, it as Stage<Orchestration>) } }
apache-2.0
41cd360f8720e8d9356e49469f121016
35.511312
182
0.691288
4.34518
false
false
false
false
jiangkang/KTools
tools/src/main/java/com/jiangkang/tools/utils/DeviceUtils.kt
1
2339
package com.jiangkang.tools.utils import android.content.Context import android.net.ConnectivityManager import android.net.wifi.WifiManager import java.net.Inet4Address import java.net.NetworkInterface import java.net.SocketException /** * Created by jiangkang on 2017/9/8. */ object DeviceUtils { fun getIPAddress(context: Context): String? { val info = (context .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo if (info != null && info.isConnected) { if (info.type == ConnectivityManager.TYPE_MOBILE) { //当前使用2G/3G/4G网络 try { //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces(); val en = NetworkInterface.getNetworkInterfaces() while (en.hasMoreElements()) { val intf = en.nextElement() val enumIpAddr = intf.inetAddresses while (enumIpAddr.hasMoreElements()) { val inetAddress = enumIpAddr.nextElement() if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) { return inetAddress.getHostAddress() } } } } catch (e: SocketException) { e.printStackTrace() } } else if (info.type == ConnectivityManager.TYPE_WIFI) { //当前使用无线网络 val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager val wifiInfo = wifiManager.connectionInfo return intIP2StringIP(wifiInfo.ipAddress) } } else { //当前无网络连接,请在设置中打开网络 } return null } /** * 将得到的int类型的IP转换为String类型 * * @param ip * @return */ private fun intIP2StringIP(ip: Int): String { return (ip and 0xFF).toString() + "." + (ip shr 8 and 0xFF) + "." + (ip shr 16 and 0xFF) + "." + (ip shr 24 and 0xFF) } /** * 虚拟机版本 */ val vmVersion = System.getProperty("java.vm.version") }
mit
8f8ebd315ce202e8b259959dd4e7e610
34.09375
105
0.544766
4.838362
false
false
false
false
vmmaldonadoz/android-reddit-example
Reddit/app/src/main/java/com/thirdmono/reddit/domain/utils/Constants.kt
1
549
package com.thirdmono.reddit.domain.utils object Constants { const val API_URL = "https://www.reddit.com/" const val NEXT_PAGE_KEY = "NEXT_PAGE_KEY" const val REDDIT_SELECTED_KEY = "REDDIT_SELECTED_KEY" const val DEFAULT_LIMIT = 50 const val QUERY_REDDITS = "reddits.json" const val QUERY_PAGINATE_AFTER = "after" const val QUERY_LIMIT = "limit" const val REDDIT_LIST_KEY = "REDDIT_LIST_KEY" // public final static String QUERY_REDDITS = "reddits.json?after={" + NEXT_PAGE_KEY + "}&limit=" + QUERY_LIMIT; }
apache-2.0
2469468fff77e2d361c5c34e35031df8
35.6
119
0.677596
3.248521
false
false
false
false
ze-pequeno/okhttp
okhttp/src/jvmMain/kotlin/okhttp3/HttpUrl.kt
3
70743
/* * Copyright (C) 2015 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3 import java.net.InetAddress import java.net.MalformedURLException import java.net.URI import java.net.URISyntaxException import java.net.URL import java.nio.charset.Charset import java.util.Collections import kotlin.text.Charsets.UTF_8 import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.internal.canParseAsIpAddress import okhttp3.internal.delimiterOffset import okhttp3.internal.indexOfFirstNonAsciiWhitespace import okhttp3.internal.indexOfLastNonAsciiWhitespace import okhttp3.internal.parseHexDigit import okhttp3.internal.publicsuffix.PublicSuffixDatabase import okhttp3.internal.toCanonicalHost import okio.Buffer /** * A uniform resource locator (URL) with a scheme of either `http` or `https`. Use this class to * compose and decompose Internet addresses. For example, this code will compose and print a URL for * Google search: * * ```java * HttpUrl url = new HttpUrl.Builder() * .scheme("https") * .host("www.google.com") * .addPathSegment("search") * .addQueryParameter("q", "polar bears") * .build(); * System.out.println(url); * ``` * * which prints: * * ``` * https://www.google.com/search?q=polar%20bears * ``` * * As another example, this code prints the human-readable query parameters of a Twitter search: * * ```java * HttpUrl url = HttpUrl.parse("https://twitter.com/search?q=cute%20%23puppies&f=images"); * for (int i = 0, size = url.querySize(); i < size; i++) { * System.out.println(url.queryParameterName(i) + ": " + url.queryParameterValue(i)); * } * ``` * * which prints: * * ``` * q: cute #puppies * f: images * ``` * * In addition to composing URLs from their component parts and decomposing URLs into their * component parts, this class implements relative URL resolution: what address you'd reach by * clicking a relative link on a specified page. For example: * * ```java * HttpUrl base = HttpUrl.parse("https://www.youtube.com/user/WatchTheDaily/videos"); * HttpUrl link = base.resolve("../../watch?v=cbP2N1BQdYc"); * System.out.println(link); * ``` * * which prints: * * ``` * https://www.youtube.com/watch?v=cbP2N1BQdYc * ``` * * ## What's in a URL? * * A URL has several components. * * ### Scheme * * Sometimes referred to as *protocol*, A URL's scheme describes what mechanism should be used to * retrieve the resource. Although URLs have many schemes (`mailto`, `file`, `ftp`), this class only * supports `http` and `https`. Use [java.net.URI][URI] for URLs with arbitrary schemes. * * ### Username and Password * * Username and password are either present, or the empty string `""` if absent. This class offers * no mechanism to differentiate empty from absent. Neither of these components are popular in * practice. Typically HTTP applications use other mechanisms for user identification and * authentication. * * ### Host * * The host identifies the webserver that serves the URL's resource. It is either a hostname like * `square.com` or `localhost`, an IPv4 address like `192.168.0.1`, or an IPv6 address like `::1`. * * Usually a webserver is reachable with multiple identifiers: its IP addresses, registered * domain names, and even `localhost` when connecting from the server itself. Each of a web server's * names is a distinct URL and they are not interchangeable. For example, even if * `http://square.github.io/dagger` and `http://google.github.io/dagger` are served by the same IP * address, the two URLs identify different resources. * * ### Port * * The port used to connect to the web server. By default this is 80 for HTTP and 443 for HTTPS. * This class never returns -1 for the port: if no port is explicitly specified in the URL then the * scheme's default is used. * * ### Path * * The path identifies a specific resource on the host. Paths have a hierarchical structure like * "/square/okhttp/issues/1486" and decompose into a list of segments like `["square", "okhttp", * "issues", "1486"]`. * * This class offers methods to compose and decompose paths by segment. It composes each path * from a list of segments by alternating between "/" and the encoded segment. For example the * segments `["a", "b"]` build "/a/b" and the segments `["a", "b", ""]` build "/a/b/". * * If a path's last segment is the empty string then the path ends with "/". This class always * builds non-empty paths: if the path is omitted it defaults to "/". The default path's segment * list is a single empty string: `[""]`. * * ### Query * * The query is optional: it can be null, empty, or non-empty. For many HTTP URLs the query string * is subdivided into a collection of name-value parameters. This class offers methods to set the * query as the single string, or as individual name-value parameters. With name-value parameters * the values are optional and names may be repeated. * * ### Fragment * * The fragment is optional: it can be null, empty, or non-empty. Unlike host, port, path, and * query the fragment is not sent to the webserver: it's private to the client. * * ## Encoding * * Each component must be encoded before it is embedded in the complete URL. As we saw above, the * string `cute #puppies` is encoded as `cute%20%23puppies` when used as a query parameter value. * * ### Percent encoding * * Percent encoding replaces a character (like `\ud83c\udf69`) with its UTF-8 hex bytes (like * `%F0%9F%8D%A9`). This approach works for whitespace characters, control characters, non-ASCII * characters, and characters that already have another meaning in a particular context. * * Percent encoding is used in every URL component except for the hostname. But the set of * characters that need to be encoded is different for each component. For example, the path * component must escape all of its `?` characters, otherwise it could be interpreted as the * start of the URL's query. But within the query and fragment components, the `?` character * doesn't delimit anything and doesn't need to be escaped. * * ```java * HttpUrl url = HttpUrl.parse("http://who-let-the-dogs.out").newBuilder() * .addPathSegment("_Who?_") * .query("_Who?_") * .fragment("_Who?_") * .build(); * System.out.println(url); * ``` * * This prints: * * ``` * http://who-let-the-dogs.out/_Who%3F_?_Who?_#_Who?_ * ``` * * When parsing URLs that lack percent encoding where it is required, this class will percent encode * the offending characters. * * ### IDNA Mapping and Punycode encoding * * Hostnames have different requirements and use a different encoding scheme. It consists of IDNA * mapping and Punycode encoding. * * In order to avoid confusion and discourage phishing attacks, [IDNA Mapping][idna] transforms * names to avoid confusing characters. This includes basic case folding: transforming shouting * `SQUARE.COM` into cool and casual `square.com`. It also handles more exotic characters. For * example, the Unicode trademark sign (™) could be confused for the letters "TM" in * `http://ho™ail.com`. To mitigate this, the single character (™) maps to the string (tm). There * is similar policy for all of the 1.1 million Unicode code points. Note that some code points such * as "\ud83c\udf69" are not mapped and cannot be used in a hostname. * * [Punycode](http://ietf.org/rfc/rfc3492.txt) converts a Unicode string to an ASCII string to make * international domain names work everywhere. For example, "σ" encodes as "xn--4xa". The encoded * string is not human readable, but can be used with classes like [InetAddress] to establish * connections. * * ## Why another URL model? * * Java includes both [java.net.URL][URL] and [java.net.URI][URI]. We offer a new URL * model to address problems that the others don't. * * ### Different URLs should be different * * Although they have different content, `java.net.URL` considers the following two URLs * equal, and the [equals()][Object.equals] method between them returns true: * * * https://example.net/ * * * https://example.com/ * * This is because those two hosts share the same IP address. This is an old, bad design decision * that makes `java.net.URL` unusable for many things. It shouldn't be used as a [Map] key or in a * [Set]. Doing so is both inefficient because equality may require a DNS lookup, and incorrect * because unequal URLs may be equal because of how they are hosted. * * ### Equal URLs should be equal * * These two URLs are semantically identical, but `java.net.URI` disagrees: * * * http://host:80/ * * * http://host * * Both the unnecessary port specification (`:80`) and the absent trailing slash (`/`) cause URI to * bucket the two URLs separately. This harms URI's usefulness in collections. Any application that * stores information-per-URL will need to either canonicalize manually, or suffer unnecessary * redundancy for such URLs. * * Because they don't attempt canonical form, these classes are surprisingly difficult to use * securely. Suppose you're building a webservice that checks that incoming paths are prefixed * "/static/images/" before serving the corresponding assets from the filesystem. * * ```java * String attack = "http://example.com/static/images/../../../../../etc/passwd"; * System.out.println(new URL(attack).getPath()); * System.out.println(new URI(attack).getPath()); * System.out.println(HttpUrl.parse(attack).encodedPath()); * ``` * * By canonicalizing the input paths, they are complicit in directory traversal attacks. Code that * checks only the path prefix may suffer! * * ``` * /static/images/../../../../../etc/passwd * /static/images/../../../../../etc/passwd * /etc/passwd * ``` * * ### If it works on the web, it should work in your application * * The `java.net.URI` class is strict around what URLs it accepts. It rejects URLs like * `http://example.com/abc|def` because the `|` character is unsupported. This class is more * forgiving: it will automatically percent-encode the `|'` yielding `http://example.com/abc%7Cdef`. * This kind behavior is consistent with web browsers. `HttpUrl` prefers consistency with major web * browsers over consistency with obsolete specifications. * * ### Paths and Queries should decompose * * Neither of the built-in URL models offer direct access to path segments or query parameters. * Manually using `StringBuilder` to assemble these components is cumbersome: do '+' characters get * silently replaced with spaces? If a query parameter contains a '&amp;', does that get escaped? * By offering methods to read and write individual query parameters directly, application * developers are saved from the hassles of encoding and decoding. * * ### Plus a modern API * * The URL (JDK1.0) and URI (Java 1.4) classes predate builders and instead use telescoping * constructors. For example, there's no API to compose a URI with a custom port without also * providing a query and fragment. * * Instances of [HttpUrl] are well-formed and always have a scheme, host, and path. With * `java.net.URL` it's possible to create an awkward URL like `http:/` with scheme and path but no * hostname. Building APIs that consume such malformed values is difficult! * * This class has a modern API. It avoids punitive checked exceptions: [toHttpUrl] throws * [IllegalArgumentException] on invalid input or [toHttpUrlOrNull] returns null if the input is an * invalid URL. You can even be explicit about whether each component has been encoded already. * * [idna]: http://www.unicode.org/reports/tr46/#ToASCII */ class HttpUrl internal constructor( /** Either "http" or "https". */ @get:JvmName("scheme") val scheme: String, /** * The decoded username, or an empty string if none is present. * * | URL | `username()` | * | :------------------------------- | :----------- | * | `http://host/` | `""` | * | `http://username@host/` | `"username"` | * | `http://username:password@host/` | `"username"` | * | `http://a%20b:c%20d@host/` | `"a b"` | */ @get:JvmName("username") val username: String, /** * Returns the decoded password, or an empty string if none is present. * * | URL | `password()` | * | :------------------------------- | :----------- | * | `http://host/` | `""` | * | `http://username@host/` | `""` | * | `http://username:password@host/` | `"password"` | * | `http://a%20b:c%20d@host/` | `"c d"` | */ @get:JvmName("password") val password: String, /** * The host address suitable for use with [InetAddress.getAllByName]. May be: * * * A regular host name, like `android.com`. * * * An IPv4 address, like `127.0.0.1`. * * * An IPv6 address, like `::1`. Note that there are no square braces. * * * An encoded IDN, like `xn--n3h.net`. * * | URL | `host()` | * | :-------------------- | :-------------- | * | `http://android.com/` | `"android.com"` | * | `http://127.0.0.1/` | `"127.0.0.1"` | * | `http://[::1]/` | `"::1"` | * | `http://xn--n3h.net/` | `"xn--n3h.net"` | */ @get:JvmName("host") val host: String, /** * The explicitly-specified port if one was provided, or the default port for this URL's scheme. * For example, this returns 8443 for `https://square.com:8443/` and 443 for * `https://square.com/`. The result is in `[1..65535]`. * * | URL | `port()` | * | :------------------ | :------- | * | `http://host/` | `80` | * | `http://host:8000/` | `8000` | * | `https://host/` | `443` | */ @get:JvmName("port") val port: Int, /** * A list of path segments like `["a", "b", "c"]` for the URL `http://host/a/b/c`. This list is * never empty though it may contain a single empty string. * * | URL | `pathSegments()` | * | :----------------------- | :------------------ | * | `http://host/` | `[""]` | * | `http://host/a/b/c"` | `["a", "b", "c"]` | * | `http://host/a/b%20c/d"` | `["a", "b c", "d"]` | */ @get:JvmName("pathSegments") val pathSegments: List<String>, /** * Alternating, decoded query names and values, or null for no query. Names may be empty or * non-empty, but never null. Values are null if the name has no corresponding '=' separator, or * empty, or non-empty. */ private val queryNamesAndValues: List<String?>?, /** * This URL's fragment, like `"abc"` for `http://host/#abc`. This is null if the URL has no * fragment. * * | URL | `fragment()` | * | :--------------------- | :----------- | * | `http://host/` | null | * | `http://host/#` | `""` | * | `http://host/#abc` | `"abc"` | * | `http://host/#abc|def` | `"abc|def"` | */ @get:JvmName("fragment") val fragment: String?, /** Canonical URL. */ private val url: String ) { val isHttps: Boolean = scheme == "https" /** Returns this URL as a [java.net.URL][URL]. */ @JvmName("url") fun toUrl(): URL { try { return URL(url) } catch (e: MalformedURLException) { throw RuntimeException(e) // Unexpected! } } /** * Returns this URL as a [java.net.URI][URI]. Because `URI` is more strict than this class, the * returned URI may be semantically different from this URL: * * * Characters forbidden by URI like `[` and `|` will be escaped. * * * Invalid percent-encoded sequences like `%xx` will be encoded like `%25xx`. * * * Whitespace and control characters in the fragment will be stripped. * * These differences may have a significant consequence when the URI is interpreted by a * web server. For this reason the [URI class][URI] and this method should be avoided. */ @JvmName("uri") fun toUri(): URI { val uri = newBuilder().reencodeForUri().toString() return try { URI(uri) } catch (e: URISyntaxException) { // Unlikely edge case: the URI has a forbidden character in the fragment. Strip it & retry. try { val stripped = uri.replace(Regex("[\\u0000-\\u001F\\u007F-\\u009F\\p{javaWhitespace}]"), "") URI.create(stripped) } catch (e1: Exception) { throw RuntimeException(e) // Unexpected! } } } /** * The username, or an empty string if none is set. * * | URL | `encodedUsername()` | * | :------------------------------- | :------------------ | * | `http://host/` | `""` | * | `http://username@host/` | `"username"` | * | `http://username:password@host/` | `"username"` | * | `http://a%20b:c%20d@host/` | `"a%20b"` | */ @get:JvmName("encodedUsername") val encodedUsername: String get() { if (username.isEmpty()) return "" val usernameStart = scheme.length + 3 // "://".length() == 3. val usernameEnd = url.delimiterOffset(":@", usernameStart, url.length) return url.substring(usernameStart, usernameEnd) } /** * The password, or an empty string if none is set. * * | URL | `encodedPassword()` | * | :--------------------------------| :------------------ | * | `http://host/` | `""` | * | `http://username@host/` | `""` | * | `http://username:password@host/` | `"password"` | * | `http://a%20b:c%20d@host/` | `"c%20d"` | */ @get:JvmName("encodedPassword") val encodedPassword: String get() { if (password.isEmpty()) return "" val passwordStart = url.indexOf(':', scheme.length + 3) + 1 val passwordEnd = url.indexOf('@') return url.substring(passwordStart, passwordEnd) } /** * The number of segments in this URL's path. This is also the number of slashes in this URL's * path, like 3 in `http://host/a/b/c`. This is always at least 1. * * | URL | `pathSize()` | * | :------------------- | :----------- | * | `http://host/` | `1` | * | `http://host/a/b/c` | `3` | * | `http://host/a/b/c/` | `4` | */ @get:JvmName("pathSize") val pathSize: Int get() = pathSegments.size /** * The entire path of this URL encoded for use in HTTP resource resolution. The returned path will * start with `"/"`. * * | URL | `encodedPath()` | * | :---------------------- | :-------------- | * | `http://host/` | `"/"` | * | `http://host/a/b/c` | `"/a/b/c"` | * | `http://host/a/b%20c/d` | `"/a/b%20c/d"` | */ @get:JvmName("encodedPath") val encodedPath: String get() { val pathStart = url.indexOf('/', scheme.length + 3) // "://".length() == 3. val pathEnd = url.delimiterOffset("?#", pathStart, url.length) return url.substring(pathStart, pathEnd) } /** * A list of encoded path segments like `["a", "b", "c"]` for the URL `http://host/a/b/c`. This * list is never empty though it may contain a single empty string. * * | URL | `encodedPathSegments()` | * | :---------------------- | :---------------------- | * | `http://host/` | `[""]` | * | `http://host/a/b/c` | `["a", "b", "c"]` | * | `http://host/a/b%20c/d` | `["a", "b%20c", "d"]` | */ @get:JvmName("encodedPathSegments") val encodedPathSegments: List<String> get() { val pathStart = url.indexOf('/', scheme.length + 3) val pathEnd = url.delimiterOffset("?#", pathStart, url.length) val result = mutableListOf<String>() var i = pathStart while (i < pathEnd) { i++ // Skip the '/'. val segmentEnd = url.delimiterOffset('/', i, pathEnd) result.add(url.substring(i, segmentEnd)) i = segmentEnd } return result } /** * The query of this URL, encoded for use in HTTP resource resolution. This string may be null * (for URLs with no query), empty (for URLs with an empty query) or non-empty (all other URLs). * * | URL | `encodedQuery()` | * | :-------------------------------- | :--------------------- | * | `http://host/` | null | * | `http://host/?` | `""` | * | `http://host/?a=apple&k=key+lime` | `"a=apple&k=key+lime"` | * | `http://host/?a=apple&a=apricot` | `"a=apple&a=apricot"` | * | `http://host/?a=apple&b` | `"a=apple&b"` | */ @get:JvmName("encodedQuery") val encodedQuery: String? get() { if (queryNamesAndValues == null) return null // No query. val queryStart = url.indexOf('?') + 1 val queryEnd = url.delimiterOffset('#', queryStart, url.length) return url.substring(queryStart, queryEnd) } /** * This URL's query, like `"abc"` for `http://host/?abc`. Most callers should prefer * [queryParameterName] and [queryParameterValue] because these methods offer direct access to * individual query parameters. * * | URL | `query()` | * | :-------------------------------- | :--------------------- | * | `http://host/` | null | * | `http://host/?` | `""` | * | `http://host/?a=apple&k=key+lime` | `"a=apple&k=key lime"` | * | `http://host/?a=apple&a=apricot` | `"a=apple&a=apricot"` | * | `http://host/?a=apple&b` | `"a=apple&b"` | */ @get:JvmName("query") val query: String? get() { if (queryNamesAndValues == null) return null // No query. val result = StringBuilder() queryNamesAndValues.toQueryString(result) return result.toString() } /** * The number of query parameters in this URL, like 2 for `http://host/?a=apple&b=banana`. If this * URL has no query this is 0. Otherwise it is one more than the number of `"&"` separators in the * query. * * | URL | `querySize()` | * | :-------------------------------- | :------------ | * | `http://host/` | `0` | * | `http://host/?` | `1` | * | `http://host/?a=apple&k=key+lime` | `2` | * | `http://host/?a=apple&a=apricot` | `2` | * | `http://host/?a=apple&b` | `2` | */ @get:JvmName("querySize") val querySize: Int get() { return if (queryNamesAndValues != null) queryNamesAndValues.size / 2 else 0 } /** * The first query parameter named `name` decoded using UTF-8, or null if there is no such query * parameter. * * | URL | `queryParameter("a")` | * | :-------------------------------- | :-------------------- | * | `http://host/` | null | * | `http://host/?` | null | * | `http://host/?a=apple&k=key+lime` | `"apple"` | * | `http://host/?a=apple&a=apricot` | `"apple"` | * | `http://host/?a=apple&b` | `"apple"` | */ fun queryParameter(name: String): String? { if (queryNamesAndValues == null) return null for (i in 0 until queryNamesAndValues.size step 2) { if (name == queryNamesAndValues[i]) { return queryNamesAndValues[i + 1] } } return null } /** * The distinct query parameter names in this URL, like `["a", "b"]` for * `http://host/?a=apple&b=banana`. If this URL has no query this is the empty set. * * | URL | `queryParameterNames()` | * | :-------------------------------- | :---------------------- | * | `http://host/` | `[]` | * | `http://host/?` | `[""]` | * | `http://host/?a=apple&k=key+lime` | `["a", "k"]` | * | `http://host/?a=apple&a=apricot` | `["a"]` | * | `http://host/?a=apple&b` | `["a", "b"]` | */ @get:JvmName("queryParameterNames") val queryParameterNames: Set<String> get() { if (queryNamesAndValues == null) return emptySet() val result = LinkedHashSet<String>() for (i in 0 until queryNamesAndValues.size step 2) { result.add(queryNamesAndValues[i]!!) } return Collections.unmodifiableSet(result) } /** * Returns all values for the query parameter `name` ordered by their appearance in this * URL. For example this returns `["banana"]` for `queryParameterValue("b")` on * `http://host/?a=apple&b=banana`. * * | URL | `queryParameterValues("a")` | `queryParameterValues("b")` | * | :-------------------------------- | :-------------------------- | :-------------------------- | * | `http://host/` | `[]` | `[]` | * | `http://host/?` | `[]` | `[]` | * | `http://host/?a=apple&k=key+lime` | `["apple"]` | `[]` | * | `http://host/?a=apple&a=apricot` | `["apple", "apricot"]` | `[]` | * | `http://host/?a=apple&b` | `["apple"]` | `[null]` | */ fun queryParameterValues(name: String): List<String?> { if (queryNamesAndValues == null) return emptyList() val result = mutableListOf<String?>() for (i in 0 until queryNamesAndValues.size step 2) { if (name == queryNamesAndValues[i]) { result.add(queryNamesAndValues[i + 1]) } } return Collections.unmodifiableList(result) } /** * Returns the name of the query parameter at `index`. For example this returns `"a"` * for `queryParameterName(0)` on `http://host/?a=apple&b=banana`. This throws if * `index` is not less than the [query size][querySize]. * * | URL | `queryParameterName(0)` | `queryParameterName(1)` | * | :-------------------------------- | :---------------------- | :---------------------- | * | `http://host/` | exception | exception | * | `http://host/?` | `""` | exception | * | `http://host/?a=apple&k=key+lime` | `"a"` | `"k"` | * | `http://host/?a=apple&a=apricot` | `"a"` | `"a"` | * | `http://host/?a=apple&b` | `"a"` | `"b"` | */ fun queryParameterName(index: Int): String { if (queryNamesAndValues == null) throw IndexOutOfBoundsException() return queryNamesAndValues[index * 2]!! } /** * Returns the value of the query parameter at `index`. For example this returns `"apple"` for * `queryParameterName(0)` on `http://host/?a=apple&b=banana`. This throws if `index` is not less * than the [query size][querySize]. * * | URL | `queryParameterValue(0)` | `queryParameterValue(1)` | * | :-------------------------------- | :----------------------- | :----------------------- | * | `http://host/` | exception | exception | * | `http://host/?` | null | exception | * | `http://host/?a=apple&k=key+lime` | `"apple"` | `"key lime"` | * | `http://host/?a=apple&a=apricot` | `"apple"` | `"apricot"` | * | `http://host/?a=apple&b` | `"apple"` | null | */ fun queryParameterValue(index: Int): String? { if (queryNamesAndValues == null) throw IndexOutOfBoundsException() return queryNamesAndValues[index * 2 + 1] } /** * This URL's encoded fragment, like `"abc"` for `http://host/#abc`. This is null if the URL has * no fragment. * * | URL | `encodedFragment()` | * | :--------------------- | :------------------ | * | `http://host/` | null | * | `http://host/#` | `""` | * | `http://host/#abc` | `"abc"` | * | `http://host/#abc|def` | `"abc|def"` | */ @get:JvmName("encodedFragment") val encodedFragment: String? get() { if (fragment == null) return null val fragmentStart = url.indexOf('#') + 1 return url.substring(fragmentStart) } /** * Returns a string with containing this URL with its username, password, query, and fragment * stripped, and its path replaced with `/...`. For example, redacting * `http://username:[email protected]/path` returns `http://example.com/...`. */ fun redact(): String { return newBuilder("/...")!! .username("") .password("") .build() .toString() } /** * Returns the URL that would be retrieved by following `link` from this URL, or null if the * resulting URL is not well-formed. */ fun resolve(link: String): HttpUrl? = newBuilder(link)?.build() /** * Returns a builder based on this URL. */ fun newBuilder(): Builder { val result = Builder() result.scheme = scheme result.encodedUsername = encodedUsername result.encodedPassword = encodedPassword result.host = host // If we're set to a default port, unset it in case of a scheme change. result.port = if (port != defaultPort(scheme)) port else -1 result.encodedPathSegments.clear() result.encodedPathSegments.addAll(encodedPathSegments) result.encodedQuery(encodedQuery) result.encodedFragment = encodedFragment return result } /** * Returns a builder for the URL that would be retrieved by following `link` from this URL, * or null if the resulting URL is not well-formed. */ fun newBuilder(link: String): Builder? { return try { Builder().parse(this, link) } catch (_: IllegalArgumentException) { null } } override fun equals(other: Any?): Boolean { return other is HttpUrl && other.url == url } override fun hashCode(): Int = url.hashCode() override fun toString(): String = url /** * Returns the domain name of this URL's [host] that is one level beneath the public suffix by * consulting the [public suffix list](https://publicsuffix.org). Returns null if this URL's * [host] is an IP address or is considered a public suffix by the public suffix list. * * In general this method **should not** be used to test whether a domain is valid or routable. * Instead, DNS is the recommended source for that information. * * | URL | `topPrivateDomain()` | * | :---------------------------- | :------------------- | * | `http://google.com` | `"google.com"` | * | `http://adwords.google.co.uk` | `"google.co.uk"` | * | `http://square` | null | * | `http://co.uk` | null | * | `http://localhost` | null | * | `http://127.0.0.1` | null | */ fun topPrivateDomain(): String? { return if (host.canParseAsIpAddress()) { null } else { PublicSuffixDatabase.get().getEffectiveTldPlusOne(host) } } @JvmName("-deprecated_url") @Deprecated( message = "moved to toUrl()", replaceWith = ReplaceWith(expression = "toUrl()"), level = DeprecationLevel.ERROR) fun url(): URL = toUrl() @JvmName("-deprecated_uri") @Deprecated( message = "moved to toUri()", replaceWith = ReplaceWith(expression = "toUri()"), level = DeprecationLevel.ERROR) fun uri(): URI = toUri() @JvmName("-deprecated_scheme") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "scheme"), level = DeprecationLevel.ERROR) fun scheme(): String = scheme @JvmName("-deprecated_encodedUsername") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "encodedUsername"), level = DeprecationLevel.ERROR) fun encodedUsername(): String = encodedUsername @JvmName("-deprecated_username") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "username"), level = DeprecationLevel.ERROR) fun username(): String = username @JvmName("-deprecated_encodedPassword") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "encodedPassword"), level = DeprecationLevel.ERROR) fun encodedPassword(): String = encodedPassword @JvmName("-deprecated_password") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "password"), level = DeprecationLevel.ERROR) fun password(): String = password @JvmName("-deprecated_host") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "host"), level = DeprecationLevel.ERROR) fun host(): String = host @JvmName("-deprecated_port") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "port"), level = DeprecationLevel.ERROR) fun port(): Int = port @JvmName("-deprecated_pathSize") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "pathSize"), level = DeprecationLevel.ERROR) fun pathSize(): Int = pathSize @JvmName("-deprecated_encodedPath") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "encodedPath"), level = DeprecationLevel.ERROR) fun encodedPath(): String = encodedPath @JvmName("-deprecated_encodedPathSegments") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "encodedPathSegments"), level = DeprecationLevel.ERROR) fun encodedPathSegments(): List<String> = encodedPathSegments @JvmName("-deprecated_pathSegments") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "pathSegments"), level = DeprecationLevel.ERROR) fun pathSegments(): List<String> = pathSegments @JvmName("-deprecated_encodedQuery") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "encodedQuery"), level = DeprecationLevel.ERROR) fun encodedQuery(): String? = encodedQuery @JvmName("-deprecated_query") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "query"), level = DeprecationLevel.ERROR) fun query(): String? = query @JvmName("-deprecated_querySize") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "querySize"), level = DeprecationLevel.ERROR) fun querySize(): Int = querySize @JvmName("-deprecated_queryParameterNames") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "queryParameterNames"), level = DeprecationLevel.ERROR) fun queryParameterNames(): Set<String> = queryParameterNames @JvmName("-deprecated_encodedFragment") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "encodedFragment"), level = DeprecationLevel.ERROR) fun encodedFragment(): String? = encodedFragment @JvmName("-deprecated_fragment") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "fragment"), level = DeprecationLevel.ERROR) fun fragment(): String? = fragment class Builder { internal var scheme: String? = null internal var encodedUsername = "" internal var encodedPassword = "" internal var host: String? = null internal var port = -1 internal val encodedPathSegments = mutableListOf<String>() internal var encodedQueryNamesAndValues: MutableList<String?>? = null internal var encodedFragment: String? = null init { encodedPathSegments.add("") // The default path is '/' which needs a trailing space. } /** * @param scheme either "http" or "https". */ fun scheme(scheme: String) = apply { when { scheme.equals("http", ignoreCase = true) -> this.scheme = "http" scheme.equals("https", ignoreCase = true) -> this.scheme = "https" else -> throw IllegalArgumentException("unexpected scheme: $scheme") } } fun username(username: String) = apply { this.encodedUsername = username.canonicalize(encodeSet = USERNAME_ENCODE_SET) } fun encodedUsername(encodedUsername: String) = apply { this.encodedUsername = encodedUsername.canonicalize( encodeSet = USERNAME_ENCODE_SET, alreadyEncoded = true ) } fun password(password: String) = apply { this.encodedPassword = password.canonicalize(encodeSet = PASSWORD_ENCODE_SET) } fun encodedPassword(encodedPassword: String) = apply { this.encodedPassword = encodedPassword.canonicalize( encodeSet = PASSWORD_ENCODE_SET, alreadyEncoded = true ) } /** * @param host either a regular hostname, International Domain Name, IPv4 address, or IPv6 * address. */ fun host(host: String) = apply { val encoded = host.percentDecode().toCanonicalHost() ?: throw IllegalArgumentException( "unexpected host: $host") this.host = encoded } fun port(port: Int) = apply { require(port in 1..65535) { "unexpected port: $port" } this.port = port } private fun effectivePort(): Int { return if (port != -1) port else defaultPort(scheme!!) } fun addPathSegment(pathSegment: String) = apply { push(pathSegment, 0, pathSegment.length, addTrailingSlash = false, alreadyEncoded = false) } /** * Adds a set of path segments separated by a slash (either `\` or `/`). If `pathSegments` * starts with a slash, the resulting URL will have empty path segment. */ fun addPathSegments(pathSegments: String): Builder = addPathSegments(pathSegments, false) fun addEncodedPathSegment(encodedPathSegment: String) = apply { push(encodedPathSegment, 0, encodedPathSegment.length, addTrailingSlash = false, alreadyEncoded = true) } /** * Adds a set of encoded path segments separated by a slash (either `\` or `/`). If * `encodedPathSegments` starts with a slash, the resulting URL will have empty path segment. */ fun addEncodedPathSegments(encodedPathSegments: String): Builder = addPathSegments(encodedPathSegments, true) private fun addPathSegments(pathSegments: String, alreadyEncoded: Boolean) = apply { var offset = 0 do { val segmentEnd = pathSegments.delimiterOffset("/\\", offset, pathSegments.length) val addTrailingSlash = segmentEnd < pathSegments.length push(pathSegments, offset, segmentEnd, addTrailingSlash, alreadyEncoded) offset = segmentEnd + 1 } while (offset <= pathSegments.length) } fun setPathSegment(index: Int, pathSegment: String) = apply { val canonicalPathSegment = pathSegment.canonicalize(encodeSet = PATH_SEGMENT_ENCODE_SET) require(!isDot(canonicalPathSegment) && !isDotDot(canonicalPathSegment)) { "unexpected path segment: $pathSegment" } encodedPathSegments[index] = canonicalPathSegment } fun setEncodedPathSegment(index: Int, encodedPathSegment: String) = apply { val canonicalPathSegment = encodedPathSegment.canonicalize( encodeSet = PATH_SEGMENT_ENCODE_SET, alreadyEncoded = true ) encodedPathSegments[index] = canonicalPathSegment require(!isDot(canonicalPathSegment) && !isDotDot(canonicalPathSegment)) { "unexpected path segment: $encodedPathSegment" } } fun removePathSegment(index: Int) = apply { encodedPathSegments.removeAt(index) if (encodedPathSegments.isEmpty()) { encodedPathSegments.add("") // Always leave at least one '/'. } } fun encodedPath(encodedPath: String) = apply { require(encodedPath.startsWith("/")) { "unexpected encodedPath: $encodedPath" } resolvePath(encodedPath, 0, encodedPath.length) } fun query(query: String?) = apply { this.encodedQueryNamesAndValues = query?.canonicalize( encodeSet = QUERY_ENCODE_SET, plusIsSpace = true )?.toQueryNamesAndValues() } fun encodedQuery(encodedQuery: String?) = apply { this.encodedQueryNamesAndValues = encodedQuery?.canonicalize( encodeSet = QUERY_ENCODE_SET, alreadyEncoded = true, plusIsSpace = true )?.toQueryNamesAndValues() } /** Encodes the query parameter using UTF-8 and adds it to this URL's query string. */ fun addQueryParameter(name: String, value: String?) = apply { if (encodedQueryNamesAndValues == null) encodedQueryNamesAndValues = mutableListOf() encodedQueryNamesAndValues!!.add(name.canonicalize( encodeSet = QUERY_COMPONENT_ENCODE_SET, plusIsSpace = true )) encodedQueryNamesAndValues!!.add(value?.canonicalize( encodeSet = QUERY_COMPONENT_ENCODE_SET, plusIsSpace = true )) } /** Adds the pre-encoded query parameter to this URL's query string. */ fun addEncodedQueryParameter(encodedName: String, encodedValue: String?) = apply { if (encodedQueryNamesAndValues == null) encodedQueryNamesAndValues = mutableListOf() encodedQueryNamesAndValues!!.add(encodedName.canonicalize( encodeSet = QUERY_COMPONENT_REENCODE_SET, alreadyEncoded = true, plusIsSpace = true )) encodedQueryNamesAndValues!!.add(encodedValue?.canonicalize( encodeSet = QUERY_COMPONENT_REENCODE_SET, alreadyEncoded = true, plusIsSpace = true )) } fun setQueryParameter(name: String, value: String?) = apply { removeAllQueryParameters(name) addQueryParameter(name, value) } fun setEncodedQueryParameter(encodedName: String, encodedValue: String?) = apply { removeAllEncodedQueryParameters(encodedName) addEncodedQueryParameter(encodedName, encodedValue) } fun removeAllQueryParameters(name: String) = apply { if (encodedQueryNamesAndValues == null) return this val nameToRemove = name.canonicalize( encodeSet = QUERY_COMPONENT_ENCODE_SET, plusIsSpace = true ) removeAllCanonicalQueryParameters(nameToRemove) } fun removeAllEncodedQueryParameters(encodedName: String) = apply { if (encodedQueryNamesAndValues == null) return this removeAllCanonicalQueryParameters(encodedName.canonicalize( encodeSet = QUERY_COMPONENT_REENCODE_SET, alreadyEncoded = true, plusIsSpace = true )) } private fun removeAllCanonicalQueryParameters(canonicalName: String) { for (i in encodedQueryNamesAndValues!!.size - 2 downTo 0 step 2) { if (canonicalName == encodedQueryNamesAndValues!![i]) { encodedQueryNamesAndValues!!.removeAt(i + 1) encodedQueryNamesAndValues!!.removeAt(i) if (encodedQueryNamesAndValues!!.isEmpty()) { encodedQueryNamesAndValues = null return } } } } fun fragment(fragment: String?) = apply { this.encodedFragment = fragment?.canonicalize( encodeSet = FRAGMENT_ENCODE_SET, unicodeAllowed = true ) } fun encodedFragment(encodedFragment: String?) = apply { this.encodedFragment = encodedFragment?.canonicalize( encodeSet = FRAGMENT_ENCODE_SET, alreadyEncoded = true, unicodeAllowed = true ) } /** * Re-encodes the components of this URL so that it satisfies (obsolete) RFC 2396, which is * particularly strict for certain components. */ internal fun reencodeForUri() = apply { host = host?.replace(Regex("[\"<>^`{|}]"), "") for (i in 0 until encodedPathSegments.size) { encodedPathSegments[i] = encodedPathSegments[i].canonicalize( encodeSet = PATH_SEGMENT_ENCODE_SET_URI, alreadyEncoded = true, strict = true ) } val encodedQueryNamesAndValues = this.encodedQueryNamesAndValues if (encodedQueryNamesAndValues != null) { for (i in 0 until encodedQueryNamesAndValues.size) { encodedQueryNamesAndValues[i] = encodedQueryNamesAndValues[i]?.canonicalize( encodeSet = QUERY_COMPONENT_ENCODE_SET_URI, alreadyEncoded = true, strict = true, plusIsSpace = true ) } } encodedFragment = encodedFragment?.canonicalize( encodeSet = FRAGMENT_ENCODE_SET_URI, alreadyEncoded = true, strict = true, unicodeAllowed = true ) } fun build(): HttpUrl { @Suppress("UNCHECKED_CAST") // percentDecode returns either List<String?> or List<String>. return HttpUrl( scheme = scheme ?: throw IllegalStateException("scheme == null"), username = encodedUsername.percentDecode(), password = encodedPassword.percentDecode(), host = host ?: throw IllegalStateException("host == null"), port = effectivePort(), pathSegments = encodedPathSegments.map { it.percentDecode() }, queryNamesAndValues = encodedQueryNamesAndValues?.map { it?.percentDecode(plusIsSpace = true) }, fragment = encodedFragment?.percentDecode(), url = toString() ) } override fun toString(): String { return buildString { if (scheme != null) { append(scheme) append("://") } else { append("//") } if (encodedUsername.isNotEmpty() || encodedPassword.isNotEmpty()) { append(encodedUsername) if (encodedPassword.isNotEmpty()) { append(':') append(encodedPassword) } append('@') } if (host != null) { if (':' in host!!) { // Host is an IPv6 address. append('[') append(host) append(']') } else { append(host) } } if (port != -1 || scheme != null) { val effectivePort = effectivePort() if (scheme == null || effectivePort != defaultPort(scheme!!)) { append(':') append(effectivePort) } } encodedPathSegments.toPathString(this) if (encodedQueryNamesAndValues != null) { append('?') encodedQueryNamesAndValues!!.toQueryString(this) } if (encodedFragment != null) { append('#') append(encodedFragment) } } } internal fun parse(base: HttpUrl?, input: String): Builder { var pos = input.indexOfFirstNonAsciiWhitespace() val limit = input.indexOfLastNonAsciiWhitespace(pos) // Scheme. val schemeDelimiterOffset = schemeDelimiterOffset(input, pos, limit) if (schemeDelimiterOffset != -1) { when { input.startsWith("https:", ignoreCase = true, startIndex = pos) -> { this.scheme = "https" pos += "https:".length } input.startsWith("http:", ignoreCase = true, startIndex = pos) -> { this.scheme = "http" pos += "http:".length } else -> throw IllegalArgumentException("Expected URL scheme 'http' or 'https' but was '" + input.substring(0, schemeDelimiterOffset) + "'") } } else if (base != null) { this.scheme = base.scheme } else { val truncated = if (input.length > 6) input.take(6) + "..." else input throw IllegalArgumentException( "Expected URL scheme 'http' or 'https' but no scheme was found for $truncated") } // Authority. var hasUsername = false var hasPassword = false val slashCount = input.slashCount(pos, limit) if (slashCount >= 2 || base == null || base.scheme != this.scheme) { // Read an authority if either: // * The input starts with 2 or more slashes. These follow the scheme if it exists. // * The input scheme exists and is different from the base URL's scheme. // // The structure of an authority is: // username:password@host:port // // Username, password and port are optional. // [username[:password]@]host[:port] pos += slashCount authority@ while (true) { val componentDelimiterOffset = input.delimiterOffset("@/\\?#", pos, limit) val c = if (componentDelimiterOffset != limit) { input[componentDelimiterOffset].code } else { -1 } when (c) { '@'.code -> { // User info precedes. if (!hasPassword) { val passwordColonOffset = input.delimiterOffset(':', pos, componentDelimiterOffset) val canonicalUsername = input.canonicalize( pos = pos, limit = passwordColonOffset, encodeSet = USERNAME_ENCODE_SET, alreadyEncoded = true ) this.encodedUsername = if (hasUsername) { this.encodedUsername + "%40" + canonicalUsername } else { canonicalUsername } if (passwordColonOffset != componentDelimiterOffset) { hasPassword = true this.encodedPassword = input.canonicalize( pos = passwordColonOffset + 1, limit = componentDelimiterOffset, encodeSet = PASSWORD_ENCODE_SET, alreadyEncoded = true ) } hasUsername = true } else { this.encodedPassword = this.encodedPassword + "%40" + input.canonicalize( pos = pos, limit = componentDelimiterOffset, encodeSet = PASSWORD_ENCODE_SET, alreadyEncoded = true ) } pos = componentDelimiterOffset + 1 } -1, '/'.code, '\\'.code, '?'.code, '#'.code -> { // Host info precedes. val portColonOffset = portColonOffset(input, pos, componentDelimiterOffset) if (portColonOffset + 1 < componentDelimiterOffset) { host = input.percentDecode(pos = pos, limit = portColonOffset).toCanonicalHost() port = parsePort(input, portColonOffset + 1, componentDelimiterOffset) require(port != -1) { "Invalid URL port: \"${input.substring(portColonOffset + 1, componentDelimiterOffset)}\"" } } else { host = input.percentDecode(pos = pos, limit = portColonOffset).toCanonicalHost() port = defaultPort(scheme!!) } require(host != null) { "$INVALID_HOST: \"${input.substring(pos, portColonOffset)}\"" } pos = componentDelimiterOffset break@authority } } } } else { // This is a relative link. Copy over all authority components. Also maybe the path & query. this.encodedUsername = base.encodedUsername this.encodedPassword = base.encodedPassword this.host = base.host this.port = base.port this.encodedPathSegments.clear() this.encodedPathSegments.addAll(base.encodedPathSegments) if (pos == limit || input[pos] == '#') { encodedQuery(base.encodedQuery) } } // Resolve the relative path. val pathDelimiterOffset = input.delimiterOffset("?#", pos, limit) resolvePath(input, pos, pathDelimiterOffset) pos = pathDelimiterOffset // Query. if (pos < limit && input[pos] == '?') { val queryDelimiterOffset = input.delimiterOffset('#', pos, limit) this.encodedQueryNamesAndValues = input.canonicalize( pos = pos + 1, limit = queryDelimiterOffset, encodeSet = QUERY_ENCODE_SET, alreadyEncoded = true, plusIsSpace = true ).toQueryNamesAndValues() pos = queryDelimiterOffset } // Fragment. if (pos < limit && input[pos] == '#') { this.encodedFragment = input.canonicalize( pos = pos + 1, limit = limit, encodeSet = FRAGMENT_ENCODE_SET, alreadyEncoded = true, unicodeAllowed = true ) } return this } private fun resolvePath(input: String, startPos: Int, limit: Int) { var pos = startPos // Read a delimiter. if (pos == limit) { // Empty path: keep the base path as-is. return } val c = input[pos] if (c == '/' || c == '\\') { // Absolute path: reset to the default "/". encodedPathSegments.clear() encodedPathSegments.add("") pos++ } else { // Relative path: clear everything after the last '/'. encodedPathSegments[encodedPathSegments.size - 1] = "" } // Read path segments. var i = pos while (i < limit) { val pathSegmentDelimiterOffset = input.delimiterOffset("/\\", i, limit) val segmentHasTrailingSlash = pathSegmentDelimiterOffset < limit push(input, i, pathSegmentDelimiterOffset, segmentHasTrailingSlash, true) i = pathSegmentDelimiterOffset if (segmentHasTrailingSlash) i++ } } /** Adds a path segment. If the input is ".." or equivalent, this pops a path segment. */ private fun push( input: String, pos: Int, limit: Int, addTrailingSlash: Boolean, alreadyEncoded: Boolean ) { val segment = input.canonicalize( pos = pos, limit = limit, encodeSet = PATH_SEGMENT_ENCODE_SET, alreadyEncoded = alreadyEncoded ) if (isDot(segment)) { return // Skip '.' path segments. } if (isDotDot(segment)) { pop() return } if (encodedPathSegments[encodedPathSegments.size - 1].isEmpty()) { encodedPathSegments[encodedPathSegments.size - 1] = segment } else { encodedPathSegments.add(segment) } if (addTrailingSlash) { encodedPathSegments.add("") } } private fun isDot(input: String): Boolean { return input == "." || input.equals("%2e", ignoreCase = true) } private fun isDotDot(input: String): Boolean { return input == ".." || input.equals("%2e.", ignoreCase = true) || input.equals(".%2e", ignoreCase = true) || input.equals("%2e%2e", ignoreCase = true) } /** * Removes a path segment. When this method returns the last segment is always "", which means * the encoded path will have a trailing '/'. * * Popping "/a/b/c/" yields "/a/b/". In this case the list of path segments goes from ["a", * "b", "c", ""] to ["a", "b", ""]. * * Popping "/a/b/c" also yields "/a/b/". The list of path segments goes from ["a", "b", "c"] * to ["a", "b", ""]. */ private fun pop() { val removed = encodedPathSegments.removeAt(encodedPathSegments.size - 1) // Make sure the path ends with a '/' by either adding an empty string or clearing a segment. if (removed.isEmpty() && encodedPathSegments.isNotEmpty()) { encodedPathSegments[encodedPathSegments.size - 1] = "" } else { encodedPathSegments.add("") } } companion object { internal const val INVALID_HOST = "Invalid URL host" /** * Returns the index of the ':' in `input` that is after scheme characters. Returns -1 if * `input` does not have a scheme that starts at `pos`. */ private fun schemeDelimiterOffset(input: String, pos: Int, limit: Int): Int { if (limit - pos < 2) return -1 val c0 = input[pos] if ((c0 < 'a' || c0 > 'z') && (c0 < 'A' || c0 > 'Z')) return -1 // Not a scheme start char. characters@ for (i in pos + 1 until limit) { return when (input[i]) { // Scheme character. Keep going. in 'a'..'z', in 'A'..'Z', in '0'..'9', '+', '-', '.' -> continue@characters // Scheme prefix! ':' -> i // Non-scheme character before the first ':'. else -> -1 } } return -1 // No ':'; doesn't start with a scheme. } /** Returns the number of '/' and '\' slashes in this, starting at `pos`. */ private fun String.slashCount(pos: Int, limit: Int): Int { var slashCount = 0 for (i in pos until limit) { val c = this[i] if (c == '\\' || c == '/') { slashCount++ } else { break } } return slashCount } /** Finds the first ':' in `input`, skipping characters between square braces "[...]". */ private fun portColonOffset(input: String, pos: Int, limit: Int): Int { var i = pos while (i < limit) { when (input[i]) { '[' -> { while (++i < limit) { if (input[i] == ']') break } } ':' -> return i } i++ } return limit // No colon. } private fun parsePort(input: String, pos: Int, limit: Int): Int { return try { // Canonicalize the port string to skip '\n' etc. val portString = input.canonicalize(pos = pos, limit = limit, encodeSet = "") val i = portString.toInt() if (i in 1..65535) i else -1 } catch (_: NumberFormatException) { -1 // Invalid port. } } } } companion object { private val HEX_DIGITS = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F') internal const val USERNAME_ENCODE_SET = " \"':;<=>@[]^`{}|/\\?#" internal const val PASSWORD_ENCODE_SET = " \"':;<=>@[]^`{}|/\\?#" internal const val PATH_SEGMENT_ENCODE_SET = " \"<>^`{}|/\\?#" internal const val PATH_SEGMENT_ENCODE_SET_URI = "[]" internal const val QUERY_ENCODE_SET = " \"'<>#" internal const val QUERY_COMPONENT_REENCODE_SET = " \"'<>#&=" internal const val QUERY_COMPONENT_ENCODE_SET = " !\"#$&'(),/:;<=>?@[]\\^`{|}~" internal const val QUERY_COMPONENT_ENCODE_SET_URI = "\\^`{|}" internal const val FORM_ENCODE_SET = " !\"#$&'()+,/:;<=>?@[\\]^`{|}~" internal const val FRAGMENT_ENCODE_SET = "" internal const val FRAGMENT_ENCODE_SET_URI = " \"#<>\\^`{|}" /** Returns 80 if `scheme.equals("http")`, 443 if `scheme.equals("https")` and -1 otherwise. */ @JvmStatic fun defaultPort(scheme: String): Int { return when (scheme) { "http" -> 80 "https" -> 443 else -> -1 } } /** Returns a path string for this list of path segments. */ internal fun List<String>.toPathString(out: StringBuilder) { for (i in 0 until size) { out.append('/') out.append(this[i]) } } /** Returns a string for this list of query names and values. */ internal fun List<String?>.toQueryString(out: StringBuilder) { for (i in 0 until size step 2) { val name = this[i] val value = this[i + 1] if (i > 0) out.append('&') out.append(name) if (value != null) { out.append('=') out.append(value) } } } /** * Cuts this string up into alternating parameter names and values. This divides a query string * like `subject=math&easy&problem=5-2=3` into the list `["subject", "math", "easy", null, * "problem", "5-2=3"]`. Note that values may be null and may contain '=' characters. */ internal fun String.toQueryNamesAndValues(): MutableList<String?> { val result = mutableListOf<String?>() var pos = 0 while (pos <= length) { var ampersandOffset = indexOf('&', pos) if (ampersandOffset == -1) ampersandOffset = length val equalsOffset = indexOf('=', pos) if (equalsOffset == -1 || equalsOffset > ampersandOffset) { result.add(substring(pos, ampersandOffset)) result.add(null) // No value for this name. } else { result.add(substring(pos, equalsOffset)) result.add(substring(equalsOffset + 1, ampersandOffset)) } pos = ampersandOffset + 1 } return result } /** * Returns a new [HttpUrl] representing this. * * @throws IllegalArgumentException If this is not a well-formed HTTP or HTTPS URL. */ @JvmStatic @JvmName("get") fun String.toHttpUrl(): HttpUrl = Builder().parse(null, this).build() /** * Returns a new `HttpUrl` representing `url` if it is a well-formed HTTP or HTTPS URL, or null * if it isn't. */ @JvmStatic @JvmName("parse") fun String.toHttpUrlOrNull(): HttpUrl? { return try { toHttpUrl() } catch (_: IllegalArgumentException) { null } } /** * Returns an [HttpUrl] for this if its protocol is `http` or `https`, or null if it has any * other protocol. */ @JvmStatic @JvmName("get") fun URL.toHttpUrlOrNull(): HttpUrl? = toString().toHttpUrlOrNull() @JvmStatic @JvmName("get") fun URI.toHttpUrlOrNull(): HttpUrl? = toString().toHttpUrlOrNull() @JvmName("-deprecated_get") @Deprecated( message = "moved to extension function", replaceWith = ReplaceWith( expression = "url.toHttpUrl()", imports = ["okhttp3.HttpUrl.Companion.toHttpUrl"]), level = DeprecationLevel.ERROR) fun get(url: String): HttpUrl = url.toHttpUrl() @JvmName("-deprecated_parse") @Deprecated( message = "moved to extension function", replaceWith = ReplaceWith( expression = "url.toHttpUrlOrNull()", imports = ["okhttp3.HttpUrl.Companion.toHttpUrlOrNull"]), level = DeprecationLevel.ERROR) fun parse(url: String): HttpUrl? = url.toHttpUrlOrNull() @JvmName("-deprecated_get") @Deprecated( message = "moved to extension function", replaceWith = ReplaceWith( expression = "url.toHttpUrlOrNull()", imports = ["okhttp3.HttpUrl.Companion.toHttpUrlOrNull"]), level = DeprecationLevel.ERROR) fun get(url: URL): HttpUrl? = url.toHttpUrlOrNull() @JvmName("-deprecated_get") @Deprecated( message = "moved to extension function", replaceWith = ReplaceWith( expression = "uri.toHttpUrlOrNull()", imports = ["okhttp3.HttpUrl.Companion.toHttpUrlOrNull"]), level = DeprecationLevel.ERROR) fun get(uri: URI): HttpUrl? = uri.toHttpUrlOrNull() internal fun String.percentDecode( pos: Int = 0, limit: Int = length, plusIsSpace: Boolean = false ): String { for (i in pos until limit) { val c = this[i] if (c == '%' || c == '+' && plusIsSpace) { // Slow path: the character at i requires decoding! val out = Buffer() out.writeUtf8(this, pos, i) out.writePercentDecoded(this, pos = i, limit = limit, plusIsSpace = plusIsSpace) return out.readUtf8() } } // Fast path: no characters in [pos..limit) required decoding. return substring(pos, limit) } private fun Buffer.writePercentDecoded( encoded: String, pos: Int, limit: Int, plusIsSpace: Boolean ) { var codePoint: Int var i = pos while (i < limit) { codePoint = encoded.codePointAt(i) if (codePoint == '%'.code && i + 2 < limit) { val d1 = encoded[i + 1].parseHexDigit() val d2 = encoded[i + 2].parseHexDigit() if (d1 != -1 && d2 != -1) { writeByte((d1 shl 4) + d2) i += 2 i += Character.charCount(codePoint) continue } } else if (codePoint == '+'.code && plusIsSpace) { writeByte(' '.code) i++ continue } writeUtf8CodePoint(codePoint) i += Character.charCount(codePoint) } } private fun String.isPercentEncoded(pos: Int, limit: Int): Boolean { return pos + 2 < limit && this[pos] == '%' && this[pos + 1].parseHexDigit() != -1 && this[pos + 2].parseHexDigit() != -1 } /** * Returns a substring of `input` on the range `[pos..limit)` with the following * transformations: * * * Tabs, newlines, form feeds and carriage returns are skipped. * * * In queries, ' ' is encoded to '+' and '+' is encoded to "%2B". * * * Characters in `encodeSet` are percent-encoded. * * * Control characters and non-ASCII characters are percent-encoded. * * * All other characters are copied without transformation. * * @param alreadyEncoded true to leave '%' as-is; false to convert it to '%25'. * @param strict true to encode '%' if it is not the prefix of a valid percent encoding. * @param plusIsSpace true to encode '+' as "%2B" if it is not already encoded. * @param unicodeAllowed true to leave non-ASCII codepoint unencoded. * @param charset which charset to use, null equals UTF-8. */ internal fun String.canonicalize( pos: Int = 0, limit: Int = length, encodeSet: String, alreadyEncoded: Boolean = false, strict: Boolean = false, plusIsSpace: Boolean = false, unicodeAllowed: Boolean = false, charset: Charset? = null ): String { var codePoint: Int var i = pos while (i < limit) { codePoint = codePointAt(i) if (codePoint < 0x20 || codePoint == 0x7f || codePoint >= 0x80 && !unicodeAllowed || codePoint.toChar() in encodeSet || codePoint == '%'.code && (!alreadyEncoded || strict && !isPercentEncoded(i, limit)) || codePoint == '+'.code && plusIsSpace) { // Slow path: the character at i requires encoding! val out = Buffer() out.writeUtf8(this, pos, i) out.writeCanonicalized( input = this, pos = i, limit = limit, encodeSet = encodeSet, alreadyEncoded = alreadyEncoded, strict = strict, plusIsSpace = plusIsSpace, unicodeAllowed = unicodeAllowed, charset = charset ) return out.readUtf8() } i += Character.charCount(codePoint) } // Fast path: no characters in [pos..limit) required encoding. return substring(pos, limit) } private fun Buffer.writeCanonicalized( input: String, pos: Int, limit: Int, encodeSet: String, alreadyEncoded: Boolean, strict: Boolean, plusIsSpace: Boolean, unicodeAllowed: Boolean, charset: Charset? ) { var encodedCharBuffer: Buffer? = null // Lazily allocated. var codePoint: Int var i = pos while (i < limit) { codePoint = input.codePointAt(i) if (alreadyEncoded && (codePoint == '\t'.code || codePoint == '\n'.code || codePoint == '\u000c'.code || codePoint == '\r'.code)) { // Skip this character. } else if (codePoint == ' '.code && encodeSet === FORM_ENCODE_SET) { // Encode ' ' as '+'. writeUtf8("+") } else if (codePoint == '+'.code && plusIsSpace) { // Encode '+' as '%2B' since we permit ' ' to be encoded as either '+' or '%20'. writeUtf8(if (alreadyEncoded) "+" else "%2B") } else if (codePoint < 0x20 || codePoint == 0x7f || codePoint >= 0x80 && !unicodeAllowed || codePoint.toChar() in encodeSet || codePoint == '%'.code && (!alreadyEncoded || strict && !input.isPercentEncoded(i, limit))) { // Percent encode this character. if (encodedCharBuffer == null) { encodedCharBuffer = Buffer() } if (charset == null || charset == UTF_8) { encodedCharBuffer.writeUtf8CodePoint(codePoint) } else { encodedCharBuffer.writeString(input, i, i + Character.charCount(codePoint), charset) } while (!encodedCharBuffer.exhausted()) { val b = encodedCharBuffer.readByte().toInt() and 0xff writeByte('%'.code) writeByte(HEX_DIGITS[b shr 4 and 0xf].code) writeByte(HEX_DIGITS[b and 0xf].code) } } else { // This character doesn't need encoding. Just copy it over. writeUtf8CodePoint(codePoint) } i += Character.charCount(codePoint) } } } }
apache-2.0
a8a719e929dad4c28f13e148a4f92571
36.826738
106
0.574644
4.199228
false
false
false
false
toastkidjp/Jitte
app/src/main/java/jp/toastkid/yobidashi/browser/webview/dialog/ImageAnchorTypeLongTapDialogFragment.kt
1
3390
/* * Copyright (c) 2018 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.browser.webview.dialog import android.app.Dialog import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.core.net.toUri import androidx.core.os.bundleOf import androidx.fragment.app.DialogFragment import androidx.lifecycle.ViewModelProvider import jp.toastkid.lib.BrowserViewModel import jp.toastkid.lib.ContentViewModel import jp.toastkid.lib.Urls import jp.toastkid.search.ImageSearchUrlGenerator import jp.toastkid.yobidashi.R import jp.toastkid.yobidashi.browser.ImageDownloadActionDialogFragment import jp.toastkid.yobidashi.libs.clip.Clipboard /** * @author toastkidjp */ class ImageAnchorTypeLongTapDialogFragment : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val activityContext = activity ?: return super.onCreateDialog(savedInstanceState) val title = arguments?.getString(KEY_TITLE) ?: "" val imageUrl = arguments?.getString(KEY_IMAGE_URL) ?: return super.onCreateDialog(savedInstanceState) val anchor = arguments?.getString(KEY_ANCHOR) ?: return super.onCreateDialog(savedInstanceState) val viewModel = ViewModelProvider(activityContext).get(BrowserViewModel::class.java) val uri = anchor.toUri() return AlertDialog.Builder(activityContext) .setTitle("URL: $anchor") .setItems(R.array.image_anchor_menu) { _, which -> when (which) { 0 -> viewModel.open(uri) 1 -> viewModel.openBackground(title, uri) 2 -> viewModel.open(ImageSearchUrlGenerator()(imageUrl)) 3 -> ViewModelProvider(activityContext).get(BrowserViewModel::class.java).preview(uri) 4 -> downloadImage(imageUrl) 5 -> Clipboard.clip(activityContext, anchor) } } .setNegativeButton(R.string.cancel) { d, _ -> d.cancel() } .create() } private fun downloadImage(url: String) { val activityContext = activity ?: return if (Urls.isInvalidUrl(url)) { ViewModelProvider(activityContext).get(ContentViewModel::class.java) .snackShort(R.string.message_cannot_downloading_image) return } ImageDownloadActionDialogFragment.show(activityContext, url) } companion object { private const val KEY_TITLE = "title" private const val KEY_ANCHOR = "anchor" private const val KEY_IMAGE_URL = "extra" fun make(title: String, extra: String, anchor: String) = ImageAnchorTypeLongTapDialogFragment() .also { it.arguments = bundleOf( KEY_TITLE to title, KEY_IMAGE_URL to extra, KEY_ANCHOR to anchor ) } } }
epl-1.0
69f87c7a3d5d6598ac45051173143315
36.677778
110
0.623894
5.082459
false
false
false
false
andreas-oberheim/universal-markup-converter
src/main/kotlin/org/universal_markup_converter/api/FlexmarkMarkdownToHtmlConverter.kt
1
1944
/* * MIT License * Copyright (c) 2016 Andreas M. Oberheim * * 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 org.universal_markup_converter.api import com.vladsch.flexmark.html.HtmlRenderer import com.vladsch.flexmark.parser.Parser import com.vladsch.flexmark.profiles.pegdown.Extensions import com.vladsch.flexmark.profiles.pegdown.PegdownOptionsAdapter import java.io.File class FlexmarkMarkdownToHtmlConverter(fromFile: String, toFile: String) : AbstractMarkupConverter(fromFile, toFile) { override fun convert() { val options = PegdownOptionsAdapter.flexmarkOptions(Extensions.ALL) val parser = Parser.builder(options).build() val document = parser.parse(File(fromFile).readText()) val renderer = HtmlRenderer.builder(options).build() val html = renderer.render(document) File(toFile).writeText(html) } }
mit
0b92c26594fecc513b8e0572532c6dd9
45.285714
99
0.745885
4.489607
false
false
false
false
jdinkla/groovy-java-ray-tracer
src/main/kotlin/net/dinkla/raytracer/objects/Sphere.kt
1
2237
package net.dinkla.raytracer.objects import net.dinkla.raytracer.hits.Hit import net.dinkla.raytracer.hits.ShadowHit import net.dinkla.raytracer.math.* class Sphere(var center: Point3D = Point3D.ORIGIN, var radius: Double = 0.0) : GeometricObject() { init { boundingBox = BBox(center - radius, center + radius) } override fun hit(ray: Ray, sr: Hit): Boolean { var t: Double val temp = ray.origin - center val a = ray.direction.dot(ray.direction) val b = temp.times(2.0).dot(ray.direction) val c = temp.dot(temp) - radius * radius val disc = b * b - 4.0 * a * c if (disc < 0) { return false } else { val e = Math.sqrt(disc) val denom = 2 * a t = (-b - e) / denom if (t > MathUtils.K_EPSILON) { sr.t = t sr.normal = Normal(ray.direction.times(t).plus(temp).times(1.0 / radius)) return true } t = (-b + e) / denom if (t > MathUtils.K_EPSILON) { sr.t = t sr.normal = Normal(ray.direction.times(t).plus(temp).times(1.0 / radius)) return true } } return false } override fun shadowHit(ray: Ray, tmin: ShadowHit): Boolean { var t: Double val temp = ray.origin.minus(center) val a = ray.direction.dot(ray.direction) val b = temp.times(2.0).dot(ray.direction) val c = temp.dot(temp) - radius * radius val disc = b * b - 4.0 * a * c if (disc < 0) { return false } else { val e = Math.sqrt(disc) val denom = 2 * a t = (-b - e) / denom if (t > MathUtils.K_EPSILON) { tmin.t = t return true } t = (-b + e) / denom if (t > MathUtils.K_EPSILON) { tmin.t = t return true } } return false } override fun toString(): String { return "Sphere(" + center.toString() + ", " + radius + ")" } }
apache-2.0
41159a9b98fefc488a866fa1e1bbd4f0
28.643836
98
0.467143
3.843643
false
false
false
false
SUPERCILEX/Robot-Scouter
app/server/functions/src/main/kotlin/com/supercilex/robotscouter/server/functions/ClientApi.kt
1
1286
package com.supercilex.robotscouter.server.functions import com.supercilex.robotscouter.server.utils.types.CallableContext import com.supercilex.robotscouter.server.utils.types.HttpsError import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.asPromise import kotlinx.coroutines.async import kotlin.js.Json import kotlin.js.Promise fun processClientRequest(data: Json, context: CallableContext): Promise<Any?> { val auth = context.auth ?: throw HttpsError("unauthenticated") val rawOperation = data["operation"] as? String console.log( "Processing '$rawOperation' operation for user '${auth.uid}' with args: ", JSON.stringify(data) ) if (rawOperation == null) { throw HttpsError("invalid-argument", "An operation must be supplied.") } val operation = rawOperation.toUpperCase().replace("-", "_") return GlobalScope.async { when (operation) { "EMPTY_TRASH" -> emptyTrash(auth, data) "TRANSFER_USER_DATA" -> transferUserData(auth, data) "UPDATE_OWNERS" -> updateOwners(auth, data) "UPDATE_TEAM_MEDIA" -> updateTeamMedia(auth, data) else -> throw HttpsError("invalid-argument", "Unknown operation: $rawOperation") } }.asPromise() }
gpl-3.0
ca01e7aa3fe01f0d4e0d06c89472eec0
37.969697
92
0.68818
4.286667
false
false
false
false
jainaman224/Algo_Ds_Notes
nCr mod P/nCr_mod_P.kt
1
1058
import java.util.* // Function for nCr fun nCr(n: Int, r: Int, mod: Int):Int { if(n < r) { return -1 } var pascal = IntArray(r + 1) pascal[0] = 1 for (i in 1 until r + 1) { pascal[i] = 0 } // We use the known formula nCr = (n-1)C(r) + (n-1)C(r-1) for computing the values. for (i in 1 until n + 1) { var k: Int if (i < r) { k = i } else { k = r } for (j in k downTo 1) { pascal[j] = (pascal[j] + pascal[j - 1]) % mod } } return pascal[r] } fun main() { val scanner = Scanner(System.`in`) println("Please Enter Three Integers.") var n = scanner.nextInt() var r = scanner.nextInt() var mod = scanner.nextInt() var ans = nCr(n, r, mod) if (ans == -1) { println("n can never be less than r.") } else { println("The value of nCr($n,$r) % $mod = $ans") } } // Input:- Please Enter Three Integers. // 7 5 6 // Output:- The value of nCr(7,5) % 6 = 3
gpl-3.0
57c30689f9ce1e4942a63182139f0591
21.510638
87
0.47448
2.997167
false
false
false
false