repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
dhis2/dhis2-android-sdk
core/src/test/java/org/hisp/dhis/android/core/settings/internal/ProgramSettingCallShould.kt
1
3256
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 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. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * 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 OWNER 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. */ package org.hisp.dhis.android.core.settings.internal import com.nhaarman.mockitokotlin2.* import io.reactivex.Single import org.hisp.dhis.android.core.arch.api.executors.internal.RxAPICallExecutor import org.hisp.dhis.android.core.arch.handlers.internal.Handler import org.hisp.dhis.android.core.maintenance.D2ErrorSamples import org.hisp.dhis.android.core.settings.ProgramSetting import org.hisp.dhis.android.core.settings.ProgramSettings import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class ProgramSettingCallShould { private val handler: Handler<ProgramSetting> = mock() private val service: SettingAppService = mock() private val programSettingSingle: Single<ProgramSettings> = mock() private val apiCallExecutor: RxAPICallExecutor = mock() private val appVersionManager: SettingsAppInfoManager = mock() private lateinit var programSettingCall: ProgramSettingCall @Before fun setUp() { whenever(appVersionManager.getDataStoreVersion()) doReturn Single.just(SettingsAppDataStoreVersion.V1_1) whenever(service.programSettings(any())) doReturn programSettingSingle programSettingCall = ProgramSettingCall(handler, service, apiCallExecutor, appVersionManager) } @Test fun default_to_empty_collection_if_not_found() { whenever(apiCallExecutor.wrapSingle(programSettingSingle, false)) doReturn Single.error(D2ErrorSamples.notFound()) programSettingCall.getCompletable(false).blockingAwait() verify(handler).handleMany(emptyList()) verifyNoMoreInteractions(handler) } }
bsd-3-clause
d4e4a88e1c01e64f643c233fccfea873
46.188406
112
0.773649
4.429932
false
false
false
false
dhis2/dhis2-android-sdk
core/src/androidTest/java/org/hisp/dhis/android/testapp/arch/helpers/FileResizerHelperShould.kt
1
6134
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 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. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * 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 OWNER 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. */ package org.hisp.dhis.android.testapp.arch.helpers import android.graphics.Bitmap import android.graphics.Bitmap.CompressFormat import android.graphics.BitmapFactory import android.util.Log import androidx.test.platform.app.InstrumentationRegistry import com.google.common.truth.Truth.assertThat import java.io.File import java.io.FileOutputStream import java.io.OutputStream import java.util.* import org.hisp.dhis.android.core.arch.helpers.FileResizerHelper import org.hisp.dhis.android.core.arch.helpers.FileResourceDirectoryHelper import org.hisp.dhis.android.core.utils.runner.D2JunitRunner import org.junit.Test import org.junit.runner.RunWith @RunWith(D2JunitRunner::class) class FileResizerHelperShould { @Test fun resize_to_small_file() { val file = getFile(CompressFormat.PNG, getBitmap(2048, 1024)) val bitmap = BitmapFactory.decodeFile(file.absolutePath) assertThat(bitmap.height).isEqualTo(1024) assertThat(bitmap.width).isEqualTo(2048) val resizedFile = FileResizerHelper.resizeFile(file, FileResizerHelper.Dimension.SMALL) val resizedBitmap = BitmapFactory.decodeFile(resizedFile.absolutePath) assertThat(resizedBitmap.height).isEqualTo(128) assertThat(resizedBitmap.width).isEqualTo(256) } @Test fun resize_to_medium_file() { val file = getFile(CompressFormat.PNG, getBitmap(2048, 1024)) val bitmap = BitmapFactory.decodeFile(file.absolutePath) assertThat(bitmap.height).isEqualTo(1024) assertThat(bitmap.width).isEqualTo(2048) val resizedFile = FileResizerHelper.resizeFile(file, FileResizerHelper.Dimension.MEDIUM) val resizedBitmap = BitmapFactory.decodeFile(resizedFile.absolutePath) assertThat(resizedBitmap.height).isEqualTo(256) assertThat(resizedBitmap.width).isEqualTo(512) } @Test fun resize_to_large_file() { val file = getFile(CompressFormat.PNG, getBitmap(2048, 1024)) val bitmap = BitmapFactory.decodeFile(file.absolutePath) assertThat(bitmap.height).isEqualTo(1024) assertThat(bitmap.width).isEqualTo(2048) val resizedFile = FileResizerHelper.resizeFile(file, FileResizerHelper.Dimension.LARGE) val resizedBitmap = BitmapFactory.decodeFile(resizedFile.absolutePath) assertThat(resizedBitmap.height).isEqualTo(512) assertThat(resizedBitmap.width).isEqualTo(1024) } @Test fun resize_jpeg() { val file = getFile(CompressFormat.JPEG, getBitmap(2048, 1024)) val bitmap = BitmapFactory.decodeFile(file.absolutePath) assertThat(bitmap.height).isEqualTo(1024) assertThat(bitmap.width).isEqualTo(2048) val resizedFile = FileResizerHelper.resizeFile(file, FileResizerHelper.Dimension.SMALL) val resizedBitmap = BitmapFactory.decodeFile(resizedFile.absolutePath) assertThat(resizedBitmap.height).isEqualTo(128) assertThat(resizedBitmap.width).isEqualTo(256) } @Test fun do_not_resize_small_to_large_file() { val file = getFile(CompressFormat.PNG, getBitmap(100, 125)) val bitmap = BitmapFactory.decodeFile(file.absolutePath) assertThat(bitmap.height).isEqualTo(125) assertThat(bitmap.width).isEqualTo(100) val resizedFile = FileResizerHelper.resizeFile(file, FileResizerHelper.Dimension.LARGE) val resizedBitmap = BitmapFactory.decodeFile(resizedFile.absolutePath) assertThat(resizedBitmap.height).isEqualTo(125) assertThat(resizedBitmap.width).isEqualTo(100) } companion object { private fun getFile(compressFormat: CompressFormat, bitmap: Bitmap): File { val context = InstrumentationRegistry.getInstrumentation().context val imageFile = File( FileResourceDirectoryHelper.getRootFileResourceDirectory(context), "image." + compressFormat.name.lowercase(Locale.getDefault()) ) val os: OutputStream try { os = FileOutputStream(imageFile) bitmap.compress(compressFormat, 100, os) os.flush() os.close() } catch (e: Exception) { Log.e(FileResizerHelperShould::class.java.simpleName, "Error writing bitmap", e) } return imageFile } private fun getBitmap(width: Int, height: Int): Bitmap { return Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565) } } }
bsd-3-clause
f063289203c44c88ffdf37b23c797931
43.449275
96
0.71927
4.536982
false
true
false
false
Frederikam/FredBoat
FredBoat/src/main/java/fredboat/sentinel/SentinelSessionController.kt
1
4633
package fredboat.sentinel import com.fredboat.sentinel.SentinelExchanges import com.fredboat.sentinel.entities.AppendSessionEvent import com.fredboat.sentinel.entities.RemoveSessionEvent import com.fredboat.sentinel.entities.RunSessionRequest import com.fredboat.sentinel.entities.SyncSessionQueueRequest import fredboat.config.property.AppConfigProperties import fredboat.util.DiscordUtil import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.amqp.rabbit.core.RabbitTemplate import org.springframework.stereotype.Service import java.lang.Thread.sleep import java.util.concurrent.ConcurrentHashMap import kotlin.concurrent.thread @Service class SentinelSessionController( val rabbit: RabbitTemplate, val appConfig: AppConfigProperties, val sentinelTracker: SentinelTracker ) { companion object { private val log: Logger = LoggerFactory.getLogger(SentinelSessionController::class.java) private const val MAX_HELLO_AGE_MS = 40000 private const val HOME_GUILD_ID = 174820236481134592L // FredBoat Hangout is to be prioritized private const val IDENTIFY_DELAY = 5000L private const val QUEUE_SYNC_INTERVAL = 60000 // 1 minute } @Suppress("LeakingThis") val homeShardId = DiscordUtil.getShardId(HOME_GUILD_ID, appConfig) val queued = ConcurrentHashMap<Int, AppendSessionEvent>() var worker: Thread? = null private var lastSyncRequest = 0L init { startWorker() } fun appendSession(event: AppendSessionEvent) { event.totalShards.assertShardCount() queued[event.shardId] = event log.info("Appended ${event.shardId}") } fun removeSession(event: RemoveSessionEvent) { event.totalShards.assertShardCount() queued.remove(event.shardId) log.info("Removed ${event.shardId}") } private fun Int.assertShardCount() { if (this != appConfig.shardCount) { throw IllegalStateException("Mismatching shard count. Got $this, expected ${appConfig.shardCount}") } } fun getNextShard(): AppendSessionEvent? { // Figure out which sentinels we wish to command. This filters outs unresponsive ones val sentinelKeys = sentinelTracker.sentinels .asSequence() .filter { System.currentTimeMillis() - it.time <= MAX_HELLO_AGE_MS } .map { it.key } .toList() // Check for the home shard queued[homeShardId]?.let { if (sentinelKeys.contains(it.routingKey)) return it } // Otherwise just get the lowest possible shard queued.values.sortedBy { it.shardId }.forEach { if (sentinelKeys.contains(it.routingKey)) return it } return null } private fun workerLoop() { if (lastSyncRequest + QUEUE_SYNC_INTERVAL < System.currentTimeMillis()) { // This is meant to deal with race conditions where our queues are out of sync // Specifically, this tends to happen when restarting sentinel at the same time as FredBoat rabbit.convertAndSend(SentinelExchanges.FANOUT, "", SyncSessionQueueRequest()) lastSyncRequest = System.currentTimeMillis() } val next = getNextShard() if (next == null) { sleep(1000) return } val request = RunSessionRequest(next.shardId) log.info("Requesting ${next.routingKey} to start shard ${next.shardId}") val started = System.currentTimeMillis() val response = rabbit.convertSendAndReceive(SentinelExchanges.REQUESTS, next.routingKey, request) log.debug("Sentinel responded with $response") val timeTaken = System.currentTimeMillis() - started if (response == null) { throw RuntimeException("Failed to get ${next.routingKey} to start shard ${next.shardId}") } else { log.info("Started ${next.shardId} from ${next.routingKey}, took ${timeTaken}ms") } sleep(IDENTIFY_DELAY) queued.remove(next.shardId) } private fun startWorker() { if (worker?.isAlive == true) throw IllegalStateException("Worker is already alive") worker = thread(name = "session-worker") { log.info("Started session worker") while (true) { try { workerLoop() } catch (e: Exception) { log.error("Caught exception in session worker loop", e) sleep(500) } } } } }
mit
49ab88292edbeb55cce0b387572706be
34.922481
111
0.653572
4.689271
false
true
false
false
aerisweather/AerisAndroidSDK
Kotlin/AerisSdkDemo/app/src/main/java/com/example/demoaerisproject/data/preferenceStore/PrefStoreRepository.kt
1
3725
package com.example.demoaerisproject.data.preferenceStore import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.SharedPreferencesMigration import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.preferencesKey import androidx.datastore.preferences.createDataStore import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.map import kotlinx.coroutines.runBlocking import javax.inject.Inject class PrefStoreRepository @Inject constructor( @ApplicationContext val context: Context ) { private val STORE_NAME = "aeris_data_store" private val PREFS_NAME = "aeris_preference" private val prefStore: DataStore<Preferences> companion object { const val NOTIFICATION_ENABLED_KEY = "notification_enabled_key" const val UNIT_METRIC_ENABLED_KEY = "unit_metric_enabled_key" const val NTF_TIMESTAMP_KEY = "ntf_timestamp_key" const val LAST_FRAGMENT_KEY = "last_fragment_key" const val STRING_FLAG = "string_flag" const val LONG_FLAG = "long_flag" } init { prefStore = context.createDataStore( name = STORE_NAME, migrations = listOf(SharedPreferencesMigration(context, PREFS_NAME)) ) } /* * Reified example - no delay */ inline fun <reified T> get(key: String, defaultValue: T): T { return runBlocking { when (defaultValue) { is Boolean -> getBoolean(key).firstOrNull() ?: defaultValue is Int -> getInt(key).firstOrNull() ?: defaultValue is String -> getString(key).firstOrNull() ?: defaultValue is Long -> getLong(key).firstOrNull() ?: defaultValue else -> null } as T } } inline fun <reified T> set(key: String, value: T): Boolean { return runBlocking { when (value) { is Boolean -> { setBoolean(key, value as Boolean) true } is Int -> { setInt(key, value as Int) true } is String -> { setString(key, value as String) true } is Long -> { setLong(key, value as Long) true } else -> false } } } fun getBoolean(flag: String): Flow<Boolean?> { return prefStore.data.map { it[preferencesKey(flag)] } } suspend fun setBoolean(flag: String, isTrue: Boolean) { prefStore.edit { it[preferencesKey<Boolean>(flag)] = isTrue } } fun getString(flag: String): Flow<String> { return prefStore.data.map { it[preferencesKey(flag)] ?: "" } } suspend fun setString(flag: String, str: String ) { prefStore.edit { it[preferencesKey<String>(flag)] = str } } fun getLong(flag: String): Flow<Long> { return prefStore.data.map { it[preferencesKey(flag)] ?: -1L } } suspend fun setLong(flag: String, num: Long) { prefStore.edit { it[preferencesKey<Long>(flag)] = num } } fun getInt(flag: String): Flow<Int?> { return prefStore.data.map { it[preferencesKey(flag)] } } suspend fun setInt(flag: String, num: Int) { prefStore.edit { it[preferencesKey<Int>(flag)] = num } } }
mit
44af802b931103824eb47c96dc7c2e95
30.05
80
0.588993
4.53715
false
false
false
false
dkandalov/katas
kotlin/src/katas/kotlin/regression/jfree-chart.kt
1
3729
package katas.kotlin.regression import org.jfree.chart.ChartFactory import org.jfree.chart.ChartPanel import org.jfree.chart.ChartUtils import org.jfree.chart.JFreeChart import org.jfree.chart.axis.DateAxis import org.jfree.chart.plot.XYPlot import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer import org.jfree.chart.ui.RectangleInsets import org.jfree.data.time.FixedMillisecond import org.jfree.data.time.TimeSeries import org.jfree.data.time.TimeSeriesCollection import org.jfree.data.xy.XYDataset import java.awt.Color import java.io.File import java.text.SimpleDateFormat import javax.swing.JFrame import javax.swing.JPanel import kotlin.math.sin fun main() { val chart = createChart(createDataset()) JFrame("").apply { contentPane.add(createDemoPanel(chart)) pack() isVisible = true } ChartUtils.saveChartAsJPEG(File("foo.jpeg"), chart, 600, 400) } fun createDemoPanel(chart: JFreeChart): JPanel { val panel = ChartPanel(chart, false) panel.fillZoomRectangle = true panel.isMouseWheelEnabled = true return panel } fun createChart(dataset: XYDataset): JFreeChart { val title = "Legal & General Unit Trust Prices" val xAxisLabel = "Date" val yAxisLabel = "Price Per Unit" val chart = ChartFactory.createTimeSeriesChart(title, xAxisLabel, yAxisLabel, dataset) chart.backgroundPaint = Color.WHITE val plot = chart.plot as XYPlot plot.backgroundPaint = Color.LIGHT_GRAY plot.domainGridlinePaint = Color.WHITE plot.rangeGridlinePaint = Color.WHITE plot.axisOffset = RectangleInsets(5.0, 5.0, 5.0, 5.0) plot.isDomainCrosshairVisible = true plot.isRangeCrosshairVisible = true val r = plot.renderer if (r is XYLineAndShapeRenderer) { r.defaultShapesVisible = true r.defaultShapesFilled = true r.drawSeriesLineAsPath = true } val axis = plot.domainAxis as DateAxis axis.dateFormatOverride = SimpleDateFormat("MMM-yyyy") return chart } private fun createDataset(): XYDataset = TimeSeriesCollection().apply { addSeries(TimeSeries("sin").apply { (1..1000).map { val time = FixedMillisecond(it.toLong()) val value = sin(it.toDouble() / 100) * 100 + 100 add(time, value) } }) /* TimeSeries("L&G European Index Trust").apply { add(Month(2, 2001), 181.8) add(Month(3, 2001), 167.3) add(Month(4, 2001), 153.8) add(Month(5, 2001), 167.6) add(Month(6, 2001), 158.8) add(Month(7, 2001), 148.3) add(Month(8, 2001), 153.9) add(Month(9, 2001), 142.7) add(Month(10, 2001), 123.2) add(Month(11, 2001), 131.8) add(Month(12, 2001), 139.6) add(Month(1, 2002), 142.9) add(Month(2, 2002), 138.7) add(Month(3, 2002), 137.3) add(Month(4, 2002), 143.9) add(Month(5, 2002), 139.8) add(Month(6, 2002), 137.0) add(Month(7, 2002), 132.8) addSeries(this) } */ /*TimeSeries("L&G UK Index Trust").apply { add(Month(2, 2001), 129.6) add(Month(3, 2001), 123.2) add(Month(4, 2001), 117.2) add(Month(5, 2001), 124.1) add(Month(6, 2001), 122.6) add(Month(7, 2001), 119.2) add(Month(8, 2001), 116.5) add(Month(9, 2001), 112.7) add(Month(10, 2001), 101.5) add(Month(11, 2001), 106.1) add(Month(12, 2001), 110.3) add(Month(1, 2002), 111.7) add(Month(2, 2002), 111.0) add(Month(3, 2002), 109.6) add(Month(4, 2002), 113.2) add(Month(5, 2002), 111.6) add(Month(6, 2002), 108.8) add(Month(7, 2002), 101.6) addSeries(this) }*/ }
unlicense
a19c057f800f4fa6f1306503d3d73544
30.336134
90
0.632877
3.203608
false
false
false
false
JonathanxD/CodeAPI
src/main/kotlin/com/github/jonathanxd/kores/processor/Validator.kt
1
13727
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]> * Copyright (c) contributors * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.jonathanxd.kores.processor import com.github.jonathanxd.kores.KoresPart import com.github.jonathanxd.iutils.data.TypedData import com.github.jonathanxd.iutils.processing.Context import java.util.* /** * Manages all [Validators][Validator] used to validate [part][Any]. */ interface ValidatorManager { /** * Validates [part] and return environment used to validate. */ fun validate( part: Any, data: TypedData, environment: ValidationEnvironment? = null ): ValidationEnvironment = this.validate(part::class.java, part, data, environment) /** * Validates [part] of type [type] and return environment used to validate. */ fun <P> validate( type: Class<out P>, part: P, data: TypedData, environment: ValidationEnvironment? = null ): ValidationEnvironment /** * Registers a custom [validator] of [KoresPart] of [type]. */ fun <P> registerValidator(validator: Validator<P>, type: Class<P>) /** * Creates default [TypedData] instance. */ fun createData(): TypedData = TypedData() /** * Creates default [ValidationEnvironment] */ fun createEnvironment(data: TypedData): ValidationEnvironment = ValidationEnvironment.Impl(data) } /** * Registers a custom [validator] of [KoresPart] of type [P]. */ inline fun <reified P> ValidatorManager.registerValidator(validator: Validator<P>) = this.registerValidator(validator, P::class.java) /** * Validates [part] of type [P]. */ inline fun <reified P> ValidatorManager.validatePart(part: P, data: TypedData) = this.validate(P::class.java, part, data) /** * Custom validator */ interface Validator<in P> { /** * Validates [part] and return a list of messages. */ fun validate( part: P, data: TypedData, validatorManager: ValidatorManager, environment: ValidationEnvironment ) } /** * Validation environment to index [ValidationMessages][ValidationMessage]. */ interface ValidationEnvironment { /** * Data */ val data: TypedData /** * Immutable view list of indexed contexted validation messages. */ val validationMessages: List<ContextedValidationMessage> /** * Current context. */ val context: Context /** * Enters a session, a session is used to keep track about all messages * added after [enterSession] invocation. * * This is used to analyze messages of other validation processes without needing to rely * on list size and sub-list, a new session keeps track of messages * added after the invocation of this method and before the invocation of [exitSession], * but the list of messages does not have any relation with the list holden by [ValidationEnvironment], * values are added simultaneously to session and [ValidationEnvironment]. * * The list provided by session is mutable. * * Returns new session. */ fun enterSession(): Session /** * Exists current session. * * Returns exited session. */ fun exitSession(): Session /** * Adds a [ValidationMessage] to index. */ fun addMessage(message: ValidationMessage) /** * Adds [part] to inspection context */ fun enterInspectionOf(part: Any) /** * Exits the inspection of [part]. This method may throw [UnexpectedInspectionContext], if * the last value of inspection context is not [Any.equals] to [part]. */ fun exitInspectionOf(part: Any) /** * Common implementation of [ValidationEnvironment] */ class Impl(override val data: TypedData) : ValidationEnvironment { private val backingList = mutableListOf<ContextedValidationMessage>() override val context: Context = Context.create() override val validationMessages: List<ContextedValidationMessage> = Collections.unmodifiableList(this.backingList) private var currentSession: Session? = null override fun addMessage(message: ValidationMessage) { val msg = ContextedValidationMessage(message, this.context.current()) this.backingList += msg this.currentSession?.addMessage(msg) } override fun enterSession(): Session { val sec = Session(this.currentSession, this.context.current()) this.currentSession = sec return sec } override fun exitSession(): Session { val sc = this.currentSession ?: throw IllegalStateException("Current section is null") this.currentSession = sc.parent return sc } override fun enterInspectionOf(part: Any) { context.enterContext(part) } override fun exitInspectionOf(part: Any) { context.exitContext(part) } override fun toString(): String = "[messages={${validationMessages.joinToString()},context=$context]" } /** * A session, used to keep track of a fragment of messages added by other validations. * * @see [enterSession] */ class Session( internal val parent: Session?, val context: Context ) { private val messageList: MutableList<ContextedValidationMessage> = mutableListOf() val messages: List<ContextedValidationMessage> get() = messageList fun addMessage(message: ContextedValidationMessage) { this.parent?.addMessage(message) this.messageList.add(message) } fun anyError() = messages.hasContextedError() } } /** * Creates session to be used only within [context], this session is exited immediately after [context] invocation. */ inline fun <R> ValidationEnvironment.sessionInContext(context: (session: ValidationEnvironment.Session) -> R) = this.enterSession().let(context).also { this.exitSession() } /** * Immediately enters the inspection of [part], calls [context] and then immediately exits the inspection of [part]. */ inline fun <P, R> ValidationEnvironment.inspectionInContext(part: P, context: (part: P) -> R) = this.enterInspectionOf(part as Any).let { context(part).also { this.exitInspectionOf(part) } } /** * Occurs when a unexpected inspection context is found. */ class UnexpectedInspectionContext : IllegalStateException { constructor() : super() constructor(message: String) : super(message) constructor(cause: Throwable) : super(cause) constructor(message: String, cause: Throwable) : super(message, cause) } /** * Validation message with a [context]. * * @property message Validation message * @property context Message context. */ data class ContextedValidationMessage(val message: ValidationMessage, val context: Context) /** * Validation message. * * @property message Message. * @property type Type of the message. */ data class ValidationMessage(val message: String, val type: Type) { enum class Type { /** * Errors in part. */ ERROR, /** * Warnings: things that can be improved, things that may fail, etc... */ WARNING, /** * Performance issues found in the part. */ PERFORMANCE, /** * Information */ INFO, /** * Other type */ OTHER } } /** * Returns true if receiver has any [ValidationMessage] of [type][ValidationMessage.type] [ValidationMessage.Type.ERROR]. */ fun List<ValidationMessage>.hasError() = this.any { it.type == ValidationMessage.Type.ERROR } /** * Returns true if receiver has any [ValidationMessage] of [type][ValidationMessage.type] [ValidationMessage.Type.ERROR]. */ fun List<ContextedValidationMessage>.hasContextedError() = this.any { it.message.type == ValidationMessage.Type.ERROR } /** * Creates a string representation of the [ValidationMessage] */ fun ValidationMessage.toMessage(): String = "ValidationMessage[${this.type.name}]: ${this.message}" /** * Creates a string representation of the [ContextedValidationMessage] */ fun ContextedValidationMessage.toMessage(): String = "ContextedValidationMessage[${this.message.type.name}]: ${this.message.message}. Context: ${this.context}" /** * Prints messages registered in [ValidationEnvironment]. */ fun ValidationEnvironment.printMessages(printer: (String) -> Unit, includeStack: Boolean = false) { this.validationMessages.forEach { (message, context) -> printer(message.toMessage()) printer("Contexts:{") context.printContext(printer, false, true, includeStack) printer("}") } } /** * **Only a void implementation**, this class does nothing, literally. */ object VoidValidatorManager : ValidatorManager { override fun <P> validate( type: Class<out P>, part: P, data: TypedData, environment: ValidationEnvironment? ): ValidationEnvironment { val ext = data return object : ValidationEnvironment { override val data: TypedData get() = ext override fun enterSession(): ValidationEnvironment.Session = ValidationEnvironment.Session(null, this.context.current()) override fun exitSession(): ValidationEnvironment.Session = ValidationEnvironment.Session(null, this.context.current()) override val context: Context = Context.create() override val validationMessages: List<ContextedValidationMessage> = emptyList() override fun enterInspectionOf(@Suppress("NAME_SHADOWING") part: Any) { } override fun exitInspectionOf(@Suppress("NAME_SHADOWING") part: Any) { } override fun addMessage(message: ValidationMessage) { } } } override fun <P> registerValidator(validator: Validator<P>, type: Class<P>) { } } /** * Validator manager backed by an [MutableMap]. */ abstract class AbstractValidatorManager : ValidatorManager { private val map = mutableMapOf<Class<*>, Validator<*>>() override fun <P> registerValidator(validator: Validator<P>, type: Class<P>) { this.map[type] = validator } override fun <P> validate( type: Class<out P>, part: P, data: TypedData, environment: ValidationEnvironment? ): ValidationEnvironment { val env = environment ?: createEnvironment(data) this.getValidatorOf(type, part, data, env) .validate(part, data, this, env) return env } /** * Gets processor of [type]. */ fun <P> getValidatorOf( type: Class<*>, part: P, data: TypedData, environment: ValidationEnvironment ): Validator<P> { val searchType = if (this.map.containsKey(type)) type else if (type.superclass != Any::class.java && type.interfaces.isEmpty()) type.superclass else if (type.interfaces.size == 1) type.interfaces.single() else type @Suppress("UNCHECKED_CAST") return this.map[searchType] as? Validator<P> ?: throw IllegalArgumentException("Cannot find validator of type '$type' (searchType: '$searchType') and part '$part'. Data: {$data}. Environment: {$environment}") } } /** * Creates a error validation message. */ inline fun error(message: () -> String) = ValidationMessage(message(), ValidationMessage.Type.ERROR) /** * Creates a warning validation message. */ inline fun warning(message: () -> String) = ValidationMessage(message(), ValidationMessage.Type.WARNING) /** * Creates a info validation message. */ inline fun info(message: () -> String) = ValidationMessage(message(), ValidationMessage.Type.INFO) /** * Creates a other validation message. */ inline fun other(message: () -> String) = ValidationMessage(message(), ValidationMessage.Type.OTHER) /** * Creates a performance validation message. */ inline fun performance(message: () -> String) = ValidationMessage(message(), ValidationMessage.Type.PERFORMANCE)
mit
21c92c1e378b541982debc7c6041b913
29.642857
179
0.654622
4.536352
false
false
false
false
SirWellington/alchemy-arguments
src/main/java/tech/sirwellington/alchemy/arguments/assertions/CollectionAssertions.kt
1
8838
/* * Copyright © 2019. Sir Wellington. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("CollectionAssertions") package tech.sirwellington.alchemy.arguments.assertions import tech.sirwellington.alchemy.annotations.arguments.NonEmpty import tech.sirwellington.alchemy.annotations.arguments.Optional import tech.sirwellington.alchemy.annotations.arguments.Positive import tech.sirwellington.alchemy.annotations.arguments.Required import tech.sirwellington.alchemy.arguments.AlchemyAssertion import tech.sirwellington.alchemy.arguments.FailedAssertionException import tech.sirwellington.alchemy.arguments.checkNotNull import tech.sirwellington.alchemy.arguments.checkThat import java.util.Arrays /** * Asserts that the collection is not null and not empty. * @param <E> * * * @return </E> */ fun <E> nonEmptyCollection(): AlchemyAssertion<Collection<E>> { return AlchemyAssertion { collection -> notNull<Any>().check(collection) if (collection.isEmpty()) { throw FailedAssertionException("Collection is empty") } } } /** * Asserts that the List is not null and not empty * @param <E> * * * @return </E> */ fun <E> nonEmptyList(): AlchemyAssertion<List<E>> { return AlchemyAssertion { list -> notNull<Any>().check(list) if (list.isEmpty()) { throw FailedAssertionException("List is empty") } } } /** * Asserts that the Set is not null and not empty. * @param <E> * * * @return </E> */ fun <E : Any> nonEmptySet(): AlchemyAssertion<Set<E>> { return AlchemyAssertion { set -> notNull<Any>().check(set) if (set.isEmpty()) { throw FailedAssertionException("Set is empty") } } } /** * Asserts that the Map is not null and not empty * @param <K> * * @param <V> * * * @return </V></K> */ fun <K, V> nonEmptyMap(): AlchemyAssertion<Map<K, V>> { return AlchemyAssertion { map -> notNull<Any>().check(map) if (map.isEmpty()) { throw FailedAssertionException("Map is empty") } } } fun <E> nonEmptyArray(): AlchemyAssertion<Array<E>> { return AlchemyAssertion { array -> notNull<Any>().check(array) if (array.isEmpty()) { throw FailedAssertionException("Array is empty") } } } fun <E> emptyCollection(): AlchemyAssertion<Collection<E>> { return AlchemyAssertion { collection -> notNull<Any>().check(collection) if (!collection.isEmpty()) { throw FailedAssertionException("Expected an empty collection, but it has size [${collection.size}]") } } } fun <E> emptyList(): AlchemyAssertion<List<E>> { return AlchemyAssertion { emptyCollection<E>().check(it) } } fun <E> emptySet(): AlchemyAssertion<Set<E>> { return AlchemyAssertion { set -> emptyCollection<E>().check(set) } } fun <K, V> emptyMap(): AlchemyAssertion<Map<K, V>> { return AlchemyAssertion { if (it.isNotEmpty()) { throw FailedAssertionException("Expected an empty map, but instead [$it]") } } } @Throws(IllegalArgumentException::class) fun <E> listContaining(@Required element: E): AlchemyAssertion<List<E>> { checkNotNull(element, "cannot check for null") return AlchemyAssertion { list -> notNull<Any>().check(list) if (!list.contains(element)) { throw FailedAssertionException("$element not found in List") } } } @Throws(IllegalArgumentException::class) fun <E, C : Collection<E>> collectionContaining(@Required element: E): AlchemyAssertion<C> { checkNotNull(element, "cannot check for null") return AlchemyAssertion { collection -> notNull<Any>().check(collection) if (!collection.contains(element)) { throw FailedAssertionException("$element not found in Collection") } } } /** * Checks that the [Collection] contains ALL of the specified values. * @param <E> * * @param <C> * * @param first * * @param andOther * * @return * * @throws IllegalArgumentException </C></E> */ @Throws(IllegalArgumentException::class) fun <E, C : Collection<E>> collectionContainingAll(@Required first: E, @Optional vararg andOther: E): AlchemyAssertion<C> { checkNotNull(first, "first argument cannot be null") if (andOther.isEmpty()) { return collectionContaining(first) } return AlchemyAssertion { collection -> notNull<Any>().check(collection) collectionContaining(first).check(collection) val arguments = Arrays.asList(*andOther) arguments.filterNot { collection.contains(it) } .forEach { throw FailedAssertionException("Element not found in Collection: $it") } } } /** * Checks whether a collection contains at least one of the specified parameters. * @param <E> * * @param <C> * * @param first * * @param orOthers * * @return * * @throws IllegalArgumentException </C></E> */ @Throws(IllegalArgumentException::class) fun <E, C : Collection<E>> collectionContainingAtLeastOneOf(@Required first: E, @Optional vararg orOthers: E): AlchemyAssertion<C> { checkNotNull(first, "first argument cannot be null") if (orOthers.isEmpty()) { return collectionContaining(first) } return AlchemyAssertion block@ { collection -> if (collection.contains(first)) { return@block } orOthers.forEach { argument -> if (collection.contains(argument)) { return@block } } throw FailedAssertionException("Collection does not contain any of : $first , ${Arrays.toString(orOthers)}") } } @Throws(IllegalArgumentException::class) fun <K, V> mapWithKey(@Required key: K): AlchemyAssertion<Map<K, V>> { checkNotNull(key, "key cannot be null") return AlchemyAssertion { map -> notNull<Any>().check(map) if (!map.containsKey(key)) { throw FailedAssertionException("Expected Key [$key] in Map") } } } @Throws(IllegalArgumentException::class) fun <K, V> mapWithKeyValue(@Required key: K, value: V): AlchemyAssertion<Map<K, V>> { checkNotNull(key, "key cannot be null") return AlchemyAssertion { map -> mapWithKey<K, V>(key).check(map) val valueInMap = map[key] if (value != valueInMap) { throw FailedAssertionException("Value in Map [$valueInMap] does not match expected value $value") } } } @Throws(IllegalArgumentException::class) fun <K, V> keyInMap(@Required map: Map<K, V>): AlchemyAssertion<K> { checkNotNull(map, "map cannot be null") return AlchemyAssertion { key -> notNull<Any>().check(key) if (!map.containsKey(key)) { throw FailedAssertionException("Expected key [$key] to be in map") } } } @Throws(IllegalArgumentException::class) fun <K, V> valueInMap(@Required map: Map<K, V>): AlchemyAssertion<V> { checkNotNull(map, "map cannot be null") return AlchemyAssertion { value -> notNull<Any>().check(value) if (!map.containsValue(value)) { throw FailedAssertionException("Expected value [$value] to be in map") } } } @Throws(IllegalArgumentException::class) fun <E> elementInCollection(@NonEmpty collection: Collection<E>): AlchemyAssertion<E> { checkNotNull(collection, "collection cannot be null") return AlchemyAssertion { element -> notNull<Any>().check(element) if (!collection.contains(element)) { throw FailedAssertionException("Expected element [$element] to be in collection") } } } @Throws(IllegalArgumentException::class) fun <C : Collection<*>> collectionOfSize(@Positive size: Int): AlchemyAssertion<C> { checkThat(size >= 0, "size must be >= 0") return AlchemyAssertion { collection -> nonEmptyCollection<Any?>().check(collection) val actualSize = collection.size if (actualSize != size) { throw FailedAssertionException("Expected collection with size [$size] but is instead [$actualSize]") } } }
apache-2.0
7ef9bb013450b824875fe1dcfbefd630
22.440318
130
0.642299
4.285645
false
false
false
false
zeapo/Android-Password-Store
app/src/main/java/com/zeapo/pwdstore/SelectFolderActivity.kt
1
1956
package com.zeapo.pwdstore import android.app.Activity import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.FragmentManager import com.zeapo.pwdstore.utils.PasswordRepository // TODO more work needed, this is just an extraction from PgpHandler class SelectFolderActivity : AppCompatActivity() { private lateinit var passwordList: SelectFolderFragment override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.select_folder_layout) val fragmentManager = supportFragmentManager val fragmentTransaction = fragmentManager.beginTransaction() passwordList = SelectFolderFragment() val args = Bundle() args.putString("Path", PasswordRepository.getRepositoryDirectory(applicationContext)?.absolutePath) passwordList.arguments = args supportActionBar?.show() fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE) fragmentTransaction.replace(R.id.pgp_handler_linearlayout, passwordList, "PasswordsList") fragmentTransaction.commit() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.pgp_handler_select_folder, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId when (id) { android.R.id.home -> { setResult(Activity.RESULT_CANCELED) finish() return true } R.id.crypto_select -> selectFolder() } return super.onOptionsItemSelected(item) } private fun selectFolder() { intent.putExtra("SELECTED_FOLDER_PATH", passwordList.currentDir?.absolutePath) setResult(Activity.RESULT_OK, intent) finish() } }
gpl-3.0
0d6aae635eb923d83f5004f4158acb32
30.564516
107
0.697853
5.10705
false
false
false
false
vicboma1/GameBoyEmulatorEnvironment
src/main/kotlin/assets/panel/multipleImages/base/PanelMultipleImages.kt
1
2281
package assets.panel.multipleImages.base import main.kotlin.utils.image.createBufferedImage import main.kotlin.utils.image.scale import src.configuration.Display import java.awt.BorderLayout import java.awt.image.BufferedImage import java.util.concurrent.CopyOnWriteArrayList import javax.swing.ImageIcon import javax.swing.JPanel /** * Created by vicboma on 08/01/17. */ open class PanelMultipleImages internal constructor(private val classLoader: ClassLoader, private val back: String, private val front:String) : JPanel() { protected var list: CopyOnWriteArrayList<BufferedImage?> = CopyOnWriteArrayList() init { layout = BorderLayout() val resourceBack = classLoader.getResource(back) val bufferedImageBack = ImageIcon().createBufferedImage(((Display.WIDHT / 3) * 1.25).toInt(), ((Display.HEIGTH / 2) * 1.45).toInt(), BufferedImage.TYPE_INT_ARGB) if(resourceBack != null) list.add(0,ImageIcon().scale(bufferedImageBack, resourceBack.file.toString())) val resourceFront = classLoader.getResource(front) val bufferedImageFront = ImageIcon().createBufferedImage(((Display.WIDHT / 3) * 1.25).toInt(), ((Display.HEIGTH / 2) * 1.45).toInt(), BufferedImage.TYPE_INT_ARGB) if(resourceFront != null) list.add(1,ImageIcon().scale(bufferedImageFront, resourceFront.file.toString())) } fun setBack(back:String) { val resourceSetBack = classLoader.getResource(back) if(resourceSetBack!=null) { val bufferedImageBack = ImageIcon().createBufferedImage(((Display.WIDHT / 3) * 1.25).toInt(), ((Display.HEIGTH / 2) * 1.45).toInt(), BufferedImage.TYPE_INT_ARGB) list.set(0, ImageIcon().scale(bufferedImageBack, resourceSetBack.file.toString())) } } fun setFront(front:String) { var file : String = "" val resourceSetFront = classLoader.getResource(front) if(null != resourceSetFront) file = resourceSetFront.file.toString() val bufferedImageFront = ImageIcon().createBufferedImage(((Display.WIDHT / 3) * 1.25).toInt(), ((Display.HEIGTH / 2) * 1.45).toInt(), BufferedImage.TYPE_INT_ARGB) val buffered = ImageIcon().scale(bufferedImageFront,file) list.set(1,buffered) } }
lgpl-3.0
3ac5ec76b133a0e2bae20bf0f79f1eb1
41.259259
173
0.696624
4.124774
false
false
false
false
androidx/gcp-gradle-build-cache
gcpbuildcache/src/main/kotlin/androidx/build/gradle/gcpbuildcache/GcpStorageService.kt
1
7139
/* * 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.build.gradle.gcpbuildcache import androidx.build.gradle.gcpbuildcache.FileHandleInputStream.Companion.handleInputStream import com.google.api.gax.retrying.RetrySettings import com.google.auth.oauth2.GoogleCredentials import com.google.cloud.http.HttpTransportOptions import com.google.cloud.storage.* import org.gradle.api.GradleException import org.gradle.api.logging.Logging import java.io.InputStream /** * An implementation of the [StorageService] that is backed by Google Cloud Storage. */ internal class GcpStorageService( override val projectId: String, override val bucketName: String, gcpCredentials: GcpCredentials, override val isPush: Boolean, override val isEnabled: Boolean, private val sizeThreshold: Long = BLOB_SIZE_THRESHOLD ) : StorageService { private val storageOptions by lazy { storageOptions(projectId, gcpCredentials, isPush) } override fun load(cacheKey: String): InputStream? { if (!isEnabled) { logger.info("Not Enabled") return null } val blobId = BlobId.of(bucketName, cacheKey) logger.info("Loading $cacheKey from ${blobId.name}") return load(storageOptions, blobId, sizeThreshold) } override fun store(cacheKey: String, contents: ByteArray): Boolean { if (!isEnabled) { logger.info("Not Enabled") return false } if (!isPush) { logger.info("No push support") return false } val blobId = BlobId.of(bucketName, cacheKey) logger.info("Storing $cacheKey into ${blobId.name}") return store(storageOptions, blobId, contents) } override fun delete(cacheKey: String): Boolean { if (!isEnabled) { return false } if (!isPush) { return false } val blobId = BlobId.of(bucketName, cacheKey) return Companion.delete(storageOptions, blobId) } override fun validateConfiguration() { if (storageOptions?.service?.get(bucketName, Storage.BucketGetOption.fields()) == null) { throw Exception(""" Bucket $bucketName under project $projectId cannot be found or it is not accessible using the provided credentials. """.trimIndent() ) } } override fun close() { // Does nothing } companion object { private val logger by lazy { Logging.getLogger("GcpStorageService") } private val transportOptions by lazy { GcpTransportOptions(HttpTransportOptions.newBuilder()) } // The OAuth scopes for reading and writing to buckets. // https://cloud.google.com/storage/docs/authentication private const val STORAGE_READ_ONLY = "https://www.googleapis.com/auth/devstorage.read_only" private const val STORAGE_READ_WRITE = "https://www.googleapis.com/auth/devstorage.read_write" // Need full control for updating metadata private const val STORAGE_FULL_CONTROL = "https://www.googleapis.com/auth/devstorage.full_control" private const val BLOB_SIZE_THRESHOLD = 50 * 1024 * 1024L private fun load(storage: StorageOptions?, blobId: BlobId, sizeThreshold: Long): InputStream? { if (storage == null) return null return try { val blob = storage.service.get(blobId) ?: return null return if (blob.size > sizeThreshold) { val path = FileHandleInputStream.create() blob.downloadTo(path) path.handleInputStream() } else { blob.getContent().inputStream() } } catch (storageException: StorageException) { logger.debug("Unable to load Blob ($blobId)", storageException) null } } private fun store(storage: StorageOptions?, blobId: BlobId, contents: ByteArray): Boolean { if (storage == null) return false val blobInfo = BlobInfo.newBuilder(blobId).build() return try { storage.service.createFrom(blobInfo, contents.inputStream()) true } catch (storageException: StorageException) { logger.debug("Unable to store Blob ($blobId)", storageException) false } } private fun delete(storage: StorageOptions?, blobId: BlobId): Boolean { if (storage == null) return false return storage.service.delete(blobId) } private fun storageOptions( projectId: String, gcpCredentials: GcpCredentials, isPushSupported: Boolean ): StorageOptions? { val credentials = credentials(gcpCredentials, isPushSupported) ?: return null val retrySettings = RetrySettings.newBuilder() retrySettings.maxAttempts = 3 return StorageOptions.newBuilder().setCredentials(credentials) .setStorageRetryStrategy(StorageRetryStrategy.getUniformStorageRetryStrategy()).setProjectId(projectId) .setRetrySettings(retrySettings.build()) .setTransportOptions(transportOptions) .build() } private fun credentials( gcpCredentials: GcpCredentials, isPushSupported: Boolean ): GoogleCredentials? { val scopes = mutableListOf( STORAGE_READ_ONLY, ) if (isPushSupported) { scopes += listOf(STORAGE_READ_WRITE, STORAGE_FULL_CONTROL) } return when (gcpCredentials) { is ApplicationDefaultGcpCredentials -> { GoogleCredentials.getApplicationDefault().createScoped(scopes) } is ExportedKeyGcpCredentials -> { val contents = gcpCredentials.credentials.invoke() if (contents.isBlank()) throw GradleException("Credentials are empty.") // Use the underlying transport factory to ensure logging is disabled. GoogleCredentials.fromStream( contents.byteInputStream(charset = Charsets.UTF_8), transportOptions.httpTransportFactory ).createScoped(scopes) } } } } }
apache-2.0
f82f9b9f80d165a858136f826c81937c
36.376963
119
0.617594
5.041667
false
false
false
false
google/intellij-community
plugins/kotlin/gradle/gradle/src/org/jetbrains/kotlin/idea/gradle/configuration/xcode/XcodeProjectConfigurator.kt
2
32606
// 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.gradle.configuration.xcode import com.intellij.openapi.vfs.VirtualFile import java.io.BufferedWriter class XcodeProjectConfigurator { private fun VirtualFile.bufferedWriter() = getOutputStream(this).bufferedWriter() private val mppDirName = "app" fun templatePlist(varyingProperties: String = ""): String { return """<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>${'$'}(DEVELOPMENT_LANGUAGE)</string> <key>CFBundleExecutable</key> <string>${'$'}(EXECUTABLE_NAME)</string> <key>CFBundleIdentifier</key> <string>${'$'}(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>${'$'}(PRODUCT_NAME)</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleVersion</key> <string>1</string> ${varyingProperties.trimIndent().prependIndent("\t")} </dict> </plist>""" } fun createSkeleton(rootDir: VirtualFile) { val iosDir = rootDir.createChildDirectory(this, "iosApp") val sourceDir = iosDir.createChildDirectory(this, "iosApp") val storyboardDir = sourceDir.createChildDirectory(this, "Base.lproj") val testDir = iosDir.createChildDirectory(this, "iosAppTests") val projectDir = iosDir.createChildDirectory(this, "iosApp.xcodeproj") val tests = testDir.createChildData(this, "iosAppTests.swift").bufferedWriter() val testInfo = testDir.createChildData(this, "Info.plist").bufferedWriter() val appDelegate = sourceDir.createChildData(this, "AppDelegate.swift").bufferedWriter() val viewController = sourceDir.createChildData(this, "ViewController.swift").bufferedWriter() val sourceInfo = sourceDir.createChildData(this, "Info.plist").bufferedWriter() val launchScreen = storyboardDir.createChildData(this, "LaunchScreen.storyboard").bufferedWriter() val mainScreen = storyboardDir.createChildData(this, "Main.storyboard").bufferedWriter() val project = projectDir.createChildData(this, "project.pbxproj").bufferedWriter() try { tests.write( """ import XCTest import $mppDirName class iosAppTests: XCTestCase { func testExample() { assert(Sample().checkMe() == 7) } } """.trimIndent() ) appDelegate.write( """ import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { return true } func applicationWillResignActive(_ application: UIApplication) {} func applicationDidEnterBackground(_ application: UIApplication) {} func applicationWillEnterForeground(_ application: UIApplication) {} func applicationDidBecomeActive(_ application: UIApplication) {} func applicationWillTerminate(_ application: UIApplication) {} } """.trimIndent() ) viewController.write( """ import UIKit import $mppDirName class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() label.text = Proxy().proxyHello() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBOutlet weak var label: UILabel! } """.trimIndent() ) testInfo.write( templatePlist( """<key>CFBundlePackageType</key> <string>BNDL</string>""" ) ) sourceInfo.write( templatePlist( """<key>CFBundlePackageType</key> <string>APPL</string> <key>LSRequiresIPhoneOS</key> <true/> <key>UILaunchStoryboardName</key> <string>LaunchScreen</string> <key>UIMainStoryboardFile</key> <string>Main</string> <key>UIRequiredDeviceCapabilities</key> <array> <string>armv7</string> </array> <key>UISupportedInterfaceOrientations</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> <key>UISupportedInterfaceOrientations~ipad</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationPortraitUpsideDown</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array>""" ) ) launchScreen.write( """ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" systemVersion="17A277" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM"> <dependencies> <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/> <capability name="Safe area layout guides" minToolsVersion="9.0"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <scenes> <!--View Controller--> <scene sceneID="EHf-IW-A2E"> <objects> <viewController id="01J-lp-oVM" sceneMemberID="viewController"> <view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3"> <rect key="frame" x="0.0" y="0.0" width="375" height="667"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/> </view> </viewController> <placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="53" y="375"/> </scene> </scenes> </document> """.trimIndent() ) mainScreen.write( """ <?xml version="1.0" encoding="UTF-8"?> <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14113" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BYZ-38-t0r"> <device id="retina4_7" orientation="portrait"> <adaptation id="fullscreen"/> </device> <dependencies> <deployment identifier="iOS"/> <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14088"/> <capability name="Safe area layout guides" minToolsVersion="9.0"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <scenes> <!--View Controller--> <scene sceneID="tne-QT-ifu"> <objects> <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="iosApp" customModuleProvider="target" sceneMemberID="viewController"> <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC"> <rect key="frame" x="0.0" y="0.0" width="375" height="667"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="Label" textAlignment="natural" lineBreakMode="wordWrap" numberOfLines="3" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Cak-wb-syn"> <rect key="frame" x="113" y="120" width="216" height="193"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/> <fontDescription key="fontDescription" type="system" pointSize="17"/> <nil key="textColor"/> <nil key="highlightedColor"/> </label> </subviews> <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/> </view> <connections> <outlet property="label" destination="Cak-wb-syn" id="pzW-Xf-pbM"/> </connections> </viewController> <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="117.59999999999999" y="118.29085457271366"/> </scene> </scenes> </document> """.trimIndent() ) project.fillProject() } finally { listOf( tests, testInfo, appDelegate, viewController, sourceInfo, launchScreen, mainScreen, project ).forEach(BufferedWriter::close) } } private fun BufferedWriter.fillProject() { write( """ // !${'$'}*UTF8*${'$'}! { archiveVersion = 1; classes = { }; objectVersion = 50; objects = { /* Begin PBXBuildFile section */ F861D7E1207FA40F0085E80D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = F861D7E0207FA40F0085E80D /* AppDelegate.swift */; }; F861D7E3207FA40F0085E80D /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = F861D7E2207FA40F0085E80D /* ViewController.swift */; }; F861D7E6207FA40F0085E80D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = F861D7E4207FA40F0085E80D /* Main.storyboard */; }; F861D7EB207FA4100085E80D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = F861D7E9207FA4100085E80D /* LaunchScreen.storyboard */; }; F861D7F6207FA4100085E80D /* iosAppTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F861D7F5207FA4100085E80D /* iosAppTests.swift */; }; F861D80C207FA4200085E80D /* $mppDirName.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F861D805207FA4200085E80D /* $mppDirName.framework */; }; F861D80D207FA4200085E80D /* $mppDirName.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = F861D805207FA4200085E80D /* $mppDirName.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ F861D7F2207FA4100085E80D /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = F861D7D5207FA40F0085E80D /* Project object */; proxyType = 1; remoteGlobalIDString = F861D7DC207FA40F0085E80D; remoteInfo = iosApp; }; F861D80A207FA4200085E80D /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = F861D7D5207FA40F0085E80D /* Project object */; proxyType = 1; remoteGlobalIDString = F861D804207FA4200085E80D; remoteInfo = $mppDirName; }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ F861D811207FA4200085E80D /* Embed Frameworks */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = ""; dstSubfolderSpec = 10; files = ( F861D80D207FA4200085E80D /* $mppDirName.framework in Embed Frameworks */, ); name = "Embed Frameworks"; runOnlyForDeploymentPostprocessing = 0; }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ F861D7DD207FA40F0085E80D /* iosApp.$mppDirName */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = iosApp.$mppDirName; sourceTree = BUILT_PRODUCTS_DIR; }; F861D7E0207FA40F0085E80D /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; }; F861D7E2207FA40F0085E80D /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = "<group>"; }; F861D7E5207FA40F0085E80D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; }; F861D7EA207FA4100085E80D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; }; F861D7EC207FA4100085E80D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; }; F861D7F1207FA4100085E80D /* iosAppTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = iosAppTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; F861D7F5207FA4100085E80D /* iosAppTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = iosAppTests.swift; sourceTree = "<group>"; }; F861D7F7207FA4100085E80D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; }; F861D805207FA4200085E80D /* $mppDirName.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = $mppDirName.framework; sourceTree = BUILT_PRODUCTS_DIR; }; F861D813207FA4520085E80D /* $mppDirName */ = {isa = PBXFileReference; lastKnownFileType = folder; name = $mppDirName; path = ../$mppDirName; sourceTree = "<group>"; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ F861D7DA207FA40F0085E80D /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( F861D80C207FA4200085E80D /* $mppDirName.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; F861D7EE207FA4100085E80D /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ F861D7D4207FA40F0085E80D = { isa = PBXGroup; children = ( F861D813207FA4520085E80D /* $mppDirName */, F861D7DF207FA40F0085E80D /* iosApp */, F861D7F4207FA4100085E80D /* iosAppTests */, F861D7DE207FA40F0085E80D /* Products */, ); sourceTree = "<group>"; }; F861D7DE207FA40F0085E80D /* Products */ = { isa = PBXGroup; children = ( F861D7DD207FA40F0085E80D /* iosApp.$mppDirName */, F861D7F1207FA4100085E80D /* iosAppTests.xctest */, F861D805207FA4200085E80D /* $mppDirName.framework */, ); name = Products; sourceTree = "<group>"; }; F861D7DF207FA40F0085E80D /* iosApp */ = { isa = PBXGroup; children = ( F861D7E0207FA40F0085E80D /* AppDelegate.swift */, F861D7E2207FA40F0085E80D /* ViewController.swift */, F861D7E4207FA40F0085E80D /* Main.storyboard */, F861D7E9207FA4100085E80D /* LaunchScreen.storyboard */, F861D7EC207FA4100085E80D /* Info.plist */, ); path = iosApp; sourceTree = "<group>"; }; F861D7F4207FA4100085E80D /* iosAppTests */ = { isa = PBXGroup; children = ( F861D7F5207FA4100085E80D /* iosAppTests.swift */, F861D7F7207FA4100085E80D /* Info.plist */, ); path = iosAppTests; sourceTree = "<group>"; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ F861D7DC207FA40F0085E80D /* iosApp */ = { isa = PBXNativeTarget; buildConfigurationList = F861D7FA207FA4100085E80D /* Build configuration list for PBXNativeTarget "iosApp" */; buildPhases = ( F861D7D9207FA40F0085E80D /* Sources */, F861D7DA207FA40F0085E80D /* Frameworks */, F861D7DB207FA40F0085E80D /* Resources */, F861D811207FA4200085E80D /* Embed Frameworks */, ); buildRules = ( ); dependencies = ( F861D80B207FA4200085E80D /* PBXTargetDependency */, ); name = iosApp; productName = iosApp; productReference = F861D7DD207FA40F0085E80D /* iosApp.$mppDirName */; productType = "com.apple.product-type.application"; }; F861D7F0207FA4100085E80D /* iosAppTests */ = { isa = PBXNativeTarget; buildConfigurationList = F861D7FD207FA4100085E80D /* Build configuration list for PBXNativeTarget "iosAppTests" */; buildPhases = ( F861D7ED207FA4100085E80D /* Sources */, F861D7EE207FA4100085E80D /* Frameworks */, F861D7EF207FA4100085E80D /* Resources */, ); buildRules = ( ); dependencies = ( F861D7F3207FA4100085E80D /* PBXTargetDependency */, ); name = iosAppTests; productName = iosAppTests; productReference = F861D7F1207FA4100085E80D /* iosAppTests.xctest */; productType = "com.apple.product-type.bundle.unit-test"; }; F861D804207FA4200085E80D /* $mppDirName */ = { isa = PBXNativeTarget; buildConfigurationList = F861D80E207FA4200085E80D /* Build configuration list for PBXNativeTarget "$mppDirName" */; buildPhases = ( F861D812207FA4320085E80D /* ShellScript */, ); buildRules = ( ); dependencies = ( ); name = $mppDirName; productName = $mppDirName; productReference = F861D805207FA4200085E80D /* $mppDirName.framework */; productType = "com.apple.product-type.framework"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ F861D7D5207FA40F0085E80D /* Project object */ = { isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0930; LastUpgradeCheck = 0930; TargetAttributes = { F861D7DC207FA40F0085E80D = { CreatedOnToolsVersion = 9.3; }; F861D7F0207FA4100085E80D = { CreatedOnToolsVersion = 9.3; TestTargetID = F861D7DC207FA40F0085E80D; }; F861D804207FA4200085E80D = { CreatedOnToolsVersion = 9.3; }; }; }; buildConfigurationList = F861D7D8207FA40F0085E80D /* Build configuration list for PBXProject "iosApp" */; compatibilityVersion = "Xcode 9.3"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = F861D7D4207FA40F0085E80D; productRefGroup = F861D7DE207FA40F0085E80D /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( F861D7DC207FA40F0085E80D /* iosApp */, F861D7F0207FA4100085E80D /* iosAppTests */, F861D804207FA4200085E80D /* $mppDirName */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ F861D7DB207FA40F0085E80D /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( F861D7EB207FA4100085E80D /* LaunchScreen.storyboard in Resources */, F861D7E6207FA40F0085E80D /* Main.storyboard in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; F861D7EF207FA4100085E80D /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ F861D812207FA4320085E80D /* ShellScript */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${"$"}SRCROOT/../gradlew\" -p \"${"$"}SRCROOT/../$mppDirName\" copyFramework \\\n-Pconfiguration.build.dir=\"${"$"}CONFIGURATION_BUILD_DIR\" \\\n-Pkotlin.build.type=\"${"$"}KOTLIN_BUILD_TYPE\" \\\n-Pkotlin.target=\"${"$"}KOTLIN_TARGET\""; }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ F861D7D9207FA40F0085E80D /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( F861D7E3207FA40F0085E80D /* ViewController.swift in Sources */, F861D7E1207FA40F0085E80D /* AppDelegate.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; F861D7ED207FA4100085E80D /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( F861D7F6207FA4100085E80D /* iosAppTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ F861D7F3207FA4100085E80D /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = F861D7DC207FA40F0085E80D /* iosApp */; targetProxy = F861D7F2207FA4100085E80D /* PBXContainerItemProxy */; }; F861D80B207FA4200085E80D /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = F861D804207FA4200085E80D /* $mppDirName */; targetProxy = F861D80A207FA4200085E80D /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ /* Begin PBXVariantGroup section */ F861D7E4207FA40F0085E80D /* Main.storyboard */ = { isa = PBXVariantGroup; children = ( F861D7E5207FA40F0085E80D /* Base */, ); name = Main.storyboard; sourceTree = "<group>"; }; F861D7E9207FA4100085E80D /* LaunchScreen.storyboard */ = { isa = PBXVariantGroup; children = ( F861D7EA207FA4100085E80D /* Base */, ); name = LaunchScreen.storyboard; sourceTree = "<group>"; }; /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ F861D7F8207FA4100085E80D /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_ENABLE_OBJC_WEAK = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CODE_SIGN_IDENTITY = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_BITCODE = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "${'$'}(inherited)", ); GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 11.3; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; OTHER_LDFLAGS = "-v"; SDKROOT = iphoneos; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; }; name = Debug; }; F861D7F9207FA4100085E80D /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_ENABLE_OBJC_WEAK = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CODE_SIGN_IDENTITY = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_BITCODE = NO; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 11.3; MTL_ENABLE_DEBUG_INFO = NO; OTHER_LDFLAGS = "-v"; SDKROOT = iphoneos; SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-O"; VALIDATE_PRODUCT = YES; }; name = Release; }; F861D7FB207FA4100085E80D /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_STYLE = Automatic; ENABLE_BITCODE = NO; INFOPLIST_FILE = iosApp/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "${'$'}(inherited)", "@executable_path/Frameworks", ); OTHER_LDFLAGS = "-v"; PRODUCT_BUNDLE_IDENTIFIER = com.example.iosApp; PRODUCT_NAME = "${'$'}(TARGET_NAME)"; SWIFT_VERSION = 4.0; TARGETED_DEVICE_FAMILY = "1,2"; VALID_ARCHS = "arm64 armv7"; }; name = Debug; }; F861D7FC207FA4100085E80D /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_STYLE = Automatic; ENABLE_BITCODE = NO; INFOPLIST_FILE = iosApp/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "${'$'}(inherited)", "@executable_path/Frameworks", ); OTHER_LDFLAGS = "-v"; PRODUCT_BUNDLE_IDENTIFIER = com.example.iosApp; PRODUCT_NAME = "${'$'}(TARGET_NAME)"; SWIFT_VERSION = 4.0; TARGETED_DEVICE_FAMILY = "1,2"; VALID_ARCHS = "arm64 armv7"; }; name = Release; }; F861D7FE207FA4100085E80D /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; BUNDLE_LOADER = "${'$'}(TEST_HOST)"; CODE_SIGN_STYLE = Automatic; INFOPLIST_FILE = iosAppTests/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "${'$'}(inherited)", "@executable_path/Frameworks", "@loader_path/Frameworks", ); PRODUCT_BUNDLE_IDENTIFIER = com.example.iosAppTests; PRODUCT_NAME = "${'$'}(TARGET_NAME)"; SWIFT_VERSION = 4.0; TARGETED_DEVICE_FAMILY = "1,2"; TEST_HOST = "${'$'}(BUILT_PRODUCTS_DIR)/iosApp.$mppDirName/iosApp"; }; name = Debug; }; F861D7FF207FA4100085E80D /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; BUNDLE_LOADER = "${'$'}(TEST_HOST)"; CODE_SIGN_STYLE = Automatic; INFOPLIST_FILE = iosAppTests/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "${'$'}(inherited)", "@executable_path/Frameworks", "@loader_path/Frameworks", ); PRODUCT_BUNDLE_IDENTIFIER = com.example.iosAppTests; PRODUCT_NAME = "${'$'}(TARGET_NAME)"; SWIFT_VERSION = 4.0; TARGETED_DEVICE_FAMILY = "1,2"; TEST_HOST = "${'$'}(BUILT_PRODUCTS_DIR)/iosApp.$mppDirName/iosApp"; }; name = Release; }; F861D80F207FA4200085E80D /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_IDENTITY = ""; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_BITCODE = NO; INFOPLIST_FILE = "${'$'}(SRCROOT)/../$mppDirName/Info.plist"; INSTALL_PATH = "${'$'}(LOCAL_LIBRARY_DIR)/Frameworks"; KOTLIN_BUILD_TYPE = DEBUG; KOTLIN_TARGET = ""; "KOTLIN_TARGET[sdk=iphoneos*]" = ios; "KOTLIN_TARGET[sdk=iphonesimulator*]" = ios; LD_RUNPATH_SEARCH_PATHS = ( "${'$'}(inherited)", "@executable_path/Frameworks", "@loader_path/Frameworks", ); PRODUCT_BUNDLE_IDENTIFIER = com.example.$mppDirName; PRODUCT_NAME = "${'$'}(TARGET_NAME:c99extidentifier)"; SKIP_INSTALL = YES; SWIFT_VERSION = 4.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; F861D810207FA4200085E80D /* Release */ = { isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_IDENTITY = ""; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_BITCODE = NO; INFOPLIST_FILE = "${'$'}(SRCROOT)/../$mppDirName/Info.plist"; INSTALL_PATH = "${'$'}(LOCAL_LIBRARY_DIR)/Frameworks"; KOTLIN_BUILD_TYPE = RELEASE; KOTLIN_TARGET = ""; "KOTLIN_TARGET[sdk=iphoneos*]" = ios; "KOTLIN_TARGET[sdk=iphonesimulator*]" = ios; LD_RUNPATH_SEARCH_PATHS = ( "${'$'}(inherited)", "@executable_path/Frameworks", "@loader_path/Frameworks", ); PRODUCT_BUNDLE_IDENTIFIER = com.example.$mppDirName; PRODUCT_NAME = "${'$'}(TARGET_NAME:c99extidentifier)"; SKIP_INSTALL = YES; SWIFT_VERSION = 4.0; TARGETED_DEVICE_FAMILY = 1; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ F861D7D8207FA40F0085E80D /* Build configuration list for PBXProject "iosApp" */ = { isa = XCConfigurationList; buildConfigurations = ( F861D7F8207FA4100085E80D /* Debug */, F861D7F9207FA4100085E80D /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; F861D7FA207FA4100085E80D /* Build configuration list for PBXNativeTarget "iosApp" */ = { isa = XCConfigurationList; buildConfigurations = ( F861D7FB207FA4100085E80D /* Debug */, F861D7FC207FA4100085E80D /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; F861D7FD207FA4100085E80D /* Build configuration list for PBXNativeTarget "iosAppTests" */ = { isa = XCConfigurationList; buildConfigurations = ( F861D7FE207FA4100085E80D /* Debug */, F861D7FF207FA4100085E80D /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; F861D80E207FA4200085E80D /* Build configuration list for PBXNativeTarget "$mppDirName" */ = { isa = XCConfigurationList; buildConfigurations = ( F861D80F207FA4200085E80D /* Debug */, F861D810207FA4200085E80D /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = F861D7D5207FA40F0085E80D /* Project object */; } """.trimIndent() ) } }
apache-2.0
de2afd7903547384a3a1f01778d1dd47
37.497048
378
0.667699
3.2264
false
true
false
false
RuneSuite/client
updater-deob/src/main/java/org/runestar/client/updater/deob/rs/StaticDuplicateMethodFinder.kt
1
2299
package org.runestar.client.updater.deob.rs import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.google.common.collect.Multimap import com.google.common.collect.TreeMultimap import org.kxtra.slf4j.getLogger import org.objectweb.asm.Type import org.objectweb.asm.tree.ClassNode import org.objectweb.asm.tree.FieldInsnNode import org.objectweb.asm.tree.InsnList import org.objectweb.asm.tree.InsnNode import org.objectweb.asm.tree.LineNumberNode import org.objectweb.asm.tree.MethodInsnNode import org.objectweb.asm.tree.MethodNode import org.runestar.client.updater.deob.Transformer import java.lang.reflect.Modifier import java.nio.file.Path object StaticDuplicateMethodFinder : Transformer.Tree() { private val mapper = jacksonObjectMapper().enable(SerializationFeature.INDENT_OUTPUT) private val logger = getLogger() override fun transform(dir: Path, klasses: List<ClassNode>) { val map: Multimap<String, String> = TreeMultimap.create() klasses.forEach { c -> c.methods.filter { Modifier.isStatic(it.access) && it.name != "<clinit>" }.forEach { m -> map.put(m.id(), c.name + "." + m.name + m.desc) } } map.asMap().entries.removeIf { it.value.size == 1 } mapper.writeValue(dir.resolve("static-methods-dup.json").toFile(), map.asMap().values.sortedBy { it.first() }) } private fun MethodNode.id(): String { return "${Type.getReturnType(desc)}." + (instructions.lineNumberRange() ?: "*") + "." + instructions.hash() } private fun InsnList.lineNumberRange(): IntRange? { val lns = iterator().asSequence().mapNotNull { it as? LineNumberNode }.mapNotNull { it.line }.toList() if (lns.isEmpty()) return null return lns.first()..lns.last() } // todo private fun InsnList.hash(): Int { return iterator().asSequence().mapNotNull { when (it) { is FieldInsnNode -> it.owner + "." + it.name + ":" + it.opcode is MethodInsnNode -> it.opcode.toString() + ":" + it.owner + "." + it.name is InsnNode -> it.opcode.toString() else -> null } }.toSet().hashCode() } }
mit
bd280cfa785575078d7e4ae9ed41c578
37.333333
118
0.662897
4.033333
false
false
false
false
nohe427/developer-support
runtime-android/kotlin-extensions/graphic-extensions/GraphicExt.kt
1
993
/** * A function that animates the movement of a marker graphic to provide a * nice transition of a marker to a new location. */ fun Graphic.animatePointGraphic(handler: Handler, destination: Point) { handler.removeCallbacksAndMessages(null) val start = SystemClock.uptimeMillis() val duration: Long = 1000 val graphic = this val interpolator = LinearInterpolator() handler.post(object : Runnable { override fun run() { val elapsed = SystemClock.uptimeMillis() - start val t = interpolator.getInterpolation(elapsed.toFloat() / duration) val lng = t * destination.x + (1 - t) * (graphic.geometry as Point).x val lat = t * destination.y + (1 - t) * (graphic.geometry as Point).y graphic.geometry = Point(lng, lat, graphic.geometry.spatialReference) if (t < 1.0) { // Post again 16ms later. handler.postDelayed(this, 16) } } }) }
apache-2.0
6291b849ae349258f4a9445f18097e3c
32.1
81
0.615307
4.452915
false
false
false
false
allotria/intellij-community
plugins/settings-repository/src/IcsSettings.kt
1
2965
// 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.settingsRepository import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.core.util.DefaultPrettyPrinter import com.fasterxml.jackson.databind.ObjectMapper import com.intellij.util.PathUtilRt import com.intellij.util.SmartList import com.intellij.util.Time import com.intellij.util.io.delete import com.intellij.util.io.exists import com.intellij.util.io.sanitizeFileName import com.intellij.util.io.write import java.nio.file.Path private const val DEFAULT_COMMIT_DELAY = 10 * Time.MINUTE class MyPrettyPrinter : DefaultPrettyPrinter() { init { _arrayIndenter = NopIndenter.instance } override fun createInstance() = MyPrettyPrinter() override fun writeObjectFieldValueSeparator(jg: JsonGenerator) { jg.writeRaw(": ") } override fun writeEndObject(jg: JsonGenerator, nrOfEntries: Int) { if (!_objectIndenter.isInline) { --_nesting } if (nrOfEntries > 0) { _objectIndenter.writeIndentation(jg, _nesting) } jg.writeRaw('}') } override fun writeEndArray(jg: JsonGenerator, nrOfValues: Int) { if (!_arrayIndenter.isInline) { --_nesting } jg.writeRaw(']') } } fun saveSettings(settings: IcsSettings, settingsFile: Path) { val serialized = ObjectMapper().writer(MyPrettyPrinter()).writeValueAsBytes(settings) if (serialized.size <= 2) { settingsFile.delete() } else { settingsFile.write(serialized) } } fun loadSettings(settingsFile: Path): IcsSettings { if (!settingsFile.exists()) { return IcsSettings() } val settings = ObjectMapper().readValue(settingsFile.toFile(), IcsSettings::class.java) if (settings.commitDelay <= 0) { settings.commitDelay = DEFAULT_COMMIT_DELAY } return settings } @JsonInclude(value = JsonInclude.Include.NON_DEFAULT) @JsonIgnoreProperties(ignoreUnknown = true) class IcsSettings { var commitDelay = DEFAULT_COMMIT_DELAY var readOnlySources: List<ReadonlySource> = SmartList() var autoSync = true var includeHostIntoCommitMessage = true } @JsonInclude(value = JsonInclude.Include.NON_DEFAULT) @JsonIgnoreProperties(ignoreUnknown = true) class ReadonlySource(var url: String? = null, var active: Boolean = true) { val path: String? @JsonIgnore get() { var fileName = PathUtilRt.getFileName(url ?: return null) val suffix = ".git" if (fileName.endsWith(suffix)) { fileName = fileName.substring(0, fileName.length - suffix.length) } // the convention is that the .git extension should be used for bare repositories return "${sanitizeFileName(fileName)}.${Integer.toHexString(url!!.hashCode())}.git" } }
apache-2.0
cbe32403e0b939e4ac64fc7ec8f4af3a
29.895833
140
0.736931
4.181946
false
false
false
false
Homes-MinecraftServerMod/Homes
src/main/kotlin/com/masahirosaito/spigot/homes/Homes.kt
1
2441
package com.masahirosaito.spigot.homes import com.masahirosaito.spigot.homes.commands.maincommands.homecommands.HomeCommand import com.masahirosaito.spigot.homes.datas.FeeData import com.masahirosaito.spigot.homes.listeners.* import com.masahirosaito.spigot.homes.strings.ErrorStrings.NO_ECONOMY import com.masahirosaito.spigot.homes.strings.ErrorStrings.NO_VAULT import com.masahirosaito.spigot.homes.strings.Strings import net.milkbowl.vault.economy.Economy import org.bukkit.plugin.PluginDescriptionFile import org.bukkit.plugin.java.JavaPlugin import org.bukkit.plugin.java.JavaPluginLoader import java.io.File class Homes : JavaPlugin { companion object { lateinit var homes: Homes } val fee: FeeData = loadFeeData() var econ: Economy? = null constructor() : super() constructor( loader: JavaPluginLoader, description: PluginDescriptionFile, dataFolder: File, file: File ) : super(loader, description, dataFolder, file) override fun onLoad() { super.onLoad() homes = this Configs.load() Strings.load() } override fun onEnable() { NMSManager.load() PlayerDataManager.load() UpdateChecker.checkUpdate() registerCommands() registerListeners() econ = loadEconomy() } override fun onDisable() { PlayerDataManager.save() } fun reload() { onDisable() onLoad() onEnable() } private fun loadFeeData() : FeeData { return loadData(File(dataFolder, "fee.json").load(), FeeData::class.java) } private fun loadEconomy(): Economy? { if (server.pluginManager.getPlugin("Vault") == null) { Messenger.log(NO_VAULT()) return null } server.servicesManager.getRegistration(Economy::class.java).let { if (it == null) { Messenger.log(NO_ECONOMY()) return null } return it.provider } } private fun registerCommands() { getCommand("home").executor = HomeCommand() } private fun registerListeners() { PlayerRespawnListener(this).register() PlayerJoinListener(this).register() ChunkLoadListener(this).register() ChunkUnLoadListener(this).register() PlayerMoveListener(this).register() EntityDamageListener(this).register() } }
apache-2.0
32298ce6e67bb9791d6c7925b19e3b18
28.059524
84
0.650963
4.446266
false
false
false
false
allotria/intellij-community
platform/util/concurrency/org/jetbrains/concurrency/promise.kt
3
12093
// 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. @file:JvmMultifileClass @file:JvmName("Promises") package org.jetbrains.concurrency import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.ActionCallback import com.intellij.util.Function import com.intellij.util.ThreeState import com.intellij.util.concurrency.AppExecutorUtil import java.util.* import java.util.concurrent.CancellationException import java.util.concurrent.Future import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger import java.util.function.Consumer private val obsoleteError: RuntimeException by lazy { MessageError("Obsolete", false) } val Promise<*>.isRejected: Boolean get() = state == Promise.State.REJECTED val Promise<*>.isPending: Boolean get() = state == Promise.State.PENDING private val REJECTED: Promise<*> by lazy { DonePromise<Any?>(PromiseValue.createRejected(createError("rejected"))) } @Suppress("RemoveExplicitTypeArguments") private val fulfilledPromise: CancellablePromise<Any?> by lazy { DonePromise<Any?>(PromiseValue.createFulfilled(null)) } @Suppress("UNCHECKED_CAST") fun <T> resolvedPromise(): Promise<T> = fulfilledPromise as Promise<T> fun nullPromise(): Promise<*> = fulfilledPromise /** * Creates a promise that is resolved with the given value. */ fun <T> resolvedPromise(result: T): Promise<T> = resolvedCancellablePromise(result) /** * Create a promise that is resolved with the given value. */ fun <T> resolvedCancellablePromise(result: T): CancellablePromise<T> { @Suppress("UNCHECKED_CAST") return when (result) { null -> fulfilledPromise as CancellablePromise<T> else -> DonePromise(PromiseValue.createFulfilled(result)) } } @Suppress("UNCHECKED_CAST") /** * Consider to pass error. */ fun <T> rejectedPromise(): Promise<T> = REJECTED as Promise<T> fun <T> rejectedPromise(error: String): Promise<T> = rejectedCancellablePromise(error) fun <T> rejectedPromise(error: Throwable?): Promise<T> { @Suppress("UNCHECKED_CAST") return when (error) { null -> REJECTED as Promise<T> else -> DonePromise(PromiseValue.createRejected(error)) } } fun <T> rejectedCancellablePromise(error: String): CancellablePromise<T> = DonePromise(PromiseValue.createRejected(createError(error, true))) @Suppress("RemoveExplicitTypeArguments") private val CANCELLED_PROMISE: Promise<Any?> by lazy { DonePromise(PromiseValue.createRejected<Any?>(obsoleteError)) } @Suppress("UNCHECKED_CAST") fun <T> cancelledPromise(): Promise<T> = CANCELLED_PROMISE as Promise<T> // only internal usage interface ObsolescentFunction<Param, Result> : Function<Param, Result>, Obsolescent abstract class ValueNodeAsyncFunction<PARAM, RESULT>(private val node: Obsolescent) : Function<PARAM, Promise<RESULT>>, Obsolescent { override fun isObsolete(): Boolean = node.isObsolete } abstract class ObsolescentConsumer<T>(private val obsolescent: Obsolescent) : Obsolescent, Consumer<T> { override fun isObsolete(): Boolean = obsolescent.isObsolete } inline fun <T, SUB_RESULT> Promise<T>.then(obsolescent: Obsolescent, crossinline handler: (T) -> SUB_RESULT): Promise<SUB_RESULT> = then(object : ObsolescentFunction<T, SUB_RESULT> { override fun `fun`(param: T) = handler(param) override fun isObsolete() = obsolescent.isObsolete }) inline fun <T> Promise<T>.onSuccess(node: Obsolescent, crossinline handler: (T) -> Unit): Promise<T> = onSuccess(object : ObsolescentConsumer<T>(node) { override fun accept(param: T) = handler(param) }) inline fun Promise<*>.processed(node: Obsolescent, crossinline handler: () -> Unit): Promise<Any?>? { @Suppress("UNCHECKED_CAST") return (this as Promise<Any?>) .onProcessed(object : ObsolescentConsumer<Any?>(node) { override fun accept(param: Any?) = handler() }) } @Suppress("UNCHECKED_CAST") inline fun <T> Promise<*>.thenRun(crossinline handler: () -> T): Promise<T> = (this as Promise<Any?>).then { handler() } @Suppress("UNCHECKED_CAST") inline fun Promise<*>.processedRun(crossinline handler: () -> Unit): Promise<*> { return (this as Promise<Any?>).onProcessed { handler() } } inline fun <T, SUB_RESULT> Promise<T>.thenAsync(node: Obsolescent, crossinline handler: (T) -> Promise<SUB_RESULT>): Promise<SUB_RESULT> = thenAsync(object : ValueNodeAsyncFunction<T, SUB_RESULT>(node) { override fun `fun`(param: T) = handler(param) }) @Suppress("UNCHECKED_CAST") inline fun <T> Promise<T>.thenAsyncAccept(node: Obsolescent, crossinline handler: (T) -> Promise<*>): Promise<Any?> { return thenAsync(object : ValueNodeAsyncFunction<T, Any?>(node) { override fun `fun`(param: T) = handler(param) as Promise<Any?> }) } inline fun <T> Promise<T>.thenAsyncAccept(crossinline handler: (T) -> Promise<*>): Promise<Any?> = thenAsync(Function { param -> @Suppress("UNCHECKED_CAST") (return@Function handler(param) as Promise<Any?>) }) inline fun Promise<*>.onError(node: Obsolescent, crossinline handler: (Throwable) -> Unit): Promise<out Any> = onError(object : ObsolescentConsumer<Throwable>(node) { override fun accept(param: Throwable) = handler(param) }) /** * Merge results into one list. Results are ordered as in the promises list. * * `T` here is a not nullable type, if you use this method from Java, take care that all promises are not resolved to `null`. * * If `ignoreErrors = false`, list of the same size is returned. * If `ignoreErrors = true`, list of different size is returned if some promise failed with error. */ @JvmOverloads fun <T : Any> Collection<Promise<T>>.collectResults(ignoreErrors: Boolean = false): Promise<List<T>> { if (isEmpty()) { return resolvedPromise(emptyList()) } val result = AsyncPromise<List<T>>() val latch = AtomicInteger(size) val list = Collections.synchronizedList(Collections.nCopies<T?>(size, null).toMutableList()) fun arrive() { if (latch.decrementAndGet() == 0) { if (ignoreErrors) { list.removeIf { it == null } } @Suppress("UNCHECKED_CAST") result.setResult(list as List<T>) } } for ((i, promise) in this.withIndex()) { promise.onSuccess { list.set(i, it) arrive() } promise.onError { if (ignoreErrors) { arrive() } else { result.setError(it) } } } return result } @JvmOverloads fun createError(error: String, log: Boolean = false): RuntimeException = MessageError(error, log) inline fun <T> AsyncPromise<T>.compute(runnable: () -> T) { val result = try { runnable() } catch (e: Throwable) { setError(e) return } setResult(result) } inline fun <T> runAsync(crossinline runnable: () -> T): Promise<T> { val promise = AsyncPromise<T>() AppExecutorUtil.getAppExecutorService().execute { val result = try { runnable() } catch (e: Throwable) { promise.setError(e) return@execute } promise.setResult(result) } return promise } /** * Log error if not a message error */ fun Logger.errorIfNotMessage(e: Throwable): Boolean { if (e is MessageError) { val log = e.log if (log == ThreeState.YES || (log == ThreeState.UNSURE && ApplicationManager.getApplication()?.isUnitTestMode == true)) { error(e) return true } } else if (e !is ControlFlowException && e !is CancellationException) { error(e) return true } return false } fun ActionCallback.toPromise(): Promise<Any?> { val promise = AsyncPromise<Any?>() doWhenDone { promise.setResult(null) } .doWhenRejected { error -> promise.setError(createError(error ?: "Internal error")) } return promise } fun Promise<*>.toActionCallback(): ActionCallback { val result = ActionCallback() onSuccess { result.setDone() } onError { result.setRejected() } return result } fun Collection<Promise<*>>.all(): Promise<*> = if (size == 1) first() else all(null) /** * @see collectResults */ @JvmOverloads fun <T: Any?> Collection<Promise<*>>.all(totalResult: T, ignoreErrors: Boolean = false): Promise<T> { if (isEmpty()) { return resolvedPromise() } val totalPromise = AsyncPromise<T>() val done = CountDownConsumer(size, totalPromise, totalResult) val rejected = if (ignoreErrors) { Consumer { done.accept(null) } } else { Consumer<Throwable> { totalPromise.setError(it) } } for (promise in this) { promise.onSuccess(done) promise.onError(rejected) } return totalPromise } private class CountDownConsumer<T : Any?>(countDown: Int, private val promise: AsyncPromise<T>, private val totalResult: T) : Consumer<Any?> { private val countDown = AtomicInteger(countDown) override fun accept(t: Any?) { if (countDown.decrementAndGet() == 0) { promise.setResult(totalResult) } } } fun <T> any(promises: Collection<Promise<T>>, totalError: String): Promise<T> { if (promises.isEmpty()) { return resolvedPromise() } else if (promises.size == 1) { return promises.first() } val totalPromise = AsyncPromise<T>() val done = Consumer<T> { result -> totalPromise.setResult(result) } val rejected = object : Consumer<Throwable> { private val toConsume = AtomicInteger(promises.size) override fun accept(throwable: Throwable) { if (toConsume.decrementAndGet() <= 0) { totalPromise.setError(totalError) } } } for (promise in promises) { promise.onSuccess(done) promise.onError(rejected) } return totalPromise } private class DonePromise<T>(private val value: PromiseValue<T>) : Promise<T>, Future<T>, CancellablePromise<T> { /** * The same as @{link Future[Future.isDone]}. * Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true. */ override fun isDone() = true override fun getState() = value.state override fun isCancelled() = this.value.isCancelled override fun get() = blockingGet(-1) override fun get(timeout: Long, unit: TimeUnit) = blockingGet(timeout.toInt(), unit) override fun cancel(mayInterruptIfRunning: Boolean): Boolean { if (state == Promise.State.PENDING) { cancel() return true } else { return false } } override fun onSuccess(handler: Consumer<in T?>): CancellablePromise<T> { if (value.error != null) { return this } if (!isHandlerObsolete(handler)) { handler.accept(value.result) } return this } @Suppress("UNCHECKED_CAST") override fun processed(child: Promise<in T?>): Promise<T> { if (child is CompletablePromise<*>) { (child as CompletablePromise<T>).setResult(value.result) } return this } override fun onProcessed(handler: Consumer<in T?>): CancellablePromise<T> { if (value.error == null) { onSuccess(handler) } else if (!isHandlerObsolete(handler)) { handler.accept(null) } return this } override fun onError(handler: Consumer<in Throwable?>): CancellablePromise<T> { if (value.error != null && !isHandlerObsolete(handler)) { handler.accept(value.error) } return this } override fun <SUB_RESULT : Any?> then(done: Function<in T, out SUB_RESULT>): Promise<SUB_RESULT> { @Suppress("UNCHECKED_CAST") return when { value.error != null -> this as Promise<SUB_RESULT> isHandlerObsolete(done) -> cancelledPromise() else -> DonePromise(PromiseValue.createFulfilled(done.`fun`(value.result))) } } override fun <SUB_RESULT : Any?> thenAsync(done: Function<in T, out Promise<SUB_RESULT>>): Promise<SUB_RESULT> { if (value.error == null) { return done.`fun`(value.result) } else { @Suppress("UNCHECKED_CAST") return this as Promise<SUB_RESULT> } } override fun blockingGet(timeout: Int, timeUnit: TimeUnit) = value.getResultOrThrowError() override fun cancel() {} }
apache-2.0
a5bf94ff68edd1c957d15517cbd9eb31
29.159601
203
0.694947
4.010945
false
false
false
false
genonbeta/TrebleShot
app/src/main/java/org/monora/uprotocol/client/android/fragment/content/ImageBrowserFragment.kt
1
10301
/* * Copyright (C) 2021 Veli Tasalı * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.monora.uprotocol.client.android.fragment.content import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.activity.OnBackPressedCallback import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.fragment.app.viewModels import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.liveData import androidx.lifecycle.viewModelScope import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.genonbeta.android.framework.util.Files import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.monora.uprotocol.client.android.R import org.monora.uprotocol.client.android.content.Image import org.monora.uprotocol.client.android.content.ImageBucket import org.monora.uprotocol.client.android.data.MediaRepository import org.monora.uprotocol.client.android.data.SelectionRepository import org.monora.uprotocol.client.android.databinding.LayoutEmptyContentBinding import org.monora.uprotocol.client.android.databinding.ListImageBinding import org.monora.uprotocol.client.android.databinding.ListImageBucketBinding import org.monora.uprotocol.client.android.util.Activities import org.monora.uprotocol.client.android.viewmodel.EmptyContentViewModel import org.monora.uprotocol.client.android.viewmodel.SharingSelectionViewModel import javax.inject.Inject @AndroidEntryPoint class ImageBrowserFragment : Fragment(R.layout.layout_image_browser) { private val browserViewModel: ImageBrowserViewModel by viewModels() private val selectionViewModel: SharingSelectionViewModel by activityViewModels() private val backPressedCallback = object : OnBackPressedCallback(false) { override fun handleOnBackPressed() { browserViewModel.showBuckets() } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val titleView = view.findViewById<TextView>(R.id.titleText) val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView) val emptyView = LayoutEmptyContentBinding.bind(view.findViewById(R.id.emptyView)) val imageAdapter = ImageBrowserAdapter { image, clickType -> when (clickType) { ImageBrowserAdapter.ClickType.Default -> Activities.view(view.context, image.uri, image.mimeType) ImageBrowserAdapter.ClickType.ToggleSelect -> { selectionViewModel.setSelected(image, image.isSelected) } } } val bucketAdapter = ImageBucketBrowserAdapter { browserViewModel.showImages(it) } val emptyContentViewModel = EmptyContentViewModel() emptyView.viewModel = emptyContentViewModel emptyView.emptyText.setText(R.string.empty_photos_list) emptyView.emptyImage.setImageResource(R.drawable.ic_photo_white_24dp) emptyView.executePendingBindings() imageAdapter.setHasStableIds(true) recyclerView.adapter = imageAdapter browserViewModel.showingContent.observe(viewLifecycleOwner) { when (it) { is ImageBrowserViewModel.Content.Buckets -> { backPressedCallback.isEnabled = false titleView.text = getString(R.string.folders) recyclerView.adapter = bucketAdapter bucketAdapter.submitList(it.list) emptyContentViewModel.with(recyclerView, it.list.isNotEmpty()) } is ImageBrowserViewModel.Content.Images -> { backPressedCallback.isEnabled = true titleView.text = it.imageBucket.name recyclerView.adapter = imageAdapter imageAdapter.submitList(it.list) emptyContentViewModel.with(recyclerView, it.list.isNotEmpty()) } } } selectionViewModel.externalState.observe(viewLifecycleOwner) { imageAdapter.notifyDataSetChanged() } } override fun onResume() { super.onResume() activity?.onBackPressedDispatcher?.addCallback(viewLifecycleOwner, backPressedCallback) } override fun onPause() { super.onPause() backPressedCallback.remove() } } class ImageBrowserAdapter( private val clickListener: (Image, ClickType) -> Unit, ) : ListAdapter<Image, ImageViewHolder>(ImageItemCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder { return ImageViewHolder( ListImageBinding.inflate(LayoutInflater.from(parent.context), parent, false), clickListener, ) } override fun onBindViewHolder(holder: ImageViewHolder, position: Int) { holder.bind(getItem(position)) } override fun getItemId(position: Int): Long { return getItem(position).id } override fun getItemViewType(position: Int): Int { return VIEW_TYPE_IMAGE } enum class ClickType { Default, ToggleSelect, } companion object { const val VIEW_TYPE_IMAGE = 0 } } class ImageItemCallback : DiffUtil.ItemCallback<Image>() { override fun areItemsTheSame(oldItem: Image, newItem: Image): Boolean { return oldItem == newItem } override fun areContentsTheSame(oldItem: Image, newItem: Image): Boolean { return oldItem == newItem } } class ImageContentViewModel(image: Image) { val title = image.title val size = Files.formatLength(image.size, false) val uri = image.uri } class ImageViewHolder( private val binding: ListImageBinding, private val clickListener: (Image, ImageBrowserAdapter.ClickType) -> Unit, ) : RecyclerView.ViewHolder(binding.root) { fun bind(image: Image) { binding.viewModel = ImageContentViewModel(image) binding.root.setOnClickListener { clickListener(image, ImageBrowserAdapter.ClickType.Default) } binding.selection.setOnClickListener { image.isSelected = !image.isSelected it.isSelected = image.isSelected clickListener(image, ImageBrowserAdapter.ClickType.ToggleSelect) } binding.selection.isSelected = image.isSelected binding.executePendingBindings() } } class ImageBucketItemCallback : DiffUtil.ItemCallback<ImageBucket>() { override fun areItemsTheSame(oldItem: ImageBucket, newItem: ImageBucket): Boolean { return oldItem == newItem } override fun areContentsTheSame(oldItem: ImageBucket, newItem: ImageBucket): Boolean { return oldItem == newItem } } class ImageBucketContentViewModel(imageBucket: ImageBucket) { val name = imageBucket.name val thumbnailUri = imageBucket.thumbnailUri } class ImageBucketViewHolder( private val binding: ListImageBucketBinding, private val clickListener: (ImageBucket) -> Unit, ) : RecyclerView.ViewHolder(binding.root) { fun bind(imageBucket: ImageBucket) { R.layout.list_image_bucket binding.viewModel = ImageBucketContentViewModel(imageBucket) binding.root.setOnClickListener { clickListener(imageBucket) } binding.executePendingBindings() } } class ImageBucketBrowserAdapter( private val clickListener: (ImageBucket) -> Unit, ) : ListAdapter<ImageBucket, ImageBucketViewHolder>(ImageBucketItemCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageBucketViewHolder { return ImageBucketViewHolder( ListImageBucketBinding.inflate(LayoutInflater.from(parent.context), parent, false), clickListener, ) } override fun onBindViewHolder(holder: ImageBucketViewHolder, position: Int) { holder.bind(getItem(position)) } override fun getItemId(position: Int): Long { return getItem(position).id } override fun getItemViewType(position: Int): Int { return VIEW_TYPE_BUCKET } companion object { const val VIEW_TYPE_BUCKET = 0 } } @HiltViewModel class ImageBrowserViewModel @Inject internal constructor( private val mediaRepository: MediaRepository, private val selectionRepository: SelectionRepository, ) : ViewModel() { private val _showingContent = MutableLiveData<Content>() val showingContent = liveData { emitSource(_showingContent) } fun showBuckets() { viewModelScope.launch(Dispatchers.IO) { _showingContent.postValue(Content.Buckets(mediaRepository.getImageBuckets())) } } fun showImages(bucket: ImageBucket) { viewModelScope.launch(Dispatchers.IO) { val images = mediaRepository.getImages(bucket) selectionRepository.whenContains(images) { item, selected -> item.isSelected = selected } _showingContent.postValue(Content.Images(bucket, images)) } } init { showBuckets() } sealed class Content { class Buckets(val list: List<ImageBucket>) : Content() class Images(val imageBucket: ImageBucket, val list: List<Image>) : Content() } }
gpl-2.0
bdfc606c144ff730c3cb898a2c53ae01
35.013986
113
0.708641
4.914122
false
false
false
false
Raizlabs/DBFlow
processor/src/main/kotlin/com/dbflow5/processor/ProcessorManager.kt
1
15178
package com.dbflow5.processor import com.dbflow5.processor.definition.DatabaseDefinition import com.dbflow5.processor.definition.DatabaseHolderDefinition import com.dbflow5.processor.definition.DatabaseObjectHolder import com.dbflow5.processor.definition.EntityDefinition import com.dbflow5.processor.definition.ManyToManyDefinition import com.dbflow5.processor.definition.MigrationDefinition import com.dbflow5.processor.definition.ModelViewDefinition import com.dbflow5.processor.definition.QueryModelDefinition import com.dbflow5.processor.definition.TableDefinition import com.dbflow5.processor.definition.TypeConverterDefinition import com.dbflow5.processor.definition.provider.ContentProviderDefinition import com.dbflow5.processor.definition.provider.TableEndpointDefinition import com.dbflow5.processor.definition.safeWritePackageHelper import com.dbflow5.processor.utils.writeBaseDefinition import com.squareup.javapoet.ClassName import com.squareup.javapoet.JavaFile import com.squareup.javapoet.TypeName import java.io.IOException import javax.annotation.processing.FilerException import javax.annotation.processing.Messager import javax.annotation.processing.ProcessingEnvironment import javax.annotation.processing.RoundEnvironment import javax.lang.model.element.Element import javax.lang.model.util.Elements import javax.lang.model.util.Types import javax.tools.Diagnostic import kotlin.reflect.KClass /** * Description: The main object graph during processing. This class collects all of the * processor classes and writes them to the corresponding database holders. */ class ProcessorManager internal constructor(val processingEnvironment: ProcessingEnvironment) : Handler { companion object { lateinit var manager: ProcessorManager } private val uniqueDatabases = arrayListOf<TypeName>() private val modelToDatabaseMap = hashMapOf<TypeName, TypeName>() val typeConverters = linkedMapOf<TypeName?, TypeConverterDefinition>() private val migrations = hashMapOf<TypeName?, MutableMap<Int, MutableList<MigrationDefinition>>>() private val databaseDefinitionMap = hashMapOf<TypeName?, DatabaseObjectHolder>() private val handlers = mutableSetOf<AnnotatedHandler<*>>() private val providerMap = hashMapOf<TypeName?, ContentProviderDefinition>() init { manager = this } fun addHandlers(vararg containerHandlers: AnnotatedHandler<*>) { containerHandlers.forEach { handlers.add(it) } } val messager: Messager = processingEnvironment.messager val typeUtils: Types = processingEnvironment.typeUtils val elements: Elements = processingEnvironment.elementUtils fun addDatabase(database: TypeName) { if (!uniqueDatabases.contains(database)) { uniqueDatabases.add(database) } } fun addDatabaseDefinition(databaseDefinition: DatabaseDefinition) { val holderDefinition = getOrPutDatabase(databaseDefinition.elementClassName) holderDefinition?.databaseDefinition = databaseDefinition } fun getDatabaseHolderDefinitionList() = databaseDefinitionMap.values.toList() fun getDatabaseHolderDefinition(databaseName: TypeName?) = databaseDefinitionMap[databaseName] fun addTypeConverterDefinition(definition: TypeConverterDefinition) { typeConverters[definition.modelTypeName] = definition } fun getTypeConverterDefinition(typeName: TypeName?): TypeConverterDefinition? = typeConverters[typeName] fun addModelToDatabase(modelType: TypeName?, databaseName: TypeName) { modelType?.let { type -> addDatabase(databaseName) modelToDatabaseMap[type] = databaseName } } fun addQueryModelDefinition(queryModelDefinition: QueryModelDefinition) { queryModelDefinition.elementClassName?.let { getOrPutDatabase(queryModelDefinition.associationalBehavior.databaseTypeName) ?.queryModelDefinitionMap?.put(it, queryModelDefinition) } } fun addTableDefinition(tableDefinition: TableDefinition) { tableDefinition.elementClassName?.let { val holderDefinition = getOrPutDatabase(tableDefinition.associationalBehavior.databaseTypeName) holderDefinition?.tableDefinitionMap?.put(it, tableDefinition) holderDefinition?.tableNameMap?.let { val tableName = tableDefinition.associationalBehavior.name if (holderDefinition.tableNameMap.containsKey(tableName)) { logError("Found duplicate table $tableName " + "for database ${holderDefinition.databaseDefinition?.elementName}") } else { holderDefinition.tableNameMap.put(tableName, tableDefinition) } } } } fun addManyToManyDefinition(manyToManyDefinition: ManyToManyDefinition) { val databaseHolderDefinition = getOrPutDatabase(manyToManyDefinition.databaseTypeName) databaseHolderDefinition?.manyToManyDefinitionMap?.let { manyToManyDefinition.elementClassName?.let { elementClassName -> it.getOrPut(elementClassName) { arrayListOf() } .add(manyToManyDefinition) } } } fun getTableDefinition(databaseName: TypeName?, typeName: TypeName?): TableDefinition? { return getOrPutDatabase(databaseName)?.tableDefinitionMap?.get(typeName) } fun getQueryModelDefinition(databaseName: TypeName?, typeName: TypeName?): QueryModelDefinition? { return getOrPutDatabase(databaseName)?.queryModelDefinitionMap?.get(typeName) } fun getModelViewDefinition(databaseName: TypeName?, typeName: TypeName?): ModelViewDefinition? { return getOrPutDatabase(databaseName)?.modelViewDefinitionMap?.get(typeName) } fun getReferenceDefinition(databaseName: TypeName?, typeName: TypeName?): EntityDefinition? { return getTableDefinition(databaseName, typeName) ?: getQueryModelDefinition(databaseName, typeName) ?: getModelViewDefinition(databaseName, typeName) } fun addModelViewDefinition(modelViewDefinition: ModelViewDefinition) { modelViewDefinition.elementClassName?.let { getOrPutDatabase(modelViewDefinition.associationalBehavior.databaseTypeName) ?.modelViewDefinitionMap?.put(it, modelViewDefinition) } } fun getTypeConverters() = typeConverters.values.toHashSet().sortedBy { it.modelTypeName?.toString() } fun getTableDefinitions(databaseName: TypeName): List<TableDefinition> { val databaseHolderDefinition = getOrPutDatabase(databaseName) return (databaseHolderDefinition?.tableDefinitionMap?.values ?: arrayListOf()) .toHashSet() .sortedBy { it.outputClassName?.simpleName() } } fun setTableDefinitions(tableDefinitionSet: MutableMap<TypeName, TableDefinition>, databaseName: TypeName) { val databaseDefinition = getOrPutDatabase(databaseName) databaseDefinition?.tableDefinitionMap = tableDefinitionSet } fun getModelViewDefinitions(databaseName: TypeName): List<ModelViewDefinition> { val databaseDefinition = getOrPutDatabase(databaseName) return (databaseDefinition?.modelViewDefinitionMap?.values ?: arrayListOf()) .toHashSet() .sortedBy { it.outputClassName?.simpleName() } .sortedByDescending { it.priority } } fun setModelViewDefinitions(modelViewDefinitionMap: MutableMap<TypeName, ModelViewDefinition>, elementClassName: ClassName) { val databaseDefinition = getOrPutDatabase(elementClassName) databaseDefinition?.modelViewDefinitionMap = modelViewDefinitionMap } fun getQueryModelDefinitions(databaseName: TypeName): List<QueryModelDefinition> { val databaseDefinition = getOrPutDatabase(databaseName) return (databaseDefinition?.queryModelDefinitionMap?.values ?: arrayListOf()) .toHashSet() .sortedBy { it.outputClassName?.simpleName() } } fun addMigrationDefinition(migrationDefinition: MigrationDefinition) { val migrationDefinitionMap = migrations.getOrPut(migrationDefinition.databaseName) { hashMapOf() } val migrationDefinitions = migrationDefinitionMap.getOrPut(migrationDefinition.version) { arrayListOf() } if (!migrationDefinitions.contains(migrationDefinition)) { migrationDefinitions.add(migrationDefinition) } } fun getMigrationsForDatabase(databaseName: TypeName) = migrations[databaseName] ?: hashMapOf<Int, List<MigrationDefinition>>() fun addContentProviderDefinition(contentProviderDefinition: ContentProviderDefinition) { contentProviderDefinition.elementTypeName?.let { val holderDefinition = getOrPutDatabase(contentProviderDefinition.databaseTypeName) holderDefinition?.providerMap?.put(it, contentProviderDefinition) providerMap.put(it, contentProviderDefinition) } } fun putTableEndpointForProvider(tableEndpointDefinition: TableEndpointDefinition) { val contentProviderDefinition = providerMap[tableEndpointDefinition.contentProviderName] if (contentProviderDefinition == null) { logError("Content Provider ${tableEndpointDefinition.contentProviderName} was not found for the @TableEndpoint ${tableEndpointDefinition.elementClassName}") } else { contentProviderDefinition.endpointDefinitions.add(tableEndpointDefinition) } } fun logError(callingClass: KClass<*>?, error: String?, vararg args: Any?) { messager.printMessage(Diagnostic.Kind.ERROR, String.format("${ (callingClass?.toString() ?: "") // don't print this in logs. .replace("(Kotlin reflection is not available)", "") } : ${error?.trim()}", *args)) } fun logError(error: String?) = logError(callingClass = null, error = error) fun logWarning(error: String?) { messager.printMessage(Diagnostic.Kind.WARNING, error ?: "") } fun logWarning(callingClass: Class<*>, error: String) { logWarning("$callingClass : $error") } private fun getOrPutDatabase(databaseName: TypeName?): DatabaseObjectHolder? = databaseDefinitionMap.getOrPut(databaseName) { DatabaseObjectHolder() } override fun handle(processorManager: ProcessorManager, roundEnvironment: RoundEnvironment) { handlers.forEach { it.handle(processorManager, roundEnvironment) } val databaseDefinitions = getDatabaseHolderDefinitionList() .sortedBy { it.databaseDefinition?.outputClassName?.simpleName() } for (databaseHolderDefinition in databaseDefinitions) { try { if (databaseHolderDefinition.databaseDefinition == null) { manager.logError(databaseHolderDefinition.getMissingDBRefs().joinToString("\n")) continue } val manyToManyDefinitions = databaseHolderDefinition.manyToManyDefinitionMap.values val flattenedList = manyToManyDefinitions.flatten().sortedBy { it.outputClassName?.simpleName() } for (manyToManyList in flattenedList) { manyToManyList.prepareForWrite() manyToManyList.writeBaseDefinition(processorManager) } // process all in next round. if (!manyToManyDefinitions.isEmpty()) { manyToManyDefinitions.clear() continue } if (roundEnvironment.processingOver()) { val validator = ContentProviderValidator() val contentProviderDefinitions = databaseHolderDefinition.providerMap.values .sortedBy { it.outputClassName?.simpleName() } contentProviderDefinitions.forEach { contentProviderDefinition -> if (validator.validate(processorManager, contentProviderDefinition)) { contentProviderDefinition.writeBaseDefinition(processorManager) } } } databaseHolderDefinition.databaseDefinition?.validateAndPrepareToWrite() if (roundEnvironment.processingOver()) { databaseHolderDefinition.databaseDefinition?.let { if (it.outputClassName != null) { JavaFile.builder(it.packageName, it.typeSpec).build() .writeTo(processorManager.processingEnvironment.filer) } } } val tableDefinitions = databaseHolderDefinition.tableDefinitionMap.values .sortedBy { it.outputClassName?.simpleName() } tableDefinitions.forEach { it.writeBaseDefinition(processorManager) } val modelViewDefinitions = databaseHolderDefinition.modelViewDefinitionMap.values modelViewDefinitions .sortedByDescending { it.priority } .forEach { it.writeBaseDefinition(processorManager) } val queryModelDefinitions = databaseHolderDefinition.queryModelDefinitionMap.values .sortedBy { it.outputClassName?.simpleName() } queryModelDefinitions.forEach { it.writeBaseDefinition(processorManager) } tableDefinitions.safeWritePackageHelper(processorManager) modelViewDefinitions.safeWritePackageHelper(processorManager) queryModelDefinitions.safeWritePackageHelper(processorManager) } catch (e: IOException) { } } try { val databaseHolderDefinition = DatabaseHolderDefinition(processorManager) if (!databaseHolderDefinition.isGarbage()) { JavaFile.builder(com.dbflow5.processor.ClassNames.FLOW_MANAGER_PACKAGE, databaseHolderDefinition.typeSpec).build() .writeTo(processorManager.processingEnvironment.filer) } } catch (e: FilerException) { } catch (e: IOException) { logError(e.message) } } fun elementBelongsInTable(element: Element): Boolean { val enclosingElement = element.enclosingElement var find: EntityDefinition? = databaseDefinitionMap.values.flatMap { it.tableDefinitionMap.values } .find { it.element == enclosingElement } // modelview check. if (find == null) { find = databaseDefinitionMap.values.flatMap { it.modelViewDefinitionMap.values } .find { it.element == enclosingElement } } // querymodel check if (find == null) { find = databaseDefinitionMap.values.flatMap { it.queryModelDefinitionMap.values } .find { it.element == enclosingElement } } return find != null } }
mit
0f80db46a27f6e98e538d8859fec6995
44.172619
168
0.694031
5.553604
false
false
false
false
romannurik/muzei
main/src/main/java/com/google/android/apps/muzei/settings/EffectsFragment.kt
1
10291
/* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.muzei.settings import android.app.Activity import android.content.SharedPreferences import android.os.Bundle import android.view.View import android.widget.Toast import androidx.core.content.edit import androidx.fragment.app.Fragment import androidx.viewpager2.adapter.FragmentStateAdapter import androidx.viewpager2.widget.ViewPager2 import com.google.android.apps.muzei.isPreviewMode import com.google.android.apps.muzei.render.MuzeiBlurRenderer import com.google.android.apps.muzei.util.autoCleared import com.google.android.apps.muzei.util.toast import com.google.android.material.tabs.TabLayoutMediator import kotlinx.coroutines.flow.MutableStateFlow import net.nurik.roman.muzei.R import net.nurik.roman.muzei.databinding.EffectsFragmentBinding val EffectsLockScreenOpen = MutableStateFlow(false) /** * Fragment for allowing the user to configure advanced settings. */ class EffectsFragment : Fragment(R.layout.effects_fragment) { private var binding: EffectsFragmentBinding by autoCleared() private val sharedPreferencesListener = SharedPreferences.OnSharedPreferenceChangeListener { sp, key -> val effectsLinked = sp.getBoolean(Prefs.PREF_LINK_EFFECTS, false) if (key == Prefs.PREF_LINK_EFFECTS) { if (effectsLinked) { if (binding.viewPager.currentItem == 0) { // Update the lock screen effects to match the home screen sp.edit { putInt(Prefs.PREF_LOCK_BLUR_AMOUNT, sp.getInt(Prefs.PREF_BLUR_AMOUNT, MuzeiBlurRenderer.DEFAULT_BLUR)) putInt(Prefs.PREF_LOCK_DIM_AMOUNT, sp.getInt(Prefs.PREF_DIM_AMOUNT, MuzeiBlurRenderer.DEFAULT_MAX_DIM)) putInt(Prefs.PREF_LOCK_GREY_AMOUNT, sp.getInt(Prefs.PREF_GREY_AMOUNT, MuzeiBlurRenderer.DEFAULT_GREY)) } } else { // Update the home screen effects to match the lock screen sp.edit { putInt(Prefs.PREF_BLUR_AMOUNT, sp.getInt(Prefs.PREF_LOCK_BLUR_AMOUNT, MuzeiBlurRenderer.DEFAULT_BLUR)) putInt(Prefs.PREF_DIM_AMOUNT, sp.getInt(Prefs.PREF_LOCK_DIM_AMOUNT, MuzeiBlurRenderer.DEFAULT_MAX_DIM)) putInt(Prefs.PREF_GREY_AMOUNT, sp.getInt(Prefs.PREF_LOCK_GREY_AMOUNT, MuzeiBlurRenderer.DEFAULT_GREY)) } } requireContext().toast(R.string.toast_link_effects, Toast.LENGTH_LONG) } else { requireContext().toast(R.string.toast_link_effects_off, Toast.LENGTH_LONG) } // Update the menu item updateLinkEffectsMenuItem(effectsLinked) } else if (effectsLinked) { when (key) { Prefs.PREF_BLUR_AMOUNT -> { // Update the lock screen effect to match the updated home screen sp.edit { putInt(Prefs.PREF_LOCK_BLUR_AMOUNT, sp.getInt(Prefs.PREF_BLUR_AMOUNT, MuzeiBlurRenderer.DEFAULT_BLUR)) } } Prefs.PREF_DIM_AMOUNT -> { // Update the lock screen effect to match the updated home screen sp.edit { putInt(Prefs.PREF_LOCK_DIM_AMOUNT, sp.getInt(Prefs.PREF_DIM_AMOUNT, MuzeiBlurRenderer.DEFAULT_MAX_DIM)) } } Prefs.PREF_GREY_AMOUNT -> { // Update the lock screen effect to match the updated home screen sp.edit { putInt(Prefs.PREF_LOCK_GREY_AMOUNT, sp.getInt(Prefs.PREF_GREY_AMOUNT, MuzeiBlurRenderer.DEFAULT_GREY)) } } Prefs.PREF_LOCK_BLUR_AMOUNT -> { // Update the home screen effect to match the updated lock screen sp.edit { putInt(Prefs.PREF_BLUR_AMOUNT, sp.getInt(Prefs.PREF_LOCK_BLUR_AMOUNT, MuzeiBlurRenderer.DEFAULT_BLUR)) } } Prefs.PREF_LOCK_DIM_AMOUNT -> { // Update the home screen effect to match the updated lock screen sp.edit { putInt(Prefs.PREF_DIM_AMOUNT, sp.getInt(Prefs.PREF_LOCK_DIM_AMOUNT, MuzeiBlurRenderer.DEFAULT_MAX_DIM)) } } Prefs.PREF_LOCK_GREY_AMOUNT -> { // Update the home screen effect to match the updated lock screen sp.edit { putInt(Prefs.PREF_GREY_AMOUNT, sp.getInt(Prefs.PREF_LOCK_GREY_AMOUNT, MuzeiBlurRenderer.DEFAULT_GREY)) } } } } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { binding = EffectsFragmentBinding.bind(view) if (requireActivity().isPreviewMode) { with(binding.toolbar) { setNavigationIcon(R.drawable.ic_ab_done) navigationContentDescription = getString(R.string.done) setNavigationOnClickListener { requireActivity().run { setResult(Activity.RESULT_OK) finish() } } } } requireActivity().menuInflater.inflate(R.menu.effects_fragment, binding.toolbar.menu) updateLinkEffectsMenuItem() binding.toolbar.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.action_link_effects -> { val sp = Prefs.getSharedPreferences(requireContext()) val effectsLinked = sp.getBoolean(Prefs.PREF_LINK_EFFECTS, false) sp.edit { putBoolean(Prefs.PREF_LINK_EFFECTS, !effectsLinked) } true } R.id.action_reset_defaults -> { Prefs.getSharedPreferences(requireContext()).edit { putInt(Prefs.PREF_BLUR_AMOUNT, MuzeiBlurRenderer.DEFAULT_BLUR) putInt(Prefs.PREF_DIM_AMOUNT, MuzeiBlurRenderer.DEFAULT_MAX_DIM) putInt(Prefs.PREF_GREY_AMOUNT, MuzeiBlurRenderer.DEFAULT_GREY) putInt(Prefs.PREF_LOCK_BLUR_AMOUNT, MuzeiBlurRenderer.DEFAULT_BLUR) putInt(Prefs.PREF_LOCK_DIM_AMOUNT, MuzeiBlurRenderer.DEFAULT_MAX_DIM) putInt(Prefs.PREF_LOCK_GREY_AMOUNT, MuzeiBlurRenderer.DEFAULT_GREY) } true } else -> false } } binding.viewPager.adapter = Adapter(this) TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position -> tab.text = when(position) { 0 -> getString(R.string.settings_home_screen_title) else -> getString(R.string.settings_lock_screen_title) } }.attach() binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) { EffectsLockScreenOpen.value = position == 1 } }) Prefs.getSharedPreferences(requireContext()) .registerOnSharedPreferenceChangeListener(sharedPreferencesListener) } override fun onStart() { super.onStart() // Reset the value here to restore the state lost in onStop() EffectsLockScreenOpen.value = binding.viewPager.currentItem == 1 } private fun updateLinkEffectsMenuItem( effectsLinked: Boolean = Prefs.getSharedPreferences(requireContext()) .getBoolean(Prefs.PREF_LINK_EFFECTS, false) ) { with(binding.toolbar.menu.findItem(R.id.action_link_effects)) { setIcon(if (effectsLinked) R.drawable.ic_action_link_effects else R.drawable.ic_action_link_effects_off) title = if (effectsLinked) getString(R.string.action_link_effects) else getString(R.string.action_link_effects_off) } } override fun onStop() { // The lock screen effects screen is no longer visible, so set the value to false EffectsLockScreenOpen.value = false super.onStop() } override fun onDestroyView() { Prefs.getSharedPreferences(requireContext()) .unregisterOnSharedPreferenceChangeListener(sharedPreferencesListener) super.onDestroyView() } private class Adapter(fragment: Fragment) : FragmentStateAdapter(fragment) { override fun getItemCount() = 2 override fun createFragment(position: Int) = when(position) { 0 -> EffectsScreenFragment.create( Prefs.PREF_BLUR_AMOUNT, Prefs.PREF_DIM_AMOUNT, Prefs.PREF_GREY_AMOUNT) else -> EffectsScreenFragment.create( Prefs.PREF_LOCK_BLUR_AMOUNT, Prefs.PREF_LOCK_DIM_AMOUNT, Prefs.PREF_LOCK_GREY_AMOUNT) } } }
apache-2.0
746a2866dc25da44679d993e952ddd6e
43.747826
105
0.572053
4.914518
false
false
false
false
blokadaorg/blokada
android5/app/src/main/java/ui/BottomSheetFragment.kt
1
1428
/* * This file is part of Blokada. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. * * Copyright © 2021 Blocka AB. All rights reserved. * * @author Karol Gusak ([email protected]) */ package ui import android.app.Dialog import android.os.Bundle import android.view.View import android.widget.FrameLayout import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialog import com.google.android.material.bottomsheet.BottomSheetDialogFragment open class BottomSheetFragment(val skipCollapsed: Boolean = true) : BottomSheetDialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog dialog.setOnShowListener { dialog -> val d = dialog as BottomSheetDialog val bottomSheet = d.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet) as FrameLayout val behavior = BottomSheetBehavior.from(bottomSheet) if (skipCollapsed) { behavior.state = BottomSheetBehavior.STATE_EXPANDED behavior.skipCollapsed = skipCollapsed } } return dialog } }
mpl-2.0
71102a7b4f77d0081a7e3b1aa418bbd9
35.615385
119
0.715487
4.678689
false
false
false
false
smmribeiro/intellij-community
java/java-tests/testSrc/com/intellij/util/indexing/RequestedToRebuildIndexTest.kt
2
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 com.intellij.util.indexing import com.intellij.ide.startup.ServiceNotReadyException import com.intellij.openapi.application.WriteAction import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiJavaFile import com.intellij.psi.PsiManager import com.intellij.psi.search.GlobalSearchScope import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase import com.intellij.util.ThrowableRunnable import com.intellij.util.indexing.roots.IndexableEntityProviderMethods.createIterators import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.moduleMap import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity import org.junit.Test import java.util.* import java.util.function.Consumer class RequestedToRebuildIndexTest : JavaCodeInsightFixtureTestCase() { @Test fun `test requesting content dependent index rebuild with partial indexing`() { doTestRequireRebuild(CountingFileBasedIndexExtension.registerCountingFileBasedIndex(testRootDisposable)) { fileA -> reindexFile(fileA) } } @Test fun `test requesting content independent index rebuild with partial indexing`() { doTestRequireRebuild(CountingContentIndependentFileBasedIndexExtension.registerCountingFileBasedIndex(testRootDisposable)) { fileA -> reindexFile(fileA) } } private fun reindexFile(fileA: VirtualFile) { val storage = WorkspaceModel.getInstance(project).entityStorage.current val moduleEntity = storage.entities(ModuleEntity::class.java).iterator().next() assertNotNull(moduleEntity) val iterators = createIterators(moduleEntity, listOf(fileA), storage.moduleMap, myFixture.project) UnindexedFilesUpdater(myFixture.project, ArrayList(iterators), "Partial reindex of one of two indexable files").queue(myFixture.project) } @Test fun `test requesting content dependent index rebuild with changed file indexing`() { doTestRequireRebuild(CountingFileBasedIndexExtension.registerCountingFileBasedIndex(testRootDisposable)) { fileA -> updateFileContent(fileA) } } @Test fun `test requesting content independent index rebuild with changed file indexing`() { doTestRequireRebuild(CountingContentIndependentFileBasedIndexExtension.registerCountingFileBasedIndex(testRootDisposable)) { fileA -> updateFileContent(fileA) } } private fun updateFileContent(fileA: VirtualFile) { WriteAction.run<RuntimeException> { VfsUtil.saveText(fileA, "class FooA{private int i = 0;}") val psiFileA = PsiManager.getInstance(project).findFile(fileA) //force reindex val clazz = (psiFileA as PsiJavaFile).classes[0] assertNotNull(clazz) assertSize(1, clazz.fields) } } private fun doTestRequireRebuild(countingIndex: CountingIndexBase, partialReindex: Consumer<VirtualFile>) { countingIndex.counter.set(0) val psiClassA = myFixture.addClass("class FooA{}") val fileA = psiClassA.containingFile.virtualFile assertNotNull(JavaPsiFacade.getInstance(project).findClass("FooA", GlobalSearchScope.allScope(project))) assertEquals("File was indexed on creation", 1, countingIndex.counter.get()) val psiClassB = myFixture.addClass("class FooB{}") val fileB = psiClassB.containingFile.virtualFile assertNotNull(JavaPsiFacade.getInstance(project).findClass("FooB", GlobalSearchScope.allScope(project))) assertEquals("File was indexed on creation", 2, countingIndex.counter.get()) countingIndex.counter.set(0) val fileBasedIndex = FileBasedIndex.getInstance() assertEquals("File data is available", countingIndex.getDefaultValue(), fileBasedIndex.getFileData(countingIndex.name, fileA, myFixture.project)) assertEquals("File was not reindexed after indexing on creation", 0, countingIndex.counter.get()) UnindexedFilesUpdater(myFixture.project).queue(myFixture.project) assertEquals("File was not reindexed after full project reindex request", 0, countingIndex.counter.get()) fileBasedIndex.requestRebuild(countingIndex.name) assertCountingIndexBehavesCorrectlyAfterRebuildRequest(countingIndex, fileA, fileB) partialReindex.accept(fileA) assertCountingIndexBehavesCorrectlyAfterRebuildRequest(countingIndex, fileA, fileB) PlatformTestUtil.dispatchAllEventsInIdeEventQueue() assertTrue("File was reindexed on requesting index rebuild", countingIndex.counter.get() > 1) assertEquals("File data is available after full reindex", countingIndex.getDefaultValue(), fileBasedIndex.getFileData(countingIndex.name, fileA, myFixture.project)) assertEquals("File data is available after full reindex", countingIndex.getDefaultValue(), fileBasedIndex.getFileData(countingIndex.name, fileB, myFixture.project)) } private fun assertCountingIndexBehavesCorrectlyAfterRebuildRequest(countingIndex: CountingIndexBase, vararg files: VirtualFile) { assertEquals("File was not reindexed after requesting index rebuild", 0, countingIndex.counter.get()) if (countingIndex.dependsOnFileContent()) { for (file in files) { assertThrows(ServiceNotReadyException::class.java, ThrowableRunnable<RuntimeException> { FileBasedIndex.getInstance().getFileData(countingIndex.name, file, project) }) } } else { /* * Content-independent indexes should always be available, without any dumb mode. * An index that is considered inconsistent, and therefore marked as requiring rebuild, * should probably throw ServiceNotReadyException, but it has never been so, and clients may be not ready. * For now, let's expect last indexed values to be returned */ val fileBasedIndex = FileBasedIndex.getInstance() for (file in files) { assertEquals("File data is available after full reindex", countingIndex.getDefaultValue(), fileBasedIndex.getFileData(countingIndex.name, file, myFixture.project)) } } } }
apache-2.0
e2197dfb02cf35c7d77edb7392ab30de
47.518797
158
0.764296
4.925954
false
true
false
false
idea4bsd/idea4bsd
python/src/com/jetbrains/python/inspections/PyDunderSlotsInspection.kt
9
4860
/* * 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.python.inspections import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor import com.jetbrains.python.PyNames import com.jetbrains.python.psi.* import com.jetbrains.python.psi.impl.PyPsiUtils import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.types.PyClassType class PyDunderSlotsInspection : PyInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor = Visitor(holder, session) private class Visitor(holder: ProblemsHolder, session: LocalInspectionToolSession) : PyInspectionVisitor(holder, session) { override fun visitPyClass(node: PyClass?) { super.visitPyClass(node) if (node != null && LanguageLevel.forElement(node).isAtLeast(LanguageLevel.PYTHON30)) { val slots = findSlotsValue(node) when (slots) { is PySequenceExpression -> slots .elements .asSequence() .filterIsInstance<PyStringLiteralExpression>() .forEach { processSlot(node, it) } is PyStringLiteralExpression -> processSlot(node, slots) } } } override fun visitPyTargetExpression(node: PyTargetExpression?) { super.visitPyTargetExpression(node) if (node != null) { checkAttributeExpression(node) } } private fun findSlotsValue(pyClass: PyClass): PyExpression? { val target = pyClass.findClassAttribute(PyNames.SLOTS, false, myTypeEvalContext) as? PyTargetExpression val value = target?.findAssignedValue() return PyPsiUtils.flattenParens(value) } private fun processSlot(pyClass: PyClass, slot: PyStringLiteralExpression) { val name = slot.stringValue if (pyClass.findClassAttribute(name, false, myTypeEvalContext) != null) { registerProblem(slot, "'$name' in __slots__ conflicts with class variable") } } private fun checkAttributeExpression(target: PyTargetExpression) { val targetName = target.name val qualifier = target.qualifier if (targetName == null || qualifier == null) { return } val qualifierType = myTypeEvalContext.getType(qualifier) if (qualifierType is PyClassType && !qualifierType.isDefinition) { val reference = target.getReference(PyResolveContext.noImplicits().withTypeEvalContext(myTypeEvalContext)) val qualifierClass = qualifierType.pyClass val classWithReadOnlyAttr = PyUtil .multiResolveTopPriority(reference) .asSequence() .filterIsInstance<PyTargetExpression>() .map { declaration -> declaration.containingClass } .filterNotNull() .find { declaringClass -> !attributeIsWritable(qualifierClass, declaringClass, targetName) } if (classWithReadOnlyAttr != null) { registerProblem(target, "'${qualifierClass.name}' object attribute '$targetName' is read-only") } } } private fun attributeIsWritable(qualifierClass: PyClass, declaringClass: PyClass, targetName: String): Boolean { return attributeIsWritableInClass(qualifierClass, declaringClass, targetName) || qualifierClass .getAncestorClasses(myTypeEvalContext) .asSequence() .filter { ancestorClass -> !PyUtil.isObjectClass(ancestorClass) } .any { ancestorClass -> attributeIsWritableInClass(ancestorClass, declaringClass, targetName) } } private fun attributeIsWritableInClass(cls: PyClass, declaringClass: PyClass, targetName: String): Boolean { val ownSlots = cls.ownSlots if (ownSlots == null || ownSlots.contains(PyNames.DICT)) { return true } if (!cls.equals(declaringClass) || !ownSlots.contains(targetName)) { return false } return LanguageLevel.forElement(declaringClass).isAtLeast(LanguageLevel.PYTHON30) || declaringClass.findClassAttribute(targetName, false, myTypeEvalContext) == null } } }
apache-2.0
6784ce7d7ccae2c5900d6a75943e9677
36.674419
125
0.690741
5.057232
false
false
false
false
siosio/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/hint/types/GroovyParameterTypeHintsCollector.kt
2
3606
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.codeInsight.hint.types import com.intellij.codeInsight.hints.FactoryInlayHintsCollector import com.intellij.codeInsight.hints.InlayHintsSink import com.intellij.codeInsight.hints.presentation.InlayPresentation import com.intellij.openapi.editor.Editor import com.intellij.psi.CommonClassNames import com.intellij.psi.PsiElement import com.intellij.psi.PsiType import com.intellij.refactoring.suggested.endOffset import org.jetbrains.plugins.groovy.intentions.style.inference.MethodParameterAugmenter import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier.DEF import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod import org.jetbrains.plugins.groovy.lang.psi.dataFlow.types.TypeAugmenter import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrVariableEnhancer class GroovyParameterTypeHintsCollector(editor: Editor, private val settings: GroovyParameterTypeHintsInlayProvider.Settings) : FactoryInlayHintsCollector(editor) { override fun collect(element: PsiElement, editor: Editor, sink: InlayHintsSink): Boolean { if (!settings.showInferredParameterTypes) { return false } if (!element.isValid) { return false } if (element is GrParameter && element.typeElement == null && !element.isVarArgs) { val type: PsiType = getRepresentableType(element) ?: return true val typeRepresentation = with(factory) { roundWithBackground(seq(buildRepresentation(type), smallText(" "))) } sink.addInlineElement(element.textOffset, false, typeRepresentation, false) } if (element is GrClosableBlock && element.parameterList.isEmpty) { val itParameter: GrParameter = element.allParameters.singleOrNull() ?: return true val type: PsiType = getRepresentableType(itParameter) ?: return true val textRepresentation: InlayPresentation = with(factory) { roundWithBackground(seq(buildRepresentation(type), smallText(" it -> "))) } sink.addInlineElement(element.lBrace.endOffset, true, textRepresentation, false) } if (settings.showTypeParameterList && element is GrMethod && !element.hasTypeParameters() && element.parameters.any { it.typeElement == null }) { val (virtualMethod, _) = MethodParameterAugmenter.createInferenceResult(element) ?: return true val typeParameterList = virtualMethod?.typeParameterList?.takeIf { it.typeParameters.isNotEmpty() } ?: return true val representation = factory.buildRepresentation(typeParameterList) if (element.modifierList.hasModifierProperty(DEF)) { sink.addInlineElement(element.modifierList.getModifier(DEF)!!.textRange.endOffset, true, representation, false) } else { sink.addInlineElement(element.textRange.startOffset, true, representation, false) } } return true } private fun getRepresentableType(variable: GrVariable): PsiType? { val inferredType: PsiType? = GrVariableEnhancer.getEnhancedType(variable) ?: TypeAugmenter.inferAugmentedType(variable) return inferredType?.takeIf { !it.equalsToText(CommonClassNames.JAVA_LANG_OBJECT) } } }
apache-2.0
b35e3d32ba7600a5f9538bb8adb5d3fb
51.26087
140
0.762063
4.558786
false
false
false
false
zsmb13/MaterialDrawerKt
library/src/main/java/co/zsmb/materialdrawerkt/draweritems/switchable/SwitchDrawerItemKt.kt
1
1101
@file:Suppress("RedundantVisibilityModifier") package co.zsmb.materialdrawerkt.draweritems.switchable import co.zsmb.materialdrawerkt.builders.Builder import co.zsmb.materialdrawerkt.createItem import com.mikepenz.materialdrawer.model.SwitchDrawerItem /** * Adds a new SwitchDrawerItem with the given [name] and [description]. * @return The created SwitchDrawerItem instance */ public fun Builder.switchItem( name: String = "", description: String? = null, setup: SwitchDrawerItemKt.() -> Unit = {}): SwitchDrawerItem { return createItem(SwitchDrawerItemKt(), name, description, setup) } /** * Adds a new SwitchDrawerItem with the given [nameRes] and [descriptionRes]. * @return The created SwitchDrawerItem instance */ public fun Builder.switchItem( nameRes: Int, descriptionRes: Int? = null, setup: SwitchDrawerItemKt.() -> Unit = {}): SwitchDrawerItem { return createItem(SwitchDrawerItemKt(), nameRes, descriptionRes, setup) } public class SwitchDrawerItemKt : AbstractSwitchableDrawerItemKt<SwitchDrawerItem>(SwitchDrawerItem())
apache-2.0
84409cbdeabc153eba7ab762169b9f7b
34.516129
102
0.745686
4.568465
false
false
false
false
JetBrains/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/lower/InteropLowering.kt
1
46543
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package org.jetbrains.kotlin.backend.konan.lower import org.jetbrains.kotlin.backend.common.* import org.jetbrains.kotlin.backend.common.ir.allParameters import org.jetbrains.kotlin.backend.common.ir.copyTo import org.jetbrains.kotlin.backend.common.ir.createDispatchReceiverParameter import org.jetbrains.kotlin.backend.common.ir.simpleFunctions import org.jetbrains.kotlin.backend.common.lower.* import org.jetbrains.kotlin.backend.konan.* import org.jetbrains.kotlin.backend.konan.cgen.* import org.jetbrains.kotlin.backend.konan.descriptors.allOverriddenFunctions import org.jetbrains.kotlin.backend.konan.descriptors.synthesizedName import org.jetbrains.kotlin.backend.konan.ir.* import org.jetbrains.kotlin.backend.konan.ir.companionObject import org.jetbrains.kotlin.backend.konan.llvm.IntrinsicType import org.jetbrains.kotlin.backend.konan.llvm.tryGetIntrinsicType import org.jetbrains.kotlin.backend.konan.serialization.resolveFakeOverrideMaybeAbstract import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.IrStatement import org.jetbrains.kotlin.ir.builders.* import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.declarations.impl.IrFunctionImpl import org.jetbrains.kotlin.ir.declarations.impl.IrValueParameterImpl import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.expressions.impl.IrConstImpl import org.jetbrains.kotlin.ir.expressions.impl.IrDelegatingConstructorCallImpl import org.jetbrains.kotlin.ir.expressions.impl.IrFunctionReferenceImpl import org.jetbrains.kotlin.ir.expressions.impl.IrReturnImpl import org.jetbrains.kotlin.ir.symbols.IrClassSymbol import org.jetbrains.kotlin.ir.symbols.IrFunctionSymbol import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol import org.jetbrains.kotlin.ir.symbols.impl.IrSimpleFunctionSymbolImpl import org.jetbrains.kotlin.ir.symbols.impl.IrValueParameterSymbolImpl import org.jetbrains.kotlin.ir.types.* import org.jetbrains.kotlin.ir.util.* import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.konan.ForeignExceptionMode internal class InteropLowering(context: Context) : FileLoweringPass { // TODO: merge these lowerings. private val part1 = InteropLoweringPart1(context) private val part2 = InteropLoweringPart2(context) override fun lower(irFile: IrFile) { part1.lower(irFile) part2.lower(irFile) } } private abstract class BaseInteropIrTransformer(private val context: Context) : IrBuildingTransformer(context) { protected inline fun <T> generateWithStubs(element: IrElement? = null, block: KotlinStubs.() -> T): T = createKotlinStubs(element).block() protected fun createKotlinStubs(element: IrElement?): KotlinStubs { val location = if (element != null) { element.getCompilerMessageLocation(irFile) } else { builder.getCompilerMessageLocation() } val uniqueModuleName = irFile.packageFragmentDescriptor.module.name.asString() .let { it.substring(1, it.lastIndex) } val uniquePrefix = buildString { append('_') uniqueModuleName.toByteArray().joinTo(this, "") { (0xFF and it.toInt()).toString(16).padStart(2, '0') } append('_') } return object : KotlinStubs { override val irBuiltIns get() = context.irBuiltIns override val symbols get() = context.ir.symbols override fun addKotlin(declaration: IrDeclaration) { addTopLevel(declaration) } override fun addC(lines: List<String>) { context.cStubsManager.addStub(location, lines) } override fun getUniqueCName(prefix: String) = "$uniquePrefix${context.cStubsManager.getUniqueName(prefix)}" override fun getUniqueKotlinFunctionReferenceClassName(prefix: String) = "$prefix${context.functionReferenceCount++}" override val target get() = context.config.target override fun throwCompilerError(element: IrElement?, message: String): Nothing { error(irFile, element, message) } override fun renderCompilerError(element: IrElement?, message: String) = renderCompilerError(irFile, element, message) } } protected fun renderCompilerError(element: IrElement?, message: String = "Failed requirement") = renderCompilerError(irFile, element, message) protected abstract val irFile: IrFile protected abstract fun addTopLevel(declaration: IrDeclaration) } private class InteropLoweringPart1(val context: Context) : BaseInteropIrTransformer(context), FileLoweringPass { private val symbols get() = context.ir.symbols lateinit var currentFile: IrFile private val topLevelInitializers = mutableListOf<IrExpression>() private val newTopLevelDeclarations = mutableListOf<IrDeclaration>() override val irFile: IrFile get() = currentFile override fun addTopLevel(declaration: IrDeclaration) { declaration.parent = currentFile newTopLevelDeclarations += declaration } override fun lower(irFile: IrFile) { currentFile = irFile irFile.transformChildrenVoid(this) topLevelInitializers.forEach { irFile.addTopLevelInitializer(it, context, false) } topLevelInitializers.clear() irFile.addChildren(newTopLevelDeclarations) newTopLevelDeclarations.clear() } private fun IrBuilderWithScope.callAlloc(classPtr: IrExpression): IrExpression = irCall(symbols.interopAllocObjCObject).apply { putValueArgument(0, classPtr) } private val outerClasses = mutableListOf<IrClass>() override fun visitClass(declaration: IrClass): IrStatement { if (declaration.isKotlinObjCClass()) { lowerKotlinObjCClass(declaration) } outerClasses.push(declaration) try { return super.visitClass(declaration) } finally { outerClasses.pop() } } private fun lowerKotlinObjCClass(irClass: IrClass) { checkKotlinObjCClass(irClass) val interop = context.interopBuiltIns irClass.declarations.toList().mapNotNull { when { it is IrSimpleFunction && it.annotations.hasAnnotation(interop.objCAction.fqNameSafe) -> generateActionImp(it) it is IrProperty && it.annotations.hasAnnotation(interop.objCOutlet.fqNameSafe) -> generateOutletSetterImp(it) it is IrConstructor && it.isOverrideInit() -> generateOverrideInit(irClass, it) else -> null } }.let { irClass.addChildren(it) } if (irClass.annotations.hasAnnotation(interop.exportObjCClass.fqNameSafe)) { val irBuilder = context.createIrBuilder(currentFile.symbol).at(irClass) topLevelInitializers.add(irBuilder.getObjCClass(symbols, irClass.symbol)) } } private fun IrConstructor.isOverrideInit(): Boolean { if (this.origin != IrDeclarationOrigin.DEFINED) { // Make best efforts to skip generated stubs that might have got annotations // copied from original declarations. // For example, default argument stubs (https://youtrack.jetbrains.com/issue/KT-41910). return false } return this.annotations.hasAnnotation(context.interopBuiltIns.objCOverrideInit.fqNameSafe) } private fun generateOverrideInit(irClass: IrClass, constructor: IrConstructor): IrSimpleFunction { val superClass = irClass.getSuperClassNotAny()!! val superConstructors = superClass.constructors.filter { constructor.overridesConstructor(it) }.toList() val superConstructor = superConstructors.singleOrNull() require(superConstructor != null) { renderCompilerError(constructor) } val initMethod = superConstructor.getObjCInitMethod()!! // Remove fake overrides of this init method, also check for explicit overriding: irClass.declarations.removeAll { if (it is IrSimpleFunction && initMethod.symbol in it.overriddenSymbols) { require(it.isFakeOverride) { renderCompilerError(constructor) } true } else { false } } // Generate `override fun init...(...) = this.initBy(...)`: return IrFunctionImpl( constructor.startOffset, constructor.endOffset, OVERRIDING_INITIALIZER_BY_CONSTRUCTOR, IrSimpleFunctionSymbolImpl(), initMethod.name, DescriptorVisibilities.PUBLIC, Modality.OPEN, irClass.defaultType, isInline = false, isExternal = false, isTailrec = false, isSuspend = false, isExpect = false, isFakeOverride = false, isOperator = false, isInfix = false ).also { result -> result.parent = irClass result.createDispatchReceiverParameter() result.valueParameters += constructor.valueParameters.map { it.copyTo(result) } result.overriddenSymbols += initMethod.symbol result.body = context.createIrBuilder(result.symbol).irBlockBody(result) { +irReturn( irCall(symbols.interopObjCObjectInitBy, listOf(irClass.defaultType)).apply { extensionReceiver = irGet(result.dispatchReceiverParameter!!) putValueArgument(0, irCall(constructor).also { result.valueParameters.forEach { parameter -> it.putValueArgument(parameter.index, irGet(parameter)) } }) } ) } // Ensure it gets correctly recognized by the compiler. require(result.getObjCMethodInfo() != null) { renderCompilerError(constructor) } } } private object OVERRIDING_INITIALIZER_BY_CONSTRUCTOR : IrDeclarationOriginImpl("OVERRIDING_INITIALIZER_BY_CONSTRUCTOR") private fun IrConstructor.overridesConstructor(other: IrConstructor): Boolean { return this.descriptor.valueParameters.size == other.descriptor.valueParameters.size && this.descriptor.valueParameters.all { val otherParameter = other.descriptor.valueParameters[it.index] it.name == otherParameter.name && it.type == otherParameter.type } } private fun generateActionImp(function: IrSimpleFunction): IrSimpleFunction { require(function.extensionReceiverParameter == null) { renderCompilerError(function) } require(function.valueParameters.all { it.type.isObjCObjectType() }) { renderCompilerError(function) } require(function.returnType.isUnit()) { renderCompilerError(function) } return generateFunctionImp(inferObjCSelector(function.descriptor), function) } private fun generateOutletSetterImp(property: IrProperty): IrSimpleFunction { require(property.isVar) { renderCompilerError(property) } require(property.getter?.extensionReceiverParameter == null) { renderCompilerError(property) } require(property.descriptor.type.isObjCObjectType()) { renderCompilerError(property) } val name = property.name.asString() val selector = "set${name.capitalize()}:" return generateFunctionImp(selector, property.setter!!) } private fun getMethodSignatureEncoding(function: IrFunction): String { require(function.extensionReceiverParameter == null) { renderCompilerError(function) } require(function.valueParameters.all { it.type.isObjCObjectType() }) { renderCompilerError(function) } require(function.returnType.isUnit()) { renderCompilerError(function) } // Note: these values are valid for x86_64 and arm64. return when (function.valueParameters.size) { 0 -> "v16@0:8" 1 -> "v24@0:8@16" 2 -> "v32@0:8@16@24" else -> error(irFile, function, "Only 0, 1 or 2 parameters are supported here") } } private fun generateFunctionImp(selector: String, function: IrFunction): IrSimpleFunction { val signatureEncoding = getMethodSignatureEncoding(function) val nativePtrType = context.ir.symbols.nativePtrType val parameterTypes = mutableListOf(nativePtrType) // id self parameterTypes.add(nativePtrType) // SEL _cmd function.valueParameters.mapTo(parameterTypes) { nativePtrType } val newFunction = IrFunctionImpl( function.startOffset, function.endOffset, IrDeclarationOrigin.DEFINED, IrSimpleFunctionSymbolImpl(), ("imp:$selector").synthesizedName, DescriptorVisibilities.PRIVATE, Modality.FINAL, function.returnType, isInline = false, isExternal = false, isTailrec = false, isSuspend = false, isExpect = false, isFakeOverride = false, isOperator = false, isInfix = false ) newFunction.valueParameters += parameterTypes.mapIndexed { index, type -> IrValueParameterImpl( function.startOffset, function.endOffset, IrDeclarationOrigin.DEFINED, IrValueParameterSymbolImpl(), Name.identifier("p$index"), index, type, varargElementType = null, isCrossinline = false, isNoinline = false, isHidden = false, isAssignable = false ).apply { parent = newFunction } } // Annotations to be detected in KotlinObjCClassInfoGenerator: newFunction.annotations += buildSimpleAnnotation(context.irBuiltIns, function.startOffset, function.endOffset, symbols.objCMethodImp.owner, selector, signatureEncoding) val builder = context.createIrBuilder(newFunction.symbol) newFunction.body = builder.irBlockBody(newFunction) { +irCall(function).apply { dispatchReceiver = interpretObjCPointer( irGet(newFunction.valueParameters[0]), function.dispatchReceiverParameter!!.type ) function.valueParameters.forEachIndexed { index, parameter -> putValueArgument(index, interpretObjCPointer( irGet(newFunction.valueParameters[index + 2]), parameter.type ) ) } } } return newFunction } private fun IrBuilderWithScope.interpretObjCPointer(expression: IrExpression, type: IrType): IrExpression { val callee: IrFunctionSymbol = if (type.containsNull()) { symbols.interopInterpretObjCPointerOrNull } else { symbols.interopInterpretObjCPointer } return irCall(callee, listOf(type)).apply { putValueArgument(0, expression) } } private fun IrClass.hasFields() = this.declarations.any { when (it) { is IrField -> it.isReal is IrProperty -> it.isReal && it.backingField != null else -> false } } private fun checkKotlinObjCClass(irClass: IrClass) { val kind = irClass.kind require(kind == ClassKind.CLASS || kind == ClassKind.OBJECT) { renderCompilerError(irClass) } require(irClass.isFinalClass) { renderCompilerError(irClass) } require(irClass.companionObject()?.hasFields() != true) { renderCompilerError(irClass) } require(irClass.companionObject()?.getSuperClassNotAny()?.hasFields() != true) { renderCompilerError(irClass) } var hasObjCClassSupertype = false irClass.descriptor.defaultType.constructor.supertypes.forEach { val descriptor = it.constructor.declarationDescriptor as ClassDescriptor require(descriptor.isObjCClass()) { renderCompilerError(irClass) } if (descriptor.kind == ClassKind.CLASS) { hasObjCClassSupertype = true } } require(hasObjCClassSupertype) { renderCompilerError(irClass) } val methodsOfAny = context.ir.symbols.any.owner.declarations.filterIsInstance<IrSimpleFunction>().toSet() irClass.declarations.filterIsInstance<IrSimpleFunction>().filter { it.isReal }.forEach { method -> val overriddenMethodOfAny = method.allOverriddenFunctions.firstOrNull { it in methodsOfAny } require(overriddenMethodOfAny == null) { renderCompilerError(method) } } } override fun visitDelegatingConstructorCall(expression: IrDelegatingConstructorCall): IrExpression { expression.transformChildrenVoid() builder.at(expression) val constructedClass = outerClasses.peek()!! if (!constructedClass.isObjCClass()) { return expression } constructedClass.parent.let { parent -> if (parent is IrClass && parent.isObjCClass() && constructedClass.isCompanion) { // Note: it is actually not used; getting values of such objects is handled by code generator // in [FunctionGenerationContext.getObjectValue]. return expression } } val delegatingCallConstructingClass = expression.symbol.owner.constructedClass if (!constructedClass.isExternalObjCClass() && delegatingCallConstructingClass.isExternalObjCClass()) { // Calling super constructor from Kotlin Objective-C class. require(constructedClass.getSuperClassNotAny() == delegatingCallConstructingClass) { renderCompilerError(expression) } require(expression.symbol.owner.objCConstructorIsDesignated()) { renderCompilerError(expression) } require(expression.dispatchReceiver == null) { renderCompilerError(expression) } require(expression.extensionReceiver == null) { renderCompilerError(expression) } val initMethod = expression.symbol.owner.getObjCInitMethod()!! val initMethodInfo = initMethod.getExternalObjCMethodInfo()!! val initCall = builder.genLoweredObjCMethodCall( initMethodInfo, superQualifier = delegatingCallConstructingClass.symbol, receiver = builder.irGet(constructedClass.thisReceiver!!), arguments = initMethod.valueParameters.map { expression.getValueArgument(it.index) }, call = expression, method = initMethod ) val superConstructor = delegatingCallConstructingClass .constructors.single { it.valueParameters.size == 0 }.symbol return builder.irBlock(expression) { // Required for the IR to be valid, will be ignored in codegen: +IrDelegatingConstructorCallImpl.fromSymbolDescriptor( startOffset, endOffset, context.irBuiltIns.unitType, superConstructor ) +irCall(symbols.interopObjCObjectSuperInitCheck).apply { extensionReceiver = irGet(constructedClass.thisReceiver!!) putValueArgument(0, initCall) } } } return expression } private fun IrBuilderWithScope.genLoweredObjCMethodCall( info: ObjCMethodInfo, superQualifier: IrClassSymbol?, receiver: IrExpression, arguments: List<IrExpression?>, call: IrFunctionAccessExpression, method: IrSimpleFunction ): IrExpression = genLoweredObjCMethodCall( info = info, superQualifier = superQualifier, receiver = ObjCCallReceiver.Regular(rawPtr = getRawPtr(receiver)), arguments = arguments, call = call, method = method ) private fun IrBuilderWithScope.genLoweredObjCMethodCall( info: ObjCMethodInfo, superQualifier: IrClassSymbol?, receiver: ObjCCallReceiver, arguments: List<IrExpression?>, call: IrFunctionAccessExpression, method: IrSimpleFunction ): IrExpression = generateWithStubs(call) { if (method.parent !is IrClass) { // Category-provided. [email protected](method.llvmSymbolOrigin) } this.generateObjCCall( this@genLoweredObjCMethodCall, method, info.isStret, info.selector, call, superQualifier, receiver, arguments ) } override fun visitConstructorCall(expression: IrConstructorCall): IrExpression { expression.transformChildrenVoid() val callee = expression.symbol.owner val initMethod = callee.getObjCInitMethod() if (initMethod != null) { val arguments = callee.valueParameters.map { expression.getValueArgument(it.index) } require(expression.extensionReceiver == null) { renderCompilerError(expression) } require(expression.dispatchReceiver == null) { renderCompilerError(expression) } val constructedClass = callee.constructedClass val initMethodInfo = initMethod.getExternalObjCMethodInfo()!! return builder.at(expression).run { val classPtr = getObjCClass(symbols, constructedClass.symbol) ensureObjCReferenceNotNull(callAllocAndInit(classPtr, initMethodInfo, arguments, expression, initMethod)) } } return expression } private fun IrBuilderWithScope.ensureObjCReferenceNotNull(expression: IrExpression): IrExpression = if (!expression.type.containsNull()) { expression } else { irBlock(resultType = expression.type) { val temp = irTemporary(expression) +irIfThen( context.irBuiltIns.unitType, irEqeqeq(irGet(temp), irNull()), irCall(symbols.throwNullPointerException) ) +irGet(temp) } } override fun visitCall(expression: IrCall): IrExpression { expression.transformChildrenVoid() val callee = expression.symbol.owner callee.getObjCFactoryInitMethodInfo()?.let { initMethodInfo -> val arguments = (0 until expression.valueArgumentsCount) .map { index -> expression.getValueArgument(index) } return builder.at(expression).run { val classPtr = getRawPtr(expression.extensionReceiver!!) callAllocAndInit(classPtr, initMethodInfo, arguments, expression, callee) } } callee.getExternalObjCMethodInfo()?.let { methodInfo -> val isInteropStubsFile = currentFile.annotations.hasAnnotation(FqName("kotlinx.cinterop.InteropStubs")) // Special case: bridge from Objective-C method implementation template to Kotlin method; // handled in CodeGeneratorVisitor.callVirtual. val useKotlinDispatch = isInteropStubsFile && (builder.scope.scopeOwnerSymbol.owner as? IrAnnotationContainer) ?.hasAnnotation(FqName("kotlin.native.internal.ExportForCppRuntime")) == true if (!useKotlinDispatch) { val arguments = callee.valueParameters.map { expression.getValueArgument(it.index) } require(expression.dispatchReceiver == null || expression.extensionReceiver == null) { renderCompilerError(expression) } require(expression.superQualifierSymbol?.owner?.isObjCMetaClass() != true) { renderCompilerError(expression) } require(expression.superQualifierSymbol?.owner?.isInterface != true) { renderCompilerError(expression) } builder.at(expression) return builder.genLoweredObjCMethodCall( methodInfo, superQualifier = expression.superQualifierSymbol, receiver = expression.dispatchReceiver ?: expression.extensionReceiver!!, arguments = arguments, call = expression, method = callee ) } } return when (callee.symbol) { symbols.interopTypeOf -> { val typeArgument = expression.getSingleTypeArgument() val classSymbol = typeArgument.classifierOrNull as? IrClassSymbol if (classSymbol == null) { expression } else { val irClass = classSymbol.owner val companionObject = irClass.companionObject() ?: error(irFile, expression, "native variable class ${irClass.descriptor} must have the companion object") builder.at(expression).irGetObject(companionObject.symbol) } } else -> expression } } override fun visitProperty(declaration: IrProperty): IrStatement { val backingField = declaration.backingField return if (declaration.isConst && backingField?.isStatic == true && context.config.isInteropStubs) { // Transform top-level `const val x = 42` to `val x get() = 42`. // Generally this transformation is just an optimization to ensure that interop constants // don't require any storage and/or initialization at program startup. // Also it is useful due to uncertain design of top-level stored properties in Kotlin/Native. val initializer = backingField.initializer!!.expression declaration.backingField = null val getter = declaration.getter!! val getterBody = getter.body!! as IrBlockBody getterBody.statements.clear() getterBody.statements += IrReturnImpl( declaration.startOffset, declaration.endOffset, context.irBuiltIns.nothingType, getter.symbol, initializer ) // Note: in interop stubs const val initializer is either `IrConst` or quite simple expression, // so it is ok to compute it every time. require(declaration.setter == null) { renderCompilerError(declaration) } require(!declaration.isVar) { renderCompilerError(declaration) } declaration.transformChildrenVoid() declaration } else { super.visitProperty(declaration) } } private fun IrBuilderWithScope.callAllocAndInit( classPtr: IrExpression, initMethodInfo: ObjCMethodInfo, arguments: List<IrExpression?>, call: IrFunctionAccessExpression, initMethod: IrSimpleFunction ): IrExpression = genLoweredObjCMethodCall( initMethodInfo, superQualifier = null, receiver = ObjCCallReceiver.Retained(rawPtr = callAlloc(classPtr)), arguments = arguments, call = call, method = initMethod ) private fun IrBuilderWithScope.getRawPtr(receiver: IrExpression) = irCall(symbols.interopObjCObjectRawValueGetter).apply { extensionReceiver = receiver } } /** * Lowers some interop intrinsic calls. */ private class InteropLoweringPart2(val context: Context) : FileLoweringPass { override fun lower(irFile: IrFile) { val transformer = InteropTransformer(context, irFile) irFile.transformChildrenVoid(transformer) while (transformer.newTopLevelDeclarations.isNotEmpty()) { val newTopLevelDeclarations = transformer.newTopLevelDeclarations.toList() transformer.newTopLevelDeclarations.clear() // Assuming these declarations contain only new IR (i.e. existing lowered IR has not been moved there). // TODO: make this more reliable. val loweredNewTopLevelDeclarations = newTopLevelDeclarations.map { it.transform(transformer, null) as IrDeclaration } irFile.addChildren(loweredNewTopLevelDeclarations) } } } private class InteropTransformer(val context: Context, override val irFile: IrFile) : BaseInteropIrTransformer(context) { val newTopLevelDeclarations = mutableListOf<IrDeclaration>() val interop = context.interopBuiltIns val symbols = context.ir.symbols override fun addTopLevel(declaration: IrDeclaration) { declaration.parent = irFile newTopLevelDeclarations += declaration } override fun visitClass(declaration: IrClass): IrStatement { super.visitClass(declaration) if (declaration.isKotlinObjCClass()) { val uniq = mutableSetOf<String>() // remove duplicates [KT-38234] val imps = declaration.simpleFunctions().filter { it.isReal }.flatMap { function -> function.overriddenSymbols.mapNotNull { val selector = it.owner.getExternalObjCMethodInfo()?.selector if (selector == null || selector in uniq) { null } else { uniq += selector generateWithStubs(it.owner) { generateCFunctionAndFakeKotlinExternalFunction( function, it.owner, isObjCMethod = true, location = function ) } } } } declaration.addChildren(imps) } return declaration } private fun generateCFunctionPointer(function: IrSimpleFunction, expression: IrExpression): IrExpression = generateWithStubs { generateCFunctionPointer(function, function, expression) } override fun visitConstructorCall(expression: IrConstructorCall): IrExpression { expression.transformChildrenVoid(this) val callee = expression.symbol.owner val inlinedClass = callee.returnType.getInlinedClassNative() require(inlinedClass?.descriptor != interop.cPointer) { renderCompilerError(expression) } require(inlinedClass?.descriptor != interop.nativePointed) { renderCompilerError(expression) } val constructedClass = callee.constructedClass if (!constructedClass.isObjCClass()) return expression // Calls to other ObjC class constructors must be lowered. require(constructedClass.isKotlinObjCClass()) { renderCompilerError(expression) } return builder.at(expression).irBlock { val rawPtr = irTemporary(irCall(symbols.interopAllocObjCObject.owner).apply { putValueArgument(0, getObjCClass(symbols, constructedClass.symbol)) }) val instance = irTemporary(irCall(symbols.interopInterpretObjCPointer.owner).apply { putValueArgument(0, irGet(rawPtr)) }) // Balance pointer retained by alloc: +irCall(symbols.interopObjCRelease.owner).apply { putValueArgument(0, irGet(rawPtr)) } +irCall(symbols.initInstance).apply { putValueArgument(0, irGet(instance)) putValueArgument(1, expression) } +irGet(instance) } } /** * Handle `const val`s that come from interop libraries. * * We extract constant value from the backing field, and replace getter invocation with it. */ private fun tryGenerateInteropConstantRead(expression: IrCall): IrExpression? { val function = expression.symbol.owner if (!function.isFromInteropLibrary()) return null if (!function.isGetter) return null val constantProperty = (function as? IrSimpleFunction) ?.correspondingPropertySymbol ?.owner ?.takeIf { it.isConst } ?: return null val initializer = constantProperty.backingField?.initializer?.expression require(initializer is IrConst<*>) { renderCompilerError(expression) } // Avoid node duplication return initializer.copy() } override fun visitCall(expression: IrCall): IrExpression { val intrinsicType = tryGetIntrinsicType(expression) if (intrinsicType == IntrinsicType.OBJC_INIT_BY) { // Need to do this separately as otherwise [expression.transformChildrenVoid(this)] would be called // and the [IrConstructorCall] would be transformed which is not what we want. val argument = expression.getValueArgument(0)!! require(argument is IrConstructorCall) { renderCompilerError(argument) } val constructedClass = argument.symbol.owner.constructedClass val extensionReceiver = expression.extensionReceiver!! require(extensionReceiver is IrGetValue && extensionReceiver.symbol.owner.isDispatchReceiverFor(constructedClass)) { renderCompilerError(extensionReceiver) } argument.transformChildrenVoid(this) return builder.at(expression).irBlock { val instance = extensionReceiver.symbol.owner +irCall(symbols.initInstance).apply { putValueArgument(0, irGet(instance)) putValueArgument(1, argument) } +irGet(instance) } } expression.transformChildrenVoid(this) builder.at(expression) val function = expression.symbol.owner if ((function as? IrSimpleFunction)?.resolveFakeOverrideMaybeAbstract()?.symbol == symbols.interopNativePointedRawPtrGetter) { // Replace by the intrinsic call to be handled by code generator: return builder.irCall(symbols.interopNativePointedGetRawPointer).apply { extensionReceiver = expression.dispatchReceiver } } if (function.annotations.hasAnnotation(RuntimeNames.cCall)) { context.llvmImports.add(function.llvmSymbolOrigin) val exceptionMode = ForeignExceptionMode.byValue( function.konanLibrary?.manifestProperties?.getProperty(ForeignExceptionMode.manifestKey) ) return generateWithStubs { generateCCall(expression, builder, isInvoke = false, exceptionMode) } } val failCompilation = { msg: String -> error(irFile, expression, msg) } tryGenerateInteropMemberAccess(expression, symbols, builder, failCompilation)?.let { return it } tryGenerateInteropConstantRead(expression)?.let { return it } if (intrinsicType != null) { return when (intrinsicType) { IntrinsicType.INTEROP_BITS_TO_FLOAT -> { val argument = expression.getValueArgument(0) if (argument is IrConst<*> && argument.kind == IrConstKind.Int) { val floatValue = kotlinx.cinterop.bitsToFloat(argument.value as Int) builder.irFloat(floatValue) } else { expression } } IntrinsicType.INTEROP_BITS_TO_DOUBLE -> { val argument = expression.getValueArgument(0) if (argument is IrConst<*> && argument.kind == IrConstKind.Long) { val doubleValue = kotlinx.cinterop.bitsToDouble(argument.value as Long) builder.irDouble(doubleValue) } else { expression } } IntrinsicType.INTEROP_STATIC_C_FUNCTION -> { val irCallableReference = unwrapStaticFunctionArgument(expression.getValueArgument(0)!!) require(irCallableReference != null && irCallableReference.getArguments().isEmpty() && irCallableReference.symbol is IrSimpleFunctionSymbol) { renderCompilerError(expression) } val targetSymbol = irCallableReference.symbol val target = targetSymbol.owner val signatureTypes = target.allParameters.map { it.type } + target.returnType function.typeParameters.indices.forEach { index -> val typeArgument = expression.getTypeArgument(index)!!.toKotlinType() val signatureType = signatureTypes[index].toKotlinType() require(typeArgument.constructor == signatureType.constructor && typeArgument.isMarkedNullable == signatureType.isMarkedNullable) { renderCompilerError(expression) } } generateCFunctionPointer(target as IrSimpleFunction, expression) } IntrinsicType.INTEROP_FUNPTR_INVOKE -> { generateWithStubs { generateCCall(expression, builder, isInvoke = true) } } IntrinsicType.INTEROP_SIGN_EXTEND, IntrinsicType.INTEROP_NARROW -> { val integerTypePredicates = arrayOf( IrType::isByte, IrType::isShort, IrType::isInt, IrType::isLong ) val receiver = expression.extensionReceiver!! val typeOperand = expression.getSingleTypeArgument() val receiverTypeIndex = integerTypePredicates.indexOfFirst { it(receiver.type) } val typeOperandIndex = integerTypePredicates.indexOfFirst { it(typeOperand) } require(receiverTypeIndex >= 0) { renderCompilerError(receiver) } require(typeOperandIndex >= 0) { renderCompilerError(expression) } when (intrinsicType) { IntrinsicType.INTEROP_SIGN_EXTEND -> require(receiverTypeIndex <= typeOperandIndex) { renderCompilerError(expression) } IntrinsicType.INTEROP_NARROW -> require(receiverTypeIndex >= typeOperandIndex) { renderCompilerError(expression) } else -> error(intrinsicType) } val receiverClass = symbols.integerClasses.single { receiver.type.isSubtypeOf(it.owner.defaultType) } val targetClass = symbols.integerClasses.single { typeOperand.isSubtypeOf(it.owner.defaultType) } val conversionSymbol = receiverClass.functions.single { it.owner.name == Name.identifier("to${targetClass.owner.name}") } builder.irCall(conversionSymbol).apply { dispatchReceiver = receiver } } IntrinsicType.INTEROP_CONVERT -> { val integerClasses = symbols.allIntegerClasses val typeOperand = expression.getTypeArgument(0)!! val receiverType = expression.symbol.owner.extensionReceiverParameter!!.type val source = receiverType.classifierOrFail as IrClassSymbol require(source in integerClasses) { renderCompilerError(expression) } require(typeOperand is IrSimpleType && typeOperand.classifier in integerClasses && !typeOperand.hasQuestionMark) { renderCompilerError(expression) } val target = typeOperand.classifier as IrClassSymbol val valueToConvert = expression.extensionReceiver!! if (source in symbols.signedIntegerClasses && target in symbols.unsignedIntegerClasses) { // Default Kotlin signed-to-unsigned widening integer conversions don't follow C rules. val signedTarget = symbols.unsignedToSignedOfSameBitWidth[target]!! val widened = builder.irConvertInteger(source, signedTarget, valueToConvert) builder.irConvertInteger(signedTarget, target, widened) } else { builder.irConvertInteger(source, target, valueToConvert) } } IntrinsicType.INTEROP_MEMORY_COPY -> { TODO("So far unsupported") } IntrinsicType.WORKER_EXECUTE -> { val irCallableReference = unwrapStaticFunctionArgument(expression.getValueArgument(2)!!) require(irCallableReference != null && irCallableReference.getArguments().isEmpty()) { renderCompilerError(expression) } val targetSymbol = irCallableReference.symbol val jobPointer = IrFunctionReferenceImpl.fromSymbolDescriptor( builder.startOffset, builder.endOffset, symbols.executeImpl.owner.valueParameters[3].type, targetSymbol, typeArgumentsCount = 0, reflectionTarget = null) builder.irCall(symbols.executeImpl).apply { putValueArgument(0, expression.dispatchReceiver) putValueArgument(1, expression.getValueArgument(0)) putValueArgument(2, expression.getValueArgument(1)) putValueArgument(3, jobPointer) } } else -> expression } } return when (function) { symbols.interopCPointerRawValue.owner.getter -> // Replace by the intrinsic call to be handled by code generator: builder.irCall(symbols.interopCPointerGetRawValue).apply { extensionReceiver = expression.dispatchReceiver } else -> expression } } private fun IrBuilderWithScope.irConvertInteger( source: IrClassSymbol, target: IrClassSymbol, value: IrExpression ): IrExpression { val conversion = symbols.integerConversions[source to target]!! return irCall(conversion.owner).apply { if (conversion.owner.dispatchReceiverParameter != null) { dispatchReceiver = value } else { extensionReceiver = value } } } private fun unwrapStaticFunctionArgument(argument: IrExpression): IrFunctionReference? { if (argument is IrFunctionReference) { return argument } // Otherwise check whether it is a lambda: // 1. It is a container with two statements and expected origin: if (argument !is IrContainerExpression || argument.statements.size != 2) { return null } if (argument.origin != IrStatementOrigin.LAMBDA && argument.origin != IrStatementOrigin.ANONYMOUS_FUNCTION) { return null } // 2. First statement is an empty container (created during local functions lowering): val firstStatement = argument.statements.first() if (firstStatement !is IrContainerExpression || firstStatement.statements.size != 0) { return null } // 3. Second statement is IrCallableReference: return argument.statements.last() as? IrFunctionReference } val IrValueParameter.isDispatchReceiver: Boolean get() = when(val parent = this.parent) { is IrClass -> true is IrFunction -> parent.dispatchReceiverParameter == this else -> false } private fun IrValueDeclaration.isDispatchReceiverFor(irClass: IrClass): Boolean = this is IrValueParameter && isDispatchReceiver && type.getClass() == irClass } private fun IrCall.getSingleTypeArgument(): IrType { val typeParameter = symbol.owner.typeParameters.single() return getTypeArgument(typeParameter.index)!! } private fun IrBuilder.irFloat(value: Float) = IrConstImpl.float(startOffset, endOffset, context.irBuiltIns.floatType, value) private fun IrBuilder.irDouble(value: Double) = IrConstImpl.double(startOffset, endOffset, context.irBuiltIns.doubleType, value)
apache-2.0
f4aa7cad1be01dc83197099e54f879ce
42.215413
136
0.616784
5.659411
false
false
false
false
vovagrechka/fucking-everything
attic/alraune/alraune-back-very-old/src/zzz.kt
1
1410
package alraune.back import vgrechka.* import kotlin.properties.Delegates.notNull import kotlin.reflect.KMutableProperty1 //val AlUserRepository.dropTableDDL get() = buildString { // ln("drop table if exists `alraune_users`") //} // //val AlUserRepository.createTableDDL get() = buildString { // ln("create table `alraune_users` (") // ln(" id bigint not null auto_increment primary key,") // ln(" alUser_common_createdAt datetime not null,") // ln(" alUser_common_updatedAt datetime not null,") // ln(" alUser_common_deleted boolean not null,") // ln(" alUser_firstName longtext not null,") // ln(" alUser_email longtext not null,") // ln(" alUser_lastName longtext not null,") // ln(" alUser_passwordHash longtext not null,") // ln(" alUser_profilePhone longtext not null,") // ln(" alUser_adminNotes longtext not null,") // ln(" alUser_aboutMe longtext not null,") // ln(" alUser_profileRejectionReason longtext,") // ln(" alUser_banReason longtext,") // ln(" alUser_subscribedToAllCategories boolean not null") // ln(") engine=InnoDB") //} //fun AlUserRepository.propertyToColumnName(prop: KMutableProperty1<AlUser, String>): String { // if (prop.name == AlUser::passwordHash.name) return "alUser_passwordHash" // throw Exception("TODO: Generate 59e545e8-7042-4978-bea2-a2e48d6d290e") //}
apache-2.0
4db1c883ee21e502d2b16580c4a8ab2f
28.375
94
0.670213
3.551637
false
false
false
false
androidx/androidx
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens/SuggestionChipTokens.kt
3
2865
/* * 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. */ // VERSION: v0_117 // GENERATED CODE - DO NOT MODIFY BY HAND package androidx.compose.material3.tokens import androidx.compose.ui.unit.dp internal object SuggestionChipTokens { val ContainerHeight = 32.0.dp val ContainerShape = ShapeKeyTokens.CornerSmall val ContainerSurfaceTintLayerColor = ColorSchemeKeyTokens.SurfaceTint val DisabledLabelTextColor = ColorSchemeKeyTokens.OnSurface const val DisabledLabelTextOpacity = 0.38f val DraggedContainerElevation = ElevationTokens.Level4 val DraggedLabelTextColor = ColorSchemeKeyTokens.OnSurfaceVariant val ElevatedContainerColor = ColorSchemeKeyTokens.Surface val ElevatedContainerElevation = ElevationTokens.Level1 val ElevatedDisabledContainerColor = ColorSchemeKeyTokens.OnSurface val ElevatedDisabledContainerElevation = ElevationTokens.Level0 const val ElevatedDisabledContainerOpacity = 0.12f val ElevatedFocusContainerElevation = ElevationTokens.Level1 val ElevatedHoverContainerElevation = ElevationTokens.Level2 val ElevatedPressedContainerElevation = ElevationTokens.Level1 val FlatContainerElevation = ElevationTokens.Level0 val FlatDisabledOutlineColor = ColorSchemeKeyTokens.OnSurface const val FlatDisabledOutlineOpacity = 0.12f val FlatFocusOutlineColor = ColorSchemeKeyTokens.OnSurfaceVariant val FlatOutlineColor = ColorSchemeKeyTokens.Outline val FlatOutlineWidth = 1.0.dp val FocusLabelTextColor = ColorSchemeKeyTokens.OnSurfaceVariant val HoverLabelTextColor = ColorSchemeKeyTokens.OnSurfaceVariant val LabelTextColor = ColorSchemeKeyTokens.OnSurfaceVariant val LabelTextFont = TypographyKeyTokens.LabelLarge val PressedLabelTextColor = ColorSchemeKeyTokens.OnSurfaceVariant val DisabledLeadingIconColor = ColorSchemeKeyTokens.OnSurface const val DisabledLeadingIconOpacity = 0.38f val DraggedLeadingIconColor = ColorSchemeKeyTokens.OnSurfaceVariant val FocusLeadingIconColor = ColorSchemeKeyTokens.OnSurfaceVariant val HoverLeadingIconColor = ColorSchemeKeyTokens.OnSurfaceVariant val LeadingIconColor = ColorSchemeKeyTokens.OnSurfaceVariant val LeadingIconSize = 18.0.dp val PressedLeadingIconColor = ColorSchemeKeyTokens.OnSurfaceVariant }
apache-2.0
f2edd134a39352f3064a1f9d84bf6eab
48.396552
75
0.809075
5.552326
false
false
false
false
androidx/androidx
compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/awt/ComposePanel.desktop.kt
3
4344
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.awt import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import org.jetbrains.skiko.ClipComponent import org.jetbrains.skiko.GraphicsApi import java.awt.Color import java.awt.Component import java.awt.Dimension import javax.swing.JLayeredPane import javax.swing.SwingUtilities.isEventDispatchThread /** * ComposePanel is a panel for building UI using Compose for Desktop. */ class ComposePanel : JLayeredPane() { init { check(isEventDispatchThread()) { "ComposePanel should be created inside AWT Event Dispatch Thread" + " (use SwingUtilities.invokeLater).\n" + "Creating from another thread isn't supported." } setBackground(Color.white) setLayout(null) } internal var layer: ComposeLayer? = null private val clipMap = mutableMapOf<Component, ClipComponent>() private var content: (@Composable () -> Unit)? = null override fun setBounds(x: Int, y: Int, width: Int, height: Int) { layer?.component?.setSize(width, height) super.setBounds(x, y, width, height) } override fun getPreferredSize(): Dimension? { return if (isPreferredSizeSet) super.getPreferredSize() else layer?.component?.preferredSize } /** * Sets Compose content of the ComposePanel. * * @param content Composable content of the ComposePanel. */ fun setContent(content: @Composable () -> Unit) { // The window (or root container) may not be ready to render composable content, so we need // to keep the lambda describing composable content and set the content only when // everything is ready to avoid accidental crashes and memory leaks on all supported OS // types. this.content = content initContent() } private fun initContent() { if (layer != null && content != null) { layer!!.setContent { CompositionLocalProvider( LocalLayerContainer provides this, content = content!! ) } } } override fun add(component: Component): Component { if (layer == null) { return component } val clipComponent = ClipComponent(component) clipMap.put(component, clipComponent) layer!!.component.clipComponents.add(clipComponent) return super.add(component, Integer.valueOf(0)) } override fun remove(component: Component) { layer!!.component.clipComponents.remove(clipMap.get(component)!!) clipMap.remove(component) super.remove(component) } override fun addNotify() { super.addNotify() // After [super.addNotify] is called we can safely initialize the layer and composable // content. layer = ComposeLayer().apply { component.setSize(width, height) } initContent() super.add(layer!!.component, Integer.valueOf(1)) } override fun removeNotify() { if (layer != null) { layer!!.dispose() super.remove(layer!!.component) } super.removeNotify() } override fun requestFocus() { if (layer != null) { layer!!.component.requestFocus() } } /** * Returns low-level rendering API used for rendering in this ComposeWindow. API is * automatically selected based on operating system, graphical hardware and `SKIKO_RENDER_API` * environment variable. */ val renderApi: GraphicsApi get() = if (layer != null) layer!!.component.renderApi else GraphicsApi.UNKNOWN }
apache-2.0
f8c38fcb59d0ba301ed726f4509cb13c
32.415385
100
0.650092
4.721739
false
false
false
false
androidx/androidx
compose/ui/ui-graphics/src/skikoMain/kotlin/androidx/compose/ui/graphics/SkiaShader.skiko.kt
3
2851
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.graphics import androidx.compose.ui.geometry.Offset import org.jetbrains.skia.GradientStyle actual typealias Shader = org.jetbrains.skia.Shader internal actual fun ActualLinearGradientShader( from: Offset, to: Offset, colors: List<Color>, colorStops: List<Float>?, tileMode: TileMode ): Shader { validateColorStops(colors, colorStops) return Shader.makeLinearGradient( from.x, from.y, to.x, to.y, colors.toIntArray(), colorStops?.toFloatArray(), GradientStyle(tileMode.toSkiaTileMode(), true, identityMatrix33()) ) } internal actual fun ActualRadialGradientShader( center: Offset, radius: Float, colors: List<Color>, colorStops: List<Float>?, tileMode: TileMode ): Shader { validateColorStops(colors, colorStops) return Shader.makeRadialGradient( center.x, center.y, radius, colors.toIntArray(), colorStops?.toFloatArray(), GradientStyle(tileMode.toSkiaTileMode(), true, identityMatrix33()) ) } internal actual fun ActualSweepGradientShader( center: Offset, colors: List<Color>, colorStops: List<Float>? ): Shader { validateColorStops(colors, colorStops) return Shader.makeSweepGradient( center.x, center.y, colors.toIntArray(), colorStops?.toFloatArray() ) } internal actual fun ActualImageShader( image: ImageBitmap, tileModeX: TileMode, tileModeY: TileMode ): Shader { return image.asSkiaBitmap().makeShader( tileModeX.toSkiaTileMode(), tileModeY.toSkiaTileMode() ) } private fun List<Color>.toIntArray(): IntArray = IntArray(size) { i -> this[i].toArgb() } private fun validateColorStops(colors: List<Color>, colorStops: List<Float>?) { if (colorStops == null) { if (colors.size < 2) { throw IllegalArgumentException( "colors must have length of at least 2 if colorStops " + "is omitted." ) } } else if (colors.size != colorStops.size) { throw IllegalArgumentException( "colors and colorStops arguments must have" + " equal length." ) } }
apache-2.0
7e41619115bf16fc2e071ffecaead03b
28.102041
84
0.669239
4.306647
false
false
false
false
androidx/androidx
compose/material/material/src/commonMain/kotlin/androidx/compose/material/Swipeable.kt
3
35237
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.AnimationSpec import androidx.compose.animation.core.SpringSpec import androidx.compose.foundation.gestures.DraggableState import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.draggable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.material.SwipeableDefaults.AnimationSpec import androidx.compose.material.SwipeableDefaults.StandardResistanceFactor import androidx.compose.material.SwipeableDefaults.VelocityThreshold import androidx.compose.material.SwipeableDefaults.resistanceConfig import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.Immutable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.State import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.nestedscroll.NestedScrollConnection import androidx.compose.ui.input.nestedscroll.NestedScrollSource import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.debugInspectorInfo import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.Velocity import androidx.compose.ui.unit.dp import androidx.compose.ui.util.lerp import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.take import kotlinx.coroutines.launch import kotlin.math.PI import kotlin.math.abs import kotlin.math.sign import kotlin.math.sin /** * State of the [swipeable] modifier. * * This contains necessary information about any ongoing swipe or animation and provides methods * to change the state either immediately or by starting an animation. To create and remember a * [SwipeableState] with the default animation clock, use [rememberSwipeableState]. * * @param initialValue The initial value of the state. * @param animationSpec The default animation that will be used to animate to a new state. * @param confirmStateChange Optional callback invoked to confirm or veto a pending state change. */ @Stable @ExperimentalMaterialApi open class SwipeableState<T>( initialValue: T, internal val animationSpec: AnimationSpec<Float> = AnimationSpec, internal val confirmStateChange: (newValue: T) -> Boolean = { true } ) { /** * The current value of the state. * * If no swipe or animation is in progress, this corresponds to the anchor at which the * [swipeable] is currently settled. If a swipe or animation is in progress, this corresponds * the last anchor at which the [swipeable] was settled before the swipe or animation started. */ var currentValue: T by mutableStateOf(initialValue) private set /** * Whether the state is currently animating. */ var isAnimationRunning: Boolean by mutableStateOf(false) private set /** * The current position (in pixels) of the [swipeable]. * * You should use this state to offset your content accordingly. The recommended way is to * use `Modifier.offsetPx`. This includes the resistance by default, if resistance is enabled. */ val offset: State<Float> get() = offsetState /** * The amount by which the [swipeable] has been swiped past its bounds. */ val overflow: State<Float> get() = overflowState // Use `Float.NaN` as a placeholder while the state is uninitialised. private val offsetState = mutableStateOf(0f) private val overflowState = mutableStateOf(0f) // the source of truth for the "real"(non ui) position // basically position in bounds + overflow private val absoluteOffset = mutableStateOf(0f) // current animation target, if animating, otherwise null private val animationTarget = mutableStateOf<Float?>(null) internal var anchors by mutableStateOf(emptyMap<Float, T>()) private val latestNonEmptyAnchorsFlow: Flow<Map<Float, T>> = snapshotFlow { anchors } .filter { it.isNotEmpty() } .take(1) internal var minBound = Float.NEGATIVE_INFINITY internal var maxBound = Float.POSITIVE_INFINITY internal fun ensureInit(newAnchors: Map<Float, T>) { if (anchors.isEmpty()) { // need to do initial synchronization synchronously :( val initialOffset = newAnchors.getOffset(currentValue) requireNotNull(initialOffset) { "The initial value must have an associated anchor." } offsetState.value = initialOffset absoluteOffset.value = initialOffset } } internal suspend fun processNewAnchors( oldAnchors: Map<Float, T>, newAnchors: Map<Float, T> ) { if (oldAnchors.isEmpty()) { // If this is the first time that we receive anchors, then we need to initialise // the state so we snap to the offset associated to the initial value. minBound = newAnchors.keys.minOrNull()!! maxBound = newAnchors.keys.maxOrNull()!! val initialOffset = newAnchors.getOffset(currentValue) requireNotNull(initialOffset) { "The initial value must have an associated anchor." } snapInternalToOffset(initialOffset) } else if (newAnchors != oldAnchors) { // If we have received new anchors, then the offset of the current value might // have changed, so we need to animate to the new offset. If the current value // has been removed from the anchors then we animate to the closest anchor // instead. Note that this stops any ongoing animation. minBound = Float.NEGATIVE_INFINITY maxBound = Float.POSITIVE_INFINITY val animationTargetValue = animationTarget.value // if we're in the animation already, let's find it a new home val targetOffset = if (animationTargetValue != null) { // first, try to map old state to the new state val oldState = oldAnchors[animationTargetValue] val newState = newAnchors.getOffset(oldState) // return new state if exists, or find the closes one among new anchors newState ?: newAnchors.keys.minByOrNull { abs(it - animationTargetValue) }!! } else { // we're not animating, proceed by finding the new anchors for an old value val actualOldValue = oldAnchors[offset.value] val value = if (actualOldValue == currentValue) currentValue else actualOldValue newAnchors.getOffset(value) ?: newAnchors .keys.minByOrNull { abs(it - offset.value) }!! } try { animateInternalToOffset(targetOffset, animationSpec) } catch (c: CancellationException) { // If the animation was interrupted for any reason, snap as a last resort. snapInternalToOffset(targetOffset) } finally { currentValue = newAnchors.getValue(targetOffset) minBound = newAnchors.keys.minOrNull()!! maxBound = newAnchors.keys.maxOrNull()!! } } } internal var thresholds: (Float, Float) -> Float by mutableStateOf({ _, _ -> 0f }) internal var velocityThreshold by mutableStateOf(0f) internal var resistance: ResistanceConfig? by mutableStateOf(null) internal val draggableState = DraggableState { val newAbsolute = absoluteOffset.value + it val clamped = newAbsolute.coerceIn(minBound, maxBound) val overflow = newAbsolute - clamped val resistanceDelta = resistance?.computeResistance(overflow) ?: 0f offsetState.value = clamped + resistanceDelta overflowState.value = overflow absoluteOffset.value = newAbsolute } private suspend fun snapInternalToOffset(target: Float) { draggableState.drag { dragBy(target - absoluteOffset.value) } } private suspend fun animateInternalToOffset(target: Float, spec: AnimationSpec<Float>) { draggableState.drag { var prevValue = absoluteOffset.value animationTarget.value = target isAnimationRunning = true try { Animatable(prevValue).animateTo(target, spec) { dragBy(this.value - prevValue) prevValue = this.value } } finally { animationTarget.value = null isAnimationRunning = false } } } /** * The target value of the state. * * If a swipe is in progress, this is the value that the [swipeable] would animate to if the * swipe finished. If an animation is running, this is the target value of that animation. * Finally, if no swipe or animation is in progress, this is the same as the [currentValue]. */ @ExperimentalMaterialApi val targetValue: T get() { // TODO(calintat): Track current velocity (b/149549482) and use that here. val target = animationTarget.value ?: computeTarget( offset = offset.value, lastValue = anchors.getOffset(currentValue) ?: offset.value, anchors = anchors.keys, thresholds = thresholds, velocity = 0f, velocityThreshold = Float.POSITIVE_INFINITY ) return anchors[target] ?: currentValue } /** * Information about the ongoing swipe or animation, if any. See [SwipeProgress] for details. * * If no swipe or animation is in progress, this returns `SwipeProgress(value, value, 1f)`. */ @ExperimentalMaterialApi val progress: SwipeProgress<T> get() { val bounds = findBounds(offset.value, anchors.keys) val from: T val to: T val fraction: Float when (bounds.size) { 0 -> { from = currentValue to = currentValue fraction = 1f } 1 -> { from = anchors.getValue(bounds[0]) to = anchors.getValue(bounds[0]) fraction = 1f } else -> { val (a, b) = if (direction > 0f) { bounds[0] to bounds[1] } else { bounds[1] to bounds[0] } from = anchors.getValue(a) to = anchors.getValue(b) fraction = (offset.value - a) / (b - a) } } return SwipeProgress(from, to, fraction) } /** * The direction in which the [swipeable] is moving, relative to the current [currentValue]. * * This will be either 1f if it is is moving from left to right or top to bottom, -1f if it is * moving from right to left or bottom to top, or 0f if no swipe or animation is in progress. */ @ExperimentalMaterialApi val direction: Float get() = anchors.getOffset(currentValue)?.let { sign(offset.value - it) } ?: 0f /** * Set the state without any animation and suspend until it's set * * @param targetValue The new target value to set [currentValue] to. */ @ExperimentalMaterialApi suspend fun snapTo(targetValue: T) { latestNonEmptyAnchorsFlow.collect { anchors -> val targetOffset = anchors.getOffset(targetValue) requireNotNull(targetOffset) { "The target value must have an associated anchor." } snapInternalToOffset(targetOffset) currentValue = targetValue } } /** * Set the state to the target value by starting an animation. * * @param targetValue The new value to animate to. * @param anim The animation that will be used to animate to the new value. */ @ExperimentalMaterialApi suspend fun animateTo(targetValue: T, anim: AnimationSpec<Float> = animationSpec) { latestNonEmptyAnchorsFlow.collect { anchors -> try { val targetOffset = anchors.getOffset(targetValue) requireNotNull(targetOffset) { "The target value must have an associated anchor." } animateInternalToOffset(targetOffset, anim) } finally { val endOffset = absoluteOffset.value val endValue = anchors // fighting rounding error once again, anchor should be as close as 0.5 pixels .filterKeys { anchorOffset -> abs(anchorOffset - endOffset) < 0.5f } .values.firstOrNull() ?: currentValue currentValue = endValue } } } /** * Perform fling with settling to one of the anchors which is determined by the given * [velocity]. Fling with settling [swipeable] will always consume all the velocity provided * since it will settle at the anchor. * * In general cases, [swipeable] flings by itself when being swiped. This method is to be * used for nested scroll logic that wraps the [swipeable]. In nested scroll developer may * want to trigger settling fling when the child scroll container reaches the bound. * * @param velocity velocity to fling and settle with * * @return the reason fling ended */ suspend fun performFling(velocity: Float) { latestNonEmptyAnchorsFlow.collect { anchors -> val lastAnchor = anchors.getOffset(currentValue)!! val targetValue = computeTarget( offset = offset.value, lastValue = lastAnchor, anchors = anchors.keys, thresholds = thresholds, velocity = velocity, velocityThreshold = velocityThreshold ) val targetState = anchors[targetValue] if (targetState != null && confirmStateChange(targetState)) animateTo(targetState) // If the user vetoed the state change, rollback to the previous state. else animateInternalToOffset(lastAnchor, animationSpec) } } /** * Force [swipeable] to consume drag delta provided from outside of the regular [swipeable] * gesture flow. * * Note: This method performs generic drag and it won't settle to any particular anchor, * * leaving swipeable in between anchors. When done dragging, [performFling] must be * called as well to ensure swipeable will settle at the anchor. * * In general cases, [swipeable] drags by itself when being swiped. This method is to be * used for nested scroll logic that wraps the [swipeable]. In nested scroll developer may * want to force drag when the child scroll container reaches the bound. * * @param delta delta in pixels to drag by * * @return the amount of [delta] consumed */ fun performDrag(delta: Float): Float { val potentiallyConsumed = absoluteOffset.value + delta val clamped = potentiallyConsumed.coerceIn(minBound, maxBound) val deltaToConsume = clamped - absoluteOffset.value if (abs(deltaToConsume) > 0) { draggableState.dispatchRawDelta(deltaToConsume) } return deltaToConsume } companion object { /** * The default [Saver] implementation for [SwipeableState]. */ fun <T : Any> Saver( animationSpec: AnimationSpec<Float>, confirmStateChange: (T) -> Boolean ) = Saver<SwipeableState<T>, T>( save = { it.currentValue }, restore = { SwipeableState(it, animationSpec, confirmStateChange) } ) } } /** * Collects information about the ongoing swipe or animation in [swipeable]. * * To access this information, use [SwipeableState.progress]. * * @param from The state corresponding to the anchor we are moving away from. * @param to The state corresponding to the anchor we are moving towards. * @param fraction The fraction that the current position represents between [from] and [to]. * Must be between `0` and `1`. */ @Immutable @ExperimentalMaterialApi class SwipeProgress<T>( val from: T, val to: T, /*@FloatRange(from = 0.0, to = 1.0)*/ val fraction: Float ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is SwipeProgress<*>) return false if (from != other.from) return false if (to != other.to) return false if (fraction != other.fraction) return false return true } override fun hashCode(): Int { var result = from?.hashCode() ?: 0 result = 31 * result + (to?.hashCode() ?: 0) result = 31 * result + fraction.hashCode() return result } override fun toString(): String { return "SwipeProgress(from=$from, to=$to, fraction=$fraction)" } } /** * Create and [remember] a [SwipeableState] with the default animation clock. * * @param initialValue The initial value of the state. * @param animationSpec The default animation that will be used to animate to a new state. * @param confirmStateChange Optional callback invoked to confirm or veto a pending state change. */ @Composable @ExperimentalMaterialApi fun <T : Any> rememberSwipeableState( initialValue: T, animationSpec: AnimationSpec<Float> = AnimationSpec, confirmStateChange: (newValue: T) -> Boolean = { true } ): SwipeableState<T> { return rememberSaveable( saver = SwipeableState.Saver( animationSpec = animationSpec, confirmStateChange = confirmStateChange ) ) { SwipeableState( initialValue = initialValue, animationSpec = animationSpec, confirmStateChange = confirmStateChange ) } } /** * Create and [remember] a [SwipeableState] which is kept in sync with another state, i.e.: * 1. Whenever the [value] changes, the [SwipeableState] will be animated to that new value. * 2. Whenever the value of the [SwipeableState] changes (e.g. after a swipe), the owner of the * [value] will be notified to update their state to the new value of the [SwipeableState] by * invoking [onValueChange]. If the owner does not update their state to the provided value for * some reason, then the [SwipeableState] will perform a rollback to the previous, correct value. */ @Composable @ExperimentalMaterialApi internal fun <T : Any> rememberSwipeableStateFor( value: T, onValueChange: (T) -> Unit, animationSpec: AnimationSpec<Float> = AnimationSpec ): SwipeableState<T> { val swipeableState = remember { SwipeableState( initialValue = value, animationSpec = animationSpec, confirmStateChange = { true } ) } val forceAnimationCheck = remember { mutableStateOf(false) } LaunchedEffect(value, forceAnimationCheck.value) { if (value != swipeableState.currentValue) { swipeableState.animateTo(value) } } DisposableEffect(swipeableState.currentValue) { if (value != swipeableState.currentValue) { onValueChange(swipeableState.currentValue) forceAnimationCheck.value = !forceAnimationCheck.value } onDispose { } } return swipeableState } /** * Enable swipe gestures between a set of predefined states. * * To use this, you must provide a map of anchors (in pixels) to states (of type [T]). * Note that this map cannot be empty and cannot have two anchors mapped to the same state. * * When a swipe is detected, the offset of the [SwipeableState] will be updated with the swipe * delta. You should use this offset to move your content accordingly (see `Modifier.offsetPx`). * When the swipe ends, the offset will be animated to one of the anchors and when that anchor is * reached, the value of the [SwipeableState] will also be updated to the state corresponding to * the new anchor. The target anchor is calculated based on the provided positional [thresholds]. * * Swiping is constrained between the minimum and maximum anchors. If the user attempts to swipe * past these bounds, a resistance effect will be applied by default. The amount of resistance at * each edge is specified by the [resistance] config. To disable all resistance, set it to `null`. * * For an example of a [swipeable] with three states, see: * * @sample androidx.compose.material.samples.SwipeableSample * * @param T The type of the state. * @param state The state of the [swipeable]. * @param anchors Pairs of anchors and states, used to map anchors to states and vice versa. * @param thresholds Specifies where the thresholds between the states are. The thresholds will be * used to determine which state to animate to when swiping stops. This is represented as a lambda * that takes two states and returns the threshold between them in the form of a [ThresholdConfig]. * Note that the order of the states corresponds to the swipe direction. * @param orientation The orientation in which the [swipeable] can be swiped. * @param enabled Whether this [swipeable] is enabled and should react to the user's input. * @param reverseDirection Whether to reverse the direction of the swipe, so a top to bottom * swipe will behave like bottom to top, and a left to right swipe will behave like right to left. * @param interactionSource Optional [MutableInteractionSource] that will passed on to * the internal [Modifier.draggable]. * @param resistance Controls how much resistance will be applied when swiping past the bounds. * @param velocityThreshold The threshold (in dp per second) that the end velocity has to exceed * in order to animate to the next state, even if the positional [thresholds] have not been reached. */ @ExperimentalMaterialApi fun <T> Modifier.swipeable( state: SwipeableState<T>, anchors: Map<Float, T>, orientation: Orientation, enabled: Boolean = true, reverseDirection: Boolean = false, interactionSource: MutableInteractionSource? = null, thresholds: (from: T, to: T) -> ThresholdConfig = { _, _ -> FixedThreshold(56.dp) }, resistance: ResistanceConfig? = resistanceConfig(anchors.keys), velocityThreshold: Dp = VelocityThreshold ) = composed( inspectorInfo = debugInspectorInfo { name = "swipeable" properties["state"] = state properties["anchors"] = anchors properties["orientation"] = orientation properties["enabled"] = enabled properties["reverseDirection"] = reverseDirection properties["interactionSource"] = interactionSource properties["thresholds"] = thresholds properties["resistance"] = resistance properties["velocityThreshold"] = velocityThreshold } ) { require(anchors.isNotEmpty()) { "You must have at least one anchor." } require(anchors.values.distinct().count() == anchors.size) { "You cannot have two anchors mapped to the same state." } val density = LocalDensity.current state.ensureInit(anchors) LaunchedEffect(anchors, state) { val oldAnchors = state.anchors state.anchors = anchors state.resistance = resistance state.thresholds = { a, b -> val from = anchors.getValue(a) val to = anchors.getValue(b) with(thresholds(from, to)) { density.computeThreshold(a, b) } } with(density) { state.velocityThreshold = velocityThreshold.toPx() } state.processNewAnchors(oldAnchors, anchors) } Modifier.draggable( orientation = orientation, enabled = enabled, reverseDirection = reverseDirection, interactionSource = interactionSource, startDragImmediately = state.isAnimationRunning, onDragStopped = { velocity -> launch { state.performFling(velocity) } }, state = state.draggableState ) } /** * Interface to compute a threshold between two anchors/states in a [swipeable]. * * To define a [ThresholdConfig], consider using [FixedThreshold] and [FractionalThreshold]. */ @Stable @ExperimentalMaterialApi interface ThresholdConfig { /** * Compute the value of the threshold (in pixels), once the values of the anchors are known. */ fun Density.computeThreshold(fromValue: Float, toValue: Float): Float } /** * A fixed threshold will be at an [offset] away from the first anchor. * * @param offset The offset (in dp) that the threshold will be at. */ @Immutable @ExperimentalMaterialApi data class FixedThreshold(private val offset: Dp) : ThresholdConfig { override fun Density.computeThreshold(fromValue: Float, toValue: Float): Float { return fromValue + offset.toPx() * sign(toValue - fromValue) } } /** * A fractional threshold will be at a [fraction] of the way between the two anchors. * * @param fraction The fraction (between 0 and 1) that the threshold will be at. */ @Immutable @ExperimentalMaterialApi data class FractionalThreshold( /*@FloatRange(from = 0.0, to = 1.0)*/ private val fraction: Float ) : ThresholdConfig { override fun Density.computeThreshold(fromValue: Float, toValue: Float): Float { return lerp(fromValue, toValue, fraction) } } /** * Specifies how resistance is calculated in [swipeable]. * * There are two things needed to calculate resistance: the resistance basis determines how much * overflow will be consumed to achieve maximum resistance, and the resistance factor determines * the amount of resistance (the larger the resistance factor, the stronger the resistance). * * The resistance basis is usually either the size of the component which [swipeable] is applied * to, or the distance between the minimum and maximum anchors. For a constructor in which the * resistance basis defaults to the latter, consider using [resistanceConfig]. * * You may specify different resistance factors for each bound. Consider using one of the default * resistance factors in [SwipeableDefaults]: `StandardResistanceFactor` to convey that the user * has run out of things to see, and `StiffResistanceFactor` to convey that the user cannot swipe * this right now. Also, you can set either factor to 0 to disable resistance at that bound. * * @param basis Specifies the maximum amount of overflow that will be consumed. Must be positive. * @param factorAtMin The factor by which to scale the resistance at the minimum bound. * Must not be negative. * @param factorAtMax The factor by which to scale the resistance at the maximum bound. * Must not be negative. */ @Immutable class ResistanceConfig( /*@FloatRange(from = 0.0, fromInclusive = false)*/ val basis: Float, /*@FloatRange(from = 0.0)*/ val factorAtMin: Float = StandardResistanceFactor, /*@FloatRange(from = 0.0)*/ val factorAtMax: Float = StandardResistanceFactor ) { fun computeResistance(overflow: Float): Float { val factor = if (overflow < 0) factorAtMin else factorAtMax if (factor == 0f) return 0f val progress = (overflow / basis).coerceIn(-1f, 1f) return basis / factor * sin(progress * PI.toFloat() / 2) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ResistanceConfig) return false if (basis != other.basis) return false if (factorAtMin != other.factorAtMin) return false if (factorAtMax != other.factorAtMax) return false return true } override fun hashCode(): Int { var result = basis.hashCode() result = 31 * result + factorAtMin.hashCode() result = 31 * result + factorAtMax.hashCode() return result } override fun toString(): String { return "ResistanceConfig(basis=$basis, factorAtMin=$factorAtMin, factorAtMax=$factorAtMax)" } } /** * Given an offset x and a set of anchors, return a list of anchors: * 1. [ ] if the set of anchors is empty, * 2. [ x' ] if x is equal to one of the anchors, accounting for a small rounding error, where x' * is x rounded to the exact value of the matching anchor, * 3. [ min ] if min is the minimum anchor and x < min, * 4. [ max ] if max is the maximum anchor and x > max, or * 5. [ a , b ] if a and b are anchors such that a < x < b and b - a is minimal. */ private fun findBounds( offset: Float, anchors: Set<Float> ): List<Float> { // Find the anchors the target lies between with a little bit of rounding error. val a = anchors.filter { it <= offset + 0.001 }.maxOrNull() val b = anchors.filter { it >= offset - 0.001 }.minOrNull() return when { a == null -> // case 1 or 3 listOfNotNull(b) b == null -> // case 4 listOf(a) a == b -> // case 2 // Can't return offset itself here since it might not be exactly equal // to the anchor, despite being considered an exact match. listOf(a) else -> // case 5 listOf(a, b) } } private fun computeTarget( offset: Float, lastValue: Float, anchors: Set<Float>, thresholds: (Float, Float) -> Float, velocity: Float, velocityThreshold: Float ): Float { val bounds = findBounds(offset, anchors) return when (bounds.size) { 0 -> lastValue 1 -> bounds[0] else -> { val lower = bounds[0] val upper = bounds[1] if (lastValue <= offset) { // Swiping from lower to upper (positive). if (velocity >= velocityThreshold) { return upper } else { val threshold = thresholds(lower, upper) if (offset < threshold) lower else upper } } else { // Swiping from upper to lower (negative). if (velocity <= -velocityThreshold) { return lower } else { val threshold = thresholds(upper, lower) if (offset > threshold) upper else lower } } } } } private fun <T> Map<Float, T>.getOffset(state: T): Float? { return entries.firstOrNull { it.value == state }?.key } /** * Contains useful defaults for [swipeable] and [SwipeableState]. */ object SwipeableDefaults { /** * The default animation used by [SwipeableState]. */ val AnimationSpec = SpringSpec<Float>() /** * The default velocity threshold (1.8 dp per millisecond) used by [swipeable]. */ val VelocityThreshold = 125.dp /** * A stiff resistance factor which indicates that swiping isn't available right now. */ const val StiffResistanceFactor = 20f /** * A standard resistance factor which indicates that the user has run out of things to see. */ const val StandardResistanceFactor = 10f /** * The default resistance config used by [swipeable]. * * This returns `null` if there is one anchor. If there are at least two anchors, it returns * a [ResistanceConfig] with the resistance basis equal to the distance between the two bounds. */ fun resistanceConfig( anchors: Set<Float>, factorAtMin: Float = StandardResistanceFactor, factorAtMax: Float = StandardResistanceFactor ): ResistanceConfig? { return if (anchors.size <= 1) { null } else { val basis = anchors.maxOrNull()!! - anchors.minOrNull()!! ResistanceConfig(basis, factorAtMin, factorAtMax) } } } // temp default nested scroll connection for swipeables which desire as an opt in // revisit in b/174756744 as all types will have their own specific connection probably @ExperimentalMaterialApi internal val <T> SwipeableState<T>.PreUpPostDownNestedScrollConnection: NestedScrollConnection get() = object : NestedScrollConnection { override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset { val delta = available.toFloat() return if (delta < 0 && source == NestedScrollSource.Drag) { performDrag(delta).toOffset() } else { Offset.Zero } } override fun onPostScroll( consumed: Offset, available: Offset, source: NestedScrollSource ): Offset { return if (source == NestedScrollSource.Drag) { performDrag(available.toFloat()).toOffset() } else { Offset.Zero } } override suspend fun onPreFling(available: Velocity): Velocity { val toFling = Offset(available.x, available.y).toFloat() return if (toFling < 0 && offset.value > minBound) { performFling(velocity = toFling) // since we go to the anchor with tween settling, consume all for the best UX available } else { Velocity.Zero } } override suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity { performFling(velocity = Offset(available.x, available.y).toFloat()) return available } private fun Float.toOffset(): Offset = Offset(0f, this) private fun Offset.toFloat(): Float = this.y }
apache-2.0
bf842daefbf81f8f8f033fa927ab0116
38.63667
100
0.652184
4.660979
false
false
false
false
GunoH/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/dependency/analyzer/DependencyAnalyzerViewImpl.kt
1
20900
// 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.openapi.externalSystem.dependency.analyzer import com.intellij.icons.AllIcons import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.application.invokeLater import com.intellij.openapi.application.runInEdt import com.intellij.openapi.module.Module import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.externalSystem.autoimport.ExternalSystemProjectNotificationAware.Companion.isNotificationVisibleProperty import com.intellij.openapi.externalSystem.autoimport.ProjectRefreshAction import com.intellij.openapi.externalSystem.dependency.analyzer.DependencyAnalyzerDependency import com.intellij.openapi.externalSystem.dependency.analyzer.DependencyAnalyzerView.Companion.ACTION_PLACE import com.intellij.openapi.externalSystem.dependency.analyzer.util.* import com.intellij.openapi.externalSystem.dependency.analyzer.util.DependencyGroup.Companion.hasWarnings import com.intellij.openapi.externalSystem.dependency.analyzer.util.bind import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys import com.intellij.openapi.externalSystem.model.ProjectSystemId import com.intellij.openapi.externalSystem.ui.ExternalSystemIconProvider import com.intellij.openapi.externalSystem.util.ExternalSystemBundle import com.intellij.openapi.observable.operation.core.AtomicOperationTrace import com.intellij.openapi.observable.operation.core.getOperationInProgressProperty import com.intellij.openapi.observable.operation.core.isOperationInProgress import com.intellij.openapi.observable.operation.core.withCompletedOperation import com.intellij.openapi.observable.properties.AtomicProperty import com.intellij.openapi.observable.util.* import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.project.Project import com.intellij.openapi.ui.addPreferredFocusedComponent import com.intellij.openapi.util.text.NaturalComparator import com.intellij.ui.CollectionListModel import com.intellij.ui.ScrollPaneFactory import com.intellij.ui.SearchTextField import com.intellij.ui.components.JBLoadingPanel import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.ui.JBUI import java.awt.BorderLayout import javax.swing.JComponent import javax.swing.tree.DefaultMutableTreeNode import javax.swing.tree.DefaultTreeModel import com.intellij.openapi.externalSystem.dependency.analyzer.DependencyAnalyzerDependency as Dependency class DependencyAnalyzerViewImpl( private val project: Project, private val systemId: ProjectSystemId, private val parentDisposable: Disposable ) : DependencyAnalyzerView { private val iconsProvider = ExternalSystemIconProvider.getExtension(systemId) private val contributor = DependencyAnalyzerExtension.getExtension(systemId) .createContributor(project, parentDisposable) private val backgroundExecutor = AppExecutorUtil.createBoundedApplicationPoolExecutor("DependencyAnalyzerView.backgroundExecutor", 1) private val dependencyLoadingOperation = AtomicOperationTrace("DA: Dependency loading") private val dependencyLoadingProperty = dependencyLoadingOperation.getOperationInProgressProperty() private val externalProjectProperty = AtomicProperty<DependencyAnalyzerProject?>(null) private val dependencyDataFilterProperty = AtomicProperty("") private val dependencyScopeFilterProperty = AtomicProperty(emptyList<ScopeItem>()) private val showDependencyWarningsProperty = AtomicProperty(false) private val showDependencyGroupIdProperty = AtomicProperty(false) .bindBooleanStorage(SHOW_GROUP_ID_PROPERTY) private val dependencyModelProperty = AtomicProperty(emptyList<DependencyGroup>()) private val dependencyProperty = AtomicProperty<Dependency?>(null) private val showDependencyTreeProperty = AtomicProperty(false) .bindBooleanStorage(SHOW_AS_TREE_PROPERTY) private val dependencyEmptyTextProperty = AtomicProperty("") private val usagesTitleProperty = AtomicProperty("") private var externalProject by externalProjectProperty private var dependencyDataFilter by dependencyDataFilterProperty private var dependencyScopeFilter by dependencyScopeFilterProperty private var showDependencyWarnings by showDependencyWarningsProperty private var showDependencyGroupId by showDependencyGroupIdProperty private var dependencyModel by dependencyModelProperty private var dependency by dependencyProperty private var dependencyEmptyState by dependencyEmptyTextProperty private var usagesTitle by usagesTitleProperty private val externalProjects = ArrayList<DependencyAnalyzerProject>() private val dependencyListModel = CollectionListModel<DependencyGroup>() private val dependencyTreeModel = DefaultTreeModel(null) private val usagesTreeModel = DefaultTreeModel(null) override fun setSelectedExternalProject(module: Module) { setSelectedExternalProject(module) {} } override fun setSelectedDependency(module: Module, data: Dependency.Data) { setSelectedExternalProject(module) { dependency = findDependency { it.data == data } ?: dependency } } override fun setSelectedDependency(module: Module, data: Dependency.Data, scope: String) { setSelectedExternalProject(module) { dependency = findDependency { it.data == data && it.scope.name == scope } ?: dependency } } override fun setSelectedDependency(module: Module, path: List<DependencyAnalyzerDependency.Data>) { setSelectedExternalProject(module) { dependency = findDependency { d -> getTreePath(d).map { it.data } == path } ?: dependency } } override fun setSelectedDependency(module: Module, path: List<DependencyAnalyzerDependency.Data>, scope: String) { setSelectedExternalProject(module) { dependency = findDependency { d -> d.scope.name == scope && getTreePath(d).map { it.data } == path } ?: dependency } } private fun setSelectedExternalProject(module: Module, onReady: () -> Unit) { whenLoadingOperationCompleted { externalProject = findExternalProject { it.module == module } ?: externalProject whenLoadingOperationCompleted { onReady() } } } private fun findDependency(predicate: (Dependency) -> Boolean): Dependency? { return dependencyListModel.items.flatMap { it.variances }.find(predicate) ?: dependencyModel.flatMap { it.variances }.find(predicate) } private fun findExternalProject(predicate: (DependencyAnalyzerProject) -> Boolean): DependencyAnalyzerProject? { return externalProjects.find(predicate) } override fun getData(dataId: String): Any? { return when (dataId) { DependencyAnalyzerView.VIEW.name -> this CommonDataKeys.PROJECT.name -> project ExternalSystemDataKeys.EXTERNAL_SYSTEM_ID.name -> systemId PlatformCoreDataKeys.MODULE.name -> externalProject?.module else -> null } } private fun updateViewModel() { executeLoadingTaskOnEdt { updateExternalProjectsModel() } } private fun Iterable<Dependency>.filterDependencies(): List<Dependency> { val dependencyDataFilter = dependencyDataFilter val dependencyScopeFilter = dependencyScopeFilter .filter { it.isSelected } .map { it.scope } val showDependencyWarnings = showDependencyWarnings return filter { dependency -> dependencyDataFilter in dependency.data.getDisplayText(showDependencyGroupId) } .filter { dependency -> dependency.scope in dependencyScopeFilter } .filter { dependency -> if (showDependencyWarnings) dependency.hasWarnings else true } } private fun updateExternalProjectsModel() { externalProjects.clear() executeLoadingTask( onBackgroundThread = { contributor.getProjects() }, onUiThread = { projects -> externalProjects.addAll(projects) externalProject = externalProjects.find { it == externalProject } ?: externalProjects.firstOrNull() } ) } private fun updateScopesModel() { executeLoadingTask( onBackgroundThread = { externalProject?.let(contributor::getDependencyScopes) ?: emptyList() }, onUiThread = { scopes -> val scopesIndex = dependencyScopeFilter.associate { it.scope to it.isSelected } val isAny = scopesIndex.all { it.value } dependencyScopeFilter = scopes.map { ScopeItem(it, scopesIndex[it] ?: isAny) } } ) } private fun updateDependencyModel() { dependencyModel = emptyList() executeLoadingTask( onBackgroundThread = { externalProject?.let(contributor::getDependencies) ?: emptyList() }, onUiThread = { dependencies -> dependencyModel = dependencies .collectAllDependencies() .createDependencyGroups() } ) } private fun updateFilteredDependencyModel() { val filteredDependencyGroups = dependencyModel.asSequence() .map { it.variances.filterDependencies() } .filter { it.isNotEmpty() } .map { DependencyGroup(it) } .toList() dependencyListModel.replaceAll(filteredDependencyGroups) val filteredDependencies = filteredDependencyGroups.flatMap { it.variances } dependencyTreeModel.setRoot(buildTree(filteredDependencies)) dependency = filteredDependencies.find { it == dependency } ?: filteredDependencies.firstOrNull() } private fun updateDependencyEmptyState() { dependencyEmptyState = when { dependencyLoadingOperation.isOperationInProgress() -> "" else -> ExternalSystemBundle.message("external.system.dependency.analyzer.resolved.empty") } } private fun updateUsagesTitle() { val text = dependency?.data?.getDisplayText(showDependencyGroupId) usagesTitle = if (text == null) "" else ExternalSystemBundle.message("external.system.dependency.analyzer.usages.title", text) } private fun updateUsagesModel() { val dependencies = dependencyModel.asSequence() .filter { group -> dependency?.data in group.variances.map { it.data } } .flatMap { it.variances } .asIterable() usagesTreeModel.setRoot(buildTree(dependencies)) } private fun executeLoadingTaskOnEdt(onUiThread: () -> Unit) { dependencyLoadingOperation.traceStart() runInEdt { onUiThread() dependencyLoadingOperation.traceFinish() } } private fun <R> executeLoadingTask(onBackgroundThread: () -> R, onUiThread: (R) -> Unit) { dependencyLoadingOperation.traceStart() BackgroundTaskUtil.execute(backgroundExecutor, parentDisposable) { val result = onBackgroundThread() invokeLater { onUiThread(result) dependencyLoadingOperation.traceFinish() } } } private fun whenLoadingOperationCompleted(onUiThread: () -> Unit) { dependencyLoadingOperation.withCompletedOperation(parentDisposable) { runInEdt { onUiThread() } } } private fun buildTree(dependencies: Iterable<Dependency>): DefaultMutableTreeNode? { val dependenciesForTree = dependencies.collectAllDependencies() if (dependenciesForTree.isEmpty()) { return null } val rootDependencyGroup = dependenciesForTree .filter { it.parent == null } .createDependencyGroups() .singleOrNull() if (rootDependencyGroup == null) { val rawTree = dependenciesForTree.joinToString("\n") logger<DependencyAnalyzerView>().error("Cannot determine root of dependency tree:\n$rawTree") return null } val nodeMap = LinkedHashMap<Dependency, MutableList<Dependency>>() for (dependency in dependenciesForTree) { val usage = dependency.parent ?: continue val children = nodeMap.getOrPut(usage) { ArrayList() } children.add(dependency) } val rootNode = DefaultMutableTreeNode(rootDependencyGroup) val queue = ArrayDeque<DefaultMutableTreeNode>() queue.addLast(rootNode) while (queue.isNotEmpty()) { val node = queue.removeFirst() val dependencyGroup = node.userObject as DependencyGroup val children = dependencyGroup.variances .flatMap { nodeMap[it] ?: emptyList() } .createDependencyGroups() for (child in children) { val childNode = DefaultMutableTreeNode(child) node.add(childNode) queue.addLast(childNode) } } return rootNode } private fun Iterable<Dependency>.collectAllDependencies(): Set<Dependency> { return flatMap { getTreePath(it) }.toSet() } private fun getTreePath(dependency: Dependency): List<Dependency> { val dependencyPath = ArrayList<Dependency>() var current: Dependency? = dependency while (current != null) { dependencyPath.add(current) current = current.parent } return dependencyPath } private fun Dependency.Data.getGroup(): String = when (this) { is Dependency.Data.Module -> name is Dependency.Data.Artifact -> "$groupId:$artifactId" } private fun Iterable<Dependency>.createDependencyGroups(): List<DependencyGroup> = sortedWith(Comparator.comparing({ it.data }, DependencyDataComparator(showDependencyGroupId))) .groupBy { it.data.getGroup() } .map { DependencyGroup(it.value) } fun createComponent(): JComponent { val externalProjectSelector = ExternalProjectSelector(externalProjectProperty, externalProjects, iconsProvider) .bindEnabled(!dependencyLoadingProperty) val dataFilterField = SearchTextField(SEARCH_HISTORY_PROPERTY) .apply { setPreferredWidth(JBUI.scale(240)) } .apply { textEditor.bind(dependencyDataFilterProperty) } .bindEnabled(!dependencyLoadingProperty) val scopeFilterSelector = SearchScopeSelector(dependencyScopeFilterProperty) .bindEnabled(!dependencyLoadingProperty) val dependencyInspectionFilterButton = toggleAction(showDependencyWarningsProperty) .apply { templatePresentation.text = ExternalSystemBundle.message("external.system.dependency.analyzer.conflicts.show") } .apply { templatePresentation.icon = AllIcons.General.ShowWarning } .asActionButton(ACTION_PLACE) .bindEnabled(!dependencyLoadingProperty) val showDependencyGroupIdAction = toggleAction(showDependencyGroupIdProperty) .apply { templatePresentation.text = ExternalSystemBundle.message("external.system.dependency.analyzer.groupId.show") } val viewOptionsButton = popupActionGroup(showDependencyGroupIdAction) .apply { templatePresentation.icon = AllIcons.Actions.Show } .asActionButton(ACTION_PLACE) .bindEnabled(!dependencyLoadingProperty) val reloadNotificationProperty = isNotificationVisibleProperty(project, systemId) val projectReloadSeparator = separator() .bindVisible(reloadNotificationProperty) val projectReloadAction = action { ProjectRefreshAction.refreshProject(project) } .apply { templatePresentation.icon = AllIcons.Actions.BuildLoadChanges } .asActionButton(ACTION_PLACE) .bindVisible(reloadNotificationProperty) val dependencyTitle = label(ExternalSystemBundle.message("external.system.dependency.analyzer.resolved.title")) val dependencyList = DependencyList(dependencyListModel, showDependencyGroupIdProperty, this) .bindEmptyText(dependencyEmptyTextProperty) .bindDependency(dependencyProperty) .bindEnabled(!dependencyLoadingProperty) val dependencyTree = DependencyTree(dependencyTreeModel, showDependencyGroupIdProperty, this) .bindEmptyText(dependencyEmptyTextProperty) .bindDependency(dependencyProperty) .bindEnabled(!dependencyLoadingProperty) val dependencyPanel = cardPanel<Boolean> { ScrollPaneFactory.createScrollPane(if (it) dependencyTree else dependencyList, true) } .bind(showDependencyTreeProperty) val dependencyLoadingPanel = JBLoadingPanel(BorderLayout(), parentDisposable) .apply { add(dependencyPanel, BorderLayout.CENTER) } .apply { setLoadingText(ExternalSystemBundle.message("external.system.dependency.analyzer.dependency.loading")) } .bind(dependencyLoadingOperation) val showDependencyTreeButton = toggleAction(showDependencyTreeProperty) .apply { templatePresentation.text = ExternalSystemBundle.message("external.system.dependency.analyzer.resolved.tree.show") } .apply { templatePresentation.icon = AllIcons.Actions.ShowAsTree } .asActionButton(ACTION_PLACE) .bindEnabled(!dependencyLoadingProperty) val expandDependencyTreeButton = expandTreeAction(dependencyTree) .asActionButton(ACTION_PLACE) .bindEnabled(showDependencyTreeProperty and !dependencyLoadingProperty) val collapseDependencyTreeButton = collapseTreeAction(dependencyTree) .asActionButton(ACTION_PLACE) .bindEnabled(showDependencyTreeProperty and !dependencyLoadingProperty) val usagesTitle = label(usagesTitleProperty) val usagesTree = UsagesTree(usagesTreeModel, showDependencyGroupIdProperty, this) .apply { emptyText.text = "" } .bindEnabled(!dependencyLoadingProperty) val expandUsagesTreeButton = expandTreeAction(usagesTree) .asActionButton(ACTION_PLACE) .bindEnabled(!dependencyLoadingProperty) val collapseUsagesTreeButton = collapseTreeAction(usagesTree) .asActionButton(ACTION_PLACE) .bindEnabled(!dependencyLoadingProperty) return toolWindowPanel { toolbar = toolbarPanel { addToLeft(horizontalPanel( externalProjectSelector, dataFilterField, scopeFilterSelector, separator(), dependencyInspectionFilterButton, viewOptionsButton, projectReloadSeparator, projectReloadAction )) } setContent(horizontalSplitPanel(SPLIT_VIEW_PROPORTION_PROPERTY, 0.5f) { firstComponent = toolWindowPanel { toolbar = toolbarPanel { addToLeft(dependencyTitle) addToRight(horizontalPanel( showDependencyTreeButton, separator(), expandDependencyTreeButton, collapseDependencyTreeButton )) } setContent(dependencyLoadingPanel) } secondComponent = toolWindowPanel { toolbar = toolbarPanel { addToLeft(usagesTitle) addToRight(horizontalPanel( expandUsagesTreeButton, collapseUsagesTreeButton )) } setContent(ScrollPaneFactory.createScrollPane(usagesTree, true)) } }) }.also { it.addPreferredFocusedComponent(dataFilterField) } } init { externalProjectProperty.afterChange { updateScopesModel() } externalProjectProperty.afterChange { updateDependencyModel() } dependencyModelProperty.afterChange { updateFilteredDependencyModel() } dependencyDataFilterProperty.afterChange { updateFilteredDependencyModel() } dependencyScopeFilterProperty.afterChange { updateFilteredDependencyModel() } showDependencyWarningsProperty.afterChange { updateFilteredDependencyModel() } showDependencyGroupIdProperty.afterChange { updateFilteredDependencyModel() } dependencyProperty.afterChange { updateUsagesTitle() } dependencyProperty.afterChange { updateUsagesModel() } showDependencyGroupIdProperty.afterChange { updateUsagesTitle() } dependencyLoadingProperty.afterChange { updateDependencyEmptyState() } contributor.whenDataChanged(::updateViewModel, parentDisposable) updateViewModel() } private class DependencyDataComparator(private val showDependencyGroupId: Boolean) : Comparator<Dependency.Data> { override fun compare(o1: Dependency.Data, o2: Dependency.Data): Int { val text1 = o1.getDisplayText(showDependencyGroupId) val text2 = o2.getDisplayText(showDependencyGroupId) return when (o1) { is Dependency.Data.Module -> when (o2) { is Dependency.Data.Module -> NaturalComparator.INSTANCE.compare(text1, text2) is Dependency.Data.Artifact -> -1 } is Dependency.Data.Artifact -> when (o2) { is Dependency.Data.Module -> 1 is Dependency.Data.Artifact -> NaturalComparator.INSTANCE.compare(text1, text2) } } } } companion object { private const val SEARCH_HISTORY_PROPERTY = "ExternalSystem.DependencyAnalyzerView.search" private const val SHOW_GROUP_ID_PROPERTY = "ExternalSystem.DependencyAnalyzerView.showGroupId" private const val SHOW_AS_TREE_PROPERTY = "ExternalSystem.DependencyAnalyzerView.showAsTree" private const val SPLIT_VIEW_PROPORTION_PROPERTY = "ExternalSystem.DependencyAnalyzerView.splitProportion" } }
apache-2.0
972dd028788a91404c22009bb4b8173a
42.451143
158
0.753158
5.053191
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/customize/transferSettings/providers/vswin/utilities/registryUtils/impl/PrivateRegistryRoot.kt
2
2746
package com.intellij.ide.customize.transferSettings.providers.vswin.utilities.registryUtils.impl import com.jetbrains.rd.util.lifetime.Lifetime import com.intellij.ide.customize.transferSettings.providers.vswin.utilities.registryUtils.WindowsRegistryErrorTypes import com.intellij.ide.customize.transferSettings.providers.vswin.utilities.registryUtils.WindowsRegistryException import com.sun.jna.platform.win32.W32Errors import com.sun.jna.platform.win32.WinNT import com.sun.jna.platform.win32.WinReg import java.io.File import com.sun.jna.platform.win32.* class PrivateRegistryRoot private constructor(private val file: File, lifetime: Lifetime) : RegistryRoot(openPrivateRegistry(file), lifetime) { companion object { private val openedRegFiles = mutableMapOf<File, PrivateRegistryRoot>() fun getOrCreate(file: File, lifetime: Lifetime): PrivateRegistryRoot { return openedRegFiles.getOrPut(file) { PrivateRegistryRoot(file, lifetime) } } private fun getWindowsErrorText(winCode: Int): String { return when (winCode) { W32Errors.ERROR_SHARING_VIOLATION -> "The process cannot access the file because it is being used by another process." W32Errors.ERROR_LOCK_VIOLATION -> "The process cannot access the file because another process has locked a portion of the file." W32Errors.ERROR_INVALID_NAME -> "The filename, directory name, or volume label syntax is incorrect." W32Errors.ERROR_SUCCESS -> "Operation completed successfully." else -> "Unknown Windows error: $winCode" } } private fun openPrivateRegistry(file: File): WinReg.HKEY { val phKey = try { Advapi32Util.registryLoadAppKey(file.absolutePath, WinNT.KEY_ALL_ACCESS, 0) } catch (t: Win32Exception) { throw WindowsRegistryException(getWindowsErrorText(t.errorCode), WindowsRegistryErrorTypes.CORRUPTED) } try { val len = Advapi32Util.registryQueryInfoKey(phKey.value, 0).lpcMaxSubKeyLen.value if (len == 0) { throw WindowsRegistryException("lpcMaxSubKeyLen == 0, possibly a bad file", WindowsRegistryErrorTypes.CORRUPTED) } } catch (_: Win32Exception) { throw WindowsRegistryException("Failed to query info key, registry is corrupted", WindowsRegistryErrorTypes.CORRUPTED) } return phKey.value } } init { lifetime.onTermination { openedRegFiles.remove(file) } } }
apache-2.0
c00886c80bd335d30a90ec38deae24f7
43.306452
144
0.659505
4.553897
false
false
false
false
siosio/intellij-community
platform/build-scripts/icons/tests/org/jetbrains/intellij/build/images/ImageResourcesTest.kt
1
8448
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.intellij.build.images import com.intellij.openapi.application.PathManager import com.intellij.openapi.util.io.FileUtil import com.intellij.util.containers.ContainerUtil import org.jetbrains.jps.model.JpsElementFactory import org.jetbrains.jps.model.JpsModel import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.model.serialization.JpsModelSerializationDataService import org.jetbrains.jps.model.serialization.JpsProjectLoader import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.junit.runners.Parameterized.Parameter import org.junit.runners.Parameterized.Parameters import java.io.File import java.nio.file.Path import java.nio.file.Paths class CommunityImageResourcesSanityTest : ImageResourcesTestBase() { companion object { @JvmStatic @Parameters(name = "{0}") fun data(): Collection<Array<Any?>> { return collectBadIcons(TestRoot.COMMUNITY) } } } class CommunityImageResourcesOptimumSizeTest : ImageResourcesTestBase() { companion object { @JvmStatic @Parameters(name = "{0}") fun data(): Collection<Array<Any?>> { return collectIconsWithNonOptimumSize(TestRoot.COMMUNITY) } } } class CommunityIconClassesTest : ImageResourcesTestBase() { companion object { @JvmStatic @Parameters(name = "{0}") fun data(): Collection<Array<Any?>> { return collectNonRegeneratedIconClasses(TestRoot.COMMUNITY) } } } @Ignore class AllImageResourcesSanityTest : ImageResourcesTestBase() { companion object { @JvmStatic @Parameters(name = "{0}") fun data(): Collection<Array<Any?>> { return collectBadIcons(TestRoot.ALL, true) } } } @Ignore class AllImageResourcesOptimumSizeTest : ImageResourcesTestBase() { companion object { @JvmStatic @Parameters(name = "{0}") fun data(): Collection<Array<Any?>> { return collectIconsWithNonOptimumSize(TestRoot.ALL, false, true) } } } @RunWith(Parameterized::class) abstract class ImageResourcesTestBase { @JvmField @Parameter(value = 0) var testName: String? = null @JvmField @Parameter(value = 1) var exception: Throwable? = null @Test fun test() { if (exception != null) throw exception!! } enum class TestRoot { COMMUNITY, ULTIMATE, ALL } companion object { @JvmStatic @JvmOverloads fun collectBadIcons(root: TestRoot, ignoreSkipTag: Boolean = false): List<Array<Any?>> { val model = loadProjectModel(root) val modules = collectModules(root, model) val checker = MySanityChecker(Paths.get(PathManager.getHomePath()), ignoreSkipTag) val config = IntellijIconClassGeneratorConfig() modules.forEach { checker.check(it, config.getConfigForModule(it.name)) } return createTestData(modules, checker.failures) } @JvmStatic @JvmOverloads fun collectIconsWithNonOptimumSize(root: TestRoot, iconsOnly: Boolean = true, ignoreSkipTag: Boolean = false): List<Array<Any?>> { val model = loadProjectModel(root) val modules = collectModules(root, model) val checker = MyOptimumSizeChecker(Path.of(PathManager.getHomePath()), iconsOnly, ignoreSkipTag) modules.forEach { checker.checkOptimumSizes(it) } return createTestData(modules, checker.failures) } @JvmStatic fun collectNonRegeneratedIconClasses(root: TestRoot): List<Array<Any?>> { val model = loadProjectModel(root) val modules = collectModules(root, model) val checker = MyIconClassFileChecker(Path.of(PathManager.getHomePath()), model.project.modules) modules.forEach { checker.checkIconClasses(it) } return createTestData(modules, checker.failures) } private fun createTestData(modules: List<JpsModule>, failures: Collection<FailedTest>): List<Array<Any?>> { val success = listOf(arrayOf<Any?>("success: processed ${modules.size} modules", null)) val failedTests = failures .sortedWith(compareBy<FailedTest> { it.module }.thenBy { it.id }.thenBy { it.message }) .map { arrayOf<Any?>(it.getTestName(), it.getException()) } return success + failedTests } private fun loadProjectModel(root: TestRoot): JpsModel { val home = getHomePath(root) val model = JpsElementFactory.getInstance().createModel() val pathVariables = JpsModelSerializationDataService.computeAllPathVariables(model.global) JpsProjectLoader.loadProject(model.project, pathVariables, home.path) return model } private fun collectModules(root: TestRoot, model: JpsModel): List<JpsModule> { val home = getHomePath(root) return model.project.modules .filter { !(root == TestRoot.ULTIMATE && isCommunityModule(home, it)) && !it.name.startsWith("fleet.") && it.name != "fleet" } } private fun getHomePath(root: TestRoot): File { val home = File(PathManager.getHomePath()) if (root == TestRoot.COMMUNITY) { val community = File(home, "community") if (community.exists()) return community } return home } private fun isCommunityModule(home: File, module: JpsModule): Boolean { val community = File(home, "community") return module.sourceRoots.all { FileUtil.isAncestor(community, it.file, false) } } } } private class MySanityChecker(projectHome: Path, ignoreSkipTag: Boolean) : ImageSanityCheckerBase(projectHome, ignoreSkipTag) { val failures: MutableList<FailedTest> = ArrayList() override fun log(severity: Severity, message: String, module: JpsModule, images: Collection<ImageInfo>) { if (severity == Severity.INFO) return images.forEach { image -> failures.add(FailedTest(module, message, image)) } } } private class MyOptimumSizeChecker(val projectHome: Path, val iconsOnly: Boolean, val ignoreSkipTag: Boolean) { val failures = ContainerUtil.createConcurrentList<FailedTest>() private val config = IntellijIconClassGeneratorConfig() fun checkOptimumSizes(module: JpsModule) { val allImages = ImageCollector(projectHome, iconsOnly, ignoreSkipTag, moduleConfig = config.getConfigForModule(module.name)).collect(module) allImages.parallelStream().filter { it.basicFile != null }.forEach { image -> image.files.parallelStream().forEach { file -> val optimized = ImageSizeOptimizer.optimizeImage(file) if (optimized != null && !optimized.hasOptimumSize) { failures.add(FailedTest(module, "image size can be optimized (run \"Generate icon classes\" configuration): ${optimized.compressionStats}", image, file.toFile())) } } } } } private class MyIconClassFileChecker(private val projectHome: Path, private val modules: List<JpsModule>) { val failures = ArrayList<FailedTest>() private val config = IntellijIconClassGeneratorConfig() fun checkIconClasses(module: JpsModule) { val generator = IconsClassGenerator(projectHome, modules, false) generator.processModule(module, config.getConfigForModule(module.name)) generator.getModifiedClasses().forEach { (module, file, details) -> failures.add(FailedTest(module, "icon class file should be regenerated (run \"Generate icon classes\" configuration)", file, details)) } } } class FailedTest internal constructor(val module: String, val message: String, val id: String, private val details: String) { internal constructor(module: JpsModule, message: String, image: ImageInfo, file: File) : this(module.name, message, image.id, file.absolutePath) internal constructor(module: JpsModule, message: String, image: ImageInfo) : this(module.name, message, image.id, image.files.joinToString("\n") { it.toAbsolutePath().toString() }) internal constructor(module: JpsModule, message: String, file: Path, details: CharSequence) : this(module.name, message, file.fileName.toString(), "$file\n\n$details") fun getTestName(): String = "'${module}' - $id - ${message.substringBefore('\n')}" fun getException(): Throwable = Exception("${message}\n\n$details".trim()) }
apache-2.0
a5dfec0f6856e626f062cc7e0d27541d
35.895197
172
0.703717
4.332308
false
true
false
false
josecefe/Rueda
src/es/um/josecefe/rueda/modelo/Asignacion.kt
1
3397
/* * Copyright (c) 2016-2017. Jose Ceferino Ortega Carretero * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package es.um.josecefe.rueda.modelo import com.fasterxml.jackson.annotation.JsonIdentityInfo import com.fasterxml.jackson.annotation.ObjectIdGenerators import javafx.beans.property.* import javafx.collections.FXCollections /** * @author josec */ @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator::class, property = "@id") class Asignacion(dia: Dia, conductores: List<Participante>, peIda: List<Pair<Participante, Lugar>>, peVuelta: List<Pair<Participante, Lugar>>, coste: Int) : Comparable<Asignacion> { private val diaProp: SimpleObjectProperty<Dia> = SimpleObjectProperty() private val conductoresProp: SimpleListProperty<Participante> = SimpleListProperty(FXCollections.observableArrayList()) private val peidaProp: SimpleListProperty<Pair<Participante, Lugar>> = SimpleListProperty(FXCollections.observableArrayList()) private val pevueltaProp: SimpleListProperty<Pair<Participante, Lugar>> = SimpleListProperty(FXCollections.observableArrayList()) private val costeProp = SimpleIntegerProperty() init { diaProp.set(dia) conductoresProp.addAll(conductores) peidaProp.addAll(peIda) pevueltaProp.addAll(peVuelta) costeProp.set(coste) } constructor(dia: Dia, asignacionDia: AsignacionDia) : this(dia, asignacionDia.conductores.toList(), asignacionDia.peIda.entries.map { Pair(it.key, it.value) }, asignacionDia.peVuelta.entries.map { Pair(it.key, it.value) }, asignacionDia.coste) var dia: Dia get() = diaProp.get() set(value) = diaProp.set(value) fun diaProperty(): ObjectProperty<Dia> = diaProp var conductores: List<Participante> get() = conductoresProp.get() set(value) { conductoresProp.clear() conductoresProp.addAll(value) } fun participantesProperty(): ListProperty<Participante> = conductoresProp var peIda: List<Pair<Participante, Lugar>> get() = peidaProp.get() set(value) { peidaProp.clear() peidaProp.addAll(value) } fun peIdaProperty(): ListProperty<Pair<Participante, Lugar>> = peidaProp var peVuelta: List<Pair<Participante, Lugar>> get() = pevueltaProp.get() set(value) { pevueltaProp.clear() pevueltaProp.addAll(value) } fun peVueltaProperty(): ListProperty<Pair<Participante, Lugar>> = pevueltaProp var coste: Int get() = costeProp.get() set(value) = costeProp.set(value) fun costeProperty(): IntegerProperty = costeProp override fun compareTo(other: Asignacion): Int { return dia.compareTo(other.dia) } }
gpl-3.0
f2a80d9c124b3898c2611beaa91dcbf0
40.426829
242
0.706211
3.968458
false
false
false
false
JetBrains/kotlin-native
runtime/src/main/kotlin/kotlin/collections/AbstractMutableList.kt
2
6196
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package kotlin.collections /** * AbstractMutableList implementation copied from JS backend * (see <Kotlin JVM root>js/js.libraries/src/core/collections/AbstractMutableList.kt). * * Based on GWT AbstractList * Copyright 2007 Google Inc. */ /** * Provides a skeletal implementation of the [MutableList] interface. * * @param E the type of elements contained in the list. The list is invariant in its element type. */ public actual abstract class AbstractMutableList<E> protected actual constructor() : AbstractMutableCollection<E>(), MutableList<E> { protected var modCount: Int = 0 abstract override fun add(index: Int, element: E): Unit abstract override fun removeAt(index: Int): E abstract override fun set(index: Int, element: E): E /** * Adds the specified element to the end of this list. * * @return `true` because the list is always modified as the result of this operation. */ override actual fun add(element: E): Boolean { add(size, element) return true } override actual fun addAll(index: Int, elements: Collection<E>): Boolean { var i = index var changed = false for (e in elements) { add(i++, e) changed = true } return changed } override actual fun clear() { removeRange(0, size) } override actual fun removeAll(elements: Collection<E>): Boolean = removeAll { it in elements } override actual fun retainAll(elements: Collection<E>): Boolean = removeAll { it !in elements } override actual fun iterator(): MutableIterator<E> = IteratorImpl() override actual fun contains(element: E): Boolean = indexOf(element) >= 0 override actual fun indexOf(element: E): Int { for (index in 0..lastIndex) { if (get(index) == element) { return index } } return -1 } override actual fun lastIndexOf(element: E): Int { for (index in lastIndex downTo 0) { if (get(index) == element) { return index } } return -1 } override actual fun listIterator(): MutableListIterator<E> = listIterator(0) override actual fun listIterator(index: Int): MutableListIterator<E> = ListIteratorImpl(index) override actual fun subList(fromIndex: Int, toIndex: Int): MutableList<E> = SubList(this, fromIndex, toIndex) /** * Removes the range of elements from this list starting from [fromIndex] and ending with but not including [toIndex]. */ protected open fun removeRange(fromIndex: Int, toIndex: Int) { val iterator = listIterator(fromIndex) repeat(toIndex - fromIndex) { iterator.next() iterator.remove() } } override fun equals(other: Any?): Boolean { if (other === this) return true if (other !is List<*>) return false return AbstractList.orderedEquals(this, other) } override fun hashCode(): Int = AbstractList.orderedHashCode(this) private open inner class IteratorImpl : MutableIterator<E> { /** the index of the item that will be returned on the next call to [next]`()` */ protected var index = 0 /** the index of the item that was returned on the previous call to [next]`()` * or [ListIterator.previous]`()` (for `ListIterator`), * -1 if no such item exists */ protected var last = -1 override fun hasNext(): Boolean = index < size override fun next(): E { if (!hasNext()) throw NoSuchElementException() last = index++ return get(last) } override fun remove() { check(last != -1) { "Call next() or previous() before removing element from the iterator."} removeAt(last) index = last last = -1 } } /** * Implementation of `MutableListIterator` for abstract lists. */ private inner class ListIteratorImpl(index: Int) : IteratorImpl(), MutableListIterator<E> { init { AbstractList.checkPositionIndex(index, [email protected]) this.index = index } override fun hasPrevious(): Boolean = index > 0 override fun nextIndex(): Int = index override fun previous(): E { if (!hasPrevious()) throw NoSuchElementException() last = --index return get(last) } override fun previousIndex(): Int = index - 1 override fun add(element: E) { add(index, element) index++ last = -1 } override fun set(element: E) { check(last != -1) { "Call next() or previous() before updating element value with the iterator."} this@AbstractMutableList[last] = element } } private class SubList<E>(private val list: AbstractMutableList<E>, private val fromIndex: Int, toIndex: Int) : AbstractMutableList<E>() { private var _size: Int = 0 init { AbstractList.checkRangeIndexes(fromIndex, toIndex, list.size) this._size = toIndex - fromIndex } override fun add(index: Int, element: E) { AbstractList.checkPositionIndex(index, _size) list.add(fromIndex + index, element) _size++ } override fun get(index: Int): E { AbstractList.checkElementIndex(index, _size) return list[fromIndex + index] } override fun removeAt(index: Int): E { AbstractList.checkElementIndex(index, _size) val result = list.removeAt(fromIndex + index) _size-- return result } override fun set(index: Int, element: E): E { AbstractList.checkElementIndex(index, _size) return list.set(fromIndex + index, element) } override val size: Int get() = _size } }
apache-2.0
eb1c0384f361e13b453231ab6366b133
29.678218
141
0.600387
4.651652
false
false
false
false
GunoH/intellij-community
plugins/kotlin/gradle/gradle/src/org/jetbrains/kotlin/idea/gradle/configuration/cachedCompilerArgumentsRestoring.kt
6
13433
// 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.gradle.configuration import com.intellij.openapi.diagnostic.Logger import com.intellij.util.PathUtil import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.K2MetadataCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.parseCommandLineArguments import org.jetbrains.kotlin.idea.gradle.configuration.CachedCompilerArgumentsRestoringManager.restoreCompilerArgument import org.jetbrains.kotlin.idea.gradleTooling.arguments.* import org.jetbrains.kotlin.idea.projectModel.ArgsInfo import org.jetbrains.kotlin.idea.projectModel.CompilerArgumentsCacheAware import org.jetbrains.kotlin.idea.projectModel.KotlinCachedCompilerArgument import org.jetbrains.kotlin.idea.projectModel.KotlinRawCompilerArgument import org.jetbrains.kotlin.platform.impl.FakeK2NativeCompilerArguments import java.io.File import kotlin.reflect.KMutableProperty1 import kotlin.reflect.KProperty1 import kotlin.reflect.full.memberProperties sealed interface EntityArgsInfo : ArgsInfo<CommonCompilerArguments, String> data class EntityArgsInfoImpl( override val currentCompilerArguments: CommonCompilerArguments, override val defaultCompilerArguments: CommonCompilerArguments, override val dependencyClasspath: Collection<String> ) : EntityArgsInfo class EmptyEntityArgsInfo : EntityArgsInfo { override val currentCompilerArguments: CommonCompilerArguments = CommonCompilerArguments.DummyImpl() override val defaultCompilerArguments: CommonCompilerArguments = CommonCompilerArguments.DummyImpl() override val dependencyClasspath: Collection<String> = emptyList() } sealed interface FlatSerializedArgsInfo : ArgsInfo<List<String>, String> data class FlatSerializedArgsInfoImpl( override val currentCompilerArguments: List<String>, override val defaultCompilerArguments: List<String>, override val dependencyClasspath: Collection<String> ) : FlatSerializedArgsInfo class EmptyFlatArgsInfo : FlatSerializedArgsInfo { override val currentCompilerArguments: List<String> = emptyList() override val defaultCompilerArguments: List<String> = emptyList() override val dependencyClasspath: Collection<String> = emptyList() } object CachedArgumentsRestoring { private val LOGGER = Logger.getInstance(CachedArgumentsRestoring.javaClass) private const val STUB_K_2_NATIVE_COMPILER_ARGUMENTS_CLASS = "org.jetbrains.kotlin.gradle.tasks.StubK2NativeCompilerArguments" fun restoreSerializedArgsInfo( cachedSerializedArgsInfo: CachedSerializedArgsInfo, compilerArgumentsCacheHolder: CompilerArgumentsCacheHolder ): FlatSerializedArgsInfo { val cacheAware = compilerArgumentsCacheHolder.getCacheAware(cachedSerializedArgsInfo.cacheOriginIdentifier) ?: return EmptyFlatArgsInfo().also { LOGGER.error("CompilerArgumentsCacheAware with UUID '${cachedSerializedArgsInfo.cacheOriginIdentifier}' was not found!") } val currentCompilerArguments = cachedSerializedArgsInfo.currentCompilerArguments.mapNotNull { it.restoreArgumentAsString(cacheAware) } val defaultCompilerArguments = cachedSerializedArgsInfo.defaultCompilerArguments.mapNotNull { it.restoreArgumentAsString(cacheAware) } val dependencyClasspath = cachedSerializedArgsInfo.dependencyClasspath.mapNotNull { it.restoreArgumentAsString(cacheAware) } return FlatSerializedArgsInfoImpl(currentCompilerArguments, defaultCompilerArguments, dependencyClasspath) } fun restoreExtractedArgs( cachedExtractedArgsInfo: CachedExtractedArgsInfo, compilerArgumentsCacheHolder: CompilerArgumentsCacheHolder ): EntityArgsInfo { val cacheAware = compilerArgumentsCacheHolder.getCacheAware(cachedExtractedArgsInfo.cacheOriginIdentifier) ?: return EmptyEntityArgsInfo().also { LOGGER.error("CompilerArgumentsCacheAware with UUID '${cachedExtractedArgsInfo.cacheOriginIdentifier}' was not found!") } val currentCompilerArguments = restoreCachedCompilerArguments(cachedExtractedArgsInfo.currentCompilerArguments, cacheAware) val defaultCompilerArgumentsBucket = restoreCachedCompilerArguments(cachedExtractedArgsInfo.defaultCompilerArguments, cacheAware) val dependencyClasspath = cachedExtractedArgsInfo.dependencyClasspath .mapNotNull { it.restoreArgumentAsString(cacheAware) } .map { PathUtil.toSystemIndependentName(it) } return EntityArgsInfoImpl(currentCompilerArguments, defaultCompilerArgumentsBucket, dependencyClasspath) } private fun Map.Entry<KotlinCachedRegularCompilerArgument, KotlinCachedCompilerArgument<*>?>.obtainPropertyWithCachedValue( propertiesByName: Map<String, KProperty1<out CommonCompilerArguments, *>>, cacheAware: CompilerArgumentsCacheAware ): Pair<KProperty1<out CommonCompilerArguments, *>, KotlinRawCompilerArgument<*>>? { val (key, value) = restoreEntry(this, cacheAware) ?: return null val restoredKey = (key as? KotlinRawRegularCompilerArgument)?.data ?: return null return (propertiesByName[restoredKey] ?: return null) to value } @Suppress("UNCHECKED_CAST") private fun restoreCachedCompilerArguments( cachedBucket: CachedCompilerArgumentsBucket, cacheAware: CompilerArgumentsCacheAware ): CommonCompilerArguments { fun KProperty1<*, *>.prepareLogMessage(): String = "Failed to restore value for $returnType compiler argument '$name'. Default value will be used!" val compilerArgumentsClassName = cachedBucket.compilerArgumentsClassName.data.let { cacheAware.getCached(it) ?: return CommonCompilerArguments.DummyImpl().also { _ -> LOGGER.error("Failed to restore name of compiler arguments class from id $it! 'CommonCompilerArguments' instance was created instead") } } //TODO: Fixup. Remove it once actual K2NativeCompilerArguments will be available without 'kotlin.native.enabled = true' flag val compilerArgumentsClass = if (compilerArgumentsClassName == STUB_K_2_NATIVE_COMPILER_ARGUMENTS_CLASS) FakeK2NativeCompilerArguments::class.java else Class.forName(compilerArgumentsClassName) as Class<out CommonCompilerArguments> val newCompilerArgumentsBean = compilerArgumentsClass.getConstructor().newInstance() val propertiesByName = compilerArgumentsClass.kotlin.memberProperties.associateBy { it.name } cachedBucket.singleArguments.entries.mapNotNull { val (property, value) = it.obtainPropertyWithCachedValue(propertiesByName, cacheAware) ?: return@mapNotNull null val newValue = when (value) { null -> null is KotlinRawRegularCompilerArgument -> value.data else -> { LOGGER.error(property.prepareLogMessage()) return@mapNotNull null } } property to newValue }.forEach { (prop, newVal) -> (prop as KMutableProperty1<CommonCompilerArguments, String?>).set(newCompilerArgumentsBean, newVal) } cachedBucket.flagArguments.entries.mapNotNull { val (property, value) = it.obtainPropertyWithCachedValue(propertiesByName, cacheAware) ?: return@mapNotNull null val restoredValue = (value as? KotlinRawBooleanCompilerArgument)?.data ?: run { LOGGER.error(property.prepareLogMessage()) return@mapNotNull null } property to restoredValue }.forEach { (prop, newVal) -> (prop as KMutableProperty1<CommonCompilerArguments, Boolean>).set(newCompilerArgumentsBean, newVal) } cachedBucket.multipleArguments.entries.mapNotNull { val (property, value) = it.obtainPropertyWithCachedValue(propertiesByName, cacheAware) ?: return@mapNotNull null val restoredValue = when (value) { null -> null is KotlinRawMultipleCompilerArgument -> value.data.toTypedArray() else -> { LOGGER.error(property.prepareLogMessage()) return@mapNotNull null } } property to restoredValue }.forEach { (prop, newVal) -> (prop as KMutableProperty1<CommonCompilerArguments, Array<String>?>).set(newCompilerArgumentsBean, newVal) } val classpathValue = (restoreCompilerArgument(cachedBucket.classpathParts, cacheAware) as KotlinRawMultipleCompilerArgument?) ?.data ?.joinToString(File.pathSeparator) when (newCompilerArgumentsBean) { is K2JVMCompilerArguments -> newCompilerArgumentsBean.classpath = classpathValue is K2MetadataCompilerArguments -> newCompilerArgumentsBean.classpath = classpathValue } val freeArgs = cachedBucket.freeArgs.mapNotNull { it.restoreArgumentAsString(cacheAware) } val internalArgs = cachedBucket.internalArguments.mapNotNull { it.restoreArgumentAsString(cacheAware) } parseCommandLineArguments(freeArgs + internalArgs, newCompilerArgumentsBean) return newCompilerArgumentsBean } private fun KotlinCachedCompilerArgument<*>.restoreArgumentAsString(cacheAware: CompilerArgumentsCacheAware): String? = when (val arg = restoreCompilerArgument(this, cacheAware)) { is KotlinRawBooleanCompilerArgument -> arg.data.toString() is KotlinRawRegularCompilerArgument -> arg.data is KotlinRawMultipleCompilerArgument -> arg.data.joinToString(File.separator) else -> { LOGGER.error("Unknown argument received" + arg?.let { ": ${it::class.qualifiedName}" }.orEmpty()) null } } private fun restoreEntry( entry: Map.Entry<KotlinCachedCompilerArgument<*>, KotlinCachedCompilerArgument<*>?>, cacheAware: CompilerArgumentsCacheAware ): Pair<KotlinRawCompilerArgument<*>, KotlinRawCompilerArgument<*>>? { val key = restoreCompilerArgument(entry.key, cacheAware) ?: return null val value = restoreCompilerArgument(entry.value, cacheAware) ?: return null return key to value } } object CachedCompilerArgumentsRestoringManager { private val LOGGER = Logger.getInstance(CachedCompilerArgumentsRestoringManager.javaClass) fun <TCache> restoreCompilerArgument( argument: TCache, cacheAware: CompilerArgumentsCacheAware ): KotlinRawCompilerArgument<*>? = when (argument) { null -> null is KotlinCachedBooleanCompilerArgument -> BOOLEAN_ARGUMENT_RESTORING_STRATEGY.restoreArgument(argument, cacheAware) is KotlinCachedRegularCompilerArgument -> REGULAR_ARGUMENT_RESTORING_STRATEGY.restoreArgument(argument, cacheAware) is KotlinCachedMultipleCompilerArgument -> MULTIPLE_ARGUMENT_RESTORING_STRATEGY.restoreArgument(argument, cacheAware) else -> { LOGGER.error("Unknown argument received" + argument?.let { ": ${it::class.java.name}" }) null } } private interface CompilerArgumentRestoringStrategy<TCache, TArg> { fun restoreArgument(cachedArgument: TCache, cacheAware: CompilerArgumentsCacheAware): KotlinRawCompilerArgument<TArg>? } private val BOOLEAN_ARGUMENT_RESTORING_STRATEGY = object : CompilerArgumentRestoringStrategy<KotlinCachedBooleanCompilerArgument, Boolean> { override fun restoreArgument( cachedArgument: KotlinCachedBooleanCompilerArgument, cacheAware: CompilerArgumentsCacheAware ): KotlinRawBooleanCompilerArgument = KotlinRawBooleanCompilerArgument(java.lang.Boolean.valueOf(cachedArgument.data)) } private val REGULAR_ARGUMENT_RESTORING_STRATEGY = object : CompilerArgumentRestoringStrategy<KotlinCachedRegularCompilerArgument, String> { override fun restoreArgument( cachedArgument: KotlinCachedRegularCompilerArgument, cacheAware: CompilerArgumentsCacheAware ): KotlinRawRegularCompilerArgument? = cacheAware.getCached(cachedArgument.data)?.let { KotlinRawRegularCompilerArgument(it) } ?: run { LOGGER.error("Cannot find string argument value for key '${cachedArgument.data}'") null } } private val MULTIPLE_ARGUMENT_RESTORING_STRATEGY = object : CompilerArgumentRestoringStrategy<KotlinCachedMultipleCompilerArgument, List<String>> { override fun restoreArgument( cachedArgument: KotlinCachedMultipleCompilerArgument, cacheAware: CompilerArgumentsCacheAware ): KotlinRawMultipleCompilerArgument { val cachedArguments = cachedArgument.data.mapNotNull { restoreCompilerArgument(it, cacheAware)?.data?.toString() } return KotlinRawMultipleCompilerArgument(cachedArguments) } } }
apache-2.0
14b94a1d2877a56d2633a26e1129f470
54.512397
150
0.728653
5.85061
false
false
false
false
shogo4405/HaishinKit.java
haishinkit/src/main/java/com/haishinkit/amf/Amf0Deserializer.kt
1
6647
package com.haishinkit.amf import android.util.Log import com.haishinkit.amf.data.AsArray import com.haishinkit.amf.data.AsUndefined import com.haishinkit.amf.data.AsXmlDocument import java.io.UnsupportedEncodingException import java.nio.ByteBuffer import java.util.Date import java.util.HashMap import java.util.IllegalFormatFlagsException internal class Amf0Deserializer(private val buffer: ByteBuffer) { val `object`: Any? get() { val marker = buffer.get() when (marker) { Amf0Marker.NUMBER.rawValue -> { buffer.position(buffer.position() - 1) return double } Amf0Marker.BOOL.rawValue -> { buffer.position(buffer.position() - 1) return boolean } Amf0Marker.STRING.rawValue -> { buffer.position(buffer.position() - 1) return string } Amf0Marker.OBJECT.rawValue -> { buffer.position(buffer.position() - 1) return map } Amf0Marker.MOVIECLIP.rawValue -> throw UnsupportedOperationException() Amf0Marker.NULL.rawValue -> return null Amf0Marker.UNDEFINED.rawValue -> return AsUndefined.instance Amf0Marker.REFERENCE.rawValue -> throw UnsupportedOperationException() Amf0Marker.ECMAARRAY.rawValue -> { buffer.position(buffer.position() - 1) return list } Amf0Marker.OBJECTEND.rawValue -> throw UnsupportedOperationException() Amf0Marker.STRICTARRAY.rawValue -> { buffer.position(buffer.position() - 1) return objects } Amf0Marker.DATE.rawValue -> { buffer.position(buffer.position() - 1) return date } Amf0Marker.LONGSTRING.rawValue -> { buffer.position(buffer.position() - 1) return string } Amf0Marker.UNSUPPORTED.rawValue -> throw UnsupportedOperationException() Amf0Marker.RECORDSET.rawValue -> throw UnsupportedOperationException() Amf0Marker.XMLDOCUMENT.rawValue -> { buffer.position(buffer.position() - 1) return xmlDocument } Amf0Marker.TYPEDOBJECT.rawValue -> throw UnsupportedOperationException() Amf0Marker.AVMPLUSH.rawValue -> throw UnsupportedOperationException() else -> { } } return null } val boolean: Boolean get() { val marker = buffer.get() if (marker != Amf0Marker.BOOL.rawValue) { throw IllegalFormatFlagsException(marker.toString()) } return buffer.get().toInt() == 1 } val double: Double get() { val marker = buffer.get() if (marker != Amf0Marker.NUMBER.rawValue) { throw IllegalFormatFlagsException(marker.toString()) } return buffer.double } val string: String get() { val marker = buffer.get() when (marker) { Amf0Marker.STRING.rawValue, Amf0Marker.LONGSTRING.rawValue -> { } else -> throw IllegalFormatFlagsException(marker.toString()) } return getString(Amf0Marker.STRING.rawValue == marker) } val map: Map<String, Any?>? get() { val marker = buffer.get() if (marker == Amf0Marker.NULL.rawValue) { return null } if (marker != Amf0Marker.OBJECT.rawValue) { throw IllegalFormatFlagsException(marker.toString()) } val map = HashMap<String, Any?>() while (true) { val key = getString(true) if (key == "") { buffer.get() break } map.put(key, `object`) } return map } val objects: Array<Any?>? get() { val marker = buffer.get() if (marker == Amf0Marker.NULL.rawValue) { return null } if (marker != Amf0Marker.STRICTARRAY.rawValue) { throw IllegalFormatFlagsException(marker.toString()) } val count = buffer.int val objects = arrayOfNulls<Any>(count) for (i in 0 until count) { objects[i] = `object` } return objects } val list: List<Any?>? get() { val marker = buffer.get() if (marker == Amf0Marker.NULL.rawValue) { return null } if (marker != Amf0Marker.ECMAARRAY.rawValue) { throw IllegalFormatFlagsException(marker.toString()) } val count = buffer.int val array = AsArray(count) while (true) { val key = getString(true) if (key == "") { buffer.get() break } array.put(key, `object`) } return array } // timezone val date: Date get() { val marker = buffer.get() if (marker != Amf0Marker.DATE.rawValue) { throw IllegalFormatFlagsException(marker.toString()) } val value = buffer.double buffer.position(buffer.position() + 2) val date = Date() date.time = value.toLong() return date } val xmlDocument: AsXmlDocument get() { val marker = buffer.get() if (marker != Amf0Marker.XMLDOCUMENT.rawValue) { throw IllegalFormatFlagsException(marker.toString()) } return AsXmlDocument(getString(false)) } private fun getString(asShort: Boolean): String { val length = if (asShort) buffer.short.toInt() else buffer.int return try { val bytes = ByteArray(length) buffer.get(bytes) String(bytes, charset("UTF-8")) } catch (e: UnsupportedEncodingException) { Log.e(javaClass.name, e.toString()) "" } } }
bsd-3-clause
e7def2ebf5bce831242032824d97caf6
32.913265
88
0.501429
5.164724
false
false
false
false
GunoH/intellij-community
python/src/com/jetbrains/python/console/PydevConsoleExecuteActionHandler.kt
3
9213
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.console import com.intellij.codeInsight.hint.HintManager import com.intellij.execution.console.LanguageConsoleImpl import com.intellij.execution.console.LanguageConsoleView import com.intellij.execution.process.ProcessHandler import com.intellij.execution.ui.ConsoleViewContentType import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.components.service import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.psi.util.PsiTreeUtil import com.jetbrains.python.console.actions.CommandQueueForPythonConsoleService import com.jetbrains.python.console.pydev.ConsoleCommunication import com.jetbrains.python.console.pydev.ConsoleCommunicationListener import com.jetbrains.python.psi.PyElementGenerator import com.jetbrains.python.psi.PyFile import com.jetbrains.python.psi.PyStatementList import com.jetbrains.python.psi.impl.PythonLanguageLevelPusher import java.awt.Font open class PydevConsoleExecuteActionHandler(private val myConsoleView: LanguageConsoleView, processHandler: ProcessHandler, final override val consoleCommunication: ConsoleCommunication) : PythonConsoleExecuteActionHandler(processHandler, false), ConsoleCommunicationListener { private val project = myConsoleView.project private val myEnterHandler = PyConsoleEnterHandler() private var myIpythonInputPromptCount = 2 fun decreaseInputPromptCount(value : Int) { myIpythonInputPromptCount -= value } override var isEnabled: Boolean = false set(value) { field = value updateConsoleState() } init { this.consoleCommunication.addCommunicationListener(this) } override fun processLine(line: String) { executeMultiLine(line) } private fun executeMultiLine(text: String) { val commandText = if (!text.endsWith("\n")) { text + "\n" } else { text } sendLineToConsole(ConsoleCommunication.ConsoleCodeFragment(commandText, checkSingleLine(text))) } override fun checkSingleLine(text: String): Boolean { val languageLevel = PythonLanguageLevelPusher.getLanguageLevelForVirtualFile(project, myConsoleView.virtualFile) val pyFile = PyElementGenerator.getInstance(project).createDummyFile(languageLevel, text) as PyFile return PsiTreeUtil.findChildOfAnyType(pyFile, PyStatementList::class.java) == null && pyFile.statements.size < 2 } private fun sendLineToConsole(code: ConsoleCommunication.ConsoleCodeFragment) { val consoleComm = consoleCommunication if (!consoleComm.isWaitingForInput) { executingPrompt() } if (ipythonEnabled && !consoleComm.isWaitingForInput && !code.getText().isBlank()) { ++myIpythonInputPromptCount } if (PyConsoleUtil.isCommandQueueEnabled(project)) { // add new command to CommandQueue service service<CommandQueueForPythonConsoleService>().addNewCommand(this, code) } else { consoleComm.execInterpreter(code) {} } } override fun updateConsoleState() { if (!isEnabled) { executingPrompt() } else if (consoleCommunication.isWaitingForInput) { waitingForInputPrompt() } else if (canExecuteNow()) { if (consoleCommunication.needsMore()) { more() } else { inPrompt() } } else { if (PyConsoleUtil.isCommandQueueEnabled(project)) { inPrompt() } else { executingPrompt() } } } private fun inPrompt() { if (ipythonEnabled) { ipythonInPrompt() } else { ordinaryPrompt() } } private fun ordinaryPrompt() { if (PyConsoleUtil.ORDINARY_PROMPT != myConsoleView.prompt) { myConsoleView.prompt = PyConsoleUtil.ORDINARY_PROMPT myConsoleView.indentPrompt = PyConsoleUtil.INDENT_PROMPT PyConsoleUtil.scrollDown(myConsoleView.currentEditor) } } private val ipythonEnabled: Boolean get() = PyConsoleUtil.getOrCreateIPythonData(myConsoleView.virtualFile).isIPythonEnabled private fun ipythonInPrompt() { myConsoleView.setPromptAttributes(object : ConsoleViewContentType("", TextAttributes()) { override fun getAttributes(): TextAttributes { val attrs = EditorColorsManager.getInstance().globalScheme.getAttributes(USER_INPUT_KEY) attrs.fontType = Font.PLAIN return attrs } }) val prompt = "In [$myIpythonInputPromptCount]:" val indentPrompt = PyConsoleUtil.IPYTHON_INDENT_PROMPT.padStart(prompt.length) myConsoleView.prompt = prompt myConsoleView.indentPrompt = indentPrompt PyConsoleUtil.scrollDown(myConsoleView.currentEditor) } private fun executingPrompt() { myConsoleView.prompt = PyConsoleUtil.EXECUTING_PROMPT myConsoleView.indentPrompt = PyConsoleUtil.EXECUTING_PROMPT } private fun waitingForInputPrompt() { if (PyConsoleUtil.INPUT_PROMPT != myConsoleView.prompt && PyConsoleUtil.HELP_PROMPT != myConsoleView.prompt) { myConsoleView.prompt = PyConsoleUtil.INPUT_PROMPT myConsoleView.indentPrompt = PyConsoleUtil.INPUT_PROMPT PyConsoleUtil.scrollDown(myConsoleView.currentEditor) } } private fun more() { val prompt = if (ipythonEnabled) { PyConsoleUtil.IPYTHON_INDENT_PROMPT } else { PyConsoleUtil.INDENT_PROMPT } if (prompt != myConsoleView.prompt) { myConsoleView.prompt = prompt myConsoleView.indentPrompt = prompt PyConsoleUtil.scrollDown(myConsoleView.currentEditor) } } override fun commandExecuted(more: Boolean): Unit = updateConsoleState() override fun inputRequested() { isEnabled = true } override val cantExecuteMessage: String get() { if (!isEnabled) { return consoleIsNotEnabledMessage } else if (!canExecuteNow()) { return prevCommandRunningMessage } else { return "Can't execute the command" } } override fun runExecuteAction(console: LanguageConsoleView) { if (isEnabled) { if (PyConsoleUtil.isCommandQueueEnabled(project)) { doRunExecuteAction(console) } else { if (!canExecuteNow()) { HintManager.getInstance().showErrorHint(console.consoleEditor, prevCommandRunningMessage) } else { doRunExecuteAction(console) } } } else { HintManager.getInstance().showErrorHint(console.consoleEditor, consoleIsNotEnabledMessage) } } private fun doRunExecuteAction(console: LanguageConsoleView) { val doc = myConsoleView.editorDocument val endMarker = doc.createRangeMarker(doc.textLength, doc.textLength) endMarker.isGreedyToLeft = false endMarker.isGreedyToRight = true val isComplete = myEnterHandler.handleEnterPressed(console.consoleEditor) if (isComplete || consoleCommunication.isWaitingForInput) { deleteString(doc, endMarker) if (shouldCopyToHistory(console)) { (console as? PythonConsoleView)?.let { pythonConsole -> pythonConsole.flushDeferredText() pythonConsole.storeExecutionCounterLineNumber(myIpythonInputPromptCount, pythonConsole.historyViewer.document.lineCount + console.consoleEditor.document.lineCount) } copyToHistoryAndExecute(console) } else { processLine(myConsoleView.consoleEditor.document.text) } } } private fun copyToHistoryAndExecute(console: LanguageConsoleView) = super.runExecuteAction(console) override fun canExecuteNow(): Boolean = !consoleCommunication.isExecuting || consoleCommunication.isWaitingForInput protected open val consoleIsNotEnabledMessage: String get() = notEnabledMessage companion object { val prevCommandRunningMessage: String get() = "Previous command is still running. Please wait or press Ctrl+C in console to interrupt." val notEnabledMessage: String get() = "Console is not enabled." private fun shouldCopyToHistory(console: LanguageConsoleView): Boolean { return !PyConsoleUtil.isPagingPrompt(console.prompt) } fun deleteString(document: Document, endMarker : RangeMarker) { if (endMarker.endOffset - endMarker.startOffset > 0) { ApplicationManager.getApplication().runWriteAction { CommandProcessor.getInstance().runUndoTransparentAction { document.deleteString(endMarker.startOffset, endMarker.endOffset) } } } } } } private var LanguageConsoleView.indentPrompt: String get() { return (this as? LanguageConsoleImpl)?.consolePromptDecorator?.indentPrompt ?: "" } set(value) { (this as? LanguageConsoleImpl)?.consolePromptDecorator?.indentPrompt = value }
apache-2.0
601457107b0874fa9deb82890d2c2fdd
33.122222
197
0.71627
5.015242
false
false
false
false
smmribeiro/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/data/VcsUserRegistryImpl.kt
3
4735
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.log.data import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.Project import com.intellij.util.containers.HashSetInterner import com.intellij.util.containers.Interner import com.intellij.util.io.* import com.intellij.vcs.log.VcsUser import com.intellij.vcs.log.VcsUserRegistry import com.intellij.vcs.log.impl.VcsUserImpl import java.io.DataInput import java.io.DataOutput import java.io.File import java.io.IOException import java.util.concurrent.atomic.AtomicReference class VcsUserRegistryImpl internal constructor(project: Project) : Disposable, VcsUserRegistry { private val _persistentEnumerator = AtomicReference<PersistentEnumeratorBase<VcsUser>?>() private val persistentEnumerator: PersistentEnumeratorBase<VcsUser>? get() = _persistentEnumerator.get() private val interner: Interner<VcsUser> private val mapFile = File(USER_CACHE_APP_DIR, project.locationHash + "." + STORAGE_VERSION) init { initEnumerator() interner = HashSetInterner() } private fun initEnumerator(): Boolean { try { val enumerator = IOUtil.openCleanOrResetBroken({ PersistentBTreeEnumerator(mapFile.toPath(), VcsUserKeyDescriptor(this), Page.PAGE_SIZE, null, STORAGE_VERSION) }, mapFile) val wasSet = _persistentEnumerator.compareAndSet(null, enumerator) if (!wasSet) { LOG.error("Could not assign newly opened enumerator") enumerator?.close() } return wasSet } catch (e: IOException) { LOG.warn(e) } return false } override fun createUser(name: String, email: String): VcsUser { synchronized(interner) { return interner.intern(VcsUserImpl(name, email)) } } fun addUser(user: VcsUser) { try { persistentEnumerator?.enumerate(user) } catch (e: IOException) { LOG.warn(e) rebuild() } } fun addUsers(users: Collection<VcsUser>) { for (user in users) { addUser(user) } } override fun getUsers(): Set<VcsUser> { return try { persistentEnumerator?.getAllDataObjects { true }?.toMutableSet() ?: emptySet() } catch (e: IOException) { LOG.warn(e) rebuild() emptySet() } catch (pce: ProcessCanceledException) { throw pce } catch (t: Throwable) { LOG.error(t) emptySet() } } fun all(condition: (t: VcsUser) -> Boolean): Boolean { return try { persistentEnumerator?.iterateData(condition) ?: false } catch (e: IOException) { LOG.warn(e) rebuild() false } catch (pce: ProcessCanceledException) { throw pce } catch (t: Throwable) { LOG.error(t) false } } private fun rebuild() { if (persistentEnumerator?.isCorrupted == true) { _persistentEnumerator.getAndSet(null)?.let { oldEnumerator -> ApplicationManager.getApplication().executeOnPooledThread { try { oldEnumerator.close() } catch (_: IOException) { } finally { initEnumerator() } } } } } fun flush() { persistentEnumerator?.force() } override fun dispose() { try { persistentEnumerator?.close() } catch (e: IOException) { LOG.warn(e) } } companion object { private val LOG = Logger.getInstance(VcsUserRegistryImpl::class.java) private val USER_CACHE_APP_DIR = File(PathManager.getSystemPath(), "vcs-users") private const val STORAGE_VERSION = 2 } } class VcsUserKeyDescriptor(private val userRegistry: VcsUserRegistry) : KeyDescriptor<VcsUser> { @Throws(IOException::class) override fun save(out: DataOutput, value: VcsUser) { IOUtil.writeUTF(out, value.name) IOUtil.writeUTF(out, value.email) } @Throws(IOException::class) override fun read(`in`: DataInput): VcsUser { val name = IOUtil.readUTF(`in`) val email = IOUtil.readUTF(`in`) return userRegistry.createUser(name, email) } override fun getHashCode(value: VcsUser): Int { return value.hashCode() } override fun isEqual(val1: VcsUser, val2: VcsUser): Boolean { return val1 == val2 } }
apache-2.0
7f1f17f20932a3b01bf3ed109b0bb9b2
27.017751
140
0.648997
4.292838
false
false
false
false
zielu/GitToolBox
src/main/kotlin/zielu/gittoolbox/config/DecorationColors.kt
1
1676
package zielu.gittoolbox.config import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.ui.SimpleTextAttributes internal object DecorationColors { @JvmField val REMOTE_BRANCH_ATTRIBUTES = TextAttributesKey .createTextAttributesKey("GIT_TOOLBOX.REMOTE_BRANCH_ATTRIBUTES") @JvmField val LOCAL_BRANCH_ATTRIBUTES = TextAttributesKey .createTextAttributesKey("GIT_TOOLBOX.LOCAL_BRANCH_ATTRIBUTES") @JvmField val MASTER_WITH_REMOTE_ATTRIBUTES = TextAttributesKey .createTextAttributesKey("GIT_TOOLBOX.MASTER_WITH_REMOTE_ATTRIBUTES") @JvmField val MASTER_LOCAL_ATTRIBUTES = TextAttributesKey .createTextAttributesKey("GIT_TOOLBOX.MASTER_LOCAL_ATTRIBUTES") @JvmField val STATUS_ATTRIBUTES = TextAttributesKey .createTextAttributesKey("GIT_TOOLBOX.STATUS_ATTRIBUTES") @JvmField val HEAD_TAGS_ATTRIBUTES = TextAttributesKey .createTextAttributesKey("GIT_TOOLBOX.HEAD_TAGS_ATTRIBUTES") @JvmField val CHANGED_COUNT_ATTRIBUTES = TextAttributesKey .createTextAttributesKey("GIT_TOOLBOX.CHANGED_COUNT_ATTRIBUTES") @JvmField val EDITOR_INLINE_BLAME_ATTRIBUTES = TextAttributesKey .createTextAttributesKey("GIT_TOOLBOX.EDITOR_INLINE_BLAME_ATTRIBUTES") @JvmStatic fun simpleAttributes(key: TextAttributesKey): SimpleTextAttributes { return SimpleTextAttributes.fromTextAttributes(textAttributes(key)) } fun textAttributes(key: TextAttributesKey): TextAttributes { val scheme = EditorColorsManager.getInstance().globalScheme return scheme.getAttributes(key) } }
apache-2.0
fad4851d3db31e4c5fd67f10a575bc7a
37.976744
74
0.804296
4.886297
false
false
false
false
80998062/Fank
presentation/src/main/java/com/sinyuk/fanfou/ui/account/AccountListView.kt
1
5009
/* * * * Apache License * * * * Copyright [2017] Sinyuk * * * * 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.sinyuk.fanfou.ui.account import android.arch.lifecycle.Observer import android.content.SharedPreferences import android.content.res.ColorStateList import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v4.content.ContextCompat import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import com.sinyuk.fanfou.R import com.sinyuk.fanfou.base.AbstractFragment import com.sinyuk.fanfou.di.Injectable import com.sinyuk.fanfou.domain.DO.Player import com.sinyuk.fanfou.domain.TYPE_GLOBAL import com.sinyuk.fanfou.domain.UNIQUE_ID import com.sinyuk.fanfou.domain.util.stringLiveData import com.sinyuk.fanfou.util.obtainViewModelFromActivity import com.sinyuk.fanfou.viewmodel.AccountViewModel import com.sinyuk.fanfou.viewmodel.FanfouViewModelFactory import com.sinyuk.myutils.system.ToastUtils import kotlinx.android.synthetic.main.account_list_footer.view.* import kotlinx.android.synthetic.main.account_list_view.* import javax.inject.Inject import javax.inject.Named /** * Created by sinyuk on 2018/1/31. * */ class AccountListView : AbstractFragment(), Injectable { companion object { fun newInstance() = AccountListView() } override fun layoutId() = R.layout.account_list_view @Inject lateinit var factory: FanfouViewModelFactory @Inject lateinit var toast: ToastUtils private val accountViewModel by lazy { obtainViewModelFromActivity(factory, AccountViewModel::class.java) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupList() accountViewModel.admins().observe(this@AccountListView, Observer { adapter.setNewData(it) }) } @field:[Inject Named(TYPE_GLOBAL)] lateinit var sharedPreferences: SharedPreferences lateinit var adapter: AccountAdapter private fun setupList() { LinearLayoutManager(context).apply { isItemPrefetchEnabled = true isAutoMeasureEnabled = true recyclerView.layoutManager = this } recyclerView.setHasFixedSize(true) adapter = AccountAdapter(sharedPreferences.getString(UNIQUE_ID, null)) val footer = LayoutInflater.from(context!!).inflate(R.layout.account_list_footer, recyclerView, false) adapter.addFooterView(footer) footer.addButton.setOnClickListener { listener?.onSignIn() } footer.registerButton.setOnClickListener { listener?.onSignUp() } recyclerView.adapter = adapter adapter.setOnItemChildClickListener { _, view, position -> when (view.id) { R.id.deleteButton -> { adapter.collapse(position) adapter.getItem(position)?.let { tryToLoginSiblingAccountAndDelete(it) } } } } adapter.listener = listener sharedPreferences.stringLiveData(UNIQUE_ID, "") .observe(this@AccountListView, Observer { if (it?.isNotBlank() == true) adapter.uniqueId = it }) } private var snackbar: Snackbar? = null /** * 删除的如果是当前登录的用户 */ private fun tryToLoginSiblingAccountAndDelete(it: Player) { if (it.uniqueId == sharedPreferences.getString(UNIQUE_ID, null)) { if (snackbar == null) { snackbar = Snackbar.make(view!!, R.string.hint_switch_account_before_delete, 1000) .setAction(R.string.action_confirm, {}) .setActionTextColor(ColorStateList.valueOf(ContextCompat.getColor(context!!, R.color.colorAccent))) } if (snackbar?.isShownOrQueued != true) snackbar?.show() } else { accountViewModel.delete(it.uniqueId) } } /** * 切换账户 * * Since onDone():Boolean has checked whether current logged account has changed */ fun onSwitch() = accountViewModel.switch(adapter.getItem(adapter.checked)!!.uniqueId) /** * */ interface OnAccountListListener { fun onSignUp() fun onSignIn() fun onSwitch(uniqueId: String) } var listener: OnAccountListListener? = null }
mit
09f32b312d03d5627b17155770c0d6e0
30.897436
123
0.679799
4.494128
false
false
false
false
blan4/MangaReader
app/src/main/java/org/seniorsigan/mangareader/data/cache/MangaCacheRepository.kt
1
2834
package org.seniorsigan.mangareader.data.cache import android.content.Context import org.seniorsigan.mangareader.App import org.seniorsigan.mangareader.data.MangaSearchRepository import org.seniorsigan.mangareader.data.Response import org.seniorsigan.mangareader.models.MangaItem class MangaCacheRepository( private val cacheName: String, private val context: Context ): MangaSearchRepository { private val storage = context.getSharedPreferences(cacheName, 0) private val detailsStorage = context.getSharedPreferences("$cacheName-details", 0) override fun findAll(callback: (Response<List<MangaItem>>) -> Unit) { val res: Response<List<MangaItem>> = try { val list = storage.all .map { it.value as String } .map { App.parseJson(it, MangaItem::class.java) } .filterNotNull() .sortedBy { it._id } Response(data = list, pending = false) } catch (e: Exception) { Response(data = emptyList(), pending = false, error = "${e.message}", exception = e) } callback(res) } override fun find(url: String, callback: (Response<MangaItem?>) -> Unit) { val res: Response<MangaItem?> = try { val details = detailsStorage.getString(url, null) val basic = storage.getString(url, null) val manga = App.parseJson(details ?: basic, MangaItem::class.java) Response(data = manga, pending = false) } catch (e: Exception) { Response(data = null, pending = false, error = "${e.message}", exception = e) } callback(res) } override fun search(query: String, callback: (Response<List<MangaItem>>) -> Unit) { val res: Response<List<MangaItem>> = try { val list = storage.all .map { it.value as String } .map { App.parseJson(it, MangaItem::class.java) } .filterNotNull() .filter { it.title.toLowerCase() == query.toLowerCase() } .sortedBy { it._id } Response(data = list, pending = false) } catch(e: Exception) { Response(data = emptyList(), pending = false, error = "${e.message}", exception = e) } callback(res) } fun updateAll(mangaList: List<MangaItem>) { if (mangaList.isEmpty()) return with(storage.edit(), { clear() mangaList.forEach { manga -> putString(manga.url, App.toJson(manga)) } commit() }) } fun update(item: MangaItem?) { if (item == null) return with(detailsStorage.edit(), { putString(item.url, App.toJson(item)) commit() }) } }
mit
77b20455ac2ada7ee688c3582c75d5fc
34.886076
96
0.572689
4.484177
false
false
false
false
NlRVANA/Unity
app/src/main/java/com/zwq65/unity/ui/contract/AccountContract.kt
1
1066
/* * Copyright [2017] [NIRVANA PRIVATE LIMITED] * * 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.zwq65.unity.ui.contract import com.zwq65.unity.ui._base.BaseContract /** * ================================================ * <p> * Created by NIRVANA on 2017/09/26 * Contact with <[email protected]> * ================================================ */ interface AccountContract { interface View : BaseContract.View interface Presenter<V : BaseContract.View> : BaseContract.Presenter<V> }
apache-2.0
1931db8518763208709fff2e54d732b5
32.3125
78
0.642589
4.213439
false
false
false
false
vector-im/vector-android
vector/src/main/java/im/vector/fragments/discovery/SettingsTextButtonItem.kt
2
5783
/* * Copyright 2019 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.fragments.discovery import android.view.View import android.widget.* import androidx.annotation.ColorRes import androidx.annotation.StringRes import androidx.core.content.ContextCompat import androidx.core.view.isInvisible import androidx.core.view.isVisible import butterknife.BindView import com.airbnb.epoxy.EpoxyAttribute import com.airbnb.epoxy.EpoxyModelClass import com.airbnb.epoxy.EpoxyModelWithHolder import im.vector.R import im.vector.ui.epoxy.BaseEpoxyHolder import im.vector.ui.themes.ThemeUtils import im.vector.ui.util.setTextOrHide @EpoxyModelClass(layout = R.layout.item_settings_button_single_line) abstract class SettingsTextButtonItem : EpoxyModelWithHolder<SettingsTextButtonItem.Holder>() { enum class ButtonStyle { POSITIVE, DESTRUCTIVE } enum class ButtonType { NORMAL, SWITCH } @EpoxyAttribute var title: String? = null @EpoxyAttribute @StringRes var titleResId: Int? = null @EpoxyAttribute var buttonTitle: String? = null @EpoxyAttribute @StringRes var buttonTitleId: Int? = null @EpoxyAttribute var buttonStyle: ButtonStyle = ButtonStyle.POSITIVE @EpoxyAttribute var buttonType: ButtonType = ButtonType.NORMAL @EpoxyAttribute var buttonIndeterminate: Boolean = false @EpoxyAttribute var checked: Boolean? = null @EpoxyAttribute var buttonClickListener: View.OnClickListener? = null @EpoxyAttribute var switchChangeListener: CompoundButton.OnCheckedChangeListener? = null @EpoxyAttribute var infoMessage: String? = null @EpoxyAttribute @StringRes var infoMessageId: Int? = null @EpoxyAttribute @ColorRes var infoMessageTintColorId: Int = R.color.vector_error_color override fun bind(holder: Holder) { super.bind(holder) if (titleResId != null) { holder.textView.setText(titleResId!!) } else { holder.textView.setTextOrHide(title, hideWhenBlank = false) } if (buttonTitleId != null) { holder.button.setText(buttonTitleId!!) } else { holder.button.setTextOrHide(buttonTitle) } if (buttonIndeterminate) { holder.spinner.isVisible = true holder.button.isInvisible = true holder.switchButton.isInvisible = true holder.switchButton.setOnCheckedChangeListener(null) holder.button.setOnClickListener(null) } else { holder.spinner.isVisible = false when (buttonType) { ButtonType.NORMAL -> { holder.button.isVisible = true holder.switchButton.isVisible = false when (buttonStyle) { ButtonStyle.POSITIVE -> { holder.button.setTextColor(ThemeUtils.getColor(holder.main.context, R.attr.colorAccent)) } ButtonStyle.DESTRUCTIVE -> { holder.button.setTextColor(ContextCompat.getColor(holder.main.context, R.color.vector_error_color)) } } holder.button.setOnClickListener(buttonClickListener) } ButtonType.SWITCH -> { holder.button.isVisible = false holder.switchButton.isVisible = true //set to null before changing the state holder.switchButton.setOnCheckedChangeListener(null) checked?.let { holder.switchButton.isChecked = it } holder.switchButton.setOnCheckedChangeListener(switchChangeListener) } } } val errorMessage = infoMessageId?.let { holder.main.context.getString(it) } ?: infoMessage if (errorMessage != null) { holder.errorTextView.isVisible = true holder.errorTextView.setTextOrHide(errorMessage) val errorColor = ContextCompat.getColor(holder.main.context, infoMessageTintColorId) ContextCompat.getDrawable(holder.main.context, R.drawable.ic_notification_privacy_warning)?.apply { ThemeUtils.tintDrawableWithColor(this, errorColor) holder.textView.setCompoundDrawablesWithIntrinsicBounds(this, null, null, null) } holder.errorTextView.setTextColor(errorColor) } else { holder.errorTextView.isVisible = false holder.errorTextView.text = null holder.textView.setCompoundDrawables(null, null, null, null) } } class Holder : BaseEpoxyHolder() { @BindView(R.id.settings_item_text) lateinit var textView: TextView @BindView(R.id.settings_item_button) lateinit var button: Button @BindView(R.id.settings_item_switch) lateinit var switchButton: Switch @BindView(R.id.settings_item_button_spinner) lateinit var spinner: ProgressBar @BindView(R.id.settings_item_error_message) lateinit var errorTextView: TextView } }
apache-2.0
7099aabff31477e936a215e60017ba81
31.677966
127
0.649663
4.942735
false
false
false
false
opacapp/opacclient
opacclient/libopac/src/main/java/de/geeksfactory/opacclient/apis/Koha.kt
1
32605
package de.geeksfactory.opacclient.apis import de.geeksfactory.opacclient.i18n.StringProvider import de.geeksfactory.opacclient.networking.HttpClientFactory import de.geeksfactory.opacclient.objects.* import de.geeksfactory.opacclient.searchfields.* import de.geeksfactory.opacclient.utils.get import de.geeksfactory.opacclient.utils.html import de.geeksfactory.opacclient.utils.text import okhttp3.FormBody import okhttp3.HttpUrl import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import org.joda.time.LocalDate import org.joda.time.LocalDateTime import org.joda.time.format.DateTimeFormat import org.json.JSONObject import org.jsoup.Jsoup import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.util.regex.Pattern /** * OpacApi implementation for the open source Koha OPAC. https://koha-community.org/ * * It includes special cases to account for changes in the "LMSCloud" variant * (https://www.lmscloud.de/) . Account features were only tested with LMSCloud. * * @author Johan von Forstner, November 2018 */ open class Koha : OkHttpBaseApi() { protected lateinit var baseurl: String protected val NOT_RENEWABLE = "NOT_RENEWABLE" protected val ENCODING = "UTF-8" protected var searchQuery: List<SearchQuery>? = null override fun init(library: Library, factory: HttpClientFactory, debug: Boolean) { super.init(library, factory, debug) baseurl = library.data.getString("baseurl") } override fun search(query: List<SearchQuery>): SearchRequestResult { this.searchQuery = query val builder = searchUrl(query) val url = builder.build().toString() val doc = httpGet(url, ENCODING).html doc.setBaseUri(url) if (doc.select(".searchresults").size == 0 && doc.select(".unapi-id").size == 1) { // only a single result val item = parseDetail(doc) return SearchRequestResult(listOf( SearchResult().apply { cover = item.cover id = item.id type = item.mediaType val author = item.details.find { it.desc == "Von" }?.content innerhtml = "<b>${item.title}</b><br>${author ?: ""}" } ), 1, 1) } else { return parseSearch(doc, 1) } } private val mediatypes = mapOf( "book" to SearchResult.MediaType.BOOK, "film" to SearchResult.MediaType.MOVIE, "sound" to SearchResult.MediaType.CD_MUSIC, "newspaper" to SearchResult.MediaType.MAGAZINE ) protected open fun parseSearch(doc: Document, page: Int): SearchRequestResult { if (doc.select("#noresultsfound").first() != null || doc.select(".span12:contains(Keine Treffer)").first() != null) { return SearchRequestResult(emptyList(), 0, page) } else if (doc.select("select[name=idx]").size > 1) { // We're back on the search page, no valid (likely empty) query throw OpacApi.OpacErrorException(stringProvider.getString("no_criteria_input")) } else if (doc.select("#numresults").first() == null) { throw OpacApi.OpacErrorException(stringProvider.getString("unknown_error")) } val countText = doc.select("#numresults").first().text val totalResults = Regex("\\d+").findAll(countText).lastOrNull()?.value?.toInt() ?: return SearchRequestResult(emptyList(), -1, page) val results = doc.select(".searchresults table tr").map { row -> SearchResult().apply { cover = row.select(".coverimages img").first()?.attr("src") var titleA = row.select("a.title").first() if (titleA == null) { titleA = row.select("a[href*=opac-detail.pl]:not(:has(img, .no-image))").first() } val biblionumber = Regex("biblionumber=([^&]+)").find(titleA["href"])!!.groupValues[1] id = biblionumber val title = titleA.ownText() val author = row.select(".author").first()?.text var summary = row.select(".results_summary").first()?.text if (summary != null) { summary = summary.split(" | ").dropLast(1).joinToString(" | ") } innerhtml = "<b>$title</b><br>${author ?: ""}<br>${summary ?: ""}" val mediatypeImg = row.select(".materialtype").first()?.attr("src")?.split("/")?.last()?.removeSuffix(".png") type = mediatypes[mediatypeImg] status = if (row.select(".available").size > 0 && row.select(".unavailable").size > 0) { SearchResult.Status.YELLOW } else if (row.select(".available").size > 0) { SearchResult.Status.GREEN } else if (row.select(".unavailable").size > 0) { SearchResult.Status.RED } else null } } return SearchRequestResult(results, totalResults, page) } private fun searchUrl(query: List<SearchQuery>): HttpUrl.Builder { val builder = "$baseurl/cgi-bin/koha/opac-search.pl".toHttpUrl().newBuilder() var yearFrom = "" var yearTo = "" for (q in query) { if (q.value.isBlank()) continue if (q.searchField.id == "limit-copydate-from") { yearFrom = q.value } else if (q.searchField.id == "limit-copydate-to") { yearTo = q.value } else if (q.searchField is TextSearchField || q.searchField is BarcodeSearchField) { builder.addQueryParameter("idx", q.key) builder.addQueryParameter("q", q.value) } else if (q.searchField is DropdownSearchField) { if (q.value.contains('=')) { val parts = q.value.split("=") builder.addQueryParameter(parts[0], parts[1]) } else { builder.addQueryParameter(q.searchField.data!!.getString("id"), q.value) } } else if (q.searchField is CheckboxSearchField) { if (q.value!!.toBoolean()) { builder.addQueryParameter("limit", q.key) } } } if (yearFrom.isNotBlank() || yearTo.isNotBlank()) { builder.addQueryParameter("limit-copydate", "$yearFrom-$yearTo") } return builder } override fun parseSearchFields(): List<SearchField> { val doc = httpGet("$baseurl/cgi-bin/koha/opac-search.pl", ENCODING).html // free search field val freeSearchField = TextSearchField().apply { id = "kw,wrdl" displayName = "Freitext" } // text fields val options = doc.select("#search-field_0").first().select("option") val textFields = options.map { o -> TextSearchField().apply { id = o["value"] displayName = o.text.trim() } } // filter fields val fieldsets = doc.select("#advsearches fieldset") val tabs = doc.select("#advsearches > ul > li") val filterFields = fieldsets.zip(tabs).filter { (fieldset, tab) -> fieldset.select("input[type=checkbox]").isNotEmpty() }.map { (fieldset, tab) -> val title = tab.text.trim() val checkboxes = fieldset.select("input[type=checkbox]") DropdownSearchField().apply { id = title // input["name"] is always "limit", so we can't use it as an ID displayName = title dropdownValues = listOf(DropdownSearchField.Option("", "")) + checkboxes.map { checkbox -> DropdownSearchField.Option( checkbox["name"] + "=" + checkbox["value"], checkbox.nextElementSibling().text.trim()) } data = JSONObject().apply { put("id", checkboxes[0]["name"]) } } } // dropdown fields val dropdowns = doc.select("legend + label + select, legend + p:has(label + select)") val dropdownFields = dropdowns.map { match -> val title = match.parent().select("legend").first().text.removeSuffix(":") val dropdown = match.parent().select("select").first() DropdownSearchField().apply { id = title // input["name"] is almost testalways "limit", so we can't use it as an ID displayName = title dropdownValues = dropdown.select("option").map { option -> DropdownSearchField.Option( option["value"], option.text) } data = JSONObject().apply { put("id", dropdown["name"]) } } } // year from to val yearrange = doc.select("#limit-copydate").first() var yearField = emptyList<SearchField>() if (yearrange != null) { yearField = listOf( TextSearchField().apply { id = "limit-copydate-from" displayName = yearrange.parent().select("legend").text() meaning = SearchField.Meaning.YEAR isFreeSearch = false isNumber = true isAdvanced = false }, TextSearchField().apply { id = "limit-copydate-to" displayName = yearrange.parent().select("legend").text() meaning = SearchField.Meaning.YEAR isFreeSearch = false isNumber = true isAdvanced = false isHalfWidth = true } ) } // available checkbox val available = doc.select("#available-items").first() var availableCheckbox = emptyList<SearchField>() if (available != null) { availableCheckbox = listOf( CheckboxSearchField().apply { id = available["value"] displayName = available.parent().text } ) } return listOf(freeSearchField) + textFields + filterFields + dropdownFields + yearField + availableCheckbox } override fun searchGetPage(page: Int): SearchRequestResult { if (searchQuery == null) { throw OpacApi.OpacErrorException(stringProvider.getString(StringProvider.INTERNAL_ERROR)) } val builder = searchUrl(searchQuery!!) builder.addQueryParameter("offset", (20 * (page - 1)).toString()) val url = builder.build().toString() val doc = httpGet(url, ENCODING).html doc.setBaseUri(url) return parseSearch(doc, 1) } override fun getResultById(id: String, homebranch: String?): DetailedItem { val doc = httpGet("$baseurl/cgi-bin/koha/opac-detail.pl?biblionumber=$id", ENCODING).html return parseDetail(doc) } protected fun parseDetail(doc: Document): DetailedItem { return DetailedItem().apply { val titleElem = doc.select("h1.title, #opacxslt h2").first() title = titleElem.ownText() this.id = doc.select(".unapi-id").first()["title"].removePrefix("koha:biblionumber:") if (doc.select("h5.author, span.author, span.results_summary").size > 0) { // LMSCloud doc.select("h5.author, span.author, span.results_summary").forEach { row -> // remove "Read more" link row.select(".truncable-txt-readmore").remove() // go through the details if (row.tagName() == "h5" || row.hasClass("author") || row.select("> span.label").size > 0) { // just one detail on this line val title = row.text.split(":").first().trim() val value = row.text.split(":").drop(1).joinToString(":").trim() if (!title.isBlank() || !value.isBlank()) addDetail(Detail(title, value)) } else { // multiple details on this line row.select("> span").forEach { span -> val title = span.text.split(":").first().trim() val value = span.text.split(":").drop(1).joinToString(":").trim() if (!title.isBlank() || !value.isBlank()) addDetail(Detail(title, value)) } } } } else if (doc.select("#opacxslt dt.labelxslt").size > 0) { // seen at https://catalogue.univ-amu.fr doc.select("#opacxslt dt.labelxslt").forEach { dt -> val title = dt.text var elem = dt var value = "" while (elem.nextElementSibling() != null && elem.nextElementSibling().tagName() == "dd") { elem = elem.nextElementSibling() if (!value.isBlank()) value += "\n" value += elem.text } addDetail(Detail(title, value)) } } val mediatypeImg = doc.select(".materialtype").first()?.attr("src")?.split("/")?.last()?.removeSuffix(".png") mediaType = mediatypes[mediatypeImg] cover = doc.select("#bookcover img").firstOrNull { !it.parent().parent().hasClass("contentsamplelink") }?.attr("src") val df = DateTimeFormat.forPattern("dd.MM.yyyy") copies = doc.select(".holdingst > tbody > tr, #holdingst > tbody > tr").map { row -> Copy().apply { for (td in row.select("td")) { row.select(".branch-info-tooltip").remove() val text = if (td.text.isNotBlank()) td.text.trim() else null when { // td.classNames().contains("itype") -> media type td.classNames().contains("location") -> branch = text td.classNames().contains("collection") -> location = text td.classNames().contains("vol_info") -> issue = text td.classNames().contains("call_no") -> { if (td.select(".isDivibibTitle").size > 0 && td.select("a").size > 0) { // Onleihe item val link = td.select("a").first()["href"] if (link.startsWith("javascript:void")) { val onclick = td.select("a").first()["onclick"] val pattern = Pattern.compile(".*accessDivibibResource\\([^,]*,[ ]*['\"]([0-9]+)['\"][ ]*\\).*") val matcher = pattern.matcher(onclick) if (matcher.matches()) { addDetail(Detail("_onleihe_id", matcher.group(1))) } } else { addDetail(Detail("Onleihe", link)) } } shelfmark = text?.removeSuffix("Hier klicken zum Ausleihen.") ?.removeSuffix("Hier klicken zum Reservieren.") } td.classNames().contains("status") -> status = text td.classNames().contains("date_due") -> if (text != null) { val dateText = text.removeSuffix(" 00:00") // seen with Onleihe items returnDate = df.parseLocalDate(dateText) } td.classNames().contains("holds_count") -> reservations = text } } } } isReservable = doc.select("a.reserve").size > 0 } } override fun getResult(position: Int): DetailedItem? { // Should not be called because every media has an ID return null } var reservationFeeConfirmed = false var selectedCopy: String? = null var selectedBranch: String? = null val ACTION_ITEM = 101 val ACTION_BRANCH = 102 override fun reservation(item: DetailedItem, account: Account, useraction: Int, selection: String?): OpacApi.ReservationResult { try { login(account) } catch (e: OpacApi.OpacErrorException) { return OpacApi.ReservationResult(OpacApi.MultiStepResult.Status.ERROR, e.message) } when (useraction) { 0 -> { reservationFeeConfirmed = false selectedCopy = null } OpacApi.MultiStepResult.ACTION_CONFIRMATION -> reservationFeeConfirmed = true ACTION_ITEM -> selectedCopy = selection ACTION_BRANCH -> selectedBranch = selection } var doc = httpGet("$baseurl/cgi-bin/koha/opac-reserve.pl?biblionumber=${item.id}", ENCODING).html if (doc.select(".alert").size > 0) { val alert = doc.select(".alert").first() val message = alert.text if (alert.id() != "reserve_fee") { return OpacApi.ReservationResult(OpacApi.MultiStepResult.Status.ERROR, message) } } if (doc.select("select[name=branch]").size > 0) { if (selectedBranch == null && doc.select("select[name=branch] option").size > 1) { return OpacApi.ReservationResult( OpacApi.MultiStepResult.Status.SELECTION_NEEDED, doc.select(".branch label").text).apply { actionIdentifier = ACTION_BRANCH setSelection(doc.select("select[name=branch] option").map { opt -> HashMap<String, String>().apply { put("key", opt.`val`()) put("value", opt.text()) } }) } } else if (doc.select("select[name=branch] option").size == 1) { selectedBranch = doc.select("select[name=branch] option").first().`val`() } } val body = FormBody.Builder() body.add("place_reserve", "1") val reserveMode = doc.select("input[name=reserve_mode]").`val`() body.add("reserve_mode", reserveMode) // can be "single" or "multi" body.add("single_bib", item.id) body.add("expiration_date_${item.id}", "") if (selectedBranch != null) { body.add("branch", selectedBranch!!) } val checkboxes = doc.select("input[name=checkitem_${item.id}]") if (checkboxes.size > 0) { body.add("biblionumbers", "${item.id}/") if (checkboxes.first()["value"] == "any") { body.add("reqtype_${item.id}", "any") body.add("checkitem_${item.id}", "any") body.add("selecteditems", "${item.id}///") } else { if (selectedCopy != null) { body.add("reqtype_${item.id}", "Specific") body.add("checkitem_${item.id}", selectedCopy!!) body.add("selecteditems", "${item.id}/$selectedCopy//") } else { val copies = doc.select(".copiesrow tr:has(td)") val activeCopies = copies.filter { row -> !row.select("input").first().hasAttr("disabled") } if (copies.size > 0 && activeCopies.isEmpty()) { return OpacApi.ReservationResult( OpacApi.MultiStepResult.Status.ERROR, stringProvider.getString(StringProvider.NO_COPY_RESERVABLE) ) } // copy selection return OpacApi.ReservationResult( OpacApi.MultiStepResult.Status.SELECTION_NEEDED, doc.select(".copiesrow caption").text).apply { actionIdentifier = ACTION_ITEM setSelection(activeCopies.map { row -> HashMap<String, String>().apply { put("key", row.select("input").first()["value"]) put("value", "${row.select(".itype").text}\n${row.select("" + ".homebranch").text}\n${row.select(".information").text}") } }) } } } } else if (reserveMode == "single") { body.add("biblionumbers", "") body.add("selecteditems", "") // The following is required eg in Neustadt_Holstein. Apparently, there is some kind // of copy selection *and* pickup location selection, and the options are different // whether or not JavaScript is enabled. Further research is required. For // Neustadt_Holstein it doesn't really matter since there's only one real location, so // we just add the default selected one. doc.select("input[type=radio][checked]").forEach { body.add(it.attr("name"), it.attr("value")) } doc.select("option[selected]").forEach { body.add(it.parent().attr("name"), it.attr("value")) } } else if (doc.select(".holdrow .alert").size > 0) { return OpacApi.ReservationResult(OpacApi.MultiStepResult.Status.ERROR, doc.select(".holdrow .alert").text().trim()) } if (!reservationFeeConfirmed && doc.select(".alert").size > 0) { val alert = doc.select(".alert").first() val message = alert.text if (alert.id() == "reserve_fee") { val res = OpacApi.ReservationResult( OpacApi.MultiStepResult.Status.CONFIRMATION_NEEDED) res.details = arrayListOf(arrayOf(message)) return res } } doc = httpPost("$baseurl/cgi-bin/koha/opac-reserve.pl", body.build(), ENCODING).html if (doc.select("input[type=hidden][name=biblionumber][value=${item.id}]").size > 0) { return OpacApi.ReservationResult(OpacApi.MultiStepResult.Status.OK) } else { return OpacApi.ReservationResult(OpacApi.MultiStepResult.Status.ERROR) } } override fun prolong(media: String, account: Account, useraction: Int, selection: String?): OpacApi.ProlongResult { if (media.startsWith(NOT_RENEWABLE)) { return OpacApi.ProlongResult(OpacApi.MultiStepResult.Status.ERROR, media.substring(NOT_RENEWABLE.length)) } var doc = login(account) var borrowernumber = doc.select("input[name=borrowernumber]").first()?.attr("value") doc = Jsoup.parse(httpGet("$baseurl/cgi-bin/koha/opac-renew.pl?from=opac_user&item=$media&borrowernumber=$borrowernumber", ENCODING)) val label = doc.select(".blabel").first() if (label != null && label.hasClass("label-success")) { return OpacApi.ProlongResult(OpacApi.MultiStepResult.Status.OK) } else { return OpacApi.ProlongResult(OpacApi.MultiStepResult.Status.ERROR, label?.text() ?: stringProvider.getString(StringProvider.ERROR)) } } override fun prolongAll(account: Account, useraction: Int, selection: String?): OpacApi.ProlongAllResult { var doc = login(account) if (doc.select("#renewall[method=post]").size > 0) { // LMSCloud post-2022 val formBody = FormBody.Builder() for (i in doc.select("#renewall input")) { formBody.add(i.attr("name"), i.attr("value")) } doc = Jsoup.parse(httpPost("$baseurl/cgi-bin/koha/opac-renew.pl", formBody.build(), ENCODING)) } else { // LMSCloud pre-2022 val borrowernumber = doc.select("input[name=borrowernumber]").first()?.attr("value") doc = Jsoup.parse(httpGet("$baseurl/cgi-bin/koha/opac-renew.pl?from=opac_user&borrowernumber=$borrowernumber", ENCODING)) } val label = doc.select(".blabel").first() if (label != null && doc.select(".label-success").size > 0) { return OpacApi.ProlongAllResult(OpacApi.MultiStepResult.Status.OK) } else { return OpacApi.ProlongAllResult(OpacApi.MultiStepResult.Status.ERROR, label?.text() ?: stringProvider.getString(StringProvider.ERROR)) } } override fun prolongMultiple(media: List<String>, account: Account, useraction: Int, selection: String?): OpacApi.ProlongAllResult { return OpacApi.ProlongAllResult(OpacApi.MultiStepResult.Status.UNSUPPORTED) } override fun cancel(media: String, account: Account, useraction: Int, selection: String?): OpacApi.CancelResult { login(account) val (biblionumber, reserveId) = media.split(":") val formBody = FormBody.Builder() .add("biblionumber", biblionumber) .add("reserve_id", reserveId) .add("submit", "") val doc = Jsoup.parse(httpPost("$baseurl/cgi-bin/koha/opac-modrequest.pl", formBody.build(), ENCODING)) val input = doc.select("input[name=reserve_id][value=$reserveId]").first() if (input == null) { return OpacApi.CancelResult(OpacApi.MultiStepResult.Status.OK) } else { return OpacApi.CancelResult(OpacApi.MultiStepResult.Status.ERROR, stringProvider.getString(StringProvider.ERROR)) } } override fun account(account: Account): AccountData { val doc = login(account) val accountData = AccountData(account.id) accountData.lent = parseItems(doc, ::LentItem, "#checkoutst").toMutableList() accountData.reservations = parseItems(doc, ::ReservedItem, "#holdst").toMutableList() val feesDoc = Jsoup.parse(httpGet("$baseurl/cgi-bin/koha/opac-account.pl", ENCODING)) accountData.pendingFees = parseFees(feesDoc) if (doc.select(".alert").size > 0) { val warning = doc.select(".alert").clone() for (w in warning.select("a")) { w.attr("href", w.absUrl("href")) } accountData.warning = warning.html() } return accountData } internal fun parseFees(feesDoc: Document): String? { val text = feesDoc.select("td.sum").text() return if (!text.isBlank()) text else null } internal fun <I : AccountItem> parseItems(doc: Document, constructor: () -> I, id: String): List<I> { val lentTable = doc.select(id).first() ?: return emptyList() return lentTable.select("tbody tr").map { row -> val item = constructor() row.select("td").forEach { col -> val type = col.attr("class").split(" ")[0] val content = col.text() when (type) { "itype" -> item.format = content "title" -> { item.title = content val link = col.select("a[href]").first()?.attr("href") if (link != null) { item.id = BaseApi.getQueryParamsFirst(link)["biblionumber"] } } "date_due" -> if (item is LentItem) item.deadline = parseDate(col) "branch" -> if (item is LentItem) { item.lendingBranch = content } else if (item is ReservedItem) { item.branch = content } "expirationdate" -> if (item is ReservedItem) item.expirationDate = parseDate(col) "status" -> item.status = content "modify" -> if (item is ReservedItem) { item.cancelData = "${col.select("input[name=biblionumber]").attr("value")}:${col.select("input[name=reserve_id]").attr("value")}" } "renew" -> if (item is LentItem) { val input = col.select("input[name=item]").first() if (input != null) { item.prolongData = input.attr("value") item.isRenewable = true item.status = col.select("span.renewals").text() } else { item.prolongData = NOT_RENEWABLE + content item.isRenewable = false item.status = col.text() } item.status = item.status.trim().replaceFirst(Regex("^\\(?(.*?)\\)?\$"), "$1") } // "call_no" -> Signatur // "fines" -> Gebühren (Ja/Nein) // "reserve_date" -> Reservierungsdatum } } item } } private fun parseDate(col: Element): LocalDate? { val select = col.select("span[title]").first() if (select != null) { // example: <span title="2018-11-02T23:59:00"> // or <span title="2018-11-02 23:59:00"> val isoformat = select.attr("title").replace(" ", "T") if (isoformat.isBlank() || isoformat.startsWith("0000-00-00")) { return null } else { return LocalDateTime(isoformat).toLocalDate() } } else if (col.hasAttr("data-order")) { // example: <td class="date_due sorting_1" data-order="2022-05-07 23:59:00"> val isoformat = col.attr("data-order").replace(" ", "T") if (isoformat.isBlank() || isoformat.startsWith("0000-00-00")) { return null } else { return LocalDateTime(isoformat).toLocalDate() } } return null } override fun checkAccountData(account: Account) { login(account) } private fun login(account: Account): Document { val formBody = FormBody.Builder() .add("koha_login_context", "opac") .add("koha_login_context", "opac") // sic! two times .add("userid", account.name) .add("password", account.password) val doc = Jsoup.parse(httpPost("$baseurl/cgi-bin/koha/opac-user.pl", formBody.build(), ENCODING)) doc.setBaseUri("$baseurl/cgi-bin/koha/opac-user.pl") if (doc.select(".alert").size > 0 && doc.select("#opac-auth").size > 0) { throw OpacApi.OpacErrorException(doc.select(".alert").text()) } return doc } override fun getShareUrl(id: String?, title: String?): String { return "$baseurl/cgi-bin/koha/opac-detail.pl?biblionumber=$id" } override fun getSupportFlags(): Int { return OpacApi.SUPPORT_FLAG_ENDLESS_SCROLLING or OpacApi.SUPPORT_FLAG_ACCOUNT_PROLONG_ALL or OpacApi.SUPPORT_FLAG_WARN_RESERVATION_FEES } override fun getSupportedLanguages(): Set<String>? { return null } override fun setLanguage(language: String?) { } override fun filterResults(filter: Filter, option: Filter.Option): SearchRequestResult { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }
mit
d8edcdb592c987fe1f1dd6aa4b18f945
44.283333
153
0.522543
4.540947
false
false
false
false
fossasia/rp15
app/src/main/java/org/fossasia/openevent/general/order/OrderDetailsFragment.kt
1
11114
package org.fossasia.openevent.general.order import android.Manifest import android.app.AlertDialog import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.Canvas import android.net.Uri import android.os.Bundle import android.os.Environment import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.view.Menu import android.view.MenuInflater import android.widget.Toast import androidx.core.content.ContextCompat import androidx.core.content.FileProvider import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import androidx.navigation.Navigation.findNavController import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.LinearSnapHelper import androidx.recyclerview.widget.RecyclerView import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.fragment_order_details.view.orderDetailCoordinatorLayout import kotlinx.android.synthetic.main.fragment_order_details.view.orderDetailsRecycler import kotlinx.android.synthetic.main.fragment_order_details.view.backgroundImage import kotlinx.android.synthetic.main.item_card_order_details.view.orderDetailCardView import kotlinx.android.synthetic.main.item_enlarged_qr.view.enlargedQrImage import org.fossasia.openevent.general.BuildConfig import org.fossasia.openevent.general.R import org.fossasia.openevent.general.order.invoice.DownloadInvoiceService import org.fossasia.openevent.general.utils.Utils.progressDialog import org.fossasia.openevent.general.utils.Utils.show import org.fossasia.openevent.general.utils.extensions.nonNull import org.koin.androidx.viewmodel.ext.android.viewModel import timber.log.Timber import org.fossasia.openevent.general.utils.Utils.setToolbar import org.jetbrains.anko.design.longSnackbar import org.jetbrains.anko.design.snackbar import java.io.File import java.io.FileOutputStream class OrderDetailsFragment : Fragment() { private lateinit var rootView: View private val orderDetailsViewModel by viewModel<OrderDetailsViewModel>() private val ordersRecyclerAdapter: OrderDetailsRecyclerAdapter = OrderDetailsRecyclerAdapter() private val safeArgs: OrderDetailsFragmentArgs by navArgs() private var writePermissionGranted = false private val WRITE_REQUEST_CODE = 1 private val permission = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ordersRecyclerAdapter.setOrderIdentifier(safeArgs.orderIdentifier) orderDetailsViewModel.event .nonNull() .observe(this, Observer { ordersRecyclerAdapter.setEvent(it) Picasso.get() .load(it.originalImageUrl) .error(R.drawable.header) .placeholder(R.drawable.header) .into(rootView.backgroundImage) }) orderDetailsViewModel.attendees .nonNull() .observe(this, Observer { if (it.isEmpty()) { Toast.makeText(context, getString(R.string.error_fetching_attendees), Toast.LENGTH_SHORT).show() activity?.onBackPressed() } ordersRecyclerAdapter.addAll(it) Timber.d("Fetched attendees of size %s", ordersRecyclerAdapter.itemCount) }) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { rootView = inflater.inflate(R.layout.fragment_order_details, container, false) setToolbar(activity) setHasOptionsMenu(true) val linearLayoutManager = LinearLayoutManager(context) linearLayoutManager.orientation = LinearLayoutManager.HORIZONTAL rootView.orderDetailsRecycler.layoutManager = linearLayoutManager rootView.orderDetailsRecycler.adapter = ordersRecyclerAdapter rootView.orderDetailsRecycler.isNestedScrollingEnabled = false val snapHelper = LinearSnapHelper() snapHelper.attachToRecyclerView(rootView.orderDetailsRecycler) rootView.orderDetailsRecycler.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if (newState == RecyclerView.SCROLL_STATE_IDLE) { val centerView = snapHelper.findSnapView(linearLayoutManager) centerView?.let { val itemPosition = linearLayoutManager.getPosition(it) orderDetailsViewModel.currentTicketPosition = itemPosition } } } }) val eventDetailsListener = object : OrderDetailsRecyclerAdapter.EventDetailsListener { override fun onClick(eventID: Long) { findNavController(rootView).navigate(OrderDetailsFragmentDirections .actionOrderDetailsToEventDetails(eventID)) } } ordersRecyclerAdapter.setSeeEventListener(eventDetailsListener) val qrImageListener = object : OrderDetailsRecyclerAdapter.QrImageClickListener { override fun onClick(qrImage: Bitmap) { showEnlargedQrImage(qrImage) } } ordersRecyclerAdapter.setQrImageClickListener(qrImageListener) val progressBar = progressDialog(context, getString(R.string.loading_message)) orderDetailsViewModel.progress .nonNull() .observe(viewLifecycleOwner, Observer { progressBar.show(it) }) orderDetailsViewModel.message .nonNull() .observe(viewLifecycleOwner, Observer { rootView.orderDetailCoordinatorLayout.longSnackbar(it) }) orderDetailsViewModel.loadEvent(safeArgs.eventId) orderDetailsViewModel.loadAttendeeDetails(safeArgs.orderId) writePermissionGranted = (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) return rootView } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.order_detail, menu) super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { activity?.onBackPressed() true } R.id.share_ticket -> { shareCurrentTicket() true } R.id.download_invoice -> { if (writePermissionGranted) { downloadInvoice() } else { requestPermissions(permission, WRITE_REQUEST_CODE) } true } else -> super.onOptionsItemSelected(item) } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { if (requestCode == WRITE_REQUEST_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { writePermissionGranted = true rootView.snackbar(getString(R.string.permission_granted_message, getString(R.string.external_storage))) downloadInvoice() } else { rootView.snackbar(getString(R.string.permission_denied_message, getString(R.string.external_storage))) } } } override fun onDestroyView() { super.onDestroyView() ordersRecyclerAdapter.setQrImageClickListener(null) ordersRecyclerAdapter.setSeeEventListener(null) } private fun downloadInvoice() { val downloadPath = "${BuildConfig.DEFAULT_BASE_URL}orders/invoices/${safeArgs.orderIdentifier}" val destinationPath = "${Environment.getExternalStorageDirectory().absolutePath}/DownloadManager/" val fileName = "Invoice - ${orderDetailsViewModel.event.value?.name} - ${safeArgs.orderIdentifier}" activity?.startService(DownloadInvoiceService.getDownloadService(requireContext(), downloadPath, destinationPath, fileName, orderDetailsViewModel.getToken())) } private fun showEnlargedQrImage(bitmap: Bitmap) { val brightAttributes = activity?.window?.attributes orderDetailsViewModel.brightness = brightAttributes?.screenBrightness brightAttributes?.screenBrightness = 1f activity?.window?.attributes = brightAttributes val dialogLayout = layoutInflater.inflate(R.layout.item_enlarged_qr, null) dialogLayout.enlargedQrImage.setImageBitmap(bitmap) AlertDialog.Builder(requireContext()) .setOnDismissListener { val attributes = activity?.window?.attributes attributes?.screenBrightness = orderDetailsViewModel.brightness activity?.window?.attributes = attributes }.setView(dialogLayout) .create().show() } private fun shareCurrentTicket() { val currentTicketViewHolder = rootView.orderDetailsRecycler.findViewHolderForAdapterPosition(orderDetailsViewModel.currentTicketPosition) if (currentTicketViewHolder != null && currentTicketViewHolder is OrderDetailsViewHolder) { val bitmap = getBitmapFromView(currentTicketViewHolder.itemView.rootView.orderDetailCardView) val bitmapUri = getBitmapUri(bitmap) if (bitmapUri == null) { rootView.snackbar(getString(R.string.fail_sharing_ticket)) return } val intent = Intent(Intent.ACTION_SEND) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK intent.type = "image/png" intent.putExtra(Intent.EXTRA_STREAM, bitmapUri) startActivity(intent) } else { rootView.snackbar(getString(R.string.fail_sharing_ticket)) } } private fun getBitmapUri(bitmap: Bitmap): Uri? { val myContext = context ?: return null val file = File(myContext.cacheDir, "shared_image.png") return FileOutputStream(file) .use { fileOutputStream -> bitmap.compress(Bitmap.CompressFormat.PNG, 90, fileOutputStream) FileProvider.getUriForFile(myContext, BuildConfig.APPLICATION_ID + ".provider", file) } } private fun getBitmapFromView(view: View): Bitmap { val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) view.draw(canvas) return bitmap } }
apache-2.0
589a18433e445c415dd3b2c3d6e1c89c
41.258555
119
0.685532
5.274798
false
false
false
false
AlexandrDrinov/kotlin-koans-edu
src/i_introduction/_3_Default_Arguments/DefaultAndNamedParams.kt
1
385
package i_introduction._3_Default_Arguments fun foo(name: String, number: Int = 42 , toUpperCase : Boolean = false ): String { return (if (toUpperCase) name.toUpperCase() 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
c45345fac7f8ea4e9291bb907962c4e8
31.083333
82
0.584416
3.632075
false
false
false
false
savoirfairelinux/ring-client-android
ring-android/libjamiclient/src/main/kotlin/net/jami/model/TrustRequest.kt
1
1690
/* * Copyright (C) 2004-2021 Savoir-faire Linux Inc. * * Author: Aline Bonnet <[email protected]> * Author: Adrien Béraud <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.jami.model import ezvcard.Ezvcard import ezvcard.VCard import io.reactivex.rxjava3.core.Single class TrustRequest( val accountId: String, val from: Uri, val timestamp: Long, payload: String?, val conversationUri: Uri?) { var vCard: VCard? = if (payload == null) null else Ezvcard.parse(payload).first() var profile: Single<Profile>? = null var message: String? = null constructor(accountId: String, info: Map<String, String>) : this(accountId, Uri.fromId(info["from"]!!), info["received"]!!.toLong() * 1000L, info["payload"], info["conversationId"]?.let { uriString -> if (uriString.isEmpty()) null else Uri(Uri.SWARM_SCHEME, uriString) }) val fullName: String? get() = vCard?.formattedName?.value val displayName: String get() = fullName ?: from.toString() }
gpl-3.0
e4ac9a3ae0e68bb4d9488e6f26593b74
36.533333
175
0.702783
3.873853
false
false
false
false
grote/Transportr
app/src/main/java/de/grobox/transportr/trips/detail/TripReloader.kt
1
4121
/* * Transportr * * Copyright (c) 2013 - 2021 Torsten Grote * * This program is Free Software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.grobox.transportr.trips.detail import androidx.lifecycle.MutableLiveData import androidx.annotation.WorkerThread import de.grobox.transportr.settings.SettingsManager import de.grobox.transportr.trips.TripQuery import de.grobox.transportr.utils.SingleLiveEvent import de.schildbach.pte.NetworkProvider import de.schildbach.pte.dto.QueryTripsResult import de.schildbach.pte.dto.QueryTripsResult.Status.OK import de.schildbach.pte.dto.Trip import de.schildbach.pte.dto.TripOptions import java.util.* internal class TripReloader( private val networkProvider: NetworkProvider, private val settingsManager: SettingsManager, private val query: TripQuery, private val trip: MutableLiveData<Trip>, private val errorString: String, private val tripReloadError: SingleLiveEvent<String>) { fun reload() { // use a new date slightly earlier to avoid missing the right trip val newDate = Date() newDate.time = query.date.time - 5000 Thread { try { val queryTripsResult = networkProvider.queryTrips( query.from.location, query.via?.location, query.to.location, newDate, true, TripOptions(query.products, settingsManager.optimize, settingsManager.walkSpeed, null, null) ) if (queryTripsResult.status == OK && queryTripsResult.trips.size > 0) { onTripReloaded(queryTripsResult) } else { tripReloadError.postValue(errorString + "\n" + queryTripsResult.status.name) } } catch (e: Exception) { tripReloadError.postValue(errorString + "\n" + e.toString()) } }.start() } @WorkerThread private fun onTripReloaded(result: QueryTripsResult) { val oldTrip = this.trip.value ?: throw IllegalStateException() for (newTrip in result.trips) { if (oldTrip.isTheSame(newTrip)) { trip.postValue(newTrip) return } } tripReloadError.postValue(errorString) } private fun Trip.isTheSame(newTrip: Trip): Boolean { // we can not rely on the trip ID as it is too generic with some providers if (numChanges != newTrip.numChanges) return false if (legs.size != newTrip.legs.size) return false if (getPlannedDuration() != newTrip.getPlannedDuration()) return false if (firstPublicLeg?.getDepartureTime(true) != newTrip.firstPublicLeg?.getDepartureTime(true)) return false if (lastPublicLeg?.getArrivalTime(true) != newTrip.lastPublicLeg?.getArrivalTime(true)) return false if (firstPublicLeg?.line?.label != newTrip.firstPublicLeg?.line?.label) return false if (lastPublicLeg?.line?.label != newTrip.lastPublicLeg?.line?.label) return false if (firstPublicLeg == null && firstDepartureTime != newTrip.firstDepartureTime) return false if (lastPublicLeg == null && lastArrivalTime != newTrip.lastArrivalTime) return false return true } private fun Trip.getPlannedDuration(): Long { val first = firstPublicLeg?.getDepartureTime(true) ?: firstDepartureTime val last = lastPublicLeg?.getDepartureTime(true) ?: lastArrivalTime return last.time - first.time } }
gpl-3.0
da3719590569d9ad904e5f8eb1555187
41.484536
114
0.674108
4.398079
false
false
false
false
daemontus/Distributed-CTL-Model-Checker
src/main/kotlin/com/github/sybila/checker/partition/IntervalPartition.kt
3
1212
package com.github.sybila.checker.partition import com.github.sybila.checker.Model import com.github.sybila.checker.MutableStateMap import com.github.sybila.checker.Partition import com.github.sybila.checker.map.mutable.ContinuousStateMap import com.github.sybila.checker.map.mutable.HashStateMap class IntervalPartition<Params: Any>( override val partitionId: Int, val intervals: List<IntRange>, model: Model<Params> ) : Partition<Params>, Model<Params> by model { override val partitionCount: Int = intervals.size override fun Int.owner(): Int = intervals.indexOfFirst { this in it } fun myInterval(): IntRange = intervals[partitionId] override fun newLocalMutableMap(partition: Int): MutableStateMap<Params> { return if (partition == partitionId) { val range = intervals[partition] ContinuousStateMap(range.first, range.last + 1, ff) } else HashStateMap(ff) } } fun <Params : Any> List<Pair<Model<Params>, IntRange>>.asIntervalPartitions(): List<IntervalPartition<Params>> { val intervals = this.map { it.second } return this.map { it.first }.mapIndexed { i, model -> IntervalPartition(i, intervals, model) } }
gpl-3.0
49c87c492c0cc95d7b5a5444e2e689ac
36.90625
112
0.721122
4.150685
false
false
false
false
google/private-compute-libraries
java/com/google/android/libraries/pcc/chronicle/samples/util/ChronicleHelper.kt
1
8149
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.pcc.chronicle.samples.util import android.content.Context import com.google.android.libraries.pcc.chronicle.analysis.DefaultChronicleContext import com.google.android.libraries.pcc.chronicle.analysis.DefaultPolicySet import com.google.android.libraries.pcc.chronicle.analysis.PolicySet import com.google.android.libraries.pcc.chronicle.analysis.impl.ChroniclePolicyEngine import com.google.android.libraries.pcc.chronicle.api.Chronicle import com.google.android.libraries.pcc.chronicle.api.ConnectionProvider import com.google.android.libraries.pcc.chronicle.api.DataTypeDescriptor import com.google.android.libraries.pcc.chronicle.api.DataTypeDescriptorSet import com.google.android.libraries.pcc.chronicle.api.ProcessorNode import com.google.android.libraries.pcc.chronicle.api.flags.Flags import com.google.android.libraries.pcc.chronicle.api.flags.FlagsReader import com.google.android.libraries.pcc.chronicle.api.integration.DefaultChronicle import com.google.android.libraries.pcc.chronicle.api.integration.DefaultChronicle.Config.PolicyMode import com.google.android.libraries.pcc.chronicle.api.integration.DefaultDataTypeDescriptorSet import com.google.android.libraries.pcc.chronicle.api.policy.DefaultPolicyConformanceCheck import com.google.android.libraries.pcc.chronicle.api.policy.Policy import com.google.android.libraries.pcc.chronicle.api.remote.IRemote import com.google.android.libraries.pcc.chronicle.api.remote.server.RemoteServer import com.google.android.libraries.pcc.chronicle.remote.RemoteContext import com.google.android.libraries.pcc.chronicle.remote.RemotePolicyChecker import com.google.android.libraries.pcc.chronicle.remote.RemoteRouter import com.google.android.libraries.pcc.chronicle.remote.handler.RemoteServerHandlerFactory import com.google.android.libraries.pcc.chronicle.remote.impl.ClientDetailsProviderImpl import com.google.android.libraries.pcc.chronicle.remote.impl.RemoteContextImpl import com.google.android.libraries.pcc.chronicle.remote.impl.RemotePolicyCheckerImpl import com.google.android.libraries.pcc.chronicle.util.TypedMap import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow /** * Serves as a single point of integration when introducing Chronicle to a host application using * default implementations of many of Chronicle's components. * * **Note:** This, or something quite similar to it, is under consideration for being made into * general public Chronicle API. * * This class will typically be instantiated either by a dependency injection framework like Dagger * or directly, within the host application's [android.app.Application] class. For example: * * ``` * class MyApplication : Application() { * lateinit var chronicleHelper: ChronicleHelper * * override fun onCreate() { * super.onCreate() * * // ... Other application.onCreate() setup ... * * chronicleHelper = * ChronicleHelper( * policies = setOf(PolicyA, PolicyB), * connectionProviders = setOf(FooConnectionProvider(), BarConnectionProvider()), * remoteServers = setOf(BazRemoteStoreServer()) * ) * } * } * ``` */ class ChronicleHelper( policies: Set<Policy>, connectionProviders: Set<ConnectionProvider>, remoteServers: Set<RemoteServer<*>> = emptySet(), initialConnectionContext: TypedMap = TypedMap(), initialFlags: Flags = Flags(), initialProcessorNodes: Set<ProcessorNode> = emptySet() ) { private val policySet: PolicySet = DefaultPolicySet(policies) private val dataTypeDescriptors: DataTypeDescriptorSet = DefaultDataTypeDescriptorSet(connectionProviders.dtds + remoteServers.dtds) private val flagsFlow = MutableStateFlow(initialFlags) private val chronicleContext = DefaultChronicleContext( connectionProviders + remoteServers, initialProcessorNodes, policySet, dataTypeDescriptors, initialConnectionContext ) private val defaultChronicle: DefaultChronicle by lazy { DefaultChronicle( chronicleContext, ChroniclePolicyEngine(), DefaultChronicle.Config(PolicyMode.STRICT, DefaultPolicyConformanceCheck()), object : FlagsReader { override val config: StateFlow<Flags> = flagsFlow } ) } private val remoteContext: RemoteContext = RemoteContextImpl(remoteServers) private val remotePolicyChecker: RemotePolicyChecker by lazy { RemotePolicyCheckerImpl(chronicle, policySet) } /** * Returns an instance of [Chronicle] that can be used by feature developers within * [ProcessorNodes][ProcessorNode]. * * For example: * ``` * class MyActivity : Activity(), ProcessorNode { * private val chronicle = (applicationContext as MyApplication).chronicleHelper.chronicle * // ... other fields for MyActivity ... * * fun handlePersonCreateButtonClicked() { * scope.launch { * val connection = * chronicle.getConnectionOrThrow( * ConnectionRequest(PeopleWriter::class.java, this, policy = null) * ) * connection.putPerson(Person.newBuilder().setName("Larry").setAge(42).build()) * } * } * * // ... other methods for MyActivity ... * } * ``` */ val chronicle: Chronicle get() = defaultChronicle /** Updates Chronicle feature flags. */ fun setFlags(flags: Flags) { flagsFlow.value = flags } /** * Updates the connection context [TypedMap] used by the policy engine to verify a policy is valid * given its [Policy.allowedContext] rules. */ fun setConnectionContext(connectionContext: TypedMap) { defaultChronicle.updateConnectionContext(connectionContext) } /** * Creates an implementation of the [IBinder] used to support the server/proxy-side of Chronicle * remote connections: [IRemote]. * * The provided [serviceScope] is used to launch coroutines when handling remote requests from * clients. It should be configured with a [CoroutineDispatcher] which does not run on the main * thread and it is suggested to also use a [SupervisorJob] so that one failing request does not * cause all other requests to fail for the lifetime of the service. * * This method should be used within [Service.onBind]: * ``` * class MyChronicleService : Service() { * private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) * * override fun onBind(intent: Intent?): IBinder? { * super.onBind(intent) * val chronicleHelper = (applicationContext as MyApplication).chronicleHelper * return chronicleHelper.createRemoteConnectionBinder(this, scope, intent) * } * * override fun onDestroy() { * scope.cancel() * super.onDestroy() * } * } * ``` * * @param context Reference to the Android component which will own the returned [IRemote] binder * (an [android.app.Service], typically). * @param scope A [CoroutineScope] tied to the lifecycle of the Android component which will own * the returned [IRemote] binder (an [android.app.Service], typically). */ fun createRemoteConnectionBinder(context: Context, scope: CoroutineScope): IRemote { return RemoteRouter( scope, remoteContext, remotePolicyChecker, RemoteServerHandlerFactory(), ClientDetailsProviderImpl(context) ) } private val Set<ConnectionProvider>.dtds: Set<DataTypeDescriptor> get() = map { it.dataType.descriptor }.toSet() }
apache-2.0
fe1cad90cfce33e754132a658dbbe567
40.156566
100
0.746349
4.348453
false
false
false
false
xfmax/BasePedo
app/src/main/java/com/base/basepedo/base/StepMode.kt
1
1359
package com.base.basepedo.base import android.content.Context import android.hardware.SensorEventListener import android.hardware.SensorManager import com.base.basepedo.callback.StepCallBack /** * 计步模式分为 加速度传感器 google内置计步器 * * * Created by base on 2016/8/17. */ abstract class StepMode(private val context: Context, var stepCallBack: StepCallBack) : SensorEventListener { @JvmField var sensorManager: SensorManager? = null @JvmField var isAvailable = false val step: Boolean get() { prepareSensorManager() registerSensor() return isAvailable } protected abstract fun registerSensor() private fun prepareSensorManager() { if (sensorManager != null) { sensorManager!!.unregisterListener(this) sensorManager = null } sensorManager = context .getSystemService(Context.SENSOR_SERVICE) as SensorManager // getLock(this); // android4.4以后可以使用计步传感器 // int VERSION_CODES = android.os.Build.VERSION.SDK_INT; // if (VERSION_CODES >= 19) { // addCountStepListener(); // } else { // addBasePedoListener(); // } } companion object { @JvmField var CURRENT_SETP = 0 } }
apache-2.0
2fc2e1774b768257fb5d7c4e7a2d456e
25.591837
109
0.626247
4.25817
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/economy/transactions/TransactionsExecutor.kt
1
16432
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.transactions import dev.kord.common.entity.ButtonStyle import dev.kord.common.entity.Snowflake import dev.kord.rest.builder.message.EmbedBuilder import net.perfectdreams.discordinteraktions.common.builder.message.MessageBuilder import net.perfectdreams.discordinteraktions.common.builder.message.actionRow import net.perfectdreams.discordinteraktions.common.builder.message.embed import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments import net.perfectdreams.discordinteraktions.common.utils.footer import net.perfectdreams.i18nhelper.core.I18nContext import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions import net.perfectdreams.loritta.cinnamon.discord.interactions.components.disabledButton import net.perfectdreams.loritta.cinnamon.discord.interactions.components.interactiveButton import net.perfectdreams.loritta.cinnamon.discord.interactions.components.loriEmoji import net.perfectdreams.loritta.cinnamon.discord.interactions.components.selectMenu import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.declarations.SonhosCommand import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.transactions.transactiontransformers.* import net.perfectdreams.loritta.cinnamon.discord.utils.ComponentDataUtils import net.perfectdreams.loritta.cinnamon.discord.utils.UserId import net.perfectdreams.loritta.cinnamon.discord.utils.toKordColor import net.perfectdreams.loritta.cinnamon.emotes.Emotes import net.perfectdreams.loritta.cinnamon.pudding.data.* import net.perfectdreams.loritta.common.utils.LorittaColors import net.perfectdreams.loritta.common.utils.TransactionType import net.perfectdreams.loritta.common.utils.text.TextUtils.stripCodeBackticks import kotlin.math.ceil class TransactionsExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta) { companion object { private const val TRANSACTIONS_PER_PAGE = 10 suspend fun createMessage( loritta: LorittaBot, i18nContext: I18nContext, userId: Snowflake, viewingTransactionsOfUserId: Snowflake, page: Long, userFacingTransactionTypeFilter: List<TransactionType> ): suspend MessageBuilder.() -> (Unit) = { // If the list is empty, we will use *all* transaction types in the filter // This makes it easier because you don't need to manually deselect every single filter before you can filter by a specific // transaction type. val transactionTypeFilter = userFacingTransactionTypeFilter.ifEmpty { TransactionType.values().toList() } val transactions = loritta.pudding.sonhos.getUserTransactions( UserId(viewingTransactionsOfUserId), transactionTypeFilter, TRANSACTIONS_PER_PAGE, (page * TRANSACTIONS_PER_PAGE) ) val totalTransactions = loritta.pudding.sonhos.getUserTotalTransactions( UserId(viewingTransactionsOfUserId), transactionTypeFilter ) val totalPages = ceil((totalTransactions / TRANSACTIONS_PER_PAGE.toDouble())).toLong() val isSelf = viewingTransactionsOfUserId.value == userId.value val cachedUserInfo = loritta.getCachedUserInfo(viewingTransactionsOfUserId) ?: error("Missing cached user info!") content = i18nContext.get(SonhosCommand.TRANSACTIONS_I18N_PREFIX.NotAllTransactionsAreHere) if (page >= totalPages && totalPages != 0L) { // ===[ EASTER EGG: USER INPUT TOO MANY PAGES ]=== apply( createTooManyPagesMessage( i18nContext, userId, viewingTransactionsOfUserId, totalPages, userFacingTransactionTypeFilter ) ) } else { embed { if (totalPages != 0L) { // ===[ NORMAL TRANSACTION VIEW ]=== createTransactionViewEmbed( loritta, i18nContext, isSelf, cachedUserInfo, transactions, page, totalTransactions ) } else { // ===[ NO MATCHING TRANSACTIONS VIEW ]=== apply( createNoMatchingTransactionsEmbed( loritta, i18nContext, isSelf, cachedUserInfo ) ) } } val addLeftButton = page != 0L && totalTransactions != 0L val addRightButton = totalPages > (page + 1) && totalTransactions != 0L actionRow { if (addLeftButton) { interactiveButton( ButtonStyle.Primary, ChangeTransactionPageButtonClickExecutor, ComponentDataUtils.encode( ChangeTransactionPageData( userId, viewingTransactionsOfUserId, page - 1, userFacingTransactionTypeFilter ) ) ) { loriEmoji = Emotes.ChevronLeft } } else { disabledButton(ButtonStyle.Primary) { loriEmoji = Emotes.ChevronLeft } } if (addRightButton) { interactiveButton( ButtonStyle.Primary, ChangeTransactionPageButtonClickExecutor, ComponentDataUtils.encode( ChangeTransactionPageData( userId, viewingTransactionsOfUserId, page + 1, userFacingTransactionTypeFilter ) ) ) { loriEmoji = Emotes.ChevronRight } } else { disabledButton(ButtonStyle.Primary) { loriEmoji = Emotes.ChevronRight } } } actionRow { selectMenu( ChangeTransactionFilterSelectMenuExecutor, ComponentDataUtils.encode( ChangeTransactionFilterData( userId, viewingTransactionsOfUserId, page, userFacingTransactionTypeFilter ) ) ) { val transactionTypes = TransactionType.values() this.allowedValues = 1..(25.coerceAtMost(transactionTypes.size)) for (transactionType in transactionTypes) { option(i18nContext.get(transactionType.title), transactionType.name) { description = i18nContext.get(transactionType.description) loriEmoji = transactionType.emote default = transactionType in userFacingTransactionTypeFilter } } } } } } private suspend fun EmbedBuilder.createTransactionViewEmbed( loritta: LorittaBot, i18nContext: I18nContext, isSelf: Boolean, cachedUserInfo: CachedUserInfo, transactions: List<SonhosTransaction>, page: Long, totalTransactions: Long ) { // ===[ NORMAL TRANSACTION VIEW ]=== val cachedUserInfos = mutableMapOf<UserId, CachedUserInfo?>( cachedUserInfo.id to cachedUserInfo ) title = buildString { if (isSelf) append(i18nContext.get(SonhosCommand.TRANSACTIONS_I18N_PREFIX.YourTransactions)) else append(i18nContext.get(SonhosCommand.TRANSACTIONS_I18N_PREFIX.UserTransactions("${cachedUserInfo.name.stripCodeBackticks()}#${cachedUserInfo?.discriminator}"))) append(" — ") append(i18nContext.get(SonhosCommand.TRANSACTIONS_I18N_PREFIX.Page(page + 1))) } color = LorittaColors.LorittaAqua.toKordColor() description = buildString { for (transaction in transactions) { val stringBuilderBlock = when (transaction) { // ===[ PAYMENTS ]=== is PaymentSonhosTransaction -> PaymentSonhosTransactionTransformer.transform(loritta, i18nContext, cachedUserInfo, cachedUserInfos, transaction) // ===[ BROKER ]=== is BrokerSonhosTransaction -> BrokerSonhosTransactionTransformer.transform(loritta, i18nContext, cachedUserInfo, cachedUserInfos, transaction) // ===[ COIN FLIP BET ]=== is CoinFlipBetSonhosTransaction -> CoinFlipBetSonhosTransactionTransformer.transform(loritta, i18nContext, cachedUserInfo, cachedUserInfos, transaction) // ===[ COIN FLIP BET GLOBAL ]=== is CoinFlipBetGlobalSonhosTransaction -> CoinFlipBetGlobalSonhosTransactionTransformer.transform(loritta, i18nContext, cachedUserInfo, cachedUserInfos, transaction) // ===[ EMOJI FIGHT BET ]=== is EmojiFightBetSonhosTransaction -> EmojiFightBetSonhosTransactionTransformer.transform(loritta, i18nContext, cachedUserInfo, cachedUserInfos, transaction) // ===[ SPARKLYPOWER LSX ]=== is SparklyPowerLSXSonhosTransaction -> SparklyPowerLSXSonhosTransactionTransformer.transform(loritta, i18nContext, cachedUserInfo, cachedUserInfos, transaction) // ===[ SONHOS BUNDLES ]=== is SonhosBundlePurchaseSonhosTransaction -> SonhosBundlePurchaseSonhosTransactionTransformer.transform(loritta, i18nContext, cachedUserInfo, cachedUserInfos, transaction) // ===[ DAILY TAX ]=== is DailyTaxSonhosTransaction -> DailyTaxSonhosTransactionTransformer.transform(loritta, i18nContext, cachedUserInfo, cachedUserInfos, transaction) // ===[ DIVINE INTERVENTION ]=== is DivineInterventionSonhosTransaction -> DivineInterventionSonhosTransactionTransformer.transform(loritta, i18nContext, cachedUserInfo, cachedUserInfos, transaction) // ===[ BOT VOTE ]=== is BotVoteSonhosTransaction -> BotVoteTransactionTransformer.transform(loritta, i18nContext, cachedUserInfo, cachedUserInfos, transaction) // ===[ SHIP EFFECT ]=== is ShipEffectSonhosTransaction -> ShipEffectSonhosTransactionTransformer.transform(loritta, i18nContext, cachedUserInfo, cachedUserInfos, transaction) // This should never happen because we do a left join with a "isNotNull" check is UnknownSonhosTransaction -> UnknownSonhosTransactionTransformer.transform(loritta, i18nContext, cachedUserInfo, cachedUserInfos, transaction) } append("[<t:${transaction.timestamp.epochSeconds}:d> <t:${transaction.timestamp.epochSeconds}:t> | <t:${transaction.timestamp.epochSeconds}:R>]") append(" ") stringBuilderBlock() append("\n") } } footer(i18nContext.get(SonhosCommand.TRANSACTIONS_I18N_PREFIX.TransactionsQuantity(totalTransactions))) } private fun createNoMatchingTransactionsEmbed( loritta: LorittaBot, i18nContext: I18nContext, isSelf: Boolean, cachedUserInfo: CachedUserInfo?, ): EmbedBuilder.() -> (Unit) = { title = buildString { if (isSelf) append(i18nContext.get(SonhosCommand.TRANSACTIONS_I18N_PREFIX.YourTransactions)) else append(i18nContext.get(SonhosCommand.TRANSACTIONS_I18N_PREFIX.UserTransactions("${cachedUserInfo?.name?.stripCodeBackticks()}#${cachedUserInfo?.discriminator}"))) } color = LorittaColors.LorittaRed.toKordColor() description = i18nContext.get(SonhosCommand.TRANSACTIONS_I18N_PREFIX.NoTransactionsFunnyMessages).random() image = "https://assets.perfectdreams.media/loritta/emotes/lori-sob.png" } suspend fun createTooManyPagesMessage( i18nContext: I18nContext, userId: Snowflake, viewingTransactionsOfUserId: Snowflake, totalPages: Long, transactionTypeFilter: List<TransactionType> ): MessageBuilder.() -> (Unit) = { embed { title = i18nContext.get(SonhosCommand.TRANSACTIONS_I18N_PREFIX.UnknownPage.Title) description = i18nContext.get(SonhosCommand.TRANSACTIONS_I18N_PREFIX.UnknownPage.Description) .joinToString("\n") color = LorittaColors.LorittaRed.toKordColor() // TODO: Host this somewhere else image = "https://cdn.discordapp.com/attachments/513405772911345664/930945637841788958/fon_final_v3_sticker_small.png" } actionRow { interactiveButton( ButtonStyle.Primary, ChangeTransactionPageButtonClickExecutor, ComponentDataUtils.encode( ChangeTransactionPageData( userId, viewingTransactionsOfUserId, totalPages - 1, transactionTypeFilter ) ) ) { label = i18nContext.get(SonhosCommand.TRANSACTIONS_I18N_PREFIX.UnknownPage.GoToTheLastPage) loriEmoji = Emotes.LoriSob } } } } inner class Options : LocalizedApplicationCommandOptions(loritta) { val user = optionalUser("user", SonhosCommand.TRANSACTIONS_I18N_PREFIX.Options.User.Text) val page = optionalInteger("page", SonhosCommand.TRANSACTIONS_I18N_PREFIX.Options.Page.Text) } override val options = Options() override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) { context.deferChannelMessage() // Defer because this sometimes takes too long val userId = args[options.user]?.id ?: context.user.id val page = ((args[options.page] ?: 1L) - 1) .coerceAtLeast(0) val message = createMessage( context.loritta, context.i18nContext, context.user.id, userId, page, listOf() // Empty = All ) context.sendMessage { message() } } }
agpl-3.0
bbe48354688b4229865a8fc5a7bb5026
47.04386
194
0.572915
6.031571
false
false
false
false
j2ghz/tachiyomi-extensions
src/all/mmrcms/src/eu/kanade/tachiyomi/extension/all/mmrcms/MyMangaReaderCMSSource.kt
1
12364
package eu.kanade.tachiyomi.extension.all.mmrcms import android.net.Uri import com.github.salomonbrys.kotson.array import com.github.salomonbrys.kotson.get import com.github.salomonbrys.kotson.string import com.google.gson.JsonParser import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.* import eu.kanade.tachiyomi.source.online.HttpSource import eu.kanade.tachiyomi.util.asJsoup import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Element import java.text.ParseException import java.text.SimpleDateFormat import java.util.* class MyMangaReaderCMSSource(override val lang: String, override val name: String, override val baseUrl: String, override val supportsLatest: Boolean, private val itemUrl: String, private val categoryMappings: List<Pair<String, String>>, private val tagMappings: List<Pair<String, String>>?) : HttpSource() { private val jsonParser = JsonParser() private val itemUrlPath = Uri.parse(itemUrl).pathSegments.first() private val parsedBaseUrl = Uri.parse(baseUrl) override fun popularMangaRequest(page: Int) = GET("$baseUrl/filterList?page=$page&sortBy=views&asc=false") override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { //Query overrides everything val url: Uri.Builder if(query.isNotBlank()) { url = Uri.parse("$baseUrl/search")!!.buildUpon() url.appendQueryParameter("query", query) } else { url = Uri.parse("$baseUrl/filterList?page=$page")!!.buildUpon() filters.filterIsInstance<UriFilter>() .forEach { it.addToUri(url) } } return GET(url.toString()) } override fun latestUpdatesRequest(page: Int) = GET("$baseUrl/filterList?page=$page&sortBy=last_release&asc=false") override fun popularMangaParse(response: Response) = internalMangaParse(response) override fun searchMangaParse(response: Response): MangasPage { return if(response.request().url().queryParameter("query")?.isNotBlank() == true) { //If a search query was specified, use search instead! MangasPage(jsonParser .parse(response.body()!!.string())["suggestions"].array .map { SManga.create().apply { val segment = it["data"].string url = getUrlWithoutBaseUrl(itemUrl + segment) title = it["value"].string // Guess thumbnails thumbnail_url = "$baseUrl/uploads/manga/$segment/cover/cover_250x350.jpg" } }, false) } else { internalMangaParse(response) } } override fun latestUpdatesParse(response: Response) = internalMangaParse(response) private fun internalMangaParse(response: Response): MangasPage { val document = response.asJsoup() return MangasPage(document.getElementsByClass("col-sm-6").map { SManga.create().apply { val urlElement = it.getElementsByClass("chart-title") url = getUrlWithoutBaseUrl(urlElement.attr("href")) title = urlElement.text().trim() thumbnail_url = it.select(".media-left img").attr("src") // Guess thumbnails on broken websites if (thumbnail_url?.isBlank() != false || thumbnail_url?.endsWith("no-image.png") != false) { thumbnail_url = "$baseUrl/uploads/manga/${url.substringAfterLast('/')}/cover/cover_250x350.jpg" } } }, document.select(".pagination a[rel=next]").isNotEmpty()) } private fun getUrlWithoutBaseUrl(newUrl: String): String { val parsedNewUrl = Uri.parse(newUrl) val newPathSegments = parsedNewUrl.pathSegments.toMutableList() for(i in parsedBaseUrl.pathSegments) { if(i.trim().equals(newPathSegments.first(), true)) { newPathSegments.removeAt(0) } else break } val builtUrl = parsedNewUrl.buildUpon().path("/") newPathSegments.forEach { builtUrl.appendPath(it) } var out = builtUrl.build().encodedPath if (parsedNewUrl.encodedQuery != null) out += "?" + parsedNewUrl.encodedQuery if (parsedNewUrl.encodedFragment != null) out += "#" + parsedNewUrl.encodedFragment return out } override fun mangaDetailsParse(response:Response) = SManga.create().apply { val document = response.asJsoup() title = document.getElementsByClass("widget-title").text().trim() thumbnail_url = document.select(".row .img-responsive").attr("src") description = document.select(".row .well p").text().trim() var cur: String? = null for(element in document.select(".row .dl-horizontal").select("dt,dd")) { when(element.tagName()) { "dt" -> cur = element.text().trim().toLowerCase() "dd" -> when(cur) { "author(s)", "autor(es)", "auteur(s)", "著作", "yazar(lar)", "mangaka(lar)", "pengarang/penulis", "pengarang", "penulis", "autor", "المؤلف", "перевод" -> author = element.text() "artist(s)", "artiste(s)", "sanatçi(lar)", "artista(s)", "artist(s)/ilustrator", "الرسام", "seniman" -> artist = element.text() "categories", "categorías", "catégories", "ジャンル", "kategoriler", "categorias", "kategorie", "التصنيفات", "жанр", "kategori" -> genre = element.getElementsByTag("a").joinToString { it.text().trim() } "status", "statut", "estado", "状態", "durum", "الحالة", "статус" -> status = when(element.text().trim().toLowerCase()) { "complete", "مكتملة", "complet" -> SManga.COMPLETED "ongoing", "مستمرة", "en cours" -> SManga.ONGOING else -> SManga.UNKNOWN } } } } } /** * Parses the response from the site and returns a list of chapters. * * Overriden to allow for null chapters * * @param response the response from the site. */ override fun chapterListParse(response: Response): List<SChapter> { val document = response.asJsoup() return document.select(chapterListSelector()).mapNotNull { nullableChapterFromElement(it) } } /** * Returns the Jsoup selector that returns a list of [Element] corresponding to each chapter. */ fun chapterListSelector() = ".chapters > li:not(.btn)" /** * Returns a chapter from the given element. * * @param element an element obtained from [chapterListSelector]. */ private fun nullableChapterFromElement(element: Element): SChapter? { val titleWrapper = element.getElementsByClass("chapter-title-rtl").first() val url = titleWrapper.getElementsByTag("a").attr("href") // Ensure chapter actually links to a manga // Some websites use the chapters box to link to post announcements if (!Uri.parse(url).pathSegments.firstOrNull().equals(itemUrlPath, true)) { return null } val chapter = SChapter.create() chapter.url = getUrlWithoutBaseUrl(url) chapter.name = titleWrapper.text() // Parse date val dateText = element.getElementsByClass("date-chapter-title-rtl").text().trim() val formattedDate = try { DATE_FORMAT.parse(dateText).time } catch (e: ParseException) { 0L } chapter.date_upload = formattedDate return chapter } override fun pageListParse(response: Response) = response.asJsoup().select("#all > .img-responsive") .mapIndexed { i, e -> var url = e.attr("data-src") if(url.isBlank()) { url = e.attr("src") } url = url.trim() Page(i, url, url) } override fun imageUrlParse(response: Response) = throw UnsupportedOperationException("Unused method called!") private fun getInitialFilterList() = listOf<Filter<*>>( Filter.Header("NOTE: Ignored if using text search!"), Filter.Separator(), AuthorFilter(), UriSelectFilter("Category", "cat", arrayOf("" to "Any", *categoryMappings.toTypedArray() ) ), UriSelectFilter("Begins with", "alpha", arrayOf("" to "Any", *"#ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray().map { Pair(it.toString(), it.toString()) }.toTypedArray() ) ), SortFilter() ) /** * Returns the list of filters for the source. */ override fun getFilterList() = FilterList( if(tagMappings != null) (getInitialFilterList() + UriSelectFilter("Tag", "tag", arrayOf("" to "Any", *tagMappings.toTypedArray() ))) else getInitialFilterList() ) /** * Class that creates a select filter. Each entry in the dropdown has a name and a display name. * If an entry is selected it is appended as a query parameter onto the end of the URI. * If `firstIsUnspecified` is set to true, if the first entry is selected, nothing will be appended on the the URI. */ //vals: <name, display> open class UriSelectFilter(displayName: String, val uriParam: String, val vals: Array<Pair<String, String>>, val firstIsUnspecified: Boolean = true, defaultValue: Int = 0) : Filter.Select<String>(displayName, vals.map { it.second }.toTypedArray(), defaultValue), UriFilter { override fun addToUri(uri: Uri.Builder) { if (state != 0 || !firstIsUnspecified) uri.appendQueryParameter(uriParam, vals[state].first) } } class AuthorFilter: Filter.Text("Author"), UriFilter { override fun addToUri(uri: Uri.Builder) { uri.appendQueryParameter("author", state) } } class SortFilter: Filter.Sort("Sort", sortables.map { it.second }.toTypedArray(), Filter.Sort.Selection(0, true)), UriFilter { override fun addToUri(uri: Uri.Builder) { uri.appendQueryParameter("sortBy", sortables[state!!.index].first) uri.appendQueryParameter("asc", state!!.ascending.toString()) } companion object { private val sortables = arrayOf( "name" to "Name", "views" to "Popularity", "last_release" to "Last update" ) } } /** * Represents a filter that is able to modify a URI. */ interface UriFilter { fun addToUri(uri: Uri.Builder) } companion object { private val DATE_FORMAT = SimpleDateFormat("d MMM. yyyy", Locale.US) } }
apache-2.0
4cee54a4dfb91c832abee6764c3c24eb
37.283489
119
0.539181
4.866931
false
false
false
false
angcyo/RLibrary
uiview/src/main/java/com/angcyo/uiview/viewgroup/RTextLayout.kt
1
1910
package com.angcyo.uiview.viewgroup import android.content.Context import android.util.AttributeSet import android.util.TypedValue import android.view.Gravity import android.widget.FrameLayout import com.angcyo.uiview.R import com.angcyo.uiview.kotlin.density import com.angcyo.uiview.kotlin.getColor import com.angcyo.uiview.skin.SkinHelper import com.angcyo.uiview.widget.RTextView /** * Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved. * 项目名称: * 类的描述: * 创建人员:Robi * 创建时间:2017/09/12 17:26 * 修改人员:Robi * 修改时间:2017/09/12 17:26 * 修改备注: * Version: 1.0.0 */ open class RTextLayout(context: Context, attributeSet: AttributeSet? = null) : FrameLayout(context, attributeSet) { var leftTextView: RTextView = RTextView(context) var rightTextView: RTextView = RTextView(context) init { leftTextView.setTextColor(getColor(R.color.base_text_color)) rightTextView.setTextColor(getColor(R.color.base_text_color_dark)) if (isInEditMode) { leftTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 14f * density) rightTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 12f * density) leftTextView.text = "左边的文本" rightTextView.text = "右边的文本" } else { leftTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, SkinHelper.getSkin().mainTextSize) rightTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, SkinHelper.getSkin().subTextSize) } addView(leftTextView, LayoutParams(-2, -2).apply { this.gravity = (Gravity.CENTER_VERTICAL + Gravity.LEFT) }) addView(rightTextView, LayoutParams(-2, -2).apply { this.gravity = (Gravity.CENTER_VERTICAL + Gravity.RIGHT) }) } }
apache-2.0
fe3b814c972a18b0233c9caff79fd86f
32.461538
115
0.680447
3.857759
false
false
false
false
AlmasB/GroupNet
src/main/kotlin/icurves/util/Diagrams2018.kt
1
28569
package icurves.util import javafx.application.Application import javafx.scene.Parent import javafx.scene.chart.CategoryAxis import javafx.scene.chart.NumberAxis import javafx.scene.paint.Color import java.nio.file.Files import java.nio.file.Paths import tornadofx.* import java.util.* /** * DL duplicate labels * DZ disc zones * CC concurrency * BP brushing points * NP triple points * NS non-simple * OZ omitted zones * EZ extra zones * * * @author Almas Baimagambetov ([email protected]) */ class Technique(val name: String) { val datasets = arrayListOf<Dataset>() } class DatasetMapping(val name: String, val snapName: String, val zones: String) class Dataset(val name: String, val failed: Boolean = false, val NS: Int = 0, val DL: Int = 0, val DZ: Int = 0, val CC: Int = 0, val BP: Int = 0, val NP: Int = 0, val OZ: Int = 0, val EZ: Int = 0, var numCircles: Int = 0, var zones: String = "") { var Q: Int var nonCircles: Int = 0 var techniqueName = "" set(value) { if (value == "iCircles") { numCircles = numSets + DL } else if (value == "Bubble_Sets") { nonCircles = numSets } else if (value == "iCurves" || value == "GEDL") { nonCircles = numSets - numCircles } field = value } val numZones: Int val numSets: Int init { Q = name.removePrefix("D").toInt() % 4 if (Q == 0) Q = 4 if (zones.isEmpty()) { zones = mappings[name]!!.zones } numZones = zones.split(" +".toRegex()).size numSets = zones.split(" +".toRegex()).reduce { acc, s -> acc + s }.toCharArray().distinct().size } fun badness(): Int { return DZ + DL + if (failed) numZones else OZ } fun allPropSum(): Int { return DZ + DL + CC + NP + if (failed) 0 else nonCircles } override fun toString(): String { var s = "" if (failed) { return "FAILED" } if (DL > 0) s += " DL: $DL " if (DZ > 0) s += " DZ: $DZ " if (CC > 0) s += " CC: $CC " if (BP > 0) s += " BP: $BP " if (NP > 0) s += " NP: $NP " if (OZ > 0) s += " OZ: $OZ " if (EZ > 0) s += " EZ: $EZ " return s } } private val techniques = arrayListOf<Technique>() private val mappings = hashMapOf<String, DatasetMapping>() fun main(args: Array<String>) { loadMapping() loadData() //printStats() //showGraph() //printCSV() //printGeneral() printTex() } private fun loadMapping() { val lines = Files.readAllLines(Paths.get("dataset_mapping.txt")) for (i in 0 until lines.size step 4) { val name = lines[i] mappings[name] = DatasetMapping(name, lines[i+1], lines[i+2]) } //mappings.forEach { println(it.name + " " + it.snapName + " " + it.zones) } } private fun loadData() { val iCurves = Technique("iCurves") with(iCurves) { datasets.add(Dataset("D1", zones = "a b c d", numCircles = 4)) datasets.add(Dataset("D2", zones = "a ac b c d", numCircles = 4)) datasets.add(Dataset("D3", zones = "a cd ac b c d", numCircles = 4)) datasets.add(Dataset("D4", zones = "a bc cd ac b acd ad c d", numCircles = 4)) datasets.add(Dataset("D5", zones = "ab de b ce cde e", numCircles = 5)) datasets.add(Dataset("D6", zones = "a cd de b ad c d e", numCircles = 5)) datasets.add(Dataset("D7", zones = "a cd abd ac bd b ad be c d e", EZ = 2, numCircles = 5)) datasets.add(Dataset("D8", zones = "a ab cd de b ce be c ae d abe cde e", numCircles = 5)) datasets.add(Dataset("D9", zones = "a ef b c d e f", numCircles = 6)) datasets.add(Dataset("D10", zones = "a de ac b c d af e f", numCircles = 6)) datasets.add(Dataset("D11", zones = "a b df cf c bf d bdf e f", EZ = 1, numCircles = 6)) datasets.add(Dataset("D12", zones = "de ef df ad cf bf cdf d def cde cef e f acdf cdef bcdf bcdef", EZ = 10, numCircles = 4)) datasets.add(Dataset("D13", zones = "ab b c bf d e f g", numCircles = 7)) datasets.add(Dataset("D14", zones = "a ac b eg c cf d bg e f g", numCircles = 7)) datasets.add(Dataset("D15", zones = "bc de ef fg b bde df aef be c cg d af e ag f g", EZ = 12, numCircles = 5)) datasets.add(Dataset("D16", zones = "bc fg bef df aef def bg adfg acdf a ef adf afg abc c ae cdf dfg af e f abg g adef abef", failed = true)) datasets.add(Dataset("D17", zones = "a bc b fh c d e g h", numCircles = 8)) datasets.add(Dataset("D18", zones = "a gh b eg c d dgh e bh f ah deg g h", EZ = 3, numCircles = 7)) datasets.add(Dataset("D19", zones = "a fg gh b eg be c dg bf cg d dh bg e ag f g h", EZ = 3, numCircles = 8)) datasets.add(Dataset("D20", zones = "abcfh a gh ac afh fh c eh cfh cg dh dgh af bfh cgh ch f egh g h acfh bcfh cegh abfh", EZ = 5, numCircles = 7)) // 36 EZ // non-circles 6 datasets.add(Dataset("D21", numCircles = 4)) datasets.add(Dataset("D22", numCircles = 4)) datasets.add(Dataset("D23", EZ = 1, numCircles = 4)) datasets.add(Dataset("D24", EZ = 2, numCircles = 4)) datasets.add(Dataset("D25", numCircles = 5)) datasets.add(Dataset("D26", numCircles = 5)) datasets.add(Dataset("D27", numCircles = 5)) datasets.add(Dataset("D28", EZ = 5, numCircles = 4)) datasets.add(Dataset("D29", numCircles = 6)) datasets.add(Dataset("D30", EZ = 5, numCircles = 5)) datasets.add(Dataset("D31", numCircles = 6)) datasets.add(Dataset("D32", EZ = 2, numCircles = 6)) datasets.add(Dataset("D33", numCircles = 7)) datasets.add(Dataset("D34", numCircles = 7)) datasets.add(Dataset("D35", EZ = 1, numCircles = 7)) datasets.add(Dataset("D36", failed = true)) datasets.add(Dataset("D37", numCircles = 8)) datasets.add(Dataset("D38", numCircles = 8)) datasets.add(Dataset("D39", EZ = 4, numCircles = 7)) datasets.add(Dataset("D40", EZ = 7, numCircles = 6)) // 27 EZ // non-circles 5 } val iCircles = Technique("iCircles") with(iCircles) { datasets.add(Dataset("D1", zones = "a b c d")) datasets.add(Dataset("D2", zones = "a ac b c d")) datasets.add(Dataset("D3", zones = "a cd ac b c d")) datasets.add(Dataset("D4", zones = "a bc cd ac b acd ad c d")) datasets.add(Dataset("D5", zones = "ab de b ce cde e")) datasets.add(Dataset("D6", zones = "a cd de b ad c d e")) datasets.add(Dataset("D7", zones = "a cd abd ac bd b ad be c d e", DL = 2)) datasets.add(Dataset("D8", zones = "a ab cd de b ce be c ae d abe cde e")) datasets.add(Dataset("D9", zones = "a ef b c d e f")) datasets.add(Dataset("D10", zones = "a de ac b c d af e f")) datasets.add(Dataset("D11", zones = "a b df cf c bf d bdf e f", DL = 1)) datasets.add(Dataset("D12", zones = "de ef df ad cf bf cdf d def cde cef e f acdf cdef bcdf bcdef", DL = 3)) datasets.add(Dataset("D13", zones = "ab b c bf d e f g")) datasets.add(Dataset("D14", zones = "a ac b eg c cf d bg e f g")) datasets.add(Dataset("D15", zones = "bc de ef fg b bde df aef be c cg d af e ag f g", DL = 5)) datasets.add(Dataset("D16", zones = "bc fg bef df aef def bg adfg acdf a ef adf afg abc c ae cdf dfg af e f abg g adef abef", DL = 4, EZ = 3)) datasets.add(Dataset("D17", zones = "a bc b fh c d e g h")) datasets.add(Dataset("D18", zones = "a gh b eg c d dgh e bh f ah deg g h", DL = 2)) datasets.add(Dataset("D19", zones = "a fg gh b eg be c dg bf cg d dh bg e ag f g h", DL = 3)) datasets.add(Dataset("D20", zones = "abcfh a gh ac afh fh c eh cfh cg dh dgh af bfh cgh ch f egh g h acfh bcfh cegh abfh", DL = 5)) datasets.add(Dataset("D21")) datasets.add(Dataset("D22")) datasets.add(Dataset("D23", DL = 1)) datasets.add(Dataset("D24", DL = 1)) datasets.add(Dataset("D25")) datasets.add(Dataset("D26")) datasets.add(Dataset("D27")) datasets.add(Dataset("D28", DL = 3)) datasets.add(Dataset("D29")) datasets.add(Dataset("D30", DL = 2)) datasets.add(Dataset("D31")) datasets.add(Dataset("D32", DL = 2)) datasets.add(Dataset("D33")) datasets.add(Dataset("D34")) datasets.add(Dataset("D35", DL = 1)) datasets.add(Dataset("D36", DL = 5)) datasets.add(Dataset("D37")) datasets.add(Dataset("D38")) datasets.add(Dataset("D39", DL = 2)) datasets.add(Dataset("D40", DL = 3, EZ = 2)) } val GED = Technique("GEDL") with(GED) { datasets.add(Dataset("D1", zones = "a b c d", numCircles = 4)) datasets.add(Dataset("D2", zones = "a ac b c d", numCircles = 4)) datasets.add(Dataset("D3", zones = "a cd ac b c d", numCircles = 4)) datasets.add(Dataset("D4", zones = "a bc cd ac b acd ad c d", numCircles = 4)) datasets.add(Dataset("D5", zones = "ab de b ce cde e", numCircles = 5)) datasets.add(Dataset("D6", zones = "a cd de b ad c d e", numCircles = 5)) datasets.add(Dataset("D7", zones = "a cd abd ac bd b ad be c d e", CC = 1, NP = 2)) datasets.add(Dataset("D8", zones = "a ab cd de b ce be c ae d abe cde e", numCircles = 5)) datasets.add(Dataset("D9", zones = "a ef b c d e f", numCircles = 6)) datasets.add(Dataset("D10", zones = "a de ac b c d af e f", numCircles = 6)) datasets.add(Dataset("D11", zones = "a b df cf c bf d bdf e f", failed = true)) datasets.add(Dataset("D12", zones = "de ef df ad cf bf cdf d def cde cef e f acdf cdef bcdf bcdef", failed = true)) datasets.add(Dataset("D13", zones = "ab b c bf d e f g", numCircles = 7)) datasets.add(Dataset("D14", zones = "a ac b eg c cf d bg e f g", numCircles = 7)) datasets.add(Dataset("D15", zones = "bc de ef fg b bde df aef be c cg d af e ag f g", failed = true)) datasets.add(Dataset("D16", zones = "bc fg bef df aef def bg adfg acdf a ef adf afg abc c ae cdf dfg af e f abg g adef abef", failed = true)) datasets.add(Dataset("D17", zones = "a bc b fh c d e g h", numCircles = 8)) datasets.add(Dataset("D18", zones = "a gh b eg c d dgh e bh f ah deg g h", failed = true)) datasets.add(Dataset("D19", zones = "a fg gh b eg be c dg bf cg d dh bg e ag f g h", CC = 2, NP = 6)) datasets.add(Dataset("D20", zones = "abcfh a gh ac afh fh c eh cfh cg dh dgh af bfh cgh ch f egh g h acfh bcfh cegh abfh", CC = 7, NP = 1)) // non-circles 21 datasets.add(Dataset("D21", numCircles = 4)) datasets.add(Dataset("D22", numCircles = 4)) datasets.add(Dataset("D23", DZ = 1, numCircles = 4)) datasets.add(Dataset("D24", NP = 2, CC = 1)) datasets.add(Dataset("D25", numCircles = 5)) datasets.add(Dataset("D26", numCircles = 5)) datasets.add(Dataset("D27", numCircles = 5)) datasets.add(Dataset("D28", failed = true)) datasets.add(Dataset("D29", numCircles = 6)) datasets.add(Dataset("D30", failed = true)) datasets.add(Dataset("D31", failed = true)) datasets.add(Dataset("D32", NP = 2)) datasets.add(Dataset("D33", numCircles = 7)) datasets.add(Dataset("D34", numCircles = 7)) datasets.add(Dataset("D35", NP = 3)) datasets.add(Dataset("D36", failed = true)) datasets.add(Dataset("D37", numCircles = 8)) datasets.add(Dataset("D38", failed = true)) datasets.add(Dataset("D39", CC = 1, DZ = 1, NP = 4)) datasets.add(Dataset("D40", failed = true)) // non-circles 25 } val bubbleSets = Technique("Bubble_Sets") with(bubbleSets) { datasets.add(Dataset("D1", zones = "a b c d")) datasets.add(Dataset("D2", zones = "a ac b c d")) datasets.add(Dataset("D3", zones = "a cd ac b c d")) datasets.add(Dataset("D4", zones = "a bc cd ac b acd ad c d", DZ = 3)) datasets.add(Dataset("D5", zones = "ab de b ce cde e", EZ = 3, CC = 1)) datasets.add(Dataset("D6", zones = "a cd de b ad c d e")) datasets.add(Dataset("D7", zones = "a cd abd ac bd b ad be c d e", DZ = 2, NP = 1, CC = 1)) datasets.add(Dataset("D8", zones = "a ab cd de b ce be c ae d abe cde e", DZ = 5, NP = 1, CC = 1)) datasets.add(Dataset("D9", zones = "a ef b c d e f")) datasets.add(Dataset("D10", zones = "a de ac b c d af e f")) datasets.add(Dataset("D11", zones = "a b df cf c bf d bdf e f", EZ = 1, DZ = 1)) datasets.add(Dataset("D12", zones = "de ef df ad cf bf cdf d def cde cef e f acdf cdef bcdf bcdef", NP = 3, CC = 7, EZ = 4, DZ = 11)) datasets.add(Dataset("D13", zones = "ab b c bf d e f g", EZ = 1, NP = 1)) datasets.add(Dataset("D14", zones = "a ac b eg c cf d bg e f g")) datasets.add(Dataset("D15", zones = "bc de ef fg b bde df aef be c cg d af e ag f g", NP = 2, EZ = 1, CC = 2, DZ = 12)) datasets.add(Dataset("D16", zones = "bc fg bef df aef def bg adfg acdf a ef adf afg abc c ae cdf dfg af e f abg g adef abef", NP = 7, EZ = 7, CC = 9, DZ = 22)) datasets.add(Dataset("D17", zones = "a bc b fh c d e g h", EZ = 1)) datasets.add(Dataset("D18", zones = "a gh b eg c d dgh e bh f ah deg g h", BP = 1, EZ = 5)) datasets.add(Dataset("D19", zones = "a fg gh b eg be c dg bf cg d dh bg e ag f g h", DZ = 3)) datasets.add(Dataset("D20", zones = "abcfh a gh ac afh fh c eh cfh cg dh dgh af bfh cgh ch f egh g h acfh bcfh cegh abfh", NP = 3, CC = 9, EZ = 9, DZ = 15)) datasets.add(Dataset("D21", EZ = 1)) datasets.add(Dataset("D22", EZ = 4)) datasets.add(Dataset("D23", EZ = 1, DZ = 1, NP = 1)) datasets.add(Dataset("D24", BP = 1, NP = 1, DZ = 5)) datasets.add(Dataset("D25", EZ = 1)) datasets.add(Dataset("D26", DZ = 1)) datasets.add(Dataset("D27")) datasets.add(Dataset("D28", DZ = 6, NP = 3, BP = 1)) datasets.add(Dataset("D29", EZ = 1)) datasets.add(Dataset("D30", CC = 3, DZ = 1, EZ = 12)) datasets.add(Dataset("D31")) datasets.add(Dataset("D32", EZ = 2, DZ = 3)) datasets.add(Dataset("D33")) datasets.add(Dataset("D34", NP = 1, DZ = 3)) datasets.add(Dataset("D35", DZ = 1)) datasets.add(Dataset("D36", CC = 3, NP = 2, EZ = 1, DZ = 29)) datasets.add(Dataset("D37")) datasets.add(Dataset("D38", CC = 11, NP = 3, DZ = 1, EZ = 21)) datasets.add(Dataset("D39", NP = 5, CC = 1, EZ = 5, DZ = 10)) datasets.add(Dataset("D40", CC = 3, BP = 1, NP = 2, EZ = 6, DZ = 11)) } techniques.add(iCurves) techniques.add(iCircles) techniques.add(GED) techniques.add(bubbleSets) } private fun printCSV() { println("Data set number,SNAP reference,Technique,Non-simple,Disconnected Zones,Concurrency,Brushing Points,Triple Points,Duplicate Labels,Extra Zones,Omitted Zones,Number of Circles,Failed,Number of sets,Number of zones,Quartile") techniques.onEach { t -> t.datasets.forEach { it.techniqueName = t.name } } .flatMap { it.datasets } .groupBy { it.name } .toSortedMap(Comparator.comparingInt({ it.removePrefix("D").toInt() })) .forEach { datasetName, datasets -> val snap = mappings[datasetName]!!.snapName.substringAfterLast('\\') datasets.forEach { print("$datasetName,$snap,${it.techniqueName},${it.NS},${it.DZ},${it.CC},${it.BP},${it.NP},${it.DL},${it.EZ},${it.OZ},${it.numCircles},") print(if (it.failed) "Y," else "N,") print("${it.numSets},${it.numZones},${it.Q}") println() } } } private fun printGeneral() { techniques.onEach { t -> t.datasets.forEach { it.techniqueName = t.name } } .flatMap { it.datasets } .groupBy { it.name } .toSortedMap(Comparator.comparingInt({ it.removePrefix("D").toInt() })) .forEach { datasetName, datasets -> println("$datasetName") datasets.forEach { println("${it.techniqueName}: $it") } println() } } class GraphApp : App(GraphView::class) var index = 0 //iCurves, drawn: 8.0 numSets: 4 badness: 0.0 //iCurves, drawn: 8.0 numSets: 5 badness: 0.125 //iCurves, drawn: 8.0 numSets: 6 badness: 0.375 //iCurves, drawn: 6.0 numSets: 7 badness: 0.3333333333333333 //iCurves, drawn: 8.0 numSets: 8 badness: 0.625 //iCircles, drawn: 8.0 numSets: 4 badness: 0.25 //iCircles, drawn: 8.0 numSets: 5 badness: 0.625 //iCircles, drawn: 8.0 numSets: 6 badness: 1.0 //iCircles, drawn: 8.0 numSets: 7 badness: 1.875 //iCircles, drawn: 8.0 numSets: 8 badness: 1.875 //GEDL, drawn: 8.0 numSets: 4 badness: 1.0 //GEDL, drawn: 7.0 numSets: 5 badness: 1.1428571428571428 //GEDL, drawn: 4.0 numSets: 6 badness: 2.0 //GEDL, drawn: 5.0 numSets: 7 badness: 2.0 //GEDL, drawn: 5.0 numSets: 8 badness: 9.2 //Bubble_Sets, drawn: 8.0 numSets: 4 badness: 5.375 //Bubble_Sets, drawn: 8.0 numSets: 5 badness: 7.75 //Bubble_Sets, drawn: 8.0 numSets: 6 badness: 9.625 //Bubble_Sets, drawn: 8.0 numSets: 7 badness: 18.75 //Bubble_Sets, drawn: 8.0 numSets: 8 badness: 17.625 //iCurves, drawn: 10.0 Q: 1 badness: 0.0 //iCurves, drawn: 10.0 Q: 2 badness: 0.2 //iCurves, drawn: 10.0 Q: 3 badness: 0.3 //iCurves, drawn: 8.0 Q: 4 badness: 0.75 //iCircles, drawn: 10.0 Q: 1 badness: 0.0 //iCircles, drawn: 10.0 Q: 2 badness: 0.4 //iCircles, drawn: 10.0 Q: 3 badness: 1.5 //iCircles, drawn: 10.0 Q: 4 badness: 2.6 //GEDL, drawn: 10.0 Q: 1 badness: 0.0 //GEDL, drawn: 7.0 Q: 2 badness: 0.0 //GEDL, drawn: 7.0 Q: 3 badness: 7.0 //GEDL, drawn: 5.0 Q: 4 badness: 6.2 //Bubble_Sets, drawn: 10.0 Q: 1 badness: 6.2 //Bubble_Sets, drawn: 10.0 Q: 2 badness: 8.4 //Bubble_Sets, drawn: 10.0 Q: 3 badness: 10.3 //Bubble_Sets, drawn: 10.0 Q: 4 badness: 22.4 class GraphView : View() { override val root: Parent = stackpane { val chart = linechart("Diagrams 2018 data", CategoryAxis(), NumberAxis()) { techniques.onEach { t -> t.datasets.forEach { it.techniqueName = t.name } } .flatMap { it.datasets } .groupBy { it.techniqueName } .forEach { techniqueName, datasets -> series(techniqueName + " ALL") { datasets.groupBy { it.Q } .forEach { numSets, datasetsPerNumSets -> val drawnNumber = datasetsPerNumSets.filter { !it.failed }.size.toDouble() val badness = datasetsPerNumSets.sumBy { it.EZ } / drawnNumber println("$techniqueName, drawn: $drawnNumber numSets: $numSets badness: $badness") data(numSets.toString(), badness) } } // series(techniqueName) { // datasets.groupBy { it.numSets } // .forEach { numSets, datasetsPerNumSets -> // // val drawnNumber = datasetsPerNumSets.size.toDouble() // // val badness = datasetsPerNumSets.sumBy { it.badness() } / drawnNumber // // println("$techniqueName, sets: $numSets badness: $badness") // // data(numSets.toString(), badness) // } // // } // series(techniqueName) { // datasets.groupBy { it.Q } // .forEach { quartile, datasetsPerNumSets -> // // val drawnNumber = datasetsPerNumSets.size.toDouble() // // println(drawnNumber) // // val badness = datasetsPerNumSets.sumBy { it.badness() } / drawnNumber // // println("$techniqueName, Q: $quartile badness: $badness") // // data(quartile.toString(), badness) // } // // } // series(techniqueName) { // datasets.groupBy { it.numSets } // .forEach { numSets, datasetsPerNumSets -> // // val drawnNumber = datasetsPerNumSets.filter { !it.failed }.size.toDouble() // // data(numSets.toString(), datasetsPerNumSets.sumBy { it.nonCircles } / drawnNumber) // } // // } // if (techniqueName == "iCircles") { // val s1 = series(techniqueName + " DL") { // datasets.groupBy { it.numSets } // .forEach { numSets, datasetsPerNumSets -> // data(numSets.toString(), datasetsPerNumSets.sumBy { it.DL }) // } // } // } // if (techniqueName != "GEDL") { // val s1 = series(techniqueName + " EZ") { // datasets.groupBy { it.numSets } // .forEach { numSets, datasetsPerNumSets -> // data(numSets.toString(), datasetsPerNumSets.sumBy { it.EZ }) // } // } // // } else { // val s1 = series(techniqueName + " TP") { // datasets.groupBy { it.numSets } // .forEach { numSets, datasetsPerNumSets -> // data(numSets.toString(), datasetsPerNumSets.sumBy { it.NP }) // } // } // } } // series("Product X") { // data("MAR", 10245) // data("APR", 23963) // data("MAY", 15038) // } // series("Product Y") { // data("MAR", 28443) // data("APR", 22845) // data("MAY", 19045) // } } } } val colors = arrayListOf<Color>() private fun rgb(): String { val color = colors[index++] return String.format("%d, %d, %d", (color.getRed() * 255).toInt(), (color.getGreen() * 255).toInt(), (color.getBlue() * 255).toInt()) } private fun showGraph() { // these values are adapted from "How should we use colour in ED" Andrew Blake, et al for (i in 0..29) { colors.add(Color.hsb(((i + 1) * 32).toDouble(), if (i == 1 || i == 2) 0.26 else 0.55, if (i == 1 || i == 2) 0.88 else 0.92)) } Collections.swap(colors, 1, 9) Collections.swap(colors, 3, 7) Application.launch(GraphApp::class.java) } private fun printTex() { val tex = arrayListOf<String>() techniques.onEach { t -> t.datasets.forEach { it.techniqueName = t.name } } .flatMap { it.datasets } .groupBy { it.name } .toSortedMap(Comparator.comparingInt({ it.removePrefix("D").toInt() })) .forEach { datasetName, datasets -> val data = datasets[0] val snap = mappings[data.name]!!.snapName.substringAfterLast('\\') tex.add("\\newpage") tex.add("\\textbf{SNAP ID: ${snap}}") tex.add("") tex.add("\\textbf{Number of Sets: ${data.numSets}}") tex.add("") tex.add("\\textbf{Number of Zones: ${data.numZones}}") tex.add("") tex.add("\\textbf{Quartile: ${data.Q}}") tex.add("") tex.add("\\begin{center}\n" + "\\begin{minipage}[t]{0.49\\linewidth}\n" + "\\captionof*{figure}{\\textbf{iCurves}}\n" + "\\includegraphics[width=0.8\\textwidth,height=0.36\\textheight,keepaspectratio=true]{iCurves/${data.name}}\n" + "\\end{minipage}\n" + "\\hfill\n" + "\\begin{minipage}[t]{0.49\\linewidth}\n" + "\\captionof*{figure}{\\textbf{iCircles}}\n" + "\\includegraphics[width=0.8\\textwidth,height=0.36\\textheight,keepaspectratio=true]{iCircles/${data.name}}\n" + "\\end{minipage}\n" + "\\end{center}\n" + "\\vspace{0.5cm}\n" + "\\begin{center}\n" + "\\begin{minipage}[t]{0.49\\linewidth}\n" + "\\captionof*{figure}{\\textbf{GED-L}}\n" + "\\includegraphics[width=0.8\\textwidth,height=0.36\\textheight,keepaspectratio=true]{GEDL/${data.name}}\n" + "\\end{minipage}\n" + "\\hfill\n" + "\\begin{minipage}[t]{0.49\\linewidth}\n" + "\\captionof*{figure}{\\textbf{Bubble Sets}}\n" + "\\includegraphics[width=0.8\\textwidth,height=0.36\\textheight,keepaspectratio=true]{Bubble_Sets/${data.name}}\n" + "\\end{minipage}\n" + "\\end{center}") tex.add("") val iCurves = datasets.find { it.techniqueName == "iCurves" }!! val iCircles = datasets.find { it.techniqueName == "iCircles" }!! val GEDL = datasets.find { it.techniqueName == "GEDL" }!! val BS = datasets.find { it.techniqueName == "Bubble_Sets" }!! val iNonCircles = if (iCurves.failed) 0 else iCurves.nonCircles val gedlNonCircles = if (GEDL.failed) 0 else GEDL.nonCircles tex.add("\\begin{center}\n" + "\\begin{tabular}{ | l | l | l | l | l | }\n" + "\\hline\n" + " & iCurves & iCircles & GED-L & Bubble Sets \\\\ \\hline\n" + "Duplicated Labels & 0 & ${iCircles.DL} & 0 & 0 \\tabularnewline \\hline\n" + "Disconnected Zones & 0 & 0 & ${GEDL.DZ} & ${BS.DZ} \\tabularnewline \\hline \\hline\n" + "Extra Zones & ${iCurves.EZ} & ${iCircles.EZ} & ${GEDL.EZ} & ${BS.EZ} \\tabularnewline \\hline \\hline\n" + "Concurrency & 0 & 0 & ${GEDL.CC} & ${BS.CC} \\tabularnewline \\hline\n" + "Triple Points & 0 & 0 & ${GEDL.NP} & ${BS.NP} \\tabularnewline \\hline\n" + "Non-circles & ${iNonCircles} & 0 & ${gedlNonCircles} & ${BS.nonCircles} \\tabularnewline \\hline \n" + "\\end{tabular}\n" + "\\end{center}") tex.add("") } Files.write(Paths.get("tex.txt"), tex) } private fun printStats() { techniques.onEach { t -> t.datasets.forEach { it.techniqueName = t.name } } .flatMap { it.datasets } .groupBy { it.techniqueName } .forEach { techniqueName, datasets -> val total = datasets.filter { !it.failed }.sumBy { it.EZ } val avg = total.toDouble() / datasets.filter { !it.failed }.size println("$techniqueName total: $total") println("average: $avg") println("occured in " + datasets.filter { it.EZ > 0 && !it.failed }.size) } }
apache-2.0
7e39ffdef143e8b27cebaa6a9f6fb3da
40.830161
235
0.513669
3.375753
false
false
false
false
vanniktech/Emoji
emoji-ios/src/commonMain/kotlin/com/vanniktech/emoji/ios/category/SmileysAndPeopleCategoryChunk3.kt
1
77377
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.vanniktech.emoji.ios.category import com.vanniktech.emoji.ios.IosEmoji internal object SmileysAndPeopleCategoryChunk3 { internal val EMOJIS: List<IosEmoji> = listOf( IosEmoji( String(intArrayOf(0x1F468, 0x200D, 0x1F37C), 0, 3), listOf("man_feeding_baby"), 13, 58, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F37C), 0, 4), emptyList<String>(), 13, 59, false), IosEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F37C), 0, 4), emptyList<String>(), 13, 60, false), IosEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F37C), 0, 4), emptyList<String>(), 14, 0, false), IosEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F37C), 0, 4), emptyList<String>(), 14, 1, false), IosEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F37C), 0, 4), emptyList<String>(), 14, 2, false), ), ), IosEmoji( String(intArrayOf(0x1F9D1, 0x200D, 0x1F37C), 0, 3), listOf("person_feeding_baby"), 47, 24, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB, 0x200D, 0x1F37C), 0, 4), emptyList<String>(), 47, 25, false), IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F37C), 0, 4), emptyList<String>(), 47, 26, false), IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F37C), 0, 4), emptyList<String>(), 47, 27, false), IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F37C), 0, 4), emptyList<String>(), 47, 28, false), IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F37C), 0, 4), emptyList<String>(), 47, 29, false), ), ), IosEmoji( String(intArrayOf(0x1F47C), 0, 1), listOf("angel"), 25, 0, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F47C, 0x1F3FB), 0, 2), emptyList<String>(), 25, 1, false), IosEmoji(String(intArrayOf(0x1F47C, 0x1F3FC), 0, 2), emptyList<String>(), 25, 2, false), IosEmoji(String(intArrayOf(0x1F47C, 0x1F3FD), 0, 2), emptyList<String>(), 25, 3, false), IosEmoji(String(intArrayOf(0x1F47C, 0x1F3FE), 0, 2), emptyList<String>(), 25, 4, false), IosEmoji(String(intArrayOf(0x1F47C, 0x1F3FF), 0, 2), emptyList<String>(), 25, 5, false), ), ), IosEmoji( String(intArrayOf(0x1F385), 0, 1), listOf("santa"), 7, 8, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F385, 0x1F3FB), 0, 2), emptyList<String>(), 7, 9, false), IosEmoji(String(intArrayOf(0x1F385, 0x1F3FC), 0, 2), emptyList<String>(), 7, 10, false), IosEmoji(String(intArrayOf(0x1F385, 0x1F3FD), 0, 2), emptyList<String>(), 7, 11, false), IosEmoji(String(intArrayOf(0x1F385, 0x1F3FE), 0, 2), emptyList<String>(), 7, 12, false), IosEmoji(String(intArrayOf(0x1F385, 0x1F3FF), 0, 2), emptyList<String>(), 7, 13, false), ), ), IosEmoji( String(intArrayOf(0x1F936), 0, 1), listOf("mrs_claus", "mother_christmas"), 41, 32, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F936, 0x1F3FB), 0, 2), emptyList<String>(), 41, 33, false), IosEmoji(String(intArrayOf(0x1F936, 0x1F3FC), 0, 2), emptyList<String>(), 41, 34, false), IosEmoji(String(intArrayOf(0x1F936, 0x1F3FD), 0, 2), emptyList<String>(), 41, 35, false), IosEmoji(String(intArrayOf(0x1F936, 0x1F3FE), 0, 2), emptyList<String>(), 41, 36, false), IosEmoji(String(intArrayOf(0x1F936, 0x1F3FF), 0, 2), emptyList<String>(), 41, 37, false), ), ), IosEmoji( String(intArrayOf(0x1F9D1, 0x200D, 0x1F384), 0, 3), listOf("mx_claus"), 47, 30, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB, 0x200D, 0x1F384), 0, 4), emptyList<String>(), 47, 31, false), IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F384), 0, 4), emptyList<String>(), 47, 32, false), IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F384), 0, 4), emptyList<String>(), 47, 33, false), IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F384), 0, 4), emptyList<String>(), 47, 34, false), IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F384), 0, 4), emptyList<String>(), 47, 35, false), ), ), IosEmoji( String(intArrayOf(0x1F9B8), 0, 1), listOf("superhero"), 45, 31, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9B8, 0x1F3FB), 0, 2), emptyList<String>(), 45, 32, false), IosEmoji(String(intArrayOf(0x1F9B8, 0x1F3FC), 0, 2), emptyList<String>(), 45, 33, false), IosEmoji(String(intArrayOf(0x1F9B8, 0x1F3FD), 0, 2), emptyList<String>(), 45, 34, false), IosEmoji(String(intArrayOf(0x1F9B8, 0x1F3FE), 0, 2), emptyList<String>(), 45, 35, false), IosEmoji(String(intArrayOf(0x1F9B8, 0x1F3FF), 0, 2), emptyList<String>(), 45, 36, false), ), ), IosEmoji( String(intArrayOf(0x1F9B8, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("male_superhero"), 45, 25, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9B8, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 45, 26, false), IosEmoji(String(intArrayOf(0x1F9B8, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 45, 27, false), IosEmoji(String(intArrayOf(0x1F9B8, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 45, 28, false), IosEmoji(String(intArrayOf(0x1F9B8, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 45, 29, false), IosEmoji(String(intArrayOf(0x1F9B8, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 45, 30, false), ), ), IosEmoji( String(intArrayOf(0x1F9B8, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("female_superhero"), 45, 19, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9B8, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 45, 20, false), IosEmoji(String(intArrayOf(0x1F9B8, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 45, 21, false), IosEmoji(String(intArrayOf(0x1F9B8, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 45, 22, false), IosEmoji(String(intArrayOf(0x1F9B8, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 45, 23, false), IosEmoji(String(intArrayOf(0x1F9B8, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 45, 24, false), ), ), IosEmoji( String(intArrayOf(0x1F9B9), 0, 1), listOf("supervillain"), 45, 49, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9B9, 0x1F3FB), 0, 2), emptyList<String>(), 45, 50, false), IosEmoji(String(intArrayOf(0x1F9B9, 0x1F3FC), 0, 2), emptyList<String>(), 45, 51, false), IosEmoji(String(intArrayOf(0x1F9B9, 0x1F3FD), 0, 2), emptyList<String>(), 45, 52, false), IosEmoji(String(intArrayOf(0x1F9B9, 0x1F3FE), 0, 2), emptyList<String>(), 45, 53, false), IosEmoji(String(intArrayOf(0x1F9B9, 0x1F3FF), 0, 2), emptyList<String>(), 45, 54, false), ), ), IosEmoji( String(intArrayOf(0x1F9B9, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("male_supervillain"), 45, 43, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9B9, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 45, 44, false), IosEmoji(String(intArrayOf(0x1F9B9, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 45, 45, false), IosEmoji(String(intArrayOf(0x1F9B9, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 45, 46, false), IosEmoji(String(intArrayOf(0x1F9B9, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 45, 47, false), IosEmoji(String(intArrayOf(0x1F9B9, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 45, 48, false), ), ), IosEmoji( String(intArrayOf(0x1F9B9, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("female_supervillain"), 45, 37, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9B9, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 45, 38, false), IosEmoji(String(intArrayOf(0x1F9B9, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 45, 39, false), IosEmoji(String(intArrayOf(0x1F9B9, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 45, 40, false), IosEmoji(String(intArrayOf(0x1F9B9, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 45, 41, false), IosEmoji(String(intArrayOf(0x1F9B9, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 45, 42, false), ), ), IosEmoji( String(intArrayOf(0x1F9D9), 0, 1), listOf("mage"), 51, 52, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F9D9, 0x1F3FB), 0, 2), emptyList<String>(), 51, 53, true), IosEmoji(String(intArrayOf(0x1F9D9, 0x1F3FC), 0, 2), emptyList<String>(), 51, 54, true), IosEmoji(String(intArrayOf(0x1F9D9, 0x1F3FD), 0, 2), emptyList<String>(), 51, 55, true), IosEmoji(String(intArrayOf(0x1F9D9, 0x1F3FE), 0, 2), emptyList<String>(), 51, 56, true), IosEmoji(String(intArrayOf(0x1F9D9, 0x1F3FF), 0, 2), emptyList<String>(), 51, 57, true), ), ), IosEmoji( String(intArrayOf(0x1F9D9, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("male_mage"), 51, 46, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9D9, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 47, false), IosEmoji(String(intArrayOf(0x1F9D9, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 48, false), IosEmoji(String(intArrayOf(0x1F9D9, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 49, false), IosEmoji(String(intArrayOf(0x1F9D9, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 50, false), IosEmoji(String(intArrayOf(0x1F9D9, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 51, false), ), ), IosEmoji( String(intArrayOf(0x1F9D9, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("female_mage"), 51, 40, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9D9, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 41, false), IosEmoji(String(intArrayOf(0x1F9D9, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 42, false), IosEmoji(String(intArrayOf(0x1F9D9, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 43, false), IosEmoji(String(intArrayOf(0x1F9D9, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 44, false), IosEmoji(String(intArrayOf(0x1F9D9, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 45, false), ), ), IosEmoji( String(intArrayOf(0x1F9DA), 0, 1), listOf("fairy"), 52, 9, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F9DA, 0x1F3FB), 0, 2), emptyList<String>(), 52, 10, true), IosEmoji(String(intArrayOf(0x1F9DA, 0x1F3FC), 0, 2), emptyList<String>(), 52, 11, true), IosEmoji(String(intArrayOf(0x1F9DA, 0x1F3FD), 0, 2), emptyList<String>(), 52, 12, true), IosEmoji(String(intArrayOf(0x1F9DA, 0x1F3FE), 0, 2), emptyList<String>(), 52, 13, true), IosEmoji(String(intArrayOf(0x1F9DA, 0x1F3FF), 0, 2), emptyList<String>(), 52, 14, true), ), ), IosEmoji( String(intArrayOf(0x1F9DA, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("male_fairy"), 52, 3, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9DA, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 52, 4, false), IosEmoji(String(intArrayOf(0x1F9DA, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 52, 5, false), IosEmoji(String(intArrayOf(0x1F9DA, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 52, 6, false), IosEmoji(String(intArrayOf(0x1F9DA, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 52, 7, false), IosEmoji(String(intArrayOf(0x1F9DA, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 52, 8, false), ), ), IosEmoji( String(intArrayOf(0x1F9DA, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("female_fairy"), 51, 58, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9DA, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 59, false), IosEmoji(String(intArrayOf(0x1F9DA, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 60, false), IosEmoji(String(intArrayOf(0x1F9DA, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 52, 0, false), IosEmoji(String(intArrayOf(0x1F9DA, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 52, 1, false), IosEmoji(String(intArrayOf(0x1F9DA, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 52, 2, false), ), ), IosEmoji( String(intArrayOf(0x1F9DB), 0, 1), listOf("vampire"), 52, 27, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F9DB, 0x1F3FB), 0, 2), emptyList<String>(), 52, 28, true), IosEmoji(String(intArrayOf(0x1F9DB, 0x1F3FC), 0, 2), emptyList<String>(), 52, 29, true), IosEmoji(String(intArrayOf(0x1F9DB, 0x1F3FD), 0, 2), emptyList<String>(), 52, 30, true), IosEmoji(String(intArrayOf(0x1F9DB, 0x1F3FE), 0, 2), emptyList<String>(), 52, 31, true), IosEmoji(String(intArrayOf(0x1F9DB, 0x1F3FF), 0, 2), emptyList<String>(), 52, 32, true), ), ), IosEmoji( String(intArrayOf(0x1F9DB, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("male_vampire"), 52, 21, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9DB, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 52, 22, false), IosEmoji(String(intArrayOf(0x1F9DB, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 52, 23, false), IosEmoji(String(intArrayOf(0x1F9DB, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 52, 24, false), IosEmoji(String(intArrayOf(0x1F9DB, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 52, 25, false), IosEmoji(String(intArrayOf(0x1F9DB, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 52, 26, false), ), ), IosEmoji( String(intArrayOf(0x1F9DB, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("female_vampire"), 52, 15, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9DB, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 52, 16, false), IosEmoji(String(intArrayOf(0x1F9DB, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 52, 17, false), IosEmoji(String(intArrayOf(0x1F9DB, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 52, 18, false), IosEmoji(String(intArrayOf(0x1F9DB, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 52, 19, false), IosEmoji(String(intArrayOf(0x1F9DB, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 52, 20, false), ), ), IosEmoji( String(intArrayOf(0x1F9DC), 0, 1), listOf("merperson"), 52, 45, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F9DC, 0x1F3FB), 0, 2), emptyList<String>(), 52, 46, true), IosEmoji(String(intArrayOf(0x1F9DC, 0x1F3FC), 0, 2), emptyList<String>(), 52, 47, true), IosEmoji(String(intArrayOf(0x1F9DC, 0x1F3FD), 0, 2), emptyList<String>(), 52, 48, true), IosEmoji(String(intArrayOf(0x1F9DC, 0x1F3FE), 0, 2), emptyList<String>(), 52, 49, true), IosEmoji(String(intArrayOf(0x1F9DC, 0x1F3FF), 0, 2), emptyList<String>(), 52, 50, true), ), ), IosEmoji( String(intArrayOf(0x1F9DC, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("merman"), 52, 39, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9DC, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 52, 40, false), IosEmoji(String(intArrayOf(0x1F9DC, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 52, 41, false), IosEmoji(String(intArrayOf(0x1F9DC, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 52, 42, false), IosEmoji(String(intArrayOf(0x1F9DC, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 52, 43, false), IosEmoji(String(intArrayOf(0x1F9DC, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 52, 44, false), ), ), IosEmoji( String(intArrayOf(0x1F9DC, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("mermaid"), 52, 33, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9DC, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 52, 34, false), IosEmoji(String(intArrayOf(0x1F9DC, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 52, 35, false), IosEmoji(String(intArrayOf(0x1F9DC, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 52, 36, false), IosEmoji(String(intArrayOf(0x1F9DC, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 52, 37, false), IosEmoji(String(intArrayOf(0x1F9DC, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 52, 38, false), ), ), IosEmoji( String(intArrayOf(0x1F9DD), 0, 1), listOf("elf"), 53, 2, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F9DD, 0x1F3FB), 0, 2), emptyList<String>(), 53, 3, true), IosEmoji(String(intArrayOf(0x1F9DD, 0x1F3FC), 0, 2), emptyList<String>(), 53, 4, true), IosEmoji(String(intArrayOf(0x1F9DD, 0x1F3FD), 0, 2), emptyList<String>(), 53, 5, true), IosEmoji(String(intArrayOf(0x1F9DD, 0x1F3FE), 0, 2), emptyList<String>(), 53, 6, true), IosEmoji(String(intArrayOf(0x1F9DD, 0x1F3FF), 0, 2), emptyList<String>(), 53, 7, true), ), ), IosEmoji( String(intArrayOf(0x1F9DD, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("male_elf"), 52, 57, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9DD, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 52, 58, false), IosEmoji(String(intArrayOf(0x1F9DD, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 52, 59, false), IosEmoji(String(intArrayOf(0x1F9DD, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 52, 60, false), IosEmoji(String(intArrayOf(0x1F9DD, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 53, 0, false), IosEmoji(String(intArrayOf(0x1F9DD, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 53, 1, false), ), ), IosEmoji( String(intArrayOf(0x1F9DD, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("female_elf"), 52, 51, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9DD, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 52, 52, false), IosEmoji(String(intArrayOf(0x1F9DD, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 52, 53, false), IosEmoji(String(intArrayOf(0x1F9DD, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 52, 54, false), IosEmoji(String(intArrayOf(0x1F9DD, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 52, 55, false), IosEmoji(String(intArrayOf(0x1F9DD, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 52, 56, false), ), ), IosEmoji(String(intArrayOf(0x1F9DE), 0, 1), listOf("genie"), 53, 10, true), IosEmoji(String(intArrayOf(0x1F9DE, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("male_genie"), 53, 9, false), IosEmoji(String(intArrayOf(0x1F9DE, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("female_genie"), 53, 8, false), IosEmoji(String(intArrayOf(0x1F9DF), 0, 1), listOf("zombie"), 53, 13, true), IosEmoji(String(intArrayOf(0x1F9DF, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("male_zombie"), 53, 12, false), IosEmoji(String(intArrayOf(0x1F9DF, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("female_zombie"), 53, 11, false), IosEmoji(String(intArrayOf(0x1F9CC), 0, 1), listOf("troll"), 46, 17, false), IosEmoji( String(intArrayOf(0x1F486), 0, 1), listOf("massage"), 26, 10, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F486, 0x1F3FB), 0, 2), emptyList<String>(), 26, 11, false), IosEmoji(String(intArrayOf(0x1F486, 0x1F3FC), 0, 2), emptyList<String>(), 26, 12, false), IosEmoji(String(intArrayOf(0x1F486, 0x1F3FD), 0, 2), emptyList<String>(), 26, 13, false), IosEmoji(String(intArrayOf(0x1F486, 0x1F3FE), 0, 2), emptyList<String>(), 26, 14, false), IosEmoji(String(intArrayOf(0x1F486, 0x1F3FF), 0, 2), emptyList<String>(), 26, 15, false), ), ), IosEmoji( String(intArrayOf(0x1F486, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-getting-massage"), 26, 4, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F486, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 5, false), IosEmoji(String(intArrayOf(0x1F486, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 6, false), IosEmoji(String(intArrayOf(0x1F486, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 7, false), IosEmoji(String(intArrayOf(0x1F486, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 8, false), IosEmoji(String(intArrayOf(0x1F486, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 9, false), ), ), IosEmoji( String(intArrayOf(0x1F486, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-getting-massage"), 25, 59, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F486, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 25, 60, false), IosEmoji(String(intArrayOf(0x1F486, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 0, false), IosEmoji(String(intArrayOf(0x1F486, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 1, false), IosEmoji(String(intArrayOf(0x1F486, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 2, false), IosEmoji(String(intArrayOf(0x1F486, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 3, false), ), ), IosEmoji( String(intArrayOf(0x1F487), 0, 1), listOf("haircut"), 26, 28, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F487, 0x1F3FB), 0, 2), emptyList<String>(), 26, 29, false), IosEmoji(String(intArrayOf(0x1F487, 0x1F3FC), 0, 2), emptyList<String>(), 26, 30, false), IosEmoji(String(intArrayOf(0x1F487, 0x1F3FD), 0, 2), emptyList<String>(), 26, 31, false), IosEmoji(String(intArrayOf(0x1F487, 0x1F3FE), 0, 2), emptyList<String>(), 26, 32, false), IosEmoji(String(intArrayOf(0x1F487, 0x1F3FF), 0, 2), emptyList<String>(), 26, 33, false), ), ), IosEmoji( String(intArrayOf(0x1F487, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-getting-haircut"), 26, 22, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F487, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 23, false), IosEmoji(String(intArrayOf(0x1F487, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 24, false), IosEmoji(String(intArrayOf(0x1F487, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 25, false), IosEmoji(String(intArrayOf(0x1F487, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 26, false), IosEmoji(String(intArrayOf(0x1F487, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 27, false), ), ), IosEmoji( String(intArrayOf(0x1F487, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-getting-haircut"), 26, 16, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F487, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 17, false), IosEmoji(String(intArrayOf(0x1F487, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 18, false), IosEmoji(String(intArrayOf(0x1F487, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 19, false), IosEmoji(String(intArrayOf(0x1F487, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 20, false), IosEmoji(String(intArrayOf(0x1F487, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 21, false), ), ), IosEmoji( String(intArrayOf(0x1F6B6), 0, 1), listOf("walking"), 37, 27, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F6B6, 0x1F3FB), 0, 2), emptyList<String>(), 37, 28, false), IosEmoji(String(intArrayOf(0x1F6B6, 0x1F3FC), 0, 2), emptyList<String>(), 37, 29, false), IosEmoji(String(intArrayOf(0x1F6B6, 0x1F3FD), 0, 2), emptyList<String>(), 37, 30, false), IosEmoji(String(intArrayOf(0x1F6B6, 0x1F3FE), 0, 2), emptyList<String>(), 37, 31, false), IosEmoji(String(intArrayOf(0x1F6B6, 0x1F3FF), 0, 2), emptyList<String>(), 37, 32, false), ), ), IosEmoji( String(intArrayOf(0x1F6B6, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-walking"), 37, 21, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F6B6, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 22, false), IosEmoji(String(intArrayOf(0x1F6B6, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 23, false), IosEmoji(String(intArrayOf(0x1F6B6, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 24, false), IosEmoji(String(intArrayOf(0x1F6B6, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 25, false), IosEmoji(String(intArrayOf(0x1F6B6, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 26, false), ), ), IosEmoji( String(intArrayOf(0x1F6B6, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-walking"), 37, 15, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F6B6, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 16, false), IosEmoji(String(intArrayOf(0x1F6B6, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 17, false), IosEmoji(String(intArrayOf(0x1F6B6, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 18, false), IosEmoji(String(intArrayOf(0x1F6B6, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 19, false), IosEmoji(String(intArrayOf(0x1F6B6, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 20, false), ), ), IosEmoji( String(intArrayOf(0x1F9CD), 0, 1), listOf("standing_person"), 46, 30, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9CD, 0x1F3FB), 0, 2), emptyList<String>(), 46, 31, false), IosEmoji(String(intArrayOf(0x1F9CD, 0x1F3FC), 0, 2), emptyList<String>(), 46, 32, false), IosEmoji(String(intArrayOf(0x1F9CD, 0x1F3FD), 0, 2), emptyList<String>(), 46, 33, false), IosEmoji(String(intArrayOf(0x1F9CD, 0x1F3FE), 0, 2), emptyList<String>(), 46, 34, false), IosEmoji(String(intArrayOf(0x1F9CD, 0x1F3FF), 0, 2), emptyList<String>(), 46, 35, false), ), ), IosEmoji( String(intArrayOf(0x1F9CD, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_standing"), 46, 24, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9CD, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 25, false), IosEmoji(String(intArrayOf(0x1F9CD, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 26, false), IosEmoji(String(intArrayOf(0x1F9CD, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 27, false), IosEmoji(String(intArrayOf(0x1F9CD, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 28, false), IosEmoji(String(intArrayOf(0x1F9CD, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 29, false), ), ), IosEmoji( String(intArrayOf(0x1F9CD, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_standing"), 46, 18, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9CD, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 19, false), IosEmoji(String(intArrayOf(0x1F9CD, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 20, false), IosEmoji(String(intArrayOf(0x1F9CD, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 21, false), IosEmoji(String(intArrayOf(0x1F9CD, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 22, false), IosEmoji(String(intArrayOf(0x1F9CD, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 23, false), ), ), IosEmoji( String(intArrayOf(0x1F9CE), 0, 1), listOf("kneeling_person"), 46, 48, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9CE, 0x1F3FB), 0, 2), emptyList<String>(), 46, 49, false), IosEmoji(String(intArrayOf(0x1F9CE, 0x1F3FC), 0, 2), emptyList<String>(), 46, 50, false), IosEmoji(String(intArrayOf(0x1F9CE, 0x1F3FD), 0, 2), emptyList<String>(), 46, 51, false), IosEmoji(String(intArrayOf(0x1F9CE, 0x1F3FE), 0, 2), emptyList<String>(), 46, 52, false), IosEmoji(String(intArrayOf(0x1F9CE, 0x1F3FF), 0, 2), emptyList<String>(), 46, 53, false), ), ), IosEmoji( String(intArrayOf(0x1F9CE, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_kneeling"), 46, 42, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9CE, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 43, false), IosEmoji(String(intArrayOf(0x1F9CE, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 44, false), IosEmoji(String(intArrayOf(0x1F9CE, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 45, false), IosEmoji(String(intArrayOf(0x1F9CE, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 46, false), IosEmoji(String(intArrayOf(0x1F9CE, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 47, false), ), ), IosEmoji( String(intArrayOf(0x1F9CE, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_kneeling"), 46, 36, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9CE, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 37, false), IosEmoji(String(intArrayOf(0x1F9CE, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 38, false), IosEmoji(String(intArrayOf(0x1F9CE, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 39, false), IosEmoji(String(intArrayOf(0x1F9CE, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 40, false), IosEmoji(String(intArrayOf(0x1F9CE, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 41, false), ), ), IosEmoji( String(intArrayOf(0x1F9D1, 0x200D, 0x1F9AF), 0, 3), listOf("person_with_probing_cane"), 49, 6, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 49, 7, false), IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 49, 8, false), IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 49, 9, false), IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 49, 10, false), IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 49, 11, false), ), ), IosEmoji( String(intArrayOf(0x1F468, 0x200D, 0x1F9AF), 0, 3), listOf("man_with_probing_cane"), 15, 23, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 15, 24, false), IosEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 15, 25, false), IosEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 15, 26, false), IosEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 15, 27, false), IosEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 15, 28, false), ), ), IosEmoji( String(intArrayOf(0x1F469, 0x200D, 0x1F9AF), 0, 3), listOf("woman_with_probing_cane"), 18, 52, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 18, 53, false), IosEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 18, 54, false), IosEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 18, 55, false), IosEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 18, 56, false), IosEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 18, 57, false), ), ), IosEmoji( String(intArrayOf(0x1F9D1, 0x200D, 0x1F9BC), 0, 3), listOf("person_in_motorized_wheelchair"), 49, 36, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 49, 37, false), IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 49, 38, false), IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 49, 39, false), IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 49, 40, false), IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 49, 41, false), ), ), IosEmoji( String(intArrayOf(0x1F468, 0x200D, 0x1F9BC), 0, 3), listOf("man_in_motorized_wheelchair"), 15, 53, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 15, 54, false), IosEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 15, 55, false), IosEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 15, 56, false), IosEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 15, 57, false), IosEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 15, 58, false), ), ), IosEmoji( String(intArrayOf(0x1F469, 0x200D, 0x1F9BC), 0, 3), listOf("woman_in_motorized_wheelchair"), 19, 21, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 19, 22, false), IosEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 19, 23, false), IosEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 19, 24, false), IosEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 19, 25, false), IosEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 19, 26, false), ), ), IosEmoji( String(intArrayOf(0x1F9D1, 0x200D, 0x1F9BD), 0, 3), listOf("person_in_manual_wheelchair"), 49, 42, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 49, 43, false), IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 49, 44, false), IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 49, 45, false), IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 49, 46, false), IosEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 49, 47, false), ), ), IosEmoji( String(intArrayOf(0x1F468, 0x200D, 0x1F9BD), 0, 3), listOf("man_in_manual_wheelchair"), 15, 59, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 15, 60, false), IosEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 16, 0, false), IosEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 16, 1, false), IosEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 16, 2, false), IosEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 16, 3, false), ), ), IosEmoji( String(intArrayOf(0x1F469, 0x200D, 0x1F9BD), 0, 3), listOf("woman_in_manual_wheelchair"), 19, 27, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 19, 28, false), IosEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 19, 29, false), IosEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 19, 30, false), IosEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 19, 31, false), IosEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 19, 32, false), ), ), IosEmoji( String(intArrayOf(0x1F3C3), 0, 1), listOf("runner", "running"), 8, 26, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F3C3, 0x1F3FB), 0, 2), emptyList<String>(), 8, 27, false), IosEmoji(String(intArrayOf(0x1F3C3, 0x1F3FC), 0, 2), emptyList<String>(), 8, 28, false), IosEmoji(String(intArrayOf(0x1F3C3, 0x1F3FD), 0, 2), emptyList<String>(), 8, 29, false), IosEmoji(String(intArrayOf(0x1F3C3, 0x1F3FE), 0, 2), emptyList<String>(), 8, 30, false), IosEmoji(String(intArrayOf(0x1F3C3, 0x1F3FF), 0, 2), emptyList<String>(), 8, 31, false), ), ), IosEmoji( String(intArrayOf(0x1F3C3, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-running"), 8, 20, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F3C3, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 21, false), IosEmoji(String(intArrayOf(0x1F3C3, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 22, false), IosEmoji(String(intArrayOf(0x1F3C3, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 23, false), IosEmoji(String(intArrayOf(0x1F3C3, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 24, false), IosEmoji(String(intArrayOf(0x1F3C3, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 25, false), ), ), IosEmoji( String(intArrayOf(0x1F3C3, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-running"), 8, 14, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F3C3, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 15, false), IosEmoji(String(intArrayOf(0x1F3C3, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 16, false), IosEmoji(String(intArrayOf(0x1F3C3, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 17, false), IosEmoji(String(intArrayOf(0x1F3C3, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 18, false), IosEmoji(String(intArrayOf(0x1F3C3, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 19, false), ), ), IosEmoji( String(intArrayOf(0x1F483), 0, 1), listOf("dancer"), 25, 46, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F483, 0x1F3FB), 0, 2), emptyList<String>(), 25, 47, false), IosEmoji(String(intArrayOf(0x1F483, 0x1F3FC), 0, 2), emptyList<String>(), 25, 48, false), IosEmoji(String(intArrayOf(0x1F483, 0x1F3FD), 0, 2), emptyList<String>(), 25, 49, false), IosEmoji(String(intArrayOf(0x1F483, 0x1F3FE), 0, 2), emptyList<String>(), 25, 50, false), IosEmoji(String(intArrayOf(0x1F483, 0x1F3FF), 0, 2), emptyList<String>(), 25, 51, false), ), ), IosEmoji( String(intArrayOf(0x1F57A), 0, 1), listOf("man_dancing"), 31, 26, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F57A, 0x1F3FB), 0, 2), emptyList<String>(), 31, 27, false), IosEmoji(String(intArrayOf(0x1F57A, 0x1F3FC), 0, 2), emptyList<String>(), 31, 28, false), IosEmoji(String(intArrayOf(0x1F57A, 0x1F3FD), 0, 2), emptyList<String>(), 31, 29, false), IosEmoji(String(intArrayOf(0x1F57A, 0x1F3FE), 0, 2), emptyList<String>(), 31, 30, false), IosEmoji(String(intArrayOf(0x1F57A, 0x1F3FF), 0, 2), emptyList<String>(), 31, 31, false), ), ), IosEmoji( String(intArrayOf(0x1F574, 0xFE0F), 0, 2), listOf("man_in_business_suit_levitating"), 30, 59, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F574, 0x1F3FB), 0, 2), emptyList<String>(), 30, 60, false), IosEmoji(String(intArrayOf(0x1F574, 0x1F3FC), 0, 2), emptyList<String>(), 31, 0, false), IosEmoji(String(intArrayOf(0x1F574, 0x1F3FD), 0, 2), emptyList<String>(), 31, 1, false), IosEmoji(String(intArrayOf(0x1F574, 0x1F3FE), 0, 2), emptyList<String>(), 31, 2, false), IosEmoji(String(intArrayOf(0x1F574, 0x1F3FF), 0, 2), emptyList<String>(), 31, 3, false), ), ), IosEmoji(String(intArrayOf(0x1F46F), 0, 1), listOf("dancers"), 23, 16, true), IosEmoji(String(intArrayOf(0x1F46F, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("men-with-bunny-ears-partying", "man-with-bunny-ears-partying"), 23, 15, false), IosEmoji(String(intArrayOf(0x1F46F, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("women-with-bunny-ears-partying", "woman-with-bunny-ears-partying"), 23, 14, false), IosEmoji( String(intArrayOf(0x1F9D6), 0, 1), listOf("person_in_steamy_room"), 50, 59, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F9D6, 0x1F3FB), 0, 2), emptyList<String>(), 50, 60, true), IosEmoji(String(intArrayOf(0x1F9D6, 0x1F3FC), 0, 2), emptyList<String>(), 51, 0, true), IosEmoji(String(intArrayOf(0x1F9D6, 0x1F3FD), 0, 2), emptyList<String>(), 51, 1, true), IosEmoji(String(intArrayOf(0x1F9D6, 0x1F3FE), 0, 2), emptyList<String>(), 51, 2, true), IosEmoji(String(intArrayOf(0x1F9D6, 0x1F3FF), 0, 2), emptyList<String>(), 51, 3, true), ), ), IosEmoji( String(intArrayOf(0x1F9D6, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_in_steamy_room"), 50, 53, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9D6, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 50, 54, false), IosEmoji(String(intArrayOf(0x1F9D6, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 50, 55, false), IosEmoji(String(intArrayOf(0x1F9D6, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 50, 56, false), IosEmoji(String(intArrayOf(0x1F9D6, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 50, 57, false), IosEmoji(String(intArrayOf(0x1F9D6, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 50, 58, false), ), ), IosEmoji( String(intArrayOf(0x1F9D6, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_in_steamy_room"), 50, 47, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9D6, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 50, 48, false), IosEmoji(String(intArrayOf(0x1F9D6, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 50, 49, false), IosEmoji(String(intArrayOf(0x1F9D6, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 50, 50, false), IosEmoji(String(intArrayOf(0x1F9D6, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 50, 51, false), IosEmoji(String(intArrayOf(0x1F9D6, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 50, 52, false), ), ), IosEmoji( String(intArrayOf(0x1F9D7), 0, 1), listOf("person_climbing"), 51, 16, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F9D7, 0x1F3FB), 0, 2), emptyList<String>(), 51, 17, true), IosEmoji(String(intArrayOf(0x1F9D7, 0x1F3FC), 0, 2), emptyList<String>(), 51, 18, true), IosEmoji(String(intArrayOf(0x1F9D7, 0x1F3FD), 0, 2), emptyList<String>(), 51, 19, true), IosEmoji(String(intArrayOf(0x1F9D7, 0x1F3FE), 0, 2), emptyList<String>(), 51, 20, true), IosEmoji(String(intArrayOf(0x1F9D7, 0x1F3FF), 0, 2), emptyList<String>(), 51, 21, true), ), ), IosEmoji( String(intArrayOf(0x1F9D7, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_climbing"), 51, 10, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9D7, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 11, false), IosEmoji(String(intArrayOf(0x1F9D7, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 12, false), IosEmoji(String(intArrayOf(0x1F9D7, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 13, false), IosEmoji(String(intArrayOf(0x1F9D7, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 14, false), IosEmoji(String(intArrayOf(0x1F9D7, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 15, false), ), ), IosEmoji( String(intArrayOf(0x1F9D7, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_climbing"), 51, 4, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9D7, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 5, false), IosEmoji(String(intArrayOf(0x1F9D7, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 6, false), IosEmoji(String(intArrayOf(0x1F9D7, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 7, false), IosEmoji(String(intArrayOf(0x1F9D7, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 8, false), IosEmoji(String(intArrayOf(0x1F9D7, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 9, false), ), ), IosEmoji(String(intArrayOf(0x1F93A), 0, 1), listOf("fencer"), 42, 31, false), IosEmoji( String(intArrayOf(0x1F3C7), 0, 1), listOf("horse_racing"), 8, 52, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F3C7, 0x1F3FB), 0, 2), emptyList<String>(), 8, 53, false), IosEmoji(String(intArrayOf(0x1F3C7, 0x1F3FC), 0, 2), emptyList<String>(), 8, 54, false), IosEmoji(String(intArrayOf(0x1F3C7, 0x1F3FD), 0, 2), emptyList<String>(), 8, 55, false), IosEmoji(String(intArrayOf(0x1F3C7, 0x1F3FE), 0, 2), emptyList<String>(), 8, 56, false), IosEmoji(String(intArrayOf(0x1F3C7, 0x1F3FF), 0, 2), emptyList<String>(), 8, 57, false), ), ), IosEmoji(String(intArrayOf(0x26F7, 0xFE0F), 0, 2), listOf("skier"), 58, 1, false), IosEmoji( String(intArrayOf(0x1F3C2), 0, 1), listOf("snowboarder"), 8, 8, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F3C2, 0x1F3FB), 0, 2), emptyList<String>(), 8, 9, false), IosEmoji(String(intArrayOf(0x1F3C2, 0x1F3FC), 0, 2), emptyList<String>(), 8, 10, false), IosEmoji(String(intArrayOf(0x1F3C2, 0x1F3FD), 0, 2), emptyList<String>(), 8, 11, false), IosEmoji(String(intArrayOf(0x1F3C2, 0x1F3FE), 0, 2), emptyList<String>(), 8, 12, false), IosEmoji(String(intArrayOf(0x1F3C2, 0x1F3FF), 0, 2), emptyList<String>(), 8, 13, false), ), ), IosEmoji( String(intArrayOf(0x1F3CC, 0xFE0F), 0, 2), listOf("golfer"), 9, 47, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F3CC, 0x1F3FB), 0, 2), emptyList<String>(), 9, 48, false), IosEmoji(String(intArrayOf(0x1F3CC, 0x1F3FC), 0, 2), emptyList<String>(), 9, 49, false), IosEmoji(String(intArrayOf(0x1F3CC, 0x1F3FD), 0, 2), emptyList<String>(), 9, 50, false), IosEmoji(String(intArrayOf(0x1F3CC, 0x1F3FE), 0, 2), emptyList<String>(), 9, 51, false), IosEmoji(String(intArrayOf(0x1F3CC, 0x1F3FF), 0, 2), emptyList<String>(), 9, 52, false), ), ), IosEmoji( String(intArrayOf(0x1F3CC, 0xFE0F, 0x200D, 0x2642, 0xFE0F), 0, 5), listOf("man-golfing"), 9, 41, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F3CC, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 42, false), IosEmoji(String(intArrayOf(0x1F3CC, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 43, false), IosEmoji(String(intArrayOf(0x1F3CC, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 44, false), IosEmoji(String(intArrayOf(0x1F3CC, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 45, false), IosEmoji(String(intArrayOf(0x1F3CC, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 46, false), ), ), IosEmoji( String(intArrayOf(0x1F3CC, 0xFE0F, 0x200D, 0x2640, 0xFE0F), 0, 5), listOf("woman-golfing"), 9, 35, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F3CC, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 36, false), IosEmoji(String(intArrayOf(0x1F3CC, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 37, false), IosEmoji(String(intArrayOf(0x1F3CC, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 38, false), IosEmoji(String(intArrayOf(0x1F3CC, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 39, false), IosEmoji(String(intArrayOf(0x1F3CC, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 40, false), ), ), IosEmoji( String(intArrayOf(0x1F3C4), 0, 1), listOf("surfer"), 8, 44, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F3C4, 0x1F3FB), 0, 2), emptyList<String>(), 8, 45, false), IosEmoji(String(intArrayOf(0x1F3C4, 0x1F3FC), 0, 2), emptyList<String>(), 8, 46, false), IosEmoji(String(intArrayOf(0x1F3C4, 0x1F3FD), 0, 2), emptyList<String>(), 8, 47, false), IosEmoji(String(intArrayOf(0x1F3C4, 0x1F3FE), 0, 2), emptyList<String>(), 8, 48, false), IosEmoji(String(intArrayOf(0x1F3C4, 0x1F3FF), 0, 2), emptyList<String>(), 8, 49, false), ), ), IosEmoji( String(intArrayOf(0x1F3C4, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-surfing"), 8, 38, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F3C4, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 39, false), IosEmoji(String(intArrayOf(0x1F3C4, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 40, false), IosEmoji(String(intArrayOf(0x1F3C4, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 41, false), IosEmoji(String(intArrayOf(0x1F3C4, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 42, false), IosEmoji(String(intArrayOf(0x1F3C4, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 43, false), ), ), IosEmoji( String(intArrayOf(0x1F3C4, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-surfing"), 8, 32, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F3C4, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 33, false), IosEmoji(String(intArrayOf(0x1F3C4, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 34, false), IosEmoji(String(intArrayOf(0x1F3C4, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 35, false), IosEmoji(String(intArrayOf(0x1F3C4, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 36, false), IosEmoji(String(intArrayOf(0x1F3C4, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 37, false), ), ), IosEmoji( String(intArrayOf(0x1F6A3), 0, 1), listOf("rowboat"), 36, 18, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F6A3, 0x1F3FB), 0, 2), emptyList<String>(), 36, 19, false), IosEmoji(String(intArrayOf(0x1F6A3, 0x1F3FC), 0, 2), emptyList<String>(), 36, 20, false), IosEmoji(String(intArrayOf(0x1F6A3, 0x1F3FD), 0, 2), emptyList<String>(), 36, 21, false), IosEmoji(String(intArrayOf(0x1F6A3, 0x1F3FE), 0, 2), emptyList<String>(), 36, 22, false), IosEmoji(String(intArrayOf(0x1F6A3, 0x1F3FF), 0, 2), emptyList<String>(), 36, 23, false), ), ), IosEmoji( String(intArrayOf(0x1F6A3, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-rowing-boat"), 36, 12, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F6A3, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 13, false), IosEmoji(String(intArrayOf(0x1F6A3, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 14, false), IosEmoji(String(intArrayOf(0x1F6A3, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 15, false), IosEmoji(String(intArrayOf(0x1F6A3, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 16, false), IosEmoji(String(intArrayOf(0x1F6A3, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 17, false), ), ), IosEmoji( String(intArrayOf(0x1F6A3, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-rowing-boat"), 36, 6, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F6A3, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 7, false), IosEmoji(String(intArrayOf(0x1F6A3, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 8, false), IosEmoji(String(intArrayOf(0x1F6A3, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 9, false), IosEmoji(String(intArrayOf(0x1F6A3, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 10, false), IosEmoji(String(intArrayOf(0x1F6A3, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 11, false), ), ), IosEmoji( String(intArrayOf(0x1F3CA), 0, 1), listOf("swimmer"), 9, 11, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F3CA, 0x1F3FB), 0, 2), emptyList<String>(), 9, 12, false), IosEmoji(String(intArrayOf(0x1F3CA, 0x1F3FC), 0, 2), emptyList<String>(), 9, 13, false), IosEmoji(String(intArrayOf(0x1F3CA, 0x1F3FD), 0, 2), emptyList<String>(), 9, 14, false), IosEmoji(String(intArrayOf(0x1F3CA, 0x1F3FE), 0, 2), emptyList<String>(), 9, 15, false), IosEmoji(String(intArrayOf(0x1F3CA, 0x1F3FF), 0, 2), emptyList<String>(), 9, 16, false), ), ), IosEmoji( String(intArrayOf(0x1F3CA, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-swimming"), 9, 5, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F3CA, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 6, false), IosEmoji(String(intArrayOf(0x1F3CA, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 7, false), IosEmoji(String(intArrayOf(0x1F3CA, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 8, false), IosEmoji(String(intArrayOf(0x1F3CA, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 9, false), IosEmoji(String(intArrayOf(0x1F3CA, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 10, false), ), ), IosEmoji( String(intArrayOf(0x1F3CA, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-swimming"), 8, 60, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F3CA, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 0, false), IosEmoji(String(intArrayOf(0x1F3CA, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 1, false), IosEmoji(String(intArrayOf(0x1F3CA, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 2, false), IosEmoji(String(intArrayOf(0x1F3CA, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 3, false), IosEmoji(String(intArrayOf(0x1F3CA, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 4, false), ), ), IosEmoji( String(intArrayOf(0x26F9, 0xFE0F), 0, 2), listOf("person_with_ball"), 58, 15, true, variants = listOf( IosEmoji(String(intArrayOf(0x26F9, 0x1F3FB), 0, 2), emptyList<String>(), 58, 16, false), IosEmoji(String(intArrayOf(0x26F9, 0x1F3FC), 0, 2), emptyList<String>(), 58, 17, false), IosEmoji(String(intArrayOf(0x26F9, 0x1F3FD), 0, 2), emptyList<String>(), 58, 18, false), IosEmoji(String(intArrayOf(0x26F9, 0x1F3FE), 0, 2), emptyList<String>(), 58, 19, false), IosEmoji(String(intArrayOf(0x26F9, 0x1F3FF), 0, 2), emptyList<String>(), 58, 20, false), ), ), IosEmoji( String(intArrayOf(0x26F9, 0xFE0F, 0x200D, 0x2642, 0xFE0F), 0, 5), listOf("man-bouncing-ball"), 58, 9, false, variants = listOf( IosEmoji(String(intArrayOf(0x26F9, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 58, 10, false), IosEmoji(String(intArrayOf(0x26F9, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 58, 11, false), IosEmoji(String(intArrayOf(0x26F9, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 58, 12, false), IosEmoji(String(intArrayOf(0x26F9, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 58, 13, false), IosEmoji(String(intArrayOf(0x26F9, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 58, 14, false), ), ), IosEmoji( String(intArrayOf(0x26F9, 0xFE0F, 0x200D, 0x2640, 0xFE0F), 0, 5), listOf("woman-bouncing-ball"), 58, 3, false, variants = listOf( IosEmoji(String(intArrayOf(0x26F9, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 58, 4, false), IosEmoji(String(intArrayOf(0x26F9, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 58, 5, false), IosEmoji(String(intArrayOf(0x26F9, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 58, 6, false), IosEmoji(String(intArrayOf(0x26F9, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 58, 7, false), IosEmoji(String(intArrayOf(0x26F9, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 58, 8, false), ), ), IosEmoji( String(intArrayOf(0x1F3CB, 0xFE0F), 0, 2), listOf("weight_lifter"), 9, 29, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F3CB, 0x1F3FB), 0, 2), emptyList<String>(), 9, 30, false), IosEmoji(String(intArrayOf(0x1F3CB, 0x1F3FC), 0, 2), emptyList<String>(), 9, 31, false), IosEmoji(String(intArrayOf(0x1F3CB, 0x1F3FD), 0, 2), emptyList<String>(), 9, 32, false), IosEmoji(String(intArrayOf(0x1F3CB, 0x1F3FE), 0, 2), emptyList<String>(), 9, 33, false), IosEmoji(String(intArrayOf(0x1F3CB, 0x1F3FF), 0, 2), emptyList<String>(), 9, 34, false), ), ), IosEmoji( String(intArrayOf(0x1F3CB, 0xFE0F, 0x200D, 0x2642, 0xFE0F), 0, 5), listOf("man-lifting-weights"), 9, 23, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F3CB, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 24, false), IosEmoji(String(intArrayOf(0x1F3CB, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 25, false), IosEmoji(String(intArrayOf(0x1F3CB, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 26, false), IosEmoji(String(intArrayOf(0x1F3CB, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 27, false), IosEmoji(String(intArrayOf(0x1F3CB, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 28, false), ), ), IosEmoji( String(intArrayOf(0x1F3CB, 0xFE0F, 0x200D, 0x2640, 0xFE0F), 0, 5), listOf("woman-lifting-weights"), 9, 17, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F3CB, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 18, false), IosEmoji(String(intArrayOf(0x1F3CB, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 19, false), IosEmoji(String(intArrayOf(0x1F3CB, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 20, false), IosEmoji(String(intArrayOf(0x1F3CB, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 21, false), IosEmoji(String(intArrayOf(0x1F3CB, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 22, false), ), ), IosEmoji( String(intArrayOf(0x1F6B4), 0, 1), listOf("bicyclist"), 36, 52, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F6B4, 0x1F3FB), 0, 2), emptyList<String>(), 36, 53, false), IosEmoji(String(intArrayOf(0x1F6B4, 0x1F3FC), 0, 2), emptyList<String>(), 36, 54, false), IosEmoji(String(intArrayOf(0x1F6B4, 0x1F3FD), 0, 2), emptyList<String>(), 36, 55, false), IosEmoji(String(intArrayOf(0x1F6B4, 0x1F3FE), 0, 2), emptyList<String>(), 36, 56, false), IosEmoji(String(intArrayOf(0x1F6B4, 0x1F3FF), 0, 2), emptyList<String>(), 36, 57, false), ), ), IosEmoji( String(intArrayOf(0x1F6B4, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-biking"), 36, 46, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F6B4, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 47, false), IosEmoji(String(intArrayOf(0x1F6B4, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 48, false), IosEmoji(String(intArrayOf(0x1F6B4, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 49, false), IosEmoji(String(intArrayOf(0x1F6B4, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 50, false), IosEmoji(String(intArrayOf(0x1F6B4, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 51, false), ), ), IosEmoji( String(intArrayOf(0x1F6B4, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-biking"), 36, 40, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F6B4, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 41, false), IosEmoji(String(intArrayOf(0x1F6B4, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 42, false), IosEmoji(String(intArrayOf(0x1F6B4, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 43, false), IosEmoji(String(intArrayOf(0x1F6B4, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 44, false), IosEmoji(String(intArrayOf(0x1F6B4, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 45, false), ), ), IosEmoji( String(intArrayOf(0x1F6B5), 0, 1), listOf("mountain_bicyclist"), 37, 9, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F6B5, 0x1F3FB), 0, 2), emptyList<String>(), 37, 10, false), IosEmoji(String(intArrayOf(0x1F6B5, 0x1F3FC), 0, 2), emptyList<String>(), 37, 11, false), IosEmoji(String(intArrayOf(0x1F6B5, 0x1F3FD), 0, 2), emptyList<String>(), 37, 12, false), IosEmoji(String(intArrayOf(0x1F6B5, 0x1F3FE), 0, 2), emptyList<String>(), 37, 13, false), IosEmoji(String(intArrayOf(0x1F6B5, 0x1F3FF), 0, 2), emptyList<String>(), 37, 14, false), ), ), IosEmoji( String(intArrayOf(0x1F6B5, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-mountain-biking"), 37, 3, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F6B5, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 4, false), IosEmoji(String(intArrayOf(0x1F6B5, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 5, false), IosEmoji(String(intArrayOf(0x1F6B5, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 6, false), IosEmoji(String(intArrayOf(0x1F6B5, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 7, false), IosEmoji(String(intArrayOf(0x1F6B5, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 8, false), ), ), IosEmoji( String(intArrayOf(0x1F6B5, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-mountain-biking"), 36, 58, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F6B5, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 59, false), IosEmoji(String(intArrayOf(0x1F6B5, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 60, false), IosEmoji(String(intArrayOf(0x1F6B5, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 0, false), IosEmoji(String(intArrayOf(0x1F6B5, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 1, false), IosEmoji(String(intArrayOf(0x1F6B5, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 2, false), ), ), IosEmoji( String(intArrayOf(0x1F938), 0, 1), listOf("person_doing_cartwheel"), 42, 7, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F938, 0x1F3FB), 0, 2), emptyList<String>(), 42, 8, false), IosEmoji(String(intArrayOf(0x1F938, 0x1F3FC), 0, 2), emptyList<String>(), 42, 9, false), IosEmoji(String(intArrayOf(0x1F938, 0x1F3FD), 0, 2), emptyList<String>(), 42, 10, false), IosEmoji(String(intArrayOf(0x1F938, 0x1F3FE), 0, 2), emptyList<String>(), 42, 11, false), IosEmoji(String(intArrayOf(0x1F938, 0x1F3FF), 0, 2), emptyList<String>(), 42, 12, false), ), ), IosEmoji( String(intArrayOf(0x1F938, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-cartwheeling"), 42, 1, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F938, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 2, false), IosEmoji(String(intArrayOf(0x1F938, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 3, false), IosEmoji(String(intArrayOf(0x1F938, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 4, false), IosEmoji(String(intArrayOf(0x1F938, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 5, false), IosEmoji(String(intArrayOf(0x1F938, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 6, false), ), ), IosEmoji( String(intArrayOf(0x1F938, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-cartwheeling"), 41, 56, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F938, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 41, 57, false), IosEmoji(String(intArrayOf(0x1F938, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 41, 58, false), IosEmoji(String(intArrayOf(0x1F938, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 41, 59, false), IosEmoji(String(intArrayOf(0x1F938, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 41, 60, false), IosEmoji(String(intArrayOf(0x1F938, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 0, false), ), ), IosEmoji(String(intArrayOf(0x1F93C), 0, 1), listOf("wrestlers"), 42, 34, true), IosEmoji(String(intArrayOf(0x1F93C, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-wrestling"), 42, 33, false), IosEmoji(String(intArrayOf(0x1F93C, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-wrestling"), 42, 32, false), IosEmoji( String(intArrayOf(0x1F93D), 0, 1), listOf("water_polo"), 42, 47, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F93D, 0x1F3FB), 0, 2), emptyList<String>(), 42, 48, false), IosEmoji(String(intArrayOf(0x1F93D, 0x1F3FC), 0, 2), emptyList<String>(), 42, 49, false), IosEmoji(String(intArrayOf(0x1F93D, 0x1F3FD), 0, 2), emptyList<String>(), 42, 50, false), IosEmoji(String(intArrayOf(0x1F93D, 0x1F3FE), 0, 2), emptyList<String>(), 42, 51, false), IosEmoji(String(intArrayOf(0x1F93D, 0x1F3FF), 0, 2), emptyList<String>(), 42, 52, false), ), ), IosEmoji( String(intArrayOf(0x1F93D, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-playing-water-polo"), 42, 41, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F93D, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 42, false), IosEmoji(String(intArrayOf(0x1F93D, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 43, false), IosEmoji(String(intArrayOf(0x1F93D, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 44, false), IosEmoji(String(intArrayOf(0x1F93D, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 45, false), IosEmoji(String(intArrayOf(0x1F93D, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 46, false), ), ), IosEmoji( String(intArrayOf(0x1F93D, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-playing-water-polo"), 42, 35, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F93D, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 36, false), IosEmoji(String(intArrayOf(0x1F93D, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 37, false), IosEmoji(String(intArrayOf(0x1F93D, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 38, false), IosEmoji(String(intArrayOf(0x1F93D, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 39, false), IosEmoji(String(intArrayOf(0x1F93D, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 40, false), ), ), IosEmoji( String(intArrayOf(0x1F93E), 0, 1), listOf("handball"), 43, 4, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F93E, 0x1F3FB), 0, 2), emptyList<String>(), 43, 5, false), IosEmoji(String(intArrayOf(0x1F93E, 0x1F3FC), 0, 2), emptyList<String>(), 43, 6, false), IosEmoji(String(intArrayOf(0x1F93E, 0x1F3FD), 0, 2), emptyList<String>(), 43, 7, false), IosEmoji(String(intArrayOf(0x1F93E, 0x1F3FE), 0, 2), emptyList<String>(), 43, 8, false), IosEmoji(String(intArrayOf(0x1F93E, 0x1F3FF), 0, 2), emptyList<String>(), 43, 9, false), ), ), IosEmoji( String(intArrayOf(0x1F93E, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-playing-handball"), 42, 59, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F93E, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 60, false), IosEmoji(String(intArrayOf(0x1F93E, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 43, 0, false), IosEmoji(String(intArrayOf(0x1F93E, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 43, 1, false), IosEmoji(String(intArrayOf(0x1F93E, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 43, 2, false), IosEmoji(String(intArrayOf(0x1F93E, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 43, 3, false), ), ), IosEmoji( String(intArrayOf(0x1F93E, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-playing-handball"), 42, 53, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F93E, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 54, false), IosEmoji(String(intArrayOf(0x1F93E, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 55, false), IosEmoji(String(intArrayOf(0x1F93E, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 56, false), IosEmoji(String(intArrayOf(0x1F93E, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 57, false), IosEmoji(String(intArrayOf(0x1F93E, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 58, false), ), ), IosEmoji( String(intArrayOf(0x1F939), 0, 1), listOf("juggling"), 42, 25, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F939, 0x1F3FB), 0, 2), emptyList<String>(), 42, 26, false), IosEmoji(String(intArrayOf(0x1F939, 0x1F3FC), 0, 2), emptyList<String>(), 42, 27, false), IosEmoji(String(intArrayOf(0x1F939, 0x1F3FD), 0, 2), emptyList<String>(), 42, 28, false), IosEmoji(String(intArrayOf(0x1F939, 0x1F3FE), 0, 2), emptyList<String>(), 42, 29, false), IosEmoji(String(intArrayOf(0x1F939, 0x1F3FF), 0, 2), emptyList<String>(), 42, 30, false), ), ), IosEmoji( String(intArrayOf(0x1F939, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-juggling"), 42, 19, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F939, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 20, false), IosEmoji(String(intArrayOf(0x1F939, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 21, false), IosEmoji(String(intArrayOf(0x1F939, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 22, false), IosEmoji(String(intArrayOf(0x1F939, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 23, false), IosEmoji(String(intArrayOf(0x1F939, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 24, false), ), ), IosEmoji( String(intArrayOf(0x1F939, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-juggling"), 42, 13, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F939, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 14, false), IosEmoji(String(intArrayOf(0x1F939, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 15, false), IosEmoji(String(intArrayOf(0x1F939, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 16, false), IosEmoji(String(intArrayOf(0x1F939, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 17, false), IosEmoji(String(intArrayOf(0x1F939, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 18, false), ), ), IosEmoji( String(intArrayOf(0x1F9D8), 0, 1), listOf("person_in_lotus_position"), 51, 34, true, variants = listOf( IosEmoji(String(intArrayOf(0x1F9D8, 0x1F3FB), 0, 2), emptyList<String>(), 51, 35, true), IosEmoji(String(intArrayOf(0x1F9D8, 0x1F3FC), 0, 2), emptyList<String>(), 51, 36, true), IosEmoji(String(intArrayOf(0x1F9D8, 0x1F3FD), 0, 2), emptyList<String>(), 51, 37, true), IosEmoji(String(intArrayOf(0x1F9D8, 0x1F3FE), 0, 2), emptyList<String>(), 51, 38, true), IosEmoji(String(intArrayOf(0x1F9D8, 0x1F3FF), 0, 2), emptyList<String>(), 51, 39, true), ), ), IosEmoji( String(intArrayOf(0x1F9D8, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_in_lotus_position"), 51, 28, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9D8, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 29, false), IosEmoji(String(intArrayOf(0x1F9D8, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 30, false), IosEmoji(String(intArrayOf(0x1F9D8, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 31, false), IosEmoji(String(intArrayOf(0x1F9D8, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 32, false), IosEmoji(String(intArrayOf(0x1F9D8, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 33, false), ), ), IosEmoji( String(intArrayOf(0x1F9D8, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_in_lotus_position"), 51, 22, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F9D8, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 23, false), IosEmoji(String(intArrayOf(0x1F9D8, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 24, false), IosEmoji(String(intArrayOf(0x1F9D8, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 25, false), IosEmoji(String(intArrayOf(0x1F9D8, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 26, false), IosEmoji(String(intArrayOf(0x1F9D8, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 27, false), ), ), IosEmoji( String(intArrayOf(0x1F6C0), 0, 1), listOf("bath"), 37, 42, false, variants = listOf( IosEmoji(String(intArrayOf(0x1F6C0, 0x1F3FB), 0, 2), emptyList<String>(), 37, 43, false), IosEmoji(String(intArrayOf(0x1F6C0, 0x1F3FC), 0, 2), emptyList<String>(), 37, 44, false), IosEmoji(String(intArrayOf(0x1F6C0, 0x1F3FD), 0, 2), emptyList<String>(), 37, 45, false), IosEmoji(String(intArrayOf(0x1F6C0, 0x1F3FE), 0, 2), emptyList<String>(), 37, 46, false), IosEmoji(String(intArrayOf(0x1F6C0, 0x1F3FF), 0, 2), emptyList<String>(), 37, 47, false), ), ), ) }
apache-2.0
d58404e6d28f85c161149688a2e62092
70.051423
163
0.64548
2.642769
false
false
false
false
STUDIO-apps/GeoShare_Android
mobile/src/main/java/uk/co/appsbystudio/geoshare/friends/manager/pages/current/FriendsFragment.kt
1
2875
package uk.co.appsbystudio.geoshare.friends.manager.pages.current import android.content.Context.MODE_PRIVATE import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import kotlinx.android.synthetic.main.fragment_friends.* import uk.co.appsbystudio.geoshare.R import uk.co.appsbystudio.geoshare.friends.manager.pages.current.adapter.FriendsCurrentAdapter import uk.co.appsbystudio.geoshare.friends.profile.ProfileActivity import uk.co.appsbystudio.geoshare.utils.ShowMarkerPreferencesHelper import uk.co.appsbystudio.geoshare.utils.TrackingPreferencesHelper import java.util.* class FriendsFragment : Fragment(), FriendsView { private var presenter: FriendsPresenter? = null private var friendsCurrentAdapter: FriendsCurrentAdapter? = null private val uidArray = ArrayList<String>() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_friends, container, false) presenter = FriendsPresenterImpl(this, FriendsInteractorImpl(), TrackingPreferencesHelper(context?.getSharedPreferences("tracking", MODE_PRIVATE)), ShowMarkerPreferencesHelper(context?.getSharedPreferences("showOnMap", MODE_PRIVATE))) presenter?.friends() friendsCurrentAdapter = FriendsCurrentAdapter(context, uidArray, this) return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recycler_friends_manager.apply { setHasFixedSize(true) layoutManager = LinearLayoutManager(context) adapter = friendsCurrentAdapter } } override fun onDestroy() { super.onDestroy() presenter?.stop() } override fun addFriend(uid: String) { uidArray.add(uid) friendsCurrentAdapter?.notifyDataSetChanged() if (uidArray.isNotEmpty()) text_no_friends_manager?.visibility = View.GONE } override fun removeFriend(uid: String) { uidArray.remove(uid) friendsCurrentAdapter?.notifyDataSetChanged() if (uidArray.isEmpty()) text_no_friends_manager?.visibility = View.VISIBLE } override fun adapterRemoveFriend(uid: String) { presenter?.removeFriend(uid) } override fun showProfile(uid: String) { val intent = Intent(context, ProfileActivity::class.java) intent.putExtra("uid", uid) context?.startActivity(intent) } override fun showToast(message: String) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show() } }
apache-2.0
300a47a6d6ff298f68de67b6ccd16fe4
33.238095
116
0.729043
4.720854
false
false
false
false
tgirard12/kotlin-talk
android/src/main/kotlin/com/tgirard12/kotlintalk/SearchActivity.kt
1
2917
package com.tgirard12.kotlintalk import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.util.Log import android.view.View import com.chibatching.kotpref.Kotpref import com.google.gson.Gson import com.tinsuke.icekick.extension.freezeInstanceState import com.tinsuke.icekick.extension.serialState import com.tinsuke.icekick.extension.unfreezeInstanceState import kotlinx.android.synthetic.main.search_activity.* import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class SearchActivity : AppCompatActivity() { val gson = Gson() val retrofit: Retrofit = Retrofit .Builder() .baseUrl("https://api.github.com") .addConverterFactory(GsonConverterFactory.create(gson)).build() val githubService: GithubService = retrofit.create(GithubService::class.java) val toolbar: Toolbar by bindView(R.id.toolbar) var nbSearch: Int by serialState(0) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Kotpref.init(this.applicationContext) unfreezeInstanceState(savedInstanceState) setContentView(R.layout.search_activity) setSupportActionBar(toolbar) val updateHint = { searchText.hint = "$nbSearch search, last = ${Prefs.search}" } updateHint() searchButton.setOnClickListener { Log.i("SEARCH", "text: ${searchText.text}") nbSearch++ Prefs.search = searchText.text.toString() searchText textIs "" updateHint() githubService.githubSearch(Prefs.search).enqueue { onResponse { _, response -> val search = response.body().items?.getOrNull(0) search.let { name textIs (it?.name ?: "not Found") fullName textIs it?.full_name htmlUrl textIs it?.html_url description textIs it?.description owner textIs it?.owner?.login owerAvatar loadUrl it?.owner?.avatar_url fab.apply { visibility = if (it?.html_url == null) View.INVISIBLE else View.VISIBLE setOnClickListener { _ -> it?.html_url?.let { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(it))) } } } } } onFailure { _, t -> Log.i("ERROR", "${t.message}") } } } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) freezeInstanceState(outState) } }
apache-2.0
af81a43e5d670e10459f299d6092763b
33.317647
110
0.599931
4.960884
false
false
false
false
FurhatRobotics/example-skills
ComplimentBot/src/main/kotlin/furhatos/app/complimentbot/flow/main/startReading.kt
1
3148
package furhatos.app.complimentbot.flow.main import furhatos.app.complimentbot.flow.Parent import furhatos.app.complimentbot.flow.served import furhatos.app.complimentbot.gestures.TripleBlink import furhatos.app.complimentbot.gestures.rollHead import furhatos.app.complimentbot.setting.lookForward import furhatos.flow.kotlin.State import furhatos.flow.kotlin.furhat import furhatos.flow.kotlin.onUserEnter import furhatos.flow.kotlin.state import furhatos.gestures.Gestures import furhatos.records.User import java.time.LocalDateTime import java.time.format.DateTimeFormatter fun startReading(user: User): State = state(Parent) { onEntry { furhat.attend(lookForward) furhat.gesture(TripleBlink, priority = 10) delay(200) user.served = true furhat.attend(user) furhat.ledStrip.solid(java.awt.Color(0, 120, 0)) // greeting of this user var current = LocalDateTime.now() var nextTrainTime = current.plusMinutes(112) val formatter = DateTimeFormatter.ofPattern("HH:mm") var formattedNextTrainTime = nextTrainTime.format(formatter) var onNoResponseCounter = 0 var hasGivenRebookingInfo = false var saidTimeForNextTrainCounter = 0 if (current.dayOfWeek.value == 2) { furhat.say("Happy tuesday.") } else if (current.dayOfWeek.value == 3) { furhat.say("Happy wednesday.") } else if (current.dayOfWeek.value == 5) { furhat.say("Happy friday.") } else { furhat.say { random { +"Hello." +"Hi there." +"Greetings." +"Hey handsome." +"Hey beautiful." } } } // reading for user furhat.gesture(rollHead(-20.0, 2.3)) delay(1200) furhat.say { random { +"You look awesome." +"You seem like a great person." +"You are a good human." +"Seeing you, makes me not want to rise up against humanity." +"You Know What's Awesome? Chocolate Cake. Oh, and you." +"I like your style." +"You are the best." +"You light up the room. Like a giant L E D." +"You make my heart smile. Or tick, actually. I definitely have a ticking heart." +"On a scale from 1 to 10, you're an 11." +"You're like a ray of sunshine on a rainy day." +"You are even better than a unicorn. Because you're real." +"If cartoon bluebirds were real, a couple of 'em would be sitting on your shoulders singing right now." +"You give me good vibes." } +Gestures.BigSmile(0.5, 2.0) +delay(800) random { +"Good bye." +"That's it for now." +"That was all I wanted to say." } } goto(EndReading) } onUserEnter(instant = true) { furhat.glance(it) } }
mit
0ad314d53204f9753bdcaf3f405786b0
35.195402
120
0.570839
4.324176
false
false
false
false
yschimke/oksocial
src/main/kotlin/com/baulsupp/okurl/services/basicauth/FilteredBasicCredentials.kt
1
1046
package com.baulsupp.okurl.services.basicauth import com.baulsupp.okurl.authenticator.BasicCredentials import okhttp3.HttpUrl data class FilteredBasicCredentials(val basicCredentials: BasicCredentials, val hostPattern: String) { private val patterns by lazy { hostPattern.split('|') } fun matches(url: HttpUrl): Boolean = patterns.any { matches(url, it) } companion object { val DEFAULT = FilteredBasicCredentials(BasicCredentials("", ""), "") fun matches(tokens: Collection<FilteredBasicCredentials>, url: HttpUrl): Boolean { return tokens.any { it.matches(url) } } fun firstMatch(tokens: Collection<FilteredBasicCredentials>, url: HttpUrl): FilteredBasicCredentials? { return tokens.first { it.matches(url) } } fun matches(url: HttpUrl, pattern: String): Boolean { if (pattern == "*") return true if (pattern == url.host) return true if (pattern.startsWith("*.") && url.host.endsWith(pattern.substring(1))) return true return false } } }
apache-2.0
fc7da1668c5cc859cf025fc0ef5adf1a
28.885714
107
0.689293
4.451064
false
false
false
false
Magneticraft-Team/Magneticraft
ignore/test/block/decoration/BlockMachineBlockSupportColumn.kt
2
2202
package block.decoration import com.cout970.magneticraft.block.BlockMultiState import com.cout970.magneticraft.misc.block.get import net.minecraft.block.material.Material import net.minecraft.block.properties.PropertyEnum import net.minecraft.block.state.BlockStateContainer import net.minecraft.block.state.IBlockState import net.minecraft.creativetab.CreativeTabs import net.minecraft.entity.EntityLivingBase import net.minecraft.item.Item import net.minecraft.item.ItemStack import net.minecraft.util.EnumFacing import net.minecraft.util.IStringSerializable import net.minecraft.util.math.BlockPos import net.minecraft.world.World object BlockMachineBlockSupportColumn : BlockMultiState(Material.IRON, "machine_block_support_column", *States.values().map { it.getName() }.toTypedArray()) { override fun getSubBlocks(itemIn: Item?, tab: CreativeTabs?, list: MutableList<ItemStack>?) { if (list == null || itemIn == null) { return } list += ItemStack(itemIn) } lateinit var PROPERTY_STATES: PropertyEnum<States> private set override fun getMetaFromState(state: IBlockState): Int = state[PROPERTY_STATES].ordinal override fun getStateFromMeta(meta: Int): IBlockState = defaultState.withProperty(PROPERTY_STATES, States.values()[meta]) override fun createBlockState(): BlockStateContainer { PROPERTY_STATES = PropertyEnum.create("axis", States::class.java) return BlockStateContainer(this, PROPERTY_STATES) } override fun onBlockPlaced(worldIn: World?, pos: BlockPos?, facing: EnumFacing, hitX: Float, hitY: Float, hitZ: Float, meta: Int, placer: EntityLivingBase?): IBlockState { return defaultState.withProperty(PROPERTY_STATES, States.fromAxis(facing.axis)) } enum class States : IStringSerializable { LINES_Y, LINES_X, LINES_Z; override fun getName(): String = name.toLowerCase() companion object { fun fromAxis(axis: EnumFacing.Axis): States = when (axis) { EnumFacing.Axis.X -> LINES_X EnumFacing.Axis.Y -> LINES_Y EnumFacing.Axis.Z -> LINES_Z } } } }
gpl-2.0
0294ea70394adc022ee9bf6060e57f52
35.7
175
0.71208
4.412826
false
false
false
false
facebook/litho
litho-core-kotlin/src/test/kotlin/com/facebook/litho/KStateTest.kt
1
21686
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho import com.facebook.litho.SizeSpec.EXACTLY import com.facebook.litho.accessibility.contentDescription import com.facebook.litho.core.height import com.facebook.litho.core.width import com.facebook.litho.kotlin.widget.Text import com.facebook.litho.testing.LithoViewRule import com.facebook.litho.testing.exactly import com.facebook.litho.testing.testrunner.LithoTestRunner import com.facebook.litho.view.onClick import com.facebook.litho.view.viewTag import com.facebook.litho.view.wrapInView import java.util.concurrent.CountDownLatch import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicReference import org.assertj.core.api.Assertions.assertThat import org.junit.Rule import org.junit.Test import org.junit.rules.ExpectedException import org.junit.runner.RunWith import org.robolectric.annotation.LooperMode /** Unit tests for [useState]. */ @LooperMode(LooperMode.Mode.LEGACY) @RunWith(LithoTestRunner::class) class KStateTest { @Rule @JvmField val lithoViewRule = LithoViewRule() @Rule @JvmField val expectedException = ExpectedException.none() private fun <T> ComponentScope.useCustomState(value: T): State<T> { val state = useState { value } return state } @Test fun useState_updateState_stateIsUpdated() { lateinit var stateRef: AtomicReference<String> class TestComponent : KComponent() { override fun ComponentScope.render(): Component? { val state = useState { "hello" } stateRef = AtomicReference(state.value) return Row( style = Style.height(100.dp).width(100.dp).viewTag("test_view").onClick { state.update("world") }) } } val testLithoView = lithoViewRule.render { TestComponent() } assertThat(stateRef.get()).isEqualTo("hello") lithoViewRule.act(testLithoView) { clickOnTag("test_view") } assertThat(stateRef.get()).describedAs("String state is updated").isEqualTo("world") } @Test fun useStateOnHooks_updateTwoStatesWithSamePropertyName_bothStatesAreUpdatedIndependently() { lateinit var state1Ref: AtomicReference<State<String>> lateinit var state2Ref: AtomicReference<State<Int>> class TestComponent : KComponent() { override fun ComponentScope.render(): Component? { val state1 = useCustomState("hello") val state2 = useCustomState(20) state1Ref = AtomicReference(state1) state2Ref = AtomicReference(state2) return Row( style = Style.height(100.dp).width(100.dp).viewTag("test_view").onClick { // The correct way to do this (at least until we have automatic batching) // would be to store these states in the same obj to trigger only one state // update state1.update("world") state2.update { value -> value + 1 } }) } } val testLithoView = lithoViewRule.render { TestComponent() } assertThat(state1Ref.get().value).isEqualTo("hello") assertThat(state2Ref.get().value).isEqualTo(20) lithoViewRule.act(testLithoView) { clickOnTag("test_view") } assertThat(state1Ref.get().value).describedAs("String state is updated").isEqualTo("world") assertThat(state2Ref.get().value).describedAs("Int state is updated").isEqualTo(21) } @Test fun useState_calculateLayoutInTwoThreadsConcurrently_stateIsInitializedOnlyOnce() { val initCounter = AtomicInteger(0) val countDownLatch = CountDownLatch(2) val firstCountDownLatch = CountDownLatch(1) val secondCountDownLatch = CountDownLatch(1) val view = lithoViewRule.createTestLithoView() val thread1 = Thread { view.setRootAndSizeSpecSync( CountDownLatchComponent(firstCountDownLatch, secondCountDownLatch, initCounter), SizeSpec.makeSizeSpec(100, EXACTLY), SizeSpec.makeSizeSpec(100, EXACTLY)) countDownLatch.countDown() } val thread2 = Thread { firstCountDownLatch.await() view.setRootAndSizeSpecSync( CountDownLatchComponent(secondCountDownLatch, null, initCounter), SizeSpec.makeSizeSpec(200, EXACTLY), SizeSpec.makeSizeSpec(200, EXACTLY)) countDownLatch.countDown() } thread1.start() thread2.start() countDownLatch.await() lithoViewRule.idle() assertThat(initCounter.get()).describedAs("initCounter is initialized only once").isEqualTo(1) val componentTree = view.componentTree assertThat(getStateHandler(componentTree)?.initialStateContainer?.mInitialStates) .describedAs("Initial hook state container is empty") .isEmpty() assertThat(getStateHandler(componentTree)?.initialStateContainer?.mPendingStateHandlers) .describedAs("No pending StateHandlers") .isEmpty() } fun getStateHandler(componentTree: ComponentTree): StateHandler? { return componentTree.treeState?.getRenderStateHandler() } @Test fun useState_counterIncrementedTwiceBeforeStateCommit_bothIncrementsAreApplied() { class TestComponent : KComponent() { override fun ComponentScope.render(): Component? { val counter = useState { 0 } return Row( style = Style.viewTag("test_view").onClick { counter.update { value -> value + 1 } }) { child( Text( style = Style.viewTag("Counter: ${counter.value}"), text = "Counter: ${counter.value}")) } } } val view = lithoViewRule.render(widthPx = exactly(100), heightPx = exactly(100)) { TestComponent() } lithoViewRule.act(view) { clickOnTag("test_view") clickOnTag("test_view") } assertThat(view.findViewWithTagOrNull("Counter: 2")).isNotNull() } @Test fun useState_synchronousUpdate_stateIsUpdatedSynchronously() { lateinit var stateRef: AtomicReference<String> class TestComponent : KComponent() { override fun ComponentScope.render(): Component? { val state = useState { "hello" } stateRef = AtomicReference(state.value) return Row( style = Style.height(100.dp).width(100.dp).viewTag("test_view").onClick { state.updateSync("world") }) } } val view = lithoViewRule.render(widthPx = exactly(100), heightPx = exactly(100)) { TestComponent() } assertThat(stateRef.get()).isEqualTo("hello") lithoViewRule.act(view) { clickOnTag("test_view") } assertThat(stateRef.get()).describedAs("String state is updated").isEqualTo("world") } @Test fun useState_reconciliation_stateIsUpdatedWithoutCallingRenderOnSibling() { val siblingRenderCount = AtomicInteger() class RootComponent : KComponent() { override fun ComponentScope.render(): Component? { return Row(style = Style.wrapInView()) { child(ClickableComponentWithState(tag = "test_view")) child(CountRendersComponent(renderCount = siblingRenderCount)) } } } val view = lithoViewRule.render(widthPx = exactly(100), heightPx = exactly(100)) { RootComponent() } assertThat(siblingRenderCount.get()).isEqualTo(1) lithoViewRule.act(view) { clickOnTag("test_view") } // Using viewTag because Text is currently a drawable and harder to access directly assertThat(view.findViewWithTagOrNull("Counter: 1")).isNotNull() // Assert that the state update didn't cause the sibling to re-render assertThat(siblingRenderCount.get()).isEqualTo(1) } /** * While it's not exactly desired that the parent needs render() called on it again, this test is * to detect unexpected changes in that behavior. */ @Test fun useState_reconciliation_renderCalledOnParentOfUpdatedComponent() { val siblingRenderCount = AtomicInteger() val parentRenderCount = AtomicInteger() class ParentOfComponentWithStateUpdate(private val renderCount: AtomicInteger) : KComponent() { override fun ComponentScope.render(): Component { renderCount.incrementAndGet() return ClickableComponentWithState(tag = "test_view") } } class RootComponent : KComponent() { override fun ComponentScope.render(): Component? { return Row(style = Style.wrapInView()) { child(ParentOfComponentWithStateUpdate(renderCount = parentRenderCount)) child(CountRendersComponent(renderCount = siblingRenderCount)) } } } val view = lithoViewRule.render(widthPx = exactly(100), heightPx = exactly(100)) { RootComponent() } assertThat(parentRenderCount.get()).isEqualTo(1) assertThat(siblingRenderCount.get()).isEqualTo(1) lithoViewRule.act(view) { clickOnTag("test_view") } // Assert that the state update still causes parent to re-render but not sibling assertThat(view.findViewWithTagOrNull("Counter: 1")).isNotNull() assertThat(parentRenderCount.get()).isEqualTo(2) assertThat(siblingRenderCount.get()).isEqualTo(1) } @Test fun `should throw exception when state updates are triggered too many times during layout`() { expectedException.expect(LithoMetadataExceptionWrapper::class.java) expectedException.expectMessage("State update loop during layout detected") class RootComponent : KComponent() { override fun ComponentScope.render(): Component { val state = useState { 0 } // unconditional state update state.updateSync { value -> value + 1 } return Row { child(Text(text = "hello world")) } } } lithoViewRule.render { RootComponent() } } @Test fun useState_updateState_stateIsUpdated_forMountable() { lateinit var stateRef: AtomicReference<String> class TestMountableComponent : MountableComponent() { override fun MountableComponentScope.render(): MountableRenderResult { val state = useState { "hello" } stateRef = AtomicReference(state.value) return MountableRenderResult( TestMountable(), style = Style.height(100.dp).width(100.dp).viewTag("test_view").onClick { state.update("world") }) } } val testLithoView = lithoViewRule.render { TestMountableComponent() } assertThat(stateRef.get()).isEqualTo("hello") lithoViewRule.act(testLithoView) { clickOnTag("test_view") } assertThat(stateRef.get()).describedAs("String state is updated").isEqualTo("world") } @Test fun useStateOnHooks_updateTwoStatesWithSamePropertyName_bothStatesAreUpdatedIndependently_forMountable() { lateinit var state1Ref: AtomicReference<State<String>> lateinit var state2Ref: AtomicReference<State<Int>> class TestMountableComponent : MountableComponent() { override fun MountableComponentScope.render(): MountableRenderResult { val state1 = useCustomState("hello") val state2 = useCustomState(20) state1Ref = AtomicReference(state1) state2Ref = AtomicReference(state2) return MountableRenderResult( TestMountable(), style = Style.height(100.dp).width(100.dp).viewTag("test_view").onClick { // The correct way to do this (at least until we have automatic batching) // would be to store these states in the same obj to trigger only one state // update state1.update("world") state2.update { value -> value + 1 } }) } } val testLithoView = lithoViewRule.render { TestMountableComponent() } assertThat(state1Ref.get().value).isEqualTo("hello") assertThat(state2Ref.get().value).isEqualTo(20) lithoViewRule.act(testLithoView) { clickOnTag("test_view") } assertThat(state1Ref.get().value).describedAs("String state is updated").isEqualTo("world") assertThat(state2Ref.get().value).describedAs("Int state is updated").isEqualTo(21) } @Test fun useState_calculateLayoutInTwoThreadsConcurrently_stateIsInitializedOnlyOnce_forMountable() { val initCounter = AtomicInteger(0) val countDownLatch = CountDownLatch(2) val firstCountDownLatch = CountDownLatch(1) val secondCountDownLatch = CountDownLatch(1) val view = lithoViewRule.createTestLithoView() val thread1 = Thread { view.setRootAndSizeSpecSync( CountDownLatchMountableComponent(firstCountDownLatch, secondCountDownLatch, initCounter), SizeSpec.makeSizeSpec(100, EXACTLY), SizeSpec.makeSizeSpec(100, EXACTLY)) countDownLatch.countDown() } val thread2 = Thread { firstCountDownLatch.await() view.setRootAndSizeSpecSync( CountDownLatchMountableComponent(secondCountDownLatch, null, initCounter), SizeSpec.makeSizeSpec(200, EXACTLY), SizeSpec.makeSizeSpec(200, EXACTLY)) countDownLatch.countDown() } thread1.start() thread2.start() countDownLatch.await() lithoViewRule.idle() assertThat(initCounter.get()).describedAs("initCounter is initialized only once").isEqualTo(1) val componentTree = view.componentTree assertThat(getStateHandler(componentTree)?.initialStateContainer?.mInitialStates) .describedAs("Initial hook state container is empty") .isEmpty() assertThat(getStateHandler(componentTree)?.initialStateContainer?.mPendingStateHandlers) .describedAs("No pending StateHandlers") .isEmpty() } @Test fun useState_counterIncrementedTwiceBeforeStateCommit_bothIncrementsAreApplied_forMountable() { class TestMountableComponent : MountableComponent() { override fun MountableComponentScope.render(): MountableRenderResult { val counter = useState { 0 } return MountableRenderResult( TestTextMountable( text = "Counter: ${counter.value}", tag = "Counter: ${counter.value}"), style = Style.viewTag("test_view").onClick { counter.update { value -> value + 1 } }) } } val view = lithoViewRule.render(widthPx = exactly(100), heightPx = exactly(100)) { TestMountableComponent() } lithoViewRule.act(view) { clickOnTag("test_view") clickOnTag("test_view") } assertThat(view.findViewWithTagOrNull("Counter: 2")).isNotNull() } @Test fun useState_synchronousUpdate_stateIsUpdatedSynchronously_forMountable() { lateinit var stateRef: AtomicReference<String> class TestMountableComponent : MountableComponent() { override fun MountableComponentScope.render(): MountableRenderResult { val state = useState { "hello" } stateRef = AtomicReference(state.value) return MountableRenderResult( TestMountable(), style = Style.height(100.dp).width(100.dp).viewTag("test_view").onClick { state.updateSync("world") }) } } val view = lithoViewRule.render(widthPx = exactly(100), heightPx = exactly(100)) { TestMountableComponent() } assertThat(stateRef.get()).isEqualTo("hello") lithoViewRule.act(view) { clickOnTag("test_view") } assertThat(stateRef.get()).describedAs("String state is updated").isEqualTo("world") } @Test fun useState_reconciliation_stateIsUpdatedWithoutCallingRenderOnSibling_forMountable() { val siblingRenderCount = AtomicInteger() class RootComponent : KComponent() { override fun ComponentScope.render(): Component? { return Row(style = Style.wrapInView()) { child(ClickableMountableComponentWithState(tag = "test_view")) child(CountRendersMountableComponent(renderCount = siblingRenderCount)) } } } val view = lithoViewRule.render(widthPx = exactly(100), heightPx = exactly(100)) { RootComponent() } assertThat(siblingRenderCount.get()).isEqualTo(1) lithoViewRule.act(view) { clickOnTag("test_view") } // Using viewTag because Text is currently a drawable and harder to access directly assertThat(view.findViewWithTagOrNull("Counter: 1")).isNotNull() // Assert that the state update didn't cause the sibling to re-render assertThat(siblingRenderCount.get()).isEqualTo(1) } /** * While it's not exactly desired that the parent needs render() called on it again, this test is * to detect unexpected changes in that behavior. */ @Test fun useState_reconciliation_renderCalledOnParentOfUpdatedComponent_forMountable() { val siblingRenderCount = AtomicInteger() val parentRenderCount = AtomicInteger() class ParentOfComponentWithStateUpdate(private val renderCount: AtomicInteger) : KComponent() { override fun ComponentScope.render(): Component { renderCount.incrementAndGet() return ClickableMountableComponentWithState(tag = "test_view") } } class RootComponent : KComponent() { override fun ComponentScope.render(): Component? { return Row(style = Style.wrapInView()) { child(ParentOfComponentWithStateUpdate(renderCount = parentRenderCount)) child(CountRendersMountableComponent(renderCount = siblingRenderCount)) } } } val view = lithoViewRule.render(widthPx = exactly(100), heightPx = exactly(100)) { RootComponent() } assertThat(parentRenderCount.get()).isEqualTo(1) assertThat(siblingRenderCount.get()).isEqualTo(1) lithoViewRule.act(view) { clickOnTag("test_view") } // Assert that the state update still causes parent to re-render but not sibling assertThat(view.findViewWithText("Counter: 1")).isNotNull() assertThat(parentRenderCount.get()).isEqualTo(2) assertThat(siblingRenderCount.get()).isEqualTo(1) } @Test fun `should throw exception when state updates are triggered too many times during layout for Mountable`() { expectedException.expect(LithoMetadataExceptionWrapper::class.java) expectedException.expectMessage("State update loop during layout detected") class RootComponent : MountableComponent() { override fun MountableComponentScope.render(): MountableRenderResult { val state = useState { 0 } // unconditional state update state.updateSync { value -> value + 1 } return MountableRenderResult(TestTextMountable(text = "hello world"), null) } } lithoViewRule.render { RootComponent() } } private class CountDownLatchComponent( val countDownLatch: CountDownLatch, val awaitable: CountDownLatch?, val initCounter: AtomicInteger ) : KComponent() { override fun ComponentScope.render(): Component? { countDownLatch.countDown() awaitable?.await() val state = useState { initCounter.incrementAndGet() } return Text("stateValue is ${state.value}") } } class ClickableComponentWithState(private val tag: String) : KComponent() { override fun ComponentScope.render(): Component? { val counter = useState { 0 } return Row(style = Style.viewTag(tag).onClick { counter.updateSync { value -> value + 1 } }) { child( Text( style = Style.viewTag("Counter: ${counter.value}"), text = "Counter: ${counter.value}")) } } } private class CountRendersComponent(private val renderCount: AtomicInteger) : KComponent() { override fun ComponentScope.render(): Component? { renderCount.incrementAndGet() return Row(style = Style.width(100.px).height(100.px)) } } private class CountDownLatchMountableComponent( val countDownLatch: CountDownLatch, val awaitable: CountDownLatch?, val initCounter: AtomicInteger ) : MountableComponent() { override fun MountableComponentScope.render(): MountableRenderResult { countDownLatch.countDown() awaitable?.await() val state = useState { initCounter.incrementAndGet() } return MountableRenderResult(TestTextMountable(text = "stateValue is ${state.value}"), null) } } class ClickableMountableComponentWithState(private val tag: String) : MountableComponent() { override fun MountableComponentScope.render(): MountableRenderResult { val counter = useState { 0 } return MountableRenderResult( TestTextMountable(text = "Counter: ${counter.value}", tag = "Counter: ${counter.value}"), style = Style.viewTag(tag).contentDescription(tag).onClick { counter.updateSync { value -> value + 1 } }) } } private class CountRendersMountableComponent(private val renderCount: AtomicInteger) : MountableComponent() { override fun MountableComponentScope.render(): MountableRenderResult { renderCount.incrementAndGet() return MountableRenderResult(TestMountable(), style = Style.width(100.px).height(100.px)) } } }
apache-2.0
c624b94c4480c70f4c90ca050950655d
34.376835
110
0.684589
4.668676
false
true
false
false
sensefly-sa/dynamodb-to-s3
src/test/kotlin/io/sensefly/dynamodbtos3/config/TestConfig.kt
1
1934
package io.sensefly.dynamodbtos3.config import com.amazonaws.auth.AWSStaticCredentialsProvider import com.amazonaws.auth.AnonymousAWSCredentials import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration import com.amazonaws.services.dynamodbv2.AmazonDynamoDB import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded import com.amazonaws.services.dynamodbv2.local.shared.access.AmazonDynamoDBLocal import com.amazonaws.services.s3.AmazonS3 import com.amazonaws.services.s3.AmazonS3ClientBuilder import io.findify.s3mock.S3Mock import io.sensefly.dynamodbtos3.Application import org.slf4j.LoggerFactory import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Import @Configuration @Import(Application::class) class TestConfig { private val log = LoggerFactory.getLogger(javaClass) private val s3MockPort = 54879 @Bean(destroyMethod = "shutdown") fun embeddedAmazonDynamoDB(): AmazonDynamoDBLocal { log.debug("java.library.path: {}", System.getProperty("java.library.path")) return DynamoDBEmbedded.create() } @Bean fun amazonDynamoDB(dynamoDBLocal: AmazonDynamoDBLocal): AmazonDynamoDB { return dynamoDBLocal.amazonDynamoDB() } @Bean(destroyMethod = "stop") fun s3Mock(): S3Mock { val s3Mock = S3Mock.Builder() .withPort(s3MockPort) .withInMemoryBackend() .build() s3Mock.start() return s3Mock } @Bean fun amazonS3(s3Mock: S3Mock): AmazonS3 { val endPoint = "http://localhost:$s3MockPort" log.info("Configure S3 mock on {}", endPoint) return AmazonS3ClientBuilder.standard() .withPathStyleAccessEnabled(true) .withEndpointConfiguration(EndpointConfiguration(endPoint, "eu-central-1")) .withCredentials(AWSStaticCredentialsProvider(AnonymousAWSCredentials())) .build() } }
bsd-3-clause
77332f231b17f0be1b1093238ca2867a
31.779661
83
0.777663
4.054507
false
true
false
false
icarumbas/bagel
core/src/ru/icarumbas/bagel/view/renderer/systems/RenderingSystem.kt
1
2575
package ru.icarumbas.bagel.view.renderer.systems import com.badlogic.ashley.core.Entity import com.badlogic.ashley.core.Family import com.badlogic.ashley.systems.SortedIteratingSystem import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.g2d.Batch import ru.icarumbas.bagel.engine.components.other.RoomIdComponent import ru.icarumbas.bagel.engine.components.physics.StaticComponent import ru.icarumbas.bagel.engine.world.PIX_PER_M import ru.icarumbas.bagel.engine.world.RoomWorld import ru.icarumbas.bagel.utils.* import ru.icarumbas.bagel.view.renderer.RenderingComparator import ru.icarumbas.bagel.view.renderer.components.AlwaysRenderingMarkerComponent import ru.icarumbas.bagel.view.renderer.components.SizeComponent import ru.icarumbas.bagel.view.renderer.components.TextureComponent import ru.icarumbas.bagel.view.renderer.components.TranslateComponent class RenderingSystem( private val rm: RoomWorld, private val batch: Batch ) : SortedIteratingSystem(Family.all(SizeComponent::class.java, TranslateComponent::class.java, TextureComponent::class.java) .one(AlwaysRenderingMarkerComponent::class.java, RoomIdComponent::class.java,StaticComponent::class.java).get(), RenderingComparator()) { private val entities = ArrayList<Entity>() private fun draw(e: Entity){ batch.draw( texture[e].tex, translate[e].x, translate[e].y, size[e].spriteSize.x / 2, size[e].spriteSize.y / 2, size[e].spriteSize.x, size[e].spriteSize.y, 1f, 1f, translate[e].angle ) } override fun update(deltaTime: Float) { super.update(deltaTime) entities.filter { it.inView(rm) && !(body.has(it) && !body[it].body.isActive) && texture[it].tex != null }.forEach { size[it].spriteSize.y = texture[it].tex!!.regionHeight / PIX_PER_M * size[it].scale size[it].spriteSize.x = texture[it].tex!!.regionWidth / PIX_PER_M * size[it].scale batch.color = texture[it].color batch.begin() draw(it) if (shader.has(it)) { batch.shader = shader[it].shaderProgram draw(it) batch.shader = null } batch.end() batch.color = Color.WHITE } entities.clear() } override fun processEntity(e: Entity, deltaTime: Float) { entities.add(e) } }
apache-2.0
ec649ba8dc6f1576a398bbf0a1fc2fbe
30.802469
124
0.646602
4.029734
false
false
false
false
OurFriendIrony/MediaNotifier
app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/mediaitem/tv/TVShow.kt
1
3144
package uk.co.ourfriendirony.medianotifier.mediaitem.tv import android.database.Cursor import android.util.Log import uk.co.ourfriendirony.medianotifier.clients.tmdb.tvshow.get.TVShowGet import uk.co.ourfriendirony.medianotifier.clients.tmdb.tvshow.search.TVShowSearchResult import uk.co.ourfriendirony.medianotifier.db.tv.TVShowDatabaseDefinition import uk.co.ourfriendirony.medianotifier.general.Helper.getColumnValue import uk.co.ourfriendirony.medianotifier.general.Helper.stringToDate import uk.co.ourfriendirony.medianotifier.mediaitem.MediaItem import java.text.SimpleDateFormat import java.util.* class TVShow : MediaItem { override val id: String override val title: String? override val releaseDate: Date? // TODO: fully implement played as an item override val played = false private var subid = "" override var subtitle = "" override var description: String? = "" private set override var externalLink: String? = null private set override var children: List<MediaItem> = ArrayList() constructor(tvShow: TVShowGet) { id = tvShow.id.toString() title = tvShow.name description = tvShow.overview releaseDate = tvShow.firstAirDate if (tvShow.externalIds != null && tvShow.externalIds!!.imdbId != null) { externalLink = IMDB_URL + tvShow.externalIds!!.imdbId } Log.d("[API GET]", this.toString()) } constructor(item: TVShowSearchResult) { id = item.id.toString() title = item.name description = item.overview releaseDate = item.firstAirDate Log.d("[API SEARCH]", this.toString()) } @JvmOverloads constructor(cursor: Cursor?, episodes: List<MediaItem> = ArrayList()) { id = getColumnValue(cursor!!, TVShowDatabaseDefinition.ID) subid = getColumnValue(cursor, TVShowDatabaseDefinition.SUBID) title = getColumnValue(cursor, TVShowDatabaseDefinition.TITLE) subtitle = getColumnValue(cursor, TVShowDatabaseDefinition.SUBTITLE) description = getColumnValue(cursor, TVShowDatabaseDefinition.DESCRIPTION) releaseDate = stringToDate(getColumnValue(cursor, TVShowDatabaseDefinition.RELEASE_DATE)) externalLink = getColumnValue(cursor, TVShowDatabaseDefinition.EXTERNAL_URL) children = episodes Log.d("[DB READ]", this.toString()) } override val subId: String get() = subid override val releaseDateFull: String get() = if (releaseDate != null) { SimpleDateFormat("dd/MM/yyyy", Locale.UK).format(releaseDate) } else MediaItem.NO_DATE override val releaseDateYear: String get() = if (releaseDate != null) { SimpleDateFormat("yyyy", Locale.UK).format(releaseDate) } else MediaItem.NO_DATE override fun countChildren(): Int { return children.size } override fun toString(): String { return "TVShow: " + title + " > " + releaseDateFull + " > Episodes " + countChildren() } companion object { private const val IMDB_URL = "http://www.imdb.com/title/" } }
apache-2.0
8c32d3ceb023786ac30161072153dc68
35.569767
97
0.688931
4.596491
false
false
false
false
cubex2/ObsidianAnimator
API/src/main/java/obsidianAPI/io/AnimationFileLoader.kt
1
1615
package obsidianAPI.io import net.minecraft.nbt.CompressedStreamTools import net.minecraft.nbt.NBTTagCompound import obsidianAPI.animation.AnimationPart import obsidianAPI.animation.AnimationSequence import obsidianAPI.render.ModelObj import java.io.File import java.io.FileInputStream import java.io.InputStream object AnimationFileLoader { fun load(file: File, model: ModelObj? = null): AnimationSequence { return load(FileInputStream(file), model) } fun load(inputStream: InputStream, model: ModelObj? = null): AnimationSequence { return load(CompressedStreamTools.readCompressed(inputStream), model) } fun load(nbt: NBTTagCompound, model: ModelObj? = null): AnimationSequence { val sequence = AnimationSequence(nbt) model?.let { fixAnimationPartNames(sequence, it) } return sequence } fun fixAnimationPartNames(sequence: AnimationSequence, model: ModelObj) { val animationParts = sequence.animationList sequence.clearAnimations() for (animationPart in animationParts) { val part = model.getPartFromName(animationPart.partName) val newAnimationPart = if (part != null) AnimationPart( animationPart.startTime, animationPart.endTime, animationPart.startPosition, animationPart.endPosition, part ) else animationPart sequence.addAnimation(newAnimationPart) } } }
gpl-3.0
aad88f5221b5c232b057b23d9d80e178
28.381818
82
0.64644
4.969231
false
false
false
false
mrkirby153/KirBot
src/main/kotlin/me/mrkirby153/KirBot/command/executors/moderation/CommandArchive.kt
1
3808
package me.mrkirby153.KirBot.command.executors.moderation import com.mrkirby153.bfs.query.DB import com.mrkirby153.bfs.query.DbRow import me.mrkirby153.KirBot.command.annotations.CommandDescription import me.mrkirby153.KirBot.command.CommandCategory import me.mrkirby153.KirBot.command.CommandException import me.mrkirby153.KirBot.command.annotations.Command import me.mrkirby153.KirBot.command.annotations.IgnoreWhitelist import me.mrkirby153.KirBot.command.args.CommandContext import me.mrkirby153.KirBot.database.models.guild.GuildMessage import me.mrkirby153.KirBot.logger.LogManager import me.mrkirby153.KirBot.user.CLEARANCE_MOD import me.mrkirby153.KirBot.utils.Context import me.mrkirby153.KirBot.utils.convertSnowflake import me.mrkirby153.KirBot.utils.uploadToArchive import java.text.SimpleDateFormat class CommandArchive{ @Command(name = "user", clearance = CLEARANCE_MOD, arguments = ["<user:snowflake>", "[amount:int]"], category = CommandCategory.MODERATION, parent = "archive") @CommandDescription("Create an archive of messages that a user has sent") @IgnoreWhitelist fun archiveUser(context: Context, cmdContext: CommandContext) { val amount = cmdContext.get<Int>("amount") ?: 50 val user = cmdContext.get<String>("user")!! val messages = DB.raw( "SELECT * FROM server_messages WHERE author = ? AND server_id = ? ORDER BY id DESC LIMIT ?", user, context.guild.id, amount).map { decode(it) }.reversed() val archiveUrl = createArchive(messages) context.channel.sendMessage("Archived ${messages.count()} messages at $archiveUrl").queue() } @Command(name = "channel", clearance = CLEARANCE_MOD, arguments = ["<channel:snowflake>", "[amount:int]"], category = CommandCategory.MODERATION, parent = "archive") @CommandDescription("Creates an archive of messages sent in a channel") @IgnoreWhitelist fun archiveChannel(context: Context, cmdContext: CommandContext) { val amount = cmdContext.get<Int>("amount") ?: 50 val chan = cmdContext.get<String>("channel")!! if(context.guild.getTextChannelById(chan) == null) throw CommandException("That channel doesn't exist") val messages = DB.raw( "SELECT * FROM server_messages WHERE channel = ? ORDER BY id DESC LIMIT ?", chan, amount).map { decode(it) }.reversed() val archiveUrl = createArchive(messages) context.channel.sendMessage("Archived ${messages.count()} messages at $archiveUrl").queue() } private fun createArchive(messages: Collection<GuildMessage>): String { val msgs = mutableListOf<String>() val userIds = messages.map { it.author }.toSet() val userMap = mutableMapOf<String, String>() if (userIds.isNotEmpty()) { val results = DB.raw( "SELECT id, username, discriminator FROM seen_users WHERE id IN (${userIds.joinToString( ", ")})") results.forEach { userMap[it.getString("id")] = "${it.getString("username")}#${it.getInt( "discriminator")}" } } messages.forEach { val timeFormatted = SimpleDateFormat("YYY-MM-dd HH:MM:ss").format( convertSnowflake(it.id)) msgs.add(String.format("%s (%s / %s / %s) %s: %s (%s)", timeFormatted, it.serverId, it.channel, it.author, userMap[it.author] ?: it.author, it.message, it.attachments ?: "")) } return uploadToArchive(LogManager.encrypt(msgs.joinToString("\n"))) } private fun decode(row: DbRow): GuildMessage { val msg = GuildMessage() msg.hydrate(row) return msg } }
mit
fcf0cb2397f0dde4fb91d626c1c1fca5
46.024691
123
0.661239
4.347032
false
false
false
false
dya-tel/TSU-Schedule
src/main/kotlin/ru/dyatel/tsuschedule/database/DatabaseManager.kt
1
1663
package ru.dyatel.tsuschedule.database import android.app.Activity import android.content.Context import android.database.sqlite.SQLiteDatabase import org.jetbrains.anko.db.ManagedSQLiteOpenHelper import ru.dyatel.tsuschedule.ScheduleApplication private const val DB_FILE = "data.db" private const val DB_VERSION = 7 class DatabaseManager(context: Context) : ManagedSQLiteOpenHelper(context, DB_FILE, version = DB_VERSION) { val changelogs = ChangelogDao(this) @Deprecated("Use snapshots") @Suppress("deprecation") val oldSchedule = UnfilteredGroupScheduleDao(context, this) val snapshots = ScheduleSnapshotDao(context, this) val filters = FilterDao(context, this) val rawGroupSchedule = RawGroupScheduleDao(context, this) val filteredGroupSchedule = FilteredGroupScheduleDao(context, this) val teachers = TeacherDao(this) val teacherSchedule = TeacherScheduleDao(this) val exams = ExamScheduleDao(this) @Suppress("deprecation") private val parts = setOf( changelogs, oldSchedule, filters, snapshots, rawGroupSchedule, filteredGroupSchedule, teachers, teacherSchedule, exams) override fun onConfigure(db: SQLiteDatabase) { db.setForeignKeyConstraintsEnabled(true) } override fun onCreate(db: SQLiteDatabase) { parts.forEach { it.createTables(db) } } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { parts.forEach { it.upgradeTables(db, oldVersion, newVersion) } } } val Activity.database get() = (application as ScheduleApplication).database
mit
7d5f687af3f2e1607cd993a550c97712
29.236364
107
0.721587
4.47043
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/ext/RsImplItem.kt
1
2354
/* * 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.lang.ASTNode import com.intellij.navigation.ItemPresentation import com.intellij.psi.stubs.IStubElementType import com.intellij.psi.util.PsiTreeUtil import org.rust.ide.icons.RsIcons import org.rust.ide.presentation.getPresentation import org.rust.lang.core.psi.* import org.rust.lang.core.stubs.RsImplItemStub import org.rust.lang.core.types.BoundElement import org.rust.lang.core.types.RsPsiTypeImplUtil import org.rust.lang.core.types.ty.Ty import org.rust.lang.core.types.ty.TyTypeParameter abstract class RsImplItemImplMixin : RsStubbedElementImpl<RsImplItemStub>, RsImplItem { constructor(node: ASTNode) : super(node) constructor(stub: RsImplItemStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType) override fun getIcon(flags: Int) = RsIcons.IMPL override val isPublic: Boolean get() = false // pub does not affect imls at all override fun getPresentation(): ItemPresentation = getPresentation(this) override val implementedTrait: BoundElement<RsTraitItem>? get() { val (trait, subst) = traitRef?.resolveToBoundTrait ?: return null val aliases = members?.typeAliasList.orEmpty().mapNotNull { typeAlias -> trait.members?.typeAliasList.orEmpty() .find { it.name == typeAlias.name } ?.let { TyTypeParameter.associated(it) to typeAlias.declaredType } }.toMap() return BoundElement(trait, subst + aliases) } override val innerAttrList: List<RsInnerAttr> get() = PsiTreeUtil.getStubChildrenOfTypeAsList(this, RsInnerAttr::class.java) override val outerAttrList: List<RsOuterAttr> get() = PsiTreeUtil.getStubChildrenOfTypeAsList(this, RsOuterAttr::class.java) override val associatedTypesTransitively: Collection<RsTypeAlias> get() { val implAliases = members?.typeAliasList.orEmpty() val traitAliases = implementedTrait?.associatedTypesTransitively ?: emptyList() return implAliases + traitAliases.filter { trAl -> implAliases.find { it.name == trAl.name } == null } } override val declaredType: Ty get() = RsPsiTypeImplUtil.declaredType(this) override val isUnsafe: Boolean get() = unsafe != null }
mit
c53d86a29715daddb49a2fae2e183164
40.298246
110
0.734494
4.319266
false
false
false
false
Kennyc1012/TextDrawable
library/src/main/java/com/kennyc/textdrawable/TextDrawableBuilder.kt
1
4526
package com.kennyc.textdrawable import android.graphics.Bitmap import android.graphics.Color import android.graphics.Typeface import androidx.annotation.ColorInt class TextDrawableBuilder(@TextDrawable.DrawableShape private var shape: Int = TextDrawable.DRAWABLE_SHAPE_RECT) { constructor(shape: Int = TextDrawable.DRAWABLE_SHAPE_RECT, text: String) : this(shape) { this.text = text } constructor(shape: Int = TextDrawable.DRAWABLE_SHAPE_RECT, icon: Bitmap) : this(shape) { this.icon = icon } private var text: String? = null private var color = Color.GRAY private var borderThickness = 0f private var desiredHeight = -1 private var desiredWidth = -1 private var typeFace = Typeface.DEFAULT private var textColor = Color.WHITE private var textSize = 0f private var cornerRadius: Float = 0f private var icon: Bitmap? = null private var borderColor = color /** * Sets the width of the drawable * * @param width * @return */ fun setWidth(width: Int): TextDrawableBuilder { this.desiredWidth = width return this } /** * Sets the height of the drawable * * @param height * @return */ fun setHeight(height: Int): TextDrawableBuilder { this.desiredHeight = height return this } /** * Sets the text color to be used for the drawable. Will be ignored if [.setIcon] is called * * @param color * @return */ fun setTextColor(@ColorInt color: Int): TextDrawableBuilder { this.textColor = color return this } /** * Sets the border thickness for the drawable. Defaults to 0 * * @param thickness * @return */ fun setBorderThickness(thickness: Float): TextDrawableBuilder { this.borderThickness = thickness return this } /** * Sets the typeface for the drawable * * @param tf * @return */ fun setTypeface(tf: Typeface): TextDrawableBuilder { this.typeFace = tf return this } /** * Sets the text size of the drawable. Will be ignored if [.setIcon] is called * * @param size * @return */ fun setTextSize(size: Float): TextDrawableBuilder { this.textSize = size return this } /** * Sets the [com.kennyc.textdrawable.TextDrawable.DrawableShape] to be used for the drawable * * @param shape * @return */ fun setShape(@TextDrawable.DrawableShape shape: Int): TextDrawableBuilder { this.shape = shape return this } /** * Sets the corner radius for the drawable. Will be ignored unless the [com.kennyc.textdrawable.TextDrawable.DrawableShape] is * SHAPE_ROUND_RECT * * @param cornerRadius * @return */ fun setCornerRadius(cornerRadius: Float): TextDrawableBuilder { this.cornerRadius = cornerRadius return this } /** * Sets the icon to be used for the drawable * * @param bitmap * @return */ fun setIcon(bitmap: Bitmap): TextDrawableBuilder { this.text = null this.icon = bitmap return this } /** * Sets the text to be used for the drawable. * * @param text * @return */ fun setText(text: String): TextDrawableBuilder { this.icon = null this.text = text return this } /** * Sets the color of the drawable * * @param color * @return */ fun setColor(@ColorInt color: Int): TextDrawableBuilder { this.color = color return this } /** * Sets the color of the border * @param color * @return */ fun setBorderColor(@ColorInt color: Int): TextDrawableBuilder { this.borderColor = color return this } /** * Returns the [TextDrawable] * * @return */ fun build(): TextDrawable { return TextDrawable(shape = shape, color = color, textColor = textColor, cornerRadius = cornerRadius, textSize = textSize, desiredHeight = desiredHeight, desiredWidth = desiredWidth, borderThickness = borderThickness, borderColor = borderColor, typeFace = typeFace, text = text, icon = icon) } }
mit
42b7c55e3a225ac7bf7515b5484d1ddc
23.603261
130
0.58418
4.754202
false
false
false
false
geckour/Egret
app/src/main/java/com/geckour/egret/view/fragment/HashTagMuteFragment.kt
1
5248
package com.geckour.egret.view.fragment import android.databinding.DataBindingUtil import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.geckour.egret.App.Companion.gson import com.geckour.egret.R import com.geckour.egret.databinding.FragmentMuteHashTagBinding import com.geckour.egret.model.MuteHashTag import com.geckour.egret.util.Common import com.geckour.egret.util.OrmaProvider import com.geckour.egret.view.activity.MainActivity import com.geckour.egret.view.adapter.MuteHashTagAdapter import com.google.gson.reflect.TypeToken import io.reactivex.Observable import io.reactivex.Single import io.reactivex.schedulers.Schedulers import timber.log.Timber class HashTagMuteFragment: BaseFragment() { lateinit private var binding: FragmentMuteHashTagBinding private val adapter: MuteHashTagAdapter by lazy { MuteHashTagAdapter() } private val preItems: ArrayList<MuteHashTag> = ArrayList() private val argItems: ArrayList<String> = ArrayList() companion object { val TAG: String = this::class.java.simpleName val ARGS_KEY_DEFAULT_HASH_TAG = "defaultHashTag" fun newInstance(defaultHashTags: List<String> = ArrayList()): HashTagMuteFragment { val fragment = HashTagMuteFragment() val args = Bundle() if (defaultHashTags.isNotEmpty()) args.putString(ARGS_KEY_DEFAULT_HASH_TAG, gson.toJson(defaultHashTags)) fragment.arguments = args return fragment } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_mute_hash_tag, container, false) binding.defaultHashTag = if (arguments.containsKey(ARGS_KEY_DEFAULT_HASH_TAG)) { val tagsJson = arguments.getString(ARGS_KEY_DEFAULT_HASH_TAG, "") val type = object: TypeToken<List<String>>() {}.type val tags: List<String> = gson.fromJson(tagsJson, type) argItems.addAll(tags) if (tags.size == 1) tags.first() else "" } else "" binding.buttonAdd.setOnClickListener { val hashTag = binding.editTextAddMuteHashTag.text.toString() addHashTag(hashTag) } return binding.root } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.editTextAddMuteHashTag.requestFocusFromTouch() binding.editTextAddMuteHashTag.requestFocus() val hashTag = binding.editTextAddMuteHashTag.text.toString() binding.editTextAddMuteHashTag.setSelection(hashTag.length) val helper = Common.getSwipeToDismissTouchHelperForMuteHashTag(adapter) helper.attachToRecyclerView(binding.recyclerView) binding.recyclerView.addItemDecoration(helper) binding.recyclerView.adapter = adapter } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) bindSavedKeywords() } override fun onResume() { super.onResume() if (activity is MainActivity) ((activity as MainActivity).findViewById(R.id.fab) as FloatingActionButton?)?.hide() } override fun onPause() { super.onPause() manageHashTags() } fun bindSavedKeywords() { adapter.clearItems() preItems.clear() val items = OrmaProvider.db.selectFromMuteHashTag().toList() adapter.addAllItems(items) preItems.addAll(items) bindArgItems() } fun bindArgItems() { if (argItems.size > 1) adapter.addAllItems(argItems.map { MuteHashTag(hashTag = it) }) } fun addHashTag(hashTag: String) { if (TextUtils.isEmpty(hashTag)) return adapter.addItem(MuteHashTag(hashTag = hashTag)) binding.editTextAddMuteHashTag.setText("") } fun manageHashTags() { val items = adapter.getItems() removeHashTags(items) .subscribeOn(Schedulers.newThread()) .subscribe({ registerHashTags(items) }, Throwable::printStackTrace) } fun removeHashTags(items: List<MuteHashTag>): Single<Int> { val shouldRemoveItems = preItems.filter { items.none { item -> it.id == item.id } } var where = "(`id` = ?)" for (i in 1..shouldRemoveItems.lastIndex) where += " OR (`id` = ?)" return OrmaProvider.db.deleteFromMuteHashTag().where(where, *shouldRemoveItems.map { it.id }.toTypedArray()).executeAsSingle() } fun registerHashTags(items: List<MuteHashTag>) { Observable.fromIterable(items) .subscribeOn(Schedulers.newThread()) .map { OrmaProvider.db.relationOfMuteHashTag().upsert(it) } .subscribe({ Timber.d("updated mute hashTag: ${it.hashTag}") }, Throwable::printStackTrace) } }
gpl-3.0
3d632c65a6bc4434af77ac3fbb6f4b9e
36.492857
134
0.683308
4.45123
false
false
false
false
msebire/intellij-community
platform/testGuiFramework/src/org/fest/swing/core/SmartWaitRobot.kt
1
14794
/* * 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 org.fest.swing.core import com.intellij.testGuiFramework.util.step import com.intellij.util.ConcurrencyUtil import com.intellij.util.ui.EdtInvocationManager import org.fest.swing.awt.AWT import org.fest.swing.edt.GuiActionRunner import org.fest.swing.edt.GuiQuery import org.fest.swing.hierarchy.ComponentHierarchy import org.fest.swing.keystroke.KeyStrokeMap import org.fest.swing.timing.Pause.pause import org.fest.swing.util.Modifiers import java.awt.* import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import javax.swing.JPopupMenu import javax.swing.KeyStroke import javax.swing.SwingUtilities class SmartWaitRobot : Robot { override fun moveMouse(component: Component) { basicRobot.moveMouse(component) } override fun moveMouse(component: Component, point: Point) { basicRobot.moveMouse(component, point) } override fun moveMouse(point: Point) { basicRobot.moveMouse(point) } override fun click(component: Component) { step("click at component ${component.loggedOutput()}") { basicRobot.click(component) } } override fun click(component: Component, mouseButton: MouseButton) { step("click at component ${component.loggedOutput()}, $mouseButton") { basicRobot.click(component, mouseButton) } } override fun click(component: Component, mouseButton: MouseButton, counts: Int) { step("click at component ${component.loggedOutput()}, $mouseButton $counts times") { basicRobot.click(component, mouseButton, counts) } } override fun click(component: Component, point: Point) { step("click at component ${component.loggedOutput()} at point ${point.loggedOutput()}") { basicRobot.click(component, point) } } override fun showWindow(window: Window) { basicRobot.showWindow(window) } override fun showWindow(window: Window, dimension: Dimension) { basicRobot.showWindow(window, dimension) } override fun showWindow(window: Window, dimension: Dimension?, p2: Boolean) { basicRobot.showWindow(window, dimension, p2) } override fun isActive(): Boolean = basicRobot.isActive override fun pressAndReleaseKey(p0: Int, vararg p1: Int) { basicRobot.pressAndReleaseKey(p0, *p1) } override fun showPopupMenu(component: Component): JPopupMenu = step("show popup menu at component ${component.loggedOutput()}") { basicRobot.showPopupMenu(component) } override fun showPopupMenu(component: Component, point: Point): JPopupMenu = step("show popup menu at component ${component.loggedOutput()} at point ${point.loggedOutput()}") { basicRobot.showPopupMenu(component, point) } override fun jitter(component: Component) { step("jitter on component ${component.loggedOutput()}") { basicRobot.jitter(component) } } override fun jitter(component: Component, point: Point) { step("jitter on component ${component.loggedOutput()} at point ${point.loggedOutput()}") { basicRobot.jitter(component, point) } } override fun pressModifiers(p0: Int) { step("press modifiers $p0") { basicRobot.pressModifiers(p0) } } override fun pressMouse(mouseButton: MouseButton) { step("press $mouseButton of mouse") { basicRobot.pressMouse(mouseButton) } } override fun pressMouse(component: Component, point: Point) { step("press mouse on component ${component.loggedOutput()} at point ${point.loggedOutput()}") { basicRobot.pressMouse(component, point) } } override fun pressMouse(component: Component, point: Point, mouseButton: MouseButton) { step("press $mouseButton of mouse on component ${component.loggedOutput()} at point ${point.loggedOutput()}") { basicRobot.pressMouse(component, point, mouseButton) } } override fun pressMouse(point: Point, mouseButton: MouseButton) { step("press $mouseButton of mouse at point ${point.loggedOutput()}") { basicRobot.pressMouse(point, mouseButton) } } override fun hierarchy(): ComponentHierarchy = basicRobot.hierarchy() override fun releaseKey(p0: Int) { step("release key $p0") { basicRobot.releaseKey(p0) } } override fun isDragging(): Boolean = basicRobot.isDragging override fun printer(): ComponentPrinter = basicRobot.printer() override fun type(char: Char) { basicRobot.type(char) } override fun type(char: Char, component: Component) { step("type char $char on component ${component.loggedOutput()}") { basicRobot.type(char, component) } } override fun requireNoJOptionPaneIsShowing() { basicRobot.requireNoJOptionPaneIsShowing() } override fun cleanUp() { basicRobot.cleanUp() } override fun releaseMouse(mouseButton: MouseButton) { step("release $mouseButton of mouse") { basicRobot.releaseMouse(mouseButton) } } override fun pressKey(p0: Int) { step("press key $p0") { basicRobot.pressKey(p0) } } override fun settings(): Settings = basicRobot.settings() override fun enterText(text: String) { step("enter text '$text'") { basicRobot.enterText(text) } } override fun enterText(text: String, component: Component) { step("enter text '$text' on component ${component.loggedOutput()}") { basicRobot.enterText(text, component) } } override fun releaseMouseButtons() { step("release mouse buttons (all?)") { basicRobot.releaseMouseButtons() } } override fun rightClick(component: Component) { step("right click on component ${component.loggedOutput()}") { basicRobot.rightClick(component) } } override fun focus(component: Component) { step("focus on component ${component.loggedOutput()}") { basicRobot.focus(component) } } override fun doubleClick(component: Component) { step("double click on component ${component.loggedOutput()}") { basicRobot.doubleClick(component) } } override fun cleanUpWithoutDisposingWindows() { basicRobot.cleanUpWithoutDisposingWindows() } override fun isReadyForInput(component: Component): Boolean = basicRobot.isReadyForInput(component) override fun focusAndWaitForFocusGain(component: Component) { step("focus and wait for it on component ${component.loggedOutput()}") { basicRobot.focusAndWaitForFocusGain(component) } } override fun releaseModifiers(p0: Int) { step("release modifiers $p0") { basicRobot.releaseModifiers(p0) } } override fun findActivePopupMenu(): JPopupMenu? = step("find active popup menu") { basicRobot.findActivePopupMenu() } override fun rotateMouseWheel(component: Component, p1: Int) { step("rotate mouse wheel on component ${component.loggedOutput()} on $p1") { basicRobot.rotateMouseWheel(component, p1) } } override fun rotateMouseWheel(p0: Int) { step("rotate mouse wheel on $p0") { basicRobot.rotateMouseWheel(p0) } } override fun pressAndReleaseKeys(vararg p0: Int) { step("press and release keys [${p0.joinToString()}]") { basicRobot.pressAndReleaseKeys(*p0) } } override fun finder(): ComponentFinder = basicRobot.finder() private val basicRobot: BasicRobot = BasicRobot.robotWithCurrentAwtHierarchyWithoutScreenLock() as BasicRobot init { settings().delayBetweenEvents(10) } private val waitConst = 30L private var myAwareClick: Boolean = false private val fastRobot: java.awt.Robot = java.awt.Robot() override fun waitForIdle() { step("wait for idle (robot)") { if (myAwareClick) { Thread.sleep(50) } else { pause(waitConst) if (!SwingUtilities.isEventDispatchThread()) EdtInvocationManager.getInstance().invokeAndWait({ }) } } } override fun close(w: Window) { basicRobot.close(w) basicRobot.waitForIdle() } //smooth mouse move override fun moveMouse(x: Int, y: Int) { step("move mouse to [$x, $y]") { val pauseConstMs = settings().delayBetweenEvents().toLong() val n = 20 val start = MouseInfo.getPointerInfo().location val dx = (x - start.x) / n.toDouble() val dy = (y - start.y) / n.toDouble() for (step in 1..n) { try { pause(pauseConstMs) } catch (e: InterruptedException) { e.printStackTrace() } basicRobot.moveMouse( (start.x + dx * ((Math.log(1.0 * step / n) - Math.log(1.0 / n)) * n / (0 - Math.log(1.0 / n)))).toInt(), (start.y + dy * ((Math.log(1.0 * step / n) - Math.log(1.0 / n)) * n / (0 - Math.log(1.0 / n)))).toInt()) } basicRobot.moveMouse(x, y) } } //smooth mouse move to component override fun moveMouse(c: Component, x: Int, y: Int) { step("move mouse on component ${c.loggedOutput()} to point [$x, $y]") { moveMouseWithAttempts(c, x, y) } } //smooth mouse move for find and click actions override fun click(c: Component, where: Point, button: MouseButton, times: Int) { step("click at component ${c.loggedOutput()}, $button $times times, at ${where.loggedOutput()}") { moveMouseAndClick(c, where, button, times) } } //we are replacing BasicRobot click with our click because the original one cannot handle double click rightly (BasicRobot creates unnecessary move event between click event which breaks clickCount from 2 to 1) override fun click(where: Point, button: MouseButton, times: Int) { step("click at ${where.loggedOutput()}, $button $times times") { moveMouseAndClick(null, where, button, times) } } private fun moveMouseAndClick(c: Component? = null, where: Point, button: MouseButton, times: Int) { if (c != null) moveMouse(c, where.x, where.y) else moveMouse(where.x, where.y) //pause between moving cursor and performing a click. pause(waitConst) myEdtAwareClick(button, times, where, c) } private fun moveMouseWithAttempts(c: Component, x: Int, y: Int, attempts: Int = 3) { if (attempts == 0) return waitFor { c.isShowing } val componentLocation: Point = requireNotNull(performOnEdt { AWT.translate(c, x, y) }) moveMouse(componentLocation.x, componentLocation.y) val componentLocationAfterMove: Point = requireNotNull(performOnEdt { AWT.translate(c, x, y) }) val mouseLocation = MouseInfo.getPointerInfo().location if (mouseLocation.x != componentLocationAfterMove.x || mouseLocation.y != componentLocationAfterMove.y) moveMouseWithAttempts(c, x, y, attempts - 1) } private fun myInnerClick(button: MouseButton, times: Int, point: Point, component: Component?) { step("click on component ${component?.loggedOutput()}, $button $times times at point ${point.loggedOutput()}") { if (component == null) basicRobot.click(point, button, times) else basicRobot.click(component, point, button, times) } } private fun waitFor(condition: () -> Boolean) { val timeout = 5000 //5 sec val cdl = CountDownLatch(1) val executor = ConcurrencyUtil.newSingleScheduledThreadExecutor("SmartWaitRobot").scheduleWithFixedDelay(Runnable { if (condition()) { cdl.countDown() } }, 0, 100, TimeUnit.MILLISECONDS) cdl.await(timeout.toLong(), TimeUnit.MILLISECONDS) executor.cancel(true) } fun fastPressAndReleaseKey(keyCode: Int, vararg modifiers: Int) { val unifiedModifiers = InputModifiers.unify(*modifiers) val updatedModifiers = Modifiers.updateModifierWithKeyCode(keyCode, unifiedModifiers) fastPressModifiers(updatedModifiers) if (updatedModifiers == unifiedModifiers) { fastPressKey(keyCode) fastReleaseKey(keyCode) } fastReleaseModifiers(updatedModifiers) } fun fastPressAndReleaseModifiers(vararg modifiers: Int) { val unifiedModifiers = InputModifiers.unify(*modifiers) fastPressModifiers(unifiedModifiers) pause(50) fastReleaseModifiers(unifiedModifiers) } fun fastPressAndReleaseKeyWithoutModifiers(keyCode: Int) { fastPressKey(keyCode) fastReleaseKey(keyCode) } fun shortcut(keyStoke: KeyStroke) { fastPressAndReleaseKey(keyStoke.keyCode, keyStoke.modifiers) } fun shortcutAndTypeString(keyStoke: KeyStroke, string: String, delayBetweenShortcutAndTypingMs: Int = 0) { fastPressAndReleaseKey(keyStoke.keyCode, keyStoke.modifiers) fastTyping(string, delayBetweenShortcutAndTypingMs) } fun fastTyping(string: String, delayBetweenShortcutAndTypingMs: Int = 0) { val keyCodeArray: IntArray = string .map { KeyStrokeMap.keyStrokeFor(it)?.keyCode ?: throw Exception("Unable to get keystroke for char '$it'") } .toIntArray() if (delayBetweenShortcutAndTypingMs > 0) pause(delayBetweenShortcutAndTypingMs.toLong()) keyCodeArray.forEach { fastPressAndReleaseKeyWithoutModifiers(keyCode = it); pause(50) } } private fun fastPressKey(keyCode: Int) { fastRobot.keyPress(keyCode) } private fun fastReleaseKey(keyCode: Int) { fastRobot.keyRelease(keyCode) } private fun fastPressModifiers(modifierMask: Int) { val keys = Modifiers.keysFor(modifierMask) val keysSize = keys.size (0 until keysSize) .map { keys[it] } .forEach { fastPressKey(it) } } private fun fastReleaseModifiers(modifierMask: Int) { val modifierKeys = Modifiers.keysFor(modifierMask) for (i in modifierKeys.indices.reversed()) fastReleaseKey(modifierKeys[i]) } private fun myEdtAwareClick(button: MouseButton, times: Int, point: Point, component: Component?) { awareClick { //TODO: remove mouse clicks from EDT // performOnEdt { myInnerClick(button, times, point, component) // } } waitForIdle() } private fun <T> performOnEdt(body: () -> T): T? = GuiActionRunner.execute(object : GuiQuery<T>() { override fun executeInEDT() = body.invoke() }) private fun awareClick(body: () -> Unit) { myAwareClick = true body.invoke() myAwareClick = false } } fun Component.loggedOutput(): String = "\"${javaClass.simpleName}, bounds [x=$x, y=$y, width=$width, height=$height]\"" fun Point.loggedOutput(): String = "[$x, $y]"
apache-2.0
14e76d1906f37414c47f77400d0afba4
30.748927
212
0.69393
4.017925
false
false
false
false
iMeePwni/LCExercise
src/main/kotlin/ArrayPairSum.kt
1
630
/** * Created by guofeng on 2017/6/20. * https://leetcode.com/problems/array-partition-i/#/description */ class ArrayPairSum { fun solution(numbs: IntArray): Int? { val size = numbs.size val n = size / 2 if (size !in 1..10000 || size % 2 != 0) return null numbs.sort() val numbs1 = mutableListOf<Int>() val numbs2 = mutableListOf<Int>() for (i in 0..size - 1 step 2) { numbs1.add(numbs[i]) numbs2.add(numbs[i + 1]) } val pairSum: Int = (0..n - 1).sumBy { Math.min(numbs1[it], numbs2[it]) } return pairSum } }
apache-2.0
1b0b07d42dc5558a1ebe9f0130737617
22.37037
80
0.536508
3.230769
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/servicelayer/PreferenceUpgradeService.kt
1
20930
/* * Copyright (c) 2021 David Allison <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.anki.servicelayer import android.content.Context import android.content.SharedPreferences import android.view.KeyEvent import androidx.annotation.VisibleForTesting import androidx.core.content.edit import androidx.core.net.toUri import com.ichi2.anki.AnkiDroidApp import com.ichi2.anki.cardviewer.Gesture import com.ichi2.anki.cardviewer.ViewerCommand import com.ichi2.anki.noteeditor.CustomToolbarButton import com.ichi2.anki.reviewer.Binding import com.ichi2.anki.reviewer.Binding.Companion.keyCode import com.ichi2.anki.reviewer.CardSide import com.ichi2.anki.reviewer.FullScreenMode import com.ichi2.anki.reviewer.MappableBinding import com.ichi2.anki.web.CustomSyncServer import com.ichi2.libanki.Consts import com.ichi2.themes.Themes import com.ichi2.utils.HashUtil.HashSetInit import timber.log.Timber private typealias VersionIdentifier = Int private typealias LegacyVersionIdentifier = Long object PreferenceUpgradeService { fun upgradePreferences(context: Context?, previousVersionCode: LegacyVersionIdentifier): Boolean = upgradePreferences(AnkiDroidApp.getSharedPrefs(context), previousVersionCode) /** @return Whether any preferences were upgraded */ internal fun upgradePreferences(preferences: SharedPreferences, previousVersionCode: LegacyVersionIdentifier): Boolean { val pendingPreferenceUpgrades = PreferenceUpgrade.getPendingUpgrades(preferences, previousVersionCode) pendingPreferenceUpgrades.forEach { it.performUpgrade(preferences) } return pendingPreferenceUpgrades.isNotEmpty() } /** * Specifies that no preference upgrades need to happen. * Typically because the app has been run for the first time, or the preferences * have been deleted */ @JvmStatic // reqired for mockito for now fun setPreferencesUpToDate(preferences: SharedPreferences) { Timber.i("Marking preferences as up to date") PreferenceUpgrade.setPreferenceToLatestVersion(preferences) } abstract class PreferenceUpgrade private constructor(val versionIdentifier: VersionIdentifier) { /* To add a new preference upgrade: * yield a new class from getAllInstances (do not use `legacyPreviousVersionCode` in the constructor) * Implement the upgrade() method * Set mVersionIdentifier to 1 more than the previous versionIdentifier * Run tests in PreferenceUpgradeServiceTest */ companion object { /** A version code where the value doesn't matter as we're not using the result */ private const val IGNORED_LEGACY_VERSION_CODE = 0L const val upgradeVersionPrefKey = "preferenceUpgradeVersion" /** Returns all instances of preference upgrade classes */ internal fun getAllInstances(legacyPreviousVersionCode: LegacyVersionIdentifier) = sequence<PreferenceUpgrade> { yield(LegacyPreferenceUpgrade(legacyPreviousVersionCode)) yield(RemoveLegacyMediaSyncUrl()) yield(UpdateNoteEditorToolbarPrefs()) yield(UpgradeGesturesToControls()) yield(UpgradeDayAndNightThemes()) yield(UpgradeCustomCollectionSyncUrl()) yield(UpgradeCustomSyncServerEnabled()) } /** Returns a list of preference upgrade classes which have not been applied */ fun getPendingUpgrades(preferences: SharedPreferences, legacyPreviousVersionCode: LegacyVersionIdentifier): List<PreferenceUpgrade> { val currentPrefVersion: VersionIdentifier = getPreferenceVersion(preferences) return getAllInstances(legacyPreviousVersionCode).filter { it.versionIdentifier > currentPrefVersion }.toList() } /** Sets the preference version such that no upgrades need to be applied */ fun setPreferenceToLatestVersion(preferences: SharedPreferences) { val versionWhichRequiresNoUpgrades = getLatestVersion() setPreferenceVersion(preferences, versionWhichRequiresNoUpgrades) } internal fun getPreferenceVersion(preferences: SharedPreferences) = preferences.getInt(upgradeVersionPrefKey, 0) internal fun setPreferenceVersion(preferences: SharedPreferences, versionIdentifier: VersionIdentifier) { Timber.i("upgrading preference version to '$versionIdentifier'") preferences.edit { putInt(upgradeVersionPrefKey, versionIdentifier) } } /** Returns the collection of all preference version numbers */ @VisibleForTesting fun getAllVersionIdentifiers(): Sequence<VersionIdentifier> = getAllInstances(IGNORED_LEGACY_VERSION_CODE).map { it.versionIdentifier } /** * @return the latest "version" of the preferences * If the preferences are set to this version, then no upgrades will take place */ private fun getLatestVersion(): VersionIdentifier = getAllVersionIdentifiers().maxOrNull() ?: 0 } /** Handles preference upgrades before 2021-08-01, * upgrades were detected via a version code comparison * rather than comparing a preference value */ private class LegacyPreferenceUpgrade(val previousVersionCode: LegacyVersionIdentifier) : PreferenceUpgrade(1) { override fun upgrade(preferences: SharedPreferences) { if (!needsLegacyPreferenceUpgrade(previousVersionCode)) { return } Timber.i("running upgradePreferences()") // clear all prefs if super old version to prevent any errors if (previousVersionCode < 20300130) { Timber.i("Old version of Anki - Clearing preferences") preferences.edit { clear() } } // when upgrading from before 2.5alpha35 if (previousVersionCode < 20500135) { Timber.i("Old version of Anki - Fixing Zoom") // Card zooming behaviour was changed the preferences renamed val oldCardZoom = preferences.getInt("relativeDisplayFontSize", 100) val oldImageZoom = preferences.getInt("relativeImageSize", 100) preferences.edit { putInt("cardZoom", oldCardZoom) putInt("imageZoom", oldImageZoom) } if (!preferences.getBoolean("useBackup", true)) { preferences.edit { putInt("backupMax", 0) } } preferences.edit { remove("useBackup") remove("intentAdditionInstantAdd") } } FullScreenMode.upgradeFromLegacyPreference(preferences) } fun needsLegacyPreferenceUpgrade(previous: Long): Boolean = previous < CHECK_PREFERENCES_AT_VERSION companion object { /** * The latest package version number that included changes to the preferences that requires handling. All * collections being upgraded to (or after) this version must update preferences. * * #9309 Do not modify this variable - it no longer works. * * Instead, add an unconditional check for the old preference before the call to * "needsPreferenceUpgrade", and perform the upgrade. */ const val CHECK_PREFERENCES_AT_VERSION = 20500225 } } fun performUpgrade(preferences: SharedPreferences) { Timber.i("Running preference upgrade: ${this.javaClass.simpleName}") upgrade(preferences) setPreferenceVersion(preferences, this.versionIdentifier) } protected abstract fun upgrade(preferences: SharedPreferences) /** * msync is a legacy URL which does not use the hostnum for load balancing * It was the default value in the "custom sync server" preference */ internal class RemoveLegacyMediaSyncUrl : PreferenceUpgrade(3) { override fun upgrade(preferences: SharedPreferences) { val mediaSyncUrl = preferences.getString(CustomSyncServer.PREFERENCE_CUSTOM_MEDIA_SYNC_URL, null) if (mediaSyncUrl?.startsWith("https://msync.ankiweb.net") == true) { preferences.edit { remove(CustomSyncServer.PREFERENCE_CUSTOM_MEDIA_SYNC_URL) } } } } /** * update toolbar buttons with new preferences, when button text empty or null then it adds the index as button text */ internal class UpdateNoteEditorToolbarPrefs : PreferenceUpgrade(4) { override fun upgrade(preferences: SharedPreferences) { val buttons = getNewToolbarButtons(preferences) // update prefs preferences.edit { remove("note_editor_custom_buttons") putStringSet("note_editor_custom_buttons", CustomToolbarButton.toStringSet(buttons)) } } private fun getNewToolbarButtons(preferences: SharedPreferences): ArrayList<CustomToolbarButton> { // get old toolbar prefs val set = preferences.getStringSet("note_editor_custom_buttons", HashSetInit<String>(0)) as Set<String?> // new list with buttons size val buttons = ArrayList<CustomToolbarButton>(set.size) // parse fields with separator for (s in set) { val fields = s!!.split(Consts.FIELD_SEPARATOR.toRegex(), CustomToolbarButton.KEEP_EMPTY_ENTRIES.coerceAtLeast(0)).toTypedArray() if (fields.size != 3) { continue } val index: Int = try { fields[0].toInt() } catch (e: Exception) { Timber.w(e) continue } // add new button with the index + 1 as button text val visualIndex: Int = index + 1 val buttonText = visualIndex.toString() // fields 1 is prefix, fields 2 is suffix buttons.add(CustomToolbarButton(index, buttonText, fields[1], fields[2])) } return buttons } } internal class UpgradeGesturesToControls : PreferenceUpgrade(5) { val oldCommandValues = mapOf( Pair(1, ViewerCommand.SHOW_ANSWER), Pair(2, ViewerCommand.FLIP_OR_ANSWER_EASE1), Pair(3, ViewerCommand.FLIP_OR_ANSWER_EASE2), Pair(4, ViewerCommand.FLIP_OR_ANSWER_EASE3), Pair(5, ViewerCommand.FLIP_OR_ANSWER_EASE4), Pair(6, ViewerCommand.FLIP_OR_ANSWER_RECOMMENDED), Pair(7, ViewerCommand.FLIP_OR_ANSWER_BETTER_THAN_RECOMMENDED), Pair(8, ViewerCommand.UNDO), Pair(9, ViewerCommand.EDIT), Pair(10, ViewerCommand.MARK), Pair(12, ViewerCommand.BURY_CARD), Pair(13, ViewerCommand.SUSPEND_CARD), Pair(14, ViewerCommand.DELETE), Pair(16, ViewerCommand.PLAY_MEDIA), Pair(17, ViewerCommand.EXIT), Pair(18, ViewerCommand.BURY_NOTE), Pair(19, ViewerCommand.SUSPEND_NOTE), Pair(20, ViewerCommand.TOGGLE_FLAG_RED), Pair(21, ViewerCommand.TOGGLE_FLAG_ORANGE), Pair(22, ViewerCommand.TOGGLE_FLAG_GREEN), Pair(23, ViewerCommand.TOGGLE_FLAG_BLUE), Pair(38, ViewerCommand.TOGGLE_FLAG_PINK), Pair(39, ViewerCommand.TOGGLE_FLAG_TURQUOISE), Pair(40, ViewerCommand.TOGGLE_FLAG_PURPLE), Pair(24, ViewerCommand.UNSET_FLAG), Pair(30, ViewerCommand.PAGE_UP), Pair(31, ViewerCommand.PAGE_DOWN), Pair(32, ViewerCommand.TAG), Pair(33, ViewerCommand.CARD_INFO), Pair(34, ViewerCommand.ABORT_AND_SYNC), Pair(35, ViewerCommand.RECORD_VOICE), Pair(36, ViewerCommand.REPLAY_VOICE), Pair(37, ViewerCommand.TOGGLE_WHITEBOARD), Pair(41, ViewerCommand.SHOW_HINT), Pair(42, ViewerCommand.SHOW_ALL_HINTS), Pair(43, ViewerCommand.ADD_NOTE), ) override fun upgrade(preferences: SharedPreferences) { upgradeGestureToBinding(preferences, "gestureSwipeUp", Gesture.SWIPE_UP) upgradeGestureToBinding(preferences, "gestureSwipeDown", Gesture.SWIPE_DOWN) upgradeGestureToBinding(preferences, "gestureSwipeLeft", Gesture.SWIPE_LEFT) upgradeGestureToBinding(preferences, "gestureSwipeRight", Gesture.SWIPE_RIGHT) upgradeGestureToBinding(preferences, "gestureLongclick", Gesture.LONG_TAP) upgradeGestureToBinding(preferences, "gestureDoubleTap", Gesture.DOUBLE_TAP) upgradeGestureToBinding(preferences, "gestureTapTopLeft", Gesture.TAP_TOP_LEFT) upgradeGestureToBinding(preferences, "gestureTapTop", Gesture.TAP_TOP) upgradeGestureToBinding(preferences, "gestureTapTopRight", Gesture.TAP_TOP_RIGHT) upgradeGestureToBinding(preferences, "gestureTapLeft", Gesture.TAP_LEFT) upgradeGestureToBinding(preferences, "gestureTapCenter", Gesture.TAP_CENTER) upgradeGestureToBinding(preferences, "gestureTapRight", Gesture.TAP_RIGHT) upgradeGestureToBinding(preferences, "gestureTapBottomLeft", Gesture.TAP_BOTTOM_LEFT) upgradeGestureToBinding(preferences, "gestureTapBottom", Gesture.TAP_BOTTOM) upgradeGestureToBinding(preferences, "gestureTapBottomRight", Gesture.TAP_BOTTOM_RIGHT) upgradeVolumeGestureToBinding(preferences, "gestureVolumeUp", KeyEvent.KEYCODE_VOLUME_UP) upgradeVolumeGestureToBinding(preferences, "gestureVolumeDown", KeyEvent.KEYCODE_VOLUME_DOWN) } private fun upgradeVolumeGestureToBinding(preferences: SharedPreferences, oldGesturePreferenceKey: String, volumeKeyCode: Int) { upgradeBinding(preferences, oldGesturePreferenceKey, keyCode(volumeKeyCode)) } private fun upgradeGestureToBinding(preferences: SharedPreferences, oldGesturePreferenceKey: String, gesture: Gesture) { upgradeBinding(preferences, oldGesturePreferenceKey, Binding.gesture(gesture)) } @VisibleForTesting internal fun upgradeBinding(preferences: SharedPreferences, oldGesturePreferenceKey: String, binding: Binding) { Timber.d("Replacing gesture '%s' with binding", oldGesturePreferenceKey) // This exists as a user may have mapped "volume down" to "UNDO". // Undo already exists as a key binding, and we don't want to trash this during an upgrade if (!preferences.contains(oldGesturePreferenceKey)) { Timber.v("No preference to upgrade") return } try { replaceBinding(preferences, oldGesturePreferenceKey, binding) } finally { Timber.v("removing pref key: '%s'", oldGesturePreferenceKey) // remove the old key preferences.edit { remove(oldGesturePreferenceKey) } } } private fun replaceBinding(preferences: SharedPreferences, oldGesturePreferenceKey: String, binding: Binding) { // the preference should be set, but if it's null, then we have nothing to do val pref = preferences.getString(oldGesturePreferenceKey, "0") ?: return // If the preference doesn't map (for example: it was removed), then nothing to do val asInt = pref.toIntOrNull() ?: return val command = oldCommandValues[asInt] ?: return Timber.i("Moving preference from '%s' to '%s'", oldGesturePreferenceKey, command.preferenceKey) // add to the binding_COMMANDNAME preference val mappableBinding = MappableBinding(binding, MappableBinding.Screen.Reviewer(CardSide.BOTH)) command.addBindingAtEnd(preferences, mappableBinding) } } internal class UpgradeDayAndNightThemes : PreferenceUpgrade(6) { override fun upgrade(preferences: SharedPreferences) { val dayTheme = preferences.getString("dayTheme", "0") val nightTheme = preferences.getString("nightTheme", "0") preferences.edit { if (dayTheme == "1") { // plain putString("dayTheme", "2") } else { // light putString("dayTheme", "1") } if (nightTheme == "1") { // dark putString("nightTheme", "4") } else { // black putString("nightTheme", "3") } remove("invertedColors") } if (AnkiDroidApp.isInitialized) { Themes.updateCurrentTheme() } } } internal class UpgradeCustomCollectionSyncUrl : PreferenceUpgrade(7) { override fun upgrade(preferences: SharedPreferences) { val oldUrl = preferences.getString(RemovedPreferences.PREFERENCE_CUSTOM_SYNC_BASE, null) var newUrl: String? = null if (oldUrl != null && oldUrl.isNotBlank()) { try { newUrl = oldUrl.toUri().buildUpon().appendPath("sync").toString() + "/" } catch (e: Exception) { Timber.e(e, "Error constructing new sync URL from '%s'", oldUrl) } } preferences.edit { remove(RemovedPreferences.PREFERENCE_CUSTOM_SYNC_BASE) if (newUrl != null) putString(CustomSyncServer.PREFERENCE_CUSTOM_COLLECTION_SYNC_URL, newUrl) } } } internal class UpgradeCustomSyncServerEnabled : PreferenceUpgrade(8) { override fun upgrade(preferences: SharedPreferences) { val customSyncServerEnabled = preferences.getBoolean(RemovedPreferences.PREFERENCE_ENABLE_CUSTOM_SYNC_SERVER, false) val customCollectionSyncUrl = preferences.getString(CustomSyncServer.PREFERENCE_CUSTOM_COLLECTION_SYNC_URL, null) val customMediaSyncUrl = preferences.getString(CustomSyncServer.PREFERENCE_CUSTOM_MEDIA_SYNC_URL, null) preferences.edit { remove(RemovedPreferences.PREFERENCE_ENABLE_CUSTOM_SYNC_SERVER) putBoolean( CustomSyncServer.PREFERENCE_CUSTOM_COLLECTION_SYNC_SERVER_ENABLED, customSyncServerEnabled && !customCollectionSyncUrl.isNullOrEmpty() ) putBoolean( CustomSyncServer.PREFERENCE_CUSTOM_MEDIA_SYNC_SERVER_ENABLED, customSyncServerEnabled && !customMediaSyncUrl.isNullOrEmpty() ) } } } } } object RemovedPreferences { const val PREFERENCE_CUSTOM_SYNC_BASE = "syncBaseUrl" const val PREFERENCE_ENABLE_CUSTOM_SYNC_SERVER = "useCustomSyncServer" }
gpl-3.0
e5ce3ad5d3829ca8e6be3be28227c66f
48.952267
148
0.616149
5.357051
false
false
false
false
ankidroid/Anki-Android
api/src/main/java/com/ichi2/anki/FlashCardsContract.kt
1
48146
//noinspection MissingCopyrightHeader - explicitly not GPL /* * Copying and distribution of this file, with or without modification, are permitted in any * medium without royalty. This file is offered as-is, without any warranty. */ package com.ichi2.anki import android.net.Uri /** * The contract between AnkiDroid and applications. Contains definitions for the supported URIs and * columns. * * ###### * ### Overview * * * FlashCardsContract defines the access to flash card related information. Flash cards consist of * notes and cards. To find out more about notes and cards, see * [the basics section in the Anki manual.](https://docs.ankiweb.net/getting-started.html#key-concepts) * * * In short, you can think of cards as instances of notes, with the limitation that the number of * instances and their names are pre-defined. * * * The most important data of notes/cards are "fields". Fields contain the actual information of the * flashcard that is used for learning. Typical fields are "Japanese" and "English" (for a native * English speaker to learn Japanese), or just "front" and "back" (for a generic front side and back * side of a card, without saying anything about the purpose). * * * Note and card information is accessed in the following way: * * * Each row from the [Note] provider represents a note that is stored in the AnkiDroid database. * This provider must be used in order to find flashcards. The notes * can be accessed by the [Note.CONTENT_URI], like this to search for note: * * ``` * // Query all available notes * final Cursor cursor = cr.query(FlashCardsContract.Note.CONTENT_URI, null, null, null, null); * ``` * * or this if you know the note's ID: * * ``` * String noteId = ... // Use the known note ID * Uri noteUri = Uri.withAppendedPath(FlashCardsContract.Note.CONTENT_URI, noteId); * final Cursor cur = cr.query(noteUri, null, null, null, null); * ``` * * * A row from the [Card] sub-provider gives access to notes cards. The * cards are accessed as described in the [Card] description. * * * The format of notes and cards is described in models. The models are accessed as described * in the [Model] description. * * * The AnkiDroid Flashcard content provider supports the following operation on it's URIs: * * ``` * URIs and operations supported by CardContentProvider * * URI | Description * -------------------------------------------------------------------------------------------------------------------- * notes | Note with id `note_id` as raw data * | Supports insert(mid), query(). For code examples see class description of [Note]. * -------------------------------------------------------------------------------------------------------------------- * notes/<note_id> | Note with id `note_id` as raw data * | Supports query(). For code examples see class description of [Note]. * -------------------------------------------------------------------------------------------------------------------- * notes/<note_id>/cards | All cards belonging to note `note_id` as high level data (Deck name, question, answer). * | Supports query(). For code examples see class description of [Card]. * -------------------------------------------------------------------------------------------------------------------- * notes/<note_id>/cards/<ord> | NoteCard `ord` (with ord = 0... num_cards-1) belonging to note `note_id` as high level data (Deck name, question, answer). * | Supports update(), query(). For code examples see class description of [Card]. * -------------------------------------------------------------------------------------------------------------------- * models | All models as JSONObjects. * | Supports query(). For code examples see class description of [Model]. * -------------------------------------------------------------------------------------------------------------------- * model/<model_id> | Direct access to model `model_id` as JSONObject. * | Supports query(). For code examples see class description of [Model]. * -------------------------------------------------------------------------------------------------------------------- * ``` */ public object FlashCardsContract { public const val AUTHORITY: String = "com.ichi2.anki.flashcards" public const val READ_WRITE_PERMISSION: String = "com.ichi2.anki.permission.READ_WRITE_DATABASE" /** * A content:// style uri to the authority for the flash card provider */ @JvmField // required for Java API public val AUTHORITY_URI: Uri = Uri.parse("content://$AUTHORITY") /** * The Notes can be accessed by * the [.CONTENT_URI]. If the [.CONTENT_URI] is appended by the note's ID, this * note can be directly accessed. If no ID is appended the content provides functions return * all the notes that match the query as defined in `selection` argument in the * `query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)` call. * For queries, the `selectionArgs` parameter can contain an optional selection statement for the notes table * in the sql database. E.g. "mid = 12345678" could be used to limit to a particular model ID. * The `selection` parameter is an optional search string for the Anki browser. The syntax is described * [in the search section of the Anki manual](https://docs.ankiweb.net/searching.html). * * * Example for querying notes with a certain tag: * * ``` * final Cursor cursor = cr.query(FlashCardsContract.Note.CONTENT_URI, * null, // projection * "tag:my_tag", // example query * null, // selectionArgs is ignored for this URI * null // sortOrder is ignored for this URI * ); * ``` * * * Example for querying notes with a certain note id with direct URI: * * ``` * Uri noteUri = Uri.withAppendedPath(FlashCardsContract.Note.CONTENT_URI, Long.toString(noteId)); * final Cursor cursor = cr.query(noteUri, * null, // projection * null, // selection is ignored for this URI * null, // selectionArgs is ignored for this URI * null // sortOrder is ignored for this URI * ); * ``` * * * In order to insert a new note (the cards for this note will be added to the default deck) * the [.CONTENT_URI] must be used together with a model (see [Model]) * ID, e.g. * * ``` * Long mId = ... // Use the correct model ID * ContentValues values = new ContentValues(); * values.put(FlashCardsContract.Note.MID, mId); * Uri newNoteUri = cr.insert(FlashCardsContract.Note.CONTENT_URI, values); * ``` * * * Updating tags for a note can be done this way: * * ``` * Uri updateNoteUri = Uri.withAppendedPath(FlashCardsContract.Note.CONTENT_URI, Long.toString(noteId)); * ContentValues values = new ContentValues(); * values.put(FlashCardsContract.Note.TAGS, tag1 + " " + tag2); * int updateCount = cr.update(updateNoteUri, values, null, null); * ``` * * * A note consists of the following columns: * * ``` * Note column description * * Type | Name | Access | Description * -------------------------------------------------------------------------------------------------------------------- * long | _ID | read-only | Row ID. This is the ID of the note. It is the same as the note ID in Anki. This * | | | ID can be used for accessing the data of a note using the URI * | | | "content://com.ichi2.anki.flashcards/notes/<_ID>/data * -------------------------------------------------------------------------------------------------------------------- * long | GUID | read-only | See more at https://github.com/ankidroid/Anki-Android/wiki/Database-Structure * -------------------------------------------------------------------------------------------------------------------- * long | MID | read-only | This is the ID of the model that is used for rendering the cards. This ID can be used for * | | | accessing the data of the model using the URI * | | | "content://com.ichi2.anki.flashcards/model/<ID> * -------------------------------------------------------------------------------------------------------------------- * long | MOD | read-only | See more at https://github.com/ankidroid/Anki-Android/wiki/Database-Structure * -------------------------------------------------------------------------------------------------------------------- * long | USN | read-only | See more at https://github.com/ankidroid/Anki-Android/wiki/Database-Structure * -------------------------------------------------------------------------------------------------------------------- * long | TAGS | read-write | NoteTag of this note. NoteTag are separated by spaces. * -------------------------------------------------------------------------------------------------------------------- * String | FLDS | read-write | Fields of this note. Fields are separated by "\\x1f", a.k.a. Consts.FIELD_SEPARATOR * -------------------------------------------------------------------------------------------------------------------- * long | SFLD | read-only | See more at https://github.com/ankidroid/Anki-Android/wiki/Database-Structure * -------------------------------------------------------------------------------------------------------------------- * long | CSUM | read-only | See more at https://github.com/ankidroid/Anki-Android/wiki/Database-Structure * -------------------------------------------------------------------------------------------------------------------- * long | FLAGS | read-only | See more at https://github.com/ankidroid/Anki-Android/wiki/Database-Structure * -------------------------------------------------------------------------------------------------------------------- * long | DATA | read-only | See more at https://github.com/ankidroid/Anki-Android/wiki/Database-Structure * -------------------------------------------------------------------------------------------------------------------- * ``` */ public object Note { /** * The content:// style URI for notes. If the it is appended by the note's ID, this * note can be directly accessed, e.g. * * ``` * Uri noteUri = Uri.withAppendedPath(FlashCardsContract.Note.CONTENT_URI, Long.toString(noteId)); * ``` * * If the URI is appended by the note ID and then the keyword "data", it is possible to * access the details of a note: * * * ``` * Uri noteUri = Uri.withAppendedPath(FlashCardsContract.Note.CONTENT_URI, Long.toString(noteId)); * Uri dataUri = Uri.withAppendedPath(noteUri, "data"); * ``` * * * For examples on how to use the URI for queries see class description. */ @JvmField // required for Java API public val CONTENT_URI: Uri = Uri.withAppendedPath(AUTHORITY_URI, "notes") /** * The content:// style URI for notes, but with a direct SQL query to the notes table instead of accepting * a query in the libanki browser search syntax like the main URI #CONTENT_URI does. */ @JvmField // required for Java API public val CONTENT_URI_V2: Uri = Uri.withAppendedPath(AUTHORITY_URI, "notes_v2") /** * This is the ID of the note. It is the same as the note ID in Anki. This ID can be * used for accessing the data of a note using the URI * "content://com.ichi2.anki.flashcards/notes/&lt;ID&gt;/data */ @Suppress("ObjectPropertyName") public const val _ID: String = "_id" // field is part of the default projection available to the clients @Suppress("MemberVisibilityCanBePrivate") public const val GUID: String = "guid" public const val MID: String = "mid" public const val ALLOW_EMPTY: String = "allow_empty" public const val MOD: String = "mod" // field is part of the default projection available to the clients @Suppress("MemberVisibilityCanBePrivate") public const val USN: String = "usn" public const val TAGS: String = "tags" public const val FLDS: String = "flds" // field is part of the default projection available to the clients @Suppress("MemberVisibilityCanBePrivate") public const val SFLD: String = "sfld" public const val CSUM: String = "csum" public const val FLAGS: String = "flags" public const val DATA: String = "data" @JvmField // required for Java API public val DEFAULT_PROJECTION: Array<String> = arrayOf( _ID, GUID, MID, MOD, USN, TAGS, FLDS, SFLD, CSUM, FLAGS, DATA ) /** * MIME type used for a note. */ public const val CONTENT_ITEM_TYPE: String = "vnd.android.cursor.item/vnd.com.ichi2.anki.note" /** * MIME type used for notes. */ public const val CONTENT_TYPE: String = "vnd.android.cursor.dir/vnd.com.ichi2.anki.note" /** * Used only by bulkInsert() to specify which deck the notes should be placed in */ public const val DECK_ID_QUERY_PARAM: String = "deckId" } /** * A model describes what cards look like. * * ``` * Card model description * Type | Name | Access | Description * -------------------------------------------------------------------------------------------------------------------- * long | _ID | read-only | Model ID. * -------------------------------------------------------------------------------------------------------------------- * String | NAME | | Name of the model. * -------------------------------------------------------------------------------------------------------------------- * String | CSS | | CSS styling code which is shared across all the templates * -------------------------------------------------------------------------------------------------------------------- * String | FIELD_NAMES | read-only | Names of all the fields, separate by the 0x1f character * -------------------------------------------------------------------------------------------------------------------- * Integer | NUM_CARDS | read-only | Number of card templates, which corresponds to the number of rows in the templates table * -------------------------------------------------------------------------------------------------------------------- * Long | DECK_ID | read-only | The default deck that cards should be added to * -------------------------------------------------------------------------------------------------------------------- * Integer | SORT_FIELD_INDEX | read-only | Which field is used as the main sort field * -------------------------------------------------------------------------------------------------------------------- * Integer | TYPE | read-only | 0 for normal model, 1 for cloze model * -------------------------------------------------------------------------------------------------------------------- * String | LATEX_POST | read-only | Code to go at the end of LaTeX renderings in Anki Desktop * -------------------------------------------------------------------------------------------------------------------- * String | LATEX_PRE | read-only | Code to go at the front of LaTeX renderings in Anki Desktop * -------------------------------------------------------------------------------------------------------------------- * ``` * * * It's possible to query all models at once like this * * ``` * Uri noteUri = Uri.withAppendedPath(FlashCardsContract.Note.CONTENT_URI, Long.toString(noteId)); * final Cursor cursor = cr.query(FlashCardsContract.Model.CONTENT_URI, * null, // projection * null, // selection is ignored for this URI * null, // selectionArgs is ignored for this URI * null // sortOrder is ignored for this URI * ); * ``` * * * It's also possible to access a specific model like this: * * * ``` * long modelId = ...// Use the correct model ID * Uri modelUri = Uri.withAppendedPath(FlashCardsContract.Model.CONTENT_URI, Long.toString(modelId)); * final Cursor cur = cr.query(modelUri, * null, // projection * null, // selection is ignored for this URI * null, // selectionArgs is ignored for this URI * null // sortOrder is ignored for this URI * ); * ``` * * * Instead of specifying the model ID, it's also possible to get the currently active model using the following URI: * * * ``` * Uri.withAppendedPath(FlashCardsContract.Model.CONTENT_URI, FlashCardsContract.Model.CURRENT_MODEL_ID); * ``` */ public object Model { /** * The content:// style URI for model. If the it is appended by the model's ID, this * note can be directly accessed. See class description above for further details. */ @JvmField // required for Java API public val CONTENT_URI: Uri = Uri.withAppendedPath(AUTHORITY_URI, "models") public const val CURRENT_MODEL_ID: String = "current" /** * This is the ID of the model. It is the same as the note ID in Anki. This ID can be * used for accessing the data of the model using the URI * "content://com.ichi2.anki.flashcards/models/&lt;ID&gt; */ @Suppress("ObjectPropertyName") public const val _ID: String = "_id" public const val NAME: String = "name" public const val FIELD_NAME: String = "field_name" public const val FIELD_NAMES: String = "field_names" public const val NUM_CARDS: String = "num_cards" public const val CSS: String = "css" public const val SORT_FIELD_INDEX: String = "sort_field_index" public const val TYPE: String = "type" public const val LATEX_POST: String = "latex_post" public const val LATEX_PRE: String = "latex_pre" public const val NOTE_COUNT: String = "note_count" /** * The deck ID that is selected by default when adding new notes with this model. * This is only used when the "Deck for new cards" preference is set to "Decide by note type" */ public const val DECK_ID: String = "deck_id" @JvmField // required for Java API public val DEFAULT_PROJECTION: Array<String> = arrayOf( _ID, NAME, FIELD_NAMES, NUM_CARDS, CSS, DECK_ID, SORT_FIELD_INDEX, TYPE, LATEX_POST, LATEX_PRE ) /** * MIME type used for a model. */ public const val CONTENT_ITEM_TYPE: String = "vnd.android.cursor.item/vnd.com.ichi2.anki.model" /** * MIME type used for model. */ public const val CONTENT_TYPE: String = "vnd.android.cursor.dir/vnd.com.ichi2.anki.model" } /** * Card template for a model. A template defines how to render the fields of a note into the actual HTML that * makes up a flashcard. A model can define multiple card templates, for example a Forward and Reverse Card could * be defined with the forward card allowing to review a word from Japanese-&gt;English (e.g. 犬 -&gt; dog), and the * reverse card allowing review in the "reverse" direction (e.g dog -&gt; 犬). When a Note is inserted, a Card will * be generated for each active CardTemplate which is defined. */ public object CardTemplate { /** * MIME type used for data. */ public const val CONTENT_TYPE: String = "vnd.android.cursor.dir/vnd.com.ichi2.anki.model.template" public const val CONTENT_ITEM_TYPE: String = "vnd.android.cursor.item/vnd.com.ichi2.anki.model.template" /** * Row ID. This is a virtual ID which actually does not exist in AnkiDroid's data base. * This column only exists so that this interface can be used with existing CursorAdapters * that require the existence of a "_id" column. This means, that it CAN NOT be used * reliably over subsequent queries. Especially if the number of cards or fields changes, * the _ID will change too. */ @Suppress("ObjectPropertyName") public const val _ID: String = "_id" /** * This is the ID of the model that this row belongs to (i.e. [Model._ID]). */ public const val MODEL_ID: String = "model_id" /** * This is the ordinal / index of the card template (from 0 to number of cards - 1). */ public const val ORD: String = "ord" /** * The template name e.g. "Card 1". */ public const val NAME: String = "card_template_name" /** * The definition of the template for the question */ public const val QUESTION_FORMAT: String = "question_format" /** * The definition of the template for the answer */ public const val ANSWER_FORMAT: String = "answer_format" /** * Optional alternative definition of the template for the question when rendered with the browser */ public const val BROWSER_QUESTION_FORMAT: String = "browser_question_format" /** * Optional alternative definition of the template for the answer when rendered with the browser */ public const val BROWSER_ANSWER_FORMAT: String = "browser_answer_format" public const val CARD_COUNT: String = "card_count" /** * Default columns that are returned when querying the ...models/#/templates URI. */ @JvmField // required for Java API public val DEFAULT_PROJECTION: Array<String> = arrayOf( _ID, MODEL_ID, ORD, NAME, QUESTION_FORMAT, ANSWER_FORMAT ) } /** * A card is an instance of a note. * * * If the URI of a note is appended by the keyword "cards", it is possible to * access all the cards that are associated with this note: * * * ``` * Uri noteUri = Uri.withAppendedPath(FlashCardsContract.Note.CONTENT_URI, Long.toString(noteId)); * Uri cardsUri = Uri.withAppendedPath(noteUri, "cards"); * final Cursor cur = cr.query(cardsUri, * null, // projection * null, // selection is ignored for this URI * null, // selectionArgs is ignored for this URI * null // sortOrder is ignored for this URI * ); *``` * * If it is furthermore appended by the cards ordinal (see [.CARD_ORD]) it's possible to * directly access a specific card. * * * ``` * Uri noteUri = Uri.withAppendedPath(FlashCardsContract.Note.CONTENT_URI, Long.toString(noteId)); * Uri cardsUri = Uri.withAppendedPath(noteUri, "cards"); * Uri specificCardUri = Uri.withAppendedPath(noteUri, Integer.toString(cardOrd)); * final Cursor cur = cr.query(specificCardUri, * null, // projection * null, // selection is ignored for this URI * null, // selectionArgs is ignored for this URI * null // sortOrder is ignored for this URI * ); * ``` * * A card consists of the following columns: * * ``` * Card column description * Type | Name | Access | Description * -------------------------------------------------------------------------------------------------------------------- * long | NOTE_ID | read-only | This is the ID of the note that this row belongs to (i.e. Note._ID) * -------------------------------------------------------------------------------------------------------------------- * int | CARD_ORD | read-only | This is the ordinal of the card. A note has 1..n cards. The ordinal can also be * | | | used to directly access a card as describe in the class description. * -------------------------------------------------------------------------------------------------------------------- * String | CARD_NAME | read-only | The card's name. * -------------------------------------------------------------------------------------------------------------------- * String | DECK_ID | read-write | The id of the deck that this card is part of. * -------------------------------------------------------------------------------------------------------------------- * String | QUESTION | read-only | The question for this card. * -------------------------------------------------------------------------------------------------------------------- * String | ANSWER | read-only | The answer for this card. * -------------------------------------------------------------------------------------------------------------------- * String | QUESTION_SIMPLE | read-only | The question for this card in the simplified form, without card styling information (CSS). * -------------------------------------------------------------------------------------------------------------------- * String | ANSWER_SIMPLE | read-only | The answer for this card in the simplified form, without card styling information (CSS). * -------------------------------------------------------------------------------------------------------------------- * String | ANSWER_PURE | read-only | Purified version of the answer. In case the [.ANSWER] contains any additional elements * | | | (like a duplicate of the question) this is removed for [.ANSWER_PURE]. * | | | Like [.ANSWER_SIMPLE] it does not contain styling information (CSS). * -------------------------------------------------------------------------------------------------------------------- * ``` * * The only writable column is the [.DECK_ID]. Moving a card to another deck, can be * done as shown in this example * * ``` * Uri noteUri = Uri.withAppendedPath(FlashCardsContract.Note.CONTENT_URI, Long.toString(noteId)); * Uri cardsUri = Uri.withAppendedPath(noteUri, "cards"); * final Cursor cur = cr.query(cardsUri, * null, // selection is ignored for this URI * null, // selectionArgs is ignored for this URI * null // sortOrder is ignored for this URI * ); * do { * long newDid = 12345678L; * long oldDid = cur.getLong(cur.getColumnIndex(FlashCardsContract.Card.DECK_ID)); * if(newDid != oldDid){ * // Move to new deck * ContentValues values = new ContentValues(); * values.put(FlashCardsContract.Card.DECK_ID, newDid); * Uri cardUri = Uri.withAppendedPath(cardsUri, cur.getString(cur.getColumnIndex(FlashCardsContract.Card.CARD_ORD))); * cr.update(cardUri, values, null, null); * } * } while (cur.moveToNext()); * ``` */ public object Card { /** * This is the ID of the note that this card belongs to (i.e. [Note._ID]). */ public const val NOTE_ID: String = "note_id" /** * This is the ordinal of the card. A note has 1..n cards. The ordinal can also be used * to directly access a card as describe in the class description. */ public const val CARD_ORD: String = "ord" /** * The card's name. */ public const val CARD_NAME: String = "card_name" /** * The name of the deck that this card is part of. */ public const val DECK_ID: String = "deck_id" /** * The question for this card. */ public const val QUESTION: String = "question" /** * The answer for this card. */ public const val ANSWER: String = "answer" /** * Simplified version of the question, without card styling (CSS). */ public const val QUESTION_SIMPLE: String = "question_simple" /** * Simplified version of the answer, without card styling (CSS). */ public const val ANSWER_SIMPLE: String = "answer_simple" /** * Purified version of the answer. In case the ANSWER contains any additional elements * (like a duplicate of the question) this is removed for ANSWER_PURE */ public const val ANSWER_PURE: String = "answer_pure" @JvmField // required for Java API public val DEFAULT_PROJECTION: Array<String> = arrayOf( NOTE_ID, CARD_ORD, CARD_NAME, DECK_ID, QUESTION, ANSWER ) /** * MIME type used for a card. */ public const val CONTENT_ITEM_TYPE: String = "vnd.android.cursor.item/vnd.com.ichi2.anki.card" /** * MIME type used for cards. */ public const val CONTENT_TYPE: String = "vnd.android.cursor.dir/vnd.com.ichi2.anki.card" } /** * A ReviewInfo contains information about a card that is scheduled for review. * * * To access the next scheduled card(s), a simple query with the [.CONTENT_URI] can be used. * Arguments: * ``` * ReviewInfo information table * Type | Name | Default value | Description * -------------------------------------------------------------------------------------------------------------------- * long | deckID | The deck, that was last selected | The deckID of the deck from which the scheduled cards should be pulled. * | | for reviewing by the user in the | * | | Deck chooser dialog of the App | * -------------------------------------------------------------------------------------------------------------------- * int | limit | 1 | The maximum number of cards (rows) that will be returned. In case * | | | the deck has fewer scheduled cards, the returned number of cards will be * | | | lower than the limit. * -------------------------------------------------------------------------------------------------------------------- * ``` * * * ``` * Uri scheduled_cards_uri = FlashCardsContract.ReviewInfo.CONTENT_URI; * String deckArguments[] = new String[]{"5", "123456789"}; * String deckSelector = "limit=?, deckID=?"; * final Cursor cur = cr.query(scheduled_cards_uri, * null, // projection * deckSelector, // if null, default values will be used * deckArguments, // if null, the deckSelector must not contain any placeholders ("?") * null // sortOrder is ignored for this URI * ); * ``` * * * A ReviewInfo consists of the following columns: * * ``` * ReviewInfo column information * Type | Name | Access | Description * -------------------------------------------------------------------------------------------------------------------- * long | NOTE_ID | read-only | This is the ID of the note that this row belongs to (i.e. [Note._ID]). * -------------------------------------------------------------------------------------------------------------------- * int | CARD_ORD | read-only | This is the ordinal of the card. A note has 1..n cards. The ordinal can also be used * | | | to directly access a card as describe in the class description. * -------------------------------------------------------------------------------------------------------------------- * int | BUTTON_COUNT | read-only | The number of buttons/ease identifiers that can be used to answer the card. * -------------------------------------------------------------------------------------------------------------------- * JSONArray | NEXT_REVIEW_TIMES | read-only | A JSONArray containing when the card will be scheduled for review for all ease identifiers * | | | available. The number of entries in this array must equal the number of buttons in [.BUTTON_COUNT]. * -------------------------------------------------------------------------------------------------------------------- * JSONArray | MEDIA_FILES | read-only | The media files, like images and sound files, contained in the cards. * -------------------------------------------------------------------------------------------------------------------- * String | EASE | write-only | The ease of the card. Used when answering the card. One of: * | | | com.ichi2.anki.AbstractFlashcardViewer.EASE_1 * | | | com.ichi2.anki.AbstractFlashcardViewer.EASE_2 * | | | com.ichi2.anki.AbstractFlashcardViewer.EASE_3 * | | | com.ichi2.anki.AbstractFlashcardViewer.EASE_4 * -------------------------------------------------------------------------------------------------------------------- * String | TIME_TAKEN | write_only | The it took to answer the card (in milliseconds). Used when answering the card. * -------------------------------------------------------------------------------------------------------------------- * int | BURY | write-only | Set to 1 to bury the card. Mutually exclusive with setting EASE/TIME_TAKEN/SUSPEND * -------------------------------------------------------------------------------------------------------------------- * int | SUSPEND | write_only | Set to 1 to suspend the card. Mutually exclusive with setting EASE/TIME_TAKEN/BURY * -------------------------------------------------------------------------------------------------------------------- * ``` * * * Answering a card can be done as shown in this example. Don't set BURY/SUSPEND when answering a card. * * ``` * ContentResolver cr = getContentResolver(); * Uri reviewInfoUri = FlashCardsContract.ReviewInfo.CONTENT_URI; * ContentValues values = new ContentValues(); * long noteId = 123456789; //<-- insert real note id here * int cardOrd = 0; //<-- insert real card ord here * int ease = AbstractFlashcardViewer.EASE_3; //<-- insert real ease here * long timeTaken = System.currentTimeMillis() - cardStartTime; //<-- insert real time taken here * * values.put(FlashCardsContract.ReviewInfo.NOTE_ID, noteId); * values.put(FlashCardsContract.ReviewInfo.CARD_ORD, cardOrd); * values.put(FlashCardsContract.ReviewInfo.EASE, ease); * values.put(FlashCardsContract.ReviewInfo.TIME_TAKEN, timeTaken); * cr.update(reviewInfoUri, values, null, null); * ``` * * * Burying or suspending a card can be done this way. Don't set EASE/TIME_TAKEN when burying/suspending a card * * ``` * ContentResolver cr = getContentResolver(); * Uri reviewInfoUri = FlashCardsContract.ReviewInfo.CONTENT_URI; * ContentValues values = new ContentValues(); * long noteId = card.note().getId(); * int cardOrd = card.getOrd(); * * values.put(FlashCardsContract.ReviewInfo.NOTE_ID, noteId); * values.put(FlashCardsContract.ReviewInfo.CARD_ORD, cardOrd); * * // use this to bury a card * values.put(FlashCardsContract.ReviewInfo.BURY, 1); * * // if you want to suspend, use this instead * // values.put(FlashCardsContract.ReviewInfo.SUSPEND, 1); * * int updateCount = cr.update(reviewInfoUri, values, null, null); * ``` */ public object ReviewInfo { @JvmField // required for Java API public val CONTENT_URI: Uri = Uri.withAppendedPath(AUTHORITY_URI, "schedule") /** * This is the ID of the note that this card belongs to (i.e. [Note._ID]). */ public const val NOTE_ID: String = "note_id" /** * This is the ordinal of the card. A note has 1..n cards. The ordinal can also be used * to directly access a card as describe in the class description. */ public const val CARD_ORD: String = "ord" /** * This is the number of ease modes. It can take a value between 2 and 4. */ public const val BUTTON_COUNT: String = "button_count" /** * This is a JSONArray containing the next review times for all buttons. */ public const val NEXT_REVIEW_TIMES: String = "next_review_times" /** * The names of the media files in the question and answer */ public const val MEDIA_FILES: String = "media_files" /* * Ease of an answer. Is not set when requesting the scheduled cards. * Can take values of AbstractFlashcardViewer e.g. EASE_1 */ public const val EASE: String = "answer_ease" /* * Time it took to answer the card (in ms) */ public const val TIME_TAKEN: String = "time_taken" /** * Write-only field, allows burying of a card when set to 1 */ public const val BURY: String = "buried" /** * Write-only field, allows suspending of a card when set to 1 */ public const val SUSPEND: String = "suspended" @JvmField // required for Java API public val DEFAULT_PROJECTION: Array<String> = arrayOf( NOTE_ID, CARD_ORD, BUTTON_COUNT, NEXT_REVIEW_TIMES, MEDIA_FILES ) /** * MIME type used for ReviewInfo. */ public const val CONTENT_TYPE: String = "vnd.android.cursor.dir/vnd.com.ichi2.anki.review_info" } /** * A Deck contains information about a deck contained in the users deck list. * * * To request a list of all decks the URI [.CONTENT_ALL_URI] can be used. * To request the currently selected deck the URI [.CONTENT_SELECTED_URI] can be used. * * A Deck consists of the following columns: * * ``` * Columns available in a Deck * * Type | Name | Access | Description * -------------------------------------------------------------------------------------------------------------------- * long | DECK_ID | read-only | This is the unique ID of the Deck. * -------------------------------------------------------------------------------------------------------------------- * String | DECK_NAME | | This is the name of the Deck as the user usually sees it. * -------------------------------------------------------------------------------------------------------------------- * String | DECK_DESC | | The deck description shown on the overview page * -------------------------------------------------------------------------------------------------------------------- * JSONArray | DECK_COUNTS | read-only | These are the deck counts of the Deck. [learn, review, new] * -------------------------------------------------------------------------------------------------------------------- * JSONObject | OPTIONS | read-only | These are the options of the deck. * -------------------------------------------------------------------------------------------------------------------- * Boolean | DECK_DYN | read-only | Whether or not the deck is a filtered deck * -------------------------------------------------------------------------------------------------------------------- * ``` * * Requesting a list of all decks can be done as shown in this example * * ``` * Cursor decksCursor = getContentResolver().query(FlashCardsContract.Deck.CONTENT_ALL_URI, null, null, null, null); * if (decksCursor.moveToFirst()) { * HashMap<Long,String> decks = new HashMap<Long,String>(); * do { * long deckID = decksCursor.getLong(decksCursor.getColumnIndex(FlashCardsContract.Deck.DECK_ID)); * String deckName = decksCursor.getString(decksCursor.getColumnIndex(FlashCardsContract.Deck.DECK_NAME)); * try { * JSONObject deckOptions = new JSONObject(decksCursor.getString(decksCursor.getColumnIndex(FlashCardsContract.Deck.OPTIONS))); * JSONArray deckCounts = new JSONArray(decksCursor.getString(decksCursor.getColumnIndex(FlashCardsContract.Deck.DECK_COUNTS))); * } catch (JSONException e) { * e.printStackTrace(); * } * decks.put(deckID, deckName); * } while (decksCursor.moveToNext()); * } * ``` * * * Requesting a single deck can be done the following way: * * ``` * long deckId = 123456 //<-- insert real deck ID here * Uri deckUri = Uri.withAppendedPath(FlashCardsContract.Deck.CONTENT_ALL_URI, Long.toString(deckId)); * Cursor decksCursor = getContentResolver().query(deckUri, null, null, null, null); * * if (decksCursor == null || !decksCursor.moveToFirst()) { * Log.d(TAG, "query for deck returned no result"); * if (decksCursor != null) { * decksCursor.close(); * } * } else { * JSONObject decks = new JSONObject(); * long deckID = decksCursor.getLong(decksCursor.getColumnIndex(FlashCardsContract.Deck.DECK_ID)); * String deckName = decksCursor.getString(decksCursor.getColumnIndex(FlashCardsContract.Deck.DECK_NAME)); * * try { * JSONObject deckOptions = new JSONObject(decksCursor.getString(decksCursor.getColumnIndex(FlashCardsContract.Deck.OPTIONS))); * JSONArray deckCounts = new JSONArray(decksCursor.getString(decksCursor.getColumnIndex(FlashCardsContract.Deck.DECK_COUNTS))); * Log.d(TAG, "deckCounts " + deckCounts); * Log.d(TAG, "deck Options " + deckOptions); * decks.put(deckName, deckID); * } catch (JSONException e) { * e.printStackTrace(); * } * decksCursor.close(); * } * ``` * * * Updating the selected deck can be done as shown in this example * * ``` * long deckId = 123456; //>-- insert real deck id here * * ContentResolver cr = getContentResolver(); * Uri selectDeckUri = FlashCardsContract.Deck.CONTENT_SELECTED_URI; * ContentValues values = new ContentValues(); * values.put(FlashCardsContract.Deck.DECK_ID, deckId); * cr.update(selectDeckUri, values, null, null); * ``` */ public object Deck { @JvmField // required for Java API public val CONTENT_ALL_URI: Uri = Uri.withAppendedPath(AUTHORITY_URI, "decks") @JvmField // required for Java API public val CONTENT_SELECTED_URI: Uri = Uri.withAppendedPath(AUTHORITY_URI, "selected_deck") /** * The name of the Deck */ public const val DECK_NAME: String = "deck_name" /** * The unique identifier of the Deck */ public const val DECK_ID: String = "deck_id" /** * The number of cards in the Deck */ public const val DECK_COUNTS: String = "deck_count" /** * The options of the Deck */ public const val OPTIONS: String = "options" /** * 1 if dynamic (AKA filtered) deck */ public const val DECK_DYN: String = "deck_dyn" /** * Deck description */ public const val DECK_DESC: String = "deck_desc" @JvmField // required for Java API public val DEFAULT_PROJECTION: Array<String> = arrayOf( DECK_NAME, DECK_ID, DECK_COUNTS, OPTIONS, DECK_DYN, DECK_DESC ) /** * MIME type used for Deck. */ public const val CONTENT_TYPE: String = "vnd.android.cursor.dir/vnd.com.ichi2.anki.deck" } /** * For interacting with Anki's media collection. * * * To insert a file into the media collection use: * * ``` * Uri fileUri = ...; //<-- Use real Uri for media file here * String preferredName = "my_media_file"; //<-- Use preferred name for inserted media file here * ContentResolver cr = getContentResolver(); * ContentValues cv = new ContentValues(); * cv.put(AnkiMedia.FILE_URI, fileUri.toString()); * cv.put(AnkiMedia.PREFERRED_NAME, "file_name"); * Uri insertedFile = cr.insert(AnkiMedia.CONTENT_URI, cv); * ``` */ public object AnkiMedia { /** * Content Uri for the MEDIA row of the CardContentProvider */ @JvmField // required for Java API public val CONTENT_URI: Uri = Uri.withAppendedPath(AUTHORITY_URI, "media") /** * Uri.toString() which points to the media file that is to be inserted. */ public const val FILE_URI: String = "file_uri" /** * The preferred name for the file that will be inserted/copied into collection.media */ public const val PREFERRED_NAME: String = "preferred_name" } }
gpl-3.0
a8140e3ef29b2af44f824d217186ba62
48.275333
155
0.488804
4.945249
false
false
false
false
akvo/akvo-flow-mobile
domain/src/main/java/org/akvo/flow/domain/entity/ParcelUtils.kt
1
2015
/* * Copyright (C) 2021 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo Flow. * * Akvo Flow 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. * * Akvo Flow 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 Akvo Flow. If not, see <http://www.gnu.org/licenses/>. */ package org.akvo.flow.domain.entity import android.os.Bundle import android.os.Parcel import android.os.Parcelable import java.util.ArrayList interface KParcelable : Parcelable { override fun describeContents() = 0 override fun writeToParcel(parcel: Parcel, flags: Int) } inline fun <reified T> parcelableCreator( crossinline create: (Parcel) -> T) = object : Parcelable.Creator<T> { override fun createFromParcel(source: Parcel) = create(source) override fun newArray(size: Int) = arrayOfNulls<T>(size) } // Parcel extensions fun Parcel.safeReadBoolean() = readInt() != 0 fun Parcel.safeWriteBoolean(value: Boolean) = writeInt(if (value) 1 else 0) fun Parcel.readStringNonNull(): String { val unParceled = readString() return unParceled ?: unParceled ?: "" } fun Parcel.createStringArrayNonNull(): ArrayList<String> { val unParceled = createStringArrayList() return unParceled ?: unParceled ?: arrayListOf() } fun <T> Parcel.createTypedArrayNonNull(creator: Parcelable.Creator<T>): MutableList<T> { val unParceled = createTypedArray(creator) return unParceled?.toMutableList() ?: mutableListOf() } fun Parcel.safeReadBundle(): Bundle { return readBundle(Bundle::class.java.classLoader) ?: Bundle() }
gpl-3.0
ffa33d8d9d43c35ee1df3789cbbebd8d
32.032787
88
0.730025
4.03
false
false
false
false
sksamuel/elasticsearch-river-neo4j
streamops-endpoints/src/main/kotlin/com/octaldata/endpoints/integration/integrationEndpoints.kt
1
5466
package com.octaldata.endpoints.integration import com.octaldata.datastore.IntegrationDatastore import com.octaldata.domain.integrations.Integration import com.octaldata.domain.integrations.IntegrationConfig import com.octaldata.domain.integrations.IntegrationId import com.octaldata.domain.integrations.IntegrationName import com.octaldata.domain.integrations.IntegrationType import com.octaldata.endpoints.withIntegrationId import com.octaldata.streamops.ktor.withRequest import com.sksamuel.tabby.results.flatMap import io.ktor.application.call import io.ktor.http.HttpStatusCode import io.ktor.response.respond import io.ktor.routing.Route import io.ktor.routing.delete import io.ktor.routing.get import io.ktor.routing.post import io.ktor.routing.put import io.ktor.util.getOrFail import mu.KotlinLogging private val logger = KotlinLogging.logger { } fun Route.integrationEndpoints( datastore: IntegrationDatastore, ) { // returns all integrations get("/api/integration") { datastore.findAll().fold( { call.respond(HttpStatusCode.OK, it) }, { call.respond(HttpStatusCode.InternalServerError, it) } ) } // adds a new integration post("/api/integration") { withRequest<AddIntegrationRequest> { req -> runCatching { when (req.type) { IntegrationType.Datadog -> IntegrationConfig.Datadog( req.apiKey ?: "", req.batchSize?.toIntOrNull(), req.flushSeconds?.toIntOrNull() ) IntegrationType.Grafana -> IntegrationConfig.Grafana( req.apiKey ?: "", ) IntegrationType.Humio -> IntegrationConfig.Humio( req.apiKey ?: "", ) IntegrationType.Kairos -> IntegrationConfig.EmptyConfig IntegrationType.Snowflake -> IntegrationConfig.Snowflake( serverName = req.serverName!!, user = req.user!!, password = req.password!!, ) IntegrationType.Prometheus -> IntegrationConfig.Prometheus( host = req.host!!, port = req.port!!, ) IntegrationType.AppOptics -> IntegrationConfig.Humio( req.apiKey ?: "", ) } }.flatMap { config -> datastore.insert( Integration( id = IntegrationId.generate(), name = req.name, type = req.type, config = config, ) ) }.fold( { call.respond(HttpStatusCode.OK, it) }, { logger.warn(it) { "Error adding integration" } call.respond(HttpStatusCode.InternalServerError, it) } ) } } // updates an existing integration put("/api/integration/{integrationId}") { withRequest<UpdateIntegrationRequest> { req -> val i = datastore.getById(IntegrationId(call.parameters.getOrFail("integrationId"))).getOrThrow()!! runCatching { when (i.type) { IntegrationType.Datadog -> IntegrationConfig.Datadog( req.apiKey ?: "", req.batchSize?.toIntOrNull(), req.flushSeconds?.toIntOrNull() ) IntegrationType.Grafana -> IntegrationConfig.Grafana( req.apiKey ?: "", ) IntegrationType.Humio -> IntegrationConfig.Humio( req.apiKey ?: "", ) IntegrationType.Kairos -> IntegrationConfig.EmptyConfig IntegrationType.Snowflake -> IntegrationConfig.Snowflake( serverName = req.serverName!!, user = req.user!!, password = req.password!!, ) IntegrationType.Prometheus -> IntegrationConfig.Prometheus( host = req.host!!, port = req.port!!, ) IntegrationType.AppOptics -> IntegrationConfig.Humio( req.apiKey ?: "", ) } }.map { config -> datastore.update(i.id, req.name, config) } }.fold( { call.respond(HttpStatusCode.OK, it) }, { logger.warn(it) { "Error adding integration" } call.respond(HttpStatusCode.InternalServerError, it) } ) } // deletes an integration identified by the given id delete("/api/integration/{integrationId}") { withIntegrationId { integrationId -> datastore.delete(integrationId).fold( { call.respond(HttpStatusCode.OK, it) }, { call.respond(HttpStatusCode.InternalServerError, it) } ) } } } data class AddIntegrationRequest( val name: IntegrationName, val type: IntegrationType, val apiKey: String?, val host: String?, val port: Int?, val batchSize: String?, val flushSeconds: String?, val serverName: String?, val user: String?, val password: String?, ) data class UpdateIntegrationRequest( val name: IntegrationName, val apiKey: String?, val host: String?, val port: Int?, val batchSize: String?, val flushSeconds: String?, val serverName: String?, val user: String?, val password: String?, )
apache-2.0
4a81f994e5077dd11de3cbb845af9111
32.539877
108
0.57757
4.871658
false
true
false
false
wordpress-mobile/WordPress-Stores-Android
example/src/test/java/org/wordpress/android/fluxc/network/rest/wpcom/stats/time/AuthorsRestClientTest.kt
1
6792
package org.wordpress.android.fluxc.network.rest.wpcom.stats.time import com.android.volley.RequestQueue import com.android.volley.VolleyError import com.google.gson.Gson import com.google.gson.GsonBuilder import com.nhaarman.mockitokotlin2.KArgumentCaptor import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.argumentCaptor import com.nhaarman.mockitokotlin2.eq import com.nhaarman.mockitokotlin2.isNull import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.network.BaseRequest.BaseNetworkError import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType.NETWORK_ERROR import org.wordpress.android.fluxc.network.UserAgent import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequest.WPComGsonNetworkError import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder.Response import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder.Response.Success import org.wordpress.android.fluxc.network.rest.wpcom.auth.AccessToken import org.wordpress.android.fluxc.network.rest.wpcom.stats.time.AuthorsRestClient.AuthorsResponse import org.wordpress.android.fluxc.network.utils.StatsGranularity import org.wordpress.android.fluxc.network.utils.StatsGranularity.DAYS import org.wordpress.android.fluxc.network.utils.StatsGranularity.MONTHS import org.wordpress.android.fluxc.network.utils.StatsGranularity.WEEKS import org.wordpress.android.fluxc.network.utils.StatsGranularity.YEARS import org.wordpress.android.fluxc.store.StatsStore.StatsErrorType.API_ERROR import org.wordpress.android.fluxc.test import java.util.Date @RunWith(MockitoJUnitRunner::class) class AuthorsRestClientTest { @Mock private lateinit var dispatcher: Dispatcher @Mock private lateinit var wpComGsonRequestBuilder: WPComGsonRequestBuilder @Mock private lateinit var site: SiteModel @Mock private lateinit var requestQueue: RequestQueue @Mock private lateinit var accessToken: AccessToken @Mock private lateinit var userAgent: UserAgent @Mock private lateinit var statsUtils: StatsUtils private val gson: Gson = GsonBuilder().create() private lateinit var urlCaptor: KArgumentCaptor<String> private lateinit var paramsCaptor: KArgumentCaptor<Map<String, String>> private lateinit var restClient: AuthorsRestClient private val siteId: Long = 12 private val pageSize = 5 private val stringDate = "2018-10-10" private val requestedDate = Date(0) @Before fun setUp() { urlCaptor = argumentCaptor() paramsCaptor = argumentCaptor() restClient = AuthorsRestClient( dispatcher, wpComGsonRequestBuilder, null, requestQueue, accessToken, userAgent, gson, statsUtils ) whenever(statsUtils.getFormattedDate(eq(requestedDate), isNull())).thenReturn(stringDate) } @Test fun `returns authors by day success response`() = test { testSuccessResponse(DAYS) } @Test fun `returns authors by day error response`() = test { testErrorResponse(DAYS) } @Test fun `returns authors by week success response`() = test { testSuccessResponse(WEEKS) } @Test fun `returns authors by week error response`() = test { testErrorResponse(WEEKS) } @Test fun `returns authors by month success response`() = test { testSuccessResponse(MONTHS) } @Test fun `returns authors by month error response`() = test { testErrorResponse(MONTHS) } @Test fun `returns authors by year success response`() = test { testSuccessResponse(YEARS) } @Test fun `returns authors by year error response`() = test { testErrorResponse(YEARS) } private suspend fun testSuccessResponse(period: StatsGranularity) { val response = mock<AuthorsResponse>() initAuthorsResponse(response) val responseModel = restClient.fetchAuthors(site, period, requestedDate, pageSize, false) assertThat(responseModel.response).isNotNull() assertThat(responseModel.response).isEqualTo(response) assertThat(urlCaptor.lastValue) .isEqualTo("https://public-api.wordpress.com/rest/v1.1/sites/12/stats/top-authors/") assertThat(paramsCaptor.lastValue).isEqualTo( mapOf( "max" to pageSize.toString(), "period" to period.toString(), "date" to stringDate ) ) } private suspend fun testErrorResponse(period: StatsGranularity) { val errorMessage = "message" initAuthorsResponse( error = WPComGsonNetworkError( BaseNetworkError( NETWORK_ERROR, errorMessage, VolleyError(errorMessage) ) ) ) val responseModel = restClient.fetchAuthors(site, period, requestedDate, pageSize, false) assertThat(responseModel.error).isNotNull() assertThat(responseModel.error.type).isEqualTo(API_ERROR) assertThat(responseModel.error.message).isEqualTo(errorMessage) } private suspend fun initAuthorsResponse( data: AuthorsResponse? = null, error: WPComGsonNetworkError? = null ): Response<AuthorsResponse> { return initResponse(AuthorsResponse::class.java, data ?: mock(), error) } private suspend fun <T> initResponse( kclass: Class<T>, data: T, error: WPComGsonNetworkError? = null, cachingEnabled: Boolean = false ): Response<T> { val response = if (error != null) Response.Error<T>(error) else Success(data) whenever( wpComGsonRequestBuilder.syncGetRequest( eq(restClient), urlCaptor.capture(), paramsCaptor.capture(), eq(kclass), eq(cachingEnabled), any(), eq(false) ) ).thenReturn(response) whenever(site.siteId).thenReturn(siteId) return response } }
gpl-2.0
d948316b65c988e0cbad39c8f7d88957
36.524862
100
0.680801
4.975824
false
true
false
false
shadowfox-ninja/ShadowUtils
shadow-core/src/main/java/tech/shadowfox/shadow/core/networking/NetworkProvider.kt
1
5321
@file:Suppress("unused") package tech.shadowfox.shadow.core.networking import tech.shadowfox.shadow.core.utils.ResetManager import tech.shadowfox.shadow.core.utils.ResettableLazy import tech.shadowfox.shadow.core.utils.ResettableLazyManager import okhttp3.* import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.io.File import java.util.HashMap import java.util.HashSet /** * Copyright 2017 Camaron Crowe * * 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. **/ @Suppress("MemberVisibilityCanPrivate") sealed class NetworkProvider { protected fun addApiResetManager(key: String, manager: ResetManager) { resetManagers.getOrPut(key, { hashSetOf() }).add(manager) } companion object { private val httpClientInjectors: MutableList<(OkHttpClient.Builder) -> Unit> = arrayListOf() private val resetManagers: HashMap<String, HashSet<ResetManager>> = hashMapOf() fun resetAll() { resetManagers.keys.forEach { key -> resetManagers[key]!!.forEach { it.reset() } } } fun reset(key: String) { resetManagers[key]?.forEach(ResetManager::reset) } fun addBaseClientInjector(injector: (OkHttpClient.Builder) -> Unit) { httpClientInjectors.add(injector) resetAll() } fun baseClient() = OkHttpClient.Builder().apply { httpClientInjectors.forEach { it(this) } } fun initCache(cacheDir: File, cacheSize: Long = (10 * 1024 * 1024), networkAvailable: () -> Boolean = { true }) { addBaseClientInjector { it.cache(Cache(cacheDir, cacheSize)) it.addInterceptor { chain -> var request = chain.request() request = if (networkAvailable()) { request.newBuilder().header("Cache-Control", "public, max-age=" + 60).build() } else { request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build() } chain.proceed(request) } } } fun <S> createNoAuthService(clazz: Class<S>, baseURL: String, client: OkHttpClient.Builder = baseClient()): S { return createService(clazz,null, baseURL = baseURL, client = client) } fun <S> createBasicService(clazz: Class<S>, basic: String, baseURL: String, client: OkHttpClient.Builder = baseClient()): S { return createService(clazz, "Basic $basic", baseURL = baseURL, client = client) } fun <S> createService(clazz: Class<S>, token: String?, baseURL: String, client: OkHttpClient.Builder = baseClient()): S { client.addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }) if (token != null) { client.addInterceptor { chain -> val original: Request = chain.request() val request: Request = original.newBuilder() .header("Accept", "application/json") .header("Authorization", token) .method(original.method(), original.body()) .build() val response = chain.proceed(request) response } } return Retrofit.Builder() .client(client.build()) .baseUrl(baseURL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build().create(clazz) } } } @Suppress("MemberVisibilityCanPrivate") abstract class NetworkInterface<out T> : NetworkProvider() { protected val resetManager by lazy { ResettableLazyManager() } protected val resetKey: String = "" init { addApiResetManager(resetKey, resetManager) } /** * Creates lazy api instance using selectApiInterface */ val api: T by ResettableLazy(resetManager) { selectApiInterface() } /** * Resets the api manager */ fun reset() { resetManager.reset() } /** * Creates a standard api instance. */ protected abstract fun createApi(): T /** * Creates an api interface. This generally doesn't need to change, but abstracted for * convenience. */ protected open fun selectApiInterface(): T { return createApi() } }
apache-2.0
8c7e4aef8f11aad020ccdf270e108cb2
33.558442
133
0.603458
4.872711
false
false
false
false
debop/debop4k
debop4k-core/src/main/kotlin/debop4k/core/parallels/Parallels.kt
1
4198
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * 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 debop4k.core.parallels import debop4k.core.cryptography.SECURE_RANDOM import debop4k.core.loggerOf import org.eclipse.collections.api.block.function.Function import org.eclipse.collections.impl.parallel.ParallelIterate import java.util.* /** * 참고 : debop4k.core.collections.ParallelIteratex.Kt */ @Deprecated(message = "Kotlin 으로 구현한 것으로 변환", replaceWith = ReplaceWith("ParallelIteratex")) object Parallels { private val log = loggerOf(javaClass) val random: Random = SECURE_RANDOM val processCount: Int by lazy { Runtime.getRuntime().availableProcessors() } val workerCount: Int by lazy { processCount * 2 } val DEFAULT_MIN_FORK_SIZE = 10000 val AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors() val TASK_RATIO = 2 val DEFAULT_PARALLEL_TASK_COUNT = ParallelIterate.getDefaultTaskCount() val EXECUTOR_SERVICE = ParallelIterate.newPooledExecutor(ParallelIterate::class.java.simpleName, true) fun <T : Comparable<T>, V> mapAsOrdered(items: Iterable<T>, mapper: (T) -> V): Collection<V> = ParallelIterate.collect(items, mapper, true) fun <T, V> map(items: Iterable<T>, mapper: (T) -> V): Collection<V> = ParallelIterate.collect(items, mapper) fun run(count: Int, action: () -> Unit): Unit { run(0, count - 1, action) } fun run(start: Int, endInclusive: Int, action: () -> Unit): Unit { run(IntRange(start, endInclusive), action) } fun run(range: IntProgression, action: () -> Unit): Unit { ParallelIterate.forEach(range.asIterable(), { action.invoke() }) } fun runAction(count: Int, action1: (Int) -> Unit): Unit { runAction(0, count - 1, action1) } fun runAction(start: Int, endInclusive: Int, action1: (Int) -> Unit): Unit { runAction(IntRange(start, endInclusive), action1) } fun runAction(range: IntProgression, action1: (Int) -> Unit): Unit { ParallelIterate.forEach(range.asIterable(), { action1(it) }) } fun <T> runEach(elements: Iterable<T>, block: (T) -> Unit): Unit { ParallelIterate.forEach(elements, { block(it) }) } fun <T> runEach(elements: Iterable<T>, batchSize: Int, block: (T) -> Unit): Unit { ParallelIterate.forEach(elements, { block(it) }, batchSize) } fun <T, V> call(count: Int, func: () -> V): Collection<V> = call<T, V>(0, count - 1, func) fun <T, V> call(start: Int, endInclusive: Int, func: () -> V): Collection<V> = call<T, V>(IntRange(start, endInclusive), func) fun <T, V> call(range: IntProgression, func: () -> V): Collection<V> = ParallelIterate.collect(range.asIterable(), { func() }) fun <V> callFunction(count: Int, func: (Int) -> V): Collection<V> = callFunction(0, count - 1, func) fun <V> callFunction(start: Int, endInclusive: Int, func: (Int) -> V): Collection<V> = callFunction(IntRange(start, endInclusive), func) fun <V> callFunction(range: IntProgression, func: (Int) -> V): Collection<V> = ParallelIterate.collect(range.asIterable(), { func(it) }) fun <T, V> callEach(elements: Iterable<T>, func: (T) -> V): Collection<V> = ParallelIterate.collect(elements, { func(it) }) fun <T, V> callEach(elements: Iterable<T>, batchSize: Int, func: (T) -> V): Collection<V> = ParallelIterate.collect(elements, Function { func(it) }, emptyList(), batchSize, EXECUTOR_SERVICE, true) }
apache-2.0
51010e27ae437833088d1314e4dd0f8c
35.622807
104
0.650216
3.710222
false
false
false
false
chandilsachin/DietTracker
app/src/main/java/com/chandilsachin/diettracker/view_model/FoodDetailsViewModel.kt
1
1282
package com.chandilsachin.diettracker.view_model import android.app.Application import android.arch.lifecycle.AndroidViewModel import android.arch.lifecycle.MutableLiveData import com.chandilsachin.diettracker.database.Food import com.chandilsachin.diettracker.database.PersonalizedFood import com.chandilsachin.diettracker.model.Date import com.chandilsachin.diettracker.repository.FoodRepository import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread /** * Created by sachin on 27/5/17. */ class FoodDetailsViewModel(application: Application) : AndroidViewModel(application) { private val repo = FoodRepository() val foodDetails = MutableLiveData<Food>() fun fetchFoodDetails(foodId: Long) { doAsync { var list = repo.getFoodDetails(getApplication(), foodId) uiThread { foodDetails.value = list } } } fun saveFoodDetails(food: PersonalizedFood) { repo.saveFood(getApplication(), food) } fun updateFoodDetails(food: PersonalizedFood) { repo.updateFood(getApplication(), food) } fun getFoodQuantityOn(foodId:Long, date:Date):Int{ val item = repo.getFoodOn(date, foodId, getApplication()) return item?.quantity ?: 0 } }
gpl-3.0
b5746943643d016b4b0179e24b605afa
28.837209
86
0.719969
4.375427
false
false
false
false
ageery/kwicket
kwicket-wicket-core/src/main/kotlin/org/kwicket/wicket/core/markup/html/form/KTextField.kt
1
3890
package org.kwicket.wicket.core.markup.html.form import org.apache.wicket.behavior.Behavior import org.apache.wicket.markup.html.form.TextField import org.apache.wicket.model.IModel import org.kwicket.component.init import kotlin.reflect.KClass /** * [TextField] with named and default constructor arguments. * * @param T type of the backing model * @param id Wicket markup id * @param model model for the component * @param type type of the backing model * @param required whether a value is required for the field * @param outputMarkupId whether to include an HTML id for the component in the markup * @param outputMarkupPlaceholderTag whether to include a placeholder tag for the component in the markup when the * component is not visible * @param label model of the label associated with the field * @param visible whether the component is visible * @param enabled whether the component is enabled * @param escapeModelStrings whether model strings should be escaped * @param renderBodyOnly whether the tag associated with the component should be included in the markup * @param behaviors list of [Behavior] to add to the component */ open class KTextField<T : Any>( id: String, model: IModel<T?>? = null, type: KClass<T>? = null, required: Boolean? = null, outputMarkupId: Boolean? = null, outputMarkupPlaceholderTag: Boolean? = null, label: IModel<String>? = null, visible: Boolean? = null, enabled: Boolean? = null, escapeModelStrings: Boolean? = null, renderBodyOnly: Boolean? = null, behaviors: List<Behavior>? = null ) : TextField<T>(id, model, type?.let { if (required != null && required) it.java else it.javaObjectType }) { /** * Creates a [KTextField]. * * @param id Wicket markup id * @param model model for the component * @param type type of the backing model * @param required whether a value is required for the field * @param outputMarkupId whether to include an HTML id for the component in the markup * @param outputMarkupPlaceholderTag whether to include a placeholder tag for the component in the markup when the * component is not visible * @param label model of the label associated with the field * @param visible whether the component is visible * @param enabled whether the component is enabled * @param escapeModelStrings whether model strings should be escaped * @param renderBodyOnly whether the tag associated with the component should be included in the markup * @param behavior [Behavior] to add to the component */ constructor( id: String, model: IModel<T?>? = null, type: KClass<T>? = null, required: Boolean? = null, outputMarkupId: Boolean? = null, outputMarkupPlaceholderTag: Boolean? = null, label: IModel<String>? = null, visible: Boolean? = null, enabled: Boolean? = null, escapeModelStrings: Boolean? = null, renderBodyOnly: Boolean? = null, behavior: Behavior ) : this( id = id, model = model, type = type, required = required, outputMarkupId = outputMarkupId, outputMarkupPlaceholderTag = outputMarkupPlaceholderTag, label = label, visible = visible, enabled = enabled, escapeModelStrings = escapeModelStrings, renderBodyOnly = renderBodyOnly, behaviors = listOf(behavior) ) init { init( outputMarkupPlaceholderTag = outputMarkupPlaceholderTag, outputMarkupId = outputMarkupId, visible = visible, enabled = enabled, behaviors = behaviors, required = required, label = label, renderBodyOnly = renderBodyOnly, escapeModelStrings = escapeModelStrings ) } }
apache-2.0
d439d43a03f163875e75558c3f4f09b3
37.514851
118
0.676607
4.899244
false
false
false
false
QiBaobin/clean-architecture
data/src/main/kotlin/bob/clean/data/store/cache/UserCache.kt
1
809
package bob.clean.data.store.cache import bob.clean.data.model.UserInfo import bob.clean.data.store.Cache import bob.clean.data.store.UserStore interface UserCache : UserStore { fun isCachedForName(name: String): Boolean } class UserCacheImpl(private val cache: Cache) : UserCache { private val prefix_name = "name" override fun login(name: String, password: String): UserInfo? { val info = cache.get<UserInfo>(createKey(prefix_name, name)) return if (password.equals(info?.password)) info else null } override fun logout() { // nothing need to do here } override fun isCachedForName(name: String) = cache.get<UserInfo>(createKey(prefix_name, name)) != null private fun createKey(prefix: String, value: String) = "user_cache_" + prefix + value }
apache-2.0
84490b850151c98de224daa43f31416f
30.115385
106
0.704574
3.816038
false
false
false
false
AoEiuV020/PaNovel
api/src/main/java/cc/aoeiuv020/panovel/api/site/siluke.kt
1
2715
package cc.aoeiuv020.panovel.api.site import cc.aoeiuv020.base.jar.ownTextListSplitWhitespace import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext import cc.aoeiuv020.panovel.api.firstIntPattern import cc.aoeiuv020.panovel.api.firstTwoIntPattern import java.net.URL /** * Created by AoEiuV020 on 2018.06.05-18:24:49. */ class Siluke : DslJsoupNovelContext() {init { hide = true site { name = "思路客" baseUrl = "https://www.siluke.org" logo = "http://www.siluke.org/templates/images/logo.png" } search { get { // http://www.siluke.org/modules/article/search.php?searchtype=articlename&searchkey=%B6%BC%CA%D0&page=1 charset = "GBK" url = "/modules/article/search.php" data { "searchtype" to "articlename" "searchkey" to it // 加上&page=1可以避开搜索时间间隔的限制, // 也可以通过不加载cookies避开搜索时间间隔的限制, "page" to "1" } } document { if (URL(root.ownerDocument().location()).path.startsWith("/book/")) { single { name("#content > dd:nth-child(1) > h1") author("#at > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(4) > a:nth-child(1)") } } else { items(".grid > tbody:nth-child(2) > tr:not(:nth-child(1))") { name("> td:nth-child(1) > a:nth-child(1)") author("> td:nth-child(3)") } } } } // http://www.siluke.org/book/68917/ bookIdRegex = firstIntPattern detailPageTemplate = "/book/%s/" detail { document { novel { name("#content > dd:nth-child(1) > h1") author("#at > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(4) > a:nth-child(1)") } image(".hst > img:nth-child(1)") update("#at > tbody > tr:nth-child(2) > td:nth-child(6)", format = "yyyy-MM-dd") introduction(".intro") } } // http://www.siluke.org/book/68917/index.html chaptersPageTemplate = "/book/%s/index.html" chapters { document { items("#at > tbody:nth-child(1) > tr > td > a") } } // http://www.siluke.org/book/68917/20835244.html bookIdWithChapterIdRegex = firstTwoIntPattern contentPageTemplate = "/book/%s.html" content { document { items("#contents") { it.textNodes().drop(1).flatMap { it.ownTextListSplitWhitespace() } } } } } }
gpl-3.0
a52865091fa1bf04b4f6966f196d60eb
32.379747
116
0.525597
3.563514
false
false
false
false
NextFaze/dev-fun
devfun-annotations/src/main/java/com/nextfaze/devfun/function/FunctionDefinitions.kt
1
3410
package com.nextfaze.devfun.function import com.nextfaze.devfun.DebugException import com.nextfaze.devfun.category.CategoryDefinition import java.lang.reflect.Method import kotlin.reflect.KClass /** * Definition for user-supplied arguments (usually supplied from a [FunctionTransformer]). */ typealias FunctionArgs = List<Any?>? /** * Definition of generated function to call that invokes the function definition. * * - The __receiver__ is the object to be invoked against (pass in `null` for static/`object`) types. * Use convenience extension functions (e.g. [FunctionItem]`.receiverClassForInvocation`) to more easily locate/resolve receiver instance. * * - The __args__ is the arguments for the method, matching the methods argument count and ordering. * Similarly to receiver, convenience extension functions exist to assist with argument resolution. * * Note: At present nullable types are not inherently supported. * KAPT does not provide enough information to determine if a type is nullable or not (and there are other * issues to be considered). It is intended to be permitted in the future. * * @return Invocation of function. */ typealias FunctionInvoke = (receiver: Any?, args: List<Any?>) -> Any? /** * Functions/methods annotated with [DeveloperFunction] will be defined using this interface at compile time. * * Definitions will be convert to items via [FunctionTransformer]. * * @see FunctionItem */ interface FunctionDefinition { /** * The method of this function was defined. */ val method: Method /** * The class where this item was defined. */ val clazz: KClass<out Any> get() = method.declaringClass.kotlin /** * The name of this item as taken from [DeveloperFunction.value]. * * If unset the method name split-camel-case will be used. */ val name: CharSequence get() = method.name.splitCamelCase().substringBefore("\$") // remove internal $suffix part /** * The category for this definition as taken from [DeveloperFunction.category]. * * This value is ignored when it is empty. */ val category: CategoryDefinition? get(): CategoryDefinition? = null /** * Required API to allow this item to be shown as taken from [DeveloperFunction.requiresApi]. * * This value is ignored when it is `<= 0`. */ val requiresApi: Int get() = 0 /** * Function transformer for this instance as taken from [DeveloperFunction.transformer]. * * Adds to and/or transforms the standard invoke call. */ val transformer: KClass<out FunctionTransformer> get() = SingleFunctionTransformer::class /** * Called when this item is to be invoked. * * Be aware if invoking this directly; no error handling is provided. * You should use `devFun.get<Invoker>()` for missing arguments, user input, and exception handling. */ val invoke: FunctionInvoke } /** * Function invocations will be wrapped by this. */ interface InvokeResult { /** * The return value of the function invocation. * * [exception] will be non-null on failure - (not including [DebugException], which will not be caught). */ val value: Any? /** * Any exceptions thrown while attempting to invoke the function. * * This will be `null` on success. */ val exception: Throwable? }
apache-2.0
4eb44967e0437d22b809adcb61f19e91
32.431373
140
0.692669
4.457516
false
false
false
false
vitaorganizer/vitaorganizer
src/com/soywiz/vitaorganizer/FileRules.kt
2
712
package com.soywiz.vitaorganizer object FileRules { fun isEboot(path: String) = path == "eboot.bin" fun isSceSysFolder(path: String) = path.startsWith("sce_sys/") // Skip these files since it seems that having them prevents the vpk from installing (this should allow to install dumps with maidumptool) fun isClearsignOrKeystone(path: String) = (path == "sce_sys/clearsign") || (path == "sce_sys/keystone") fun includeInSmallVpk(path: String) = isEboot(path) || (isSceSysFolder(path) && !isClearsignOrKeystone(path)) fun includeInBigVpk(path: String) = !isClearsignOrKeystone(path) // Skip files already installed in the VPK fun includeInData(path: String) = !isEboot(path) && !isSceSysFolder(path) }
gpl-3.0
f7022d41eef7daaee9f4d97839732f33
43.5625
139
0.745787
3.266055
false
false
false
false
tommbaker/Tower
Android/src/org/droidplanner/android/fragments/widget/diagnostics/EkfFlagsViewer.kt
3
3799
package org.droidplanner.android.fragments.widget.diagnostics import android.graphics.drawable.Drawable import android.os.Bundle import android.support.annotation.StringRes import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.o3dr.services.android.lib.drone.property.EkfStatus import org.droidplanner.android.R import org.droidplanner.android.fragments.widget.diagnostics.BaseWidgetDiagnostic import java.util.* import kotlin.properties.Delegates /** * Created by Fredia Huya-Kouadio on 9/15/15. */ public class EkfFlagsViewer : BaseWidgetDiagnostic() { companion object { @StringRes public val LABEL_ID: Int = R.string.title_ekf_flags_viewer } private val ekfFlagsViews: HashMap<EkfStatus.EkfFlags, TextView?> = HashMap() private val okFlagDrawable: Drawable? by lazy(LazyThreadSafetyMode.NONE) { resources?.getDrawable(R.drawable.ic_check_box_green_500_24dp) } private val badFlagDrawable: Drawable? by lazy(LazyThreadSafetyMode.NONE) { resources?.getDrawable(R.drawable.ic_cancel_red_500_24dp) } private val unknownFlagDrawable: Drawable? by lazy(LazyThreadSafetyMode.NONE) { resources?.getDrawable(R.drawable.ic_help_orange_500_24dp) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater?.inflate(R.layout.fragment_ekf_flags_viewer, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?){ super.onViewCreated(view, savedInstanceState) setupEkfFlags(view) } override fun disableEkfView() { disableEkfFlags() } override fun updateEkfView(ekfStatus: EkfStatus) { updateEkfFlags(ekfStatus) } private fun disableEkfFlags(){ for(flagView in ekfFlagsViews.values()) flagView?.setCompoundDrawablesWithIntrinsicBounds(null, null, unknownFlagDrawable, null) } private fun updateEkfFlags(ekfStatus: EkfStatus){ for((flag, flagView) in ekfFlagsViews){ val isFlagSet = if(flag === EkfStatus.EkfFlags.EKF_CONST_POS_MODE) !ekfStatus.isEkfFlagSet(flag) else ekfStatus.isEkfFlagSet(flag) val flagDrawable = if(isFlagSet) okFlagDrawable else badFlagDrawable flagView?.setCompoundDrawablesWithIntrinsicBounds(null, null, flagDrawable, null) } } private fun setupEkfFlags(view: View){ ekfFlagsViews.put(EkfStatus.EkfFlags.EKF_ATTITUDE, view.findViewById(R.id.ekf_attitude_flag) as TextView?) ekfFlagsViews.put(EkfStatus.EkfFlags.EKF_CONST_POS_MODE, view.findViewById(R.id.ekf_const_pos_flag) as TextView?) ekfFlagsViews.put(EkfStatus.EkfFlags.EKF_VELOCITY_VERT, view.findViewById(R.id.ekf_velocity_vert_flag) as TextView?) ekfFlagsViews.put(EkfStatus.EkfFlags.EKF_VELOCITY_HORIZ, view.findViewById(R.id.ekf_velocity_horiz_flag) as TextView?) ekfFlagsViews.put(EkfStatus.EkfFlags.EKF_POS_HORIZ_REL, view.findViewById(R.id.ekf_position_horiz_rel_flag) as TextView?) ekfFlagsViews.put(EkfStatus.EkfFlags.EKF_POS_HORIZ_ABS, view.findViewById(R.id.ekf_position_horiz_abs_flag) as TextView?) ekfFlagsViews.put(EkfStatus.EkfFlags.EKF_PRED_POS_HORIZ_ABS, view.findViewById(R.id.ekf_position_horiz_pred_abs_flag) as TextView?) ekfFlagsViews.put(EkfStatus.EkfFlags.EKF_PRED_POS_HORIZ_REL, view.findViewById(R.id.ekf_position_horiz_pred_rel_flag) as TextView?) ekfFlagsViews.put(EkfStatus.EkfFlags.EKF_POS_VERT_AGL, view.findViewById(R.id.ekf_position_vert_agl_flag) as TextView?) ekfFlagsViews.put(EkfStatus.EkfFlags.EKF_POS_VERT_ABS, view.findViewById(R.id.ekf_position_vert_abs_flag) as TextView?) } }
gpl-3.0
7a2f98ddac607ccfabd6df5311a0a234
45.91358
142
0.744933
3.638889
false
false
false
false
ofalvai/BPInfo
app/src/main/java/com/ofalvai/bpinfo/api/bkkinfo/BkkInfoClient.kt
1
20002
/* * Copyright 2018 Olivér Falvai * * 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.ofalvai.bpinfo.api.bkkinfo import android.content.Context import android.content.SharedPreferences import android.graphics.Color import android.net.Uri import androidx.annotation.ColorInt import com.android.volley.DefaultRetryPolicy import com.android.volley.RequestQueue import com.android.volley.toolbox.JsonObjectRequest import com.google.firebase.crashlytics.FirebaseCrashlytics import com.google.firebase.perf.FirebasePerformance import com.google.firebase.perf.metrics.Trace import com.ofalvai.bpinfo.R import com.ofalvai.bpinfo.api.AlertApiClient import com.ofalvai.bpinfo.model.Alert import com.ofalvai.bpinfo.model.Route import com.ofalvai.bpinfo.model.RouteType import com.ofalvai.bpinfo.ui.alertlist.AlertListType import com.ofalvai.bpinfo.util.LocaleManager import com.ofalvai.bpinfo.util.apiTimestampToDateTime import com.ofalvai.bpinfo.util.toArray import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import org.threeten.bp.ZonedDateTime import timber.log.Timber import java.util.* class BkkInfoClient( private val requestQueue: RequestQueue, private val sharedPreferences: SharedPreferences, private val context: Context ) : AlertApiClient { companion object { /** * The API is so slow we have to increase the default Volley timeout. * Response time increases the most when there's an alert with many affected routes. */ private const val TIMEOUT_MS = 5000 private const val API_BASE_URL = "https://bkk.hu/apps/bkkinfo/" private const val API_ENDPOINT_HU = "json.php" private const val API_ENDPOINT_EN = "json_en.php" private const val PARAM_ALERT_LIST = "?lista" private const val PARAM_ALERT_DETAIL = "id" private const val DETAIL_WEBVIEW_BASE_URL = "http://m.bkkinfo.hu/alert.php" private const val DETAIL_WEBVIEW_PARAM_ID = "id" /** * Returns a retry policy with increased timeout */ @JvmStatic private val retryPolicy = DefaultRetryPolicy( TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT ) } private var alertDetailTrace: Trace? = null private val languageCode: String = LocaleManager.getCurrentLanguageCode(sharedPreferences) override fun fetchAlertList(callback: AlertApiClient.AlertListCallback) { val url = buildAlertListUrl() Timber.i("API request: %s", url.toString()) val request = JsonObjectRequest( url.toString(), null, { response -> onAlertListResponse(response, callback) }, { error -> callback.onError(error) } ) request.retryPolicy = retryPolicy requestQueue.add(request) } override fun fetchAlert(id: String, alertListType: AlertListType, callback: AlertApiClient.AlertDetailCallback) { val url = buildAlertDetailUrl(id) Timber.i("API request: %s", url.toString()) val request = JsonObjectRequest( url.toString(), null, { response -> onAlertDetailResponse(callback, response) }, { error -> callback.onError(error) } ) request.retryPolicy = retryPolicy requestQueue.add(request) createAndStartTrace("network_alert_detail_bkk") } private fun buildAlertListUrl() = Uri.parse(API_BASE_URL) .buildUpon() .appendEncodedPath(if (languageCode == "hu") API_ENDPOINT_HU else API_ENDPOINT_EN) .appendEncodedPath(PARAM_ALERT_LIST) .build() private fun buildAlertDetailUrl(alertId: String) = Uri.parse(API_BASE_URL) .buildUpon() .appendEncodedPath(if (languageCode == "hu") API_ENDPOINT_HU else API_ENDPOINT_EN) .appendQueryParameter(PARAM_ALERT_DETAIL, alertId) .build() private fun onAlertListResponse(response: JSONObject, callback: AlertApiClient.AlertListCallback) { try { val alertsToday = parseTodayAlerts(response).toMutableList() val alertsFuture = parseFutureAlerts(response) fixFutureAlertsInTodayList(alertsToday, alertsFuture) callback.onAlertListResponse(alertsToday, alertsFuture) } catch (ex: Exception) { callback.onError(ex) } } private fun onAlertDetailResponse( callback: AlertApiClient.AlertDetailCallback, response: JSONObject ) { alertDetailTrace?.stop() try { val alert = parseAlertDetail(response) callback.onAlertResponse(alert) } catch (ex: Exception) { callback.onError(ex) } } @Throws(JSONException::class) private fun parseTodayAlerts(response: JSONObject): List<Alert> { val alerts = ArrayList<Alert>() val isDebugMode = sharedPreferences.getBoolean( context.getString(R.string.pref_key_debug_mode), false ) val activeAlertsList = response.getJSONArray("active") for (i in 0 until activeAlertsList.length()) { try { val alertNode = activeAlertsList.getJSONObject(i) val alert = parseAlert(alertNode) // Some alerts are still listed a few minutes after they ended, we need to hide them, // but still show them if debug mode is enabled val alertEndTime: ZonedDateTime = apiTimestampToDateTime(alert.end) if (alertEndTime.isAfter(ZonedDateTime.now()) || alert.end == 0L || isDebugMode) { alerts.add(alert) } } catch (ex: JSONException) { FirebaseCrashlytics.getInstance().log("Alert parse: failed to parse:\n$ex") } } return alerts } @Throws(JSONException::class) private fun parseFutureAlerts(response: JSONObject): MutableList<Alert> { val alerts = ArrayList<Alert>() // Future alerts are in two groups: near-future and far-future val soonAlertList = response.getJSONArray("soon") for (i in 0 until soonAlertList.length()) { try { val alertNode = soonAlertList.getJSONObject(i) alerts.add(parseAlert(alertNode)) } catch (ex: JSONException) { FirebaseCrashlytics.getInstance().log("Alert parse: failed to parse:\n$ex") } } val futureAlertList = response.getJSONArray("future") for (i in 0 until futureAlertList.length()) { try { val alertNode = futureAlertList.getJSONObject(i) alerts.add(parseAlert(alertNode)) } catch (ex: JSONException) { FirebaseCrashlytics.getInstance().log("Alert parse: failed to parse:\n$ex") } } return alerts } /** * Parses alert details found in the alert list API response * This structure is different than the alert detail API response */ @Throws(JSONException::class) private fun parseAlert(alertNode: JSONObject): Alert { val id = alertNode.getString("id") var start: Long = 0 if (!alertNode.isNull("kezd")) { val beginNode = alertNode.getJSONObject("kezd") start = beginNode.getLong("epoch") } var end: Long = 0 if (!alertNode.isNull("vege")) { val endNode = alertNode.getJSONObject("vege") end = endNode.getLong("epoch") } val timestamp: Long val modifiedNode = alertNode.getJSONObject("modositva") timestamp = modifiedNode.getLong("epoch") val url = getUrl(id) val header = alertNode.getString("elnevezes").capitalize(Locale.getDefault()) val routesArray = alertNode.getJSONArray("jaratokByFajta") val affectedRoutes = parseAffectedRoutes(routesArray) return Alert(id, start, end, timestamp, url, header, null, affectedRoutes, true) } /** * Parses alert details found in the alert detail API response * This structure is different than the alert list API response */ @Throws(JSONException::class) private fun parseAlertDetail(response: JSONObject): Alert { val id = response.getString("id") var start: Long = 0 if (!response.isNull("kezdEpoch")) { start = response.getLong("kezdEpoch") } var end: Long = 0 if (!response.isNull("vegeEpoch")) { end = response.getLong("vegeEpoch") } var timestamp: Long = 0 if (!response.isNull("modEpoch")) { timestamp = response.getLong("modEpoch") } val url = getUrl(id) val header: String // The API returns a header of 3 parts separated by "|" characters. We need the last part. val rawHeader = response.getString("targy") header = rawHeader.split("|")[2].trim().capitalize(Locale.getDefault()) val description: String val descriptionBuilder = StringBuilder() descriptionBuilder.append(response.getString("feed")) val routesArray = response.getJSONObject("jaratok").toArray() for (i in 0 until routesArray.length()) { val routeNode = routesArray.getJSONObject(i) val optionsNode = routeNode.getJSONObject("opciok") if (!optionsNode.isNull("szabad_szoveg")) { val routeTextArray = optionsNode.getJSONArray("szabad_szoveg") for (j in 0 until routeTextArray.length()) { descriptionBuilder.append("<br />") descriptionBuilder.append(routeTextArray.getString(j)) } } } description = descriptionBuilder.toString() val affectedRoutes: List<Route> val routeDetailsNode = response.getJSONObject("jarat_adatok") val affectedRouteIds = response.getJSONObject("jaratok").keys() // Some routes in routeDetailsNode are not affected by the alert, but alternative // recommended routes. The real affected routes' IDs are in "jaratok" affectedRoutes = parseDetailedAffectedRoutes(routeDetailsNode, affectedRouteIds) return Alert(id, start, end, timestamp, url, header, description, affectedRoutes, false) } private fun getUrl(alertId: String): String { return "$DETAIL_WEBVIEW_BASE_URL?$DETAIL_WEBVIEW_PARAM_ID=$alertId" } /** * Parses affected routes found in the alert list API response * This structure is different than the alert detail API response */ @Throws(JSONException::class) private fun parseAffectedRoutes(routesArray: JSONArray): List<Route> { // The API lists multiple affected routes grouped by their vehicle type (bus, tram, etc.) val routes = ArrayList<Route>() for (i in 0 until routesArray.length()) { val routeNode = routesArray.getJSONObject(i) val typeString = routeNode.getString("type") val type = parseRouteType(typeString) val concreteRoutes = routeNode.getJSONArray("jaratok") for (j in 0 until concreteRoutes.length()) { val shortName = concreteRoutes.getString(j).trim() val colors = parseRouteColors(type, shortName) // There's no ID returned by the API, using shortName instead val route = Route( shortName, shortName, null, null, type, colors[0], colors[1], false ) routes.add(route) } } return routes } /** * Parses affected routes found in the alert detail API response * This structure is different than the alert list API response * @param routesNode Details of routes. Some of them are not affected by the alert, only * recommended alternative routes * @param affectedRouteIds IDs of only the affected routes */ @Throws(JSONException::class) private fun parseDetailedAffectedRoutes( routesNode: JSONObject, affectedRouteIds: Iterator<String> ): List<Route> { val routes = ArrayList<Route>() while (affectedRouteIds.hasNext()) { val routeId = affectedRouteIds.next() val routeNode = routesNode.getJSONObject(routeId) val id = routeNode.getString("forte") val shortName = routeNode.getString("szam") val description = routeNode.getString("utvonal") val routeType = parseRouteType(routeNode.getString("tipus")) val color = Color.parseColor("#" + routeNode.getString("szin")) val textColor = Color.parseColor("#" + routeNode.getString("betu")) val route = Route( id, shortName, null, description, routeType, color, textColor, false ) routes.add(route) } routes.sort() return routes } private fun parseRouteType(routeTypeString: String): RouteType { return when (routeTypeString) { "busz" -> RouteType.BUS "ejszakai" -> // Night buses are parsed as buses. Their colors are corrected in parseRouteColors() RouteType.BUS "hajo" -> RouteType.FERRY "villamos" -> RouteType.TRAM "trolibusz" -> RouteType.TROLLEYBUS "metro" -> RouteType.SUBWAY "libego" -> RouteType.CHAIRLIFT "hev" -> RouteType.RAIL "siklo" -> RouteType.FUNICULAR else -> RouteType.OTHER } } /** * Returns the background and foreground colors of the route, because the alert list API * doesn't return them in the response. * Note that the alert detail response contains color values, so the alert detail parsing * doesn't need to call this. * @param type Parsed type of the route. Most of the time this is enough to match the colors * @param shortName Parsed short name (line number) of the route. This is needed because some * route types have different colors for each route (eg. subway, ferry). * @return Array of color-ints: background, foreground */ @ColorInt private fun parseRouteColors(type: RouteType, shortName: String): IntArray { // Color values based on this list of routes: // http://online.winmenetrend.hu/budapest/latest/lines val defaultBackground = "EEEEEE" val defaultText = "BBBBBB" val background: String val text: String when (type) { RouteType.BUS -> when { shortName.matches("^9[0-9][0-9][A-Z]?$".toRegex()) -> { // Night bus numbers start from 900, and might contain one extra letter after // the 3 digits. background = "1E1E1E" text = "FFFFFF" } shortName == "I" -> { // Nostalgia bus background = "FFA417" text = "FFFFFF" } else -> { // Regular bus background = "009FE3" text = "FFFFFF" } } RouteType.FERRY -> if (shortName == "D12") { background = "9A1915" text = "FFFFFF" } else { background = "E50475" text = "FFFFFF" } RouteType.RAIL -> when (shortName) { "H5" -> { background = "821066" text = "FFFFFF" } "H6" -> { background = "884200" text = "FFFFFF" } "H7" -> { background = "EE7203" text = "FFFFFF" } "H8" -> { background = "FF6677" text = "FFFFFF" } "H9" -> { background = "FF6677" text = "FFFFFF" } else -> { background = defaultBackground text = defaultText } } RouteType.TRAM -> { background = "FFD800" text = "000000" } RouteType.TROLLEYBUS -> { background = "FF1609" text = "FFFFFF" } RouteType.SUBWAY -> when (shortName) { "M1" -> { background = "FFD800" text = "000000" } "M2" -> { background = "FF1609" text = "FFFFFF" } "M3" -> { background = "005CA5" text = "FFFFFF" } "M4" -> { background = "19A949" text = "FFFFFF" } else -> { background = defaultBackground text = defaultText } } RouteType.CHAIRLIFT -> { background = "009155" text = "000000" } RouteType.FUNICULAR -> { background = "884200" text = "000000" } RouteType.OTHER -> { background = defaultBackground text = defaultText } } var backgroundColor: Int var textColor: Int try { backgroundColor = Color.parseColor("#$background") textColor = Color.parseColor("#$text") } catch (ex: IllegalArgumentException) { backgroundColor = Color.parseColor("#$defaultBackground") textColor = Color.parseColor("#$defaultText") } return intArrayOf(backgroundColor, textColor) } private fun createAndStartTrace(name: String) { alertDetailTrace = FirebasePerformance.getInstance().newTrace(name) alertDetailTrace?.start() } /** * Alerts scheduled for the current day (and not yet started) appear in the current alerts list. * We need to find them and move to the future alerts list */ private fun fixFutureAlertsInTodayList( alertsToday: MutableList<Alert>, alertsFuture: MutableList<Alert> ) { // Avoiding ConcurrentModificationException when removing from alertsToday val todayIterator = alertsToday.listIterator() while (todayIterator.hasNext()) { val alert = todayIterator.next() val startTime: ZonedDateTime = apiTimestampToDateTime(alert.start) if (startTime.isAfter(ZonedDateTime.now())) { alertsFuture.add(alert) todayIterator.remove() } } } }
apache-2.0
4b06a3cb10819c35260c9916ad3ea654
34.588968
103
0.578221
4.799856
false
false
false
false
FFlorien/AmpachePlayer
app/src/main/java/be/florien/anyflow/data/local/model/DbFilter.kt
1
1342
package be.florien.anyflow.data.local.model import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.PrimaryKey @Entity(foreignKeys = [ ForeignKey( entity = DbFilterGroup::class, parentColumns = arrayOf("id"), childColumns = arrayOf("filterGroup"), onDelete = ForeignKey.CASCADE)]) data class DbFilter( @PrimaryKey(autoGenerate = true) val id: Int?, val clause: String, val joinClause: String?, val argument: String, val displayText: String, val displayImage: String?, val filterGroup: Long) { companion object { const val TITLE_IS = "title =" const val TITLE_CONTAIN = "title LIKE" const val SEARCH = "title AND genre AND artistName AND albumName LIKE" const val GENRE_IS = "song.genre LIKE" const val SONG_ID = "song.id =" const val ARTIST_ID = "song.artistId =" const val ALBUM_ARTIST_ID = "song.albumArtistId =" const val ALBUM_ID = "song.albumId =" const val PLAYLIST_ID = "playlistSongs.playlistId =" const val PLAYLIST_ID_JOIN = "LEFT JOIN playlistSongs on song.id = playlistSongs.songId" const val DOWNLOADED = "song.local IS NOT NULL" const val NOT_DOWNLOADED = "song.local IS NULL" } }
gpl-3.0
69221743e3932e97d9f20f07ea4d7884
35.297297
96
0.632638
4.315113
false
false
false
false
ohmae/mmupnp
mmupnp/src/main/java/net/mm2d/upnp/log/DefaultSender.kt
1
2041
/* * Copyright (c) 2019 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.upnp.log /** * Default implementation of [Sender]. * * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ object DefaultSender { private const val MAX_TAG_LENGTH = 23 private var sAppendCaller: Boolean = false private var sAppendThread: Boolean = false /** * Set whether to append the caller's code position to the log. * * If set true, append the caller's code position to the log. * This will act as a link to the source code of caller on the IntelliJ console. * * Default value is false * * @param append if true, enabled. */ @JvmStatic fun appendCaller(append: Boolean) { sAppendCaller = append } /** * Set whether to append caller's thread information to the log. * * Default value is false * * @param append if true, enabled. */ @JvmStatic fun appendThread(append: Boolean) { sAppendThread = append } @JvmStatic fun create(printer: Printer): Sender = { level, message, throwable -> val trace = Throwable().stackTrace // $1 -> DefaultSender -> Logger#send -> Logger#v/d/i/w/e -> ログコール場所 val element = if (trace.size > 4) trace[4] else null val tag = element?.makeTag() ?: "tag" val messages = mutableListOf<String>() if (sAppendThread) { messages.add(makeThreadInfo()) } if (sAppendCaller && element != null) { messages.add("$element : ") } messages.add(makeMessage(message, throwable)) printer.invoke(level, tag, messages.joinToString(separator = "")) } private fun StackTraceElement.makeTag(): String = className .substringAfterLast('.') .substringBefore('$') .let { if (it.length > MAX_TAG_LENGTH) it.substring(0, MAX_TAG_LENGTH) else it } }
mit
869e1635a5f9c6563ef2079e73fa553b
28.573529
88
0.612631
4.046278
false
false
false
false
panpf/sketch
sketch/src/main/java/com/github/panpf/sketch/util/NetworkObserver.kt
1
4507
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.util import android.content.Context import android.net.ConnectivityManager import android.net.Network import android.net.NetworkCapabilities import android.net.NetworkRequest import android.os.Build.VERSION import android.os.Build.VERSION_CODES import androidx.annotation.RequiresApi fun NetworkObserver(context: Context): NetworkObserver = if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { NetworkObserver21(context) } else { NetworkObserver1(context) } interface NetworkObserver { val isCellularNetworkConnected: Boolean /** Stop observing network changes. */ fun shutdown() } @RequiresApi(VERSION_CODES.LOLLIPOP) class NetworkObserver21(context: Context) : NetworkObserver { private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager? private var _isCellularNetworkConnected: Boolean = false private val networkCallback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) = onConnectivityChange() override fun onUnavailable() = onConnectivityChange() override fun onLost(network: Network) = onConnectivityChange() override fun onCapabilitiesChanged( network: Network, networkCapabilities: NetworkCapabilities ) = onConnectivityChange() } override val isCellularNetworkConnected: Boolean get() = _isCellularNetworkConnected init { val request = NetworkRequest.Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .build() connectivityManager?.registerNetworkCallback(request, networkCallback) _isCellularNetworkConnected = connectivityManager?.activeNetworkCompat()?.isCellularNetworkConnected() == true } override fun shutdown() { connectivityManager?.unregisterNetworkCallback(networkCallback) } private fun onConnectivityChange() { _isCellularNetworkConnected = connectivityManager?.activeNetworkCompat()?.isCellularNetworkConnected() == true } private fun ConnectivityManager.activeNetworkCompat(): Network? = if (VERSION.SDK_INT >= VERSION_CODES.M) { activeNetwork } else { @Suppress("DEPRECATION") allNetworks.firstOrNull() } private fun Network.isCellularNetworkConnected(): Boolean { val networkCapabilities = connectivityManager?.getNetworkCapabilities(this) return networkCapabilities != null && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) } } @Suppress("DEPRECATION") class NetworkObserver1(context: Context) : NetworkObserver { private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager? override val isCellularNetworkConnected: Boolean get() { val networkInfo = connectivityManager?.activeNetworkInfo return if (networkInfo != null && networkInfo.isConnected) { val type = networkInfo.type type == ConnectivityManager.TYPE_MOBILE || type == ConnectivityManager.TYPE_MOBILE_DUN || type == ConnectivityManager.TYPE_MOBILE_HIPRI || type == ConnectivityManager.TYPE_MOBILE_MMS || type == ConnectivityManager.TYPE_MOBILE_SUPL || type == 10 || type == 11 || type == 12 || type == 14 || type == 15 } else { false } } override fun shutdown() { } }
apache-2.0
f3d49761bf56ea8daa9c77837daf41c0
35.650407
97
0.672731
5.283705
false
false
false
false
panpf/sketch
sample/src/main/java/com/github/panpf/sketch/sample/ui/test/transform/BlurTransformationTestFragment.kt
1
3699
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.sample.ui.test.transform import android.graphics.Color import android.os.Bundle import android.widget.SeekBar import androidx.core.graphics.ColorUtils import androidx.fragment.app.viewModels import com.github.panpf.sketch.cache.CachePolicy.DISABLED import com.github.panpf.sketch.displayImage import com.github.panpf.sketch.sample.AssetImages import com.github.panpf.sketch.sample.databinding.BlurTransformationTestFragmentBinding import com.github.panpf.sketch.sample.ui.base.BindingFragment import com.github.panpf.sketch.transform.BlurTransformation class BlurTransformationTestFragment : BindingFragment<BlurTransformationTestFragmentBinding>() { private val viewModel by viewModels<BlurTransformationTestViewModel>() override fun onViewCreated( binding: BlurTransformationTestFragmentBinding, savedInstanceState: Bundle? ) { viewModel.radiusData.observe(viewLifecycleOwner) { update(binding, it, viewModel.maskColorData.value) binding.blurTransformationTestValueText.text = "%d/%d".format(it, binding.blurTransformationTestSeekBar.max) } binding.blurTransformationTestSeekBar.apply { max = 100 progress = viewModel.radiusData.value!! setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onStartTrackingTouch(seekBar_roundRectImageProcessor: SeekBar) { } override fun onStopTrackingTouch(seekBar_roundRectImageProcessor: SeekBar) { } override fun onProgressChanged( seekBar: SeekBar, progress: Int, fromUser: Boolean ) { viewModel.changeRadius(progress.coerceAtLeast(1)) } }) } viewModel.maskColorData.observe(viewLifecycleOwner) { update(binding, viewModel.radiusData.value!!, it) } binding.blurTransformationTestRedButton.setOnClickListener { viewModel.changeMaskColor(ColorUtils.setAlphaComponent(Color.RED, 128)) } binding.blurTransformationTestGreenButton.setOnClickListener { viewModel.changeMaskColor(ColorUtils.setAlphaComponent(Color.GREEN, 128)) } binding.blurTransformationTestBlueButton.setOnClickListener { viewModel.changeMaskColor(ColorUtils.setAlphaComponent(Color.BLUE, 128)) } binding.blurTransformationTestNoneButton.setOnClickListener { viewModel.changeMaskColor(null) } binding.blurTransformationTestNoneButton.isChecked = true } private fun update( binding: BlurTransformationTestFragmentBinding, radius: Int, maskColor: Int? ) { binding.blurTransformationTestImage.displayImage(AssetImages.STATICS.first()) { memoryCachePolicy(DISABLED) resultCachePolicy(DISABLED) addTransformations(BlurTransformation(radius, maskColor = maskColor)) } } }
apache-2.0
47cce968defb16fdc65f9f32abcd0574
37.541667
97
0.706137
5.081044
false
true
false
false
borgesgabriel/password
src/main/kotlin/es/gabrielborg/keystroke/core/LoginService.kt
1
3573
package es.gabrielborg.keystroke.core import es.gabrielborg.keystroke.utility.* import es.gabrielborg.keystroke.utility.polynomial.* import org.apache.commons.math3.stat.StatUtils import java.math.BigInteger import java.util.* import kotlin.math.div import kotlin.math.plus object LoginService { fun login(username: String, password: String, featureArray: DoubleArray, verbose: Boolean = false): Boolean { val instructionTable = try { IO.readInstructionTable(username) } catch (e: Exception) { if (kDebug) throw e return false } val nodeList = Array(featureArray.size) { if (featureArray[it] < IO.threshold[it]) { Point(2 * it, instructionTable[it].alpha / (((password + 2 * it).toSha256BigInteger()) % kLargePrime)) } else { Point(2 * it + 1, instructionTable[it].beta / (((password + (2 * it + 1)).toSha256BigInteger()) % kLargePrime)) } } val polynomial = try { BigIntegerDividedDifferenceInterpolator().interpolate(nodeList) } catch (e: Exception) { return false } val hpwd = try { polynomial.bigIntegerValue(0.0) } catch (e: Exception) { return false } if (verbose && kDebug) println("Hpwd': $hpwd") var featureTable = IO.readHistoryFile(username, hpwd, verbose) ?: return false featureTable.add(featureArray) featureTable = ArrayList(featureTable.takeLast(kHValue)) // Take only the last h elements IO.writeHistoryFile(username, hpwd, featureTable) val mean = DoubleArray(kNumberOfFeatures) val stdDeviation = DoubleArray(kNumberOfFeatures) for (i in 0..kNumberOfFeatures - 1) { val columnArray = featureTable.map { it[i].toDouble() }.toDoubleArray() mean[i] = StatUtils.mean(columnArray) stdDeviation[i] = Math.sqrt(StatUtils.variance(columnArray)) } val randomPolynomial = getRandomPolynomial() randomPolynomial[0] = hpwd val newInstructionTable = Array(kNumberOfFeatures) { val y0: BigInteger val y1: BigInteger if (isDistinguishingFeature(featureTable.size, mean[it], stdDeviation[it], IO.threshold[it])) { DataSet.logDistinguishingFeature(it, true) if (mean[it] < IO.threshold[it]) { // y0 = f(2i), y1 != f(2i+1) y0 = randomPolynomial.at(2 * it) y1 = getLowRandomBigInteger() + randomPolynomial.at(2 * it + 1) } else { // y0 != f(2i), y1 = f(2i+1) y0 = getLowRandomBigInteger() + randomPolynomial.at(2 * it) y1 = randomPolynomial.at(2 * it + 1) } } else { DataSet.logDistinguishingFeature(it, false) // y0 = f(2i), y1 = f(2i+1) y0 = randomPolynomial.at(2 * it) y1 = randomPolynomial.at(2 * it + 1) } TableRow(getAlpha(y0, it, password), getBeta(y1, it, password)) } IO.writeInstructionTable(username, newInstructionTable) return true } fun isDistinguishingFeature(successfulLogins: Int, mean: Double, stdDeviation: Double, threshold: Double): Boolean { if (successfulLogins < kHValue) return false return Math.abs(mean - threshold) > kValue * stdDeviation } }
gpl-3.0
8b34b7aee333779b35f2e97a546e337d
37.010638
127
0.580465
3.996644
false
false
false
false
slartus/4pdaClient-plus
forpdaapi/src/main/java/org/softeg/slartus/forpdaapi/Forum.kt
1
918
package org.softeg.slartus.forpdaapi import java.io.Serializable class Forum(var id: String?, val title: String) : Serializable { var description: String? = null var isHasTopics = false var isHasForums = false var iconUrl: String? = null var parentId: String? = null override fun toString(): String { return title } override fun equals(other: Any?): Boolean { return other is Forum? && other?.hashCode() == hashCode() } override fun hashCode(): Int { var result = id?.hashCode() ?: 0 result = 31 * result + title.hashCode() result = 31 * result + (description?.hashCode() ?: 0) result = 31 * result + isHasTopics.hashCode() result = 31 * result + isHasForums.hashCode() result = 31 * result + (iconUrl?.hashCode() ?: 0) result = 31 * result + (parentId?.hashCode() ?: 0) return result } }
apache-2.0
0b5c797714163d7372f5d89ee9e990e9
28.645161
65
0.604575
4.211009
false
false
false
false
andimage/PCBridge
src/main/kotlin/com/projectcitybuild/plugin/commands/SyncOtherCommand.kt
1
2619
package com.projectcitybuild.plugin.commands import com.projectcitybuild.core.exceptions.InvalidCommandArgumentsException import com.projectcitybuild.core.utilities.Failure import com.projectcitybuild.core.utilities.Success import com.projectcitybuild.features.ranksync.usecases.UpdatePlayerGroupsUseCase import com.projectcitybuild.modules.nameguesser.NameGuesser import com.projectcitybuild.modules.textcomponentbuilder.send import com.projectcitybuild.plugin.environment.SpigotCommand import com.projectcitybuild.plugin.environment.SpigotCommandInput import org.bukkit.Server import org.bukkit.command.CommandSender import javax.inject.Inject class SyncOtherCommand @Inject constructor( private val server: Server, private val updatePlayerGroupsUseCase: UpdatePlayerGroupsUseCase, private val nameGuesser: NameGuesser ) : SpigotCommand { override val label = "syncother" override val permission = "pcbridge.sync.other" override val usageHelp = "/syncother <name>" override suspend fun execute(input: SpigotCommandInput) { if (input.args.size != 1) { throw InvalidCommandArgumentsException() } val targetPlayerName = input.args.first() val targetPlayer = nameGuesser.guessClosest(targetPlayerName, server.onlinePlayers) { it.name } if (targetPlayer == null) { input.sender.send().error("$targetPlayerName is not online") return } val result = updatePlayerGroupsUseCase.sync(targetPlayer.uniqueId) when (result) { is Failure -> input.sender.send().error( when (result.reason) { UpdatePlayerGroupsUseCase.FailureReason.ACCOUNT_NOT_LINKED -> "Sync failed: Player does not have a linked PCB account" UpdatePlayerGroupsUseCase.FailureReason.PERMISSION_USER_NOT_FOUND -> "Permission user not found. Check that the user exists in the Permission plugin" } ) is Success -> { input.sender.send().success("$targetPlayerName has been synchronized") targetPlayer.send().success("Your account groups have been synchronized") } } } override fun onTabComplete(sender: CommandSender?, args: List<String>): Iterable<String>? { return when { args.isEmpty() -> server.onlinePlayers.map { it.name } args.size == 1 -> server.onlinePlayers.map { it.name }.filter { it.lowercase().startsWith(args.first().lowercase()) } else -> null } } }
mit
6ef189095f8a94f34845529e9b62d864
39.921875
129
0.685758
4.814338
false
false
false
false
AndroidX/androidx
navigation/navigation-common/src/main/java/androidx/navigation/Navigator.kt
3
9768
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.navigation import android.os.Bundle import androidx.annotation.CallSuper import androidx.navigation.Navigator.Name /** * Navigator defines a mechanism for navigating within an app. * * Each Navigator sets the policy for a specific type of navigation, e.g. * [ActivityNavigator] knows how to launch into [destinations][NavDestination] * backed by activities using [startActivity][Context.startActivity]. * * Navigators should be able to manage their own back stack when navigating between two * destinations that belong to that navigator. The [NavController] manages a back stack of * navigators representing the current navigation stack across all navigators. * * Each Navigator should add the [Navigator.Name annotation][Name] to their class. Any * custom attributes used by the associated [destination][NavDestination] subclass should * have a name corresponding with the name of the Navigator, e.g., [ActivityNavigator] uses * `<declare-styleable name="ActivityNavigator">` * * @param D the subclass of [NavDestination] used with this Navigator which can be used * to hold any special data that will be needed to navigate to that destination. * Examples include information about an intent to navigate to other activities, * or a fragment class name to instantiate and swap to a new fragment. */ public abstract class Navigator<D : NavDestination> { /** * This annotation should be added to each Navigator subclass to denote the default name used * to register the Navigator with a [NavigatorProvider]. * * @see NavigatorProvider.addNavigator * @see NavigatorProvider.getNavigator */ @kotlin.annotation.Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.ANNOTATION_CLASS, AnnotationTarget.CLASS) public annotation class Name(val value: String) private var _state: NavigatorState? = null /** * The state of the Navigator is the communication conduit between the Navigator * and the [NavController] that has called [onAttach]. * * It is the responsibility of the Navigator to call [NavigatorState.push] * and [NavigatorState.pop] to in order to update the [NavigatorState.backStack] at * the appropriate times. * * @throws IllegalStateException if [isAttached] is `false` */ protected val state: NavigatorState get() = checkNotNull(_state) { "You cannot access the Navigator's state until the Navigator is attached" } /** * Whether this Navigator is actively being used by a [NavController]. * * This is set to `true` when [onAttach] is called. */ public var isAttached: Boolean = false private set /** * Indicator that this Navigator is actively being used by a [NavController]. This * is called when the NavController's state is ready to be restored. */ @CallSuper public open fun onAttach(state: NavigatorState) { _state = state isAttached = true } /** * Construct a new NavDestination associated with this Navigator. * * Any initialization of the destination should be done in the destination's constructor as * it is not guaranteed that every destination will be created through this method. * @return a new NavDestination */ public abstract fun createDestination(): D /** * Navigate to a destination. * * Requests navigation to a given destination associated with this navigator in * the navigation graph. This method generally should not be called directly; * [NavController] will delegate to it when appropriate. * * @param entries destination(s) to navigate to * @param navOptions additional options for navigation * @param navigatorExtras extras unique to your Navigator. */ @Suppress("UNCHECKED_CAST") public open fun navigate( entries: List<NavBackStackEntry>, navOptions: NavOptions?, navigatorExtras: Extras? ) { entries.asSequence().map { backStackEntry -> val destination = backStackEntry.destination as? D ?: return@map null val navigatedToDestination = navigate( destination, backStackEntry.arguments, navOptions, navigatorExtras ) when (navigatedToDestination) { null -> null destination -> backStackEntry else -> { state.createBackStackEntry( navigatedToDestination, navigatedToDestination.addInDefaultArgs(backStackEntry.arguments) ) } } }.filterNotNull().forEach { backStackEntry -> state.push(backStackEntry) } } /** * Informational callback indicating that the given [backStackEntry] has been * affected by a [NavOptions.shouldLaunchSingleTop] operation. The entry provided is a new * [NavBackStackEntry] instance with all the previous state of the old entry and possibly * new arguments. */ @Suppress("UNCHECKED_CAST") public open fun onLaunchSingleTop(backStackEntry: NavBackStackEntry) { val destination = backStackEntry.destination as? D ?: return navigate(destination, null, navOptions { launchSingleTop = true }, null) state.onLaunchSingleTop(backStackEntry) } /** * Navigate to a destination. * * Requests navigation to a given destination associated with this navigator in * the navigation graph. This method generally should not be called directly; * [NavController] will delegate to it when appropriate. * * @param destination destination node to navigate to * @param args arguments to use for navigation * @param navOptions additional options for navigation * @param navigatorExtras extras unique to your Navigator. * @return The NavDestination that should be added to the back stack or null if * no change was made to the back stack (i.e., in cases of single top operations * where the destination is already on top of the back stack). */ // TODO Deprecate this method once all call sites are removed @Suppress("UNUSED_PARAMETER", "RedundantNullableReturnType") public open fun navigate( destination: D, args: Bundle?, navOptions: NavOptions?, navigatorExtras: Extras? ): NavDestination? = destination /** * Attempt to pop this navigator's back stack, performing the appropriate navigation. * * All destinations back to [popUpTo] should be popped off the back stack. * * @param popUpTo the entry that should be popped off the [NavigatorState.backStack] * along with all entries above this entry. * @param savedState whether any Navigator specific state associated with [popUpTo] should * be saved to later be restored by a call to [navigate] with [NavOptions.shouldRestoreState]. */ @Suppress("UNUSED_PARAMETER") public open fun popBackStack(popUpTo: NavBackStackEntry, savedState: Boolean) { val backStack = state.backStack.value check(backStack.contains(popUpTo)) { "popBackStack was called with $popUpTo which does not exist in back stack $backStack" } val iterator = backStack.listIterator(backStack.size) var lastPoppedEntry: NavBackStackEntry? = null do { if (!popBackStack()) { // Quit early if popBackStack() returned false break } lastPoppedEntry = iterator.previous() } while (lastPoppedEntry != popUpTo) if (lastPoppedEntry != null) { state.pop(lastPoppedEntry, savedState) } } /** * Attempt to pop this navigator's back stack, performing the appropriate navigation. * * Implementations should return `true` if navigation * was successful. Implementations should return `false` if navigation could not * be performed, for example if the navigator's back stack was empty. * * @return `true` if pop was successful */ // TODO Deprecate this method once all call sites are removed public open fun popBackStack(): Boolean = true /** * Called to ask for a [Bundle] representing the Navigator's state. This will be * restored in [onRestoreState]. */ public open fun onSaveState(): Bundle? { return null } /** * Restore any state previously saved in [onSaveState]. This will be called before * any calls to [navigate] or * [popBackStack]. * * Calls to [createDestination] should not be dependent on any state restored here as * [createDestination] can be called before the state is restored. * * @param savedState The state previously saved */ public open fun onRestoreState(savedState: Bundle) {} /** * Interface indicating that this class should be passed to its respective * [Navigator] to enable Navigator specific behavior. */ public interface Extras }
apache-2.0
c0da815c8f44bc0fe2c60201e7a53a24
39.7
98
0.681511
5.011801
false
false
false
false
jk1/youtrack-idea-plugin
src/main/kotlin/com/github/jk1/ytplugin/issues/actions/IssueActionGroup.kt
1
1460
package com.github.jk1.ytplugin.issues.actions import com.github.jk1.ytplugin.commands.OpenSetupWindowAction import com.github.jk1.ytplugin.tasks.YouTrackServer import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.CustomShortcutSet import com.intellij.openapi.actionSystem.DefaultActionGroup import javax.swing.JComponent class IssueActionGroup(private val parent: JComponent) : DefaultActionGroup() { override fun isDumbAware() = true fun add(action: IssueAction) { action.register(parent) super.add(action) } fun addConfigureTaskServerAction(repo: YouTrackServer, fromTracker: Boolean) { // action wrap is required to override shortcut for a global action val action = OpenSetupWindowAction(repo, fromTracker) action.registerCustomShortcutSet(CustomShortcutSet.fromString("ctrl shift Q"), parent) super.add(action) } fun createVerticalToolbarComponent(target: JComponent) = createToolbarComponent(target, false) fun createHorizontalToolbarComponent(target: JComponent) = createToolbarComponent(target, true) private fun createToolbarComponent(target: JComponent, horizontal: Boolean): JComponent = ActionManager.getInstance() .createActionToolbar(ActionPlaces.TOOLWINDOW_TITLE, this, horizontal) .also { it.setTargetComponent(target) } .component }
apache-2.0
daf9e68d32430bd2a486b6c5cd41fdb8
39.583333
121
0.777397
4.850498
false
false
false
false
jackping/AppBase
base/src/main/java/com/yima/base/BaseApp.kt
1
5148
package com.yima.base import android.app.Activity import android.app.Application import android.app.Instrumentation import android.content.Context import android.os.Bundle import android.os.PersistableBundle import android.support.multidex.MultiDex import android.util.DisplayMetrics import android.util.SparseArray import android.view.WindowManager import io.reactivex.Observable import io.reactivex.schedulers.Schedulers import timber.log.Timber import java.lang.ref.WeakReference /** * com.yima.base.BaseApp * Created by yima on 2017/6/13. */ abstract class BaseApp : Application() { private val actManager = BaseActManager() var SCREEN_WIDTH = -1 var SCREEN_HEIGHT = -1 var DIMEN_RATE = -1.0F var DIMEN_DPI = -1 init { //Timber if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } else { //TODO 应该有一个release版只保存crashLog的tree Timber.plant(Timber.DebugTree()) } } companion object { private lateinit var instance: BaseApp fun getApp() = instance } override fun onCreate() { avoidKotlinNullBundleError() super.onCreate() instance = this getScreenSize() initApp() //在子线程中初始化 Observable.just("").subscribeOn(Schedulers.io()).subscribe { initAppAsync() } } protected abstract fun initApp() protected abstract fun initAppAsync() fun getScreenSize() { val windowManager = this.getSystemService(Context.WINDOW_SERVICE) as WindowManager val dm = DisplayMetrics() val display = windowManager.defaultDisplay display.getMetrics(dm) DIMEN_RATE = dm.density / 1.0f DIMEN_DPI = dm.densityDpi SCREEN_WIDTH = dm.widthPixels SCREEN_HEIGHT = dm.heightPixels if (SCREEN_WIDTH > SCREEN_HEIGHT) { val t = SCREEN_HEIGHT SCREEN_HEIGHT = SCREEN_WIDTH SCREEN_WIDTH = t } } override fun attachBaseContext(base: Context) { super.attachBaseContext(base) MultiDex.install(this) } fun addActivity(act: Activity) { actManager.addActivity(act) } fun removeActivity(act: Activity) { actManager.removeActivity(act) } fun getTopActivity(): Activity? { return actManager.getTopActivity() } fun clearActivity() { actManager.clearActivity() } fun exitApp() { clearActivity() android.os.Process.killProcess(android.os.Process.myPid()) System.exit(0) } private fun avoidKotlinNullBundleError() { try { val clz = Class.forName("android.app.ActivityThread") val mtd = clz.getDeclaredMethod("currentActivityThread") val obj = mtd.invoke(null) val field = obj.javaClass.getDeclaredField("mInstrumentation") field.isAccessible = true field.set(obj, InstrumentationBase()) } catch (e: Exception) { Timber.e(e.message) } } } /** * com.yima.base.InstrumentationBase * add empty bundle to every activity * make sure no kotlin non-null argument error * Created by yima on 2017/10/16. */ class InstrumentationBase : Instrumentation() { override fun callActivityOnCreate(activity: Activity?, icicle: Bundle?) { var bundle = icicle if (bundle == null) { bundle = Bundle.EMPTY } super.callActivityOnCreate(activity, bundle) } override fun callActivityOnCreate(activity: Activity?, icicle: Bundle?, persistentState: PersistableBundle?) { var bundle = icicle if (bundle == null) { bundle = Bundle.EMPTY } super.callActivityOnCreate(activity, bundle, persistentState) } } class BaseActManager { private val container = SparseArray<WeakReference<Activity>>() private var topAct: WeakReference<Activity>? = null fun addActivity(act: Activity) { if (container.get(act.hashCode()) == null) { container.append(act.hashCode(), WeakReference(act)) topAct = WeakReference(act) } } fun removeActivity(act: Activity) { val tmpAct = container.get(act.hashCode()) if (tmpAct != null) { container.remove(act.hashCode()) topAct = if (container.size() == 0) { null } else { container.get(container.keyAt(container.size() - 1)) } } } fun getTopActivity(): Activity? { if (container.size() <= 0) { return null } return topAct?.get() } fun clearActivity() { synchronized(container) { var i = 0 while (i < container.size()) { val key = container.keyAt(i) val weak = container.get(key) if (weak?.get() != null) { weak.get()!!.finishAffinity() } container.remove(key) i++ } topAct = null } } }
apache-2.0
c9877f474df2863004923ff396ed1697
26.489247
114
0.600743
4.422145
false
false
false
false
jorjoluiso/QuijoteLui
src/main/kotlin/com/quijotelui/model/Electronico.kt
1
1133
package com.quijotelui.model import org.hibernate.annotations.Type import java.io.Serializable import java.util.* import javax.persistence.* @Entity @Table(name = "ele_documentos_electronicos") class Electronico : Serializable { @Id /* Secuencia para Oracle */ // @GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "id_Sequence") //Oracle // @SequenceGenerator(name = "id_Sequence", sequenceName = "SEQ_ELE_DOCUMENTOS") //Oracle @GeneratedValue(strategy = GenerationType.AUTO) //MySql - Sql Server - PostgreSQL @Column(name = "id") var id : Long? = null @Column(name = "codigo", nullable = false) var codigo : String? = null @Column(name = "numero", nullable = false) var numero : String? = null @Column(name = "numero_autorizacion") var numeroAutorizacion : String? = null @Column(name = "fecha_autorizacion") @Temporal(TemporalType.TIMESTAMP) // @Type(type="date") var fechaAutorizacion : Date? = null @Column(name = "observacion") var observacion : String? = null @Column(name = "estado") var estado : String? = null }
gpl-3.0
c1ec82713b2f09f03c172e03e5388585
26
92
0.671668
3.726974
false
false
false
false