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
christophpickl/gadsu
src/test/kotlin/at/cpickl/gadsu/appointment/gcal/matchclient.kt
1
2389
package at.cpickl.gadsu.appointment.gcal import at.cpickl.gadsu.appointment.gcal.sync.MatchClients import at.cpickl.gadsu.appointment.gcal.sync.MatchClientsInDb import at.cpickl.gadsu.client.Client import at.cpickl.gadsu.client.ClientJdbcRepository import at.cpickl.gadsu.testinfra.HsqldbTest import at.cpickl.gadsu.testinfra.unsavedValidInstance import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.contains import org.testng.annotations.BeforeMethod import org.testng.annotations.Test @Test(groups = arrayOf("hsqldb")) class MatchClientsInDbTest : HsqldbTest() { private lateinit var testee: MatchClients private lateinit var caroline: Client private lateinit var carolina: Client private lateinit var laura: Client private lateinit var ingrid: Client @BeforeMethod fun insertClients() { testee = MatchClientsInDb(ClientJdbcRepository(jdbcx, idGenerator)) caroline = newClient("Caroline", "Caro", "Firefox") carolina = newClient("Carolina", "Caro", "Safari") laura = newClient("Laura", "", "Internet Chrome") ingrid = newClient("Ingrid", "Haudegen", "Internet Explorer") } private fun findMatchingClientsProvider(): List<Pair<String, List<Client>>> = listOf( // first name testCase("caro", caroline, carolina), testCase("caroline", caroline, carolina), testCase("carolina", carolina, caroline), // last name testCase("chrome", laura), testCase("inter", ingrid, laura), // nick name testCase("haudeg", ingrid) ) // using a dataprovider does not really work here, as we need a client which is generated at runtime fun `findMatchingClients by name _ should return clients _`() { findMatchingClientsProvider().forEach { assertThat("Search string: '${it.first}'", testee.findMatchingClients(it.first), contains(*it.second.toTypedArray())) } } private fun newClient(firstName: String, nickName: String, lastName: String) = insertClientViaRepo(Client.unsavedValidInstance().copy(firstName = firstName, nickNameInt = nickName, lastName = lastName)) private fun testCase(searchName: String, vararg expectedClients: Client): Pair<String, List<Client>> { return Pair(searchName, expectedClients.toList()) } }
apache-2.0
3bc524740dabdf5b6ee618d6626a74d7
39.491525
135
0.701549
4.407749
false
true
false
false
kotlintest/kotlintest
kotest-assertions/src/jvmMain/kotlin/io/kotest/matchers/equality/reflection.kt
1
8002
package io.kotest.matchers.equality import io.kotest.matchers.Matcher import io.kotest.matchers.MatcherResult import io.kotest.matchers.should import io.kotest.matchers.shouldNot import kotlin.reflect.KProperty import kotlin.reflect.KVisibility import kotlin.reflect.full.memberProperties /** * Asserts that this is equal to [other] using specific fields * * Verifies that [this] instance is equal to [other] using only some specific fields. This is useful for matching * on objects that contain unknown values, such as a database Entity that contains an ID (you don't know this ID, and it * doesn't matter for you, for example) * * Opposite of [shouldNotBeEqualToUsingFields] * * Example: * ``` * data class Foo(val id: Int, val description: String) * * val firstFoo = Foo(1, "Bar!") * val secondFoo = Foo(2, "Bar!") * * firstFoo.shouldBeEqualUsingFields(secondFoo, Foo::description) // Assertion passes * * firstFoo shouldBe secondFoo // Assertion fails, `equals` is false! * ``` * * Note: * 1) Throws [IllegalArgumentException] in case [properties] parameter is not provided. * 2) Throws [IllegalArgumentException] if [properties] contains any non public property * */ fun <T : Any> T.shouldBeEqualToUsingFields(other: T, vararg properties: KProperty<*>) { require(properties.isNotEmpty()) { "At-least one field is required to be mentioned for checking the equality" } this should beEqualToUsingFields(other, *properties) } /** * Asserts that this is NOT equal to [other] using specific fields * * Verifies that [this] instance is not equal to [other] using only some specific fields. This is useful for matching * on objects that contain unknown values, such as a database Entity that contains an ID (you don't know this ID, and it * doesn't matter for you, for example) * * Opposite of [shouldBeEqualToUsingFields] * * Example: * ``` * data class Foo(val id: Int, val description: String) * * val firstFoo = Foo(1, "Bar!") * val secondFoo = Foo(2, "BAT") * * firstFoo.shouldNotBeEqualToUsingFields(secondFoo, Foo::description) // Assertion passes * * ``` * Note: * 1) Throws [IllegalArgumentException] in case [properties] parameter is not provided. * 2) Throws [IllegalArgumentException] if [properties] contains any non public property * * * @see [beEqualToUsingFields] * @see [shouldNotBeEqualToIgnoringFields] * */ fun <T : Any> T.shouldNotBeEqualToUsingFields(other: T, vararg properties: KProperty<*>) { require(properties.isNotEmpty()) { "At-least one field is required to be mentioned for checking the equality" } this shouldNot beEqualToUsingFields(other, *properties) } /** * Matcher that compares values using specific fields * * Verifies that two instances not equal using only some specific fields. This is useful for matching * on objects that contain unknown values, such as a database Entity that contains an ID (you don't know this ID, and it * doesn't matter for you, for example) * * * Example: * ``` * data class Foo(val id: Int, val description: String) * * val firstFoo = Foo(1, "Bar!") * val secondFoo = Foo(2, "Bar!") * * firstFoo should beEqualToUsingFields(secondFoo, Foo::description) // Assertion passes * * ``` * * Note: Throws [IllegalArgumentException] if [fields] contains any non public property * * @see [shouldBeEqualToUsingFields] * @see [shouldNotBeEqualToUsingFields] * @see [beEqualToIgnoringFields] * */ fun <T : Any> beEqualToUsingFields(other: T, vararg fields: KProperty<*>): Matcher<T> = object : Matcher<T> { override fun test(value: T): MatcherResult { val nonPublicFields = fields.filterNot { it.visibility == KVisibility.PUBLIC } if(nonPublicFields.isNotEmpty()) { throw IllegalArgumentException("Fields of only public visibility are allowed to be use for used for checking equality") } val failed = checkEqualityOfFields(fields.toList(), value, other) val fieldsString = fields.joinToString(", ", "[", "]") { it.name } return MatcherResult( failed.isEmpty(), "$value should be equal to $other using fields $fieldsString; Failed for $failed", "$value should not be equal to $other using fields $fieldsString" ) } } /** * Asserts that this is equal to [other] without using specific fields * * Verifies that [this] instance is equal to [other] without using some specific fields. This is useful for matching * on objects that contain unknown values, such as a database Entity that contains an ID (you don't know this ID, and it * doesn't matter for you, for example) * * Opposite of [shouldNotBeEqualToIgnoringFields] * * Example: * ``` * data class Foo(val id: Int, val description: String) * * val firstFoo = Foo(1, "Bar!") * val secondFoo = Foo(2, "Bar!") * * firstFoo.shouldBeEqualToIgnoringFields(secondFoo, Foo::id) // Assertion passes * * firstFoo shouldBe secondFoo // Assertion fails, `equals` is false! * ``` * * Note: Throws [IllegalArgumentException] in case [properties] parameter is not provided. */ fun <T : Any> T.shouldBeEqualToIgnoringFields(other: T, vararg properties: KProperty<*>) { require(properties.isNotEmpty()) { "At-least one field is required to be mentioned to be ignore for checking the equality" } this should beEqualToIgnoringFields(other, *properties) } /** * Asserts that this is not equal to [other] without using specific fields * * Verifies that [this] instance is not equal to [other] without using some specific fields. This is useful for matching * on objects that contain unknown values, such as a database Entity that contains an ID (you don't know this ID, and it * doesn't matter for you, for example) * * Opposite of [shouldBeEqualToIgnoringFields] * * Example: * ``` * data class Foo(val id: Int, val description: String) * * val firstFoo = Foo(1, "Bar!") * val secondFoo = Foo(2, "BAT!") * * firstFoo.shouldNotBeEqualToIgnoringFields(secondFoo, Foo::id) // Assertion passes * ``` * */ fun <T : Any> T.shouldNotBeEqualToIgnoringFields(other: T, vararg properties: KProperty<*>) = this shouldNot beEqualToIgnoringFields(other, *properties) /** * Matcher that compares values without using specific fields * * Verifies that two instances are equal by not using only some specific fields. This is useful for matching * on objects that contain unknown values, such as a database Entity that contains an ID (you don't know this ID, and it * doesn't matter for you, for example) * * * Example: * ``` * data class Foo(val id: Int, val description: String) * * val firstFoo = Foo(1, "Bar!") * val secondFoo = Foo(2, "Bar!") * * firstFoo should beEqualToIgnoringFields(secondFoo, Foo::id) // Assertion passes * * ``` * * @see [beEqualToUsingFields] * @see [shouldBeEqualToIgnoringFields] * @see [shouldNotBeEqualToIgnoringFields] * */ fun <T : Any> beEqualToIgnoringFields( other: T, vararg fields: KProperty<*> ): Matcher<T> = object : Matcher<T> { override fun test(value: T): MatcherResult { val fieldNames = fields.map { it.name } val fieldsToBeConsidered: List<KProperty<*>> = value::class.memberProperties .filterNot { fieldNames.contains(it.name) } .filter { it.visibility == KVisibility.PUBLIC } val failed = checkEqualityOfFields(fieldsToBeConsidered, value, other) val fieldsString = fields.joinToString(", ", "[", "]") { it.name } return MatcherResult( failed.isEmpty(), "$value should be equal to $other ignoring fields $fieldsString; Failed for $failed", "$value should not be equal to $other ignoring fields $fieldsString" ) } } private fun <T> checkEqualityOfFields(fields: List<KProperty<*>>, value: T, other: T): List<String> { return fields.mapNotNull { val actual = it.getter.call(value) val expected = it.getter.call(other) if (actual == expected) null else { "${it.name}: $actual != $expected" } } }
apache-2.0
ceb44d7bb53f3e4e10cc5ea26babaf11
34.723214
128
0.705324
4.101486
false
false
false
false
ngageoint/mage-android
mage/src/main/java/mil/nga/giat/mage/location/LocationProvider.kt
1
4334
package mil.nga.giat.mage.location import android.content.Context import android.content.SharedPreferences import android.location.Location import android.location.LocationListener import android.location.LocationManager import android.os.Bundle import android.util.Log import androidx.lifecycle.LiveData import dagger.hilt.android.qualifiers.ApplicationContext import mil.nga.giat.mage.R import javax.inject.Inject import javax.inject.Singleton @Singleton class LocationProvider @Inject constructor(@ApplicationContext val context: Context, val preferences: SharedPreferences) : LiveData<Location>(), SharedPreferences.OnSharedPreferenceChangeListener { companion object { private val LOG_NAME = LocationProvider::class.java.simpleName } private var locationManager: LocationManager? = null private var locationListener: LiveDataLocationListener? = null private var minimumDistanceChangeForUpdates: Long = 0 override fun onActive() { super.onActive() preferences.registerOnSharedPreferenceChangeListener(this) locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager minimumDistanceChangeForUpdates = getMinimumDistanceChangeForUpdates() requestLocationUpdates() try { var location: Location? = locationManager?.getLastKnownLocation(LocationManager.GPS_PROVIDER) if (location == null) { location = locationManager?.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) } location?.let { setValue(it) } } catch (e: SecurityException) { Log.i(LOG_NAME, "Error requesting location updates") } } override fun onInactive() { super.onInactive() removeLocationUpdates() preferences.unregisterOnSharedPreferenceChangeListener(this) } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { if (key.equals(context.getString(R.string.gpsSensitivityKey), ignoreCase = true)) { Log.d(LOG_NAME, "GPS sensitivity changed, distance in meters for change: $minimumDistanceChangeForUpdates") minimumDistanceChangeForUpdates = getMinimumDistanceChangeForUpdates() // bounce location updates so new distance sensitivity takes effect removeLocationUpdates() requestLocationUpdates() } } private fun requestLocationUpdates() { Log.v(LOG_NAME, "request location updates") locationListener = LiveDataLocationListener().apply { try { locationManager?.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, minimumDistanceChangeForUpdates.toFloat(), this) } catch (ex: java.lang.SecurityException) { Log.i(LOG_NAME, "Error requesting location updates", ex) } catch (ex: IllegalArgumentException) { Log.d(LOG_NAME, "LocationManager.NETWORK_PROVIDER does not exist, " + ex.message) } try { locationManager?.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, minimumDistanceChangeForUpdates.toFloat(), this) } catch (ex: SecurityException) { Log.i(LOG_NAME, "Error requesting location updates", ex) } catch (ex: IllegalArgumentException) { Log.d(LOG_NAME, "LocationManager.GPS_PROVIDER does not exist, " + ex.message) } } } private fun removeLocationUpdates() { Log.v(LOG_NAME, "Removing location updates.") locationListener?.let { locationManager?.removeUpdates(it) locationListener = null } } private fun getMinimumDistanceChangeForUpdates(): Long { return preferences.getInt(context.getString(R.string.gpsSensitivityKey), context.resources.getInteger(R.integer.gpsSensitivityDefaultValue)).toLong() } private inner class LiveDataLocationListener : LocationListener { override fun onLocationChanged(location: Location) { setValue(location) } override fun onProviderDisabled(provider: String) {} override fun onProviderEnabled(provider: String) {} override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {} } }
apache-2.0
1d69491e9696a163e2cf5e16872d3f77
37.696429
166
0.697508
5.592258
false
false
false
false
robinverduijn/gradle
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/precompile/PrecompiledScriptDependenciesResolver.kt
1
2525
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.precompile import org.gradle.internal.hash.Hashing import org.gradle.kotlin.dsl.resolver.KotlinBuildScriptDependencies import java.util.concurrent.Future import kotlin.script.dependencies.Environment import kotlin.script.dependencies.KotlinScriptExternalDependencies import kotlin.script.dependencies.PseudoFuture import kotlin.script.dependencies.ScriptContents import kotlin.script.dependencies.ScriptDependenciesResolver class PrecompiledScriptDependenciesResolver : ScriptDependenciesResolver { companion object { fun hashOf(charSequence: CharSequence?) = Hashing.hashString(charSequence).toString() } object EnvironmentProperties { const val kotlinDslImplicitImports = "kotlinDslImplicitImports" } override fun resolve( script: ScriptContents, environment: Environment?, report: (ScriptDependenciesResolver.ReportSeverity, String, ScriptContents.Position?) -> Unit, previousDependencies: KotlinScriptExternalDependencies? ): Future<KotlinScriptExternalDependencies?> = PseudoFuture( KotlinBuildScriptDependencies( imports = implicitImportsFrom(environment) + precompiledScriptPluginImportsFrom(environment, script), classpath = emptyList(), sources = emptyList() ) ) private fun implicitImportsFrom(environment: Environment?) = environment.stringList(EnvironmentProperties.kotlinDslImplicitImports) private fun precompiledScriptPluginImportsFrom(environment: Environment?, script: ScriptContents): List<String> = environment.stringList(hashOf(script.text)) private fun Environment?.stringList(key: String) = string(key)?.split(':') ?: emptyList() private fun Environment?.string(key: String) = this?.get(key) as? String }
apache-2.0
2e201f8495f83a1f50562a5c722455eb
33.121622
117
0.734257
5.142566
false
false
false
false
kharchenkovitaliypt/AndroidMvp
mvp/src/main/java/com/idapgroup/android/mvp/impl/v2/LifecycleCallbacks.kt
1
4201
package com.idapgroup.android.mvp.impl.v2 import android.app.Activity import android.app.Application.ActivityLifecycleCallbacks import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentManager.FragmentLifecycleCallbacks import android.view.View fun ActivityLifecycleCallbacks.filter(activity: Activity): ActivityLifecycleCallbacks { return filter { it === activity } } fun ActivityLifecycleCallbacks.filter(predicate: (Activity) -> Boolean): ActivityLifecycleCallbacks { val delegate = this return object : ActivityLifecycleCallbacks { override fun onActivityCreated(a: Activity, savedInstanceState: Bundle?) { if(predicate(a)) delegate.onActivityCreated(a, savedInstanceState) } override fun onActivitySaveInstanceState(a: Activity, outState: Bundle) { if(predicate(a)) delegate.onActivitySaveInstanceState(a, outState) } override fun onActivityStarted(a: Activity) { if(predicate(a)) delegate.onActivityStarted(a) } override fun onActivityResumed(a: Activity) { if(predicate(a)) delegate.onActivityResumed(a) } override fun onActivityPaused(a: Activity) { if(predicate(a)) delegate.onActivityPaused(a) } override fun onActivityStopped(a: Activity) { if(predicate(a)) delegate.onActivityStopped(a) } override fun onActivityDestroyed(a: Activity) { if(predicate(a)) delegate.onActivityDestroyed(a) } } } fun FragmentLifecycleCallbacks.filter(fragment: Fragment): FragmentLifecycleCallbacks { return filter { it === fragment } } fun FragmentLifecycleCallbacks.filter(predicate: (Fragment) -> Boolean): FragmentLifecycleCallbacks { val delegate = this return object : FragmentLifecycleCallbacks() { override fun onFragmentPreAttached(fm: FragmentManager?, f: Fragment, context: Context?) { if(predicate(f)) delegate.onFragmentPreAttached(fm, f, context) } override fun onFragmentAttached(fm: FragmentManager?, f: Fragment, context: Context?) { if(predicate(f)) delegate.onFragmentAttached(fm, f, context) } override fun onFragmentActivityCreated(fm: FragmentManager?, f: Fragment, savedInstanceState: Bundle?) { if(predicate(f)) delegate.onFragmentActivityCreated(fm, f, savedInstanceState) } override fun onFragmentCreated(fm: FragmentManager?, f: Fragment, savedInstanceState: Bundle?) { if(predicate(f)) delegate.onFragmentCreated(fm, f, savedInstanceState) } override fun onFragmentSaveInstanceState(fm: FragmentManager, f: Fragment, outState: Bundle) { if(predicate(f)) delegate.onFragmentSaveInstanceState(fm, f, outState) } override fun onFragmentViewCreated(fm: FragmentManager, f: Fragment, v: View?, savedInstanceState: Bundle?) { if(predicate(f)) delegate.onFragmentViewCreated(fm, f, v, savedInstanceState) } override fun onFragmentStarted(fm: FragmentManager, f: Fragment) { if(predicate(f)) delegate.onFragmentStarted(fm, f) } override fun onFragmentResumed(fm: FragmentManager, f: Fragment) { if(predicate(f)) delegate.onFragmentResumed(fm, f) } override fun onFragmentPaused(fm: FragmentManager, f: Fragment) { if(predicate(f)) delegate.onFragmentPaused(fm, f) } override fun onFragmentStopped(fm: FragmentManager, f: Fragment) { if(predicate(f)) delegate.onFragmentStopped(fm, f) } override fun onFragmentViewDestroyed(fm: FragmentManager, f: Fragment) { if(predicate(f)) delegate.onFragmentViewDestroyed(fm, f) } override fun onFragmentDestroyed(fm: FragmentManager?, f: Fragment) { if(predicate(f)) delegate.onFragmentDestroyed(fm, f) } override fun onFragmentDetached(fm: FragmentManager?, f: Fragment) { if(predicate(f)) delegate.onFragmentDetached(fm, f) } } }
apache-2.0
df4c4f81ebc8118c8ced06f4ea1348b8
44.673913
117
0.688646
4.862269
false
false
false
false
FrancYescO/PokemonGoBot
src/main/kotlin/ink/abb/pogo/scraper/controllers/BotController.kt
1
14684
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package ink.abb.pogo.scraper.controllers import POGOProtos.Data.PokedexEntryOuterClass import POGOProtos.Enums.PokemonIdOuterClass import POGOProtos.Inventory.Item.ItemIdOuterClass import com.pokegoapi.api.inventory.Item import com.pokegoapi.api.inventory.ItemBag import com.pokegoapi.api.map.pokemon.EvolutionResult import com.pokegoapi.api.player.PlayerProfile import com.pokegoapi.api.pokemon.Pokemon import com.pokegoapi.google.common.geometry.S2LatLng import ink.abb.pogo.scraper.Context import ink.abb.pogo.scraper.Settings import ink.abb.pogo.scraper.services.BotService import ink.abb.pogo.scraper.util.ApiAuthProvider import ink.abb.pogo.scraper.util.Log import ink.abb.pogo.scraper.util.credentials.GoogleAutoCredentials import ink.abb.pogo.scraper.util.data.* import ink.abb.pogo.scraper.util.pokemon.getStatsFormatted import org.springframework.beans.factory.annotation.Autowired import org.springframework.web.bind.annotation.* import javax.servlet.http.HttpServletResponse @RestController @CrossOrigin @RequestMapping("/api") class BotController { @Autowired lateinit var service: BotService @Autowired lateinit var authProvider: ApiAuthProvider @RequestMapping("/bots") fun bots(): List<Settings> { return service.getAllBotSettings() } @RequestMapping(value = "/bot/{name}/auth", method = arrayOf(RequestMethod.POST)) fun auth( @PathVariable name: String, @RequestBody pass: String, httpResponse: HttpServletResponse ): String { val ctx = service.getBotContext(name) if (ctx.restApiPassword.equals("")) { Log.red("REST API: There is no REST API password set in the configuration for bot $name, generating one now...") authProvider.generateRestPassword(name) return "REST API password generated for bot $name, check your console output!" } authProvider.generateAuthToken(name) if (!pass.equals(ctx.restApiPassword)) { httpResponse.status = HttpServletResponse.SC_UNAUTHORIZED return "Your authentication request ($pass) does not match the REST API password from the bot $name configuration!" } return ctx.restApiToken } @RequestMapping(value = "/bot/{name}/load", method = arrayOf(RequestMethod.POST)) fun loadBot(@PathVariable name: String): Settings { Log.magenta("REST API: Load bot $name") return service.submitBot(name) } @RequestMapping(value = "/bot/{name}/unload", method = arrayOf(RequestMethod.POST)) fun unloadBot(@PathVariable name: String): String { Log.magenta("REST API: Unload bot $name") return service.doWithBot(name) { it.stop() service.removeBot(it) }.toString() } @RequestMapping(value = "/bot/{name}/reload", method = arrayOf(RequestMethod.POST)) fun reloadBot(@PathVariable name: String): Settings { Log.magenta("REST API: Reload bot $name") if (unloadBot(name).equals("false")) // return default settings return Settings( credentials = GoogleAutoCredentials(), latitude = 0.0, longitude = 0.0 ) return loadBot(name) } @RequestMapping(value = "/bot/{name}/start", method = arrayOf(RequestMethod.POST)) fun startBot(@PathVariable name: String): String { Log.magenta("REST API: Starting bot $name") return service.doWithBot(name) { it.start() }.toString() } @RequestMapping(value = "/bot/{name}/stop", method = arrayOf(RequestMethod.POST)) fun stopBot(@PathVariable name: String): String { Log.magenta("REST API: Stopping bot $name") return service.doWithBot(name) { it.stop() }.toString() } @RequestMapping(value = "/bot/{name}/pokemons", method = arrayOf(RequestMethod.GET)) fun listPokemons(@PathVariable name: String): List<PokemonData> { service.getBotContext(name).api.inventories.updateInventories(true) val pokemons = mutableListOf<PokemonData>() for (pokemon in service.getBotContext(name).api.inventories.pokebank.pokemons) { pokemons.add(PokemonData().buildFromPokemon(pokemon)) } return pokemons } @RequestMapping(value = "/bot/{name}/pokemon/{id}/transfer", method = arrayOf(RequestMethod.POST)) fun transferPokemon( @PathVariable name: String, @PathVariable id: Long ): String { val result: String val pokemon: Pokemon? = getPokemonById(service.getBotContext(name), id) result = pokemon!!.transferPokemon().toString() Log.magenta("REST API: Transferring pokemon ${pokemon.pokemonId.name} with stats (${pokemon.getStatsFormatted()} CP: ${pokemon.cp})") // Update GUI service.getBotContext(name).server.sendPokebank() return result } @RequestMapping(value = "/bot/{name}/pokemon/{id}/evolve", method = arrayOf(RequestMethod.POST)) fun evolvePokemon( @PathVariable name: String, @PathVariable id: Long, httpResponse: HttpServletResponse ): String { val result: String val pokemon: Pokemon? = getPokemonById(service.getBotContext(name), id) if (pokemon!!.candiesToEvolve > pokemon.candy) { httpResponse.status = HttpServletResponse.SC_BAD_REQUEST result = "Not enough candies to evolve: ${pokemon.candy}/${pokemon.candiesToEvolve}" } else { val evolutionResult: EvolutionResult val evolved: Pokemon evolutionResult = pokemon.evolve() evolved = evolutionResult.evolvedPokemon Log.magenta("REST API: Evolved pokemon ${pokemon.pokemonId.name} with stats (${pokemon.getStatsFormatted()} CP: ${pokemon.cp})" + " to pokemon ${evolved.pokemonId.name} with stats (${evolved.getStatsFormatted()} CP: ${evolved.cp})") result = evolutionResult.result.toString() } // Update GUI service.getBotContext(name).server.sendPokebank() return result } @RequestMapping(value = "/bot/{name}/pokemon/{id}/powerup", method = arrayOf(RequestMethod.POST)) fun powerUpPokemon( @PathVariable name: String, @PathVariable id: Long, httpResponse: HttpServletResponse ): String { val result: String val pokemon: Pokemon? = getPokemonById(service.getBotContext(name), id) if (pokemon!!.candyCostsForPowerup > pokemon.candy) { httpResponse.status = HttpServletResponse.SC_BAD_REQUEST result = "Not enough candies to powerup: ${pokemon.candy}/${pokemon.candyCostsForPowerup}" } else if (pokemon.stardustCostsForPowerup > service.getBotContext(name).api.playerProfile.currencies.get(PlayerProfile.Currency.STARDUST)!!.toInt()) { httpResponse.status = HttpServletResponse.SC_BAD_REQUEST result = "Not enough stardust to powerup: ${service.getBotContext(name).api.playerProfile.currencies.get(PlayerProfile.Currency.STARDUST)}/${pokemon.stardustCostsForPowerup}" } else { Log.magenta("REST API: Powering up pokemon ${pokemon.pokemonId.name} with stats (${pokemon.getStatsFormatted()} CP: ${pokemon.cp})") result = pokemon.powerUp().toString() Log.magenta("REST API: Pokemon new CP ${pokemon.cp}") } // Update GUI service.getBotContext(name).server.sendPokebank() return result } @RequestMapping(value = "/bot/{name}/pokemon/{id}/favorite", method = arrayOf(RequestMethod.POST)) fun togglePokemonFavorite( @PathVariable name: String, @PathVariable id: Long ): String { val result: String val pokemon: Pokemon? = getPokemonById(service.getBotContext(name), id) result = pokemon!!.setFavoritePokemon(!pokemon.isFavorite).toString() when (pokemon.isFavorite) { true -> Log.magenta("REST API: Pokemon ${pokemon.pokemonId.name} with stats (${pokemon.getStatsFormatted()} CP: ${pokemon.cp}) is favorited") false -> Log.magenta("REST API: Pokemon ${pokemon.pokemonId.name} with stats (${pokemon.getStatsFormatted()} CP: ${pokemon.cp}) is now unfavorited") } // Update GUI service.getBotContext(name).server.sendPokebank() return result } @RequestMapping(value = "/bot/{name}/pokemon/{id}/rename", method = arrayOf(RequestMethod.POST)) fun renamePokemon( @PathVariable name: String, @PathVariable id: Long, @RequestBody newName: String ): String { val pokemon: Pokemon? = getPokemonById(service.getBotContext(name), id) Log.magenta("REST API: Renamed pokemon ${pokemon!!.pokemonId.name} with stats (${pokemon.getStatsFormatted()} CP: ${pokemon.cp}) to $newName") return pokemon!!.renamePokemon(newName).toString() } @RequestMapping("/bot/{name}/items") fun listItems(@PathVariable name: String): List<ItemData> { service.getBotContext(name).api.inventories.updateInventories(true) val items = mutableListOf<ItemData>() for (item in service.getBotContext(name).api.inventories.itemBag.items) { items.add(ItemData().buildFromItem(item)) } return items } @RequestMapping(value = "/bot/{name}/item/{id}/drop/{quantity}", method = arrayOf(RequestMethod.DELETE)) fun dropItem( @PathVariable name: String, @PathVariable id: Int, @PathVariable quantity: Int, httpResponse: HttpServletResponse ): String { val itemBag: ItemBag = service.getBotContext(name).api.inventories.itemBag val item: Item? = itemBag.items.find { it.itemId.number == id } if (quantity > item!!.count) { httpResponse.status = HttpServletResponse.SC_BAD_REQUEST return "Not enough items to drop ${item.count}" } else { Log.magenta("REST API: Dropping ${quantity} ${item.itemId.name}") return itemBag.removeItem(item.itemId, quantity).toString() } } @RequestMapping(value = "/bot/{name}/useIncense", method = arrayOf(RequestMethod.POST)) fun useIncense( @PathVariable name: String, httpResponse: HttpServletResponse ): String { val itemBag = service.getBotContext(name).api.inventories.itemBag val count = itemBag.items.find { it.itemId == ItemIdOuterClass.ItemId.ITEM_INCENSE_ORDINARY }?.count if (count == 0) { httpResponse.status = HttpServletResponse.SC_BAD_REQUEST return "Not enough incenses" } else { itemBag.useIncense() Log.magenta("REST API: Used incense") return "SUCCESS" } } @RequestMapping(value = "/bot/{name}/useLuckyEgg", method = arrayOf(RequestMethod.POST)) fun useLuckyEgg( @PathVariable name: String, httpResponse: HttpServletResponse ): String { val itemBag = service.getBotContext(name).api.inventories.itemBag val count = itemBag.items.find { it.itemId == ItemIdOuterClass.ItemId.ITEM_LUCKY_EGG }?.count if (count == 0) { httpResponse.status = HttpServletResponse.SC_BAD_REQUEST return "Not enough lucky eggs" } else { Log.magenta("REST API: Used lucky egg") return itemBag.useLuckyEgg().result.toString() } } @RequestMapping(value = "/bot/{name}/location", method = arrayOf(RequestMethod.GET)) fun getLocation(@PathVariable name: String): LocationData { return LocationData( service.getBotContext(name).api.latitude, service.getBotContext(name).api.longitude ) } @RequestMapping(value = "/bot/{name}/location/{latitude}/{longitude}", method = arrayOf(RequestMethod.POST)) fun changeLocation( @PathVariable name: String, @PathVariable latitude: Double, @PathVariable longitude: Double, httpResponse: HttpServletResponse ): String { val ctx: Context = service.getBotContext(name) if (!latitude.isNaN() && !longitude.isNaN()) { ctx.server.coordinatesToGoTo.add(S2LatLng.fromDegrees(latitude, longitude)) Log.magenta("REST API: Added ToGoTo coordinates $latitude $longitude") return "SUCCESS" } else { httpResponse.status = HttpServletResponse.SC_BAD_REQUEST return "FAIL" } } @RequestMapping(value = "/bot/{name}/profile", method = arrayOf(RequestMethod.GET)) fun getProfile(@PathVariable name: String): ProfileData { return ProfileData().buildFromApi(service.getBotContext(name).api) } @RequestMapping(value = "/bot/{name}/pokedex", method = arrayOf(RequestMethod.GET)) fun getPokedex(@PathVariable name: String): List<PokedexEntry> { val pokedex = mutableListOf<PokedexEntry>() val api = service.getBotContext(name).api for (i in 0..151) { val entry: PokedexEntryOuterClass.PokedexEntry? = api.inventories.pokedex.getPokedexEntry(PokemonIdOuterClass.PokemonId.forNumber(i)) entry ?: continue pokedex.add(PokedexEntry().buildFromEntry(entry)) } return pokedex } @RequestMapping(value = "/bot/{name}/eggs", method = arrayOf(RequestMethod.GET)) fun getEggs(@PathVariable name: String): List<EggData> { service.getBotContext(name).api.inventories.updateInventories(true) val eggs = mutableListOf<EggData>() for (egg in service.getBotContext(name).api.inventories.hatchery.eggs) { eggs.add(EggData().buildFromEggPokemon(egg)) } return eggs } // FIXME! currently, the IDs returned by the API are not unique. It seems that only the last 6 digits change so we remove them fun getPokemonById(ctx: Context, id: Long): Pokemon? { return ctx.api.inventories.pokebank.pokemons.find { (("" + id).substring(0, ("" + id).length - 6)).equals(("" + it.id).substring(0, ("" + it.id).length - 6)) } } }
gpl-3.0
5d7949dbbef23cef668b6a317f22a63d
36.845361
186
0.653024
4.594493
false
false
false
false
google/horologist
network-awareness/src/main/java/com/google/android/horologist/networks/db/DBDataRequestRepository.kt
1
3181
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.networks.db import com.google.android.horologist.networks.ExperimentalHorologistNetworksApi import com.google.android.horologist.networks.data.DataRequest import com.google.android.horologist.networks.data.DataRequestRepository import com.google.android.horologist.networks.data.DataUsageReport import com.google.android.horologist.networks.data.NetworkType import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import java.time.Instant import java.time.LocalDate import java.time.ZoneOffset @ExperimentalHorologistNetworksApi public class DBDataRequestRepository( public val networkUsageDao: NetworkUsageDao, public val coroutineScope: CoroutineScope ) : DataRequestRepository { public val today: LocalDate = LocalDate.now() // TODO update on day roll public val day: Int = today.let { it.year * 1000 + it.dayOfYear } public val from: Instant = today.atStartOfDay().toInstant(ZoneOffset.UTC) public val to: Instant = today.plusDays(1).atStartOfDay().toInstant(ZoneOffset.UTC) override fun storeRequest(dataRequest: DataRequest) { val bytes = dataRequest.dataBytes coroutineScope.launch { var rows = networkUsageDao.updateBytes(day, bytes) if (rows == 0) { rows = networkUsageDao.insert(DataUsage(dataRequest.networkInfo.type.name, bytes, day)) .toInt() if (rows == -1) { networkUsageDao.updateBytes(day, bytes) } } } } override fun currentPeriodUsage(): Flow<DataUsageReport> { return networkUsageDao.getRecords(day).map { list -> var ble = 0L var cell = 0L var wifi = 0L var unknown = 0L list.forEach { when (it.networkType) { "ble" -> ble += it.bytesTotal "cell" -> cell += it.bytesTotal "wifi" -> wifi += it.bytesTotal "unknown" -> unknown += it.bytesTotal } } DataUsageReport( dataByType = mapOf( NetworkType.BT to ble, NetworkType.Cell to cell, NetworkType.Wifi to wifi, NetworkType.Unknown to unknown ), from = from, to = to ) } } }
apache-2.0
5e550d66399d977a3852ff7560a43109
34.344444
100
0.633763
4.878834
false
false
false
false
meh/watch_doge
src/main/java/meh/watchdoge/request/util.kt
1
625
package meh.watchdoge.request; import android.os.Message; open class Command(command: Int): Builder { protected val _command = command; override fun build(msg: Message) { msg.arg1 = msg.arg1 or (_command shl 8); } } open class CommandWithId(id: Int, command: Int): Command(command) { protected val _id = id; override fun build(msg: Message) { super.build(msg); msg.arg2 = _id; } } open class Family(family: Int): Builder { protected val _family = family; protected lateinit var _command: Command; override fun build(msg: Message) { msg.arg1 = msg.arg1 or _family; _command.build(msg); } }
agpl-3.0
37f49d96eb4de6b13afdbad17b93cf59
19.833333
67
0.6832
2.990431
false
false
false
false
wordpress-mobile/WordPress-FluxC-Android
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/model/order/TaxLine.kt
2
680
package org.wordpress.android.fluxc.model.order import com.google.gson.annotations.SerializedName /** * Represents a tax line */ class TaxLine { @SerializedName("id") val id: Long? = null @SerializedName("rate_id") val rateId: Long? = null @SerializedName("rate_code") val rateCode: String? = null @SerializedName("rate_percent") val ratePercent: Float? = null @SerializedName("label") val label: String? = null @SerializedName("compound") val compound: Boolean? = null @SerializedName("tax_total") val taxTotal: String? = null @SerializedName("shipping_tax_total") val shippingTaxTotal: String? = null }
gpl-2.0
2af252d16b90312f3d36da87494bbf80
20.25
49
0.669118
3.908046
false
false
false
false
sephiroth74/Material-BottomNavigation
bottom-navigation/src/main/java/it/sephiroth/android/library/bottomnavigation/VerticalScrollingBehavior.kt
1
4950
package it.sephiroth.android.library.bottomnavigation import android.content.Context import android.util.AttributeSet import android.view.View import androidx.annotation.IntDef import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.view.ViewCompat import java.lang.annotation.Retention import java.lang.annotation.RetentionPolicy /** * Created by alessandro on 4/2/16. */ abstract class VerticalScrollingBehavior<V : View>(context: Context, attrs: AttributeSet) : CoordinatorLayout.Behavior<V>(context, attrs) { private var mTotalDyUnconsumed = 0 private var mTotalDy = 0 /* @return Over scroll direction: SCROLL_DIRECTION_UP, SCROLL_DIRECTION_DOWN, SCROLL_NONE */ @ScrollDirection @get:ScrollDirection var overScrollDirection = ScrollDirection.SCROLL_NONE private set /** * @return Scroll direction: SCROLL_DIRECTION_UP, SCROLL_DIRECTION_DOWN, SCROLL_NONE */ @ScrollDirection @get:ScrollDirection var scrollDirection = ScrollDirection.SCROLL_NONE private set @Suppress("DEPRECATED_JAVA_ANNOTATION") @Retention(RetentionPolicy.SOURCE) @IntDef(ScrollDirection.SCROLL_DIRECTION_UP, ScrollDirection.SCROLL_DIRECTION_DOWN) annotation class ScrollDirection { companion object { const val SCROLL_DIRECTION_UP = 1 const val SCROLL_DIRECTION_DOWN = -1 const val SCROLL_NONE = 0 } } /** * @param coordinatorLayout * @param child * @param direction Direction of the over scroll: SCROLL_DIRECTION_UP, SCROLL_DIRECTION_DOWN * @param currentOverScroll Unconsumed value, negative or positive based on the direction; * @param totalOverScroll Cumulative value for current direction */ abstract fun onNestedVerticalOverScroll( coordinatorLayout: CoordinatorLayout, child: V, @ScrollDirection direction: Int, currentOverScroll: Int, totalOverScroll: Int) /** * @param scrollDirection Direction of the over scroll: SCROLL_DIRECTION_UP, SCROLL_DIRECTION_DOWN */ abstract fun onDirectionNestedPreScroll( coordinatorLayout: CoordinatorLayout, child: V, target: View, dx: Int, dy: Int, consumed: IntArray, @ScrollDirection scrollDirection: Int) override fun onStartNestedScroll( coordinatorLayout: CoordinatorLayout, child: V, directTargetChild: View, target: View, nestedScrollAxes: Int, @ViewCompat.NestedScrollType type: Int): Boolean { return nestedScrollAxes and ViewCompat.SCROLL_AXIS_VERTICAL != 0 } override fun onNestedScroll( coordinatorLayout: CoordinatorLayout, child: V, target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, @ViewCompat.NestedScrollType type: Int) { super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type) if (dyUnconsumed > 0 && mTotalDyUnconsumed < 0) { mTotalDyUnconsumed = 0 overScrollDirection = ScrollDirection.SCROLL_DIRECTION_UP } else if (dyUnconsumed < 0 && mTotalDyUnconsumed > 0) { mTotalDyUnconsumed = 0 overScrollDirection = ScrollDirection.SCROLL_DIRECTION_DOWN } mTotalDyUnconsumed += dyUnconsumed onNestedVerticalOverScroll(coordinatorLayout, child, overScrollDirection, dyConsumed, mTotalDyUnconsumed) } override fun onNestedPreScroll(coordinatorLayout: CoordinatorLayout, child: V, target: View, dx: Int, dy: Int, consumed: IntArray, @ViewCompat.NestedScrollType type: Int) { super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type) if (dy > 0 && mTotalDy < 0) { mTotalDy = 0 scrollDirection = ScrollDirection.SCROLL_DIRECTION_UP } else if (dy < 0 && mTotalDy > 0) { mTotalDy = 0 scrollDirection = ScrollDirection.SCROLL_DIRECTION_DOWN } mTotalDy += dy onDirectionNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, scrollDirection) } override fun onNestedFling( coordinatorLayout: CoordinatorLayout, child: V, target: View, velocityX: Float, velocityY: Float, consumed: Boolean): Boolean { super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed) scrollDirection = if (velocityY > 0) ScrollDirection.SCROLL_DIRECTION_UP else ScrollDirection.SCROLL_DIRECTION_DOWN return onNestedDirectionFling(coordinatorLayout, child, target, velocityX, velocityY, scrollDirection) } protected abstract fun onNestedDirectionFling( coordinatorLayout: CoordinatorLayout, child: V, target: View, velocityX: Float, velocityY: Float, @ScrollDirection scrollDirection: Int): Boolean }
mit
ba5af6eb106d220a9ea2ae075de32029
42.814159
126
0.69899
5.177824
false
false
false
false
JiangKlijna/blog
src/main/java/com/jiangKlijna/web/websocket/ChatWebSocketHandler.kt
1
3752
package com.jiangKlijna.web.websocket import com.jiangKlijna.web.app.ContextWrapper import com.jiangKlijna.web.bean.Message import com.jiangKlijna.web.bean.User import com.jiangKlijna.web.dao.MessageMapper import com.jiangKlijna.web.service.UserService import org.springframework.data.redis.connection.MessageListener import org.springframework.data.redis.core.RedisTemplate import org.springframework.stereotype.Component import org.springframework.web.socket.CloseStatus import org.springframework.web.socket.TextMessage import org.springframework.web.socket.WebSocketSession import org.springframework.web.socket.handler.TextWebSocketHandler import java.io.ByteArrayInputStream import java.io.ObjectInputStream import java.util.concurrent.CopyOnWriteArrayList import javax.annotation.Resource /** * Created by leil7 on 2017/6/6. */ @Component("ChatWebSocketHandler") class ChatWebSocketHandler : TextWebSocketHandler() { @Resource val rt: RedisTemplate<String, Message>? = null @Resource val us: UserService? = null @Resource val mm: MessageMapper? = null //接收文本消息 //只接受login信息,否则断开连接 override fun handleTextMessage(session: WebSocketSession, message: TextMessage) { try { val username = message.payload if (username == null || username.isEmpty()) throw RuntimeException("null") val re = us!!.get(username) if (!re.isSucess()) throw RuntimeException("unknown username") session.attributes["userid"] = (re.data as User).id } catch (e: Exception) { handleTransportError(session, e) } } //0.连接建立后处理 override fun afterConnectionEstablished(session: WebSocketSession) { sessions.add(session) // session.sendMessage(TextMessage("Server:connected OK!")) } //1.连接关闭后处理 override fun afterConnectionClosed(session: WebSocketSession, closeStatus: CloseStatus?) { sessions.remove(session) } //2.抛出异常时处理 override fun handleTransportError(session: WebSocketSession, exception: Throwable?) { if (session.isOpen) session.close() if (session in sessions) sessions.remove(session) } companion object { private val sessions = CopyOnWriteArrayList<WebSocketSession>() private fun <T : java.io.Serializable> ByteArray.toObject(): T = ObjectInputStream(ByteArrayInputStream(this)).readObject() as T private val updateMessage = TextMessage("update") } /** * msg.body为com.jiangKlijna.web.bean.Message * rt.convertAndSend(String, Message) */ class RedisMessageListener : MessageListener { @Throws override fun onMessage(msg: org.springframework.data.redis.connection.Message, p1: ByteArray?) { val m = msg.body.toObject<Message>() // 遍历所有session for (session in sessions) { if ("userid" !in session.attributes) continue if (m.touser != session.attributes["userid"]) continue session.sendMessage(updateMessage) } } } //@message 推送 fun publish(flag: Int, fromuser: Int, tousers: Collection<Int>, isSubThread: Boolean = true) { if (tousers.isEmpty()) return val core = fun() { for (touser in tousers) { val msg = Message(fromuser = fromuser, touser = touser, flag = flag) mm!!.insert(msg) rt!!.convertAndSend(Message::class.java.simpleName, msg) } } if (isSubThread) ContextWrapper.execute(Runnable { core() }) else core() } }
gpl-2.0
01fa6035e8460ae502d284cf5508f2e6
33.233645
104
0.669306
4.493252
false
false
false
false
lemmingapex/mage-android-sdk
sdk/src/main/java/mil/nga/giat/mage/sdk/Compatibility.kt
2
882
package mil.nga.giat.mage.sdk import android.content.Context import androidx.preference.PreferenceManager class Compatibility { data class Server(val major: Int, val minor: Int) companion object { val servers = listOf( Server(5, 4), Server(6, 0) ) fun isCompatibleWith(major: Int, minor: Int): Boolean { for (server: Server in servers) { if (server.major == major && server.minor <= minor) { return true } } return false; } fun isServerVersion5(applicationContext: Context): Boolean { val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(applicationContext) val majorVersion: Int = sharedPreferences.getInt(applicationContext.getString(R.string.serverVersionMajorKey), 0) return majorVersion == 5 } } }
apache-2.0
f2086342d5dd57f9fbfb8462aad8b680
26.59375
122
0.639456
4.819672
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/noteeditor/FieldState.kt
1
8711
/* * Copyright (c) 2020 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.noteeditor import android.content.Context import android.os.Bundle import android.util.SparseArray import android.view.View import com.ichi2.anki.FieldEditLine import com.ichi2.anki.NoteEditor import com.ichi2.anki.R import com.ichi2.libanki.Model import com.ichi2.libanki.Models import com.ichi2.utils.KotlinCleanup import com.ichi2.utils.MapUtil.getKeyByValue import org.json.JSONObject import java.util.* /** Responsible for recreating EditFieldLines after NoteEditor operations * This primarily exists so we can use saved instance state to repopulate the dynamically created FieldEditLine */ class FieldState private constructor(private val editor: NoteEditor) { private var mSavedFieldData: List<View.BaseSavedState>? = null fun loadFieldEditLines(type: FieldChangeType): List<FieldEditLine> { val fieldEditLines: List<FieldEditLine> if (type.type == Type.INIT && mSavedFieldData != null) { fieldEditLines = recreateFieldsFromState() mSavedFieldData = null } else { fieldEditLines = createFields(type) } for (l in fieldEditLines) { l.id = View.generateViewId() } if (type.type == Type.CLEAR_KEEP_STICKY) { // we use the UI values here as the model will post-processing steps (newline -> br). val currentFieldStrings = editor.currentFieldStrings val flds = editor.currentFields for (fldIdx in 0 until flds.length()) { if (flds.getJSONObject(fldIdx).getBoolean("sticky")) { fieldEditLines[fldIdx].setContent(currentFieldStrings[fldIdx], type.replaceNewlines) } } } if (type.type == Type.CHANGE_FIELD_COUNT) { val currentFieldStrings = editor.currentFieldStrings for (i in 0 until Math.min(currentFieldStrings.size, fieldEditLines.size)) { fieldEditLines[i].setContent(currentFieldStrings[i], type.replaceNewlines) } } return fieldEditLines } private fun recreateFieldsFromState(): List<FieldEditLine> { val editLines: MutableList<FieldEditLine> = ArrayList(mSavedFieldData!!.size) for (state in mSavedFieldData!!) { val edit_line_view = FieldEditLine(editor) if (edit_line_view.id == 0) { edit_line_view.id = View.generateViewId() } edit_line_view.loadState(state) editLines.add(edit_line_view) } return editLines } protected fun createFields(type: FieldChangeType): List<FieldEditLine> { val fields = getFields(type) val editLines: MutableList<FieldEditLine> = ArrayList(fields.size) for (i in fields.indices) { val edit_line_view = FieldEditLine(editor) editLines.add(edit_line_view) edit_line_view.name = fields[i][0] edit_line_view.setContent(fields[i][1], type.replaceNewlines) edit_line_view.setOrd(i) } return editLines } private fun getFields(type: FieldChangeType): Array<Array<String>> { if (type.type == Type.REFRESH_WITH_MAP) { val items = editor.fieldsFromSelectedNote val fMapNew = Models.fieldMap(type.newModel!!) return fromFieldMap(editor, items, fMapNew, type.modelChangeFieldMap) } return editor.fieldsFromSelectedNote } @Suppress("deprecation") // get fun setInstanceState(savedInstanceState: Bundle?) { if (savedInstanceState == null) { return } if (!savedInstanceState.containsKey("customViewIds") || !savedInstanceState.containsKey("android:viewHierarchyState")) { return } val customViewIds = savedInstanceState.getIntegerArrayList("customViewIds") val viewHierarchyState = savedInstanceState.getBundle("android:viewHierarchyState") if (customViewIds == null || viewHierarchyState == null) { return } val views = viewHierarchyState["android:views"] as SparseArray<*>? ?: return val important: MutableList<View.BaseSavedState> = ArrayList(customViewIds.size) for (i in customViewIds) { important.add(views[i!!] as View.BaseSavedState) } mSavedFieldData = important } /** How fields should be changed when the UI is rebuilt */ class FieldChangeType(val type: Type, val replaceNewlines: Boolean) { var modelChangeFieldMap: Map<Int, Int>? = null var newModel: Model? = null companion object { fun refreshWithMap(newModel: Model?, modelChangeFieldMap: Map<Int, Int>?, replaceNewlines: Boolean): FieldChangeType { val typeClass = FieldChangeType(Type.REFRESH_WITH_MAP, replaceNewlines) typeClass.newModel = newModel typeClass.modelChangeFieldMap = modelChangeFieldMap return typeClass } fun refresh(replaceNewlines: Boolean): FieldChangeType { return fromType(Type.REFRESH, replaceNewlines) } fun refreshWithStickyFields(replaceNewlines: Boolean): FieldChangeType { return fromType(Type.CLEAR_KEEP_STICKY, replaceNewlines) } fun changeFieldCount(replaceNewlines: Boolean): FieldChangeType { return fromType(Type.CHANGE_FIELD_COUNT, replaceNewlines) } fun onActivityCreation(replaceNewlines: Boolean): FieldChangeType { return fromType(Type.INIT, replaceNewlines) } private fun fromType(type: Type, replaceNewlines: Boolean): FieldChangeType { return FieldChangeType(type, replaceNewlines) } } } enum class Type { INIT, CLEAR_KEEP_STICKY, CHANGE_FIELD_COUNT, REFRESH, REFRESH_WITH_MAP } companion object { private fun allowFieldRemapping(oldFields: Array<Array<String>>): Boolean { return oldFields.size > 2 } fun fromEditor(editor: NoteEditor): FieldState { return FieldState(editor) } @KotlinCleanup("speed - no need for arrayOfNulls") private fun fromFieldMap(context: Context, oldFields: Array<Array<String>>, fMapNew: Map<String, Pair<Int, JSONObject>>, modelChangeFieldMap: Map<Int, Int>?): Array<Array<String>> { // Build array of label/values to provide to field EditText views val fields = Array(fMapNew.size) { arrayOfNulls<String>(2) } for (fname in fMapNew.keys) { val fieldPair = fMapNew[fname] ?: continue // Field index of new note type val i = fieldPair.first // Add values from old note type if they exist in map, otherwise make the new field empty if (modelChangeFieldMap!!.containsValue(i)) { // Get index of field from old note type given the field index of new note type val j = getKeyByValue(modelChangeFieldMap, i) ?: continue // Set the new field label text if (allowFieldRemapping(oldFields)) { // Show the content of old field if remapping is enabled fields[i][0] = String.format(context.resources.getString(R.string.field_remapping), fname, oldFields[j][0]) } else { fields[i][0] = fname } // Set the new field label value fields[i][1] = oldFields[j][1] } else { // No values from old note type exist in the mapping fields[i][0] = fname fields[i][1] = "" } } return fields.map { it.requireNoNulls() }.toTypedArray() } } }
gpl-3.0
5630e3901e1f2dd9fc0a3469515ebb47
41.91133
189
0.626909
4.888328
false
false
false
false
envoyproxy/envoy
mobile/examples/kotlin/hello_world/MainActivity.kt
2
5958
package io.envoyproxy.envoymobile.helloenvoykotlin import android.app.Activity import android.os.Bundle import android.os.Handler import android.os.HandlerThread import android.util.Log import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import io.envoyproxy.envoymobile.AndroidEngineBuilder import io.envoyproxy.envoymobile.Element import io.envoyproxy.envoymobile.Engine import io.envoyproxy.envoymobile.LogLevel import io.envoyproxy.envoymobile.RequestHeadersBuilder import io.envoyproxy.envoymobile.RequestMethod import io.envoyproxy.envoymobile.UpstreamHttpProtocol import io.envoyproxy.envoymobile.shared.Failure import io.envoyproxy.envoymobile.shared.ResponseRecyclerViewAdapter import io.envoyproxy.envoymobile.shared.Success import java.io.IOException import java.util.concurrent.Executors import java.util.concurrent.TimeUnit private const val REQUEST_HANDLER_THREAD_NAME = "hello_envoy_kt" private const val REQUEST_AUTHORITY = "api.lyft.com" private const val REQUEST_PATH = "/ping" private const val REQUEST_SCHEME = "https" private val FILTERED_HEADERS = setOf( "server", "filter-demo", "buffer-filter-demo", "async-filter-demo", "x-envoy-upstream-service-time" ) /** * The main activity of the app. */ class MainActivity : Activity() { private val thread = HandlerThread(REQUEST_HANDLER_THREAD_NAME) private lateinit var recyclerView: RecyclerView private lateinit var viewAdapter: ResponseRecyclerViewAdapter private lateinit var engine: Engine @Suppress("MaxLineLength") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) engine = AndroidEngineBuilder(application) .addLogLevel(LogLevel.DEBUG) .enableProxying(true) .addPlatformFilter(::DemoFilter) .addPlatformFilter(::BufferDemoFilter) .addPlatformFilter(::AsyncDemoFilter) .addNativeFilter("envoy.filters.http.buffer", "{\"@type\":\"type.googleapis.com/envoy.extensions.filters.http.buffer.v3.Buffer\",\"max_request_bytes\":5242880}") .addStringAccessor("demo-accessor", { "PlatformString" }) .setOnEngineRunning { Log.d("MainActivity", "Envoy async internal setup completed") } .setEventTracker({ for (entry in it.entries) { Log.d("MainActivity", "Event emitted: ${entry.key}, ${entry.value}") } }) .setLogger { Log.d("MainActivity", it) } .build() recyclerView = findViewById(R.id.recycler_view) as RecyclerView recyclerView.layoutManager = LinearLayoutManager(this) viewAdapter = ResponseRecyclerViewAdapter() recyclerView.adapter = viewAdapter val dividerItemDecoration = DividerItemDecoration( recyclerView.context, DividerItemDecoration.VERTICAL ) recyclerView.addItemDecoration(dividerItemDecoration) thread.start() val handler = Handler(thread.looper) // Run a request loop and record stats until the application exits. handler.postDelayed( object : Runnable { override fun run() { try { makeRequest() recordStats() } catch (e: IOException) { Log.d("MainActivity", "exception making request or recording stats", e) } // Make a call and report stats again handler.postDelayed(this, TimeUnit.SECONDS.toMillis(1)) } }, TimeUnit.SECONDS.toMillis(1) ) } override fun onDestroy() { super.onDestroy() thread.quit() } private fun makeRequest() { // Note: this request will use an h2 stream for the upstream request. // The Java example uses http/1.1. This is done on purpose to test both paths in end-to-end // tests in CI. val requestHeaders = RequestHeadersBuilder( RequestMethod.GET, REQUEST_SCHEME, REQUEST_AUTHORITY, REQUEST_PATH ) .addUpstreamHttpProtocol(UpstreamHttpProtocol.HTTP2) .build() engine .streamClient() .newStreamPrototype() .setOnResponseHeaders { responseHeaders, _, _ -> val status = responseHeaders.httpStatus ?: 0L val message = "received headers with status $status" val sb = StringBuilder() for ((name, value) in responseHeaders.caseSensitiveHeaders()) { if (name in FILTERED_HEADERS) { sb.append(name).append(": ").append(value.joinToString()).append("\n") } } val headerText = sb.toString() Log.d("MainActivity", message) responseHeaders.value("filter-demo")?.first()?.let { filterDemoValue -> Log.d("MainActivity", "filter-demo: $filterDemoValue") } if (status == 200) { recyclerView.post { viewAdapter.add(Success(message, headerText)) } } else { recyclerView.post { viewAdapter.add(Failure(message)) } } } .setOnError { error, _ -> val attemptCount = error.attemptCount ?: -1 val message = "failed with error after $attemptCount attempts: ${error.message}" Log.d("MainActivity", message) recyclerView.post { viewAdapter.add(Failure(message)) } } .start(Executors.newSingleThreadExecutor()) .sendHeaders(requestHeaders, true) } private fun recordStats() { val counter = engine.pulseClient().counter(Element("foo"), Element("bar"), Element("counter")) val gauge = engine.pulseClient().gauge(Element("foo"), Element("bar"), Element("gauge")) val timer = engine.pulseClient().timer(Element("foo"), Element("bar"), Element("timer")) val distribution = engine.pulseClient().distribution(Element("foo"), Element("bar"), Element("distribution")) counter.increment() counter.increment(5) gauge.set(5) gauge.add(10) gauge.sub(1) timer.recordDuration(15) distribution.recordValue(15) } }
apache-2.0
2f67faa828d8ff2fc94e9718f30acf48
34.464286
167
0.694864
4.527356
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/tactile_paving/AddTactilePavingKerb.kt
1
2294
package de.westnordost.streetcomplete.quests.tactile_paving import de.westnordost.streetcomplete.data.osm.mapdata.MapDataWithGeometry import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression import de.westnordost.streetcomplete.data.osm.osmquests.OsmElementQuestType import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.meta.updateWithCheckDate import de.westnordost.streetcomplete.data.osm.mapdata.Element import de.westnordost.streetcomplete.data.osm.mapdata.Node import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.BLIND import de.westnordost.streetcomplete.ktx.toYesNo import de.westnordost.streetcomplete.quests.kerb_height.couldBeAKerb import de.westnordost.streetcomplete.quests.kerb_height.findAllKerbNodes class AddTactilePavingKerb : OsmElementQuestType<Boolean> { private val eligibleKerbsFilter by lazy { """ nodes with !tactile_paving or tactile_paving = unknown or tactile_paving = no and tactile_paving older today -4 years or tactile_paving = yes and tactile_paving older today -8 years """.toElementFilterExpression() } override val commitMessage = "Add tactile paving on kerbs" override val wikiLink = "Key:tactile_paving" override val icon = R.drawable.ic_quest_kerb_tactile_paving override val enabledInCountries = COUNTRIES_WHERE_TACTILE_PAVING_IS_COMMON override val questTypeAchievements = listOf(BLIND) override fun getTitle(tags: Map<String, String>) = R.string.quest_tactile_paving_kerb_title override fun createForm() = TactilePavingForm() override fun getApplicableElements(mapData: MapDataWithGeometry): Iterable<Element> = mapData.findAllKerbNodes().filter { eligibleKerbsFilter.matches(it) } override fun isApplicableTo(element: Element): Boolean? = if (!eligibleKerbsFilter.matches(element) || element !is Node || !element.couldBeAKerb()) false else null override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) { changes.updateWithCheckDate("tactile_paving", answer.toYesNo()) changes.addOrModify("barrier", "kerb") } }
gpl-3.0
2cddfde3cdc6a6d047aeb7285c706d0a
46.791667
103
0.780732
4.597194
false
false
false
false
recurly/recurly-client-android
AndroidSdk/src/main/java/com/recurly/androidsdk/domain/RecurlyDataFormatter.kt
1
4269
package com.recurly.androidsdk.domain import android.content.Context import android.graphics.drawable.Drawable import androidx.core.content.ContextCompat import com.recurly.androidsdk.R import com.recurly.androidsdk.data.model.CreditCardsParameters internal object RecurlyDataFormatter { /** * @param number credit card number * @param validInput is recognized from a credit card pattern * @return Returns the credit card number as Long if it is correct, return 0 if the Card Number is invalid or if it don´t belongs to a credit card type */ internal fun getCardNumber(number: String, validInput: Boolean): Long { val cardNumber = number.replace(" ", "") return if (cardNumber.isNotEmpty() && validInput) cardNumber.toLong() else 0 } /** * @param expiration expiration date as string * @param validInput if it is a valid expiration date * @return Returns the month as an Int */ internal fun getExpirationMonth(expiration: String, validInput: Boolean): Int { val expirationDate = expiration.split("/") return if (expirationDate.size == 2 && validInput) { if (expirationDate[0].isNotEmpty()) expirationDate[0].toInt() else 0 } else 0 } /** * @param expiration expiration date as string * @param validInput if it is a valid expiration date * @return Returns the year as an Int */ internal fun getExpirationYear(expiration: String, validInput: Boolean): Int { val expirationDate = expiration.split("/") return if (expirationDate.size == 2 && validInput) { if (expirationDate[1].isNotEmpty()) expirationDate[1].toInt() else 0 } else 0 } /** * @param cvv cvv code * @param validInput if it is a valid cvv code * @return Returns the cvv code as an Int */ internal fun getCvvCode(cvv: String, validInput: Boolean): Int { return if (cvv.isNotEmpty() && validInput) cvv.toInt() else 0 } /** * This fun get as a parameter the card type from CreditCardData to change the credit card icon * @param context Context * @param cardType the card type according to CreditCardsParameters * @return Returns the icon of the credit card */ internal fun changeCardIcon(context: Context, cardType: String): Drawable { when (cardType) { CreditCardsParameters.HIPERCARD.cardType -> return ContextCompat.getDrawable(context, R.drawable.ic_hipercard_card)!! CreditCardsParameters.AMERICAN_EXPRESS.cardType -> return ContextCompat.getDrawable(context, R.drawable.ic_amex_card)!! CreditCardsParameters.DINERS_CLUB.cardType -> return ContextCompat.getDrawable(context, R.drawable.ic_diners_club_card)!! CreditCardsParameters.DISCOVER.cardType -> return ContextCompat.getDrawable(context, R.drawable.ic_discover_card)!! CreditCardsParameters.ELO.cardType -> return ContextCompat.getDrawable(context, R.drawable.ic_elo_card)!! CreditCardsParameters.JCB.cardType -> return ContextCompat.getDrawable(context, R.drawable.ic_jcb_card)!! CreditCardsParameters.MASTER.cardType -> return ContextCompat.getDrawable(context, R.drawable.ic_mastercard_card)!! CreditCardsParameters.TARJETA_NARANJA.cardType -> return ContextCompat.getDrawable(context, R.drawable.ic_tarjeta_naranja_card)!! CreditCardsParameters.UNION_PAY.cardType -> return ContextCompat.getDrawable(context, R.drawable.ic_union_pay_card)!! CreditCardsParameters.VISA.cardType -> return ContextCompat.getDrawable(context, R.drawable.ic_visa_card)!! else -> return ContextCompat.getDrawable(context, R.drawable.ic_generic_valid_card)!! } } }
mit
103662024a9df8e0dc491bbf8bdc6b1f
39.456311
155
0.618791
5.062871
false
false
false
false
aleksey-zhidkov/jeb-k
src/main/kotlin/jeb/JebExecException.kt
1
537
package jeb import java.io.IOException class JebExecException( val cmd: String, val stdout: String, val stderr: String, val returnCode: Int, cause: Throwable? = null) : IOException("Could not execute $cmd", cause) { override fun toString(): String { return """ |Jeb error |Command: $cmd |Return code: $returnCode |Standard Out: |$stdout | ==== |Standard Error: |$stderr | ==== """.trimMargin() } }
apache-2.0
fc27b613f80a9deb573a787194f63212
20.48
82
0.519553
4.365854
false
false
false
false
CarrotCodes/Pellet
server/src/integrationTest/kotlin/dev/pellet/integration/NoContentBenchmarkTest.kt
1
4341
package dev.pellet.integration import dev.pellet.logging.pelletLogger import dev.pellet.server.PelletBuilder.pelletServer import dev.pellet.server.PelletConnector import dev.pellet.server.routing.http.HTTPRouteResponse import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.delay import kotlinx.coroutines.future.await import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.yield import okhttp3.Call import okhttp3.Callback import okhttp3.ConnectionPool import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import java.io.IOException import java.time.Duration import java.time.Instant import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger import kotlin.test.Test class NoContentBenchmarkTest { private val logger = pelletLogger<NoContentBenchmarkTest>() private val numberOfRequests = System.getProperty("benchmark.requests.total")?.toIntOrNull() ?: 1_000_000 @Test fun `benchmark no content response`() = runBlocking { val counter = AtomicInteger(numberOfRequests) val pellet = pelletServer { logRequests = false httpConnector { endpoint = PelletConnector.Endpoint( "127.0.0.1", 9001 ) router { get("/") { counter.decrementAndGet() HTTPRouteResponse.Builder() .noContent() .build() } } } } val job = pellet.start() val client = OkHttpClient().newBuilder() .connectionPool(ConnectionPool(30, 1L, TimeUnit.MINUTES)) .build() client.dispatcher.maxRequestsPerHost = 30 client.connectionPool.connectionCount() logger.info { "sending ${counter.get()} requests..." } val dispatcher = Dispatchers.Default val channel = Channel<Request>() val supervisor = SupervisorJob() val scope = CoroutineScope(dispatcher + supervisor) scope.launch { numberOfRequests.downTo(0).map { val request = Request.Builder() .url("http://127.0.0.1:9001") .get() .build() channel.send(request) } } val processorCount = Runtime.getRuntime().availableProcessors() val startTime = Instant.now() processorCount.downTo(0).map { scope.async { sendRequests(client, channel) } } scope.async { while (this.isActive) { val count = counter.get() if (count <= 0) { supervisor.cancel() return@async } logger.info { "left to complete: $count" } delay(1000L) } }.join() job.cancel() val endTime = Instant.now() val timeElapsedMs = Duration.between(startTime, endTime).toMillis() val rps = (numberOfRequests / timeElapsedMs.toDouble()) * 1000L logger.info { "completed rps: $rps" } } private suspend fun CoroutineScope.sendRequests( client: OkHttpClient, channel: Channel<Request> ) { while (this.isActive) { val request = channel.receive() val future = CompletableFuture<Response>() client.newCall(request).enqueue(toCallback(future)) val response = future.await() assert(response.code == 204) yield() } } private fun toCallback(future: CompletableFuture<Response>): Callback { return object : Callback { override fun onFailure(call: Call, e: IOException) { future.completeExceptionally(e) } override fun onResponse(call: Call, response: Response) { future.complete(response) } } } }
apache-2.0
de0b5987625aa962a477141b025a1082
31.886364
109
0.597558
5.024306
false
false
false
false
Kotlin/kotlinx.serialization
formats/json/commonMain/src/kotlinx/serialization/json/internal/StreamingJsonDecoder.kt
1
15199
/* * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.json.internal import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* import kotlinx.serialization.encoding.CompositeDecoder.Companion.DECODE_DONE import kotlinx.serialization.encoding.CompositeDecoder.Companion.UNKNOWN_NAME import kotlinx.serialization.internal.* import kotlinx.serialization.json.* import kotlinx.serialization.modules.* import kotlin.jvm.* /** * [JsonDecoder] which reads given JSON from [AbstractJsonLexer] field by field. */ @OptIn(ExperimentalSerializationApi::class) internal open class StreamingJsonDecoder( final override val json: Json, private val mode: WriteMode, @JvmField internal val lexer: AbstractJsonLexer, descriptor: SerialDescriptor, discriminatorHolder: DiscriminatorHolder? ) : JsonDecoder, AbstractDecoder() { // A mutable reference to the discriminator that have to be skipped when in optimistic phase // of polymorphic serialization, see `decodeSerializableValue` internal class DiscriminatorHolder(@JvmField var discriminatorToSkip: String?) private fun DiscriminatorHolder?.trySkip(unknownKey: String): Boolean { if (this == null) return false if (discriminatorToSkip == unknownKey) { discriminatorToSkip = null return true } return false } override val serializersModule: SerializersModule = json.serializersModule private var currentIndex = -1 private var discriminatorHolder: DiscriminatorHolder? = discriminatorHolder private val configuration = json.configuration private val elementMarker: JsonElementMarker? = if (configuration.explicitNulls) null else JsonElementMarker(descriptor) override fun decodeJsonElement(): JsonElement = JsonTreeReader(json.configuration, lexer).read() @Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE") override fun <T> decodeSerializableValue(deserializer: DeserializationStrategy<T>): T { try { /* * This is an optimized path over decodeSerializableValuePolymorphic(deserializer): * dSVP reads the very next JSON tree into a memory as JsonElement and then runs TreeJsonDecoder over it * in order to deal with an arbitrary order of keys, but with the price of additional memory pressure * and CPU consumption. * We would like to provide the best possible performance for data produced by kotlinx.serialization * itself, for that we do the following optimistic optimization: * * 0) Remember current position in the string * 1) Read the very next key of JSON structure * 2) If it matches* the discriminator key, read the value, remember current position * 3) Return the value, recover an initial position * (*) -- if it doesn't match, fallback to dSVP method. */ if (deserializer !is AbstractPolymorphicSerializer<*> || json.configuration.useArrayPolymorphism) { return deserializer.deserialize(this) } val discriminator = deserializer.descriptor.classDiscriminator(json) val type = lexer.consumeLeadingMatchingValue(discriminator, configuration.isLenient) var actualSerializer: DeserializationStrategy<out Any>? = null if (type != null) { actualSerializer = deserializer.findPolymorphicSerializerOrNull(this, type) } if (actualSerializer == null) { // Fallback if we haven't found discriminator or serializer return decodeSerializableValuePolymorphic<T>(deserializer as DeserializationStrategy<T>) } discriminatorHolder = DiscriminatorHolder(discriminator) @Suppress("UNCHECKED_CAST") val result = actualSerializer.deserialize(this) as T return result } catch (e: MissingFieldException) { throw MissingFieldException(e.missingFields, e.message + " at path: " + lexer.path.getPath(), e) } } override fun beginStructure(descriptor: SerialDescriptor): CompositeDecoder { val newMode = json.switchMode(descriptor) lexer.path.pushDescriptor(descriptor) lexer.consumeNextToken(newMode.begin) checkLeadingComma() return when (newMode) { // In fact resets current index that these modes rely on WriteMode.LIST, WriteMode.MAP, WriteMode.POLY_OBJ -> StreamingJsonDecoder( json, newMode, lexer, descriptor, discriminatorHolder ) else -> if (mode == newMode && json.configuration.explicitNulls) { this } else { StreamingJsonDecoder(json, newMode, lexer, descriptor, discriminatorHolder) } } } override fun endStructure(descriptor: SerialDescriptor) { // If we're ignoring unknown keys, we have to skip all un-decoded elements, // e.g. for object serialization. It can be the case when the descriptor does // not have any elements and decodeElementIndex is not invoked at all if (json.configuration.ignoreUnknownKeys && descriptor.elementsCount == 0) { skipLeftoverElements(descriptor) } // First consume the object so we know it's correct lexer.consumeNextToken(mode.end) // Then cleanup the path lexer.path.popDescriptor() } private fun skipLeftoverElements(descriptor: SerialDescriptor) { while (decodeElementIndex(descriptor) != DECODE_DONE) { // Skip elements } } override fun decodeNotNullMark(): Boolean { return !(elementMarker?.isUnmarkedNull ?: false) && lexer.tryConsumeNotNull() } override fun decodeNull(): Nothing? { // Do nothing, null was consumed by `decodeNotNullMark` return null } private fun checkLeadingComma() { if (lexer.peekNextToken() == TC_COMMA) { lexer.fail("Unexpected leading comma") } } override fun <T> decodeSerializableElement( descriptor: SerialDescriptor, index: Int, deserializer: DeserializationStrategy<T>, previousValue: T? ): T { val isMapKey = mode == WriteMode.MAP && index and 1 == 0 // Reset previous key if (isMapKey) { lexer.path.resetCurrentMapKey() } // Deserialize the key val value = super.decodeSerializableElement(descriptor, index, deserializer, previousValue) // Put the key to the path if (isMapKey) { lexer.path.updateCurrentMapKey(value) } return value } override fun decodeElementIndex(descriptor: SerialDescriptor): Int { val index = when (mode) { WriteMode.OBJ -> decodeObjectIndex(descriptor) WriteMode.MAP -> decodeMapIndex() else -> decodeListIndex() // Both for LIST and default polymorphic } // The element of the next index that will be decoded if (mode != WriteMode.MAP) { lexer.path.updateDescriptorIndex(index) } return index } private fun decodeMapIndex(): Int { var hasComma = false val decodingKey = currentIndex % 2 != 0 if (decodingKey) { if (currentIndex != -1) { hasComma = lexer.tryConsumeComma() } } else { lexer.consumeNextToken(COLON) } return if (lexer.canConsumeValue()) { if (decodingKey) { if (currentIndex == -1) lexer.require(!hasComma) { "Unexpected trailing comma" } else lexer.require(hasComma) { "Expected comma after the key-value pair" } } ++currentIndex } else { if (hasComma) lexer.fail("Expected '}', but had ',' instead") CompositeDecoder.DECODE_DONE } } /* * Checks whether JSON has `null` value for non-null property or unknown enum value for enum property */ private fun coerceInputValue(descriptor: SerialDescriptor, index: Int): Boolean = json.tryCoerceValue( descriptor.getElementDescriptor(index), { !lexer.tryConsumeNotNull() }, { lexer.peekString(configuration.isLenient) }, { lexer.consumeString() /* skip unknown enum string*/ } ) private fun decodeObjectIndex(descriptor: SerialDescriptor): Int { // hasComma checks are required to properly react on trailing commas var hasComma = lexer.tryConsumeComma() while (lexer.canConsumeValue()) { // TODO: consider merging comma consumption and this check hasComma = false val key = decodeStringKey() lexer.consumeNextToken(COLON) val index = descriptor.getJsonNameIndex(json, key) val isUnknown = if (index != UNKNOWN_NAME) { if (configuration.coerceInputValues && coerceInputValue(descriptor, index)) { hasComma = lexer.tryConsumeComma() false // Known element, but coerced } else { elementMarker?.mark(index) return index // Known element without coercing, return it } } else { true // unknown element } if (isUnknown) { // slow-path for unknown keys handling hasComma = handleUnknown(key) } } if (hasComma) lexer.fail("Unexpected trailing comma") return elementMarker?.nextUnmarkedIndex() ?: CompositeDecoder.DECODE_DONE } private fun handleUnknown(key: String): Boolean { if (configuration.ignoreUnknownKeys || discriminatorHolder.trySkip(key)) { lexer.skipElement(configuration.isLenient) } else { // Here we cannot properly update json path indices // as we do not have a proper SerialDescriptor in our hands lexer.failOnUnknownKey(key) } return lexer.tryConsumeComma() } private fun decodeListIndex(): Int { // Prohibit leading comma val hasComma = lexer.tryConsumeComma() return if (lexer.canConsumeValue()) { if (currentIndex != -1 && !hasComma) lexer.fail("Expected end of the array or comma") ++currentIndex } else { if (hasComma) lexer.fail("Unexpected trailing comma") CompositeDecoder.DECODE_DONE } } override fun decodeBoolean(): Boolean { /* * We prohibit any boolean literal that is not strictly 'true' or 'false' as it is considered way too * error-prone, but allow quoted literal in relaxed mode for booleans. */ return if (configuration.isLenient) { lexer.consumeBooleanLenient() } else { lexer.consumeBoolean() } } /* * The rest of the primitives are allowed to be quoted and unquoted * to simplify integrations with third-party API. */ override fun decodeByte(): Byte { val value = lexer.consumeNumericLiteral() // Check for overflow if (value != value.toByte().toLong()) lexer.fail("Failed to parse byte for input '$value'") return value.toByte() } override fun decodeShort(): Short { val value = lexer.consumeNumericLiteral() // Check for overflow if (value != value.toShort().toLong()) lexer.fail("Failed to parse short for input '$value'") return value.toShort() } override fun decodeInt(): Int { val value = lexer.consumeNumericLiteral() // Check for overflow if (value != value.toInt().toLong()) lexer.fail("Failed to parse int for input '$value'") return value.toInt() } override fun decodeLong(): Long { return lexer.consumeNumericLiteral() } override fun decodeFloat(): Float { val result = lexer.parseString("float") { toFloat() } val specialFp = json.configuration.allowSpecialFloatingPointValues if (specialFp || result.isFinite()) return result lexer.throwInvalidFloatingPointDecoded(result) } override fun decodeDouble(): Double { val result = lexer.parseString("double") { toDouble() } val specialFp = json.configuration.allowSpecialFloatingPointValues if (specialFp || result.isFinite()) return result lexer.throwInvalidFloatingPointDecoded(result) } override fun decodeChar(): Char { val string = lexer.consumeStringLenient() if (string.length != 1) lexer.fail("Expected single char, but got '$string'") return string[0] } private fun decodeStringKey(): String { return if (configuration.isLenient) { lexer.consumeStringLenientNotNull() } else { lexer.consumeKeyString() } } override fun decodeString(): String { return if (configuration.isLenient) { lexer.consumeStringLenientNotNull() } else { lexer.consumeString() } } override fun decodeInline(descriptor: SerialDescriptor): Decoder = if (descriptor.isUnsignedNumber) JsonDecoderForUnsignedTypes(lexer, json) else super.decodeInline(descriptor) override fun decodeEnum(enumDescriptor: SerialDescriptor): Int { return enumDescriptor.getJsonNameIndexOrThrow(json, decodeString(), " at path " + lexer.path.getPath()) } } @InternalSerializationApi public fun <T> Json.decodeStringToJsonTree( deserializer: DeserializationStrategy<T>, source: String ): JsonElement { val lexer = StringJsonLexer(source) val input = StreamingJsonDecoder(this, WriteMode.OBJ, lexer, deserializer.descriptor, null) val tree = input.decodeJsonElement() lexer.expectEof() return tree } @OptIn(ExperimentalSerializationApi::class) internal class JsonDecoderForUnsignedTypes( private val lexer: AbstractJsonLexer, json: Json ) : AbstractDecoder() { override val serializersModule: SerializersModule = json.serializersModule override fun decodeElementIndex(descriptor: SerialDescriptor): Int = error("unsupported") override fun decodeInt(): Int = lexer.parseString("UInt") { toUInt().toInt() } override fun decodeLong(): Long = lexer.parseString("ULong") { toULong().toLong() } override fun decodeByte(): Byte = lexer.parseString("UByte") { toUByte().toByte() } override fun decodeShort(): Short = lexer.parseString("UShort") { toUShort().toShort() } } private inline fun <T> AbstractJsonLexer.parseString(expectedType: String, block: String.() -> T): T { val input = consumeStringLenient() try { return input.block() } catch (e: IllegalArgumentException) { fail("Failed to parse type '$expectedType' for input '$input'") } }
apache-2.0
bcae88fa023a81ce7a190f5043d3e2d1
38.17268
124
0.641621
5.190915
false
false
false
false
kropp/intellij-makefile
src/test/kotlin/MakefileFindUsagesTest.kt
1
1023
import com.intellij.codeInsight.* import com.intellij.find.* import com.intellij.find.impl.* import com.intellij.testFramework.fixtures.* import org.hamcrest.core.IsNull.* import org.junit.Assert.* class MakefileFindUsagesTest : BasePlatformTestCase() { fun testSimple() { val usages = myFixture.testFindUsages("$basePath/${getTestName(true)}.mk") assertEquals(2, usages.size) } fun testPhony() = notSearchableForUsages() fun testForce() = notSearchableForUsages() fun notSearchableForUsages() { myFixture.configureByFiles("$basePath/${getTestName(true)}.mk") val targetElement = TargetElementUtil.findTargetElement(myFixture.editor, TargetElementUtil.ELEMENT_NAME_ACCEPTED or TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED) val handler = (FindManager.getInstance(project) as FindManagerImpl).findUsagesManager.getFindUsagesHandler(targetElement!!, false) assertThat(handler, nullValue()) } override fun getTestDataPath() = "testData" override fun getBasePath() = "findUsages" }
mit
79f259c3663f705e9917acc44424ae32
35.571429
167
0.772239
4.628959
false
true
false
false
cempo/SimpleTodoList
app/src/main/java/com/makeevapps/simpletodolist/viewmodel/TodayViewModel.kt
1
1389
package com.makeevapps.simpletodolist.viewmodel import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.ViewModel import com.makeevapps.simpletodolist.App import com.makeevapps.simpletodolist.datasource.db.table.Task import com.makeevapps.simpletodolist.datasource.preferences.PreferenceManager import com.makeevapps.simpletodolist.repository.TaskRepository import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject class TodayViewModel : ViewModel() { @Inject lateinit var preferenceManager: PreferenceManager @Inject lateinit var taskRepository: TaskRepository private val tasksResponse = MutableLiveData<List<Task>>() private val compositeDisposable = CompositeDisposable() init { App.component.inject(this) compositeDisposable.add(taskRepository.getTodayTasks().subscribe({ result -> tasksResponse.value = result })) } fun is24HoursFormat(): Boolean = preferenceManager.is24HourFormat() fun insertOrUpdateTask(task: Task) { compositeDisposable.add(taskRepository.insertOrUpdateTask(task).subscribe()) } fun removeTask(task: Task) { compositeDisposable.add(taskRepository.deleteTask(task).subscribe()) } fun getTasksResponse(): MutableLiveData<List<Task>> = tasksResponse override fun onCleared() { compositeDisposable.clear() } }
mit
cb5de03ecce9529722ebae8f77bd04e2
31.325581
117
0.770338
5.202247
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/lang/commands/LatexOperatorCommand.kt
1
18669
package nl.hannahsten.texifyidea.lang.commands import nl.hannahsten.texifyidea.lang.LatexPackage import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.AMSSYMB import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.STMARYRD /** * @author Hannah Schellekens */ enum class LatexOperatorCommand( override val command: String, override vararg val arguments: Argument = emptyArray(), override val dependency: LatexPackage = LatexPackage.DEFAULT, override val display: String? = null, override val isMathMode: Boolean = true, val collapse: Boolean = false ) : LatexCommand { FOR_ALL("forall", display = "∀", collapse = true), PARTIAL("partial", display = "∂", collapse = true), EXISTS("exists", display = "∃", collapse = true), NOT_EXISTS("nexists", dependency = AMSSYMB, display = "∄", collapse = true), EMPTY_SET("emptyset", display = "∅", collapse = true), NOTHING("varnothing", dependency = AMSSYMB, display = "∅", collapse = true), NABLA("nabla", display = "∇", collapse = true), ELEMENT_OF("in", display = "∈", collapse = true), NOT_ELEMENT_OF("notin", display = "∉", collapse = true), CONTAIN_AS_MEMBER("ni", display = "∋", collapse = true), COMPLEMENT("complement", dependency = AMSSYMB, display = "∁"), N_ARY_PRODUCT("prod", display = "∏", collapse = true), N_ARY_COPRODUCT("coprod", display = "∐", collapse = true), SUM("sum", display = "∑", collapse = true), MINUS_PLUS("mp", display = "∓", collapse = true), PLUS_MINUS("pm", display = "±", collapse = true), SET_MINUS("setminus", display = "∖", collapse = true), SMALL_SET_MINUS("smallsetminus", dependency = AMSSYMB, display = "∖", collapse = true), ASTERISK("ast", display = "∗"), STAR("star", display = "⋆", collapse = true), DOT_PLUS("dotplus", dependency = AMSSYMB, display = "∔"), CIRCLE("circ", display = "∘"), BULLET("bullet", display = "∙"), PROPORTIONAL_TO("propto", display = "∝", collapse = true), PROPORTIONAL_TO_SYMBOL("varpropto", dependency = AMSSYMB, display = "∝", collapse = true), INFINITY("infty", display = "∞", collapse = true), ANGLE("angle", display = "∠", collapse = true), MEASURED_ANGLE("measuredangle", dependency = AMSSYMB, display = "∡", collapse = true), SPHERICAL_ANGLE("sphericalangle", dependency = AMSSYMB, display = "∢", collapse = true), MID("mid", display = "∣", collapse = true), MID_SHORT("shortmid", dependency = AMSSYMB, display = "∣", collapse = true), NOT_MID_SHORT("nshortmid", dependency = AMSSYMB), PARALLEL("parallel", display = "∥", collapse = true), NOT_PARALLEL("nparallel", dependency = AMSSYMB, display = "∦", collapse = true), PARALLEL_SHORT("shortparallel", display = "∥", collapse = true), NOT_PARALLEL_SHORT("nshortparallel", dependency = AMSSYMB, display = "∦", collapse = true), LOGICAL_AND("land", display = "∧", collapse = true), LOGICAL_OR("lor", display = "∨", collapse = true), INTERSECTION("cap", display = "∩", collapse = true), UNION("cup", display = "∪", collapse = true), DOUBLE_UNION("Cup", dependency = AMSSYMB, display = "⋓", collapse = true), DOUBLE_INTERSECTION("Cap", dependency = AMSSYMB, display = "⋒", collapse = true), INTEGRAL("int", display = "∫", collapse = true), DOUBLE_INTEGRAL("iint", dependency = LatexPackage.AMSMATH, display = "∬", collapse = true), TRIPLE_INTEGRAL("iiint", dependency = LatexPackage.AMSMATH, display = "∭", collapse = true), QUADRUPLE_INTEGRAL("iiiint", dependency = LatexPackage.AMSMATH, display = "⨌", collapse = true), DOTS_INTEGRAL("idotsint", display = "∫⋯∫", collapse = true), CONTOUR_INTEGRAL("oint", display = "∮", collapse = true), THEREFORE("therefore", dependency = AMSSYMB, display = "∴", collapse = true), BECAUSE("because", dependency = AMSSYMB, display = "∵", collapse = true), TILDE_OPERATOR("sim", display = "∼", collapse = true), WREATH_PRODUCT("wr", display = "≀", collapse = true), APPROX("approx", display = "≈", collapse = true), NOT_EQUAL("neq", display = "≠", collapse = true), EQUIVALENT("equiv", display = "≡", collapse = true), LESS_THAN_EQUAL("leq", display = "≤", collapse = true), LESS_THAN_NOT_EQUAL("lneq", dependency = AMSSYMB, display = "⪇", collapse = true), LESS_THAN_EQUALL("leqq", dependency = AMSSYMB, display = "≦", collapse = true), GREATER_THAN_EQUAL("geq", display = "≥", collapse = true), GREATER_THAN_NOT_EQUAL("gneq", dependency = AMSSYMB, display = "⪈", collapse = true), GREATER_THAN_EQUALL("geqq", dependency = AMSSYMB, display = "≧", collapse = true), NOT_LESS_THAN("nless", dependency = AMSSYMB, display = "≮", collapse = true), NOT_GREATER_THAN("ngtr", dependency = AMSSYMB, display = "≯", collapse = true), NOT_LESS_THAN_EQUAL("nleq", dependency = AMSSYMB, display = "≰", collapse = true), NOT_LESS_THAN_EQUALL("nleqq", dependency = AMSSYMB, display = "≦\u200D\u0338"), NOT_GREATER_THAN_EQUAL("ngeq", dependency = AMSSYMB, display = "≱", collapse = true), NOT_GREATER_THAN_EQUALL("ngeqq", dependency = AMSSYMB, display = "≧\u200D\u0338"), DOUBLE_LESS_THAN("ll", dependency = AMSSYMB, display = "≪", collapse = true), LESS_LESS_LESS("lll", dependency = AMSSYMB, display = "⋘", collapse = true), LESS_NOT_EQUAL("lneqq", dependency = AMSSYMB, display = "≨", collapse = true), GREATER_NOT_EQUAL("gneqq", dependency = AMSSYMB, display = "≩", collapse = true), DOUBLE_GREATER_THAN("gg", dependency = AMSSYMB, display = "≫", collapse = true), GREATER_GREATER_GREATER("ggg", dependency = AMSSYMB, display = "⋙", collapse = true), SUBSET("subset", display = "⊂", collapse = true), SUPERSET("supset", display = "⊃", collapse = true), SUBSET_EQUALS("subseteq", display = "⊆", collapse = true), SUBSET_EQUALSS("subseteqq", dependency = AMSSYMB, display = "⊆", collapse = true), SUPERSET_EQUALS("supseteq", display = "⊇", collapse = true), SUPERSET_EQUALSS("supseteqq", dependency = AMSSYMB, display = "⊇", collapse = true), NOT_SUBSET_EQUALS("nsubseteq", dependency = AMSSYMB, display = "⊈", collapse = true), NOT_SUBSET_EQUALSS("nsubseteqq", dependency = AMSSYMB, display = "⊈", collapse = true), NOT_SUPERSET_EQUALS("nsupseteq", dependency = AMSSYMB, display = "⊉", collapse = true), NOT_SUPERSET_EQUALSS("nsupseteqq", dependency = AMSSYMB, display = "⊉", collapse = true), SQUARE_SUBSET("sqsubset", dependency = AMSSYMB, display = "⊏", collapse = true), SQUARE_SUPERSET("sqsupset", dependency = AMSSYMB, display = "⊐", collapse = true), SQUARE_SUBSET_EQUALS("sqsubseteq", dependency = AMSSYMB, display = "⊑", collapse = true), SQUARE_SUPERSET_EQUALS("sqsupseteq", dependency = AMSSYMB, display = "⊒", collapse = true), SQUARE_CAP("sqcap", display = "⊓", collapse = true), SQUARE_CUP("sqcup", display = "⊔", collapse = true), CIRCLED_PLUS("oplus", display = "⊕", collapse = true), CIRCLED_MINUS("ominus", display = "⊖", collapse = true), CIRCLED_TIMES("otimes", display = "⊗", collapse = true), CIRCLED_SLASH("oslash", display = "⊘", collapse = true), CIRCLED_DOT("odot", display = "⊙", collapse = true), BOXED_PLUS("boxplus", dependency = AMSSYMB, display = "⊞", collapse = true), BOXED_MINUS("boxminus", dependency = AMSSYMB, display = "⊟", collapse = true), BOXED_TIMES("boxtimes", dependency = AMSSYMB, display = "⊠", collapse = true), BOXED_DOT("boxdot", dependency = AMSSYMB, display = "⊡", collapse = true), BOWTIE("bowtie", display = "⋈", collapse = true), JOIN("Join", dependency = AMSSYMB, display = "⨝", collapse = true), TRIANGLE_RIGHT("triangleright", dependency = AMSSYMB, display = "▷", collapse = true), TRIANGLE_LEFT("triangleleft", dependency = AMSSYMB, display = "◁", collapse = true), LHD("lhd", dependency = AMSSYMB, display = "◁", collapse = true), RHD("rhd", dependency = AMSSYMB, display = "▷", collapse = true), UN_LHD("unlhd", dependency = AMSSYMB, display = "⊴", collapse = true), UN_RHD("unrhd", dependency = AMSSYMB, display = "⊵", collapse = true), TRIANGLELEFTEQ("tranglelefteq", dependency = AMSSYMB, display = "⊴", collapse = true), TRIANGLERIGHTEQ("trianglerighteq", dependency = AMSSYMB, display = "⊵", collapse = true), LTIMES("ltimes", dependency = AMSSYMB, display = "⋉", collapse = true), RTIMES("rtimes", dependency = AMSSYMB, display = "⋊", collapse = true), TIMES("times", display = "×", collapse = true), LEFT_THREE_TIMES("leftthreetimes", dependency = AMSSYMB, display = "⋋", collapse = true), RIGHT_THREE_TIMES("rightthreetimes", dependency = AMSSYMB, display = "⋌", collapse = true), CIRCLED_CIRCLE("circledcirc", dependency = AMSSYMB, display = "⊚", collapse = true), CIRCLED_DASH("circleddash", dependency = AMSSYMB, display = "⊝", collapse = true), CIRCLED_ASTERISK("circledast", dependency = AMSSYMB, display = "⊛", collapse = true), MULTISET_UNION("uplus", display = "⊎", collapse = true), WEDGE_BAR("barwedge", dependency = AMSSYMB, display = "⊼", collapse = true), VEE_BAR("veebar", dependency = AMSSYMB, display = "⊻", collapse = true), DOUBLE_BAR_WEDGE("doublebarwedge", dependency = AMSSYMB, display = "⌆", collapse = true), CURLY_WEDGE("curlywedge", dependency = AMSSYMB, display = "⋏", collapse = true), CURLY_VEE("curlyvee", dependency = AMSSYMB, display = "⋎", collapse = true), INTERCALATE("intercal", dependency = AMSSYMB, display = "⊺", collapse = true), PITCHFORK("pitchfork", dependency = AMSSYMB, display = "⋔", collapse = true), NOT_SIM("nsim", dependency = AMSSYMB), SIM_EQUALS("simeq", display = "≃", collapse = true), BACKWARDS_SIM_EQUALS("backsimeq", dependency = AMSSYMB, display = "⋍", collapse = true), APPROX_EQUALS("approxeq", dependency = AMSSYMB, display = "≊", collapse = true), CONG_SYMBOL("cong", dependency = AMSSYMB, display = "≅", collapse = true), NOT_CONG("ncong", dependency = AMSSYMB, display = "≇", collapse = true), SMILE("smile", dependency = AMSSYMB, display = "\u2323", collapse = true), FROWN("frown", dependency = AMSSYMB, display = "\u2322", collapse = true), SMALL_SMILE("smallsmile", dependency = AMSSYMB, display = "\u2323", collapse = true), SMALL_FROWN("smallfrown", dependency = AMSSYMB, display = "\u2322", collapse = true), BETWEEN("between", dependency = AMSSYMB, display = "≬", collapse = true), PRECEDES("prec", display = "≺", collapse = true), SUCCEEDS("succ", display = "≻", collapse = true), NOT_PRECEEDS("nprec", dependency = AMSSYMB, display = "⊀", collapse = true), NOT_SUCCEEDS("nsucc", dependency = AMSSYMB, display = "⊁", collapse = true), PRECEDES_OR_EQUAL("preceq", dependency = AMSSYMB, display = "⪯", collapse = true), SUCCEEDS_OR_EQUALS("succeq", dependency = AMSSYMB, display = "⪰", collapse = true), NOT_PRECEDES_OR_EQUALS("npreceq", dependency = AMSSYMB, display = "⋠", collapse = true), NOT_SUCCEEDS_OR_EQUALS("nsucceq", dependency = AMSSYMB, display = "⋡", collapse = true), CURLY_PRECEDES_OR_EQUALS("preccurlyeq", dependency = AMSSYMB, display = "≼", collapse = true), CURLY_SUCCEEDS_OR_EQUALS("succcurlyeq", dependency = AMSSYMB, display = "≽", collapse = true), CURLY_EQUALS_PRECEDES("curlyeqprec", dependency = AMSSYMB, display = "⋞", collapse = true), CURLY_EQUALS_SUCCEEDS("curlyeqsucc", dependency = AMSSYMB, display = "⋟", collapse = true), PRECEDES_SIM("precsim", dependency = AMSSYMB, display = "≾", collapse = true), SUCCEEDS_SIM("succsim", dependency = AMSSYMB, display = "≿", collapse = true), PRECEDES_NOT_SIM("precnsim", dependency = AMSSYMB, display = "⋨", collapse = true), SUCCEEDS_NOT_SIM("succnsim", dependency = AMSSYMB, display = "⋩", collapse = true), PRECEDES_APPROX("precapprox", dependency = AMSSYMB, display = "⪷", collapse = true), SUCCEEDS_APPROX("succapprox", dependency = AMSSYMB, display = "⪸", collapse = true), PRECEDES_NOT_APPROX("precnapprox", dependency = AMSSYMB, display = "⪹", collapse = true), SUCCEEDS_NOT_APPROX("succnapprox", dependency = AMSSYMB, display = "⪺", collapse = true), PERPENDICULAR("perp", display = "⟂", collapse = true), RIGHT_TACK("vdash", display = "⊢", collapse = true), NOT_RIGHT_TACK("nvdash", dependency = AMSSYMB, display = "⊬", collapse = true), FORCES("Vdash", dependency = AMSSYMB, display = "⊩", collapse = true), TRIPLE_RIGHT_TACK("Vvdash", dependency = AMSSYMB, display = "⊪", collapse = true), MODELS("models", display = "⊧", collapse = true), VERTICAL_DOUBLE_DASH_RIGHT("vDash", dependency = AMSSYMB, display = "⊨", collapse = true), NOT_VERTICAL_DOUBLE_DASH_RIGHT("nvDash", dependency = AMSSYMB, display = "⊭", collapse = true), NOT_DOUBLE_VERTICAL_DOUBLE_DASH_RIGHT("nVDash", dependency = AMSSYMB, display = "⊯", collapse = true), NOT_MID("nmid", dependency = AMSSYMB, display = "∤", collapse = true), LESS_THAN_DOT("lessdot", dependency = AMSSYMB, display = "⋖", collapse = true), GREATER_THAN_DOT("gtrdot", dependency = AMSSYMB, display = "⋗", collapse = true), LESS_THAN_VERTICAL_NOT_EQUALS("lvertneqq", dependency = AMSSYMB), GREATER_THAN_VERTICAL_NOT_EQUALS("gvertneqq", dependency = AMSSYMB), LESS_THAN_EQUALS_SLANT("leqslant", dependency = AMSSYMB, display = "⩽", collapse = true), GREATER_THAN_EQUALS_SLANT("geqslant", dependency = AMSSYMB, display = "⩾", collapse = true), NOT_LESS_THAN_EQUALS_SLANT("nleqslant", dependency = AMSSYMB), NOT_GREATER_THAN_EQUALS_SLANT("ngeqslant", dependency = AMSSYMB), EQUALS_SLANT_LESS_THAN("eqslantless", dependency = AMSSYMB, display = "⪕", collapse = true), EQUALS_SLANT_GREATER_THAN("eqslantgtr", dependency = AMSSYMB, display = "⪖", collapse = true), LESS_GREATER("lessgtr", dependency = AMSSYMB, display = "≶", collapse = true), GREATER_LESS("gtrless", dependency = AMSSYMB, display = "≷", collapse = true), LESS_EQUALS_GREATER("lesseqgtr", dependency = AMSSYMB, display = "⋚", collapse = true), GREATER_EQUALS_LESSER("gtreqless", dependency = AMSSYMB, display = "⋛", collapse = true), LESS_EQUALSS_GREATER("lesseqqgtr", dependency = AMSSYMB, display = "⪋", collapse = true), GREATER_EQUALSS_LESSER("gtreqqless", dependency = AMSSYMB, display = "⪌", collapse = true), LESS_SIM("lesssim", dependency = AMSSYMB, display = "≲", collapse = true), GREATER_SIM("gtrsim", dependency = AMSSYMB, display = "≳", collapse = true), LESS_NOT_SIM("lnsim", dependency = AMSSYMB, display = "⋦", collapse = true), GREATER_NOT_SIM("gnsim", dependency = AMSSYMB, display = "⋧", collapse = true), LESS_APPROX("lessapprox", dependency = AMSSYMB, display = "⪅", collapse = true), GREATER_APPROX("gtrapprox", dependency = AMSSYMB, display = "⪆", collapse = true), LESS_NOT_APPROX("lnapprox", dependency = AMSSYMB, display = "⪉", collapse = true), GREATER_NOT_APPROX("gnapprox", dependency = AMSSYMB, display = "⪊", collapse = true), TRIANGLE_RIGHT_VARIATION("vartriangleright", dependency = AMSSYMB, display = "⊳", collapse = true), TRIANGLE_LEFT_VARIATION("vartriangleleft", dependency = AMSSYMB, display = "⊲", collapse = true), NOT_TRIANGLE_LEFT("ntriangleleft", dependency = AMSSYMB, display = "⋪", collapse = true), NOT_TRIANGLE_RIGHT("ntriangleright", dependency = AMSSYMB, display = "⋫", collapse = true), TRIANGLE_LEFT_EQUALS("trianglelefteq", dependency = AMSSYMB, display = "⊴", collapse = true), TRIANGLE_RIGHT_EQUALS("trianglerighteq", dependency = AMSSYMB, display = "⊵", collapse = true), TRIANGLE_LEFT_EQUALS_SLANT("trianglelefteqslant", dependency = STMARYRD), TRIANGLE_RIGHT_EQUALS_SLANT("trianglerighteqslant", dependency = STMARYRD), NOT_TRIANGLE_LEFT_EQUALS("ntrianglelefteq", dependency = AMSSYMB, display = "⋬", collapse = true), NOT_TRIANGLE_RIGHT_EQUALS("ntrianglerighteq", dependency = AMSSYMB, display = "⋭", collapse = true), NOT_TRIANGLE_LEFT_EQUALS_SLANT("ntrianglelefteqslant", dependency = STMARYRD), NOT_TRIANGLE_RIGHT_SLANT("ntrianglerighteqslant", dependency = STMARYRD), BLACK_TRIANGLE_LEFT("blacktriangleleft", dependency = AMSSYMB, display = "◂", collapse = true), BLACK_TRIANGLE_RIGHT("blacktriangleright", dependency = AMSSYMB, display = "▸", collapse = true), SUBSET_NOT_EQUALS("subsetneq", dependency = AMSSYMB, display = "⊊", collapse = true), SUPERSET_NOT_EQUALS("supsetneq", dependency = AMSSYMB, display = "⊋", collapse = true), SUBSET_NOT_EQUALS_VARIATION("varsubsetneq", dependency = AMSSYMB), SUPERSET_NOT_EQUALS_VARIATION("varsupsetneq", dependency = AMSSYMB), SUBSET_NOT_EQUALSS("subsetneqq", dependency = AMSSYMB, display = "⫋", collapse = true), SUPERSET_NOT_EQUALSS("supsetneqq", dependency = AMSSYMB, display = "⫌", collapse = true), REVERSED_EPSILON("backepsilon", dependency = AMSSYMB, display = "϶", collapse = true), DOUBLE_SUBSET("Subset", dependency = AMSSYMB, display = "⋐", collapse = true), DOUBLE_SUPERSET("Supset", dependency = AMSSYMB, display = "⋑", collapse = true), CIRCLE_EQUALS("circeq", dependency = AMSSYMB, display = "≗", collapse = true), TRIANGLE_EQUALS("triangleq", dependency = AMSSYMB, display = "≜", collapse = true), EQUALS_CIRCLE("eqcirc", dependency = AMSSYMB), BUMP_EQUALS("bumpeq", dependency = AMSSYMB), DOUBLE_BUMP_EQUALS("Bumpeq", dependency = AMSSYMB, display = "", collapse = true), DOT_EQUALS_DOT("doteqdot", dependency = AMSSYMB, display = "≑", collapse = true), RISING_DOTS_EQUALS("risingdotseq", dependency = AMSSYMB, display = "≓", collapse = true), FALLING_DOTS_EQUALS("fallingdotseq", dependency = AMSSYMB, display = "≒", collapse = true), DOT_EQUALS("doteq", dependency = AMSSYMB), SUBSET_PLUS("subsetplus", dependency = STMARYRD), SUBSET_PLUS_EQUALS("subsetpluseq", dependency = STMARYRD), SUPERSET_PLUS("supsetplus", dependency = STMARYRD), SUPERSET_PLUS_EQUALS("supsetpluseq", dependency = STMARYRD), IN_PLUS("inplus", dependency = STMARYRD), REVERSED_IN_PLUS("niplus", dependency = STMARYRD), ; override val identifier: String get() = name }
mit
47c52c890576351680cf1f56e5a9b212
72.068
106
0.656411
3.863367
false
false
false
false
SpineEventEngine/core-java
buildSrc/src/main/kotlin/io/spine/internal/gradle/github/pages/UpdateGitHubPagesExtension.kt
2
4514
/* * Copyright 2022, TeamDev. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * 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 io.spine.internal.gradle.github.pages import java.io.File import org.gradle.api.Project import org.gradle.api.provider.Property import org.gradle.api.provider.SetProperty import org.gradle.kotlin.dsl.apply import org.gradle.kotlin.dsl.getByType import org.gradle.kotlin.dsl.property /** * Configures the `updateGitHubPages` extension. */ @Suppress("unused") fun Project.updateGitHubPages(excludeInternalDocletVersion: String, action: UpdateGitHubPagesExtension.() -> Unit) { apply<UpdateGitHubPages>() val extension = extensions.getByType(UpdateGitHubPagesExtension::class) extension.excludeInternalDocletVersion = excludeInternalDocletVersion extension.action() } /** * The extension for configuring the [UpdateGitHubPages] plugin. */ class UpdateGitHubPagesExtension private constructor( /** * Tells whether the types marked `@Internal` should be included into * the doc generation. */ val allowInternalJavadoc: Property<Boolean>, /** * The root folder of the repository to which the updated `Project` belongs. */ var rootFolder: Property<File>, /** * The external inputs, which output should be included into * the GitHub Pages update. * * The values are interpreted according to * [org.gradle.api.tasks.Copy.from] specification. * * This property is optional. */ var includeInputs: SetProperty<Any> ) { /** * The version of the * [ExcludeInternalDoclet][io.spine.internal.gradle.javadoc.ExcludeInternalDoclet] * used when updating documentation at GitHub Pages. * * This value is used when adding dependency on the doclet when the plugin tasks * are registered. Since the doclet dependency is required, its value passed as * a parameter for the extension, rather than a property. */ internal lateinit var excludeInternalDocletVersion: String internal companion object { /** The name of the extension. */ const val name = "updateGitHubPages" /** Creates a new extension and adds it to the passed project. */ fun createIn(project: Project): UpdateGitHubPagesExtension { val factory = project.objects val result = UpdateGitHubPagesExtension( allowInternalJavadoc = factory.property(Boolean::class), rootFolder = factory.property(File::class), includeInputs = factory.setProperty(Any::class.java) ) project.extensions.add(result.javaClass, name, result) return result } } /** * Returns `true` if the `@Internal`-annotated code should be included into the * generated documentation, `false` otherwise. */ fun allowInternalJavadoc(): Boolean { return allowInternalJavadoc.get() } /** * Returns the local root folder of the repository, to which the handled Gradle * Project belongs. */ fun rootFolder(): File { return rootFolder.get() } /** * Returns the external inputs, which results should be included into the * GitHub Pages update. */ fun includedInputs(): Set<Any> { return includeInputs.get() } }
apache-2.0
8b5885c5b0f05410ff5cbf07b23ec351
33.458015
86
0.694728
4.687435
false
false
false
false
soniccat/android-taskmanager
storagemanager/src/main/java/com/example/alexeyglushkov/cachemanager/disk/serializer/DiskMetadataReader.kt
1
1807
package com.example.alexeyglushkov.cachemanager.disk.serializer import com.example.alexeyglushkov.cachemanager.disk.DiskStorageMetadata import com.example.alexeyglushkov.streamlib.data_readers_and_writers.InputStreamDataReader import com.example.alexeyglushkov.streamlib.progress.ProgressUpdater import com.example.alexeyglushkov.tools.ExceptionTools import com.fasterxml.jackson.core.Version import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.module.SimpleModule import java.io.BufferedInputStream import java.io.IOException import java.io.InputStream /** * Created by alexeyglushkov on 11.09.16. */ class DiskMetadataReader : InputStreamDataReader<DiskStorageMetadata?> { private var stream: InputStream? = null override fun beginRead(stream: InputStream) { ExceptionTools.throwIfNull(stream, "DiskMetadataReader.beginRead: stream is null") this.stream = BufferedInputStream(stream) } @Throws(Exception::class) override fun closeRead() { ExceptionTools.throwIfNull(stream, "DiskMetadataReader.close: stream is null") stream!!.close() } @Throws(IOException::class) override fun read(): DiskStorageMetadata? { ExceptionTools.throwIfNull(stream, "DiskMetadataReader.read: stream is null") var result: DiskStorageMetadata? = null val md = SimpleModule("DiskMetadataModule", Version(1, 0, 0, null, null, null)) md.addDeserializer(DiskStorageMetadata::class.java, DiskMetadataDeserializer(DiskStorageMetadata::class.java)) val mapper = ObjectMapper() mapper.registerModule(md) result = mapper.readValue(stream, DiskStorageMetadata::class.java) return result } override fun setProgressUpdater(progressUpdater: ProgressUpdater) {} }
mit
cc8891e5793ad47df7fc9aa2c8f920e2
41.046512
118
0.765357
4.793103
false
false
false
false
juxeii/dztools
java/dzjforex/src/test/kotlin/com/jforex/dzjforex/login/test/LoginTest.kt
1
2607
package com.jforex.dzjforex.login.test import arrow.effects.fix import com.jforex.dzjforex.login.LoginApi.logout import com.jforex.dzjforex.mock.test.getContextDependenciesForTest_IO import com.jforex.dzjforex.mock.test.getPluginDependenciesForTest_IO import com.jforex.dzjforex.zorro.LOGOUT_OK import io.kotlintest.shouldBe import io.kotlintest.specs.StringSpec import io.mockk.Runs import io.mockk.every import io.mockk.just import io.mockk.verify private val pluginApi = getPluginDependenciesForTest_IO() private val contextApi = getContextDependenciesForTest_IO() class LoginTest : StringSpec() { val username = "John_Doe" val password = "123456" val accountName = "JohnAccount42" init { /*"Login is OK when client is already connected" { val accountType = demoLoginType every { pluginApi.client.isConnected } returns (false) every { contextApi.account.accountId } returns (accountName) val loginResult = pluginApi .brokerLogin(username = username, password = password, accountType = accountType) .fix() .unsafeRunSync() verify(exactly = 1) { pluginApi.client.isConnected } loginResult.returnCode shouldBe LOGIN_OK loginResult.accountName shouldBe accountName //confirmVerified(pluginApi.client) }*/ /*"Login is called with correct parameters" { val username = "John_Doe" val password = "123456" val accountType = demoLoginType every { pluginApi.client.disconnect() } just Runs val loginResult = pluginApi .brokerLogin(username = username, password = password, accountType = accountType) .fix() .unsafeRunSync() verify(exactly = 1) { pluginApi.client.login( match { it.password == password && it.username == username }, eq(LoginType.DEMO), IO.monadDefer() ) } // logoutResult.shouldBe(LOGOUT_OK) }*/ } } class LogoutTest : StringSpec() { init { "Disconnect is called on client instance" { every { pluginApi.client.disconnect() } just Runs val logoutResult = pluginApi .logout() .fix() .unsafeRunSync() verify(exactly = 1) { pluginApi.client.disconnect() } logoutResult.shouldBe(LOGOUT_OK) } } }
mit
5c2529f5a5dd7c26e4b378dcc097ef0b
32
97
0.599923
4.909605
false
true
false
false
binout/soccer-league
src/test/kotlin/io/github/binout/soccer/infrastructure/persistence/mongo/MongoFriendlyMatchDateRepositoryTest.kt
1
2038
package io.github.binout.soccer.infrastructure.persistence.mongo import io.github.binout.soccer.domain.date.MatchDate import io.github.binout.soccer.domain.player.Player import io.github.binout.soccer.domain.player.PlayerName import io.github.binout.soccer.domain.player.values import io.github.binout.soccer.infrastructure.persistence.MongoConfiguration import io.github.binout.soccer.infrastructure.persistence.MongoFriendlyMatchDateRepository import io.github.binout.soccer.infrastructure.persistence.MongoPlayerRepository import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import java.time.LocalDate import java.time.Month class MongoFriendlyMatchDateRepositoryTest { private lateinit var repository: MongoFriendlyMatchDateRepository private lateinit var playerRepository: MongoPlayerRepository @BeforeEach fun initRepository() { playerRepository = MongoPlayerRepository(MongoConfiguration("").database()) repository = MongoFriendlyMatchDateRepository(MongoConfiguration("").database()) } @Test fun should_persist_date_without_player() { repository.replace(MatchDate.newDateForFriendly(2016, Month.APRIL, 1)) val matchDate = repository.byDate(2016, Month.APRIL, 1) assertThat(matchDate).isNotNull assertThat(matchDate!!.date).isEqualTo(LocalDate.of(2016, Month.APRIL, 1)) assertThat(matchDate.presents().count()).isZero() } @Test fun should_persist_date_with_player() { val benoit = Player(PlayerName("benoit")) playerRepository.add(benoit) val date = MatchDate.newDateForFriendly(2016, Month.APRIL, 1) date.present(benoit) repository.replace(date) val matchDate = repository.byDate(2016, Month.APRIL, 1) assertThat(matchDate).isNotNull assertThat(matchDate!!.date).isEqualTo(LocalDate.of(2016, Month.APRIL, 1)) assertThat(matchDate.presents().values()).containsOnly("benoit") } }
apache-2.0
a4c4e8033411dbd4109bb94b0abfc28c
38.980392
90
0.757115
4.459519
false
true
false
false
ProxyApp/Proxy
Application/src/main/kotlin/com/shareyourproxy/api/rx/RxUserChannelSync.kt
1
3681
package com.shareyourproxy.api.rx import android.content.Context import com.shareyourproxy.api.RestClient.getUserChannelService import com.shareyourproxy.api.RestClient.getUserGroupService import com.shareyourproxy.api.domain.factory.UserFactory.addUserChannel import com.shareyourproxy.api.domain.factory.UserFactory.deleteUserChannel import com.shareyourproxy.api.domain.model.Channel import com.shareyourproxy.api.domain.model.User import com.shareyourproxy.api.rx.command.eventcallback.EventCallback import com.shareyourproxy.api.rx.command.eventcallback.UserChannelAddedEventCallback import com.shareyourproxy.api.rx.command.eventcallback.UserChannelDeletedEventCallback import rx.Observable import rx.functions.Func1 /** * Sync newChannel operations. */ object RxUserChannelSync { fun saveUserChannel( context: Context, oldUser: User, oldChannel: Channel?, newChannel: Channel): UserChannelAddedEventCallback { return Observable.just(oldUser) .map(putUserChannel(newChannel)) .map(addRealmUser(context)) .map(saveChannelToFirebase(context, newChannel)) .map(userChannelAddedEventCallback(oldChannel, newChannel)) .toBlocking().single() } fun deleteChannel( context: Context, oldUser: User, channel: Channel, position: Int): EventCallback { return Observable.just(oldUser).map(removeUserChannel(channel)).map(addRealmUser(context)).map(deleteChannelFromFirebase(context, channel)).map(userChannelDeletedEventCallback(channel, position)).toBlocking().single() } private fun addRealmUser(context: Context): Func1<User, User> { return Func1 { user -> RxHelper.updateRealmUser(context, user) user } } /** * Add the new channel to the users channel list and all groups. * @param newChannel * @return */ private fun putUserChannel(newChannel: Channel): Func1<User, User> { return Func1 { oldUser -> val newUser = addUserChannel(oldUser, newChannel) newUser } } private fun saveChannelToFirebase( context: Context, channel: Channel): Func1<User, User> { return Func1 { user -> val userId = user.id() val channelId = channel.id() getUserChannelService(context).addUserChannel(userId, channelId, channel).subscribe() getUserGroupService(context).updateUserGroups(userId, user.groups()).subscribe() user } } private fun userChannelAddedEventCallback( oldChannel: Channel?, newChannel: Channel): Func1<User, UserChannelAddedEventCallback> { return Func1 { user -> UserChannelAddedEventCallback(user, oldChannel, newChannel) } } private fun removeUserChannel(channel: Channel): Func1<User, User> { return Func1 { oldUser -> val newUser = deleteUserChannel(oldUser, channel) newUser } } private fun deleteChannelFromFirebase( context: Context, channel: Channel): Func1<User, User> { return Func1 { user -> val userId = user.id() val channelId = channel.id() getUserChannelService(context).deleteUserChannel(userId, channelId).subscribe() getUserGroupService(context).updateUserGroups(userId, user.groups()).subscribe() user } } private fun userChannelDeletedEventCallback( channel: Channel, position: Int): Func1<User, EventCallback> { return Func1 { user -> UserChannelDeletedEventCallback(user, channel, position) } } }
apache-2.0
64d075fbc5f9d0272097b993f1e16638
37.747368
225
0.684325
4.799218
false
false
false
false
martin-nordberg/KatyDOM
Katydid-CSS-JS/src/main/kotlin/o/katydid/css/styles/KatydidStyle.kt
1
2221
// // (C) Copyright 2018-2019 Martin E. Nordberg III // Apache 2.0 License // package o.katydid.css.styles import i.katydid.css.styles.KatydidStyleImpl //--------------------------------------------------------------------------------------------------------------------- /** * Interface to a style - one or more CSS properties with values. */ interface KatydidStyle { /** The individual properties making up this style. */ val properties: List<String> /** Funky side-effecting getter actually sets the previously set property to be !important. */ val important: Unit /** True if this style has at least one property. */ val isNotEmpty: Boolean //// /** Copies all the properties from the given [style]. (Similar to CSS @import.) */ fun include(style: KatydidStyle) /** Adds a given property with key [key] and value "inherit". */ fun inherit(key: String) /** Sets a property with 1-4 values [top], [right], [bottom], [left] for the CSS box model. */ fun <T> setBoxProperty(key: String, top: T, right: T = top, bottom: T = top, left: T = right) /** Sets a property of the style with given [key] and [value]. */ fun setProperty(key: String, value: String) /** Sets an [x]/[y] or horizontal/vertical two-value property with given [key]. */ fun <T> setXyProperty(key: String, x: T, y: T = x) /** Sets a property where the value is to become a quoted string. */ fun setStringProperty(key: String, value: String) /** * Converts this style to CSS with [indent] spaces at the beginning of each line and [whitespace] between * successive lines. */ fun toCssString(indent: String = "", whitespace: String = "\n"): String } //--------------------------------------------------------------------------------------------------------------------- /** * Builds a new style object. * @param build the callback that fills in the CSS properties. */ fun makeStyle( build: KatydidStyle.() -> Unit ): KatydidStyle { val result = KatydidStyleImpl() result.build() return result } //---------------------------------------------------------------------------------------------------------------------
apache-2.0
d60a2aa1e2c4575474866cda5bf26b96
30.28169
119
0.548852
4.598344
false
false
false
false
vondear/RxTools
RxKit/src/main/java/com/tamsiree/rxkit/TLog.kt
1
7159
package com.tamsiree.rxkit import android.content.Context import android.util.Log import com.tamsiree.rxkit.RxDataTool.Companion.isNullString import com.tamsiree.rxkit.RxFileTool.Companion.rootPath import java.io.* import java.text.SimpleDateFormat import java.util.* /** * @author tamsiree * @date 2016/1/24 */ object TLog { private val LOG_FORMAT = SimpleDateFormat("yyyy年MM月dd日_HH点mm分ss秒") // 日志的输出格式 private val FILE_SUFFIX = SimpleDateFormat("HH点mm分ss秒") // 日志文件格式 private val FILE_DIR = SimpleDateFormat("yyyy年MM月dd日") // 日志文件格式 // 日志文件总开关 private var LOG_SWITCH = true // 日志写入文件开关 private var LOG_TO_FILE = true //崩溃日志写入文件开关 private var LOG_CRASH_FILE = true private const val LOG_TAG = "TLog" // 默认的tag private const val LOG_TYPE = 'v' // 输入日志类型,v代表输出所有信息,w则只输出警告... private const val LOG_SAVE_DAYS = 7 // sd卡中日志文件的最多保存天数 private var LOG_FILE_PATH // 日志文件保存路径 : String? = null private var LOG_FILE_NAME // 日志文件保存名称 : String? = null @JvmStatic fun init(context: Context) { // 在Application中初始化 LOG_FILE_PATH = rootPath!!.path + File.separator + context.packageName + File.separator + "Log" LOG_FILE_NAME = "TLog_" } fun switchLog(switch: Boolean) { this.LOG_SWITCH = switch } fun switch2File(switch: Boolean) { this.LOG_TO_FILE = switch } fun switchCrashFile(switch: Boolean) { this.LOG_CRASH_FILE = switch } /**************************** * Warn */ @JvmStatic fun w(msg: Any): File { return w(LOG_TAG, msg) } @JvmOverloads @JvmStatic fun w(tag: String, msg: Any, tr: Throwable? = null): File { return log(tag, msg.toString(), tr, 'w') } /*************************** * Error */ @JvmStatic fun e(msg: Any): File { return e(LOG_TAG, msg) } @JvmOverloads @JvmStatic fun e(tag: String, msg: Any, tr: Throwable? = null): File { return log(tag, msg.toString(), tr, 'e') } /*************************** * Debug */ @JvmStatic fun d(msg: Any): File { return d(LOG_TAG, msg) } @JvmOverloads @JvmStatic fun d(tag: String, msg: Any?, tr: Throwable? = null): File { return log(tag, msg.toString(), tr, 'd') } /**************************** * Info */ @JvmStatic fun i(msg: Any): File { return i(LOG_TAG, msg) } @JvmOverloads @JvmStatic fun i(tag: String, msg: Any, tr: Throwable? = null): File { return log(tag, msg.toString(), tr, 'i') } /************************** * Verbose */ @JvmStatic fun v(msg: Any): File { return v(LOG_TAG, msg) } @JvmOverloads @JvmStatic fun v(tag: String, msg: Any, tr: Throwable? = null): File { return log(tag, msg.toString(), tr, 'v') } /** * 根据tag, msg和等级,输出日志 * * @param tag * @param msg * @param level */ private fun log(tag: String, msg: String, tr: Throwable?, level: Char): File { var logFile = File("") if (LOG_SWITCH) { if ('e' == level && ('e' == LOG_TYPE || 'v' == LOG_TYPE)) { // 输出错误信息 Log.e(tag, msg, tr) } else if ('w' == level && ('w' == LOG_TYPE || 'v' == LOG_TYPE)) { Log.w(tag, msg, tr) } else if ('d' == level && ('d' == LOG_TYPE || 'v' == LOG_TYPE)) { Log.d(tag, msg, tr) } else if ('i' == level && ('d' == LOG_TYPE || 'v' == LOG_TYPE)) { Log.i(tag, msg, tr) } else { Log.v(tag, msg, tr) } if (LOG_TO_FILE || (LOG_CRASH_FILE && ('e' == level || 'e' == LOG_TYPE))) { var content = "" if (!isNullString(msg)) { content += msg } if (tr != null) { content += "\n" content += Log.getStackTraceString(tr) } logFile = log2File(level.toString(), tag, content) } } return logFile } /** * 打开日志文件并写入日志 * * @return */ @Synchronized private fun log2File(mylogtype: String, tag: String, text: String): File { val nowtime = Date() val date = FILE_SUFFIX.format(nowtime) val dateLogContent = """ Date:${LOG_FORMAT.format(nowtime)} LogType:$mylogtype Tag:$tag Content: $text """.trimIndent() // 日志输出格式 val path = LOG_FILE_PATH + File.separator + FILE_DIR.format(nowtime) val destDir = File(path) if (!destDir.exists()) { destDir.mkdirs() } val file = File(path, "$LOG_FILE_NAME$date.txt") try { if (!file.exists()) { file.createNewFile() } val filerWriter = FileWriter(file, true) val bufWriter = BufferedWriter(filerWriter) bufWriter.write(dateLogContent) bufWriter.newLine() bufWriter.close() filerWriter.close() } catch (e: IOException) { e.printStackTrace() } return file } /** * 删除指定的日志文件 */ @JvmStatic fun delAllLogFile() { // 删除日志文件 // String needDelFiel = FILE_SUFFIX.format(getDateBefore()); RxFileTool.deleteDir(LOG_FILE_PATH) } /** * 得到LOG_SAVE_DAYS天前的日期 * * @return */ private val dateBefore: Date private get() { val nowtime = Date() val now = Calendar.getInstance() now.time = nowtime now[Calendar.DATE] = now[Calendar.DATE] - LOG_SAVE_DAYS return now.time } @JvmStatic fun saveLogFile(message: String) { val fileDir = File(rootPath.toString() + File.separator + RxTool.getContext().packageName) if (!fileDir.exists()) { fileDir.mkdirs() } val file = File(fileDir, RxTimeTool.getCurrentDateTime("yyyyMMdd") + ".txt") try { if (file.exists()) { val ps = PrintStream(FileOutputStream(file, true)) ps.append(""" ${RxTimeTool.getCurrentDateTime("\n\n\nyyyy-MM-dd HH:mm:ss")} $message """.trimIndent()) // 往文件里写入字符串 } else { val ps = PrintStream(FileOutputStream(file)) file.createNewFile() ps.println(""" ${RxTimeTool.getCurrentDateTime("yyyy-MM-dd HH:mm:ss")} $message """.trimIndent()) // 往文件里写入字符串 } } catch (e: IOException) { e.printStackTrace() } } }
apache-2.0
bba5b66a4ab0379cf299240d5bb7becd
26.362903
103
0.508622
3.820383
false
false
false
false
RocketChat/Rocket.Chat.Android.Lily
app/src/main/java/chat/rocket/android/chatdetails/ui/ChatDetailsFragment.kt
2
8916
package chat.rocket.android.chatdetails.ui import DrawableHelper import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import chat.rocket.android.R import chat.rocket.android.chatdetails.domain.ChatDetails import chat.rocket.android.chatdetails.presentation.ChatDetailsPresenter import chat.rocket.android.chatdetails.presentation.ChatDetailsView import chat.rocket.android.chatdetails.viewmodel.ChatDetailsViewModel import chat.rocket.android.chatdetails.viewmodel.ChatDetailsViewModelFactory import chat.rocket.android.chatroom.ui.ChatRoomActivity import chat.rocket.android.server.domain.CurrentServerRepository import chat.rocket.android.server.domain.GetSettingsInteractor import chat.rocket.android.util.extensions.inflate import chat.rocket.android.util.extensions.showToast import chat.rocket.android.util.extensions.ui import chat.rocket.android.widget.DividerItemDecoration import chat.rocket.common.model.RoomType import chat.rocket.common.model.roomTypeOf import dagger.android.support.AndroidSupportInjection import kotlinx.android.synthetic.main.fragment_chat_details.* import javax.inject.Inject fun newInstance( chatRoomId: String, chatRoomType: String, isSubscribed: Boolean, isFavorite: Boolean, disableMenu: Boolean ): ChatDetailsFragment { return ChatDetailsFragment().apply { arguments = Bundle(5).apply { putString(BUNDLE_CHAT_ROOM_ID, chatRoomId) putString(BUNDLE_CHAT_ROOM_TYPE, chatRoomType) putBoolean(BUNDLE_IS_SUBSCRIBED, isSubscribed) putBoolean(BUNDLE_IS_FAVORITE, isFavorite) putBoolean(BUNDLE_DISABLE_MENU, disableMenu) } } } internal const val TAG_CHAT_DETAILS_FRAGMENT = "ChatDetailsFragment" internal const val MENU_ACTION_FAVORITE_REMOVE_FAVORITE = 1 internal const val MENU_ACTION_VIDEO_CALL = 2 private const val BUNDLE_CHAT_ROOM_ID = "BUNDLE_CHAT_ROOM_ID" private const val BUNDLE_CHAT_ROOM_TYPE = "BUNDLE_CHAT_ROOM_TYPE" private const val BUNDLE_IS_SUBSCRIBED = "BUNDLE_IS_SUBSCRIBED" private const val BUNDLE_IS_FAVORITE = "BUNDLE_IS_FAVORITE" private const val BUNDLE_DISABLE_MENU = "BUNDLE_DISABLE_MENU" class ChatDetailsFragment : Fragment(), ChatDetailsView { @Inject lateinit var presenter: ChatDetailsPresenter @Inject lateinit var factory: ChatDetailsViewModelFactory @Inject lateinit var serverUrl: CurrentServerRepository @Inject lateinit var settings: GetSettingsInteractor private var adapter: ChatDetailsAdapter? = null private lateinit var viewModel: ChatDetailsViewModel internal lateinit var chatRoomId: String internal lateinit var chatRoomType: String private var isSubscribed: Boolean = true internal var isFavorite: Boolean = false private var disableMenu: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AndroidSupportInjection.inject(this) arguments?.run { chatRoomId = getString(BUNDLE_CHAT_ROOM_ID, "") chatRoomType = getString(BUNDLE_CHAT_ROOM_TYPE, "") isSubscribed = getBoolean(BUNDLE_IS_SUBSCRIBED) isFavorite = getBoolean(BUNDLE_IS_FAVORITE) disableMenu = getBoolean(BUNDLE_DISABLE_MENU) } ?: requireNotNull(arguments) { "no arguments supplied when the fragment was instantiated" } setHasOptionsMenu(true) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = container?.inflate(R.layout.fragment_chat_details) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = ViewModelProviders.of(this, factory).get(ChatDetailsViewModel::class.java) setupOptions() setupToolbar() getDetails() } override fun onPrepareOptionsMenu(menu: Menu) { menu.clear() setupMenu(menu) super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { setOnMenuItemClickListener(item) return true } override fun showFavoriteIcon(isFavorite: Boolean) { this.isFavorite = isFavorite activity?.invalidateOptionsMenu() } override fun displayDetails(room: ChatDetails) { ui { val text = room.name name.text = text bindImage(chatRoomType) content_topic.text = if (room.topic.isNullOrEmpty()) getString(R.string.msg_no_topic) else room.topic content_announcement.text = if (room.announcement.isNullOrEmpty()) getString(R.string.msg_no_announcement) else room.announcement content_description.text = if (room.description.isNullOrEmpty()) getString(R.string.msg_no_description) else room.description } } override fun showGenericErrorMessage() = showMessage(R.string.msg_generic_error) override fun showMessage(resId: Int) { ui { showToast(resId) } } override fun showMessage(message: String) { ui { showToast(message) } } private fun addOptions(adapter: ChatDetailsAdapter?) { adapter?.let { if (!disableMenu) { it.addOption(getString(R.string.title_files), R.drawable.ic_files_24dp) { presenter.toFiles(chatRoomId) } } if (chatRoomType != RoomType.DIRECT_MESSAGE && !disableMenu) { it.addOption(getString(R.string.msg_mentions), R.drawable.ic_at_black_20dp) { presenter.toMentions(chatRoomId) } it.addOption( getString(R.string.title_members), R.drawable.ic_people_outline_black_24dp ) { presenter.toMembers(chatRoomId) } } it.addOption( getString(R.string.title_favorite_messages), R.drawable.ic_star_border_white_24dp ) { presenter.toFavorites(chatRoomId) } it.addOption( getString(R.string.title_pinned_messages), R.drawable.ic_action_message_pin_24dp ) { presenter.toPinned(chatRoomId) } } } private fun bindImage(chatRoomType: String) { val drawable = when (roomTypeOf(chatRoomType)) { is RoomType.Channel -> { DrawableHelper.getDrawableFromId(R.drawable.ic_hashtag_black_12dp, context!!) } is RoomType.PrivateGroup -> { DrawableHelper.getDrawableFromId(R.drawable.ic_lock_black_12_dp, context!!) } else -> null } drawable?.let { val wrappedDrawable = DrawableHelper.wrapDrawable(it) val mutableDrawable = wrappedDrawable.mutate() DrawableHelper.tintDrawable(mutableDrawable, context!!, R.color.colorPrimary) DrawableHelper.compoundStartDrawable(name, mutableDrawable) } } private fun getDetails() { if (isSubscribed) viewModel.getDetails(chatRoomId).observe(viewLifecycleOwner, Observer { details -> displayDetails(details) }) else presenter.getDetails(chatRoomId, chatRoomType) } private fun setupOptions() { ui { if (options.adapter == null) { adapter = ChatDetailsAdapter() options.adapter = adapter with(options) { layoutManager = LinearLayoutManager(it) addItemDecoration( DividerItemDecoration( it, resources.getDimensionPixelSize(R.dimen.divider_item_decorator_bound_start), resources.getDimensionPixelSize(R.dimen.divider_item_decorator_bound_end) ) ) itemAnimator = DefaultItemAnimator() isNestedScrollingEnabled = false } } addOptions(adapter) } } private fun setupToolbar() { with((activity as ChatRoomActivity)) { hideExpandMoreForToolbar() setupToolbarTitle(getString(R.string.title_channel_details)) } } }
mit
b747e2ad4befb9064fddca75bb242a22
36.154167
121
0.653208
5.017445
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/ColorPickerDialogFragment.kt
1
4026
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[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 de.vanita5.twittnuker.fragment import android.app.Dialog import android.content.DialogInterface import android.graphics.Color import android.os.Bundle import android.support.v4.content.ContextCompat import android.support.v7.app.AlertDialog import me.uucky.colorpicker.ColorPickerDialog import de.vanita5.twittnuker.Constants.* import de.vanita5.twittnuker.R import de.vanita5.twittnuker.extension.applyTheme import de.vanita5.twittnuker.extension.onShow import de.vanita5.twittnuker.fragment.iface.IDialogFragmentCallback class ColorPickerDialogFragment : BaseDialogFragment(), DialogInterface.OnClickListener { private var mController: ColorPickerDialog.Controller? = null override fun onCancel(dialog: DialogInterface?) { super.onCancel(dialog) val a = activity if (a is Callback) { a.onCancelled() } } override fun onClick(dialog: DialogInterface, which: Int) { val a = activity if (a !is Callback || mController == null) return when (which) { DialogInterface.BUTTON_POSITIVE -> { val color = mController!!.color a.onColorSelected(color) } DialogInterface.BUTTON_NEUTRAL -> { a.onColorCleared() } } } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val color: Int val args = arguments if (savedInstanceState != null) { color = savedInstanceState.getInt(EXTRA_COLOR, Color.WHITE) } else { color = args.getInt(EXTRA_COLOR, Color.WHITE) } val activity = activity val builder = AlertDialog.Builder(activity) builder.setView(me.uucky.colorpicker.R.layout.cp__dialog_color_picker) builder.setPositiveButton(android.R.string.ok, this) if (args.getBoolean(EXTRA_CLEAR_BUTTON, false)) { builder.setNeutralButton(R.string.action_clear, this) } builder.setNegativeButton(android.R.string.cancel, this) val dialog = builder.create() dialog.onShow { it.applyTheme() mController = ColorPickerDialog.Controller(it.context, it.window.decorView) val showAlphaSlider = args.getBoolean(EXTRA_ALPHA_SLIDER, true) for (presetColor in PRESET_COLORS) { mController!!.addColor(ContextCompat.getColor(context, presetColor)) } mController!!.setAlphaEnabled(showAlphaSlider) mController!!.setInitialColor(color) } return dialog } override fun onDismiss(dialog: DialogInterface?) { super.onDismiss(dialog) val a = activity if (a is Callback) { a.onDismissed() } } override fun onSaveInstanceState(outState: Bundle?) { if (mController != null) { outState!!.putInt(EXTRA_COLOR, mController!!.color) } super.onSaveInstanceState(outState) } interface Callback : IDialogFragmentCallback { fun onColorCleared() fun onColorSelected(color: Int) } }
gpl-3.0
f027919d2ac817ce01f66352b38264a2
32.840336
89
0.667412
4.554299
false
false
false
false
stripe/stripe-android
payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/CardDetailsElement.kt
1
2845
package com.stripe.android.ui.core.elements import android.content.Context import androidx.annotation.RestrictTo import com.stripe.android.ui.core.forms.FormFieldEntry import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.combine /** * This is the element that represent the collection of all the card details: * card number, expiration date, and CVC. */ internal class CardDetailsElement( identifier: IdentifierSpec, context: Context, initialValues: Map<IdentifierSpec, String?>, viewOnlyFields: Set<IdentifierSpec> = emptySet(), val controller: CardDetailsController = CardDetailsController( context, initialValues, viewOnlyFields.contains(IdentifierSpec.CardNumber) ) ) : SectionMultiFieldElement(identifier) { val isCardScanEnabled = controller.numberElement.controller.cardScanEnabled override fun sectionFieldErrorController(): SectionFieldErrorController = controller override fun setRawValue(rawValuesMap: Map<IdentifierSpec, String?>) { // Nothing from formFragmentArguments to populate } override fun getTextFieldIdentifiers(): Flow<List<IdentifierSpec>> = MutableStateFlow( listOf( controller.numberElement.identifier, controller.expirationDateElement.identifier, controller.cvcElement.identifier ) ) override fun getFormFieldValueFlow() = combine( controller.numberElement.controller.formFieldValue, controller.cvcElement.controller.formFieldValue, controller.expirationDateElement.controller.formFieldValue, controller.numberElement.controller.cardBrandFlow ) { number, cvc, expirationDate, brand -> listOf( controller.numberElement.identifier to number, controller.cvcElement.identifier to cvc, IdentifierSpec.CardBrand to FormFieldEntry(brand.code, true) ) + createExpiryDateFormFieldValues(expirationDate).toList() } } @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun createExpiryDateFormFieldValues( entry: FormFieldEntry ): Map<IdentifierSpec, FormFieldEntry> { var month = -1 var year = -1 entry.value?.let { date -> val newString = convertTo4DigitDate(date) if (newString.length == 4) { month = requireNotNull(newString.take(2).toIntOrNull()) year = requireNotNull(newString.takeLast(2).toIntOrNull()) + 2000 } } val monthEntry = entry.copy( value = month.toString().padStart(length = 2, padChar = '0') ) val yearEntry = entry.copy( value = year.toString() ) return mapOf( IdentifierSpec.CardExpMonth to monthEntry, IdentifierSpec.CardExpYear to yearEntry ) }
mit
f452fe8d2ff7c1e4126f54abc002e487
33.277108
79
0.702988
4.965096
false
false
false
false
stripe/stripe-android
identity/src/test/java/com/stripe/android/identity/TestFixtures.kt
1
2841
package com.stripe.android.identity import com.stripe.android.identity.networking.VERIFICATION_PAGE_NOT_REQUIRE_LIVE_CAPTURE_JSON_STRING import com.stripe.android.identity.networking.VERIFICATION_PAGE_REQUIRE_LIVE_CAPTURE_JSON_STRING import com.stripe.android.identity.networking.models.Requirement import com.stripe.android.identity.networking.models.VerificationPage import com.stripe.android.identity.networking.models.VerificationPageData import com.stripe.android.identity.networking.models.VerificationPageDataRequirements import kotlinx.serialization.json.Json internal const val ERROR_BODY = "errorBody" internal const val ERROR_BUTTON_TEXT = "error button text" internal const val ERROR_TITLE = "errorTitle" internal val CORRECT_WITH_SUBMITTED_FAILURE_VERIFICATION_PAGE_DATA = VerificationPageData( id = "id", objectType = "type", requirements = VerificationPageDataRequirements( errors = emptyList() ), status = VerificationPageData.Status.VERIFIED, submitted = false ) internal val CORRECT_WITH_SUBMITTED_SUCCESS_VERIFICATION_PAGE_DATA = VerificationPageData( id = "id", objectType = "type", requirements = VerificationPageDataRequirements( errors = emptyList() ), status = VerificationPageData.Status.VERIFIED, submitted = true ) internal val VERIFICATION_PAGE_DATA_MISSING_BACK = VerificationPageData( id = "id", objectType = "type", requirements = VerificationPageDataRequirements( errors = emptyList(), missings = listOf(Requirement.IDDOCUMENTBACK) ), status = VerificationPageData.Status.REQUIRESINPUT, submitted = false ) internal val VERIFICATION_PAGE_DATA_NOT_MISSING_BACK = VerificationPageData( id = "id", objectType = "type", requirements = VerificationPageDataRequirements( errors = emptyList(), missings = emptyList() ), status = VerificationPageData.Status.REQUIRESINPUT, submitted = false ) internal val VERIFICATION_PAGE_DATA_MISSING_SELFIE = VerificationPageData( id = "id", objectType = "type", requirements = VerificationPageDataRequirements( errors = emptyList(), missings = listOf(Requirement.FACE) ), status = VerificationPageData.Status.REQUIRESINPUT, submitted = false ) internal val json: Json = Json { ignoreUnknownKeys = true isLenient = true encodeDefaults = true } internal val SUCCESS_VERIFICATION_PAGE_NOT_REQUIRE_LIVE_CAPTURE: VerificationPage = json.decodeFromString( VerificationPage.serializer(), VERIFICATION_PAGE_NOT_REQUIRE_LIVE_CAPTURE_JSON_STRING ) internal val SUCCESS_VERIFICATION_PAGE_REQUIRE_LIVE_CAPTURE: VerificationPage = json.decodeFromString( VerificationPage.serializer(), VERIFICATION_PAGE_REQUIRE_LIVE_CAPTURE_JSON_STRING )
mit
7373d2be6442b205fc0220cd4a823579
32.821429
100
0.743752
4.703642
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/notifications/service/delegates/ExpoPresentationDelegate.kt
2
9255
package abi44_0_0.expo.modules.notifications.service.delegates import android.app.NotificationManager import android.content.Context import android.media.RingtoneManager import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Parcel import android.provider.Settings import android.service.notification.StatusBarNotification import android.util.Log import android.util.Pair import androidx.core.app.NotificationManagerCompat import expo.modules.notifications.notifications.enums.NotificationPriority import expo.modules.notifications.notifications.model.Notification import expo.modules.notifications.notifications.model.NotificationBehavior import expo.modules.notifications.notifications.model.NotificationContent import expo.modules.notifications.notifications.model.NotificationRequest import abi44_0_0.expo.modules.notifications.notifications.presentation.builders.CategoryAwareNotificationBuilder import abi44_0_0.expo.modules.notifications.notifications.presentation.builders.ExpoNotificationBuilder import abi44_0_0.expo.modules.notifications.service.interfaces.PresentationDelegate import org.json.JSONException import org.json.JSONObject import java.util.* open class ExpoPresentationDelegate( protected val context: Context ) : PresentationDelegate { companion object { protected const val ANDROID_NOTIFICATION_ID = 0 protected const val INTERNAL_IDENTIFIER_SCHEME = "expo-notifications" protected const val INTERNAL_IDENTIFIER_AUTHORITY = "foreign_notifications" protected const val INTERNAL_IDENTIFIER_TAG_KEY = "tag" protected const val INTERNAL_IDENTIFIER_ID_KEY = "id" /** * Tries to parse given identifier as an internal foreign notification identifier * created by us in [getInternalIdentifierKey]. * * @param identifier String identifier of the notification * @return Pair of (notification tag, notification id), if the identifier could be parsed. null otherwise. */ fun parseNotificationIdentifier(identifier: String): Pair<String?, Int>? { try { val parsedIdentifier = Uri.parse(identifier) if (INTERNAL_IDENTIFIER_SCHEME == parsedIdentifier.scheme && INTERNAL_IDENTIFIER_AUTHORITY == parsedIdentifier.authority) { val tag = parsedIdentifier.getQueryParameter(INTERNAL_IDENTIFIER_TAG_KEY) val id = parsedIdentifier.getQueryParameter(INTERNAL_IDENTIFIER_ID_KEY)!!.toInt() return Pair(tag, id) } } catch (e: NullPointerException) { Log.e("expo-notifications", "Malformed foreign notification identifier: $identifier", e) } catch (e: NumberFormatException) { Log.e("expo-notifications", "Malformed foreign notification identifier: $identifier", e) } catch (e: UnsupportedOperationException) { Log.e("expo-notifications", "Malformed foreign notification identifier: $identifier", e) } return null } /** * Creates an identifier for given [StatusBarNotification]. It's supposed to be parsable * by [parseNotificationIdentifier]. * * @param notification Notification to be identified * @return String identifier */ protected fun getInternalIdentifierKey(notification: StatusBarNotification): String { return with(Uri.parse("$INTERNAL_IDENTIFIER_SCHEME://$INTERNAL_IDENTIFIER_AUTHORITY").buildUpon()) { notification.tag?.let { this.appendQueryParameter(INTERNAL_IDENTIFIER_TAG_KEY, it) } this.appendQueryParameter(INTERNAL_IDENTIFIER_ID_KEY, notification.id.toString()) this.toString() } } } /** * Callback called to present the system UI for a notification. * * If the notification behavior is set to not show any alert, * we (may) play a sound, but then bail out early. You cannot * set badge count without showing a notification. */ override fun presentNotification(notification: Notification, behavior: NotificationBehavior?) { if (behavior != null && !behavior.shouldShowAlert()) { if (behavior.shouldPlaySound()) { RingtoneManager.getRingtone( context, notification.notificationRequest.content.sound ?: Settings.System.DEFAULT_NOTIFICATION_URI ).play() } return } NotificationManagerCompat.from(context).notify( notification.notificationRequest.identifier, getNotifyId(notification.notificationRequest), createNotification(notification, behavior) ) } protected open fun getNotifyId(request: NotificationRequest?): Int { return ANDROID_NOTIFICATION_ID } /** * Callback called to fetch a collection of currently displayed notifications. * * **Note:** This feature is only supported on Android 23+. * * @return A collection of currently displayed notifications. */ override fun getAllPresentedNotifications(): Collection<Notification> { // getActiveNotifications() is not supported on platforms below Android 23 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return emptyList() } val notificationManager = (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager) return notificationManager.activeNotifications.mapNotNull { getNotification(it) } } override fun dismissNotifications(identifiers: Collection<String>) { identifiers.forEach { identifier -> val foreignNotification = parseNotificationIdentifier(identifier) if (foreignNotification != null) { // Foreign notification identified by us NotificationManagerCompat.from(context).cancel(foreignNotification.first, foreignNotification.second) } else { // If the notification exists, let's assume it's ours, we have no reason to believe otherwise val existingNotification = this.getAllPresentedNotifications().find { it.notificationRequest.identifier == identifier } NotificationManagerCompat.from(context).cancel(identifier, getNotifyId(existingNotification?.notificationRequest)) } } } override fun dismissAllNotifications() = NotificationManagerCompat.from(context).cancelAll() protected open fun createNotification(notification: Notification, notificationBehavior: NotificationBehavior?): android.app.Notification = CategoryAwareNotificationBuilder(context, SharedPreferencesNotificationCategoriesStore(context)).also { it.setNotification(notification) it.setAllowedBehavior(notificationBehavior) }.build() protected open fun getNotification(statusBarNotification: StatusBarNotification): Notification? { val notification = statusBarNotification.notification notification.extras.getByteArray(ExpoNotificationBuilder.EXTRAS_MARSHALLED_NOTIFICATION_REQUEST_KEY)?.let { try { with(Parcel.obtain()) { this.unmarshall(it, 0, it.size) this.setDataPosition(0) val request: NotificationRequest = NotificationRequest.CREATOR.createFromParcel(this) this.recycle() val notificationDate = Date(statusBarNotification.postTime) return Notification(request, notificationDate) } } catch (e: Exception) { // Let's catch all the exceptions -- there's nothing we can do here // and we'd rather return an array with a single, naively reconstructed notification // than throw an exception and return none. val message = "Could not have unmarshalled NotificationRequest from (${statusBarNotification.tag}, ${statusBarNotification.id})." Log.e("expo-notifications", message) } } // We weren't able to reconstruct the notification from our data, which means // it's either not our notification or we couldn't have unmarshaled it from // the byte array. Let's do what we can. val content = NotificationContent.Builder() .setTitle(notification.extras.getString(android.app.Notification.EXTRA_TITLE)) .setText(notification.extras.getString(android.app.Notification.EXTRA_TEXT)) .setSubtitle(notification.extras.getString(android.app.Notification.EXTRA_SUB_TEXT)) // using deprecated field .setPriority(NotificationPriority.fromNativeValue(notification.priority)) // using deprecated field .setVibrationPattern(notification.vibrate) // using deprecated field .setSound(notification.sound) .setAutoDismiss(notification.flags and android.app.Notification.FLAG_AUTO_CANCEL != 0) .setSticky(notification.flags and android.app.Notification.FLAG_ONGOING_EVENT != 0) .setBody(fromBundle(notification.extras)) .build() val request = NotificationRequest(getInternalIdentifierKey(statusBarNotification), content, null) return Notification(request, Date(statusBarNotification.postTime)) } protected open fun fromBundle(bundle: Bundle): JSONObject { return JSONObject().also { json -> for (key in bundle.keySet()) { try { json.put(key, JSONObject.wrap(bundle[key])) } catch (e: JSONException) { // can't do anything about it apart from logging it Log.d("expo-notifications", "Error encountered while serializing Android notification extras: " + key + " -> " + bundle[key], e) } } } } }
bsd-3-clause
3d2b79b444825ced12d069043963cc12
45.507538
140
0.736899
4.9973
false
false
false
false
Undin/intellij-rust
toml/src/main/kotlin/org/rust/toml/completion/CargoDependenciesPrefixMatcher.kt
3
920
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.toml.completion import com.intellij.codeInsight.completion.PrefixMatcher import com.intellij.psi.codeStyle.MinusculeMatcher import com.intellij.psi.codeStyle.NameUtil class CargoDependenciesPrefixMatcher(prefix: String): PrefixMatcher(prefix) { private val normalizedPrefix: String = normalize(prefix) private val minusculeMatcher: MinusculeMatcher = NameUtil.buildMatcher(normalizedPrefix).withSeparators("_").build() override fun prefixMatches(name: String): Boolean { val normalizedName = normalize(name) return minusculeMatcher.matches(normalizedName) } override fun cloneWithPrefix(prefix: String): PrefixMatcher = CargoDependenciesPrefixMatcher(prefix) private fun normalize(string: String) = string.replace('-', '_') }
mit
f282b3752b2866fb54b3a545e81ce6ef
33.074074
77
0.75
4.816754
false
false
false
false
google/dokka
core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt
1
14210
package org.jetbrains.dokka import com.google.inject.Inject import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.* import com.intellij.psi.impl.JavaConstantExpressionEvaluator import com.intellij.psi.util.InheritanceUtil import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.asJava.elements.KtLightDeclaration import org.jetbrains.kotlin.asJava.elements.KtLightElement import org.jetbrains.kotlin.kdoc.parser.KDocKnownTag import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtModifierListOwner import java.io.File fun getSignature(element: PsiElement?) = when(element) { is PsiPackage -> element.qualifiedName is PsiClass -> element.qualifiedName is PsiField -> element.containingClass!!.qualifiedName + "$" + element.name is PsiMethod -> element.containingClass!!.qualifiedName + "$" + element.name + "(" + element.parameterList.parameters.map { it.type.typeSignature() }.joinToString(",") + ")" else -> null } private fun PsiType.typeSignature(): String = when(this) { is PsiArrayType -> "Array((${componentType.typeSignature()}))" is PsiPrimitiveType -> "kotlin." + canonicalText.capitalize() else -> mapTypeName(this) } private fun mapTypeName(psiType: PsiType): String = when (psiType) { is PsiPrimitiveType -> psiType.canonicalText is PsiClassType -> psiType.resolve()?.qualifiedName ?: psiType.className is PsiEllipsisType -> mapTypeName(psiType.componentType) is PsiArrayType -> "kotlin.Array" else -> psiType.canonicalText } interface JavaDocumentationBuilder { fun appendFile(file: PsiJavaFile, module: DocumentationModule, packageContent: Map<String, Content>) } class JavaPsiDocumentationBuilder : JavaDocumentationBuilder { private val options: DocumentationOptions private val refGraph: NodeReferenceGraph private val docParser: JavaDocumentationParser @Inject constructor( options: DocumentationOptions, refGraph: NodeReferenceGraph, logger: DokkaLogger, signatureProvider: ElementSignatureProvider, externalDocumentationLinkResolver: ExternalDocumentationLinkResolver ) { this.options = options this.refGraph = refGraph this.docParser = JavadocParser(refGraph, logger, signatureProvider, externalDocumentationLinkResolver) } constructor(options: DocumentationOptions, refGraph: NodeReferenceGraph, docParser: JavaDocumentationParser) { this.options = options this.refGraph = refGraph this.docParser = docParser } override fun appendFile(file: PsiJavaFile, module: DocumentationModule, packageContent: Map<String, Content>) { if (skipFile(file) || file.classes.all { skipElement(it) }) { return } val packageNode = findOrCreatePackageNode(module, file.packageName, emptyMap(), refGraph) appendClasses(packageNode, file.classes) } fun appendClasses(packageNode: DocumentationNode, classes: Array<PsiClass>) { packageNode.appendChildren(classes) { build() } } fun register(element: PsiElement, node: DocumentationNode) { val signature = getSignature(element) if (signature != null) { refGraph.register(signature, node) } } fun link(node: DocumentationNode, element: PsiElement?) { val qualifiedName = getSignature(element) if (qualifiedName != null) { refGraph.link(node, qualifiedName, RefKind.Link) } } fun link(element: PsiElement?, node: DocumentationNode, kind: RefKind) { val qualifiedName = getSignature(element) if (qualifiedName != null) { refGraph.link(qualifiedName, node, kind) } } fun nodeForElement(element: PsiNamedElement, kind: NodeKind, name: String = element.name ?: "<anonymous>"): DocumentationNode { val (docComment, deprecatedContent, attrs, apiLevel, deprecatedLevel, artifactId, attribute) = docParser.parseDocumentation(element) val node = DocumentationNode(name, docComment, kind) if (element is PsiModifierListOwner) { node.appendModifiers(element) val modifierList = element.modifierList if (modifierList != null) { modifierList.annotations.filter { !ignoreAnnotation(it) }.forEach { val annotation = it.build() node.append(annotation, if (it.qualifiedName == "java.lang.Deprecated") RefKind.Deprecation else RefKind.Annotation) } } } if (deprecatedContent != null) { val deprecationNode = DocumentationNode("", deprecatedContent, NodeKind.Modifier) node.append(deprecationNode, RefKind.Deprecation) } if (element is PsiDocCommentOwner && element.isDeprecated && node.deprecation == null) { val deprecationNode = DocumentationNode("", Content.of(ContentText("Deprecated")), NodeKind.Modifier) node.append(deprecationNode, RefKind.Deprecation) } apiLevel?.let { node.append(it, RefKind.Detail) } deprecatedLevel?.let { node.append(it, RefKind.Detail) } artifactId?.let { node.append(it, RefKind.Detail) } attrs.forEach { refGraph.link(node, it, RefKind.Detail) refGraph.link(it, node, RefKind.Owner) } attribute?.let { val attrName = node.qualifiedName() refGraph.register("Attr:$attrName", attribute) } return node } fun ignoreAnnotation(annotation: PsiAnnotation) = when(annotation.qualifiedName) { "java.lang.SuppressWarnings" -> true else -> false } fun <T : Any> DocumentationNode.appendChildren(elements: Array<T>, kind: RefKind = RefKind.Member, buildFn: T.() -> DocumentationNode) { elements.forEach { if (!skipElement(it)) { append(it.buildFn(), kind) } } } private fun skipFile(javaFile: PsiJavaFile): Boolean = options.effectivePackageOptions(javaFile.packageName).suppress private fun skipElement(element: Any) = skipElementByVisibility(element) || hasSuppressDocTag(element) || hasHideAnnotation(element) || skipElementBySuppressedFiles(element) private fun skipElementByVisibility(element: Any): Boolean = element is PsiModifierListOwner && element !is PsiParameter && !(options.effectivePackageOptions((element.containingFile as? PsiJavaFile)?.packageName ?: "").includeNonPublic) && (element.hasModifierProperty(PsiModifier.PRIVATE) || element.hasModifierProperty(PsiModifier.PACKAGE_LOCAL) || element.isInternal()) private fun skipElementBySuppressedFiles(element: Any): Boolean = element is PsiElement && File(element.containingFile.virtualFile.path).absoluteFile in options.suppressedFiles private fun PsiElement.isInternal(): Boolean { val ktElement = (this as? KtLightElement<*, *>)?.kotlinOrigin ?: return false return (ktElement as? KtModifierListOwner)?.hasModifier(KtTokens.INTERNAL_KEYWORD) ?: false } fun <T : Any> DocumentationNode.appendMembers(elements: Array<T>, buildFn: T.() -> DocumentationNode) = appendChildren(elements, RefKind.Member, buildFn) fun <T : Any> DocumentationNode.appendDetails(elements: Array<T>, buildFn: T.() -> DocumentationNode) = appendChildren(elements, RefKind.Detail, buildFn) fun PsiClass.build(): DocumentationNode { val kind = when { isInterface -> NodeKind.Interface isEnum -> NodeKind.Enum isAnnotationType -> NodeKind.AnnotationClass isException() -> NodeKind.Exception else -> NodeKind.Class } val node = nodeForElement(this, kind) superTypes.filter { !ignoreSupertype(it) }.forEach { node.appendType(it, NodeKind.Supertype) val superClass = it.resolve() if (superClass != null) { link(superClass, node, RefKind.Inheritor) } } node.appendDetails(typeParameters) { build() } node.appendMembers(methods) { build() } node.appendMembers(fields) { build() } node.appendMembers(innerClasses) { build() } register(this, node) return node } fun PsiClass.isException() = InheritanceUtil.isInheritor(this, "java.lang.Throwable") fun ignoreSupertype(psiType: PsiClassType): Boolean = false // psiType.isClass("java.lang.Enum") || psiType.isClass("java.lang.Object") fun PsiClassType.isClass(qName: String): Boolean { val shortName = qName.substringAfterLast('.') if (className == shortName) { val psiClass = resolve() return psiClass?.qualifiedName == qName } return false } fun PsiField.build(): DocumentationNode { val node = nodeForElement(this, nodeKind()) node.appendType(type) node.appendConstantValueIfAny(this) register(this, node) return node } private fun DocumentationNode.appendConstantValueIfAny(field: PsiField) { val modifierList = field.modifierList ?: return val initializer = field.initializer ?: return if (modifierList.hasExplicitModifier(PsiModifier.FINAL) && modifierList.hasExplicitModifier(PsiModifier.STATIC)) { val value = JavaConstantExpressionEvaluator.computeConstantExpression(initializer, false) ?: return val text = when(value) { is String -> "\"${StringUtil.escapeStringCharacters(value)}\"" else -> value.toString() } append(DocumentationNode(text, Content.Empty, NodeKind.Value), RefKind.Detail) } } private fun PsiField.nodeKind(): NodeKind = when { this is PsiEnumConstant -> NodeKind.EnumItem else -> NodeKind.Field } fun PsiMethod.build(): DocumentationNode { val node = nodeForElement(this, nodeKind(), if (isConstructor) "<init>" else name) if (!isConstructor) { node.appendType(returnType) } node.appendDetails(parameterList.parameters) { build() } node.appendDetails(typeParameters) { build() } register(this, node) return node } private fun PsiMethod.nodeKind(): NodeKind = when { isConstructor -> NodeKind.Constructor else -> NodeKind.Function } fun PsiParameter.build(): DocumentationNode { val node = nodeForElement(this, NodeKind.Parameter) node.appendType(type) if (type is PsiEllipsisType) { node.appendTextNode("vararg", NodeKind.Modifier, RefKind.Detail) } return node } fun PsiTypeParameter.build(): DocumentationNode { val node = nodeForElement(this, NodeKind.TypeParameter) extendsListTypes.forEach { node.appendType(it, NodeKind.UpperBound) } implementsListTypes.forEach { node.appendType(it, NodeKind.UpperBound) } return node } fun DocumentationNode.appendModifiers(element: PsiModifierListOwner) { val modifierList = element.modifierList ?: return PsiModifier.MODIFIERS.forEach { if (modifierList.hasExplicitModifier(it)) { appendTextNode(it, NodeKind.Modifier) } } } fun DocumentationNode.appendType(psiType: PsiType?, kind: NodeKind = NodeKind.Type) { if (psiType == null) { return } append(psiType.build(kind), RefKind.Detail) } fun PsiType.build(kind: NodeKind = NodeKind.Type): DocumentationNode { val name = mapTypeName(this) val node = DocumentationNode(name, Content.Empty, kind) if (this is PsiClassType) { node.appendDetails(parameters) { build(NodeKind.Type) } link(node, resolve()) } if (this is PsiArrayType && this !is PsiEllipsisType) { node.append(componentType.build(NodeKind.Type), RefKind.Detail) } return node } fun PsiAnnotation.build(): DocumentationNode { val node = DocumentationNode(nameReferenceElement?.text ?: "<?>", Content.Empty, NodeKind.Annotation) parameterList.attributes.forEach { val parameter = DocumentationNode(it.name ?: "value", Content.Empty, NodeKind.Parameter) val value = it.value if (value != null) { val valueText = (value as? PsiLiteralExpression)?.value as? String ?: value.text val valueNode = DocumentationNode(valueText, Content.Empty, NodeKind.Value) parameter.append(valueNode, RefKind.Detail) } node.append(parameter, RefKind.Detail) } return node } } fun hasSuppressDocTag(element: Any?): Boolean { val declaration = (element as? KtLightDeclaration<*, *>)?.kotlinOrigin as? KtDeclaration ?: return false return PsiTreeUtil.findChildrenOfType(declaration.docComment, KDocTag::class.java).any { it.knownTag == KDocKnownTag.SUPPRESS } } /** * Determines if the @hide annotation is present in a Javadoc comment. * * @param element a doc element to analyze for the presence of @hide * * @return true if @hide is present, otherwise false * * Note: this does not process @hide annotations in KDoc. For KDoc, use the @suppress tag instead, which is processed * by [hasSuppressDocTag]. */ fun hasHideAnnotation(element: Any?): Boolean { return element is PsiDocCommentOwner && element.docComment?.run { findTagByName("hide") != null } ?: false }
apache-2.0
93a2fdd4c1d40afbac03706bbcb238c7
39.141243
140
0.646305
5.075
false
false
false
false
androidx/androidx
compose/ui/ui-tooling/src/androidMain/kotlin/androidx/compose/ui/tooling/ComposeViewAdapter.kt
3
29442
/* * 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.tooling import android.annotation.SuppressLint import android.content.Context import android.graphics.Canvas import android.graphics.DashPathEffect import android.graphics.Paint import android.os.Bundle import android.util.AttributeSet import android.util.Log import android.widget.FrameLayout import androidx.activity.OnBackPressedDispatcher import androidx.activity.OnBackPressedDispatcherOwner import androidx.activity.compose.LocalActivityResultRegistryOwner import androidx.activity.compose.LocalOnBackPressedDispatcherOwner import androidx.activity.result.ActivityResultRegistry import androidx.activity.result.ActivityResultRegistryOwner import androidx.activity.result.contract.ActivityResultContract import androidx.annotation.VisibleForTesting import androidx.compose.runtime.Composable import androidx.compose.runtime.Composition import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.SideEffect import androidx.compose.runtime.currentComposer import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.snapshots.Snapshot import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.LocalFontFamilyResolver import androidx.compose.ui.platform.LocalFontLoader import androidx.compose.ui.platform.ViewRootForTest import androidx.compose.ui.text.font.createFontFamilyResolver import androidx.compose.ui.tooling.animation.AnimateXAsStateComposeAnimation import androidx.compose.ui.tooling.animation.AnimationSearch import androidx.compose.ui.tooling.animation.PreviewAnimationClock import androidx.compose.ui.tooling.animation.UnsupportedComposeAnimation import androidx.compose.ui.tooling.data.Group import androidx.compose.ui.tooling.data.SourceLocation import androidx.compose.ui.tooling.data.UiToolingDataApi import androidx.compose.ui.tooling.data.asTree import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.tooling.preview.PreviewParameterProvider import androidx.compose.ui.unit.IntRect import androidx.core.app.ActivityOptionsCompat import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleRegistry import androidx.lifecycle.ViewModelStore import androidx.lifecycle.ViewModelStoreOwner import androidx.lifecycle.ViewTreeLifecycleOwner import androidx.lifecycle.ViewTreeViewModelStoreOwner import androidx.savedstate.SavedStateRegistry import androidx.savedstate.SavedStateRegistryController import androidx.savedstate.SavedStateRegistryOwner import androidx.savedstate.setViewTreeSavedStateRegistryOwner import java.lang.reflect.Method private const val TOOLS_NS_URI = "http://schemas.android.com/tools" private const val DESIGN_INFO_METHOD = "getDesignInfo" private const val REMEMBER = "remember" private val emptyContent: @Composable () -> Unit = @Composable {} /** * Class containing the minimum information needed by the Preview to map components to the * source code and render boundaries. * * @suppress */ @OptIn(UiToolingDataApi::class) data class ViewInfo( val fileName: String, val lineNumber: Int, val bounds: IntRect, val location: SourceLocation?, val children: List<ViewInfo> ) { fun hasBounds(): Boolean = bounds.bottom != 0 && bounds.right != 0 fun allChildren(): List<ViewInfo> = children + children.flatMap { it.allChildren() } override fun toString(): String = """($fileName:$lineNumber, |bounds=(top=${bounds.top}, left=${bounds.left}, |location=${location?.let { "(${it.offset}L${it.length}" } ?: "<none>"} |bottom=${bounds.bottom}, right=${bounds.right}), |childrenCount=${children.size})""".trimMargin() } /** * View adapter that renders a `@Composable`. The `@Composable` is found by * reading the `tools:composableName` attribute that contains the FQN. Additional attributes can * be used to customize the behaviour of this view: * - `tools:parameterProviderClass`: FQN of the [PreviewParameterProvider] to be instantiated by * the [ComposeViewAdapter] that will be used as source for the `@Composable` parameters. * - `tools:parameterProviderIndex`: The index within the [PreviewParameterProvider] of the * value to be used in this particular instance. * - `tools:paintBounds`: If true, the component boundaries will be painted. This is only meant * for debugging purposes. * - `tools:printViewInfos`: If true, the [ComposeViewAdapter] will log the tree of [ViewInfo] * to logcat for debugging. * - `tools:animationClockStartTime`: When set, a [PreviewAnimationClock] will control the * animations in the [ComposeViewAdapter] context. * * @suppress */ @Suppress("unused") @OptIn(UiToolingDataApi::class) internal class ComposeViewAdapter : FrameLayout { private val TAG = "ComposeViewAdapter" /** * [ComposeView] that will contain the [Composable] to preview. */ private val composeView = ComposeView(context) /** * When enabled, generate and cache [ViewInfo] tree that can be inspected by the Preview * to map components to source code. */ private var debugViewInfos = false /** * When enabled, paint the boundaries generated by layout nodes. */ private var debugPaintBounds = false internal var viewInfos: List<ViewInfo> = emptyList() internal var designInfoList: List<String> = emptyList() private val slotTableRecord = CompositionDataRecord.create() /** * Simple function name of the Composable being previewed. */ private var composableName = "" /** * Whether the current Composable has animations. */ private var hasAnimations = false /** * Saved exception from the last composition. Since we can not handle the exception during the * composition, we save it and throw it during onLayout, this allows Studio to catch it and * display it to the user. */ private val delayedException = ThreadSafeException() /** * The [Composable] to be rendered in the preview. It is initialized when this adapter * is initialized. */ private var previewComposition: @Composable () -> Unit = {} // Note: the constant emptyContent below instead of a literal {} works around // https://youtrack.jetbrains.com/issue/KT-17467, which causes the compiler to emit classes // named `content` and `Content` (from the Content method's composable update scope) // which causes compilation problems on case-insensitive filesystems. @Suppress("RemoveExplicitTypeArguments") private val content = mutableStateOf<@Composable () -> Unit>(emptyContent) /** * When true, the composition will be immediately invalidated after being drawn. This will * force it to be recomposed on the next render. This is useful for live literals so the * whole composition happens again on the next render. */ private var forceCompositionInvalidation = false /** * When true, the adapter will try to look objects that support the call * [DESIGN_INFO_METHOD] within the slot table and populate [designInfoList]. Used to * support rendering in Studio. */ private var lookForDesignInfoProviders = false /** * An additional [String] argument that will be passed to objects that support the * [DESIGN_INFO_METHOD] call. Meant to be used by studio to as a way to request additional * information from the Preview. */ private var designInfoProvidersArgument: String = "" /** * Callback invoked when onDraw has been called. */ private var onDraw = {} private val debugBoundsPaint = Paint().apply { pathEffect = DashPathEffect(floatArrayOf(5f, 10f, 15f, 20f), 0f) style = Paint.Style.STROKE color = Color.Red.toArgb() } private var composition: Composition? = null constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init(attrs) } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super( context, attrs, defStyleAttr ) { init(attrs) } private fun walkTable(viewInfo: ViewInfo, indent: Int = 0) { Log.d(TAG, ("| ".repeat(indent)) + "|-$viewInfo") viewInfo.children.forEach { walkTable(it, indent + 1) } } private val Group.fileName: String get() = location?.sourceFile ?: "" private val Group.lineNumber: Int get() = location?.lineNumber ?: -1 /** * Returns true if this [Group] has no source position information */ private fun Group.hasNullSourcePosition(): Boolean = fileName.isEmpty() && lineNumber == -1 /** * Returns true if this [Group] has no source position information and no children */ private fun Group.isNullGroup(): Boolean = hasNullSourcePosition() && children.isEmpty() private fun Group.toViewInfo(): ViewInfo { if (children.size == 1 && hasNullSourcePosition()) { // There is no useful information in this intermediate node, remove. return children.single().toViewInfo() } val childrenViewInfo = children .filter { !it.isNullGroup() } .map { it.toViewInfo() } // TODO: Use group names instead of indexing once it's supported return ViewInfo( location?.sourceFile ?: "", location?.lineNumber ?: -1, box, location, childrenViewInfo ) } /** * Processes the recorded slot table and re-generates the [viewInfos] attribute. */ private fun processViewInfos() { viewInfos = slotTableRecord.store.map { it.asTree() }.map { it.toViewInfo() }.toList() if (debugViewInfos) { viewInfos.forEach { walkTable(it) } } } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) // If there was a pending exception then throw it here since Studio will catch it and show // it to the user. delayedException.throwIfPresent() processViewInfos() if (composableName.isNotEmpty()) { findAndTrackAnimations() if (lookForDesignInfoProviders) { findDesignInfoProviders() } } } override fun onAttachedToWindow() { ViewTreeLifecycleOwner.set(composeView.rootView, FakeSavedStateRegistryOwner) super.onAttachedToWindow() } /** * Finds all animations defined in the Compose tree where the root is the * `@Composable` being previewed. We only return animations defined in the user code, i.e. * the ones we've got source information for. */ @Suppress("UNCHECKED_CAST") private fun findAndTrackAnimations() { val slotTrees = slotTableRecord.store.map { it.asTree() } val transitionSearch = AnimationSearch.TransitionSearch { clock.trackTransition(it) } val animatedContentSearch = AnimationSearch.AnimatedContentSearch { clock.trackAnimatedContent(it) } val animatedVisibilitySearch = AnimationSearch.AnimatedVisibilitySearch { clock.trackAnimatedVisibility(it, ::requestLayout) } fun animateXAsStateSearch() = if (AnimateXAsStateComposeAnimation.apiAvailable) setOf(AnimationSearch.AnimateXAsStateSearch { clock.trackAnimateXAsState(it) }) else emptyList() // All supported animations. fun supportedSearch() = setOf( transitionSearch, animatedVisibilitySearch, ) + animateXAsStateSearch() fun unsupportedSearch() = if (UnsupportedComposeAnimation.apiAvailable) setOf( animatedContentSearch, AnimationSearch.AnimateContentSizeSearch { clock.trackAnimateContentSize(it) }, AnimationSearch.TargetBasedSearch { clock.trackTargetBasedAnimations(it) }, AnimationSearch.DecaySearch { clock.trackDecayAnimations(it) }, AnimationSearch.InfiniteTransitionSearch { clock.trackInfiniteTransition(it) } ) else emptyList() // All supported animations val supportedSearch = supportedSearch() // Animations to track in PreviewAnimationClock. val setToTrack = supportedSearch + unsupportedSearch() // Animations to search. animatedContentSearch is included even if it's not going to be // tracked as it should be excluded from transitionSearch. val setToSearch = setToTrack + setOf(animatedContentSearch) // Check all the slot tables, since some animations might not be present in the same // table as the one containing the `@Composable` being previewed, e.g. when they're // defined using sub-composition. slotTrees.forEach { tree -> val groupsWithLocation = tree.findAll { it.location != null } setToSearch.forEach { it.addAnimations(groupsWithLocation) } // Remove all AnimatedVisibility parent transitions from the transitions list, // otherwise we'd duplicate them in the Android Studio Animation Preview because we // will track them separately. transitionSearch.animations.removeAll(animatedVisibilitySearch.animations) // Remove all AnimatedContent parent transitions from the transitions list, so we can // ignore these animations while support is not added to Animation Preview. transitionSearch.animations.removeAll(animatedContentSearch.animations) } // If non of supported animations are detected, unsupported animations should not be // available either. hasAnimations = supportedSearch.any { it.hasAnimations() } // Make the `PreviewAnimationClock` track all the transitions found. if (::clock.isInitialized && hasAnimations) { setToTrack.forEach { it.track() } } } /** * Find all data objects within the slotTree that can invoke '[DESIGN_INFO_METHOD]', and store * their result in [designInfoList]. */ private fun findDesignInfoProviders() { val slotTrees = slotTableRecord.store.map { it.asTree() } designInfoList = slotTrees.flatMap { rootGroup -> rootGroup.findAll { group -> (group.name != REMEMBER && group.hasDesignInfo()) || group.children.any { child -> child.name == REMEMBER && child.hasDesignInfo() } }.mapNotNull { group -> // Get the DesignInfoProviders from the group or one of its children group.getDesignInfoOrNull(group.box) ?: group.children.firstNotNullOfOrNull { it.getDesignInfoOrNull(group.box) } } } } private fun Group.hasDesignInfo(): Boolean = data.any { it?.getDesignInfoMethodOrNull() != null } private fun Group.getDesignInfoOrNull(box: IntRect): String? = data.firstNotNullOfOrNull { it?.invokeGetDesignInfo(box.left, box.right) } /** * Check if the object supports the method call for [DESIGN_INFO_METHOD], which is expected * to take two Integer arguments for coordinates and a String for additional encoded * arguments that may be provided from Studio. */ private fun Any.getDesignInfoMethodOrNull(): Method? { return try { javaClass.getDeclaredMethod( DESIGN_INFO_METHOD, Integer.TYPE, Integer.TYPE, String::class.java ) } catch (e: NoSuchMethodException) { null } } @Suppress("BanUncheckedReflection") private fun Any.invokeGetDesignInfo(x: Int, y: Int): String? { return this.getDesignInfoMethodOrNull()?.let { designInfoMethod -> try { // Workaround for unchecked Method.invoke val result = designInfoMethod.invoke( this, x, y, designInfoProvidersArgument ) (result as String).ifEmpty { null } } catch (e: Exception) { null } } } private fun invalidateComposition() { // Invalidate the full composition by setting it to empty and back to the actual value content.value = {} content.value = previewComposition // Invalidate the state of the view so it gets redrawn invalidate() } override fun dispatchDraw(canvas: Canvas?) { super.dispatchDraw(canvas) if (forceCompositionInvalidation) invalidateComposition() onDraw() if (!debugPaintBounds) { return } viewInfos .flatMap { listOf(it) + it.allChildren() } .forEach { if (it.hasBounds()) { canvas?.apply { val pxBounds = android.graphics.Rect( it.bounds.left, it.bounds.top, it.bounds.right, it.bounds.bottom ) drawRect(pxBounds, debugBoundsPaint) } } } } /** * Clock that controls the animations defined in the context of this [ComposeViewAdapter]. * * @suppress */ @VisibleForTesting internal lateinit var clock: PreviewAnimationClock /** * Wraps a given [Preview] method an does any necessary setup. */ @Composable private fun WrapPreview(content: @Composable () -> Unit) { // We need to replace the FontResourceLoader to avoid using ResourcesCompat. // ResourcesCompat can not load fonts within Layoutlib and, since Layoutlib always runs // the latest version, we do not need it. @Suppress("DEPRECATION") CompositionLocalProvider( LocalFontLoader provides LayoutlibFontResourceLoader(context), LocalFontFamilyResolver provides createFontFamilyResolver(context), LocalOnBackPressedDispatcherOwner provides FakeOnBackPressedDispatcherOwner, LocalActivityResultRegistryOwner provides FakeActivityResultRegistryOwner, ) { Inspectable(slotTableRecord, content) } } /** * Initializes the adapter and populates it with the given [Preview] composable. * @param className name of the class containing the preview function * @param methodName `@Preview` method name * @param parameterProvider [Class] for the [PreviewParameterProvider] to be used as * parameter input for this call. If null, no parameters will be passed to the composable. * @param parameterProviderIndex when [parameterProvider] is not null, this index will * reference the element in the [Sequence] to be used as parameter. * @param debugPaintBounds if true, the view will paint the boundaries around the layout * elements. * @param debugViewInfos if true, it will generate the [ViewInfo] structures and will log it. * @param animationClockStartTime if positive, [clock] will be defined and will control the * animations defined in the context of the `@Composable` being previewed. * @param forceCompositionInvalidation if true, the composition will be invalidated on every * draw, forcing it to recompose on next render. * @param lookForDesignInfoProviders if true, it will try to populate [designInfoList]. * @param designInfoProvidersArgument String to use as an argument when populating * [designInfoList]. * @param onCommit callback invoked after every commit of the preview composable. * @param onDraw callback invoked after every draw of the adapter. Only for test use. */ @Suppress("DEPRECATION") @OptIn(ExperimentalComposeUiApi::class) @VisibleForTesting internal fun init( className: String, methodName: String, parameterProvider: Class<out PreviewParameterProvider<*>>? = null, parameterProviderIndex: Int = 0, debugPaintBounds: Boolean = false, debugViewInfos: Boolean = false, animationClockStartTime: Long = -1, forceCompositionInvalidation: Boolean = false, lookForDesignInfoProviders: Boolean = false, designInfoProvidersArgument: String? = null, onCommit: () -> Unit = {}, onDraw: () -> Unit = {} ) { this.debugPaintBounds = debugPaintBounds this.debugViewInfos = debugViewInfos this.composableName = methodName this.forceCompositionInvalidation = forceCompositionInvalidation this.lookForDesignInfoProviders = lookForDesignInfoProviders this.designInfoProvidersArgument = designInfoProvidersArgument ?: "" this.onDraw = onDraw previewComposition = @Composable { SideEffect(onCommit) WrapPreview { val composer = currentComposer // We need to delay the reflection instantiation of the class until we are in the // composable to ensure all the right initialization has happened and the Composable // class loads correctly. val composable = { try { ComposableInvoker.invokeComposable( className, methodName, composer, *getPreviewProviderParameters(parameterProvider, parameterProviderIndex) ) } catch (t: Throwable) { // If there is an exception, store it for later but do not catch it so // compose can handle it and dispose correctly. var exception: Throwable = t // Find the root cause and use that for the delayedException. while (exception is ReflectiveOperationException) { exception = exception.cause ?: break } delayedException.set(exception) throw t } } if (animationClockStartTime >= 0) { // When animation inspection is enabled, i.e. when a valid (non-negative) // `animationClockStartTime` is passed, set the Preview Animation Clock. This // clock will control the animations defined in this `ComposeViewAdapter` // from Android Studio. clock = PreviewAnimationClock { // Invalidate the descendants of this ComposeViewAdapter's only grandchild // (an AndroidOwner) when setting the clock time to make sure the Compose // Preview will animate when the states are read inside the draw scope. val composeView = getChildAt(0) as ComposeView (composeView.getChildAt(0) as? ViewRootForTest) ?.invalidateDescendants() // Send pending apply notifications to ensure the animation duration will // be read in the correct frame. Snapshot.sendApplyNotifications() } } composable() } } composeView.setContent(previewComposition) invalidate() } /** * Disposes the Compose elements allocated during [init] */ internal fun dispose() { composeView.disposeComposition() if (::clock.isInitialized) { clock.dispose() } FakeSavedStateRegistryOwner.lifecycleRegistry.currentState = Lifecycle.State.DESTROYED FakeViewModelStoreOwner.viewModelStore.clear() } /** * Returns whether this `@Composable` has animations. This allows Android Studio to decide if * the Animation Inspector icon should be displayed for this preview. The reason for using a * method instead of the property directly is we use Java reflection to call it from Android * Studio, and to find the property we'd need to filter the method names using `contains` * instead of `equals`. * * @suppress */ fun hasAnimations() = hasAnimations private fun init(attrs: AttributeSet) { // ComposeView and lifecycle initialization ViewTreeLifecycleOwner.set(this, FakeSavedStateRegistryOwner) setViewTreeSavedStateRegistryOwner(FakeSavedStateRegistryOwner) ViewTreeViewModelStoreOwner.set(this, FakeViewModelStoreOwner) addView(composeView) val composableName = attrs.getAttributeValue(TOOLS_NS_URI, "composableName") ?: return val className = composableName.substringBeforeLast('.') val methodName = composableName.substringAfterLast('.') val parameterProviderIndex = attrs.getAttributeIntValue( TOOLS_NS_URI, "parameterProviderIndex", 0 ) val parameterProviderClass = attrs.getAttributeValue(TOOLS_NS_URI, "parameterProviderClass") ?.asPreviewProviderClass() val animationClockStartTime = try { attrs.getAttributeValue(TOOLS_NS_URI, "animationClockStartTime").toLong() } catch (e: Exception) { -1L } val forceCompositionInvalidation = attrs.getAttributeBooleanValue( TOOLS_NS_URI, "forceCompositionInvalidation", false ) init( className = className, methodName = methodName, parameterProvider = parameterProviderClass, parameterProviderIndex = parameterProviderIndex, debugPaintBounds = attrs.getAttributeBooleanValue( TOOLS_NS_URI, "paintBounds", debugPaintBounds ), debugViewInfos = attrs.getAttributeBooleanValue( TOOLS_NS_URI, "printViewInfos", debugViewInfos ), animationClockStartTime = animationClockStartTime, forceCompositionInvalidation = forceCompositionInvalidation, lookForDesignInfoProviders = attrs.getAttributeBooleanValue( TOOLS_NS_URI, "findDesignInfoProviders", lookForDesignInfoProviders ), designInfoProvidersArgument = attrs.getAttributeValue( TOOLS_NS_URI, "designInfoProvidersArgument" ) ) } @SuppressLint("VisibleForTests") private val FakeSavedStateRegistryOwner = object : SavedStateRegistryOwner { val lifecycleRegistry = LifecycleRegistry.createUnsafe(this) private val controller = SavedStateRegistryController.create(this).apply { performRestore(Bundle()) } init { lifecycleRegistry.currentState = Lifecycle.State.RESUMED } override val savedStateRegistry: SavedStateRegistry get() = controller.savedStateRegistry override fun getLifecycle(): Lifecycle = lifecycleRegistry } private val FakeViewModelStoreOwner = object : ViewModelStoreOwner { private val viewModelStore = ViewModelStore() override fun getViewModelStore() = viewModelStore } private val FakeOnBackPressedDispatcherOwner = object : OnBackPressedDispatcherOwner { private val onBackPressedDispatcher = OnBackPressedDispatcher() override fun getOnBackPressedDispatcher() = onBackPressedDispatcher override fun getLifecycle() = FakeSavedStateRegistryOwner.lifecycleRegistry } private val FakeActivityResultRegistryOwner = object : ActivityResultRegistryOwner { private val activityResultRegistry = object : ActivityResultRegistry() { override fun <I : Any?, O : Any?> onLaunch( requestCode: Int, contract: ActivityResultContract<I, O>, input: I, options: ActivityOptionsCompat? ) { throw IllegalStateException("Calling launch() is not supported in Preview") } } override fun getActivityResultRegistry(): ActivityResultRegistry = activityResultRegistry } }
apache-2.0
fde1ad8ec9166a0888ec4ddc38a23509
39.891667
100
0.658787
5.458287
false
false
false
false
DemonWav/StatCraft
src/main/kotlin/com/demonwav/statcraft/commands/sc/SCDamageDealt.kt
1
1983
/* * StatCraft Bukkit Plugin * * Copyright (c) 2016 Kyle Wood (DemonWav) * https://www.demonwav.com * * MIT License */ package com.demonwav.statcraft.commands.sc import com.demonwav.statcraft.StatCraft import com.demonwav.statcraft.commands.ResponseBuilder import com.demonwav.statcraft.querydsl.QDamageDealt import com.demonwav.statcraft.querydsl.QPlayers import org.bukkit.command.CommandSender import java.sql.Connection class SCDamageDealt(plugin: StatCraft) : SCTemplate(plugin) { init { plugin.baseCommand.registerCommand("damagedealt", this) } override fun hasPermission(sender: CommandSender, args: Array<out String>?) = sender.hasPermission("statcraft.user.damagedealt") override fun playerStatResponse(name: String, args: List<String>, connection: Connection): String { val id = getId(name) ?: return ResponseBuilder.build(plugin) { playerName { name } statName { "Damage Dealt" } stats["Total"] = "0" } val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError val d = QDamageDealt.damageDealt val total = query.from(d).where(d.id.eq(id)).uniqueResult(d.amount.sum()) ?: 0 return ResponseBuilder.build(plugin) { playerName { name } statName { "Damage Dealt" } stats["Total"] = df.format(total) } } override fun serverStatListResponse(num: Long, args: List<String>, connection: Connection): String { val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError val d = QDamageDealt.damageDealt val p = QPlayers.players val list = query .from(d) .innerJoin(p) .on(d.id.eq(p.id)) .groupBy(p.name) .orderBy(d.amount.sum().desc()) .limit(num) .list(p.name, d.amount.sum()) return topListResponse("Damage Dealt", list) } }
mit
e1daec08951d040281c53159cc49b9a9
30.47619
132
0.648008
4.148536
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/net/social/SpanUtil.kt
1
10656
/* * Copyright (c) 2018 yvolk (Yuri Volkov), http://yurivolkov.com * * 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.andstatus.app.net.social import android.text.Spannable import android.text.SpannableString import android.text.Spanned import org.andstatus.app.data.TextMediaType import org.andstatus.app.util.MyHtml import org.andstatus.app.util.MyUrlSpan import java.util.* import java.util.function.Function import java.util.stream.Stream object SpanUtil { private const val MIN_SPAN_LENGTH = 3 private const val MIN_HASHTAG_LENGTH = 2 val EMPTY = SpannableString.valueOf("") fun regionsOf(spannable: Spanned): MutableList<Region> { return Stream.concat( Arrays.stream(spannable.getSpans(0, spannable.length, Any::class.java)) .map { span: Any -> Region(spannable, span) }, Stream.of(Region(spannable, spannable.length, spannable.length + 1))) .sorted() .reduce( ArrayList(), { xs: ArrayList<Region>, region: Region -> val prevRegion = Region(spannable, if (xs.size == 0) 0 else xs.get(xs.size - 1).end, region.start) if (prevRegion.isValid()) xs.add(prevRegion) if (region.isValid()) xs.add(region) xs }, { xs1: ArrayList<Region>, xs2: ArrayList<Region> -> xs1.addAll(xs2) xs1 }) } fun textToSpannable(text: String?, mediaType: TextMediaType, audience: Audience): Spannable { return if (text.isNullOrEmpty()) EMPTY else spansModifier(audience).apply(MyUrlSpan.toSpannable( if (mediaType == TextMediaType.PLAIN) text else MyHtml.prepareForView(text), mediaType, true)) } fun spansModifier(audience: Audience): Function<Spannable, Spannable> { return Function { spannable: Spannable -> regionsOf(spannable).forEach(modifySpansInRegion(spannable, audience)) spannable } } private fun modifySpansInRegion(spannable: Spannable, audience: Audience): ((Region) -> Unit) = fun(region: Region) { if (region.start >= spannable.length || region.end > spannable.length) return val text = spannable.subSequence(region.start, region.end).toString() if (mentionAdded(spannable, audience, region, text)) return hashTagAdded(spannable, audience, region, text) } private fun mentionAdded(spannable: Spannable, audience: Audience, region: Region, text: String): Boolean { if (audience.hasNonSpecial() && text.contains("@")) { val upperText = text.toUpperCase() val mentionedByAtWebfingerID = audience.getNonSpecialActors().stream() .filter { actor: Actor -> actor.isWebFingerIdValid() && upperText.contains("@" + actor.getWebFingerId().toUpperCase()) }.findAny().orElse(Actor.EMPTY) if (mentionedByAtWebfingerID.nonEmpty) { return notesByActorSpanAdded(spannable, audience, region, "@" + mentionedByAtWebfingerID.getWebFingerId(), mentionedByAtWebfingerID) } else { val mentionedByWebfingerID = audience.getNonSpecialActors().stream() .filter { actor: Actor -> actor.isWebFingerIdValid() && upperText.contains(actor.getWebFingerId().toUpperCase()) }.findAny().orElse(Actor.EMPTY) if (mentionedByWebfingerID.nonEmpty) { return notesByActorSpanAdded(spannable, audience, region, mentionedByWebfingerID.getWebFingerId(), mentionedByWebfingerID) } else { val mentionedByUsername = audience.getNonSpecialActors().stream() .filter { actor: Actor -> actor.isUsernameValid() && upperText.contains("@" + actor.getUsername().toUpperCase()) }.findAny().orElse(Actor.EMPTY) if (mentionedByUsername.nonEmpty) { return notesByActorSpanAdded(spannable, audience, region, "@" + mentionedByUsername.getUsername(), mentionedByUsername) } } } } return false } private fun notesByActorSpanAdded(spannable: Spannable, audience: Audience, region: Region, stringFound: String, actor: Actor): Boolean { return spanAdded(spannable, audience, region, stringFound, MyUrlSpan.Data(Optional.of(actor), Optional.empty(), Optional.empty())) } private fun spanAdded(spannable: Spannable, audience: Audience, region: Region, stringFound: String, spanData: MyUrlSpan.Data): Boolean { if (region.urlSpan.isPresent()) { spannable.removeSpan(region.urlSpan.get()) spannable.setSpan(MyUrlSpan(spanData), region.start, region.end, 0) } else if (region.otherSpan.isPresent()) { spannable.removeSpan(region.otherSpan.get()) spannable.setSpan(MyUrlSpan(spanData), region.start, region.end, 0) } else { val indInRegion = getIndInRegion(spannable, region, stringFound) if (indInRegion < 0) return false val start2 = region.start + indInRegion val start3 = start2 + stringFound.length if (start3 > region.end + 1) return false spannable.setSpan(MyUrlSpan(spanData), start2, Math.min(start3, region.end), 0) if (indInRegion >= MIN_SPAN_LENGTH) { modifySpansInRegion(spannable, audience).invoke( Region(spannable, region.start, start2) ) } if (start3 + MIN_SPAN_LENGTH <= region.end) { modifySpansInRegion(spannable, audience).invoke( Region(spannable, start3, region.end) ) } } return true } /** Case insensitive search */ private fun getIndInRegion(spannable: Spannable, region: Region, stringFound: String): Int { val substr1 = spannable.subSequence(region.start, region.end).toString() val indInRegion = substr1.indexOf(stringFound) if (indInRegion >= 0) return indInRegion val foundUpper = stringFound.toUpperCase() var ind = 0 do { val ind2 = substr1.substring(ind).toUpperCase().indexOf(foundUpper) if (ind2 >= 0) return ind2 + ind ind++ } while (ind + stringFound.length < substr1.length) return -1 } /** As https://www.hashtags.org/definition/ shows, hashtags may have numbers only, * and may contain one symbol only */ private fun hashTagAdded(spannable: Spannable, audience: Audience, region: Region, text: String): Boolean { var indStart = 0 var hashTag: String do { val indTag = text.indexOf('#', indStart) if (indTag < 0) return false hashTag = hashTagAt(text, indTag) indStart = indTag + 1 } while (hashTag.length < MIN_HASHTAG_LENGTH) return spanAdded(spannable, audience, region, hashTag, MyUrlSpan.Data(Optional.empty(), Optional.of(hashTag), Optional.empty())) } private fun hashTagAt(text: String, indStart: Int): String { if (indStart + 1 >= text.length || text.get(indStart) != '#' || !Character.isLetterOrDigit(text.get(indStart + 1)) || indStart > 0 && Character.isLetterOrDigit(text.get(indStart - 1))) { return "" } var ind = indStart + 2 while (ind < text.length) { val c = text.get(ind) if (!Character.isLetterOrDigit(c) && c != '_') break ind++ } return text.substring(indStart, ind) } class Region : Comparable<Region> { val start: Int val end: Int val text: CharSequence? val urlSpan: Optional<MyUrlSpan> val otherSpan: Optional<Any> constructor(spannable: Spanned, span: Any) { val spanStart = spannable.getSpanStart(span) // Sometimes "@" is not included in the span start = if (spanStart > 0 && "@#".indexOf(spannable.get(spanStart)) < 0 && "@#".indexOf(spannable.get(spanStart - 1)) >= 0) spanStart - 1 else spanStart if (MyUrlSpan::class.java.isAssignableFrom(span.javaClass)) { urlSpan = Optional.of(span as MyUrlSpan) otherSpan = Optional.empty() } else { urlSpan = Optional.empty() otherSpan = Optional.of(span) } end = spannable.getSpanEnd(span) text = spannable.subSequence(start, end) } constructor(spannable: Spanned, start: Int, end: Int) { this.start = start this.end = end urlSpan = Optional.empty() otherSpan = Optional.empty() text = if (start < end && spannable.length >= end) spannable.subSequence(start, end) else "" } override operator fun compareTo(other: Region): Int { return Integer.compare(start, other.start) } override fun toString(): String { return "Region{" + start + "-" + end + " '" + text + "'" + urlSpan.map { s: MyUrlSpan? -> ", $s" }.orElse("") + otherSpan.map { s: Any? -> ", otherSpan" }.orElse("") + '}' } fun isValid(): Boolean { return urlSpan.isPresent() || otherSpan.isPresent() || end - start >= MIN_SPAN_LENGTH } } }
apache-2.0
d19b22aa19218fc3728b043a2fd5e979
44.538462
164
0.573198
4.852459
false
false
false
false
CruGlobal/android-gto-support
gto-support-db/src/main/java/org/ccci/gto/android/common/db/Query.kt
1
2914
package org.ccci.gto.android.common.db import android.annotation.SuppressLint import androidx.annotation.RestrictTo import androidx.annotation.VisibleForTesting import org.ccci.gto.android.common.db.AbstractDao.Companion.bindValues @SuppressLint("SupportAnnotationUsage") data class Query<T : Any> private constructor( @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) val table: Table<T>, internal val isDistinct: Boolean = false, @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) val joins: List<Join<T, *>> = emptyList(), internal val projection: List<String>? = null, @VisibleForTesting internal val where: Expression? = null, internal val orderBy: String? = null, internal val groupBy: List<Expression.Field> = emptyList(), private val having: Expression? = null, private val limit: Int? = null, private val offset: Int? = null ) { companion object { @JvmStatic fun <T : Any> select(type: Class<T>) = Query(table = Table.forClass(type)) @JvmStatic fun <T : Any> select(table: Table<T>) = Query(table = table) inline fun <reified T : Any> select() = select(T::class.java) } @get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) val allTables get() = sequenceOf(table) + joins.flatMap { it.allTables } fun distinct(isDistinct: Boolean) = copy(isDistinct = isDistinct) fun join(vararg joins: Join<T, *>) = copy(joins = this.joins + joins) fun joins(vararg joins: Join<T, *>) = copy(joins = joins.toList()) fun projection(vararg projection: String) = copy(projection = projection.toList().takeUnless { it.isEmpty() }) fun where(where: Expression?) = copy(where = where) fun where(where: String?, vararg args: Any) = where(where, *bindValues(*args)) fun where(where: String?, vararg args: String) = where(where?.let { Expression.raw(it, args) }) fun andWhere(expr: Expression) = copy(where = where?.and(expr) ?: expr) fun orderBy(orderBy: String?): Query<T> = copy(orderBy = orderBy) fun groupBy(vararg groupBy: Expression.Field) = copy(groupBy = groupBy.toList()) fun having(having: Expression?) = copy(having = having) fun limit(limit: Int?) = copy(limit = limit) fun offset(offset: Int?) = copy(offset = offset) internal fun buildSqlFrom(dao: AbstractDao) = QueryComponent(table.sqlTable(dao)) + joins.joinToQueryComponent { it.getSql(dao) } internal fun buildSqlWhere(dao: AbstractDao) = where?.buildSql(dao) internal fun buildSqlHaving(dao: AbstractDao) = having?.buildSql(dao) internal val sqlLimit get() = when { // // XXX: not supported by Android // // "{limit} OFFSET {offset}" syntax // limit != null && offset != null -> "$limit OFFSET $offset" // "{offset},{limit}" syntax limit != null && offset != null -> "$offset, $limit" limit != null -> "$limit" else -> null } }
mit
13c8aa4ca2a75a88c58928fcbe72d704
45.253968
114
0.66884
3.88016
false
false
false
false
arkon/LISTEN.moe-Unofficial-Android-App
app/src/main/java/me/echeung/moemoekyun/adapter/SongDetailAdapter.kt
1
2181
package me.echeung.moemoekyun.adapter import android.app.Activity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import androidx.databinding.DataBindingUtil import me.echeung.moemoekyun.R import me.echeung.moemoekyun.client.auth.AuthUtil import me.echeung.moemoekyun.client.model.Song import me.echeung.moemoekyun.databinding.SongDetailsBinding import me.echeung.moemoekyun.util.SongActionsUtil import me.echeung.moemoekyun.util.ext.openUrl import org.koin.core.KoinComponent import org.koin.core.inject class SongDetailAdapter( private val activity: Activity, songs: List<Song> ) : ArrayAdapter<Song>(activity, 0, songs), KoinComponent { private val authUtil: AuthUtil by inject() private val songActionsUtil: SongActionsUtil by inject() override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val inflater = LayoutInflater.from(context) val binding: SongDetailsBinding var view = convertView if (view == null) { binding = DataBindingUtil.inflate(inflater, R.layout.song_details, parent, false) view = binding.root view.tag = binding } else { binding = view.tag as SongDetailsBinding } val song = getItem(position) ?: return binding.root binding.song = song binding.isAuthenticated = authUtil.isAuthenticated binding.isFavorite = song.favorite binding.requestBtn.setOnClickListener { songActionsUtil.request(activity, song) } binding.favoriteBtn.setOnClickListener { songActionsUtil.toggleFavorite(activity, song) song.favorite = !song.favorite binding.isFavorite = song.favorite } binding.albumArt.setOnLongClickListener { val albumArtUrl = song.albumArtUrl ?: return@setOnLongClickListener false context.openUrl(albumArtUrl) true } binding.root.setOnLongClickListener { songActionsUtil.copyToClipboard(context, song) true } return binding.root } }
mit
88891c7d290563c314b1c97c4f316590
31.552239
93
0.701055
4.857461
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/helper/ActivityHelper.kt
2
1639
package ru.fantlab.android.helper import android.app.Activity import android.content.* import androidx.core.app.ShareCompat import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import es.dmoral.toasty.Toasty import ru.fantlab.android.App import ru.fantlab.android.R object ActivityHelper { fun getActivity(content: Context?): Activity? { return when (content) { null -> null is Activity -> content is ContextWrapper -> getActivity(content.baseContext) else -> null } } fun getVisibleFragment(manager: FragmentManager): Fragment? { val fragments = manager.fragments if (fragments != null && !fragments.isEmpty()) { fragments .filter { it != null && it.isVisible } .forEach { return it } } return null } fun shareUrl(context: Context, url: String) { val activity = getActivity(context) ?: throw IllegalArgumentException("Context given is not an instance of activity ${context.javaClass.name}") try { ShareCompat.IntentBuilder.from(activity) .setChooserTitle(context.getString(R.string.share)) .setType("text/plain") .setText(url) .startChooser() } catch (e: ActivityNotFoundException) { Toasty.error(App.instance, e.message!!, Toast.LENGTH_LONG).show() } } fun copyToClipboard(context: Context, uri: String) { val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val clip = ClipData.newPlainText(context.getString(R.string.app_name), uri) clipboard.primaryClip = clip Toasty.success(App.instance, context.getString(R.string.success_copied)).show() } }
gpl-3.0
aa294f2f32aa40591dd43a5d83844d03
29.37037
111
0.737035
3.776498
false
false
false
false
inorichi/tachiyomi-extensions
src/es/tmohentai/src/eu/kanade/tachiyomi/extension/es/tmohentai/TMOHentai.kt
1
12638
package eu.kanade.tachiyomi.extension.es.tmohentai import android.app.Application import android.content.SharedPreferences import eu.kanade.tachiyomi.annotations.Nsfw import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.asObservableSuccess import eu.kanade.tachiyomi.source.ConfigurableSource import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.Request import org.jsoup.nodes.Document import org.jsoup.nodes.Element import rx.Observable import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get @Nsfw class TMOHentai : ConfigurableSource, ParsedHttpSource() { override val name = "TMOHentai" override val baseUrl = "https://tmohentai.com" override val lang = "es" override val supportsLatest = true private val preferences: SharedPreferences by lazy { Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000) } override fun popularMangaRequest(page: Int) = GET("$baseUrl/section/all?view=list&page=$page&order=popularity&order-dir=desc&search[searchText]=&search[searchBy]=name&type=all", headers) override fun popularMangaSelector() = "table > tbody > tr[data-toggle=popover]" override fun popularMangaFromElement(element: Element) = SManga.create().apply { element.select("tr").let { title = it.attr("data-title") thumbnail_url = it.attr("data-content").substringAfter("src=\"").substringBeforeLast("\"") setUrlWithoutDomain(it.select("td.text-left > a").attr("href")) } } override fun popularMangaNextPageSelector() = "a[rel=next]" override fun latestUpdatesRequest(page: Int) = GET("$baseUrl/section/all?view=list&page=$page&order=publication_date&order-dir=desc&search[searchText]=&search[searchBy]=name&type=all", headers) override fun latestUpdatesSelector() = popularMangaSelector() override fun latestUpdatesFromElement(element: Element) = popularMangaFromElement(element) override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector() override fun mangaDetailsParse(document: Document) = SManga.create().apply { val parsedInformation = document.select("div.row > div.panel.panel-primary").text() val authorAndArtist = parsedInformation.substringAfter("Groups").substringBefore("Magazines").trim() title = document.select("h3.truncate").text() thumbnail_url = document.select("img.content-thumbnail-cover").attr("src") author = authorAndArtist artist = authorAndArtist description = "Sin descripción" status = SManga.UNKNOWN genre = parsedInformation.substringAfter("Genders").substringBefore("Tags").trim().split(" ").joinToString { it } } override fun chapterListSelector() = "div#app > div.container" override fun chapterFromElement(element: Element) = SChapter.create().apply { val parsedInformation = element.select("div.row > div.panel.panel-primary").text() name = element.select("h3.truncate").text() scanlator = parsedInformation.substringAfter("By").substringBefore("Language").trim() var currentUrl = element.select("a.pull-right.btn.btn-primary").attr("href") if (currentUrl.contains("/1")) { currentUrl = currentUrl.substringBeforeLast("/") } setUrlWithoutDomain(currentUrl) // date_upload = no date in the web } // "/cascade" to get all images override fun pageListRequest(chapter: SChapter): Request { val currentUrl = chapter.url val newUrl = if (getPageMethodPref() == "cascade" && currentUrl.contains("paginated")) { currentUrl.substringBefore("paginated") + "cascade" } else if (getPageMethodPref() == "paginated" && currentUrl.contains("cascade")) { currentUrl.substringBefore("cascade") + "paginated" } else currentUrl return GET("$baseUrl$newUrl", headers) } override fun pageListParse(document: Document): List<Page> = mutableListOf<Page>().apply { if (getPageMethodPref() == "cascade") { document.select("div#content-images img.content-image")?.forEach { add(Page(size, "", it.attr("data-original"))) } } else { val pageList = document.select("select#select-page").first().select("option").map { it.attr("value").toInt() } val url = document.baseUri() pageList.forEach { add(Page(it, "$url/$it")) } } } override fun imageUrlParse(document: Document) = document.select("div#content-images img.content-image").attr("data-original") override fun imageRequest(page: Page) = GET("$baseUrl${page.imageUrl!!}", headers) override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val url = "$baseUrl/section/all?view=list".toHttpUrlOrNull()!!.newBuilder() url.addQueryParameter("search[searchText]", query) url.addQueryParameter("page", page.toString()) (if (filters.isEmpty()) getFilterList() else filters).forEach { filter -> when (filter) { is Types -> { url.addQueryParameter("type", filter.toUriPart()) } is GenreList -> { filter.state .filter { genre -> genre.state } .forEach { genre -> url.addQueryParameter("genders[]", genre.id) } } is FilterBy -> { url.addQueryParameter("search[searchBy]", filter.toUriPart()) } is SortBy -> { if (filter.state != null) { url.addQueryParameter("order", SORTABLES[filter.state!!.index].second) url.addQueryParameter( "order-dir", if (filter.state!!.ascending) { "asc" } else { "desc" } ) } } } } return GET(url.build().toString(), headers) } override fun searchMangaSelector() = popularMangaSelector() override fun searchMangaFromElement(element: Element) = popularMangaFromElement(element) override fun searchMangaNextPageSelector() = popularMangaNextPageSelector() private fun searchMangaByIdRequest(id: String) = GET("$baseUrl/$PREFIX_CONTENTS/$id", headers) override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> { return if (query.startsWith(PREFIX_ID_SEARCH)) { val realQuery = query.removePrefix(PREFIX_ID_SEARCH) client.newCall(searchMangaByIdRequest(realQuery)) .asObservableSuccess() .map { response -> val details = mangaDetailsParse(response) details.url = "/$PREFIX_CONTENTS/$realQuery" MangasPage(listOf(details), false) } } else { client.newCall(searchMangaRequest(page, query, filters)) .asObservableSuccess() .map { response -> searchMangaParse(response) } } } private class Genre(name: String, val id: String) : Filter.CheckBox(name) private class GenreList(genres: List<Genre>) : Filter.Group<Genre>("Géneros", genres) override fun getFilterList() = FilterList( Types(), Filter.Separator(), FilterBy(), SortBy(), Filter.Separator(), GenreList(getGenreList()) ) private open class UriPartFilter(displayName: String, val vals: Array<Pair<String, String>>) : Filter.Select<String>(displayName, vals.map { it.first }.toTypedArray()) { fun toUriPart() = vals[state].second } private class Types : UriPartFilter( "Filtrar por tipo", arrayOf( Pair("Ver todos", "all"), Pair("Manga", "hentai"), Pair("Light Hentai", "light-hentai"), Pair("Doujinshi", "doujinshi"), Pair("One-shot", "one-shot"), Pair("Other", "otro") ) ) private class FilterBy : UriPartFilter( "Campo de orden", arrayOf( Pair("Nombre", "name"), Pair("Artista", "artist"), Pair("Revista", "magazine"), Pair("Tag", "tag") ) ) class SortBy : Filter.Sort( "Ordenar por", SORTABLES.map { it.first }.toTypedArray(), Selection(2, false) ) /** * Last check: 17/02/2021 * https://tmohentai.com/section/hentai * * Array.from(document.querySelectorAll('#advancedSearch .list-group .list-group-item')) * .map(a => `Genre("${a.querySelector('span').innerText.replace(' ', '')}", "${a.querySelector('input').value}")`).join(',\n') */ private fun getGenreList() = listOf( Genre("Romance", "1"), Genre("Fantasy", "2"), Genre("Comedy", "3"), Genre("Parody", "4"), Genre("Student", "5"), Genre("Adventure", "6"), Genre("Milf", "7"), Genre("Orgy", "8"), Genre("Big Breasts", "9"), Genre("Bondage", "10"), Genre("Tentacles", "11"), Genre("Incest", "12"), Genre("Ahegao", "13"), Genre("Bestiality", "14"), Genre("Futanari", "15"), Genre("Rape", "16"), Genre("Monsters", "17"), Genre("Pregnant", "18"), Genre("Small Breast", "19"), Genre("Bukkake", "20"), Genre("Femdom", "21"), Genre("Fetish", "22"), Genre("Forced", "23"), Genre("3D", "24"), Genre("Furry", "25"), Genre("Adultery", "26"), Genre("Anal", "27"), Genre("FootJob", "28"), Genre("BlowJob", "29"), Genre("Toys", "30"), Genre("Vanilla", "31"), Genre("Colour", "32"), Genre("Uncensored", "33"), Genre("Netorare", "34"), Genre("Virgin", "35"), Genre("Cheating", "36"), Genre("Harem", "37"), Genre("Horror", "38"), Genre("Lolicon", "39"), Genre("Mature", "40"), Genre("Nympho", "41"), Genre("Public Sex", "42"), Genre("Sport", "43"), Genre("Domination", "44"), Genre("Tsundere", "45"), Genre("Yandere", "46") ) override fun setupPreferenceScreen(screen: androidx.preference.PreferenceScreen) { val pageMethodPref = androidx.preference.ListPreference(screen.context).apply { key = PAGE_METHOD_PREF title = PAGE_METHOD_PREF_TITLE entries = arrayOf("Cascada", "Páginado") entryValues = arrayOf("cascade", "paginated") summary = PAGE_METHOD_PREF_SUMMARY setDefaultValue(PAGE_METHOD_PREF_DEFAULT_VALUE) setOnPreferenceChangeListener { _, newValue -> try { val setting = preferences.edit().putString(PAGE_METHOD_PREF, newValue as String).commit() setting } catch (e: Exception) { e.printStackTrace() false } } } screen.addPreference(pageMethodPref) } private fun getPageMethodPref() = preferences.getString(PAGE_METHOD_PREF, PAGE_METHOD_PREF_DEFAULT_VALUE) companion object { private const val PAGE_METHOD_PREF = "pageMethodPref" private const val PAGE_METHOD_PREF_TITLE = "Método de descarga de imágenes" private const val PAGE_METHOD_PREF_SUMMARY = "Puede corregir errores al cargar las imágenes.\nConfiguración actual: %s" private const val PAGE_METHOD_PREF_CASCADE = "cascade" private const val PAGE_METHOD_PREF_PAGINATED = "paginated" private const val PAGE_METHOD_PREF_DEFAULT_VALUE = PAGE_METHOD_PREF_CASCADE const val PREFIX_CONTENTS = "contents" const val PREFIX_ID_SEARCH = "id:" private val SORTABLES = listOf( Pair("Alfabético", "alphabetic"), Pair("Creación", "publication_date"), Pair("Popularidad", "popularity") ) } }
apache-2.0
de9a9ad10dd89c0209d0e9566a8941b1
37.154079
197
0.59981
4.483138
false
false
false
false
develar/mapsforge-tile-server
pixi/src/PixiSymbol.kt
1
1893
package org.develar.mapsforgeTileServer.pixi import org.mapsforge.core.graphics.Bitmap import org.mapsforge.map.model.DisplayModel import org.mapsforge.map.rendertheme.renderinstruction.Symbol import org.xmlpull.v1.XmlPullParser import java.io.OutputStream class PixiSymbol(displayModel:DisplayModel, elementName:String, pullParser:XmlPullParser, relativePathPrefix:String, textureAtlasInfo:TextureAtlasInfo) : Symbol(null, displayModel, elementName, pullParser), Bitmap { val index:Int init { val subPath = src!!.substring("file:".length() + 1) // relativePathPrefix = dist/renderThemes/Elevate => Elevate as renderer theme file parent directory name var slahIndex = subPath.indexOf('/') if (slahIndex == -1) { slahIndex = subPath.indexOf('\\') } index = textureAtlasInfo.getIndex(subPath.substring(slahIndex + 1, subPath.lastIndexOf('.'))) assert(index > -1) // release memory src = null if (width == 0f || height == 0f) { val region = textureAtlasInfo.getRegion(index) if (width == 0f) { width = region.width.toFloat() } if (height == 0f) { height = region.height.toFloat() } } } override fun getBitmap():Bitmap { return this } override fun compress(outputStream:OutputStream?):Unit = throw IllegalStateException() override fun incrementRefCount() { } override fun decrementRefCount() { } override fun getHeight():Int = height.toInt() override fun getWidth():Int = width.toInt() override fun scaleTo(width:Int, height:Int):Unit = throw IllegalStateException() override fun setBackgroundColor(color:Int):Unit = throw IllegalStateException() override fun hashCode():Int = index.hashCode() override fun equals(other:Any?):Boolean = other is PixiSymbol && other.index == index }
mit
be1f9e3e3ae5de3b744cc9d3ef7cd027
29.047619
115
0.683043
4.234899
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/utils/DateDeserializer.kt
1
2609
package com.habitrpg.android.habitica.utils import android.os.Build import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonPrimitive import com.google.gson.JsonSerializationContext import com.google.gson.JsonSerializer import java.lang.reflect.Type import java.text.DateFormat import java.text.ParseException import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import java.util.TimeZone class DateDeserializer : JsonDeserializer<Date>, JsonSerializer<Date> { private var dateFormats = mutableListOf<DateFormat>() init { addFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") addFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") addFormat("E MMM dd yyyy HH:mm:ss zzzz") addFormat("yyyy-MM-dd'T'HH:mm:sszzz") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { addFormat("yyyy-MM-dd'T'HH:mmX") } else { addFormat("yyyy-MM-dd'T'HH:mm") } addFormat("yyyy-MM-dd") } private fun addFormat(s: String) { val dateFormat = SimpleDateFormat(s, Locale.US) dateFormat.timeZone = TimeZone.getTimeZone("UTC") dateFormats.add(dateFormat) } @Synchronized @Suppress("ReturnCount") override fun deserialize( jsonElement: JsonElement, type: Type, jsonDeserializationContext: JsonDeserializationContext ): Date? { var element = jsonElement if (element.isJsonArray) { if (element.asJsonArray.size() == 0) { return null } element = element.asJsonArray.get(0) } if (element.asString.isEmpty()) { return null } val jsonString = element.asString var date: Date? = null var index = 0 while (index < dateFormats.size && date == null) { try { date = dateFormats[index].parse(jsonString) } catch (_: ParseException) {} index += 1 } if (date == null) { date = try { Date(element.asLong) } catch (e3: NumberFormatException) { null } } return date } override fun serialize(src: Date?, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { return if (src == null) { JsonPrimitive("") } else JsonPrimitive(this.dateFormats[0].format(src)) } }
gpl-3.0
7987dc278ffd557af2d74651ca791b89
29.817073
105
0.592181
4.370184
false
false
false
false
Cognifide/APM
app/aem/core/src/main/kotlin/com/cognifide/apm/core/grammar/utils/ImportScript.kt
1
3877
/* * ========================LICENSE_START================================= * AEM Permission Management * %% * Copyright (C) 2013 Wunderman Thompson Technology * %% * 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. * =========================LICENSE_END================================== */ package com.cognifide.apm.core.grammar.utils import com.cognifide.apm.core.grammar.ScriptExecutionException import com.cognifide.apm.core.grammar.argument.ArgumentResolver import com.cognifide.apm.core.grammar.argument.toPlainString import com.cognifide.apm.core.grammar.executioncontext.ExecutionContext import com.cognifide.apm.core.grammar.executioncontext.VariableHolder import com.cognifide.apm.core.grammar.parsedscript.ParsedScript class ImportScript(private val executionContext: ExecutionContext) { private val visitedScripts: MutableSet<ParsedScript> = mutableSetOf() fun import(ctx: com.cognifide.apm.core.grammar.antlr.ApmLangParser.ImportScriptContext): Result { val path = getPath(ctx) val importScriptVisitor = ImportScriptVisitor() importScriptVisitor.visit(ctx) return Result(path, importScriptVisitor.variableHolder) } private fun getNamespace(ctx: com.cognifide.apm.core.grammar.antlr.ApmLangParser.ImportScriptContext): String = if (ctx.name() != null) { ctx.name().IDENTIFIER().toPlainString() + "_" } else { "" } private fun getPath(ctx: com.cognifide.apm.core.grammar.antlr.ApmLangParser.ImportScriptContext) = ctx.path().STRING_LITERAL().toPlainString() private inner class ImportScriptVisitor : com.cognifide.apm.core.grammar.antlr.ApmLangBaseVisitor<Unit>() { val variableHolder = VariableHolder() val argumentResolver = ArgumentResolver(variableHolder) override fun visitDefineVariable(ctx: com.cognifide.apm.core.grammar.antlr.ApmLangParser.DefineVariableContext) { val variableName = ctx.IDENTIFIER().toString() val variableValue = argumentResolver.resolve(ctx.argument()) variableHolder[variableName] = variableValue } override fun visitImportScript(ctx: com.cognifide.apm.core.grammar.antlr.ApmLangParser.ImportScriptContext) { val path = getPath(ctx) val namespace = getNamespace(ctx) val importScriptVisitor = ImportScriptVisitor() val parsedScript = executionContext.loadScript(path) if (parsedScript !in visitedScripts) visitedScripts.add(parsedScript) else throw ScriptExecutionException("Found cyclic reference to ${parsedScript.path}") importScriptVisitor.visit(parsedScript.apm) val scriptVariableHolder = importScriptVisitor.variableHolder scriptVariableHolder.toMap().forEach { (name, value) -> variableHolder[namespace + name] = value } } } class Result(val path: String, val variableHolder: VariableHolder) { fun toMessages(): List<String> { val importedVariables = variableHolder.toMap().map { "Imported variable: ${it.key}= ${it.value}" } return listOf("Import from script $path. Notice, only DEFINE actions were processed!") + importedVariables } } }
apache-2.0
6620ff2bc7bef9f1b35c91838358f6d6
44.73494
121
0.676554
4.87673
false
false
false
false
walleth/walleth
app/src/main/java/org/walleth/preferences/WalletPrefsFragment.kt
1
2271
package org.walleth.preferences import android.content.SharedPreferences import android.os.Bundle import androidx.lifecycle.lifecycleScope import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.SeekBarPreference import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.koin.android.ext.android.inject import org.walleth.App import org.walleth.R import org.walleth.data.config.Settings import org.walleth.data.tokens.CurrentTokenProvider import timber.log.Timber class WalletPrefsFragment : PreferenceFragmentCompat(), SharedPreferences.OnSharedPreferenceChangeListener { private val settings: Settings by inject() private val currentTokenProvider: CurrentTokenProvider by inject() override fun onResume() { super.onResume() preferenceScreen.sharedPreferences.registerOnSharedPreferenceChangeListener(this) findPreference<Preference>(getString(R.string.key_reference))?.summary = getString(R.string.settings_currently, settings.currentFiat) lifecycleScope.launch(Dispatchers.Main) { findPreference<Preference>(getString(R.string.key_token))?.summary = getString(R.string.settings_currently, currentTokenProvider.getCurrent().name) } } override fun onPause() { super.onPause() preferenceScreen.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { try { if (key == getString(R.string.key_prefs_day_night)) { App.applyNightMode(settings) activity?.recreate() } if (key == getString(R.string.key_noscreenshots)) { activity?.recreate() } if (key == getString(R.string.key_prefs_start_light)) { } } catch (ignored: IllegalStateException) { } } override fun onCreatePreferences(bundle: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.preferences, rootKey) App.extraPreferences.forEach { addPreferencesFromResource(it.first) it.second(preferenceScreen) } } }
gpl-3.0
d82398033858b710199dc3a8a13c84df
33.953846
159
0.716865
5.184932
false
false
false
false
apollostack/apollo-android
apollo-graphql-ast/src/main/kotlin/com/apollographql/apollo3/graphql/ast/gqlfield.kt
1
1710
package com.apollographql.apollo3.graphql.ast private val typenameMetaFieldDefinition = GQLFieldDefinition( name = "__typename", type = GQLNonNullType(type = GQLNamedType(name = "String")), directives = emptyList(), arguments = emptyList(), description = "" ) private val schemaMetaFieldDefinition = GQLFieldDefinition( name = "__schema", type = GQLNonNullType(type = GQLNamedType(name = "__Schema")), directives = emptyList(), arguments = emptyList(), description = "" ) private val typeMetaFieldDefinition = GQLFieldDefinition( name = "__type", type = GQLNonNullType(type = GQLNamedType(name = "__Type")), directives = emptyList(), arguments = listOf( GQLInputValueDefinition( name = "name", type = GQLNonNullType(type = GQLNamedType(name = "String")), defaultValue = null, description = null, directives = emptyList() ) ), description = "" ) fun GQLField.definitionFromScope(schema: Schema, typeDefinitionInScope: GQLTypeDefinition): GQLFieldDefinition? { return when { name == "__typename" -> listOf(typenameMetaFieldDefinition) name == "__schema" && typeDefinitionInScope.name == schema.queryTypeDefinition.name -> listOf(schemaMetaFieldDefinition) name == "__type" && typeDefinitionInScope.name == schema.queryTypeDefinition.name -> listOf(typeMetaFieldDefinition) typeDefinitionInScope is GQLObjectTypeDefinition -> typeDefinitionInScope.fields typeDefinitionInScope is GQLInterfaceTypeDefinition -> typeDefinitionInScope.fields else -> emptyList() }.firstOrNull { it.name == name } } fun GQLField.responseName() = alias ?: name
mit
781f8fbb7ea96e0817cdf6a87f436524
35.382979
124
0.689474
4.956522
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/browse/extension/details/SourcePreferencesController.kt
1
6961
package eu.kanade.tachiyomi.ui.browse.extension.details import android.annotation.SuppressLint import android.content.Context import android.os.Bundle import android.util.TypedValue import android.view.LayoutInflater import android.view.View import androidx.appcompat.view.ContextThemeWrapper import androidx.core.os.bundleOf import androidx.preference.DialogPreference import androidx.preference.EditTextPreference import androidx.preference.EditTextPreferenceDialogController import androidx.preference.ListPreference import androidx.preference.ListPreferenceDialogController import androidx.preference.MultiSelectListPreference import androidx.preference.MultiSelectListPreferenceDialogController import androidx.preference.Preference import androidx.preference.PreferenceGroupAdapter import androidx.preference.PreferenceManager import androidx.preference.PreferenceScreen import androidx.preference.get import androidx.preference.getOnBindEditTextListener import androidx.preference.isNotEmpty import androidx.recyclerview.widget.LinearLayoutManager import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.SharedPreferencesDataStore import eu.kanade.tachiyomi.databinding.SourcePreferencesControllerBinding import eu.kanade.tachiyomi.source.ConfigurableSource import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.source.getPreferenceKey import eu.kanade.tachiyomi.ui.base.controller.NucleusController import eu.kanade.tachiyomi.util.system.logcat import eu.kanade.tachiyomi.widget.TachiyomiTextInputEditText.Companion.setIncognito import logcat.LogPriority @SuppressLint("RestrictedApi") class SourcePreferencesController(bundle: Bundle? = null) : NucleusController<SourcePreferencesControllerBinding, SourcePreferencesPresenter>(bundle), PreferenceManager.OnDisplayPreferenceDialogListener, DialogPreference.TargetFragment { private var lastOpenPreferencePosition: Int? = null private var preferenceScreen: PreferenceScreen? = null constructor(sourceId: Long) : this( bundleOf(SOURCE_ID to sourceId), ) override fun createBinding(inflater: LayoutInflater): SourcePreferencesControllerBinding { val themedInflater = inflater.cloneInContext(getPreferenceThemeContext()) return SourcePreferencesControllerBinding.inflate(themedInflater) } override fun createPresenter(): SourcePreferencesPresenter { return SourcePreferencesPresenter(args.getLong(SOURCE_ID)) } override fun getTitle(): String? { return presenter.source?.toString() } @SuppressLint("PrivateResource") override fun onViewCreated(view: View) { super.onViewCreated(view) val source = presenter.source ?: return val context = view.context val themedContext by lazy { getPreferenceThemeContext() } val manager = PreferenceManager(themedContext) val dataStore = SharedPreferencesDataStore( context.getSharedPreferences(source.getPreferenceKey(), Context.MODE_PRIVATE), ) manager.preferenceDataStore = dataStore manager.onDisplayPreferenceDialogListener = this val screen = manager.createPreferenceScreen(themedContext) preferenceScreen = screen try { addPreferencesForSource(screen, source) } catch (e: AbstractMethodError) { logcat(LogPriority.ERROR) { "Source did not implement [addPreferencesForSource]: ${source.name}" } } manager.setPreferences(screen) binding.recycler.layoutManager = LinearLayoutManager(context) binding.recycler.adapter = PreferenceGroupAdapter(screen) } override fun onDestroyView(view: View) { preferenceScreen = null super.onDestroyView(view) } override fun onSaveInstanceState(outState: Bundle) { lastOpenPreferencePosition?.let { outState.putInt(LASTOPENPREFERENCE_KEY, it) } super.onSaveInstanceState(outState) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) lastOpenPreferencePosition = savedInstanceState.get(LASTOPENPREFERENCE_KEY) as? Int } private fun addPreferencesForSource(screen: PreferenceScreen, source: Source) { val context = screen.context if (source is ConfigurableSource) { val newScreen = screen.preferenceManager.createPreferenceScreen(context) source.setupPreferenceScreen(newScreen) // Reparent the preferences while (newScreen.isNotEmpty()) { val pref = newScreen[0] pref.isIconSpaceReserved = false pref.order = Int.MAX_VALUE // reset to default order // Apply incognito IME for EditTextPreference if (pref is EditTextPreference) { val setListener = pref.getOnBindEditTextListener() pref.setOnBindEditTextListener { setListener?.onBindEditText(it) it.setIncognito(viewScope) } } newScreen.removePreference(pref) screen.addPreference(pref) } } } private fun getPreferenceThemeContext(): Context { val tv = TypedValue() activity!!.theme.resolveAttribute(R.attr.preferenceTheme, tv, true) return ContextThemeWrapper(activity, tv.resourceId) } override fun onDisplayPreferenceDialog(preference: Preference) { if (!isAttached) return val screen = preference.parent!! lastOpenPreferencePosition = (0 until screen.preferenceCount).indexOfFirst { screen[it] === preference } val f = when (preference) { is EditTextPreference -> EditTextPreferenceDialogController .newInstance(preference.getKey()) is ListPreference -> ListPreferenceDialogController .newInstance(preference.getKey()) is MultiSelectListPreference -> MultiSelectListPreferenceDialogController .newInstance(preference.getKey()) else -> throw IllegalArgumentException( "Tried to display dialog for unknown " + "preference type. Did you forget to override onDisplayPreferenceDialog()?", ) } f.targetController = this f.showDialog(router) } @Suppress("UNCHECKED_CAST") override fun <T : Preference> findPreference(key: CharSequence): T? { // We track [lastOpenPreferencePosition] when displaying the dialog // [key] isn't useful since there may be duplicates return preferenceScreen!![lastOpenPreferencePosition!!] as T } } private const val SOURCE_ID = "source_id" private const val LASTOPENPREFERENCE_KEY = "last_open_preference"
apache-2.0
d4ac06c2a3b4774d1b0f42f51b7ae8c5
37.888268
110
0.712829
5.668567
false
false
false
false
da1z/intellij-community
java/java-impl/src/com/intellij/lang/java/actions/jvmPsiUtil.kt
1
3121
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.lang.java.actions import com.intellij.codeInsight.ExpectedTypeInfo import com.intellij.codeInsight.ExpectedTypesProvider import com.intellij.codeInsight.TailType import com.intellij.lang.java.JavaLanguage import com.intellij.lang.java.request.ExpectedJavaType import com.intellij.lang.jvm.JvmClass import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.actions.ExpectedType import com.intellij.lang.jvm.actions.ExpectedTypes import com.intellij.lang.jvm.types.JvmSubstitutor import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.psi.PsiModifier.ModifierConstant import com.intellij.psi.impl.compiled.ClsClassImpl @ModifierConstant internal fun JvmModifier.toPsiModifier(): String = when (this) { JvmModifier.PUBLIC -> PsiModifier.PUBLIC JvmModifier.PROTECTED -> PsiModifier.PROTECTED JvmModifier.PRIVATE -> PsiModifier.PRIVATE JvmModifier.PACKAGE_LOCAL -> PsiModifier.PACKAGE_LOCAL JvmModifier.STATIC -> PsiModifier.STATIC JvmModifier.ABSTRACT -> PsiModifier.ABSTRACT JvmModifier.FINAL -> PsiModifier.FINAL JvmModifier.NATIVE -> PsiModifier.NATIVE JvmModifier.SYNCHRONIZED -> PsiModifier.NATIVE JvmModifier.STRICTFP -> PsiModifier.STRICTFP JvmModifier.TRANSIENT -> PsiModifier.TRANSIENT JvmModifier.VOLATILE -> PsiModifier.VOLATILE JvmModifier.TRANSITIVE -> PsiModifier.TRANSITIVE } /** * Compiled classes, type parameters are not considered classes. * * @return Java PsiClass or `null` if the receiver is not a Java PsiClass */ internal fun JvmClass.toJavaClassOrNull(): PsiClass? { if (this !is PsiClass) return null if (this is PsiTypeParameter) return null if (this is ClsClassImpl) return null if (this.language != JavaLanguage.INSTANCE) return null return this } internal val visibilityModifiers = setOf( JvmModifier.PUBLIC, JvmModifier.PROTECTED, JvmModifier.PACKAGE_LOCAL, JvmModifier.PRIVATE ) internal fun extractExpectedTypes(project: Project, expectedTypes: ExpectedTypes): List<ExpectedTypeInfo> { return expectedTypes.mapNotNull { toExpectedTypeInfo(project, it) } } private fun toExpectedTypeInfo(project: Project, expectedType: ExpectedType): ExpectedTypeInfo? { if (expectedType is ExpectedJavaType) return expectedType.info val helper = JvmPsiConversionHelper.getInstance(project) val psiType = helper.convertType(expectedType.theType) ?: return null return ExpectedTypesProvider.createInfo(psiType, expectedType.theKind.infoKind(), psiType, TailType.NONE) } @ExpectedTypeInfo.Type private fun ExpectedType.Kind.infoKind(): Int { return when (this) { ExpectedType.Kind.EXACT -> ExpectedTypeInfo.TYPE_STRICTLY ExpectedType.Kind.SUPERTYPE -> ExpectedTypeInfo.TYPE_OR_SUPERTYPE ExpectedType.Kind.SUBTYPE -> ExpectedTypeInfo.TYPE_OR_SUBTYPE } } internal fun JvmSubstitutor.toPsiSubstitutor(project: Project): PsiSubstitutor { return JvmPsiConversionHelper.getInstance(project).convertSubstitutor(this) }
apache-2.0
43e42762b245d8b57a643d180ba81b53
38.0125
140
0.803909
4.549563
false
false
false
false
wesamhaboush/kotlin-algorithms
src/main/kotlin/algorithms/goldbachs-other-conjecture.kt
1
1001
package algorithms /* Goldbach's other conjecture Problem 46 It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2×1^2 15 = 7 + 2×2^2 21 = 3 + 2×3^2 25 = 7 + 2×3^2 27 = 19 + 2×2^2 33 = 31 + 2×1^2 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? */ fun compositeOdds(): Sequence<Long> = generateSequence(3L) { it + 2 } .filter { !isPrime(it) } fun twiceSquares(): Sequence<Long> = generateSequence(1L) { it + 1 } .map { 2 * it * it } fun canBeComposedOfPrimePlusTwiceSquare(number: Long): Boolean = twiceSquares() .takeWhile { it < number } .any { isPrime(number - it) } fun firstOddCompositeBreakingGoldbachsOtherConjecture() = compositeOdds() .find { !canBeComposedOfPrimePlusTwiceSquare(it) }
gpl-3.0
147526734611321caab021295c06b070
25.891892
99
0.634171
3.466899
false
false
false
false
sjnyag/stamp
app/src/main/java/com/sjn/stamp/MusicService.kt
1
7770
package com.sjn.stamp import android.app.Service import android.content.Intent import android.os.Bundle import android.os.RemoteException import android.support.v4.media.MediaBrowserCompat import android.support.v4.media.MediaBrowserCompat.MediaItem import android.support.v4.media.MediaBrowserServiceCompat import android.support.v4.media.session.MediaControllerCompat import com.sjn.stamp.media.notification.NotificationManager import com.sjn.stamp.media.playback.Playback import com.sjn.stamp.media.playback.PlaybackManager import com.sjn.stamp.media.provider.MusicProvider import com.sjn.stamp.media.source.LocalMediaSource import com.sjn.stamp.ui.observer.MediaControllerObserver import com.sjn.stamp.utils.* import java.util.* class MusicService : MediaBrowserServiceCompat(), PlaybackManager.PlaybackServiceCallback { companion object { private val TAG = LogHelper.makeLogTag(MusicService::class.java) const val NOTIFICATION_CMD_PLAY = "CMD_PLAY" const val NOTIFICATION_CMD_PAUSE = "CMD_PAUSE" const val NOTIFICATION_CMD_STOP_CASTING = "CMD_STOP_CASTING" const val NOTIFICATION_CMD_KILL = "CMD_KILL" const val CUSTOM_ACTION_RELOAD_MUSIC_PROVIDER = "RELOAD_MUSIC_PROVIDER" const val CUSTOM_ACTION_SET_QUEUE = "SET_QUEUE" const val CUSTOM_ACTION_SET_QUEUE_BUNDLE_KEY_TITLE = "SET_QUEUE_BUNDLE_KEY_TITLE" const val CUSTOM_ACTION_SET_QUEUE_BUNDLE_MEDIA_ID = "SET_QUEUE_BUNDLE_MEDIA_ID" const val CUSTOM_ACTION_SET_QUEUE_BUNDLE_KEY_QUEUE = "SET_QUEUE_BUNDLE_KEY_QUEUE" } private var playOnPrepared = false private var playbackManager: PlaybackManager? = null private var mediaController: MediaControllerCompat? = null private val notificationManager = NotificationManager(this) private val musicProvider = MusicProvider(this, LocalMediaSource(this, object : MediaRetrieveHelper.PermissionRequiredCallback { override fun onPermissionRequired() { } })) override fun onCreate() { super.onCreate() LogHelper.d(TAG, "onCreate") musicProvider.retrieveMediaAsync(object : MusicProvider.Callback { override fun onMusicCatalogReady(success: Boolean) { LogHelper.d(TAG, "MusicProvider.callBack start") playbackManager = PlaybackManager(this@MusicService, this@MusicService, musicProvider, Playback.Type.LOCAL).apply { restorePreviousState() } sessionToken = playbackManager?.sessionToken sessionToken?.let { mediaController = MediaControllerCompat(this@MusicService, it).apply { MediaControllerObserver.register(this) } } PlayModeHelper.restore(this@MusicService) try { notificationManager.updateSessionToken() } catch (e: RemoteException) { throw IllegalStateException("Could not create a NotificationManager", e) } if (playOnPrepared) { playOnPrepared = false mediaController?.transportControls?.play() } LogHelper.d(TAG, "MusicProvider.callBack end") } }) } override fun onDestroy() { LogHelper.d(TAG, "onDestroy") mediaController?.let { it.transportControls.stop() MediaControllerObserver.unregister(it) } notificationManager.stopNotification() } override fun onStartCommand(startIntent: Intent?, flags: Int, startId: Int): Int { LogHelper.d(TAG, "onStartCommand") startIntent?.let { if (NotificationHelper.ACTION_CMD == it.action) { handleActionCommand(it.getStringExtra(NotificationHelper.CMD_NAME)) } else { playbackManager?.handleIntent(it) } } return Service.START_NOT_STICKY } /** * [MediaBrowserServiceCompat] */ override fun onCustomAction(action: String, extras: Bundle?, result: MediaBrowserServiceCompat.Result<Bundle>) { LogHelper.d(TAG, "onCustomAction $action") when (action) { CUSTOM_ACTION_RELOAD_MUSIC_PROVIDER -> { result.detach() musicProvider.cacheAndNotifyLatestMusicMap() return } CUSTOM_ACTION_SET_QUEUE -> { result.detach() extras?.let { playbackManager?.startNewQueue( extras.getString(CUSTOM_ACTION_SET_QUEUE_BUNDLE_KEY_TITLE), extras.getString(CUSTOM_ACTION_SET_QUEUE_BUNDLE_MEDIA_ID), extras.getParcelableArrayList(CUSTOM_ACTION_SET_QUEUE_BUNDLE_KEY_QUEUE)) } return } } result.sendError(null) } override fun onSearch(query: String, extras: Bundle?, result: MediaBrowserServiceCompat.Result<List<MediaBrowserCompat.MediaItem>>) { LogHelper.d(TAG, "onSearch $query") result.detach() if (musicProvider.isInitialized) { Thread(Runnable { result.sendResult(musicProvider.getChildren(query, resources)) }).start() } } override fun onGetRoot(clientPackageName: String, clientUid: Int, rootHints: Bundle?): MediaBrowserServiceCompat.BrowserRoot? { LogHelper.d(TAG, "OnGetRoot: clientPackageName=$clientPackageName", "; clientUid=$clientUid ; rootHints=", rootHints) return MediaBrowserServiceCompat.BrowserRoot(MediaIDHelper.MEDIA_ID_ROOT, null) } override fun onLoadChildren(parentMediaId: String, result: MediaBrowserServiceCompat.Result<List<MediaItem>>) { LogHelper.d(TAG, "OnLoadChildren: parentMediaId=", parentMediaId) if (MediaIDHelper.MEDIA_ID_EMPTY_ROOT == parentMediaId) { result.sendResult(ArrayList()) } else { result.detach() if (musicProvider.isInitialized) { Thread(Runnable { result.sendResult(musicProvider.getChildren(parentMediaId, resources)) }).start() } } } /** * [PlaybackManager.PlaybackServiceCallback] */ override fun onPlaybackStart() { LogHelper.d(TAG, "onPlaybackStart") // The service needs to continue running even after the bound client (usually a // MediaController) disconnects, otherwise the music playback will stop. // Calling startService(Intent) will keep the service running until it is explicitly killed. startForegroundServiceCompatible(Intent(applicationContext, MusicService::class.java)) notificationManager.startForeground() } override fun onPlaybackStop() { LogHelper.d(TAG, "onPlaybackStop") notificationManager.stopForeground(false) } override fun onNotificationRequired() { LogHelper.d(TAG, "onNotificationRequired") notificationManager.startNotification() } private fun handleActionCommand(command: String) { LogHelper.d(TAG, "handleActionCommand ", command) when (command) { NOTIFICATION_CMD_PLAY -> mediaController?.transportControls?.play() ?: run { playOnPrepared = true } NOTIFICATION_CMD_PAUSE -> mediaController?.transportControls?.pause() NOTIFICATION_CMD_STOP_CASTING -> playbackManager?.stopCasting() NOTIFICATION_CMD_KILL -> playbackManager?.let { stopSelf() } } } }
apache-2.0
2267ca0842799db44ef1b4fe504cdb18
41
131
0.637194
5.085079
false
false
false
false
k9mail/k-9
app/ui/legacy/src/main/java/com/fsck/k9/contacts/ContactLetterBitmapConfig.kt
1
914
package com.fsck.k9.contacts import android.content.Context import android.util.TypedValue import android.view.ContextThemeWrapper import com.fsck.k9.K9 import com.fsck.k9.ui.R import com.fsck.k9.ui.base.Theme import com.fsck.k9.ui.base.ThemeManager class ContactLetterBitmapConfig(context: Context, themeManager: ThemeManager) { val hasDefaultBackgroundColor: Boolean = !K9.isColorizeMissingContactPictures val useDarkTheme = themeManager.appTheme == Theme.DARK val defaultBackgroundColor: Int init { defaultBackgroundColor = if (hasDefaultBackgroundColor) { val outValue = TypedValue() val themedContext = ContextThemeWrapper(context, themeManager.appThemeResourceId) themedContext.theme.resolveAttribute(R.attr.contactPictureFallbackDefaultBackgroundColor, outValue, true) outValue.data } else { 0 } } }
apache-2.0
2bf506149b5b513971031056e1f71560
34.153846
117
0.738512
4.524752
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/caches/project/multiplatformUtil.kt
3
6357
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.caches.project import com.intellij.openapi.module.Module import com.intellij.psi.PsiElement import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.config.KotlinSourceRootType import org.jetbrains.kotlin.config.SourceKotlinRootType import org.jetbrains.kotlin.config.TestSourceKotlinRootType import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.idea.base.facet.implementingModules import org.jetbrains.kotlin.idea.base.facet.isMultiPlatformModule import org.jetbrains.kotlin.idea.base.facet.isNewMultiPlatformModule import org.jetbrains.kotlin.idea.base.facet.kotlinSourceRootType import org.jetbrains.kotlin.idea.base.projectStructure.kotlinSourceRootType import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.PlatformModuleInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfoOrNull import org.jetbrains.kotlin.idea.base.projectStructure.productionSourceInfo import org.jetbrains.kotlin.idea.base.projectStructure.testSourceInfo import org.jetbrains.kotlin.idea.base.facet.implementingModules as implementingModulesNew import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.types.typeUtil.closure @Deprecated( "Use 'org.jetbrains.kotlin.idea.base.facet.isNewMultiPlatformModule' instead.", ReplaceWith("this.isNewMultiPlatformModule", imports = ["org.jetbrains.kotlin.idea.base.facet"]), level = DeprecationLevel.ERROR ) @Suppress("unused") val Module.isNewMPPModule: Boolean get() = isNewMultiPlatformModule @Deprecated( "Use 'org.jetbrains.kotlin.idea.base.facet.kotlinSourceRootType' instead.", ReplaceWith("sourceType", imports = ["org.jetbrains.kotlin.idea.base.facet"]), level = DeprecationLevel.ERROR ) @Suppress("unused") val Module.sourceType: SourceType? get() = when (kotlinSourceRootType) { TestSourceKotlinRootType -> @Suppress("DEPRECATION") SourceType.TEST SourceKotlinRootType -> @Suppress("DEPRECATION") SourceType.PRODUCTION else -> null } @Deprecated( "Use 'org.jetbrains.kotlin.idea.base.facet.isMultiPlatformModule' instead.", ReplaceWith("isMultiPlatformModule", imports = ["org.jetbrains.kotlin.idea.base.facet"]), level = DeprecationLevel.ERROR ) @Suppress("unused") val Module.isMPPModule: Boolean get() = isMultiPlatformModule @Deprecated( "Use 'org.jetbrains.kotlin.idea.base.facet.implementingModules' instead.", ReplaceWith("implementingModules", imports = ["org.jetbrains.kotlin.idea.base.facet"]), level = DeprecationLevel.ERROR ) @Suppress("unused") val Module.implementingModules: List<Module> get() = implementingModulesNew val ModuleDescriptor.implementingDescriptors: List<ModuleDescriptor> get() { val moduleInfo = getCapability(ModuleInfo.Capability) if (moduleInfo is PlatformModuleInfo) { return listOf(this) } val moduleSourceInfo = moduleInfo as? ModuleSourceInfo ?: return emptyList() val implementingModuleInfos = moduleSourceInfo.module.implementingModules .mapNotNull { module -> val sourceRootType = moduleSourceInfo.kotlinSourceRootType ?: return@mapNotNull null module.getModuleInfo(sourceRootType) } return implementingModuleInfos.mapNotNull { it.toDescriptor() } } val ModuleDescriptor.allImplementingDescriptors: Collection<ModuleDescriptor> get() = implementingDescriptors.closure(preserveOrder = true) { it.implementingDescriptors } fun Module.getModuleInfo(sourceRootType: KotlinSourceRootType): ModuleSourceInfo? { return when (sourceRootType) { SourceKotlinRootType -> productionSourceInfo TestSourceKotlinRootType -> testSourceInfo } } /** * This function returns immediate parents in dependsOn graph */ val ModuleDescriptor.implementedDescriptors: List<ModuleDescriptor> get() { val moduleInfo = getCapability(ModuleInfo.Capability) if (moduleInfo is PlatformModuleInfo) return listOf(this) val moduleSourceInfo = moduleInfo as? ModuleSourceInfo ?: return emptyList() return moduleSourceInfo.expectedBy.mapNotNull { it.toDescriptor() } } fun Module.toDescriptor() = (productionSourceInfo ?: testSourceInfo)?.toDescriptor() fun ModuleSourceInfo.toDescriptor() = KotlinCacheService.getInstance(module.project) .getResolutionFacadeByModuleInfo(this, platform)?.moduleDescriptor fun PsiElement.getPlatformModuleInfo(desiredPlatform: TargetPlatform): PlatformModuleInfo? { assert(!desiredPlatform.isCommon()) { "Platform module cannot have Common platform" } val moduleInfo = this.moduleInfoOrNull as? ModuleSourceInfo ?: return null return doGetPlatformModuleInfo(moduleInfo, desiredPlatform) } fun getPlatformModuleInfo(moduleInfo: ModuleSourceInfo, desiredPlatform: TargetPlatform): PlatformModuleInfo? { assert(!desiredPlatform.isCommon()) { "Platform module cannot have Common platform" } return doGetPlatformModuleInfo(moduleInfo, desiredPlatform) } private fun doGetPlatformModuleInfo(moduleInfo: ModuleSourceInfo, desiredPlatform: TargetPlatform): PlatformModuleInfo? { val platform = moduleInfo.platform return when { platform.isCommon() -> { val correspondingImplementingModule = moduleInfo.module.implementingModules .map { module -> val sourceRootType = moduleInfo.kotlinSourceRootType ?: return@map null module.getModuleInfo(sourceRootType) } .firstOrNull { it?.platform == desiredPlatform } ?: return null PlatformModuleInfo(correspondingImplementingModule, correspondingImplementingModule.expectedBy) } platform == desiredPlatform -> { val expectedBy = moduleInfo.expectedBy.takeIf { it.isNotEmpty() } ?: return null PlatformModuleInfo(moduleInfo, expectedBy) } else -> null } }
apache-2.0
13c41e7a8459c93193397f2d5927efec
43.461538
158
0.762624
5.266777
false
false
false
false
Maccimo/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/intention/impl/preview/IntentionPreviewComputable.kt
2
8694
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInsight.intention.impl.preview import com.intellij.codeInsight.daemon.impl.ShowIntentionsPass import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.IntentionActionDelegate import com.intellij.codeInsight.intention.impl.CachedIntentions import com.intellij.codeInsight.intention.impl.IntentionActionWithTextCaching import com.intellij.codeInsight.intention.impl.ShowIntentionActionsHandler import com.intellij.codeInsight.intention.impl.config.IntentionManagerSettings import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo import com.intellij.codeInspection.ex.QuickFixWrapper import com.intellij.diff.comparison.ComparisonManager import com.intellij.diff.comparison.ComparisonPolicy import com.intellij.diff.fragments.LineFragment import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.plugins.cl.PluginAwareClassLoader import com.intellij.lang.injection.InjectedLanguageManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.progress.DumbProgressIndicator import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiFileFactory import com.intellij.psi.PsiRecursiveElementWalkingVisitor import com.intellij.psi.impl.source.PostprocessReformattingAspect import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtilBase import java.io.IOException import java.util.concurrent.Callable internal class IntentionPreviewComputable(private val project: Project, private val action: IntentionAction, private val originalFile: PsiFile, private val originalEditor: Editor) : Callable<IntentionPreviewInfo> { override fun call(): IntentionPreviewInfo { val diffContent = tryCreateDiffContent() if (diffContent != null) { return diffContent } return tryCreateFallbackDescriptionContent() } private fun tryCreateFallbackDescriptionContent(): IntentionPreviewInfo { val originalAction = IntentionActionDelegate.unwrap(action) val actionMetaData = IntentionManagerSettings.getInstance().getMetaData().singleOrNull { md -> IntentionActionDelegate.unwrap(md.action) === originalAction } ?: return IntentionPreviewInfo.EMPTY return try { IntentionPreviewInfo.Html(actionMetaData.description.text.replace(HTML_COMMENT_REGEX, "")) } catch(ex: IOException) { IntentionPreviewInfo.EMPTY } } private fun tryCreateDiffContent(): IntentionPreviewInfo? { try { return generatePreview() } catch (e: IntentionPreviewUnsupportedOperationException) { return null } catch (e: ProcessCanceledException) { throw e } catch (e: Exception) { logger<IntentionPreviewComputable>().debug("There are exceptions on invocation the intention: '${action.text}' on a copy of the file.", e) return null } } fun generatePreview(): IntentionPreviewInfo? { if (project.isDisposed) return null val origPair = ShowIntentionActionsHandler.chooseFileForAction(originalFile, originalEditor, action) ?: return null val origFile: PsiFile val caretOffset: Int val fileFactory = PsiFileFactory.getInstance(project) if (origPair.first != originalFile) { val manager = InjectedLanguageManager.getInstance(project) origFile = fileFactory.createFileFromText( origPair.first.name, origPair.first.fileType, manager.getUnescapedText(origPair.first)) caretOffset = mapInjectedOffsetToUnescaped(origPair.first, origPair.second.caretModel.offset) } else { origFile = originalFile caretOffset = originalEditor.caretModel.offset } val psiFileCopy = origFile.copy() as PsiFile ProgressManager.checkCanceled() val editorCopy = IntentionPreviewEditor(psiFileCopy, caretOffset, originalEditor.settings) val writable = originalEditor.document.isWritable try { originalEditor.document.setReadOnly(true) ProgressManager.checkCanceled() var result = action.generatePreview(project, editorCopy, psiFileCopy) if (result == IntentionPreviewInfo.FALLBACK_DIFF) { if (action.getElementToMakeWritable(originalFile)?.containingFile !== originalFile) return null // Use fallback algorithm only if invokeForPreview is not explicitly overridden // in this case, the absence of diff could be intended, thus should not be logged as error val action = findCopyIntention(project, editorCopy, psiFileCopy, action) ?: return null val unwrapped = IntentionActionDelegate.unwrap(action) val cls = (if (unwrapped is QuickFixWrapper) unwrapped.fix else unwrapped)::class.java val loader = cls.classLoader val thirdParty = loader is PluginAwareClassLoader && PluginManagerCore.isDevelopedByJetBrains(loader.pluginDescriptor) if (!thirdParty) { logger<IntentionPreviewComputable>().error("Intention preview fallback is used for action ${cls.name}|${action.familyName}") } action.invoke(project, editorCopy, psiFileCopy) result = IntentionPreviewInfo.DIFF } ProgressManager.checkCanceled() return when (result) { IntentionPreviewInfo.DIFF -> { PostprocessReformattingAspect.getInstance(project).doPostponedFormatting(psiFileCopy.viewProvider) IntentionPreviewDiffResult( psiFile = psiFileCopy, origFile = origFile, lineFragments = ComparisonManager.getInstance() .compareLines(origFile.text, editorCopy.document.text, ComparisonPolicy.TRIM_WHITESPACES, DumbProgressIndicator.INSTANCE)) } IntentionPreviewInfo.EMPTY -> null is IntentionPreviewInfo.CustomDiff -> { IntentionPreviewDiffResult( fileFactory.createFileFromText("__dummy__", result.fileType(), result.modifiedText()), fileFactory.createFileFromText("__dummy__", result.fileType(), result.originalText()), ComparisonManager.getInstance() .compareLines(result.originalText(), result.modifiedText(), ComparisonPolicy.TRIM_WHITESPACES, DumbProgressIndicator.INSTANCE), fakeDiff = false) } else -> result } } finally { originalEditor.document.setReadOnly(!writable) } } private fun mapInjectedOffsetToUnescaped(injectedFile: PsiFile, injectedOffset: Int): Int { var unescapedOffset = 0 var escapedOffset = 0 injectedFile.accept(object : PsiRecursiveElementWalkingVisitor() { override fun visitElement(element: PsiElement) { val leafText = InjectedLanguageUtilBase.getUnescapedLeafText(element, false) if (leafText != null) { unescapedOffset += leafText.length escapedOffset += element.textLength if (escapedOffset >= injectedOffset) { unescapedOffset -= escapedOffset - injectedOffset stopWalking() } } super.visitElement(element) } }) return unescapedOffset } } private val HTML_COMMENT_REGEX = Regex("<!--.+-->") private fun getFixes(cachedIntentions: CachedIntentions): Sequence<IntentionActionWithTextCaching> { return sequenceOf<IntentionActionWithTextCaching>() .plus(cachedIntentions.intentions) .plus(cachedIntentions.inspectionFixes) .plus(cachedIntentions.errorFixes) } private fun findCopyIntention(project: Project, editorCopy: Editor, psiFileCopy: PsiFile, originalAction: IntentionAction): IntentionAction? { val actionsToShow = ShowIntentionsPass.getActionsToShow(editorCopy, psiFileCopy, false) val cachedIntentions = CachedIntentions.createAndUpdateActions(project, psiFileCopy, editorCopy, actionsToShow) return getFixes(cachedIntentions).find { it.text == originalAction.text }?.action } internal data class IntentionPreviewDiffResult(val psiFile: PsiFile, val origFile: PsiFile, val lineFragments: List<LineFragment>, val fakeDiff: Boolean = true): IntentionPreviewInfo
apache-2.0
4164eb87a7b4546b5b4cbe2419d69d36
45.994595
144
0.722337
5.569507
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/motion/updown/MotionGotoLineFirstAction.kt
1
2036
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.action.motion.updown import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.normalizeLine import com.maddyhome.idea.vim.command.Argument import com.maddyhome.idea.vim.command.CommandFlags import com.maddyhome.idea.vim.command.MotionType import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.handler.Motion import com.maddyhome.idea.vim.handler.MotionActionHandler import com.maddyhome.idea.vim.handler.toMotion import com.maddyhome.idea.vim.helper.enumSetOf import java.util.* class MotionGotoLineFirstAction : MotionActionHandler.ForEachCaret() { override val motionType: MotionType = MotionType.LINE_WISE override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_SAVE_JUMP) override fun getOffset( editor: VimEditor, caret: VimCaret, context: ExecutionContext, argument: Argument?, operatorArguments: OperatorArguments, ): Motion { val line = editor.normalizeLine(operatorArguments.count1 - 1) return injector.motion.moveCaretToLineWithStartOfLineOption(editor, line, caret).toMotion() } } class MotionGotoLineFirstInsertAction : MotionActionHandler.ForEachCaret() { override val motionType: MotionType = MotionType.EXCLUSIVE override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_CLEAR_STROKES) override fun getOffset( editor: VimEditor, caret: VimCaret, context: ExecutionContext, argument: Argument?, operatorArguments: OperatorArguments, ): Motion { val line = editor.normalizeLine(operatorArguments.count1 - 1) return injector.motion.moveCaretToLineStart(editor, line).toMotion() } }
mit
612939abc2c554508cdab2fe93f79277
34.103448
95
0.786837
4.180698
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/util/quickfixUtil.kt
1
2796
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.util import com.intellij.codeInsight.intention.IntentionAction import com.intellij.psi.PsiElement import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory import org.jetbrains.kotlin.idea.resolve.dataFlowValueFactory import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtPrimaryConstructor import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoAfter import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.utils.ifEmpty inline fun <reified T : PsiElement> Diagnostic.createIntentionForFirstParentOfType( factory: (T) -> KotlinQuickFixAction<T>? ) = psiElement.getNonStrictParentOfType<T>()?.let(factory) fun createIntentionFactory( factory: (Diagnostic) -> IntentionAction? ) = object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic) = factory(diagnostic) } fun KtPrimaryConstructor.addConstructorKeyword(): PsiElement? { val modifierList = this.modifierList ?: return null val psiFactory = KtPsiFactory(this) val constructor = if (valueParameterList == null) { psiFactory.createPrimaryConstructor("constructor()") } else { psiFactory.createConstructorKeyword() } return addAfter(constructor, modifierList) } fun getDataFlowAwareTypes( expression: KtExpression, bindingContext: BindingContext = expression.analyze(), originalType: KotlinType? = bindingContext.getType(expression) ): Collection<KotlinType> { if (originalType == null) return emptyList() val dataFlowInfo = bindingContext.getDataFlowInfoAfter(expression) val dataFlowValueFactory = expression.getResolutionFacade().dataFlowValueFactory val expressionType = bindingContext.getType(expression) ?: return listOf(originalType) val dataFlowValue = dataFlowValueFactory.createDataFlowValue( expression, expressionType, bindingContext, expression.getResolutionFacade().moduleDescriptor ) return dataFlowInfo.getCollectedTypes(dataFlowValue, expression.languageVersionSettings).ifEmpty { listOf(originalType) } }
apache-2.0
e3ddf8ef370c9b757014c41b9e067e86
46.389831
158
0.810801
5.083636
false
false
false
false
WhisperSystems/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/components/settings/app/internal/InternalSettingsFragment.kt
1
14460
package org.thoughtcrime.securesms.components.settings.app.internal import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.DialogInterface import android.widget.Toast import androidx.lifecycle.ViewModelProviders import com.google.android.material.dialog.MaterialAlertDialogBuilder import org.signal.core.util.concurrent.SignalExecutors import org.thoughtcrime.securesms.BuildConfig import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.components.settings.DSLConfiguration import org.thoughtcrime.securesms.components.settings.DSLSettingsAdapter import org.thoughtcrime.securesms.components.settings.DSLSettingsFragment import org.thoughtcrime.securesms.components.settings.DSLSettingsText import org.thoughtcrime.securesms.components.settings.configure import org.thoughtcrime.securesms.database.DatabaseFactory import org.thoughtcrime.securesms.database.LocalMetricsDatabase import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.jobs.RefreshAttributesJob import org.thoughtcrime.securesms.jobs.RefreshOwnProfileJob import org.thoughtcrime.securesms.jobs.RemoteConfigRefreshJob import org.thoughtcrime.securesms.jobs.RotateProfileKeyJob import org.thoughtcrime.securesms.jobs.StorageForcePushJob import org.thoughtcrime.securesms.payments.DataExportUtil import org.thoughtcrime.securesms.util.ConversationUtil import org.thoughtcrime.securesms.util.concurrent.SimpleTask class InternalSettingsFragment : DSLSettingsFragment(R.string.preferences__internal_preferences) { private lateinit var viewModel: InternalSettingsViewModel override fun bindAdapter(adapter: DSLSettingsAdapter) { val repository = InternalSettingsRepository(requireContext()) val factory = InternalSettingsViewModel.Factory(repository) viewModel = ViewModelProviders.of(this, factory)[InternalSettingsViewModel::class.java] viewModel.state.observe(viewLifecycleOwner) { adapter.submitList(getConfiguration(it).toMappingModelList()) } } private fun getConfiguration(state: InternalSettingsState): DSLConfiguration { return configure { sectionHeaderPref(R.string.preferences__internal_payments) clickPref( title = DSLSettingsText.from(R.string.preferences__internal_payment_copy_data), summary = DSLSettingsText.from(R.string.preferences__internal_payment_copy_data_description), onClick = { copyPaymentsDataToClipboard() } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_account) clickPref( title = DSLSettingsText.from(R.string.preferences__internal_refresh_attributes), summary = DSLSettingsText.from(R.string.preferences__internal_refresh_attributes_description), onClick = { refreshAttributes() } ) clickPref( title = DSLSettingsText.from(R.string.preferences__internal_rotate_profile_key), summary = DSLSettingsText.from(R.string.preferences__internal_rotate_profile_key_description), onClick = { rotateProfileKey() } ) clickPref( title = DSLSettingsText.from(R.string.preferences__internal_refresh_remote_config), summary = DSLSettingsText.from(R.string.preferences__internal_refresh_remote_config_description), onClick = { refreshRemoteValues() } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_misc) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_user_details), summary = DSLSettingsText.from(R.string.preferences__internal_user_details_description), isChecked = state.seeMoreUserDetails, onClick = { viewModel.setSeeMoreUserDetails(!state.seeMoreUserDetails) } ) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_shake_to_report), summary = DSLSettingsText.from(R.string.preferences__internal_shake_to_report_description), isChecked = state.shakeToReport, onClick = { viewModel.setShakeToReport(!state.shakeToReport) } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_storage_service) clickPref( title = DSLSettingsText.from(R.string.preferences__internal_force_storage_service_sync), summary = DSLSettingsText.from(R.string.preferences__internal_force_storage_service_sync_description), onClick = { forceStorageServiceSync() } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_preferences_groups_v2) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_do_not_create_gv2), summary = DSLSettingsText.from(R.string.preferences__internal_do_not_create_gv2_description), isChecked = state.gv2doNotCreateGv2Groups, onClick = { viewModel.setGv2DoNotCreateGv2Groups(!state.gv2doNotCreateGv2Groups) } ) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_force_gv2_invites), summary = DSLSettingsText.from(R.string.preferences__internal_force_gv2_invites_description), isChecked = state.gv2forceInvites, onClick = { viewModel.setGv2ForceInvites(!state.gv2forceInvites) } ) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_ignore_gv2_server_changes), summary = DSLSettingsText.from(R.string.preferences__internal_ignore_gv2_server_changes_description), isChecked = state.gv2ignoreServerChanges, onClick = { viewModel.setGv2IgnoreServerChanges(!state.gv2ignoreServerChanges) } ) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_ignore_gv2_p2p_changes), summary = DSLSettingsText.from(R.string.preferences__internal_ignore_gv2_server_changes_description), isChecked = state.gv2ignoreP2PChanges, onClick = { viewModel.setGv2IgnoreP2PChanges(!state.gv2ignoreP2PChanges) } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_preferences_groups_v1_migration) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_do_not_initiate_automigrate), summary = DSLSettingsText.from(R.string.preferences__internal_do_not_initiate_automigrate_description), isChecked = state.disableAutoMigrationInitiation, onClick = { viewModel.setDisableAutoMigrationInitiation(!state.disableAutoMigrationInitiation) } ) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_do_not_notify_automigrate), summary = DSLSettingsText.from(R.string.preferences__internal_do_not_notify_automigrate_description), isChecked = state.disableAutoMigrationNotification, onClick = { viewModel.setDisableAutoMigrationNotification(!state.disableAutoMigrationNotification) } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_network) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_force_censorship), summary = DSLSettingsText.from(R.string.preferences__internal_force_censorship_description), isChecked = state.forceCensorship, onClick = { viewModel.setForceCensorship(!state.forceCensorship) } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_conversations_and_shortcuts) clickPref( title = DSLSettingsText.from(R.string.preferences__internal_delete_all_dynamic_shortcuts), summary = DSLSettingsText.from(R.string.preferences__internal_click_to_delete_all_dynamic_shortcuts), onClick = { deleteAllDynamicShortcuts() } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_emoji) val emojiSummary = if (state.emojiVersion == null) { getString(R.string.preferences__internal_use_built_in_emoji_set) } else { getString( R.string.preferences__internal_current_version_d_at_density_s, state.emojiVersion.version, state.emojiVersion.density ) } switchPref( title = DSLSettingsText.from(R.string.preferences__internal_use_built_in_emoji_set), summary = DSLSettingsText.from(emojiSummary), isChecked = state.useBuiltInEmojiSet, onClick = { viewModel.setDisableAutoMigrationNotification(!state.useBuiltInEmojiSet) } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_sender_key) clickPref( title = DSLSettingsText.from(R.string.preferences__internal_clear_all_state), summary = DSLSettingsText.from(R.string.preferences__internal_click_to_delete_all_sender_key_state), onClick = { clearAllSenderKeyState() } ) clickPref( title = DSLSettingsText.from(R.string.preferences__internal_clear_shared_state), summary = DSLSettingsText.from(R.string.preferences__internal_click_to_delete_all_sharing_state), onClick = { clearAllSenderKeySharedState() } ) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_remove_two_person_minimum), summary = DSLSettingsText.from(R.string.preferences__internal_remove_the_requirement_that_you_need), isChecked = state.removeSenderKeyMinimium, onClick = { viewModel.setRemoveSenderKeyMinimum(!state.removeSenderKeyMinimium) } ) switchPref( title = DSLSettingsText.from(R.string.preferences__internal_delay_resends), summary = DSLSettingsText.from(R.string.preferences__internal_delay_resending_messages_in_response_to_retry_receipts), isChecked = state.delayResends, onClick = { viewModel.setDelayResends(!state.delayResends) } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_local_metrics) clickPref( title = DSLSettingsText.from(R.string.preferences__internal_clear_local_metrics), summary = DSLSettingsText.from(R.string.preferences__internal_click_to_clear_all_local_metrics_state), onClick = { clearAllLocalMetricsState() } ) dividerPref() sectionHeaderPref(R.string.preferences__internal_calling) radioPref( title = DSLSettingsText.from(R.string.preferences__internal_calling_default), summary = DSLSettingsText.from(BuildConfig.SIGNAL_SFU_URL), isChecked = state.callingServer == BuildConfig.SIGNAL_SFU_URL, onClick = { viewModel.setInternalGroupCallingServer(null) } ) BuildConfig.SIGNAL_SFU_INTERNAL_NAMES.zip(BuildConfig.SIGNAL_SFU_INTERNAL_URLS) .forEach { (name, server) -> radioPref( title = DSLSettingsText.from(requireContext().getString(R.string.preferences__internal_calling_s_server, name)), summary = DSLSettingsText.from(server), isChecked = state.callingServer == server, onClick = { viewModel.setInternalGroupCallingServer(server) } ) } } } private fun copyPaymentsDataToClipboard() { MaterialAlertDialogBuilder(requireContext()) .setMessage( """ Local payments history will be copied to the clipboard. It may therefore compromise privacy. However, no private keys will be copied. """.trimIndent() ) .setPositiveButton( "Copy" ) { _: DialogInterface?, _: Int -> SimpleTask.run<Any?>( SignalExecutors.UNBOUNDED, { val context: Context = ApplicationDependencies.getApplication() val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val tsv = DataExportUtil.createTsv() val clip = ClipData.newPlainText(context.getString(R.string.app_name), tsv) clipboard.setPrimaryClip(clip) null }, { Toast.makeText( context, "Payments have been copied", Toast.LENGTH_SHORT ).show() } ) } .setNegativeButton(android.R.string.cancel, null) .show() } private fun refreshAttributes() { ApplicationDependencies.getJobManager() .startChain(RefreshAttributesJob()) .then(RefreshOwnProfileJob()) .enqueue() Toast.makeText(context, "Scheduled attribute refresh", Toast.LENGTH_SHORT).show() } private fun rotateProfileKey() { ApplicationDependencies.getJobManager().add(RotateProfileKeyJob()) Toast.makeText(context, "Scheduled profile key rotation", Toast.LENGTH_SHORT).show() } private fun refreshRemoteValues() { ApplicationDependencies.getJobManager().add(RemoteConfigRefreshJob()) Toast.makeText(context, "Scheduled remote config refresh", Toast.LENGTH_SHORT).show() } private fun forceStorageServiceSync() { ApplicationDependencies.getJobManager().add(StorageForcePushJob()) Toast.makeText(context, "Scheduled storage force push", Toast.LENGTH_SHORT).show() } private fun deleteAllDynamicShortcuts() { ConversationUtil.clearAllShortcuts(requireContext()) Toast.makeText(context, "Deleted all dynamic shortcuts.", Toast.LENGTH_SHORT).show() } private fun clearAllSenderKeyState() { DatabaseFactory.getSenderKeyDatabase(requireContext()).deleteAll() DatabaseFactory.getSenderKeySharedDatabase(requireContext()).deleteAll() Toast.makeText(context, "Deleted all sender key state.", Toast.LENGTH_SHORT).show() } private fun clearAllSenderKeySharedState() { DatabaseFactory.getSenderKeySharedDatabase(requireContext()).deleteAll() Toast.makeText(context, "Deleted all sender key shared state.", Toast.LENGTH_SHORT).show() } private fun clearAllLocalMetricsState() { LocalMetricsDatabase.getInstance(ApplicationDependencies.getApplication()).clear() Toast.makeText(context, "Cleared all local metrics state.", Toast.LENGTH_SHORT).show() } }
gpl-3.0
6bff11f85d850c3a9031289709c25333
36.65625
126
0.702559
4.800797
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/challenge/add/AddChallengeTrackedValueViewController.kt
1
9431
package io.ipoli.android.challenge.add import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.view.* import com.mikepenz.community_material_typeface_library.CommunityMaterial import com.mikepenz.google_material_typeface_library.GoogleMaterial import com.mikepenz.iconics.IconicsDrawable import io.ipoli.android.Constants.Companion.DECIMAL_FORMATTER import io.ipoli.android.R import io.ipoli.android.challenge.add.EditChallengeViewState.StateType.* import io.ipoli.android.challenge.entity.Challenge import io.ipoli.android.common.redux.android.BaseViewController import io.ipoli.android.common.view.* import io.ipoli.android.common.view.recyclerview.BaseRecyclerViewAdapter import io.ipoli.android.common.view.recyclerview.RecyclerViewViewModel import io.ipoli.android.common.view.recyclerview.SimpleViewHolder import kotlinx.android.synthetic.main.controller_add_challenge_tracked_value.view.* import kotlinx.android.synthetic.main.item_challenge_summary_tracked_value.view.* class AddChallengeTrackedValueViewController(args: Bundle? = null) : BaseViewController<EditChallengeAction, EditChallengeViewState>( args ) { override val stateKey = EditChallengeReducer.stateKey private var showNext = false override fun onCreateView( inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle? ): View { setHasOptionsMenu(true) applyStatusBarColors = false val view = container.inflate(R.layout.controller_add_challenge_tracked_value) view.resultCompletionIcon.setImageDrawable( IconicsDrawable(view.context) .icon(GoogleMaterial.Icon.gmd_done_all) .colorRes(R.color.md_red_500) .paddingDp(8) .sizeDp(40) ) view.resultAverageValueIcon.setImageDrawable( IconicsDrawable(view.context) .icon(CommunityMaterial.Icon.cmd_scale_balance) .colorRes(R.color.md_amber_500) .paddingDp(10) .sizeDp(40) ) view.resultCompletionBackground.dispatchOnClick { EditChallengeAction.AddCompleteAllTrackedValue } view.resultReachValueBackground.onDebounceClick { dispatch(EditChallengeAction.ShowTargetTrackedValuePicker(emptyList())) } view.resultAverageBackground.onDebounceClick { dispatch(EditChallengeAction.ShowAverageTrackedValuePicker(emptyList())) } view.expectedResultText.setTextColor(colorRes(R.color.md_dark_text_87)) view.expectedResultText.text = "Complete all Quests" view.expectedResultRemove.setImageDrawable( IconicsDrawable(view.context).normalIcon( GoogleMaterial.Icon.gmd_close, R.color.md_dark_text_87 ).respectFontBounds(true) ) view.expectedResultRemove.dispatchOnClick { EditChallengeAction.RemoveCompleteAll } view.resultCompletionDivider.gone() view.resultCompletionItem.gone() view.resultReachItems.layoutManager = LinearLayoutManager(view.context) view.resultReachItems.adapter = TrackedValueAdapter() view.resultAverageItems.layoutManager = LinearLayoutManager(view.context) view.resultAverageItems.adapter = TrackedValueAdapter() return view } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.next_wizard_menu, menu) } override fun onPrepareOptionsMenu(menu: Menu) { val nextItem = menu.findItem(R.id.actionNext) nextItem.isVisible = showNext super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.actionNext -> { dispatch(EditChallengeAction.ShowNext) true } else -> super.onOptionsItemSelected(item) } override fun render(state: EditChallengeViewState, view: View) { when (state.type) { TRACKED_VALUES_CHANGED -> { showNext = state.trackedValues.isNotEmpty() activity?.invalidateOptionsMenu() if (state.shouldTrackCompleteAll) { view.resultCompletionBackground.isEnabled = false view.resultCompletionBackground.isClickable = false view.resultCompletionBackground.isFocusable = false view.resultCompletionBackground.setOnClickListener(null) view.resultCompletionDivider.visible() view.resultCompletionItem.visible() } else { view.resultCompletionBackground.isEnabled = true view.resultCompletionBackground.isClickable = true view.resultCompletionBackground.isFocusable = true view.resultCompletionBackground.dispatchOnClick { EditChallengeAction.AddCompleteAllTrackedValue } view.resultCompletionDivider.gone() view.resultCompletionItem.gone() } (view.resultReachItems.adapter as TrackedValueAdapter).updateAll(state.trackTargetViewModels) (view.resultAverageItems.adapter as TrackedValueAdapter).updateAll(state.trackAverageViewModels) view.resultReachValueBackground.onDebounceClick { dispatch(EditChallengeAction.ShowTargetTrackedValuePicker(state.trackedValues)) } view.resultAverageBackground.onDebounceClick { dispatch(EditChallengeAction.ShowAverageTrackedValuePicker(state.trackedValues)) } } SHOW_TARGET_TRACKED_VALUE_PICKER -> navigate().toTargetValuePicker(targetValueSelectedListener = { t -> dispatch( EditChallengeAction.AddTargetTrackedValue(t) ) }) SHOW_AVERAGE_TRACKED_VALUE_PICKER -> navigate().toMaintainAverageValuePicker(trackedValueSelectedListener = { t -> dispatch( EditChallengeAction.AddAverageTrackedValue(t) ) }) else -> { } } } data class TrackedValueViewModel( override val id: String, val text: String, val trackedValue: Challenge.TrackedValue ) : RecyclerViewViewModel inner class TrackedValueAdapter : BaseRecyclerViewAdapter<TrackedValueViewModel>(R.layout.item_challenge_summary_tracked_value) { override fun onBindViewModel( vm: TrackedValueViewModel, view: View, holder: SimpleViewHolder ) { view.expectedResultRemove.setImageDrawable( IconicsDrawable(view.context).normalIcon( GoogleMaterial.Icon.gmd_close, R.color.md_dark_text_87 ).respectFontBounds(true) ) view.expectedResultRemove.dispatchOnClick { EditChallengeAction.RemoveTrackedValue(vm.id) } view.expectedResultText.setTextColor(colorRes(R.color.md_dark_text_87)) view.expectedResultText.text = vm.text when (vm.trackedValue) { is Challenge.TrackedValue.Target -> view.onDebounceClick { navigate().toTargetValuePicker( targetValueSelectedListener = { t -> dispatch(EditChallengeAction.UpdateTrackedValue(t)) }, trackedValue = vm.trackedValue ) } is Challenge.TrackedValue.Average -> view.onDebounceClick { navigate().toMaintainAverageValuePicker( trackedValueSelectedListener = { t -> dispatch(EditChallengeAction.UpdateTrackedValue(t)) }, trackedValue = vm.trackedValue ) } else -> view.setOnClickListener(null) } } } private val EditChallengeViewState.trackTargetViewModels: List<TrackedValueViewModel> get() = trackedValues .filterIsInstance(Challenge.TrackedValue.Target::class.java) .map { TrackedValueViewModel( id = it.id, text = "Reach ${DECIMAL_FORMATTER.format(it.targetValue)} ${it.units} ${it.name}", trackedValue = it ) } private val EditChallengeViewState.trackAverageViewModels: List<TrackedValueViewModel> get() = trackedValues .filterIsInstance(Challenge.TrackedValue.Average::class.java) .map { TrackedValueViewModel( id = it.id, text = "Maintain ${DECIMAL_FORMATTER.format(it.targetValue)} ${it.units} ${it.name}", trackedValue = it ) } }
gpl-3.0
730e71fe1fb5b42eeb79d1d76b5a145b
38.797468
112
0.615629
5.761148
false
false
false
false
spinnaker/orca
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/StartStageHandler.kt
1
9650
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.fasterxml.jackson.databind.ObjectMapper import com.netflix.spectator.api.Registry import com.netflix.spinnaker.orca.TaskImplementationResolver import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.NOT_STARTED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution import com.netflix.spinnaker.orca.events.StageStarted import com.netflix.spinnaker.orca.exceptions.ExceptionHandler import com.netflix.spinnaker.orca.ext.allUpstreamStagesComplete import com.netflix.spinnaker.orca.ext.anyUpstreamStagesFailed import com.netflix.spinnaker.orca.ext.firstAfterStages import com.netflix.spinnaker.orca.ext.firstBeforeStages import com.netflix.spinnaker.orca.ext.firstTask import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilderFactory import com.netflix.spinnaker.orca.pipeline.expressions.PipelineExpressionEvaluator import com.netflix.spinnaker.orca.pipeline.model.OptionalStageSupport import com.netflix.spinnaker.orca.pipeline.model.StageExecutionImpl import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor import com.netflix.spinnaker.orca.pipeline.util.StageNavigator import com.netflix.spinnaker.orca.q.CompleteExecution import com.netflix.spinnaker.orca.q.CompleteStage import com.netflix.spinnaker.orca.q.SkipStage import com.netflix.spinnaker.orca.q.StartStage import com.netflix.spinnaker.orca.q.StartTask import com.netflix.spinnaker.orca.q.addContextFlags import com.netflix.spinnaker.orca.q.buildBeforeStages import com.netflix.spinnaker.orca.q.buildTasks import com.netflix.spinnaker.q.AttemptsAttribute import com.netflix.spinnaker.q.MaxAttemptsAttribute import com.netflix.spinnaker.q.Queue import java.time.Clock import java.time.Duration import java.time.Instant import kotlin.collections.set import org.springframework.beans.factory.annotation.Qualifier import org.springframework.beans.factory.annotation.Value import org.springframework.context.ApplicationEventPublisher import org.springframework.stereotype.Component @Component class StartStageHandler( override val queue: Queue, override val repository: ExecutionRepository, override val stageNavigator: StageNavigator, override val stageDefinitionBuilderFactory: StageDefinitionBuilderFactory, override val contextParameterProcessor: ContextParameterProcessor, @Qualifier("queueEventPublisher") private val publisher: ApplicationEventPublisher, private val exceptionHandlers: List<ExceptionHandler>, @Qualifier("mapper") private val objectMapper: ObjectMapper, private val clock: Clock, private val registry: Registry, @Value("\${queue.retry.delay.ms:15000}") retryDelayMs: Long, private val taskImplementationResolver: TaskImplementationResolver ) : OrcaMessageHandler<StartStage>, StageBuilderAware, ExpressionAware, AuthenticationAware { private val retryDelay = Duration.ofMillis(retryDelayMs) override fun handle(message: StartStage) { message.withStage { stage -> try { stage.withAuth { if (stage.anyUpstreamStagesFailed()) { // this only happens in restart scenarios log.warn("Tried to start stage ${stage.id} but something upstream had failed (executionId: ${message.executionId})") queue.push(CompleteExecution(message)) } else if (stage.allUpstreamStagesComplete()) { if (stage.status != NOT_STARTED) { log.warn("Ignoring $message as stage is already ${stage.status}") } else if (stage.shouldSkip()) { queue.push(SkipStage(message)) } else if (stage.isAfterStartTimeExpiry()) { log.warn("Stage is being skipped because its start time is after TTL (stageId: ${stage.id}, executionId: ${message.executionId})") queue.push(SkipStage(stage)) } else { try { // Set the startTime in case we throw an exception. stage.startTime = clock.millis() repository.storeStage(stage) stage.plan() stage.status = RUNNING repository.storeStage(stage) stage.start() publisher.publishEvent(StageStarted(this, stage)) trackResult(stage) } catch (e: Exception) { val exceptionDetails = exceptionHandlers.shouldRetry(e, stage.name) if (exceptionDetails?.shouldRetry == true) { val attempts = message.getAttribute<AttemptsAttribute>()?.attempts ?: 0 log.warn("Error planning ${stage.type} stage for ${message.executionType}[${message.executionId}] (attempts: $attempts)") message.setAttribute(MaxAttemptsAttribute(40)) queue.push(message, retryDelay) } else { log.error("Error running ${stage.type}[${stage.id}] stage for ${message.executionType}[${message.executionId}]", e) stage.apply { context["exception"] = exceptionDetails context["beforeStagePlanningFailed"] = true } repository.storeStage(stage) queue.push(CompleteStage(message)) } } } } else { log.info("Re-queuing $message as upstream stages are not yet complete") queue.push(message, retryDelay) } } } catch (e: Exception) { message.withStage { stage -> log.error("Error running ${stage.type}[${stage.id}] stage for ${message.executionType}[${message.executionId}]", e) stage.apply { val exceptionDetails = exceptionHandlers.shouldRetry(e, stage.name) context["exception"] = exceptionDetails context["beforeStagePlanningFailed"] = true } repository.storeStage(stage) queue.push(CompleteStage(message)) } } } } private fun trackResult(stage: StageExecution) { // We only want to record invocations of parent-level stages; not synthetics if (stage.parentStageId != null) { return } val id = registry.createId("stage.invocations") .withTag("type", stage.type) .withTag("application", stage.execution.application) .let { id -> // TODO rz - Need to check synthetics for their cloudProvider. stage.context["cloudProvider"]?.let { id.withTag("cloudProvider", it.toString()) } ?: id }.let { id -> stage.additionalMetricTags?.let { id.withTags(stage.additionalMetricTags) } ?: id } registry.counter(id).increment() } override val messageType = StartStage::class.java private fun StageExecution.plan() { builder().let { builder -> // if we have a top level stage, ensure that context expressions are processed val mergedStage = if (this.parentStageId == null) this.withMergedContext() else this builder.addContextFlags(mergedStage) builder.buildTasks(mergedStage, taskImplementationResolver) builder.buildBeforeStages(mergedStage) { repository.addStage(it.withMergedContext()) } } } private fun StageExecution.start() { val beforeStages = firstBeforeStages() if (beforeStages.isEmpty()) { val task = firstTask() if (task == null) { // TODO: after stages are no longer planned at this point. We could skip this val afterStages = firstAfterStages() if (afterStages.isEmpty()) { queue.push(CompleteStage(this)) } else { afterStages.forEach { queue.push(StartStage(it)) } } } else { queue.push(StartTask(this, task.id)) } } else { beforeStages.forEach { queue.push(StartStage(it)) } } } private fun StageExecution.shouldSkip(): Boolean { if (this.execution.type != PIPELINE) { return false } val clonedContext: MutableMap<String, Any> = this.context.toMutableMap() val clonedStage = StageExecutionImpl(this.execution, this.type, clonedContext).also { it.refId = refId it.requisiteStageRefIds = requisiteStageRefIds it.syntheticStageOwner = syntheticStageOwner it.parentStageId = parentStageId } if (clonedStage.context.containsKey(PipelineExpressionEvaluator.SUMMARY)) { this.context.put(PipelineExpressionEvaluator.SUMMARY, clonedStage.context[PipelineExpressionEvaluator.SUMMARY]) } return OptionalStageSupport.isOptional(clonedStage.withMergedContext(), contextParameterProcessor) } private fun StageExecution.isAfterStartTimeExpiry(): Boolean = startTimeExpiry?.let { Instant.ofEpochMilli(it) }?.isBefore(clock.instant()) ?: false }
apache-2.0
05b95f9a5eb1547da25e88b6255ed1df
41.139738
144
0.697513
4.839519
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ParentWithNullsImpl.kt
2
8430
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToOneChild import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ParentWithNullsImpl(val dataSource: ParentWithNullsData) : ParentWithNulls, WorkspaceEntityBase() { companion object { internal val CHILD_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentWithNulls::class.java, ChildWithNulls::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, true) val connections = listOf<ConnectionId>( CHILD_CONNECTION_ID, ) } override val parentData: String get() = dataSource.parentData override val child: ChildWithNulls? get() = snapshot.extractOneToOneChild(CHILD_CONNECTION_ID, this) override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: ParentWithNullsData?) : ModifiableWorkspaceEntityBase<ParentWithNulls, ParentWithNullsData>( result), ParentWithNulls.Builder { constructor() : this(ParentWithNullsData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ParentWithNulls is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isParentDataInitialized()) { error("Field ParentWithNulls#parentData should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as ParentWithNulls if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.parentData != dataSource.parentData) this.parentData = dataSource.parentData if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var parentData: String get() = getEntityData().parentData set(value) { checkModificationAllowed() getEntityData(true).parentData = value changedProperty.add("parentData") } override var child: ChildWithNulls? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneChild(CHILD_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] as? ChildWithNulls } else { this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] as? ChildWithNulls } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*, *>) { value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) { _diff.updateOneToOneChildOfParent(CHILD_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*, *>) { value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] = value } changedProperty.add("child") } override fun getEntityClass(): Class<ParentWithNulls> = ParentWithNulls::class.java } } class ParentWithNullsData : WorkspaceEntityData<ParentWithNulls>() { lateinit var parentData: String fun isParentDataInitialized(): Boolean = ::parentData.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ParentWithNulls> { val modifiable = ParentWithNullsImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): ParentWithNulls { return getCached(snapshot) { val entity = ParentWithNullsImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ParentWithNulls::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ParentWithNulls(parentData, entitySource) { } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ParentWithNullsData if (this.entitySource != other.entitySource) return false if (this.parentData != other.parentData) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ParentWithNullsData if (this.parentData != other.parentData) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + parentData.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + parentData.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
521b4ec617d20baa347891d4ed54751c
34.720339
135
0.701661
5.366009
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/TypeOfAnnotationMemberFix.kt
3
3123
// 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.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.CleanupFix import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtTypeReference import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType class TypeOfAnnotationMemberFix( typeReference: KtTypeReference, private val fixedType: String ) : KotlinQuickFixAction<KtTypeReference>(typeReference), CleanupFix { override fun getText(): String = KotlinBundle.message("replace.array.of.boxed.with.array.of.primitive") override fun getFamilyName(): String = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val psiElement = element ?: return psiElement.replace(KtPsiFactory(psiElement).createType(fixedType)) } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val typeReference = diagnostic.psiElement as? KtTypeReference ?: return null val type = typeReference.analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, typeReference] ?: return null val itemType = type.getArrayItemType() ?: return null val itemTypeName = itemType.constructor.declarationDescriptor?.name?.asString() ?: return null val fixedArrayTypeText = if (itemType.isItemTypeToFix()) { "${itemTypeName}Array" } else { return null } return TypeOfAnnotationMemberFix(typeReference, fixedArrayTypeText) } private fun KotlinType.getArrayItemType(): KotlinType? { if (!KotlinBuiltIns.isArray(this)) { return null } val boxedType = arguments.singleOrNull() ?: return null if (boxedType.isStarProjection) { return null } return boxedType.type } private fun KotlinType.isItemTypeToFix() = KotlinBuiltIns.isByte(this) || KotlinBuiltIns.isChar(this) || KotlinBuiltIns.isShort(this) || KotlinBuiltIns.isInt(this) || KotlinBuiltIns.isLong(this) || KotlinBuiltIns.isFloat(this) || KotlinBuiltIns.isDouble(this) || KotlinBuiltIns.isBoolean(this) } }
apache-2.0
e7c0aa33f14a0c15d6f6fc8c12e191c1
42.388889
158
0.704451
5.078049
false
false
false
false
GunoH/intellij-community
platform/diff-impl/src/com/intellij/diff/settings/ExternalToolsTreePanel.kt
2
20360
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.diff.settings import com.intellij.diff.tools.external.ExternalDiffSettings import com.intellij.diff.tools.external.ExternalDiffSettings.ExternalTool import com.intellij.diff.tools.external.ExternalDiffSettings.ExternalToolGroup import com.intellij.diff.tools.external.ExternalDiffToolUtil import com.intellij.execution.impl.ConsoleViewUtil import com.intellij.ide.util.treeView.TreeState import com.intellij.openapi.Disposable import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.runInEdt import com.intellij.openapi.diff.DiffBundle import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.ui.* import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.ColoredListCellRenderer import com.intellij.ui.SimpleColoredComponent import com.intellij.ui.SmartExpander import com.intellij.ui.ToolbarDecorator import com.intellij.ui.components.JBCheckBox import com.intellij.ui.components.JBTextField import com.intellij.ui.dsl.builder.* import com.intellij.ui.layout.ComponentPredicate import com.intellij.ui.treeStructure.Tree import com.intellij.util.PathUtilRt import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.JBUI import com.intellij.util.ui.ListTableModel import com.intellij.util.ui.tree.TreeUtil import java.awt.Component import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.* import javax.swing.event.DocumentEvent import javax.swing.event.DocumentListener import javax.swing.event.TreeExpansionEvent import javax.swing.event.TreeExpansionListener import javax.swing.tree.DefaultMutableTreeNode import javax.swing.tree.DefaultTreeModel import javax.swing.tree.TreeCellRenderer import javax.swing.tree.TreePath internal class ExternalToolsTreePanel(private val models: ExternalToolsModels) { private var treeState: TreeState private val treeModel = models.treeModel private val root = treeModel.root as DefaultMutableTreeNode private val tree = Tree(treeModel).apply { visibleRowCount = 8 isRootVisible = false cellRenderer = ExternalToolsTreeCellRenderer() treeState = TreeState.createOn(this) addMouseListener(object : MouseAdapter() { override fun mousePressed(mouseEvent: MouseEvent) { val treePath = selectionPath ?: return if (mouseEvent.clickCount == 2 && SwingUtilities.isLeftMouseButton(mouseEvent)) { mouseEvent.consume() val node = treePath.lastPathComponent as DefaultMutableTreeNode when (node.userObject) { is ExternalTool -> editData() else -> {} } } } }) addTreeExpansionListener(object : TreeExpansionListener { override fun treeExpanded(event: TreeExpansionEvent) { treeState = TreeState.createOn(this@apply) } override fun treeCollapsed(event: TreeExpansionEvent) { treeState = TreeState.createOn(this@apply) } }) SmartExpander.installOn(this) } val component: JComponent init { val decoratedTree = ToolbarDecorator.createDecorator(tree) .setAddAction { addTool() } .setRemoveActionUpdater { isExternalToolSelected(tree.selectionPath) } .setRemoveAction { removeData() } .setEditActionUpdater { isExternalToolSelected(tree.selectionPath) } .setEditAction { editData() } .disableUpDownActions() .createPanel() component = decoratedTree } fun onModified(settings: ExternalDiffSettings): Boolean = treeModel.toMap() != settings.externalTools fun onApply(settings: ExternalDiffSettings) { settings.externalTools = treeModel.toMap() treeState = TreeState.createOn(tree) } fun onReset(settings: ExternalDiffSettings) { treeModel.update(settings.externalTools) treeState.applyTo(tree) } private fun addTool() { val dialog = AddToolDialog() if (dialog.showAndGet()) { val tool = dialog.createExternalTool() val node = DefaultMutableTreeNode(tool) val groupNode = findGroupNode(dialog.getToolGroup()) treeModel.insertNodeInto(node, groupNode, groupNode.childCount) treeModel.nodeChanged(root) tree.expandPath(TreePath(groupNode.path)) } } private fun findGroupNode(externalToolGroup: ExternalToolGroup): DefaultMutableTreeNode { for (child in root.children()) { val treeNode = child as DefaultMutableTreeNode val valueNode = treeNode.userObject as ExternalToolGroup if (valueNode == externalToolGroup) return treeNode } val groupNode = DefaultMutableTreeNode(externalToolGroup) treeModel.insertNodeInto(groupNode, root, root.childCount) return groupNode } private fun removeData() { val treePath = tree.selectionPath ?: return val node = treePath.lastPathComponent as DefaultMutableTreeNode val parentNode = treePath.parentPath.lastPathComponent as DefaultMutableTreeNode val toolGroup = parentNode.userObject as ExternalToolGroup val externalTool = node.userObject as ExternalTool if (isConfigurationRegistered(externalTool, toolGroup)) { Messages.showWarningDialog(DiffBundle.message("settings.external.tool.tree.remove.warning.message"), DiffBundle.message("settings.external.tool.tree.remove.warning.title")) return } val dialog = MessageDialogBuilder.okCancel(DiffBundle.message("settings.external.diff.table.remove.dialog.title"), DiffBundle.message("settings.external.diff.table.remove.dialog.message")) if (dialog.guessWindowAndAsk()) { treeModel.removeNodeFromParent(node) if (parentNode.childCount == 0) { treeModel.removeNodeFromParent(parentNode) } } } private fun editData() { val treePath = tree.selectionPath ?: return val node = treePath.lastPathComponent as DefaultMutableTreeNode if (node.userObject !is ExternalTool) { return } val currentTool = node.userObject as ExternalTool val dialog = AddToolDialog(currentTool) if (dialog.showAndGet()) { val editedTool = dialog.createExternalTool() val groupNode = findGroupNode(dialog.getToolGroup()) val toolGroup = groupNode.userObject as ExternalToolGroup node.userObject = editedTool treeModel.nodeChanged(node) models.tableModel.updateEntities(toolGroup, currentTool, editedTool) } } private fun isConfigurationRegistered(externalTool: ExternalTool, externalToolGroup: ExternalToolGroup): Boolean { val configurations = models.tableModel.items return when (externalToolGroup) { ExternalToolGroup.DIFF_TOOL -> configurations.any { it.diffToolName == externalTool.name } ExternalToolGroup.MERGE_TOOL -> configurations.any { it.mergeToolName == externalTool.name } } } private fun isExternalToolSelected(selectionPath: TreePath?): Boolean { if (selectionPath == null) return false val node = selectionPath.lastPathComponent as DefaultMutableTreeNode return when (node.userObject) { is ExternalTool -> true else -> false } } private class ExternalToolsTreeCellRenderer : TreeCellRenderer { private val renderer = SimpleColoredComponent() override fun getTreeCellRendererComponent(tree: JTree, value: Any, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean): Component { return renderer.apply { val node = value as DefaultMutableTreeNode val text = when (val userObject = node.userObject) { null -> "" // Special for root (not visible in tree) is ExternalToolGroup -> userObject.groupName // NON-NLS is ExternalTool -> userObject.name // NON-NLS else -> userObject.toString() // NON-NLS } clear() append(text) } } } private inner class AddToolDialog( private val oldToolName: String? = null, private val isEditMode: Boolean = false, ) : DialogWrapper(null) { private val groupField = ComboBox( arrayOf(ExternalToolGroup.DIFF_TOOL, ExternalToolGroup.MERGE_TOOL) ).apply { renderer = object : ColoredListCellRenderer<ExternalToolGroup>() { override fun customizeCellRenderer(list: JList<out ExternalToolGroup>, value: ExternalToolGroup, index: Int, selected: Boolean, hasFocus: Boolean) { append(value.groupName) // NON-NLS } } } private var isAutocompleteToolName = true private val toolNameField = JBTextField().apply { document.addDocumentListener(object : DocumentListener { override fun insertUpdate(event: DocumentEvent) { if (isFocusOwner) isAutocompleteToolName = false } override fun removeUpdate(event: DocumentEvent) {} override fun changedUpdate(event: DocumentEvent) {} }) } private val programPathField = TextFieldWithBrowseButton().apply { addBrowseFolderListener(DiffBundle.message("select.external.program.dialog.title"), null, null, FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor()) textField.document.addDocumentListener(object : DocumentListener { override fun insertUpdate(event: DocumentEvent) { if (isAutocompleteToolName) { val guessToolName = StringUtil.capitalize(PathUtilRt.getFileName(text)) toolNameField.text = guessToolName } } override fun removeUpdate(event: DocumentEvent) {} override fun changedUpdate(event: DocumentEvent) {} }) } private val argumentPatternField = JBTextField(DIFF_TOOL_DEFAULT_ARGUMENT_PATTERN) private val isMergeTrustExitCode = JBCheckBox(DiffBundle.message("settings.external.diff.trust.process.exit.code")) private val testDiffButton = JButton(DiffBundle.message("settings.external.diff.test.diff")).apply { addActionListener { showTestDiff() } } private val testThreeSideDiffButton = JButton(DiffBundle.message("settings.external.diff.test.three.side.diff")).apply { addActionListener { showTestThreeDiff() } } private val testMergeButton = JButton(DiffBundle.message("settings.external.diff.test.merge")).apply { addActionListener { showTestMerge() } } private val toolOutputEditor = ConsoleViewUtil.setupConsoleEditor(null, false, false).also { it.settings.additionalLinesCount = 3 } private var toolOutputConsole: MyTestOutputConsole? = null constructor(externalTool: ExternalTool) : this(externalTool.name, true) { isAutocompleteToolName = false toolNameField.text = externalTool.name programPathField.text = externalTool.programPath argumentPatternField.text = externalTool.argumentPattern isMergeTrustExitCode.isSelected = externalTool.isMergeTrustExitCode groupField.selectedItem = externalTool.groupName title = DiffBundle.message("settings.external.tool.tree.edit.dialog.title") } init { title = DiffBundle.message("settings.external.tool.tree.add.dialog.title") Disposer.register(disposable) { toolOutputConsole?.let { Disposer.dispose(it) } } init() } override fun createCenterPanel(): JComponent = panel { lateinit var argumentPatternDescription: JEditorPane row(DiffBundle.message("settings.external.tool.tree.add.dialog.field.group")) { cell(groupField).align(AlignX.FILL) }.visible(!isEditMode) row(DiffBundle.message("settings.external.tool.tree.add.dialog.field.program.path")) { cell(programPathField).align(AlignX.FILL) } row(DiffBundle.message("settings.external.tool.tree.add.dialog.field.tool.name")) { cell(toolNameField).align(AlignX.FILL).validationOnApply { toolFieldValidation(groupField.item, it.text) } } row(DiffBundle.message("settings.external.tool.tree.add.dialog.field.argument.pattern")) { cell(argumentPatternField).align(AlignX.FILL) } row { cell(isMergeTrustExitCode).align(AlignX.FILL) .visibleIf(object : ComponentPredicate() { override fun addListener(listener: (Boolean) -> Unit) { groupField.addItemListener { val isMergeGroup = invoke() testDiffButton.isVisible = !isMergeGroup testThreeSideDiffButton.isVisible = !isMergeGroup testMergeButton.isVisible = isMergeGroup if (!isEditMode) { argumentPatternField.text = if (isMergeGroup) MERGE_TOOL_DEFAULT_ARGUMENT_PATTERN else DIFF_TOOL_DEFAULT_ARGUMENT_PATTERN } argumentPatternDescription.text = if (isMergeGroup) createDescription(ExternalToolGroup.MERGE_TOOL) else createDescription(ExternalToolGroup.DIFF_TOOL) listener(isMergeGroup) } } override fun invoke(): Boolean { val item = groupField.selectedItem as ExternalToolGroup return item == ExternalToolGroup.MERGE_TOOL } }) } row { argumentPatternDescription = comment(createDescription(ExternalToolGroup.DIFF_TOOL), DEFAULT_COMMENT_WIDTH).component } row { val isMergeGroup = isMergeTrustExitCode.isVisible cell(testDiffButton).visible(!isMergeGroup) cell(testThreeSideDiffButton).visible(!isMergeGroup) cell(testMergeButton).visible(isMergeGroup) }.topGap(TopGap.MEDIUM) row { cell(toolOutputEditor.component) .align(Align.FILL) .applyToComponent { preferredSize = JBUI.size(400, 150) } }.resizableRow() } fun createExternalTool(): ExternalTool = ExternalTool(toolNameField.text, programPathField.text, argumentPatternField.text, isMergeTrustExitCode.isVisible && isMergeTrustExitCode.isSelected, groupField.item) fun getToolGroup(): ExternalToolGroup = groupField.item private fun toolFieldValidation(toolGroup: ExternalToolGroup, toolName: String): ValidationInfo? { if (toolName.isEmpty()) { return ValidationInfo(DiffBundle.message("settings.external.tool.tree.validation.empty")) } if (isToolAlreadyExist(toolGroup, toolName) && toolName != oldToolName) { return ValidationInfo(DiffBundle.message("settings.external.tool.tree.validation.already.exist", toolGroup, toolName)) } return null } private fun isToolAlreadyExist(toolGroup: ExternalToolGroup, toolName: String): Boolean { val isNodeExist = TreeUtil.findNode(findGroupNode(toolGroup)) { node -> when (val externalTool = node.userObject) { is ExternalTool -> externalTool.name == toolName else -> false // skip root } } return isNodeExist != null } @NlsContexts.DetailedDescription private fun createDescription(toolGroup: ExternalToolGroup): String { val title = DiffBundle.message("settings.external.tools.parameters.description") val argumentPattern = when (toolGroup) { ExternalToolGroup.DIFF_TOOL -> DiffBundle.message("settings.external.tools.parameters.diff") ExternalToolGroup.MERGE_TOOL -> DiffBundle.message("settings.external.tools.parameters.merge") } return "$title<br>$argumentPattern" } private fun showTestDiff() { ExternalDiffToolUtil.testDiffTool2(null, createExternalTool(), resetToolOutputConsole()) } private fun showTestThreeDiff() { ExternalDiffToolUtil.testDiffTool3(null, createExternalTool(), resetToolOutputConsole()) } private fun showTestMerge() { ExternalDiffToolUtil.testMergeTool(null, createExternalTool(), resetToolOutputConsole()) } @RequiresEdt private fun resetToolOutputConsole(): ExternalDiffToolUtil.TestOutputConsole { toolOutputConsole?.let { Disposer.dispose(it) } toolOutputConsole = MyTestOutputConsole(toolOutputEditor) return toolOutputConsole!! } } private fun DefaultTreeModel.toMap(): MutableMap<ExternalToolGroup, List<ExternalTool>> { val root = this.root as DefaultMutableTreeNode val model = mutableMapOf<ExternalToolGroup, List<ExternalTool>>() for (group in root.children()) { if (group.childCount == 0) continue val groupNode = group as DefaultMutableTreeNode val tools = mutableListOf<ExternalTool>() for (child in group.children()) { val childNode = child as DefaultMutableTreeNode val tool = childNode.userObject as ExternalTool tools.add(tool) } model[groupNode.userObject as ExternalToolGroup] = tools } return model } private fun DefaultTreeModel.update(value: Map<ExternalToolGroup, List<ExternalTool>>) { val root = this.root as DefaultMutableTreeNode root.removeAllChildren() value.toSortedMap().forEach { (group, tools) -> if (tools.isEmpty()) return@forEach val groupNode = DefaultMutableTreeNode(group) tools.forEach { groupNode.add(DefaultMutableTreeNode(it)) } insertNodeInto(groupNode, root, root.childCount) } nodeStructureChanged(root) } private fun ListTableModel<ExternalDiffSettings.ExternalToolConfiguration>.updateEntities( toolGroup: ExternalToolGroup, oldTool: ExternalTool, newTool: ExternalTool ) { items.forEach { configuration -> if (toolGroup == ExternalToolGroup.DIFF_TOOL) { if (configuration.diffToolName == oldTool.name) { configuration.diffToolName = newTool.name } } else { if (configuration.mergeToolName == oldTool.name) { configuration.mergeToolName = newTool.name } } } } companion object { private const val DIFF_TOOL_DEFAULT_ARGUMENT_PATTERN = "%1 %2 %3" private const val MERGE_TOOL_DEFAULT_ARGUMENT_PATTERN = "%1 %2 %3 %4" } private class MyTestOutputConsole(private val editor: Editor) : ExternalDiffToolUtil.TestOutputConsole, Disposable { private val document = editor.document private val modalityState = ModalityState.stateForComponent(editor.component) private var isDisposed: Boolean = false private var wasTerminated: Boolean = false // better handling for out-of-order events init { document.setText("") } override fun getComponent(): JComponent = editor.component override fun appendOutput(outputType: Key<*>, line: String) { appendText("$outputType: $line", false) } override fun processTerminated(exitCode: Int) { appendText(DiffBundle.message("settings.external.tools.test.process.exit.text", exitCode), true) } private fun appendText(text: String, isTermination: Boolean) { runInEdt(modalityState) { if (isDisposed) return@runInEdt // the next test session has started if (isTermination) wasTerminated = true val offset = if (!isTermination && wasTerminated && document.lineCount > 1) { // the last line is termination line, insert output next-to-last-line document.getLineStartOffset(document.lineCount - 2) // -2, as process termination line also ends with \n } else { // insert into the end document.textLength } val line = if (text.endsWith('\n')) text else text + '\n' document.insertString(offset, line) } } override fun dispose() { isDisposed = true } } }
apache-2.0
e1ceb2ab35028ebd93b18b627d0a1b3e
37.416981
126
0.691208
5.147914
false
true
false
false
GunoH/intellij-community
plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/operators/InvokeOperatorReferenceSearcher.kt
4
3266
// 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.search.usagesSearch.operators import com.intellij.openapi.components.service import com.intellij.openapi.components.serviceOrNull import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.search.SearchRequestCollector import com.intellij.psi.search.SearchScope import com.intellij.util.Processor import org.jetbrains.kotlin.idea.references.KtInvokeFunctionReference import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.psiUtil.isExtensionDeclaration import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance import org.jetbrains.uast.UMethod import org.jetbrains.uast.UastContext import org.jetbrains.uast.convertOpt class InvokeOperatorReferenceSearcher( targetFunction: PsiElement, searchScope: SearchScope, consumer: Processor<in PsiReference>, optimizer: SearchRequestCollector, options: KotlinReferencesSearchOptions ) : OperatorReferenceSearcher<KtCallExpression>(targetFunction, searchScope, consumer, optimizer, options, wordsToSearch = emptyList()) { private val callArgumentsSize: Int? init { val uastContext = targetFunction.project.serviceOrNull<UastContext>() callArgumentsSize = when { uastContext != null -> { val uMethod = uastContext.convertOpt<UMethod>(targetDeclaration, null) val uastParameters = uMethod?.uastParameters if (uastParameters != null) { val isStableNumberOfArguments = uastParameters.none { uParameter -> @Suppress("UElementAsPsi") uParameter.uastInitializer != null || uParameter.isVarArgs } if (isStableNumberOfArguments) { val numberOfArguments = uastParameters.size when { targetFunction.isExtensionDeclaration() -> numberOfArguments - 1 else -> numberOfArguments } } else { null } } else { null } } else -> null } } override fun processPossibleReceiverExpression(expression: KtExpression) { val callExpression = expression.parent as? KtCallExpression ?: return processReferenceElement(callExpression) } override fun isReferenceToCheck(ref: PsiReference) = ref is KtInvokeFunctionReference override fun extractReference(element: KtElement): PsiReference? { val callExpression = element as? KtCallExpression ?: return null if (callArgumentsSize != null && callArgumentsSize != callExpression.valueArguments.size) { return null } return callExpression.references.firstIsInstance<KtInvokeFunctionReference>() } }
apache-2.0
22d913d96100d10e96f5dc5f1d8a9294
40.35443
158
0.683099
5.75
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/keyvalue/DonationsValues.kt
1
13432
package org.thoughtcrime.securesms.keyvalue import androidx.annotation.WorkerThread import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.subjects.BehaviorSubject import io.reactivex.rxjava3.subjects.Subject import org.signal.core.util.logging.Log import org.signal.donations.StripeApi import org.thoughtcrime.securesms.badges.Badges import org.thoughtcrime.securesms.badges.models.Badge import org.thoughtcrime.securesms.database.model.databaseprotos.BadgeList import org.thoughtcrime.securesms.jobs.SubscriptionReceiptRequestResponseJob import org.thoughtcrime.securesms.payments.currency.CurrencyUtil import org.thoughtcrime.securesms.subscription.LevelUpdateOperation import org.thoughtcrime.securesms.subscription.Subscriber import org.whispersystems.signalservice.api.subscriptions.ActiveSubscription import org.whispersystems.signalservice.api.subscriptions.IdempotencyKey import org.whispersystems.signalservice.api.subscriptions.SubscriberId import org.whispersystems.signalservice.internal.util.JsonUtil import java.util.Currency import java.util.Locale import java.util.concurrent.TimeUnit internal class DonationsValues internal constructor(store: KeyValueStore) : SignalStoreValues(store) { companion object { private val TAG = Log.tag(DonationsValues::class.java) private const val KEY_SUBSCRIPTION_CURRENCY_CODE = "donation.currency.code" private const val KEY_CURRENCY_CODE_ONE_TIME = "donation.currency.code.boost" private const val KEY_SUBSCRIBER_ID_PREFIX = "donation.subscriber.id." private const val KEY_LAST_KEEP_ALIVE_LAUNCH = "donation.last.successful.ping" private const val KEY_LAST_END_OF_PERIOD_SECONDS = "donation.last.end.of.period" private const val EXPIRED_BADGE = "donation.expired.badge" private const val EXPIRED_GIFT_BADGE = "donation.expired.gift.badge" private const val USER_MANUALLY_CANCELLED = "donation.user.manually.cancelled" private const val KEY_LEVEL_OPERATION_PREFIX = "donation.level.operation." private const val KEY_LEVEL_HISTORY = "donation.level.history" private const val DISPLAY_BADGES_ON_PROFILE = "donation.display.badges.on.profile" private const val SUBSCRIPTION_REDEMPTION_FAILED = "donation.subscription.redemption.failed" private const val SHOULD_CANCEL_SUBSCRIPTION_BEFORE_NEXT_SUBSCRIBE_ATTEMPT = "donation.should.cancel.subscription.before.next.subscribe.attempt" private const val SUBSCRIPTION_CANCELATION_CHARGE_FAILURE = "donation.subscription.cancelation.charge.failure" private const val SUBSCRIPTION_CANCELATION_REASON = "donation.subscription.cancelation.reason" private const val SUBSCRIPTION_CANCELATION_TIMESTAMP = "donation.subscription.cancelation.timestamp" private const val SUBSCRIPTION_CANCELATION_WATERMARK = "donation.subscription.cancelation.watermark" private const val SHOW_CANT_PROCESS_DIALOG = "show.cant.process.dialog" } override fun onFirstEverAppLaunch() = Unit override fun getKeysToIncludeInBackup(): MutableList<String> = mutableListOf( KEY_CURRENCY_CODE_ONE_TIME, KEY_LAST_KEEP_ALIVE_LAUNCH, KEY_LAST_END_OF_PERIOD_SECONDS, SHOULD_CANCEL_SUBSCRIPTION_BEFORE_NEXT_SUBSCRIBE_ATTEMPT, SUBSCRIPTION_CANCELATION_REASON, SUBSCRIPTION_CANCELATION_TIMESTAMP, SUBSCRIPTION_CANCELATION_WATERMARK, SHOW_CANT_PROCESS_DIALOG ) private val subscriptionCurrencyPublisher: Subject<Currency> by lazy { BehaviorSubject.createDefault(getSubscriptionCurrency()) } val observableSubscriptionCurrency: Observable<Currency> by lazy { subscriptionCurrencyPublisher } private val oneTimeCurrencyPublisher: Subject<Currency> by lazy { BehaviorSubject.createDefault(getOneTimeCurrency()) } val observableOneTimeCurrency: Observable<Currency> by lazy { oneTimeCurrencyPublisher } fun getSubscriptionCurrency(): Currency { val currencyCode = getString(KEY_SUBSCRIPTION_CURRENCY_CODE, null) val currency: Currency? = if (currencyCode == null) { val localeCurrency = CurrencyUtil.getCurrencyByLocale(Locale.getDefault()) if (localeCurrency == null) { val e164: String? = SignalStore.account().e164 if (e164 == null) { null } else { CurrencyUtil.getCurrencyByE164(e164) } } else { localeCurrency } } else { CurrencyUtil.getCurrencyByCurrencyCode(currencyCode) } return if (currency != null && StripeApi.Validation.supportedCurrencyCodes.contains(currency.currencyCode.uppercase(Locale.ROOT))) { currency } else { Currency.getInstance("USD") } } fun getOneTimeCurrency(): Currency { val oneTimeCurrency = getString(KEY_CURRENCY_CODE_ONE_TIME, null) return if (oneTimeCurrency == null) { val currency = getSubscriptionCurrency() setOneTimeCurrency(currency) currency } else { Currency.getInstance(oneTimeCurrency) } } fun setOneTimeCurrency(currency: Currency) { putString(KEY_CURRENCY_CODE_ONE_TIME, currency.currencyCode) oneTimeCurrencyPublisher.onNext(currency) } fun getSubscriber(currency: Currency): Subscriber? { val currencyCode = currency.currencyCode val subscriberIdBytes = getBlob("$KEY_SUBSCRIBER_ID_PREFIX$currencyCode", null) return if (subscriberIdBytes == null) { null } else { Subscriber(SubscriberId.fromBytes(subscriberIdBytes), currencyCode) } } fun getSubscriber(): Subscriber? { return getSubscriber(getSubscriptionCurrency()) } fun requireSubscriber(): Subscriber { return getSubscriber() ?: throw Exception("Subscriber ID is not set.") } fun setSubscriber(subscriber: Subscriber) { Log.i(TAG, "Setting subscriber for currency ${subscriber.currencyCode}", Exception(), true) val currencyCode = subscriber.currencyCode store.beginWrite() .putBlob("$KEY_SUBSCRIBER_ID_PREFIX$currencyCode", subscriber.subscriberId.bytes) .putString(KEY_SUBSCRIPTION_CURRENCY_CODE, currencyCode) .apply() subscriptionCurrencyPublisher.onNext(Currency.getInstance(currencyCode)) } fun getLevelOperation(level: String): LevelUpdateOperation? { val idempotencyKey = getBlob("${KEY_LEVEL_OPERATION_PREFIX}$level", null) return if (idempotencyKey != null) { LevelUpdateOperation(IdempotencyKey.fromBytes(idempotencyKey), level) } else { null } } fun setLevelOperation(levelUpdateOperation: LevelUpdateOperation) { addLevelToHistory(levelUpdateOperation.level) putBlob("$KEY_LEVEL_OPERATION_PREFIX${levelUpdateOperation.level}", levelUpdateOperation.idempotencyKey.bytes) } private fun getLevelHistory(): Set<String> { return getString(KEY_LEVEL_HISTORY, "").split(",").toSet() } private fun addLevelToHistory(level: String) { val levels = getLevelHistory() + level putString(KEY_LEVEL_HISTORY, levels.joinToString(",")) } fun clearLevelOperations() { val levelHistory = getLevelHistory() val write = store.beginWrite() for (level in levelHistory) { write.remove("${KEY_LEVEL_OPERATION_PREFIX}$level") } write.apply() } fun setExpiredBadge(badge: Badge?) { if (badge != null) { putBlob(EXPIRED_BADGE, Badges.toDatabaseBadge(badge).toByteArray()) } else { remove(EXPIRED_BADGE) } } fun getExpiredBadge(): Badge? { val badgeBytes = getBlob(EXPIRED_BADGE, null) ?: return null return Badges.fromDatabaseBadge(BadgeList.Badge.parseFrom(badgeBytes)) } fun setExpiredGiftBadge(badge: Badge?) { if (badge != null) { putBlob(EXPIRED_GIFT_BADGE, Badges.toDatabaseBadge(badge).toByteArray()) } else { remove(EXPIRED_GIFT_BADGE) } } fun getExpiredGiftBadge(): Badge? { val badgeBytes = getBlob(EXPIRED_GIFT_BADGE, null) ?: return null return Badges.fromDatabaseBadge(BadgeList.Badge.parseFrom(badgeBytes)) } fun getLastKeepAliveLaunchTime(): Long { return getLong(KEY_LAST_KEEP_ALIVE_LAUNCH, 0L) } fun setLastKeepAliveLaunchTime(timestamp: Long) { putLong(KEY_LAST_KEEP_ALIVE_LAUNCH, timestamp) } fun getLastEndOfPeriod(): Long { return getLong(KEY_LAST_END_OF_PERIOD_SECONDS, 0L) } fun setLastEndOfPeriod(timestamp: Long) { putLong(KEY_LAST_END_OF_PERIOD_SECONDS, timestamp) } /** * True if the local user is likely a sustainer, otherwise false. Note the term 'likely', because this is based on cached data. Any serious decisions that * rely on this should make a network request to determine subscription status. */ fun isLikelyASustainer(): Boolean { return TimeUnit.SECONDS.toMillis(getLastEndOfPeriod()) > System.currentTimeMillis() } fun isUserManuallyCancelled(): Boolean { return getBoolean(USER_MANUALLY_CANCELLED, false) } fun markUserManuallyCancelled() { putBoolean(USER_MANUALLY_CANCELLED, true) } fun clearUserManuallyCancelled() { remove(USER_MANUALLY_CANCELLED) } fun setDisplayBadgesOnProfile(enabled: Boolean) { putBoolean(DISPLAY_BADGES_ON_PROFILE, enabled) } fun getDisplayBadgesOnProfile(): Boolean { return getBoolean(DISPLAY_BADGES_ON_PROFILE, false) } fun getSubscriptionRedemptionFailed(): Boolean { return getBoolean(SUBSCRIPTION_REDEMPTION_FAILED, false) } fun markSubscriptionRedemptionFailed() { Log.w(TAG, "markSubscriptionRedemptionFailed()", Throwable(), true) putBoolean(SUBSCRIPTION_REDEMPTION_FAILED, true) } fun clearSubscriptionRedemptionFailed() { putBoolean(SUBSCRIPTION_REDEMPTION_FAILED, false) } fun setUnexpectedSubscriptionCancelationChargeFailure(chargeFailure: ActiveSubscription.ChargeFailure?) { if (chargeFailure == null) { remove(SUBSCRIPTION_CANCELATION_CHARGE_FAILURE) } else { putString(SUBSCRIPTION_CANCELATION_CHARGE_FAILURE, JsonUtil.toJson(chargeFailure)) } } fun getUnexpectedSubscriptionCancelationChargeFailure(): ActiveSubscription.ChargeFailure? { val json = getString(SUBSCRIPTION_CANCELATION_CHARGE_FAILURE, null) return if (json.isNullOrEmpty()) { null } else { JsonUtil.fromJson(json, ActiveSubscription.ChargeFailure::class.java) } } var unexpectedSubscriptionCancelationReason: String? by stringValue(SUBSCRIPTION_CANCELATION_REASON, null) var unexpectedSubscriptionCancelationTimestamp: Long by longValue(SUBSCRIPTION_CANCELATION_TIMESTAMP, 0L) var unexpectedSubscriptionCancelationWatermark: Long by longValue(SUBSCRIPTION_CANCELATION_WATERMARK, 0L) @get:JvmName("showCantProcessDialog") var showCantProcessDialog: Boolean by booleanValue(SHOW_CANT_PROCESS_DIALOG, true) /** * Denotes that the previous attempt to subscribe failed in some way. Either an * automatic renewal failed resulting in an unexpected expiration, or payment failed * on Stripe's end. * * Before trying to resubscribe, we should first ensure there are no subscriptions set * on the server. Otherwise, we could get into a situation where the user is unable to * resubscribe. */ var shouldCancelSubscriptionBeforeNextSubscribeAttempt: Boolean get() = getBoolean(SHOULD_CANCEL_SUBSCRIPTION_BEFORE_NEXT_SUBSCRIBE_ATTEMPT, false) set(value) = putBoolean(SHOULD_CANCEL_SUBSCRIPTION_BEFORE_NEXT_SUBSCRIBE_ATTEMPT, value) /** * Consolidates a bunch of data clears that should occur whenever a user manually cancels their * subscription: * * 1. Clears keep-alive flag * 1. Clears level operation * 1. Marks the user as manually cancelled * 1. Clears out unexpected cancelation state * 1. Clears expired badge if it is for a subscription */ @WorkerThread fun updateLocalStateForManualCancellation() { synchronized(SubscriptionReceiptRequestResponseJob.MUTEX) { Log.d(TAG, "[updateLocalStateForManualCancellation] Clearing donation values.") setLastEndOfPeriod(0L) clearLevelOperations() markUserManuallyCancelled() shouldCancelSubscriptionBeforeNextSubscribeAttempt = false setUnexpectedSubscriptionCancelationChargeFailure(null) unexpectedSubscriptionCancelationReason = null unexpectedSubscriptionCancelationTimestamp = 0L val expiredBadge = getExpiredBadge() if (expiredBadge != null && expiredBadge.isSubscription()) { Log.d(TAG, "[updateLocalStateForManualCancellation] Clearing expired badge.") setExpiredBadge(null) } } } /** * Consolidates a bunch of data clears that should occur whenever a user begins a new subscription: * * 1. Manual cancellation marker * 1. Any set level operations * 1. Unexpected cancelation flags * 1. Expired badge, if it is of a subscription */ @WorkerThread fun updateLocalStateForLocalSubscribe() { synchronized(SubscriptionReceiptRequestResponseJob.MUTEX) { Log.d(TAG, "[updateLocalStateForLocalSubscribe] Clearing donation values.") clearUserManuallyCancelled() clearLevelOperations() shouldCancelSubscriptionBeforeNextSubscribeAttempt = false setUnexpectedSubscriptionCancelationChargeFailure(null) unexpectedSubscriptionCancelationReason = null unexpectedSubscriptionCancelationTimestamp = 0L val expiredBadge = getExpiredBadge() if (expiredBadge != null && expiredBadge.isSubscription()) { Log.d(TAG, "[updateLocalStateForLocalSubscribe] Clearing expired badge.") setExpiredBadge(null) } } } }
gpl-3.0
c6fe141d6cee89b49740f9f73d011a42
37.267806
156
0.749777
4.824713
false
false
false
false
ktorio/ktor
ktor-shared/ktor-websockets/common/src/io/ktor/websocket/FrameCommon.kt
1
5392
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.websocket import io.ktor.utils.io.charsets.* import io.ktor.utils.io.core.* import kotlinx.coroutines.* /** * A frame received or ready to be sent. It is not reusable and not thread-safe * @property fin is it final fragment, should be always `true` for control frames and if no fragmentation is used * @property frameType enum value * @property data - a frame content or fragment content * @property disposableHandle could be invoked when the frame is processed */ public expect sealed class Frame private constructor( fin: Boolean, frameType: FrameType, data: ByteArray, disposableHandle: DisposableHandle = NonDisposableHandle, rsv1: Boolean = false, rsv2: Boolean = false, rsv3: Boolean = false ) { public val fin: Boolean /** * First extension bit. */ public val rsv1: Boolean /** * Second extension bit. */ public val rsv2: Boolean /** * Third extension bit. */ public val rsv3: Boolean public val frameType: FrameType public val data: ByteArray public val disposableHandle: DisposableHandle /** * Represents an application level binary frame. * In a RAW web socket session a big text frame could be fragmented * (separated into several text frames so they have [fin] = false except the last one). * Note that usually there is no need to handle fragments unless you have a RAW web socket session. */ public class Binary public constructor( fin: Boolean, data: ByteArray, rsv1: Boolean = false, rsv2: Boolean = false, rsv3: Boolean = false ) : Frame { public constructor(fin: Boolean, data: ByteArray) public constructor(fin: Boolean, packet: ByteReadPacket) } /** * Represents an application level text frame. * In a RAW web socket session a big text frame could be fragmented * (separated into several text frames so they have [fin] = false except the last one). * Please note that a boundary between fragments could be in the middle of multi-byte (unicode) character * so don't apply String constructor to every fragment but use decoder loop instead of concatenate fragments first. * Note that usually there is no need to handle fragments unless you have a RAW web socket session. */ public class Text public constructor( fin: Boolean, data: ByteArray, rsv1: Boolean = false, rsv2: Boolean = false, rsv3: Boolean = false, ) : Frame { public constructor(fin: Boolean, data: ByteArray) public constructor(text: String) public constructor(fin: Boolean, packet: ByteReadPacket) } /** * Represents a low-level level close frame. It could be sent to indicate web socket session end. * Usually there is no need to send/handle it unless you have a RAW web socket session. */ public class Close(data: ByteArray) : Frame { public constructor(reason: CloseReason) public constructor(packet: ByteReadPacket) public constructor() } /** * Represents a low-level ping frame. Could be sent to test connection (peer should reply with [Pong]). * Usually there is no need to send/handle it unless you have a RAW web socket session. */ public class Ping(data: ByteArray) : Frame { public constructor(packet: ByteReadPacket) } /** * Represents a low-level pong frame. Should be sent in reply to a [Ping] frame. * Usually there is no need to send/handle it unless you have a RAW web socket session. */ public class Pong( data: ByteArray, disposableHandle: DisposableHandle = NonDisposableHandle ) : Frame { public constructor(packet: ByteReadPacket) } /** * Creates a frame copy */ public fun copy(): Frame public companion object { /** * Create a particular [Frame] instance by frame type */ public fun byType( fin: Boolean, frameType: FrameType, data: ByteArray, rsv1: Boolean, rsv2: Boolean, rsv3: Boolean ): Frame } } /** * Read text content from text frame. Shouldn't be used for fragmented frames: such frames need to be reassembled first */ public fun Frame.Text.readText(): String { require(fin) { "Text could be only extracted from non-fragmented frame" } return Charsets.UTF_8.newDecoder().decode(buildPacket { writeFully(data) }) } /** * Read binary content from a frame. For fragmented frames only returns this fragment. */ public fun Frame.readBytes(): ByteArray { return data.copyOf() } /** * Read close reason from close frame or null if no close reason provided */ @Suppress("CONFLICTING_OVERLOADS") public fun Frame.Close.readReason(): CloseReason? { if (data.size < 2) { return null } val packet = buildPacket { writeFully(data) } val code = packet.readShort() val message = packet.readText() return CloseReason(code, message) } internal object NonDisposableHandle : DisposableHandle { override fun dispose() {} override fun toString(): String = "NonDisposableHandle" }
apache-2.0
7f6e8e912ba630bdd265fd7a64018068
30.532164
119
0.663205
4.504595
false
false
false
false
marius-m/wt4
app/src/main/java/lt/markmerkk/widgets/help/html/StyledText.kt
1
1545
package lt.markmerkk.widgets.help.html class StyledText { private val mutableStyles: MutableList<StyleElement> = mutableListOf() fun elements(): List<StyleElement> { return mutableStyles .filter { it.text.isNotEmpty() } .toList() } fun text(): String { return elements() .map { it.text } .joinToString(separator = "") } fun appendTextBasic(text: String) { this.mutableStyles.add(ElementNoStyle(text = text)) } fun appendTextWithStyles(text: String, styles: Map<String, String>) { val indexStart: Int = text().length val indexEnd: Int = indexStart + text.length this.mutableStyles.add( ElementStyleBasic( text = text, styles = styles, range = IntRange( start = indexStart, endInclusive = indexEnd, ) ) ) } fun clear() { this.mutableStyles.clear() } sealed class StyleElement( val text: String, ) class ElementNoStyle( text: String, ) : StyleElement(text = text) class ElementStyleBasic( text: String, val styles: Map<String, String>, val range: IntRange, ) : StyleElement(text = text) { fun stylesAsString(): String { return styles .map { entry -> "%s: %s;".format(entry.key, entry.value) } .joinToString(separator = " ") } } }
apache-2.0
e95a56ac9cca115d816e624a9e2614ec
25.655172
74
0.533333
4.544118
false
false
false
false
google/android-fhir
demo/src/main/java/com/google/android/fhir/demo/ScreenerFragment.kt
1
4614
/* * Copyright 2021 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.fhir.demo import android.os.Bundle import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.widget.Toast import androidx.activity.addCallback import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.fragment.app.commit import androidx.fragment.app.viewModels import androidx.navigation.fragment.NavHostFragment import androidx.navigation.fragment.navArgs import com.google.android.fhir.datacapture.QuestionnaireFragment /** A fragment class to show screener questionnaire screen. */ class ScreenerFragment : Fragment(R.layout.screener_encounter_fragment) { private val viewModel: ScreenerViewModel by viewModels() private val args: ScreenerFragmentArgs by navArgs() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setUpActionBar() setHasOptionsMenu(true) updateArguments() onBackPressed() observeResourcesSaveAction() if (savedInstanceState == null) { addQuestionnaireFragment() } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.screen_encounter_fragment_menu, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_add_patient_submit -> { onSubmitAction() true } android.R.id.home -> { showCancelScreenerQuestionnaireAlertDialog() true } else -> super.onOptionsItemSelected(item) } } private fun setUpActionBar() { (requireActivity() as AppCompatActivity).supportActionBar?.apply { setDisplayHomeAsUpEnabled(true) } } private fun updateArguments() { requireArguments().putString(QUESTIONNAIRE_FILE_PATH_KEY, "screener-questionnaire.json") } private fun addQuestionnaireFragment() { val fragment = QuestionnaireFragment() fragment.arguments = bundleOf(QuestionnaireFragment.EXTRA_QUESTIONNAIRE_JSON_STRING to viewModel.questionnaire) childFragmentManager.commit { add(R.id.add_patient_container, fragment, QUESTIONNAIRE_FRAGMENT_TAG) } } private fun onSubmitAction() { val questionnaireFragment = childFragmentManager.findFragmentByTag(QUESTIONNAIRE_FRAGMENT_TAG) as QuestionnaireFragment viewModel.saveScreenerEncounter( questionnaireFragment.getQuestionnaireResponse(), args.patientId ) } private fun showCancelScreenerQuestionnaireAlertDialog() { val alertDialog: AlertDialog? = activity?.let { val builder = AlertDialog.Builder(it) builder.apply { setMessage(getString(R.string.cancel_questionnaire_message)) setPositiveButton(getString(android.R.string.yes)) { _, _ -> NavHostFragment.findNavController(this@ScreenerFragment).navigateUp() } setNegativeButton(getString(android.R.string.no)) { _, _ -> } } builder.create() } alertDialog?.show() } private fun onBackPressed() { activity?.onBackPressedDispatcher?.addCallback(viewLifecycleOwner) { showCancelScreenerQuestionnaireAlertDialog() } } private fun observeResourcesSaveAction() { viewModel.isResourcesSaved.observe(viewLifecycleOwner) { if (!it) { Toast.makeText(requireContext(), getString(R.string.inputs_missing), Toast.LENGTH_SHORT) .show() return@observe } Toast.makeText(requireContext(), getString(R.string.resources_saved), Toast.LENGTH_SHORT) .show() NavHostFragment.findNavController(this).navigateUp() } } companion object { const val QUESTIONNAIRE_FILE_PATH_KEY = "questionnaire-file-path-key" const val QUESTIONNAIRE_FRAGMENT_TAG = "questionnaire-fragment-tag" } }
apache-2.0
9bd128164bc8b0c6755ca2c5993ca1d9
31.957143
97
0.729085
4.727459
false
false
false
false
octarine-noise/BetterFoliage
src/main/kotlin/mods/betterfoliage/client/render/column/AbstractRenderer.kt
1
10649
package mods.betterfoliage.client.render.column import mods.betterfoliage.client.Client import mods.betterfoliage.client.chunk.ChunkOverlayLayer import mods.betterfoliage.client.chunk.ChunkOverlayManager import mods.betterfoliage.client.config.Config import mods.betterfoliage.client.integration.ShadersModIntegration.renderAs import mods.betterfoliage.client.render.* import mods.betterfoliage.client.render.column.ColumnLayerData.SpecialRender.BlockType.* import mods.betterfoliage.client.render.column.ColumnLayerData.SpecialRender.QuadrantType import mods.betterfoliage.client.render.column.ColumnLayerData.SpecialRender.QuadrantType.* import mods.octarinecore.client.render.* import mods.octarinecore.client.resource.ModelRenderRegistry import mods.octarinecore.common.* import net.minecraft.block.state.IBlockState import net.minecraft.client.renderer.BlockRendererDispatcher import net.minecraft.client.renderer.BufferBuilder import net.minecraft.client.renderer.texture.TextureAtlasSprite import net.minecraft.util.BlockRenderLayer import net.minecraft.util.EnumBlockRenderType import net.minecraft.util.EnumBlockRenderType.MODEL import net.minecraft.util.EnumFacing.* import net.minecraft.util.math.BlockPos import net.minecraft.world.IBlockAccess import net.minecraftforge.fml.relauncher.Side import net.minecraftforge.fml.relauncher.SideOnly @SideOnly(Side.CLIENT) @Suppress("NOTHING_TO_INLINE") abstract class AbstractRenderColumn(modId: String) : AbstractBlockRenderingHandler(modId) { /** The rotations necessary to bring the models in position for the 4 quadrants */ val quadrantRotations = Array(4) { Rotation.rot90[UP.ordinal] * it } // ============================ // Configuration // ============================ abstract val overlayLayer: ColumnRenderLayer abstract val connectPerpendicular: Boolean abstract val radiusSmall: Double abstract val radiusLarge: Double // ============================ // Models // ============================ val sideSquare = model { columnSideSquare(-0.5, 0.5) } val sideRoundSmall = model { columnSide(radiusSmall, -0.5, 0.5) } val sideRoundLarge = model { columnSide(radiusLarge, -0.5, 0.5) } val extendTopSquare = model { columnSideSquare(0.5, 0.5 + radiusLarge, topExtension(radiusLarge)) } val extendTopRoundSmall = model { columnSide(radiusSmall, 0.5, 0.5 + radiusLarge, topExtension(radiusLarge)) } val extendTopRoundLarge = model { columnSide(radiusLarge, 0.5, 0.5 + radiusLarge, topExtension(radiusLarge)) } inline fun extendTop(type: QuadrantType) = when(type) { SMALL_RADIUS -> extendTopRoundSmall.model LARGE_RADIUS -> extendTopRoundLarge.model SQUARE -> extendTopSquare.model INVISIBLE -> extendTopSquare.model else -> null } val extendBottomSquare = model { columnSideSquare(-0.5 - radiusLarge, -0.5, bottomExtension(radiusLarge)) } val extendBottomRoundSmall = model { columnSide(radiusSmall, -0.5 - radiusLarge, -0.5, bottomExtension(radiusLarge)) } val extendBottomRoundLarge = model { columnSide(radiusLarge, -0.5 - radiusLarge, -0.5, bottomExtension(radiusLarge)) } inline fun extendBottom(type: QuadrantType) = when (type) { SMALL_RADIUS -> extendBottomRoundSmall.model LARGE_RADIUS -> extendBottomRoundLarge.model SQUARE -> extendBottomSquare.model INVISIBLE -> extendBottomSquare.model else -> null } val topSquare = model { columnLidSquare() } val topRoundSmall = model { columnLid(radiusSmall) } val topRoundLarge = model { columnLid(radiusLarge) } inline fun flatTop(type: QuadrantType) = when(type) { SMALL_RADIUS -> topRoundSmall.model LARGE_RADIUS -> topRoundLarge.model SQUARE -> topSquare.model INVISIBLE -> topSquare.model else -> null } val bottomSquare = model { columnLidSquare() { it.rotate(rot(EAST) * 2 + rot(UP)).mirrorUV(true, true) } } val bottomRoundSmall = model { columnLid(radiusSmall) { it.rotate(rot(EAST) * 2 + rot(UP)).mirrorUV(true, true) } } val bottomRoundLarge = model { columnLid(radiusLarge) { it.rotate(rot(EAST) * 2 + rot(UP)).mirrorUV(true, true) } } inline fun flatBottom(type: QuadrantType) = when(type) { SMALL_RADIUS -> bottomRoundSmall.model LARGE_RADIUS -> bottomRoundLarge.model SQUARE -> bottomSquare.model INVISIBLE -> bottomSquare.model else -> null } val transitionTop = model { mix(sideRoundLarge.model, sideRoundSmall.model) { it > 1 } } val transitionBottom = model { mix(sideRoundSmall.model, sideRoundLarge.model) { it > 1 } } inline fun continuous(q1: QuadrantType, q2: QuadrantType) = q1 == q2 || ((q1 == SQUARE || q1 == INVISIBLE) && (q2 == SQUARE || q2 == INVISIBLE)) @Suppress("NON_EXHAUSTIVE_WHEN") override fun render(ctx: BlockContext, dispatcher: BlockRendererDispatcher, renderer: BufferBuilder, layer: BlockRenderLayer): Boolean { val roundLog = ChunkOverlayManager.get(overlayLayer, ctx.world!!, ctx.pos) when(roundLog) { ColumnLayerData.SkipRender -> return true ColumnLayerData.NormalRender -> return renderWorldBlockBase(ctx, dispatcher, renderer, null) ColumnLayerData.ResolveError, null -> { Client.logRenderError(ctx.blockState(Int3.zero), ctx.pos) return renderWorldBlockBase(ctx, dispatcher, renderer, null) } } // if log axis is not defined and "Default to vertical" config option is not set, render normally if ((roundLog as ColumnLayerData.SpecialRender).column.axis == null && !overlayLayer.defaultToY) { return renderWorldBlockBase(ctx, dispatcher, renderer, null) } // get AO data modelRenderer.updateShading(Int3.zero, allFaces) val baseRotation = rotationFromUp[((roundLog.column.axis ?: Axis.Y) to AxisDirection.POSITIVE).face.ordinal] renderAs(ctx.blockState(Int3.zero), MODEL, renderer) { quadrantRotations.forEachIndexed { idx, quadrantRotation -> // set rotation for the current quadrant val rotation = baseRotation + quadrantRotation // disallow sharp discontinuities in the chamfer radius, or tapering-in where inappropriate if (roundLog.quadrants[idx] == LARGE_RADIUS && roundLog.upType == PARALLEL && roundLog.quadrantsTop[idx] != LARGE_RADIUS && roundLog.downType == PARALLEL && roundLog.quadrantsBottom[idx] != LARGE_RADIUS) { roundLog.quadrants[idx] = SMALL_RADIUS } // render side of current quadrant val sideModel = when (roundLog.quadrants[idx]) { SMALL_RADIUS -> sideRoundSmall.model LARGE_RADIUS -> if (roundLog.upType == PARALLEL && roundLog.quadrantsTop[idx] == SMALL_RADIUS) transitionTop.model else if (roundLog.downType == PARALLEL && roundLog.quadrantsBottom[idx] == SMALL_RADIUS) transitionBottom.model else sideRoundLarge.model SQUARE -> sideSquare.model else -> null } if (sideModel != null) modelRenderer.render( renderer, sideModel, rotation, icon = roundLog.column.side, postProcess = noPost ) // render top and bottom end of current quadrant var upModel: Model? = null var downModel: Model? = null var upIcon = roundLog.column.top var downIcon = roundLog.column.bottom var isLidUp = true var isLidDown = true when (roundLog.upType) { NONSOLID -> upModel = flatTop(roundLog.quadrants[idx]) PERPENDICULAR -> { if (!connectPerpendicular) { upModel = flatTop(roundLog.quadrants[idx]) } else { upIcon = roundLog.column.side upModel = extendTop(roundLog.quadrants[idx]) isLidUp = false } } PARALLEL -> { if (!continuous(roundLog.quadrants[idx], roundLog.quadrantsTop[idx])) { if (roundLog.quadrants[idx] == SQUARE || roundLog.quadrants[idx] == INVISIBLE) { upModel = topSquare.model } } } } when (roundLog.downType) { NONSOLID -> downModel = flatBottom(roundLog.quadrants[idx]) PERPENDICULAR -> { if (!connectPerpendicular) { downModel = flatBottom(roundLog.quadrants[idx]) } else { downIcon = roundLog.column.side downModel = extendBottom(roundLog.quadrants[idx]) isLidDown = false } } PARALLEL -> { if (!continuous(roundLog.quadrants[idx], roundLog.quadrantsBottom[idx]) && (roundLog.quadrants[idx] == SQUARE || roundLog.quadrants[idx] == INVISIBLE)) { downModel = bottomSquare.model } } } if (upModel != null) modelRenderer.render( renderer, upModel, rotation, icon = upIcon, postProcess = { _, _, _, _, _ -> if (isLidUp) { rotateUV(idx + if (roundLog.column.axis == Axis.X) 1 else 0) } } ) if (downModel != null) modelRenderer.render( renderer, downModel, rotation, icon = downIcon, postProcess = { _, _, _, _, _ -> if (isLidDown) { rotateUV((if (roundLog.column.axis == Axis.X) 0 else 3) - idx) } } ) } } return true } }
mit
785310f517e1d01fb9deae8a0b161f2b
46.540179
140
0.587379
4.955328
false
false
false
false
Frederikam/FredBoat
FredBoat/src/main/java/fredboat/command/moderation/SoftbanCommand.kt
1
7558
/* * MIT License * * Copyright (c) 2017 Frederik Ar. Mikkelsen * * 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 fredboat.command.moderation import com.fredboat.sentinel.SentinelExchanges import com.fredboat.sentinel.entities.ModRequest import com.fredboat.sentinel.entities.ModRequestType import fredboat.messaging.internal.Context import fredboat.perms.Permission import fredboat.util.DiscordUtil import fredboat.util.TextUtils import fredboat.util.extension.escapeAndDefuse import kotlinx.coroutines.reactive.awaitFirst import kotlinx.coroutines.reactive.awaitLast import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.amqp.core.MessageDeliveryMode import reactor.core.publisher.Mono class SoftbanCommand(name: String, vararg aliases: String) : DiscordModerationCommand(name, *aliases) { companion object { private val log: Logger = LoggerFactory.getLogger(SoftbanCommand::class.java) } override fun modAction(args: DiscordModerationCommand.ModActionInfo): Mono<Unit> { val deleteDays = if(args.isKeepMessages) 0 else DiscordModerationCommand.DEFAULT_DELETE_DAYS return args.context.sentinel.genericMonoSendAndReceive<String, Unit>( exchange = SentinelExchanges.REQUESTS, request = ModRequest( guildId = args.context.guild.id, userId = args.targetUser.id, type = ModRequestType.BAN, banDeleteDays = deleteDays, reason = args.formattedReason ), routingKey = args.context.routingKey, mayBeEmpty = true, deliveryMode = MessageDeliveryMode.PERSISTENT, transform = {} ) } private fun unbanAsync(args: DiscordModerationCommand.ModActionInfo) { args.context.sentinel.genericMonoSendAndReceive<String, Unit>( exchange = SentinelExchanges.REQUESTS, request = ModRequest( guildId = args.context.guild.id, userId = args.targetUser.id, type = ModRequestType.UNBAN ), routingKey = args.context.routingKey, mayBeEmpty = true, deliveryMode = MessageDeliveryMode.PERSISTENT, transform = {} ).doOnError { log.error("Failed to unban ${args.targetUser.id} while doing softban in ${args.context.guild}", it) }.subscribe() } override fun requiresMember(): Boolean { return false } override fun onSuccess(args: DiscordModerationCommand.ModActionInfo): () -> Unit { val successOutput = (args.context.i18nFormat("softbanSuccess", args.targetUser.asMention + " " + TextUtils.escapeAndDefuse(args.targetAsString())) + "\n" + TextUtils.escapeAndDefuse(args.plainReason)) return { unbanAsync(args) args.context.replyWithName(successOutput) } } override fun onFail(args: DiscordModerationCommand.ModActionInfo): (t: Throwable) -> Unit { val escapedTargetName = TextUtils.escapeAndDefuse(args.targetAsString()) return { t -> log.error("Failed to softban ${args.targetUser.id} from ${args.context.guild}", t) args.context.replyWithName(args.context.i18nFormat("modBanFail", args.targetUser.asMention + " " + escapedTargetName)) unbanAsync(args) } } override suspend fun checkAuthorizationWithFeedback(args: DiscordModerationCommand.ModActionInfo): Boolean { val context = args.context val targetMember = args.targetMember val mod = context.member //A softban is like a kick + clear messages, so check for those on the invoker if (!context.checkInvokerPermissionsWithFeedback(Permission.KICK_MEMBERS + Permission.MESSAGE_MANAGE)) return false //We do however need ban perms to do this if (!context.checkSelfPermissionsWithFeedback(Permission.BAN_MEMBERS)) return false // if the target user is NOT member of the guild AND banned, the invoker needs to have BAN perms, because it is // essentially an UNBAN, and we dont want to allow users to unban anyone with just kick perms if (targetMember == null) { var isUnban = false fetchBanlist(context).doOnNext { if(it.user == args.targetUser.raw) isUnban = false }.awaitLast() if (!isUnban) return false return context.checkInvokerPermissionsWithFeedback(Permission.BAN_MEMBERS) } if (mod == targetMember) { context.replyWithName(context.i18n("softbanFailSelf")) return false } if (targetMember.isOwner()) { context.replyWithName(context.i18n("softbanFailOwner")) return false } if (targetMember == args.context.guild.selfMember) { context.replyWithName(context.i18n("softbanFailMyself")) return false } val modRole = DiscordUtil.getHighestRolePosition(mod).awaitFirst() val targetRole = DiscordUtil.getHighestRolePosition(targetMember).awaitFirst() val selfRole = DiscordUtil.getHighestRolePosition(mod.guild.selfMember).awaitFirst() if (modRole <= targetRole && !mod.isOwner()) { context.replyWithName(context.i18nFormat("modFailUserHierarchy", targetMember.effectiveName.escapeAndDefuse())) return false } if (selfRole <= targetRole) { context.replyWithName(context.i18nFormat("modFailBotHierarchy", targetMember.effectiveName.escapeAndDefuse())) return false } return true } override fun dmForTarget(args: DiscordModerationCommand.ModActionInfo): String? { return args.context.i18nFormat("modActionTargetDmKicked", // a softban is like a kick "**${TextUtils.escapeMarkdown(args.context.guild.name)}**", "${TextUtils.asString(args.context.user)}\n${args.plainReason}" ) } override fun help(context: Context): String { return ("{0}{1} <user>\n" + "{0}{1} <user> <reason>\n" + "{0}{1} <user> <reason> --keep\n" + "#" + context.i18n("helpSoftbanCommand") + "\n" + context.i18nFormat("modKeepMessages", "--keep or -k")) } }
mit
1d7bc33366e6904967438c17c9e09664
41.460674
123
0.657449
4.826309
false
false
false
false
iSoron/uhabits
uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/models/Frequency.kt
1
1384
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker 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. * * Loop Habit Tracker 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 org.isoron.uhabits.core.models data class Frequency( var numerator: Int, var denominator: Int, ) { init { if (numerator == denominator) { denominator = 1 numerator = 1 } } fun toDouble(): Double { return numerator.toDouble() / denominator } companion object { @JvmField val DAILY = Frequency(1, 1) @JvmField val THREE_TIMES_PER_WEEK = Frequency(3, 7) @JvmField val TWO_TIMES_PER_WEEK = Frequency(2, 7) @JvmField val WEEKLY = Frequency(1, 7) } }
gpl-3.0
104b03552fec0bd2c2e71988352fc612
27.22449
78
0.655098
4.190909
false
false
false
false
nlgcoin/guldencoin-official
src/frontend/android/unity_wallet/app/src/main/java/com/gulden/unity_wallet/URIHandlerActivity.kt
2
2292
// Copyright (c) 2019 The Gulden developers // Authored by: Malcolm MacLeod ([email protected]), Willem de Jonge ([email protected]) // Distributed under the GULDEN software license, see the accompanying // file COPYING package com.gulden.unity_wallet import android.content.Intent import android.net.Uri import android.widget.Toast import com.gulden.unity_wallet.util.AppBaseActivity // URI handlers need unity core active to function - however as they may be called when app is closed it is necessary to manually start the core in some cases // All URI handlers therefore come via this transparent activity // Which takes care of detecting whether core is already active or not and then handles the URI appropriately class URIHandlerActivity : AppBaseActivity() { private fun toastAndExit() { Toast.makeText(this, getString(R.string.toast_warn_uri_attempt_before_wallet_creation), Toast.LENGTH_SHORT).show() finish() } override fun onWalletCreate() { toastAndExit() } private fun handleURIAndClose() { if ((intentUri != null) && (scheme != null)) { try { val recipient = createRecipient(intentUri.toString()) SendCoinsFragment.newInstance(recipient, true).show(supportFragmentManager, SendCoinsFragment::class.java.simpleName) } catch (e : Exception) { //TODO: Improve error handling here finish() } } } private var intentUri : Uri? = null private var scheme : String? = null private fun isValidGuldenUri(uri: Uri?): Boolean { uri?.run { scheme?.run { toLowerCase().run { return startsWith("gulden") || startsWith("guldencoin") || startsWith("iban") || startsWith("sepa") } } } return false } override fun onWalletReady() { intentUri = intent.data scheme = intentUri?.scheme if (Intent.ACTION_VIEW == intent.action && isValidGuldenUri(intentUri)) { handleURIAndClose() } else { finish() } } }
mit
b1b8df23c812309d621498d73cd1f2f1
29.972973
158
0.596859
4.755187
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/analytics/aggregated/internal/evaluator/IndicatorSQLEvaluator.kt
1
3170
/* * 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.analytics.aggregated.internal.evaluator import javax.inject.Inject import org.hisp.dhis.android.core.analytics.aggregated.MetadataItem import org.hisp.dhis.android.core.analytics.aggregated.internal.AnalyticsServiceEvaluationItem import org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator.indicatorengine.IndicatorSQLEngine internal class IndicatorSQLEvaluator @Inject constructor( private val indicatorEngine: IndicatorSQLEngine ) : AnalyticsEvaluator { override fun evaluate( evaluationItem: AnalyticsServiceEvaluationItem, metadata: Map<String, MetadataItem> ): String? { val indicator = IndicatorEvaluatorHelper.getIndicator(evaluationItem, metadata) val contextEvaluationItem = IndicatorEvaluatorHelper.getContextEvaluationItem(evaluationItem, indicator) return indicatorEngine.evaluateIndicator( indicator = indicator, contextEvaluationItem = contextEvaluationItem, contextMetadata = metadata ) } override fun getSql( evaluationItem: AnalyticsServiceEvaluationItem, metadata: Map<String, MetadataItem> ): String { val indicator = IndicatorEvaluatorHelper.getIndicator(evaluationItem, metadata) val contextEvaluationItem = IndicatorEvaluatorHelper.getContextEvaluationItem(evaluationItem, indicator) return indicatorEngine.getSql( indicator = indicator, contextEvaluationItem = contextEvaluationItem, contextMetadata = metadata ) } }
bsd-3-clause
53790e7aee452acd4bedf40af5e83afa
47.030303
112
0.759937
5.088283
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/CanBePrimaryConstructorPropertyInspection.kt
1
3982
// 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.inspections import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.MovePropertyToConstructorIntention import org.jetbrains.kotlin.idea.intentions.loopToCallChain.hasUsages import org.jetbrains.kotlin.idea.refactoring.isInterfaceClass import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull class CanBePrimaryConstructorPropertyInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return propertyVisitor(fun(property) { if (property.isLocal) return if (property.getter != null || property.setter != null || property.delegate != null) return val assigned = property.initializer as? KtReferenceExpression ?: return val context = assigned.analyze() val assignedDescriptor = context.get(BindingContext.REFERENCE_TARGET, assigned) as? ValueParameterDescriptor ?: return val containingConstructor = assignedDescriptor.containingDeclaration as? ClassConstructorDescriptor ?: return if (containingConstructor.containingDeclaration.isData) return val propertyTypeReference = property.typeReference val propertyType = context.get(BindingContext.TYPE, propertyTypeReference) if (propertyType != null && propertyType != assignedDescriptor.type) return val nameIdentifier = property.nameIdentifier ?: return if (nameIdentifier.text != assignedDescriptor.name.asString()) return val assignedParameter = DescriptorToSourceUtils.descriptorToDeclaration(assignedDescriptor) as? KtParameter ?: return val containingClassOrObject = property.containingClassOrObject ?: return if (containingClassOrObject !== assignedParameter.containingClassOrObject) return if (containingClassOrObject.isInterfaceClass()) return if (property.hasModifier(KtTokens.OPEN_KEYWORD) && containingClassOrObject is KtClass && containingClassOrObject.isOpen() && assignedParameter.isUsedInClassInitializer(containingClassOrObject) ) return holder.registerProblem( holder.manager.createProblemDescriptor( nameIdentifier, nameIdentifier, KotlinBundle.message("property.is.explicitly.assigned.to.parameter.0.can", assignedDescriptor.name), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly, MovePropertyToConstructorIntention() ) ) }) } private fun KtClass.isOpen(): Boolean { return hasModifier(KtTokens.OPEN_KEYWORD) || hasModifier(KtTokens.ABSTRACT_KEYWORD) || hasModifier(KtTokens.SEALED_KEYWORD) } private fun KtParameter.isUsedInClassInitializer(containingClass: KtClass): Boolean { val classInitializer = containingClass.body?.declarations?.firstIsInstanceOrNull<KtClassInitializer>() ?: return false return hasUsages(classInitializer) } }
apache-2.0
438d6aee7d34b91d6fcd0d5077731efa
52.106667
131
0.739327
5.91679
false
false
false
false
google/intellij-community
platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/ExtensionFieldEntityList.kt
2
2539
package com.intellij.workspaceModel.storage.entities.test.api import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity interface MainEntityList : WorkspaceEntity { val x: String //region generated code @GeneratedCodeApiVersion(1) interface Builder : MainEntityList, ModifiableWorkspaceEntity<MainEntityList>, ObjBuilder<MainEntityList> { override var entitySource: EntitySource override var x: String } companion object : Type<MainEntityList, Builder>() { operator fun invoke(x: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): MainEntityList { val builder = builder() builder.x = x builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: MainEntityList, modification: MainEntityList.Builder.() -> Unit) = modifyEntity( MainEntityList.Builder::class.java, entity, modification) var MainEntityList.Builder.child: @Child List<AttachedEntityList> by WorkspaceEntity.extension() //endregion interface AttachedEntityList : WorkspaceEntity { val ref: MainEntityList? val data: String //region generated code @GeneratedCodeApiVersion(1) interface Builder : AttachedEntityList, ModifiableWorkspaceEntity<AttachedEntityList>, ObjBuilder<AttachedEntityList> { override var entitySource: EntitySource override var ref: MainEntityList? override var data: String } companion object : Type<AttachedEntityList, Builder>() { operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): AttachedEntityList { val builder = builder() builder.data = data builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: AttachedEntityList, modification: AttachedEntityList.Builder.() -> Unit) = modifyEntity( AttachedEntityList.Builder::class.java, entity, modification) //endregion val MainEntityList.child: List<@Child AttachedEntityList> by WorkspaceEntity.extension()
apache-2.0
9aeb557049233311734c5b3f1b1da179
32.853333
134
0.771564
5.150101
false
false
false
false
JetBrains/intellij-community
platform/bootstrap/src/com/intellij/idea/Main.kt
1
6588
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("Main") @file:Suppress("ReplacePutWithAssignment") package com.intellij.idea import com.intellij.concurrency.IdeaForkJoinWorkerThreadFactory import com.intellij.diagnostic.* import com.intellij.ide.BootstrapBundle import com.intellij.ide.plugins.StartupAbortedException import com.intellij.ide.startup.StartupActionScriptManager import com.intellij.openapi.application.PathManager import com.jetbrains.JBR import kotlinx.coroutines.* import java.awt.GraphicsEnvironment import java.io.IOException import java.lang.invoke.MethodHandles import java.lang.invoke.MethodType import java.nio.file.Files import java.nio.file.Path import java.util.* import java.util.function.Supplier import kotlin.coroutines.AbstractCoroutineContextElement import kotlin.coroutines.CoroutineContext import kotlin.system.exitProcess fun main(rawArgs: Array<String>) { val startupTimings = LinkedHashMap<String, Long>(6) startupTimings.put("startup begin", System.nanoTime()) val args: List<String> = preProcessRawArgs(rawArgs) AppMode.setFlags(args) try { bootstrap(startupTimings) startupTimings.put("main scope creating", System.nanoTime()) runBlocking(rootTask()) { StartUpMeasurer.addTimings(startupTimings, "bootstrap") val appInitPreparationActivity = StartUpMeasurer.startActivity("app initialization preparation") val busyThread = Thread.currentThread() launch(CoroutineName("ForkJoin CommonPool configuration") + Dispatchers.Default) { IdeaForkJoinWorkerThreadFactory.setupForkJoinCommonPool(AppMode.isHeadless()) } // not IO-, but CPU-bound due to descrambling, don't use here IO dispatcher val appStarterDeferred = async(CoroutineName("main class loading") + Dispatchers.Default) { val aClass = AppStarter::class.java.classLoader.loadClass("com.intellij.idea.MainImpl") MethodHandles.lookup().findConstructor(aClass, MethodType.methodType(Void.TYPE)).invoke() as AppStarter } initProjectorIfNeeded(args) withContext(Dispatchers.Default + StartupAbortedExceptionHandler()) { StartUpMeasurer.appInitPreparationActivity = appInitPreparationActivity startApplication(args = args, appStarterDeferred = appStarterDeferred, mainScope = this@runBlocking, busyThread = busyThread) } awaitCancellation() } } catch (e: Throwable) { StartupErrorReporter.showMessage(BootstrapBundle.message("bootstrap.error.title.start.failed"), e) exitProcess(AppExitCodes.STARTUP_EXCEPTION) } } private fun initProjectorIfNeeded(args: List<String>) { if (args.isEmpty() || (AppMode.CWM_HOST_COMMAND != args[0] && AppMode.CWM_HOST_NO_LOBBY_COMMAND != args[0])) { return } if (!JBR.isProjectorUtilsSupported()) { error("JBR version 17.0.5b653.12 or later is required to run a remote-dev server") } runActivity("cwm host init") { JBR.getProjectorUtils().setLocalGraphicsEnvironmentProvider( Supplier { val projectorEnvClass = AppStarter::class.java.classLoader.loadClass("org.jetbrains.projector.awt.image.PGraphicsEnvironment") projectorEnvClass.getDeclaredMethod("getInstance").invoke(null) as GraphicsEnvironment }) val projectorMainClass = AppStarter::class.java.classLoader.loadClass("org.jetbrains.projector.server.ProjectorLauncher\$Starter") MethodHandles.privateLookupIn(projectorMainClass, MethodHandles.lookup()).findStatic( projectorMainClass, "runProjectorServer", MethodType.methodType(Boolean::class.javaPrimitiveType) ).invoke() } } private fun bootstrap(startupTimings: LinkedHashMap<String, Long>) { startupTimings.put("properties loading", System.nanoTime()) PathManager.loadProperties() startupTimings.put("plugin updates install", System.nanoTime()) // this check must be performed before system directories are locked if (!AppMode.isCommandLine() || java.lang.Boolean.getBoolean(AppMode.FORCE_PLUGIN_UPDATES)) { val configImportNeeded = !AppMode.isHeadless() && !Files.exists(Path.of(PathManager.getConfigPath())) if (!configImportNeeded) { // Consider following steps: // - user opens settings, and installs some plugins; // - the plugins are downloaded and saved somewhere; // - IDE prompts for restart; // - after restart, the plugins are moved to proper directories ("installed") by the next line. // TODO get rid of this: plugins should be installed before restarting the IDE installPluginUpdates() } } startupTimings.put("classloader init", System.nanoTime()) BootstrapClassLoaderUtil.initClassLoader(AppMode.isIsRemoteDevHost()) } private fun preProcessRawArgs(rawArgs: Array<String>): List<String> { if (rawArgs.size == 1 && rawArgs[0] == "%f") return emptyList() // Parse java properties from arguments and activate them val (propArgs, other) = rawArgs.partition { it.startsWith("-D") && it.contains("=") } propArgs.forEach { arg -> val (option, value) = arg.removePrefix("-D").split("=") System.setProperty(option, value) } return other } @Suppress("HardCodedStringLiteral") private fun installPluginUpdates() { try { // referencing `StartupActionScriptManager` is ok - a string constant will be inlined val scriptFile = Path.of(PathManager.getPluginTempPath(), StartupActionScriptManager.ACTION_SCRIPT_FILE) if (Files.isRegularFile(scriptFile)) { // load StartupActionScriptManager and all others related class (ObjectInputStream and so on loaded as part of class define) // only if there is an action script to execute StartupActionScriptManager.executeActionScript() } } catch (e: IOException) { StartupErrorReporter.showMessage( "Plugin Installation Error", """ The IDE failed to install or update some plugins. Please try again, and if the problem persists, please report it to https://jb.gg/ide/critical-startup-errors The cause: $e """.trimIndent(), false ) } } // separate class for nicer presentation in dumps private class StartupAbortedExceptionHandler : AbstractCoroutineContextElement(CoroutineExceptionHandler), CoroutineExceptionHandler { override fun handleException(context: CoroutineContext, exception: Throwable) { StartupAbortedException.processException(exception) } override fun toString() = "StartupAbortedExceptionHandler" }
apache-2.0
a8fd330ee89d3481a06b3201650f8f5b
39.925466
134
0.742107
4.729361
false
false
false
false
dinosaurwithakatana/injection-helper
processor/src/main/java/io/dwak/injectionhelper/InjectionHelperBindingClass.kt
1
1908
package io.dwak.injectionhelper import com.squareup.javapoet.ClassName import com.squareup.javapoet.JavaFile import com.squareup.javapoet.MethodSpec import com.squareup.javapoet.ParameterSpec import com.squareup.javapoet.TypeName import com.squareup.javapoet.TypeSpec import java.io.IOException import javax.annotation.processing.Filer import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.element.Element import javax.lang.model.element.Modifier class InjectionHelperBindingClass(private val classPackage: String, private val className: String, private val targetClass: String, private val processingEnv: ProcessingEnvironment) { companion object { const val SUFFIX = "InjectionHelper" const val METHOD_NAME = "inject" } private val bindings = hashMapOf<String, FieldBinding>() fun createAndAddBinding(element: Element) { val binding = FieldBinding(element) bindings.put(binding.name, binding) } fun generate(): TypeSpec { val classBuilder = TypeSpec.classBuilder(className) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) val injectBuilder = MethodSpec.methodBuilder(METHOD_NAME) .addParameter(ParameterSpec.builder(ClassName.get(classPackage, targetClass), "target") .build()) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(TypeName.VOID) bindings.values .forEach { injectBuilder.addParameter(ParameterSpec.builder(ClassName.get(it.type), it.name).build()) injectBuilder.addStatement("target.${it.name} = ${it.name}") } return classBuilder.addMethod(injectBuilder.build()) .build() } @Throws(IOException::class) fun writeToFiler(filer: Filer) { JavaFile.builder(classPackage, generate()).build().writeTo(filer) } }
apache-2.0
f2a56b58f990d5ae2ab990ed7532e652
33.709091
100
0.708595
4.687961
false
false
false
false
stupacki/MultiFunctions
multi-functions/src/test/kotlin/io/multifunctions/MultiMapNotNullSpec.kt
1
4413
package io.multifunctions import io.kotest.core.spec.style.WordSpec import io.kotest.matchers.shouldBe import io.multifunctions.models.Hepta import io.multifunctions.models.Hexa import io.multifunctions.models.Penta import io.multifunctions.models.Quad internal class MultiMapNotNullSpec : WordSpec() { init { "MultiMapNotNull" should { "produce a correct mapping from Pair" { val testData = listOf(Pair("one", "two")) testData mapNotNull { one, two -> one shouldBe "one" two shouldBe "two" Pair(one, two) } shouldBe testData } "produce a correct mapping from Triple" { val testData = listOf(Triple("one", "two", "three")) testData mapNotNull { one, two, three -> one shouldBe "one" two shouldBe "two" three shouldBe "three" Triple(one, two, three) } shouldBe testData } "produce a correct mapping from Quad" { val testData = listOf(Quad("one", "two", "three", "four")) testData mapNotNull { one, two, three, four -> one shouldBe "one" two shouldBe "two" three shouldBe "three" four shouldBe "four" Quad(one, two, three, four) } shouldBe testData } "produce a correct mapping from Penta" { val testData = listOf(Penta("one", "two", "three", "four", "five")) testData mapNotNull { one, two, three, four, five -> one shouldBe "one" two shouldBe "two" three shouldBe "three" four shouldBe "four" five shouldBe "five" Penta(one, two, three, four, five) } shouldBe testData } "produce a correct mapping from Hexa" { val testData = listOf(Hexa("one", "two", "three", "four", "five", "six")) testData mapNotNull { one, two, three, four, five, six -> one shouldBe "one" two shouldBe "two" three shouldBe "three" four shouldBe "four" five shouldBe "five" six shouldBe "six" Hexa(one, two, three, four, five, six) } shouldBe testData } "produce a correct mapping from Hepta" { val testData = listOf(Hepta("one", "two", "three", "four", "five", "six", "seven")) testData mapNotNull { one, two, three, four, five, six, seven -> one shouldBe "one" two shouldBe "two" three shouldBe "three" four shouldBe "four" five shouldBe "five" six shouldBe "six" seven shouldBe "seven" Hepta(one, two, three, four, five, six, seven) } shouldBe testData } "sort out null elements" { listOf( Pair(null, null), Pair("one", "two"), Pair("one", null), Pair(null, "two") ) mapNotNull { one, two -> Pair(one, two) } shouldBe listOf( Pair("one", "two"), Pair("one", null), Pair(null, "two") ) } "handle null values" { val actual = listOf( Pair("one", null), Pair("three", "four"), Pair("fife", "six"), Pair(null, null), Pair("ten", "eleven") ) val expected = listOf( Pair("one", null), Pair("three", "four"), Pair("fife", "six"), Pair("ten", "eleven") ) actual mapNotNull { one, two -> Pair(one, two) } shouldBe expected } } } }
apache-2.0
dc06fd8612f620d2af39cd87e0ec24ee
30.297872
99
0.42828
5.323281
false
true
false
false
JetBrains/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/tree/expressions.kt
1
15564
// 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.nj2k.tree import com.intellij.psi.PsiElement import com.intellij.psi.PsiExpression import com.intellij.psi.PsiSwitchExpression import org.jetbrains.kotlin.nj2k.symbols.* import org.jetbrains.kotlin.nj2k.tree.visitors.JKVisitor import org.jetbrains.kotlin.nj2k.types.JKContextType import org.jetbrains.kotlin.nj2k.types.JKNoType import org.jetbrains.kotlin.nj2k.types.JKType import org.jetbrains.kotlin.nj2k.types.JKTypeFactory abstract class JKExpression : JKAnnotationMemberValue(), PsiOwner by PsiOwnerImpl() { protected abstract val expressionType: JKType? open fun calculateType(typeFactory: JKTypeFactory): JKType? { val psiType = (psi as? PsiExpression)?.type ?: return null return typeFactory.fromPsiType(psiType) } } abstract class JKOperatorExpression : JKExpression() { abstract var operator: JKOperator override fun calculateType(typeFactory: JKTypeFactory) = expressionType ?: operator.returnType } class JKBinaryExpression( left: JKExpression, right: JKExpression, override var operator: JKOperator, override val expressionType: JKType? = null, ) : JKOperatorExpression() { var left by child(left) var right by child(right) override fun accept(visitor: JKVisitor) = visitor.visitBinaryExpression(this) } abstract class JKUnaryExpression : JKOperatorExpression() { abstract var expression: JKExpression } class JKPrefixExpression( expression: JKExpression, override var operator: JKOperator, override val expressionType: JKType? = null, ) : JKUnaryExpression() { override var expression by child(expression) override fun accept(visitor: JKVisitor) = visitor.visitPrefixExpression(this) } class JKPostfixExpression( expression: JKExpression, override var operator: JKOperator, override val expressionType: JKType? = null ) : JKUnaryExpression() { override var expression by child(expression) override fun accept(visitor: JKVisitor) = visitor.visitPostfixExpression(this) } class JKQualifiedExpression( receiver: JKExpression, selector: JKExpression, override val expressionType: JKType? = null, ) : JKExpression() { var receiver: JKExpression by child(receiver) var selector: JKExpression by child(selector) override fun accept(visitor: JKVisitor) = visitor.visitQualifiedExpression(this) } class JKParenthesizedExpression( expression: JKExpression, override val expressionType: JKType? = null ) : JKExpression() { var expression: JKExpression by child(expression) override fun calculateType(typeFactory: JKTypeFactory) = expressionType ?: expression.calculateType(typeFactory) override fun accept(visitor: JKVisitor) = visitor.visitParenthesizedExpression(this) } class JKTypeCastExpression( expression: JKExpression, type: JKTypeElement, override val expressionType: JKType? = null, ) : JKExpression() { var expression by child(expression) var type by child(type) override fun calculateType(typeFactory: JKTypeFactory) = expressionType ?: type.type override fun accept(visitor: JKVisitor) = visitor.visitTypeCastExpression(this) } class JKLiteralExpression( var literal: String, val type: LiteralType, override val expressionType: JKType? = null, ) : JKExpression() { override fun accept(visitor: JKVisitor) = visitor.visitLiteralExpression(this) override fun calculateType(typeFactory: JKTypeFactory): JKType { expressionType?.let { return it } return when (type) { LiteralType.CHAR -> typeFactory.types.char LiteralType.BOOLEAN -> typeFactory.types.boolean LiteralType.INT -> typeFactory.types.int LiteralType.LONG -> typeFactory.types.long LiteralType.FLOAT -> typeFactory.types.float LiteralType.DOUBLE -> typeFactory.types.double LiteralType.NULL -> typeFactory.types.nullableAny LiteralType.STRING, LiteralType.TEXT_BLOCK -> typeFactory.types.string } } enum class LiteralType { STRING, TEXT_BLOCK, CHAR, BOOLEAN, NULL, INT, LONG, FLOAT, DOUBLE } } class JKStubExpression(override val expressionType: JKType? = null) : JKExpression() { override fun calculateType(typeFactory: JKTypeFactory): JKType? = expressionType override fun accept(visitor: JKVisitor) = visitor.visitStubExpression(this) } class JKThisExpression( qualifierLabel: JKLabel, override val expressionType: JKType? = null, ) : JKExpression() { var qualifierLabel: JKLabel by child(qualifierLabel) override fun accept(visitor: JKVisitor) = visitor.visitThisExpression(this) } class JKSuperExpression( override val expressionType: JKType = JKNoType, val superTypeQualifier: JKClassSymbol? = null, outerTypeQualifier: JKLabel = JKLabelEmpty(), ) : JKExpression() { var outerTypeQualifier: JKLabel by child(outerTypeQualifier) override fun accept(visitor: JKVisitor) = visitor.visitSuperExpression(this) } class JKIfElseExpression( condition: JKExpression, thenBranch: JKExpression, elseBranch: JKExpression, override val expressionType: JKType? = null, ) : JKExpression() { var condition by child(condition) var thenBranch by child(thenBranch) var elseBranch by child(elseBranch) override fun accept(visitor: JKVisitor) = visitor.visitIfElseExpression(this) } class JKLambdaExpression( statement: JKStatement, parameters: List<JKParameter>, functionalType: JKTypeElement = JKTypeElement(JKNoType), returnType: JKTypeElement = JKTypeElement(JKContextType), override val expressionType: JKType? = null, ) : JKExpression() { var statement by child(statement) var parameters by children(parameters) var functionalType by child(functionalType) val returnType by child(returnType) override fun accept(visitor: JKVisitor) = visitor.visitLambdaExpression(this) } abstract class JKCallExpression : JKExpression(), JKTypeArgumentListOwner { abstract var identifier: JKMethodSymbol abstract var arguments: JKArgumentList } class JKDelegationConstructorCall( override var identifier: JKMethodSymbol, expression: JKExpression, arguments: JKArgumentList, override val expressionType: JKType? = null, ) : JKCallExpression() { override var typeArgumentList: JKTypeArgumentList by child(JKTypeArgumentList()) val expression: JKExpression by child(expression) override var arguments: JKArgumentList by child(arguments) override fun accept(visitor: JKVisitor) = visitor.visitDelegationConstructorCall(this) } class JKCallExpressionImpl( override var identifier: JKMethodSymbol, arguments: JKArgumentList = JKArgumentList(), typeArgumentList: JKTypeArgumentList = JKTypeArgumentList(), override val expressionType: JKType? = null, ) : JKCallExpression() { override var typeArgumentList by child(typeArgumentList) override var arguments by child(arguments) override fun accept(visitor: JKVisitor) = visitor.visitCallExpressionImpl(this) } class JKNewExpression( val classSymbol: JKClassSymbol, arguments: JKArgumentList, typeArgumentList: JKTypeArgumentList = JKTypeArgumentList(), classBody: JKClassBody = JKClassBody(), val isAnonymousClass: Boolean = false, override val expressionType: JKType? = null, ) : JKExpression() { var typeArgumentList by child(typeArgumentList) var arguments by child(arguments) var classBody by child(classBody) override fun accept(visitor: JKVisitor) = visitor.visitNewExpression(this) } class JKFieldAccessExpression( var identifier: JKFieldSymbol, override val expressionType: JKType? = null, ) : JKExpression() { override fun accept(visitor: JKVisitor) = visitor.visitFieldAccessExpression(this) } class JKPackageAccessExpression(var identifier: JKPackageSymbol) : JKExpression() { override val expressionType: JKType? get() = null override fun calculateType(typeFactory: JKTypeFactory): JKType? = null override fun accept(visitor: JKVisitor) = visitor.visitPackageAccessExpression(this) } class JKClassAccessExpression( var identifier: JKClassSymbol, override val expressionType: JKType? = null, ) : JKExpression() { override fun accept(visitor: JKVisitor) = visitor.visitClassAccessExpression(this) } class JKMethodAccessExpression(val identifier: JKMethodSymbol, override val expressionType: JKType? = null) : JKExpression() { override fun accept(visitor: JKVisitor) = visitor.visitMethodAccessExpression(this) } class JKTypeQualifierExpression(val type: JKType, override val expressionType: JKType? = null) : JKExpression() { override fun accept(visitor: JKVisitor) = visitor.visitTypeQualifierExpression(this) } class JKMethodReferenceExpression( qualifier: JKExpression, val identifier: JKSymbol, functionalType: JKTypeElement, val isConstructorCall: Boolean, override val expressionType: JKType? = null, ) : JKExpression() { val qualifier by child(qualifier) val functionalType by child(functionalType) override fun accept(visitor: JKVisitor) = visitor.visitMethodReferenceExpression(this) } class JKLabeledExpression( statement: JKStatement, labels: List<JKNameIdentifier>, override val expressionType: JKType? = null, ) : JKExpression() { var statement: JKStatement by child(statement) val labels: List<JKNameIdentifier> by children(labels) override fun accept(visitor: JKVisitor) = visitor.visitLabeledExpression(this) } class JKClassLiteralExpression( classType: JKTypeElement, var literalType: ClassLiteralType, override val expressionType: JKType? = null, ) : JKExpression() { val classType: JKTypeElement by child(classType) override fun accept(visitor: JKVisitor) = visitor.visitClassLiteralExpression(this) enum class ClassLiteralType { KOTLIN_CLASS, JAVA_CLASS, JAVA_PRIMITIVE_CLASS, JAVA_VOID_TYPE } } abstract class JKKtAssignmentChainLink : JKExpression() { abstract val receiver: JKExpression abstract val assignmentStatement: JKKtAssignmentStatement abstract val field: JKExpression override val expressionType: JKType? get() = null override fun calculateType(typeFactory: JKTypeFactory) = field.calculateType(typeFactory) } class JKAssignmentChainAlsoLink( receiver: JKExpression, assignmentStatement: JKKtAssignmentStatement, field: JKExpression ) : JKKtAssignmentChainLink() { override val receiver by child(receiver) override val assignmentStatement by child(assignmentStatement) override val field by child(field) override fun accept(visitor: JKVisitor) = visitor.visitAssignmentChainAlsoLink(this) } class JKAssignmentChainLetLink( receiver: JKExpression, assignmentStatement: JKKtAssignmentStatement, field: JKExpression ) : JKKtAssignmentChainLink() { override val receiver by child(receiver) override val assignmentStatement by child(assignmentStatement) override val field by child(field) override fun accept(visitor: JKVisitor) = visitor.visitAssignmentChainLetLink(this) } class JKIsExpression(expression: JKExpression, type: JKTypeElement) : JKExpression() { var type by child(type) var expression by child(expression) override val expressionType: JKType? get() = null override fun calculateType(typeFactory: JKTypeFactory) = typeFactory.types.boolean override fun accept(visitor: JKVisitor) = visitor.visitIsExpression(this) } class JKKtItExpression(override val expressionType: JKType) : JKExpression() { override fun accept(visitor: JKVisitor) = visitor.visitKtItExpression(this) } class JKKtAnnotationArrayInitializerExpression( initializers: List<JKAnnotationMemberValue>, override val expressionType: JKType? = null ) : JKExpression() { constructor(vararg initializers: JKAnnotationMemberValue) : this(initializers.toList()) val initializers: List<JKAnnotationMemberValue> by children(initializers) override fun calculateType(typeFactory: JKTypeFactory): JKType? = expressionType override fun accept(visitor: JKVisitor) = visitor.visitKtAnnotationArrayInitializerExpression(this) } class JKKtTryExpression( tryBlock: JKBlock, finallyBlock: JKBlock, catchSections: List<JKKtTryCatchSection>, override val expressionType: JKType? = null, ) : JKExpression() { var tryBlock: JKBlock by child(tryBlock) var finallyBlock: JKBlock by child(finallyBlock) var catchSections: List<JKKtTryCatchSection> by children(catchSections) override fun accept(visitor: JKVisitor) = visitor.visitKtTryExpression(this) } class JKThrowExpression(exception: JKExpression) : JKExpression() { var exception: JKExpression by child(exception) override val expressionType: JKType? get() = null override fun calculateType(typeFactory: JKTypeFactory) = typeFactory.types.nothing override fun accept(visitor: JKVisitor) = visitor.visitKtThrowExpression(this) } class JKJavaNewEmptyArray( initializer: List<JKExpression>, type: JKTypeElement, override val expressionType: JKType? = null ) : JKExpression() { val type by child(type) var initializer by children(initializer) override fun accept(visitor: JKVisitor) = visitor.visitJavaNewEmptyArray(this) } class JKJavaNewArray( initializer: List<JKExpression>, type: JKTypeElement, override val expressionType: JKType? = null ) : JKExpression() { val type by child(type) var initializer by children(initializer) override fun accept(visitor: JKVisitor) = visitor.visitJavaNewArray(this) } class JKJavaAssignmentExpression( field: JKExpression, expression: JKExpression, var operator: JKOperator, override val expressionType: JKType? = null ) : JKExpression() { var field by child(field) var expression by child(expression) override fun accept(visitor: JKVisitor) = visitor.visitJavaAssignmentExpression(this) } class JKJavaSwitchExpression( expression: JKExpression, cases: List<JKJavaSwitchCase>, override val expressionType: JKType? = null, ) : JKExpression(), JKJavaSwitchBlock { override var expression: JKExpression by child(expression) override var cases: List<JKJavaSwitchCase> by children(cases) override fun accept(visitor: JKVisitor) = visitor.visitJavaSwitchExpression(this) override fun calculateType(typeFactory: JKTypeFactory): JKType? { val psiType = (psi as? PsiSwitchExpression)?.type ?: return null return typeFactory.fromPsiType(psiType) } } class JKKtWhenExpression( expression: JKExpression, cases: List<JKKtWhenCase>, override val expressionType: JKType?, ) : JKExpression(), JKKtWhenBlock { override var expression: JKExpression by child(expression) override var cases: List<JKKtWhenCase> by children(cases) override fun accept(visitor: JKVisitor) = visitor.visitKtWhenExpression(this) override fun calculateType(typeFactory: JKTypeFactory): JKType? = expressionType } class JKErrorExpression( override var psi: PsiElement?, override val reason: String?, override val expressionType: JKType? = null ) : JKExpression(), JKErrorElement { override fun calculateType(typeFactory: JKTypeFactory): JKType = expressionType ?: typeFactory.types.nothing override fun accept(visitor: JKVisitor) = visitor.visitExpression(this) }
apache-2.0
20ef5c3bccdce53ecd2f2ef911e24198
36.147971
126
0.756939
4.990061
false
false
false
false
Atsky/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/debugger/HaskellDebugProcess.kt
1
13852
package org.jetbrains.haskell.debugger import com.intellij.xdebugger.XDebugProcess import com.intellij.xdebugger.XDebugSession import com.intellij.execution.ui.ExecutionConsole import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider import com.intellij.xdebugger.XSourcePosition import com.intellij.execution.process.ProcessHandler import com.intellij.xdebugger.breakpoints.XBreakpointProperties import com.intellij.xdebugger.breakpoints.XBreakpoint import com.intellij.xdebugger.breakpoints.XBreakpointHandler import com.intellij.execution.ui.ConsoleView import com.intellij.xdebugger.breakpoints.XLineBreakpoint import org.jetbrains.haskell.debugger.breakpoints.HaskellLineBreakpointType import org.jetbrains.haskell.debugger.breakpoints.HaskellLineBreakpointHandler import java.util.concurrent.locks.Lock import java.util.concurrent.locks.Condition import org.jetbrains.haskell.debugger.utils.HaskellUtils import org.jetbrains.haskell.debugger.highlighting.HsDebugSessionListener import org.jetbrains.haskell.debugger.parser.LocalBinding import java.util.concurrent.locks.ReentrantLock import org.jetbrains.haskell.debugger.protocol.ForceCommand import org.jetbrains.haskell.debugger.config.HaskellDebugSettings import com.intellij.xdebugger.ui.XDebugTabLayouter import com.intellij.openapi.actionSystem.DefaultActionGroup import org.jetbrains.haskell.debugger.protocol.SyncCommand import org.jetbrains.haskell.debugger.utils.SyncObject import org.jetbrains.haskell.debugger.breakpoints.HaskellExceptionBreakpointHandler import org.jetbrains.haskell.debugger.breakpoints.HaskellExceptionBreakpointProperties import java.util.ArrayList import org.jetbrains.haskell.debugger.protocol.BreakpointListCommand import org.jetbrains.haskell.debugger.protocol.SetBreakpointByIndexCommand import org.jetbrains.haskell.debugger.protocol.SetBreakpointCommand import org.jetbrains.haskell.debugger.parser.BreakInfo import com.intellij.notification.Notifications import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.xdebugger.impl.actions.StepOutAction import com.intellij.xdebugger.impl.actions.ForceStepIntoAction import org.jetbrains.haskell.debugger.procdebuggers.ProcessDebugger import org.jetbrains.haskell.debugger.procdebuggers.GHCiDebugger import org.jetbrains.haskell.debugger.procdebuggers.RemoteDebugger import org.jetbrains.haskell.debugger.history.HistoryManager import org.jetbrains.haskell.debugger.prochandlers.HaskellDebugProcessHandler import com.intellij.execution.ui.RunnerLayoutUi import java.util.Deque import com.intellij.xdebugger.frame.XSuspendContext import java.util.ArrayDeque import org.jetbrains.haskell.debugger.procdebuggers.utils.DefaultRespondent import org.jetbrains.haskell.debugger.procdebuggers.utils.DebugRespondent import com.intellij.xdebugger.impl.XDebugSessionImpl import org.jetbrains.haskell.debugger.config.DebuggerType import org.jetbrains.haskell.repl.HaskellConsole /** * Main class for managing debug process and sending commands to real debug process through it's ProcessDebugger member. * * Attention! When sending commands to the underlying ProcessDebugger they are enqueued. But some commands may require * a lot of time to finish and, for example, if you call asynchronous command that needs much time to finish and * after that call synchronous command that freezes UI thread, you will get all the UI frozen until the first * command is finished. To check no command is in progress use * {@link org.jetbrains.haskell.debugger.HaskellDebugProcess#isReadyForNextCommand} * * @see org.jetbrains.haskell.debugger.HaskellDebugProcess#isReadyForNextCommand */ class HaskellDebugProcess(session: XDebugSession, val executionConsole: ExecutionConsole, val _processHandler: HaskellDebugProcessHandler, val stopAfterTrace: Boolean) : XDebugProcess(session) { //public val historyManager: HistoryManager = HistoryManager(session , this) var exceptionBreakpoint: XBreakpoint<HaskellExceptionBreakpointProperties>? = null private set val debugger: ProcessDebugger private val debugRespondent: DebugRespondent = DefaultRespondent(this) private val contexts: Deque<XSuspendContext> = ArrayDeque() private val debugProcessStateUpdater: DebugProcessStateUpdater private val _editorsProvider: XDebuggerEditorsProvider = HaskellDebuggerEditorsProvider() private val _breakpointHandlers: Array<XBreakpointHandler<*>> = arrayOf(HaskellLineBreakpointHandler(getSession()!!.project, HaskellLineBreakpointType::class.java, this), HaskellExceptionBreakpointHandler(this) ) private val registeredBreakpoints: MutableMap<BreakpointPosition, BreakpointEntry> = hashMapOf() private val BREAK_BY_INDEX_ERROR_MSG = "Only remote debugger supports breakpoint setting by index" init { val debuggerIsGHCi = HaskellDebugSettings.getInstance().state.debuggerType == DebuggerType.GHCI if (debuggerIsGHCi) { debugProcessStateUpdater = GHCiDebugProcessStateUpdater() debugger = GHCiDebugger(debugRespondent, _processHandler, executionConsole as ConsoleView, debugProcessStateUpdater.INPUT_READINESS_PORT) debugProcessStateUpdater.debugger = debugger } else { debugProcessStateUpdater = RemoteDebugProcessStateUpdater() debugger = RemoteDebugger(debugRespondent, _processHandler) debugProcessStateUpdater.debugger = debugger } _processHandler.setDebugProcessListener(debugProcessStateUpdater) } // XDebugProcess methods overriding override fun getEditorsProvider(): XDebuggerEditorsProvider = _editorsProvider override fun getBreakpointHandlers() : Array<XBreakpointHandler<out XBreakpoint<out XBreakpointProperties<*>?>?>> = _breakpointHandlers override fun doGetProcessHandler(): ProcessHandler? = _processHandler override fun createConsole(): ExecutionConsole = executionConsole override fun startStepOver() = debugger.stepOver() override fun startStepInto() = debugger.stepInto() override fun startStepOut() { val msg = "'Step out' not implemented" Notifications.Bus.notify(Notification("", "Debug execution error", msg, NotificationType.WARNING)) session!!.positionReached(session!!.suspendContext!!) } override fun stop() { //historyManager.clean() debugger.close() debugProcessStateUpdater.close() } override fun resume() = debugger.resume() override fun runToPosition(position: XSourcePosition) = debugger.runToPosition( HaskellUtils.getModuleName(session!!.project, position.file), HaskellUtils.zeroBasedToHaskellLineNumber(position.line)) override fun sessionInitialized() { super.sessionInitialized() val currentSession = session currentSession?.addSessionListener(HsDebugSessionListener(currentSession)) debugger.prepareDebugger() if (stopAfterTrace) { debugger.trace(null) } } override fun createTabLayouter(): XDebugTabLayouter = object : XDebugTabLayouter() { override fun registerAdditionalContent(ui: RunnerLayoutUi) { //historyManager.registerContent(ui) } } override fun registerAdditionalActions(leftToolbar: DefaultActionGroup, topToolbar: DefaultActionGroup, settings: DefaultActionGroup) { //temporary code for removal of unused actions from debug panel var stepOut: StepOutAction? = null var forceStepInto: ForceStepIntoAction? = null for (action in topToolbar.childActionsOrStubs) { if (action is StepOutAction) { stepOut = action } if (action is ForceStepIntoAction) { forceStepInto = action } } topToolbar.remove(stepOut) topToolbar.remove(forceStepInto) //historyManager.registerActions(topToolbar) } // Class' own methods fun startTrace(line: String?) { //historyManager.saveState() val context = session!!.suspendContext if (context != null) { contexts.add(context) } // disable actions debugger.trace(line) } fun traceFinished() { /* if (historyManager.hasSavedStates()) { historyManager.loadState() if (!contexts.isEmpty()) { getSession()!!.positionReached(contexts.pollLast()!!) } } else if (stopAfterTrace) { getSession()!!.stop() } else { } */ } fun isReadyForNextCommand(): Boolean = debugger.isReadyForNextCommand() fun addExceptionBreakpoint(breakpoint: XBreakpoint<HaskellExceptionBreakpointProperties>) { exceptionBreakpoint = breakpoint debugger.setExceptionBreakpoint(breakpoint.properties!!.state.exceptionType == HaskellExceptionBreakpointProperties.ExceptionType.ERROR) } fun removeExceptionBreakpoint(breakpoint: XBreakpoint<HaskellExceptionBreakpointProperties>) { assert(breakpoint == exceptionBreakpoint) exceptionBreakpoint = null debugger.removeExceptionBreakpoint() } fun setBreakpointNumberAtLine(breakpointNumber: Int, module: String, line: Int) { val entry = registeredBreakpoints.get(BreakpointPosition(module, line)) if (entry != null) { entry.breakpointNumber = breakpointNumber } } fun getBreakpointAtPosition(module: String, line: Int): XLineBreakpoint<XBreakpointProperties<*>>? = registeredBreakpoints.get(BreakpointPosition(module, line))?.breakpoint fun addBreakpoint(module: String, line: Int, breakpoint: XLineBreakpoint<XBreakpointProperties<*>>) { registeredBreakpoints.put(BreakpointPosition(module, line), BreakpointEntry(null, breakpoint)) debugger.setBreakpoint(module, line) } fun addBreakpointByIndex(module: String, index: Int, breakpoint: XLineBreakpoint<XBreakpointProperties<*>>) { if (HaskellDebugSettings.getInstance().state.debuggerType == DebuggerType.REMOTE) { val line = HaskellUtils.zeroBasedToHaskellLineNumber(breakpoint.line) registeredBreakpoints.put(BreakpointPosition(module, line), BreakpointEntry(index, breakpoint)) val command = SetBreakpointByIndexCommand(module, index, SetBreakpointCommand.Companion.StandardSetBreakpointCallback(module, debugRespondent)) debugger.enqueueCommand(command) } else { throw RuntimeException(BREAK_BY_INDEX_ERROR_MSG) } } fun removeBreakpoint(module: String, line: Int) { val breakpointNumber: Int? = registeredBreakpoints.get(BreakpointPosition(module, line))?.breakpointNumber if (breakpointNumber != null) { registeredBreakpoints.remove(BreakpointPosition(module, line)) debugger.removeBreakpoint(module, breakpointNumber) } } fun forceSetValue(localBinding: LocalBinding) { if (localBinding.name != null) { val syncObject: Lock = ReentrantLock() val bindingValueIsSet: Condition = syncObject.newCondition() val syncLocalBinding: LocalBinding = LocalBinding(localBinding.name, "", null) syncObject.lock() try { debugger.force(localBinding.name!!, ForceCommand.StandardForceCallback(syncLocalBinding, syncObject, bindingValueIsSet, this)) while (syncLocalBinding.value == null) { bindingValueIsSet.await() } if (syncLocalBinding.value?.isNotEmpty() ?: false) { localBinding.value = syncLocalBinding.value } } finally { syncObject.unlock() } } } fun syncBreakListForLine(moduleName: String, lineNumber: Int): ArrayList<BreakInfo> { if (HaskellDebugSettings.getInstance().state.debuggerType == DebuggerType.REMOTE) { val syncObject = SyncObject() val resultArray: ArrayList<BreakInfo> = ArrayList() val callback = BreakpointListCommand.Companion.DefaultCallback(resultArray) val command = BreakpointListCommand(moduleName, lineNumber, syncObject, callback) syncCommand(command, syncObject) return resultArray } return ArrayList() } private class BreakpointPosition(val module: String, val line: Int) { override fun equals(other: Any?): Boolean { if (other == null || other !is BreakpointPosition) { return false } return module.equals(other.module) && line.equals(other.line) } override fun hashCode(): Int = module.hashCode() * 31 + line } private class BreakpointEntry(var breakpointNumber: Int?, val breakpoint: XLineBreakpoint<XBreakpointProperties<*>>) /** * Used to make synchronous requests to debugger. * * @see org.jetbrains.haskell.debugger.utils.SyncObject * @see org.jetbrains.haskell.debugger.HaskellDebugProcess#isReadyForNextCommand */ private fun syncCommand(command: SyncCommand<*>, syncObject: SyncObject) { syncObject.lock() try { debugger.enqueueCommand(command) while (!syncObject.signaled()) { syncObject.await() } } finally { syncObject.unlock() } } }
apache-2.0
f5cf6c3fd14c84456f50ca6fbf7ad676
43.258786
174
0.713832
5.385692
false
false
false
false
allotria/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/declarations/JavaUClassInitializer.kt
4
1270
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.java import com.intellij.psi.PsiClassInitializer import com.intellij.psi.PsiElement import org.jetbrains.uast.* import org.jetbrains.uast.java.internal.JavaUElementWithComments class JavaUClassInitializer( override val sourcePsi: PsiClassInitializer, uastParent: UElement? ) : JavaAbstractUElement(uastParent), UClassInitializerEx, JavaUElementWithComments, UAnchorOwner, PsiClassInitializer by sourcePsi { @Suppress("OverridingDeprecatedMember") override val psi get() = sourcePsi override val javaPsi: PsiClassInitializer = sourcePsi override val uastAnchor: UIdentifier? get() = null override val uastBody: UExpression by lz { UastFacade.findPlugin(sourcePsi.body)?.convertElement(sourcePsi.body, this, null) as? UExpression ?: UastEmptyExpression(this) } override val uAnnotations: List<JavaUAnnotation> by lz { sourcePsi.annotations.map { JavaUAnnotation(it, this) } } override fun equals(other: Any?): Boolean = this === other override fun hashCode(): Int = sourcePsi.hashCode() override fun getOriginalElement(): PsiElement? = sourcePsi.originalElement }
apache-2.0
62758046d8f9120179b9e9e736409b33
38.71875
140
0.785827
4.884615
false
false
false
false
allotria/intellij-community
platform/lang-api/src/com/intellij/execution/stateExecutionWidget/StateWidgetProcess.kt
2
1625
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.stateExecutionWidget import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.util.registry.Registry import org.jetbrains.annotations.Nls import java.util.function.Predicate import javax.swing.Icon import kotlin.streams.toList interface StateWidgetProcess { companion object { private const val runDebugKey = "ide.new.navbar" private const val runDebugRerunAvailable = "ide.new.navbar.rerun.available" const val STATE_WIDGET_MORE_ACTION_GROUP = "StateWidgetMoreActionGroup" const val STATE_WIDGET_GROUP = "StateWidgetProcessesActionGroup" @JvmStatic fun isAvailable(): Boolean { return Registry.get(runDebugKey).asBoolean() } fun isRerunAvailable(): Boolean { return Registry.get(runDebugRerunAvailable).asBoolean() } val EP_NAME: ExtensionPointName<StateWidgetProcess> = ExtensionPointName("com.intellij.stateWidgetProcess") @JvmStatic fun getProcesses(): List<StateWidgetProcess> = EP_NAME.extensionList @JvmStatic fun getProcessesByExecutorId(executorId: String): List<StateWidgetProcess> { return getProcesses().filter { it.executorId == executorId }.toList() } } val ID: String val executorId: String val name: @Nls String val actionId: String val moreActionGroupName: String val moreActionSubGroupName: String val showInBar: Boolean fun rerunAvailable(): Boolean = false fun getStopIcon(): Icon? = null }
apache-2.0
2b5d1f037b7894862c9cb9f159612b1f
29.679245
140
0.758769
4.391892
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-data/src/main/kotlin/slatekit/data/encoders/Basics.kt
1
4084
package slatekit.data.encoders import slatekit.common.values.Record import slatekit.common.data.DataType import slatekit.common.data.Encoding import slatekit.common.data.Value import slatekit.common.ext.orElse import slatekit.data.Consts /** * Support for encoding to/from kotlin value to a SQL value * The encoders here are all for basic data types ( bool, string, short, int, long, double ) */ /** * @param dataType: This allows for supporting the conversion of bools to integers ( for sqlite ) */ open class BoolEncoder(val dataType: DataType = DataType.DTBool) : SqlEncoder<Boolean> { override fun encode(value: Boolean?): String = value?.let { if (value) "1" else "0" } ?: Consts.NULL override fun decode(record: Record, name: String): Boolean? = record.getBoolOrNull(name) override fun convert(name:String, value: Boolean?): Value { val finalValue = when(dataType){ DataType.DTInt -> value?.let { if(it) 1 else 0 } else -> value } return Value(name, dataType, finalValue, encode(value)) } } open class StringEncoder : SqlEncoder<String> { override fun encode(value: String?): String = value?.let { "'" + Encoding.ensureValue(value.orElse("")) + "'" } ?: Consts.NULL override fun decode(record: Record, name: String): String? = record.getStringOrNull(name) override fun convert(name:String, value: String?): Value = Value(name, DataType.DTString, value, encode(value)) } /** * @param dataType: This allows for supporting the conversion of shorts to integers ( for sqlite ) */ open class ShortEncoder(val dataType: DataType = DataType.DTShort) : SqlEncoder<Short> { override fun encode(value: Short?): String = value?.toString() ?: Consts.NULL override fun decode(record: Record, name: String): Short? = record.getShortOrNull(name) override fun convert(name:String, value: Short?): Value { val finalValue = when(dataType){ DataType.DTLong -> value?.let { it.toInt() } else -> value } return Value(name, dataType, finalValue, encode(value)) } } open class IntEncoder(val dataType: DataType = DataType.DTInt) : SqlEncoder<Int> { override fun encode(value: Int?): String = value?.toString() ?: Consts.NULL override fun decode(record: Record, name: String): Int? = record.getIntOrNull(name) override fun convert(name:String, value: Int?): Value { val finalValue = when(dataType){ DataType.DTLong -> value?.let { it.toLong() } else -> value } return Value(name, dataType, finalValue, encode(value)) } } /** * @param dataType: This allows for supporting the conversion of bools to integers ( for sqlite ) */ open class LongEncoder(val dataType: DataType = DataType.DTLong) : SqlEncoder<Long> { override fun encode(value: Long?): String = value?.toString() ?: Consts.NULL override fun decode(record: Record, name: String): Long? = record.getLongOrNull(name) override fun convert(name:String, value: Long?): Value = Value(name, dataType, value, encode(value)) } /** * @param dataType: This allows for supporting the conversion of bools to integers ( for sqlite ) */ open class FloatEncoder(val dataType: DataType = DataType.DTFloat) : SqlEncoder<Float> { override fun encode(value: Float?): String = value?.toString() ?: Consts.NULL override fun decode(record: Record, name: String): Float? = record.getFloatOrNull(name) override fun convert(name:String, value: Float?): Value { val finalValue = when(dataType){ DataType.DTDouble -> value?.let { it.toDouble() } else -> value } return Value(name, dataType, finalValue, encode(value)) } } open class DoubleEncoder : SqlEncoder<Double> { override fun encode(value: Double?): String = value?.toString() ?: Consts.NULL override fun decode(record: Record, name: String): Double? = record.getDoubleOrNull(name) override fun convert(name:String, value: Double?): Value = Value(name, DataType.DTDouble, value, encode(value)) }
apache-2.0
6eb439ad79394559497332507f23b402
40.673469
130
0.682909
4.11279
false
false
false
false
zdary/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/TagComponent.kt
1
1908
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages import com.intellij.ide.ui.AntialiasingType import com.intellij.ui.JBColor import com.intellij.ui.RelativeFont import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.GraphicsUtil import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.ui.util.ScaledPixels import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaledEmptyBorder import java.awt.Graphics import javax.swing.JLabel @Suppress("MagicNumber") // Thanks Swing class TagComponent(name: String) : JLabel() { init { foreground = JBColor.namedColor("Plugins.tagForeground", JBColor(0x808080, 0x808080)) background = JBColor.namedColor("Plugins.tagBackground", JBColor(0xE8E8E8, 0xE8E8E8)) isOpaque = false border = scaledEmptyBorder(vSize = 1, hSize = 8) RelativeFont.TINY.install(this) text = name toolTipText = PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform.tooltip") GraphicsUtil.setAntialiasingType(this, AntialiasingType.getAAHintForSwingComponent()) } @ScaledPixels var tagDiameterPx: Int = 4.scaled() set(value) { require(value >= 0) { "The diameter must be equal to or greater than zero." } field = JBUIScale.scale(value) } override fun paintComponent(g: Graphics) { val config = GraphicsUtil.setupRoundedBorderAntialiasing(g) g.color = background g.fillRoundRect(0, 0, width, height, tagDiameterPx, tagDiameterPx) config.restore() super.paintComponent(g) } }
apache-2.0
945db504c134059710ceddfef9fea41a
42.363636
140
0.74109
4.268456
false
false
false
false
blokadaorg/blokada
android5/app/wireguard-android/ui/src/main/java/com/wireguard/android/util/ErrorMessages.kt
1
7760
/* * Copyright © 2017-2021 WireGuard LLC. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package com.wireguard.android.util import android.content.res.Resources import android.os.RemoteException import com.wireguard.android.backend.BackendException import com.wireguard.android.util.RootShell.RootShellException import com.wireguard.config.BadConfigException import com.wireguard.config.InetEndpoint import com.wireguard.config.InetNetwork import com.wireguard.config.ParseException import com.wireguard.crypto.Key import com.wireguard.crypto.KeyFormatException import org.blokada.R import ui.MainApplication import java.net.InetAddress object ErrorMessages { private val BCE_REASON_MAP = mapOf( BadConfigException.Reason.INVALID_KEY to R.string.bad_config_reason_invalid_key, BadConfigException.Reason.INVALID_NUMBER to R.string.bad_config_reason_invalid_number, BadConfigException.Reason.INVALID_VALUE to R.string.bad_config_reason_invalid_value, BadConfigException.Reason.MISSING_ATTRIBUTE to R.string.bad_config_reason_missing_attribute, BadConfigException.Reason.MISSING_SECTION to R.string.bad_config_reason_missing_section, BadConfigException.Reason.SYNTAX_ERROR to R.string.bad_config_reason_syntax_error, BadConfigException.Reason.UNKNOWN_ATTRIBUTE to R.string.bad_config_reason_unknown_attribute, BadConfigException.Reason.UNKNOWN_SECTION to R.string.bad_config_reason_unknown_section ) private val BE_REASON_MAP = mapOf( BackendException.Reason.UNKNOWN_KERNEL_MODULE_NAME to R.string.module_version_error, BackendException.Reason.WG_QUICK_CONFIG_ERROR_CODE to R.string.tunnel_config_error, BackendException.Reason.TUNNEL_MISSING_CONFIG to R.string.no_config_error, BackendException.Reason.VPN_NOT_AUTHORIZED to R.string.vpn_not_authorized_error, BackendException.Reason.UNABLE_TO_START_VPN to R.string.vpn_start_error, BackendException.Reason.TUN_CREATION_ERROR to R.string.tun_create_error, BackendException.Reason.GO_ACTIVATION_ERROR_CODE to R.string.tunnel_on_error, //BackendException.Reason.DNS_RESOLUTION_FAILURE to R.string.tunnel_dns_failure ) private val KFE_FORMAT_MAP = mapOf( Key.Format.BASE64 to R.string.key_length_explanation_base64, Key.Format.BINARY to R.string.key_length_explanation_binary, Key.Format.HEX to R.string.key_length_explanation_hex ) private val KFE_TYPE_MAP = mapOf( KeyFormatException.Type.CONTENTS to R.string.key_contents_error, KeyFormatException.Type.LENGTH to R.string.key_length_error ) private val PE_CLASS_MAP = mapOf( InetAddress::class.java to R.string.parse_error_inet_address, InetEndpoint::class.java to R.string.parse_error_inet_endpoint, InetNetwork::class.java to R.string.parse_error_inet_network, Int::class.java to R.string.parse_error_integer ) private val RSE_REASON_MAP = mapOf( RootShellException.Reason.NO_ROOT_ACCESS to R.string.error_root, RootShellException.Reason.SHELL_MARKER_COUNT_ERROR to R.string.shell_marker_count_error, RootShellException.Reason.SHELL_EXIT_STATUS_READ_ERROR to R.string.shell_exit_status_read_error, RootShellException.Reason.SHELL_START_ERROR to R.string.shell_start_error, RootShellException.Reason.CREATE_BIN_DIR_ERROR to R.string.create_bin_dir_error, RootShellException.Reason.CREATE_TEMP_DIR_ERROR to R.string.create_temp_dir_error ) operator fun get(throwable: Throwable?): String { val resources = MainApplication.get().resources if (throwable == null) return resources.getString(R.string.unknown_error) val rootCause = rootCause(throwable) return when { rootCause is BadConfigException -> { val reason = getBadConfigExceptionReason(resources, rootCause) val context = if (rootCause.location == BadConfigException.Location.TOP_LEVEL) { resources.getString(R.string.bad_config_context_top_level, rootCause.section.getName()) } else { resources.getString(R.string.bad_config_context, rootCause.section.getName(), rootCause.location.getName()) } val explanation = getBadConfigExceptionExplanation(resources, rootCause) resources.getString(R.string.bad_config_error, reason, context) + explanation } rootCause is BackendException -> { resources.getString(BE_REASON_MAP.getValue(rootCause.reason), *rootCause.format) } rootCause is RootShellException -> { resources.getString(RSE_REASON_MAP.getValue(rootCause.reason), *rootCause.format) } // rootCause is Resources.NotFoundException -> { // resources.getString(R.string.error_no_qr_found) // } // rootCause is ChecksumException -> { // resources.getString(R.string.error_qr_checksum) // } rootCause.message != null -> { rootCause.message!! } else -> { val errorType = rootCause.javaClass.simpleName resources.getString(R.string.generic_error, errorType) } } } private fun getBadConfigExceptionExplanation(resources: Resources, bce: BadConfigException): String { if (bce.cause is KeyFormatException) { val kfe = bce.cause as KeyFormatException? if (kfe!!.type == KeyFormatException.Type.LENGTH) return resources.getString(KFE_FORMAT_MAP.getValue(kfe.format)) } else if (bce.cause is ParseException) { val pe = bce.cause as ParseException? if (pe!!.message != null) return ": ${pe.message}" } else if (bce.location == BadConfigException.Location.LISTEN_PORT) { return resources.getString(R.string.bad_config_explanation_udp_port) } else if (bce.location == BadConfigException.Location.MTU) { return resources.getString(R.string.bad_config_explanation_positive_number) } else if (bce.location == BadConfigException.Location.PERSISTENT_KEEPALIVE) { return resources.getString(R.string.bad_config_explanation_pka) } return "" } private fun getBadConfigExceptionReason(resources: Resources, bce: BadConfigException): String { if (bce.cause is KeyFormatException) { val kfe = bce.cause as KeyFormatException? return resources.getString(KFE_TYPE_MAP.getValue(kfe!!.type)) } else if (bce.cause is ParseException) { val pe = bce.cause as ParseException? val type = resources.getString((if (PE_CLASS_MAP.containsKey(pe!!.parsingClass)) PE_CLASS_MAP[pe.parsingClass] else R.string.parse_error_generic)!!) return resources.getString(R.string.parse_error_reason, type, pe.text) } return resources.getString(BCE_REASON_MAP.getValue(bce.reason), bce.text) } private fun rootCause(throwable: Throwable): Throwable { var cause = throwable while (cause.cause != null) { if (cause is BadConfigException || cause is BackendException || cause is RootShellException) break val nextCause = cause.cause!! if (nextCause is RemoteException) break cause = nextCause } return cause } }
mpl-2.0
e4047a4599063860ffd6e1cecd38f051
52.510345
160
0.667096
4.418565
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/resolve/references/KotlinPropertyAssignment.kt
12
552
class A { var something: Int = 10 } fun A.foo(a: A) { print(a.<caret>something) a.<caret>something = 1 a.<caret>something += 1 a.<caret>something++ --a.<caret>something <caret>something++ (<caret>something)++ (<caret>something) = 1 (a.<caret>something) = 1 } // MULTIRESOLVE // REF1: (in A).something // REF2: (in A).something // REF3: (in A).something // REF4: (in A).something // REF5: (in A).something // REF6: (in A).something // REF7: (in A).something // REF8: (in A).something // REF9: (in A).something
apache-2.0
2d40ccc73240e62772dddb3dae007995
19.444444
29
0.596014
2.875
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/groovy/src/org/jetbrains/kotlin/idea/groovy/inspections/DifferentStdlibGradleVersionInspection.kt
1
4530
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.groovy.inspections import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.roots.ProjectRootManager import com.intellij.psi.PsiFile import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.idea.configuration.KOTLIN_GROUP_ID import org.jetbrains.kotlin.idea.extensions.gradle.KotlinGradleFacade import org.jetbrains.kotlin.idea.extensions.gradle.SCRIPT_PRODUCTION_DEPENDENCY_STATEMENTS import org.jetbrains.kotlin.idea.groovy.KotlinGroovyBundle import org.jetbrains.kotlin.idea.platform.tooling import org.jetbrains.kotlin.idea.roots.findAll import org.jetbrains.kotlin.idea.roots.findGradleProjectStructure import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.plugins.groovy.codeInspection.BaseInspection import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression class DifferentStdlibGradleVersionInspection : BaseInspection() { override fun buildVisitor(): BaseInspectionVisitor = MyVisitor(KOTLIN_GROUP_ID, JvmIdePlatformKind.tooling.mavenLibraryIds) override fun buildErrorString(vararg args: Any) = KotlinGroovyBundle.message("error.text.different.kotlin.library.version", args[0], args[1]) private abstract class VersionFinder(private val groupId: String, private val libraryIds: List<String>) : KotlinGradleInspectionVisitor() { protected abstract fun onFound(stdlibVersion: String, stdlibStatement: GrCallExpression) override fun visitClosure(closure: GrClosableBlock) { super.visitClosure(closure) val dependenciesCall = closure.getStrictParentOfType<GrMethodCall>() ?: return if (dependenciesCall.invokedExpression.text != "dependencies") return if (dependenciesCall.parent !is PsiFile) return val stdlibStatement = findLibraryStatement(closure, "org.jetbrains.kotlin", libraryIds) ?: return val stdlibVersion = getResolvedLibVersion(closure.containingFile, groupId, libraryIds) ?: return onFound(stdlibVersion, stdlibStatement) } } private inner class MyVisitor(groupId: String, libraryIds: List<String>) : VersionFinder(groupId, libraryIds) { override fun onFound(stdlibVersion: String, stdlibStatement: GrCallExpression) { val gradlePluginVersion = getResolvedKotlinGradleVersion(stdlibStatement.containingFile) if (stdlibVersion != gradlePluginVersion) { registerError(stdlibStatement, gradlePluginVersion, stdlibVersion) } } } companion object { private fun findLibraryStatement( closure: GrClosableBlock, @NonNls libraryGroup: String, libraryIds: List<String> ): GrCallExpression? { return GradleHeuristicHelper.findStatementWithPrefixes(closure, SCRIPT_PRODUCTION_DEPENDENCY_STATEMENTS).firstOrNull { statement -> libraryIds.any { val index = statement.text.indexOf(it) // This prevents detecting kotlin-stdlib inside kotlin-stdlib-common, -jdk8, etc. index != -1 && statement.text.getOrNull(index + it.length) != '-' } && statement.text.contains(libraryGroup) } } fun getResolvedLibVersion(file: PsiFile, groupId: String, libraryIds: List<String>): String? { val projectStructureNode = findGradleProjectStructure(file) ?: return null val module = ProjectRootManager.getInstance(file.project).fileIndex.getModuleForFile(file.virtualFile) ?: return null val gradleFacade = KotlinGradleFacade.instance ?: return null for (moduleData in projectStructureNode.findAll(ProjectKeys.MODULE).filter { it.data.internalName == module.name }) { gradleFacade.findLibraryVersionByModuleData(moduleData.node, groupId, libraryIds)?.let { return it } } return null } } }
apache-2.0
3fa159da6ac240be1a78e9fb6f591dd6
50.488636
158
0.729801
5.044543
false
false
false
false
Flank/flank
test_runner/src/main/kotlin/ftl/config/ios/IosGcloudConfig.kt
1
4368
package ftl.config.ios import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import ftl.args.yml.IYmlKeys import ftl.args.yml.ymlKeys import ftl.config.Config import picocli.CommandLine /** * iOS specific gcloud parameters * * https://cloud.google.com/sdk/gcloud/reference/firebase/test/android/run * https://cloud.google.com/sdk/gcloud/reference/alpha/firebase/test/ios/run */ @JsonIgnoreProperties(ignoreUnknown = true) data class IosGcloudConfig @JsonIgnore constructor( @JsonIgnore override val data: MutableMap<String, Any?> ) : Config { @set:CommandLine.Option( names = ["--test"], description = [ "The path to the test package (a zip file containing the iOS app " + "and XCTest files). The given path may be in the local filesystem or in Google Cloud Storage using a URL " + "beginning with gs://. Note: any .xctestrun file in this zip file will be ignored if --xctestrun-file " + "is specified." ] ) @set:JsonProperty("test") var test: String? by data @set:CommandLine.Option( names = ["--xctestrun-file"], description = [ "The path to an .xctestrun file that will override any " + ".xctestrun file contained in the --test package. Because the .xctestrun file contains environment variables " + "along with test methods to run and/or ignore, this can be useful for customizing or sharding test suites. The " + "given path may be in the local filesystem or in Google Cloud Storage using a URL beginning with gs://." ] ) @set:JsonProperty("xctestrun-file") var xctestrunFile: String? by data @set:CommandLine.Option( names = ["--xcode-version"], description = [ "The version of Xcode that should be used to run an XCTest. " + "Defaults to the latest Xcode version supported in Firebase Test Lab. This Xcode version must be supported by " + "all iOS versions selected in the test matrix." ] ) @set:JsonProperty("xcode-version") var xcodeVersion: String? by data @set:CommandLine.Option( names = ["--additional-ipas"], split = ",", description = [ "List of up to 100 additional IPAs to install, in addition to the one being directly tested. " + "The path may be in the local filesystem or in Google Cloud Storage using gs:// notation." ] ) @set:JsonProperty("additional-ipas") var additionalIpas: List<String>? by data @set:CommandLine.Option( names = ["--app"], description = [ "The path to the application archive (.ipa file) for game-loop testing. " + "The path may be in the local filesystem or in Google Cloud Storage using gs:// notation. " + "This flag is only valid when --type=game-loop is also set" ] ) @set:JsonProperty("app") var app: String? by data @set:CommandLine.Option( names = ["--test-special-entitlements"], description = [ "Enables testing special app entitlements. Re-signs an app having special entitlements with a new" + " application-identifier. This currently supports testing Push Notifications (aps-environment) entitlement " + "for up to one app in a project.\n" + "Note: Because this changes the app's identifier, make sure none of the resources in your zip file contain " + "direct references to the test app's bundle id." ] ) @set:JsonProperty("test-special-entitlements") var testSpecialEntitlements: Boolean? by data constructor() : this(mutableMapOf<String, Any?>().withDefault { null }) companion object : IYmlKeys { override val group = IYmlKeys.Group.GCLOUD override val keys by lazy { IosGcloudConfig::class.ymlKeys } fun default() = IosGcloudConfig().apply { test = null xctestrunFile = null xcodeVersion = null additionalIpas = emptyList() app = null testSpecialEntitlements = false } } }
apache-2.0
bcfe699f0e9875facc13c7af304ecd01
38
130
0.630723
4.569038
false
true
false
false
michaelkourlas/voipms-sms-client
voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/sms/receivers/SendMessageReceiver.kt
1
4711
/* * VoIP.ms SMS * Copyright (C) 2018-2021 Michael Kourlas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.kourlas.voipms_sms.sms.receivers import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import androidx.core.app.RemoteInput import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import net.kourlas.voipms_sms.R import net.kourlas.voipms_sms.database.Database import net.kourlas.voipms_sms.sms.ConversationId import net.kourlas.voipms_sms.sms.workers.SendMessageWorker import net.kourlas.voipms_sms.utils.getMessageTexts import net.kourlas.voipms_sms.utils.logException /** * Broadcast receiver used to forward send message requests from a notification * PendingIntent to a SendMessageWorker. */ class SendMessageReceiver : BroadcastReceiver() { @OptIn(DelicateCoroutinesApi::class) override fun onReceive(context: Context?, intent: Intent?) { try { // Collect the required state. if (context == null || intent == null) { throw Exception("No context or intent provided") } if (intent.action != context.getString( R.string.send_message_receiver_action ) ) { throw Exception("Unrecognized action " + intent.action) } val did = intent.getStringExtra( context.getString( R.string.send_message_receiver_did ) ) ?: throw Exception( "No DID provided" ) val contact = intent.getStringExtra( context.getString( R.string.send_message_receiver_contact ) ) ?: throw Exception( "No contact provided" ) val remoteInput = RemoteInput.getResultsFromIntent(intent) val messageText = remoteInput?.getCharSequence( context.getString( R.string.notifications_reply_key ) )?.toString() ?: throw Exception("No message text provided") val pendingResult = goAsync() ?: throw Exception("No PendingResult returned") GlobalScope.launch(Dispatchers.Default) { // Insert the messages into the database, then tell the // SendMessageWorker to send them. try { val databaseIds = Database.getInstance(context) .insertConversationMessagesDeliveryInProgress( ConversationId(did, contact), getMessageTexts(context, messageText) ) for (id in databaseIds) { SendMessageWorker.sendMessage( context, id, inlineReplyConversationId = ConversationId( did, contact ) ) } } catch (e: Exception) { logException(e) } finally { pendingResult.finish() } } } catch (e: Exception) { logException(e) } } companion object { /** * Gets an intent which can be used to send a message to the * specified contact and from the specified DID. */ fun getIntent(context: Context, did: String, contact: String): Intent { val intent = Intent() intent.action = context.getString(R.string.send_message_receiver_action) intent.putExtra( context.getString( R.string.send_message_receiver_did ), did ) intent.putExtra( context.getString( R.string.send_message_receiver_contact ), contact ) return intent } } }
apache-2.0
05e14227a5d6e935564d263a08f0d6f7
36.094488
79
0.566546
5.377854
false
false
false
false
WycliffeAssociates/translationRecorder
translationRecorder/app/src/main/java/org/wycliffeassociates/translationrecorder/login/utils/ConvertAudio.kt
1
4415
package org.wycliffeassociates.translationrecorder.login.utils import android.media.MediaCodec import android.media.MediaCodecInfo import android.media.MediaFormat import android.media.MediaMuxer import net.gotev.uploadservice.UploadService.BUFFER_SIZE import org.apache.commons.codec.binary.Hex import org.apache.commons.codec.digest.DigestUtils import java.io.File import java.io.FileInputStream /** * Created by sarabiaj on 5/2/2018. */ const val COMPRESSED_AUDIO_FILE_MIME_TYPE = "audio/mp4a-latm" const val COMPRESSED_AUDIO_FILE_BIT_RATE = 64000 // 64kbps const val SAMPLING_RATE = 44100 const val CODEC_TIMEOUT_IN_MS = 5000 const val BUFFER_SIZE = 44100 fun convertWavToMp4(AUDIO_RECORDING_FILE_NAME: File, COMPRESSED_AUDIO_FILE_NAME: File): String { val inputFile = AUDIO_RECORDING_FILE_NAME val fis = FileInputStream(inputFile) val outputFile = COMPRESSED_AUDIO_FILE_NAME if (outputFile.exists()) outputFile.delete() val mux = MediaMuxer(outputFile.absolutePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4) var outputFormat = MediaFormat.createAudioFormat(COMPRESSED_AUDIO_FILE_MIME_TYPE, SAMPLING_RATE, 1) outputFormat.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC) outputFormat.setInteger(MediaFormat.KEY_BIT_RATE, COMPRESSED_AUDIO_FILE_BIT_RATE) val codec = MediaCodec.createEncoderByType(COMPRESSED_AUDIO_FILE_MIME_TYPE) codec.configure(outputFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE) codec.start() val codecInputBuffers = codec.inputBuffers // Note: Array of buffers val codecOutputBuffers = codec.outputBuffers val outBuffInfo = MediaCodec.BufferInfo() val tempBuffer = ByteArray(BUFFER_SIZE) var hasMoreData = true var presentationTimeUs = 0.0 var audioTrackIdx = 0 var totalBytesRead = 0 do { var inputBufIndex = 0 while (inputBufIndex != -1 && hasMoreData) { inputBufIndex = codec.dequeueInputBuffer(CODEC_TIMEOUT_IN_MS.toLong()) if (inputBufIndex >= 0) { val dstBuf = codecInputBuffers[inputBufIndex] dstBuf.clear() val bytesRead = fis.read(tempBuffer, 0, dstBuf.limit()) if (bytesRead == -1) { // -1 implies EOS hasMoreData = false codec.queueInputBuffer(inputBufIndex, 0, 0, presentationTimeUs.toLong(), MediaCodec.BUFFER_FLAG_END_OF_STREAM) } else { totalBytesRead += bytesRead dstBuf.put(tempBuffer, 0, bytesRead) codec.queueInputBuffer(inputBufIndex, 0, bytesRead, presentationTimeUs.toLong(), 0) presentationTimeUs = (1000000L * (totalBytesRead / 2) / SAMPLING_RATE).toDouble() } } } // Drain audio var outputBufIndex = 0 while (outputBufIndex != MediaCodec.INFO_TRY_AGAIN_LATER) { outputBufIndex = codec.dequeueOutputBuffer(outBuffInfo, CODEC_TIMEOUT_IN_MS.toLong()) if (outputBufIndex >= 0) { val encodedData = codecOutputBuffers[outputBufIndex] encodedData.position(outBuffInfo.offset) encodedData.limit(outBuffInfo.offset + outBuffInfo.size) if (outBuffInfo.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0 && outBuffInfo.size != 0) { codec.releaseOutputBuffer(outputBufIndex, false) } else { mux.writeSampleData(audioTrackIdx, codecOutputBuffers[outputBufIndex], outBuffInfo) codec.releaseOutputBuffer(outputBufIndex, false) } } else if (outputBufIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { outputFormat = codec.outputFormat audioTrackIdx = mux.addTrack(outputFormat) mux.start() } else if (outputBufIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { } else if (outputBufIndex == MediaCodec.INFO_TRY_AGAIN_LATER) { } else { } } } while (outBuffInfo.flags != MediaCodec.BUFFER_FLAG_END_OF_STREAM) fis.close() mux.stop() mux.release() return getHash(COMPRESSED_AUDIO_FILE_NAME) } private fun getHash(file: File): String { return String(Hex.encodeHex(DigestUtils.md5(FileInputStream(file)))) }
mit
550cbddabe6f53166329b523c7315660
38.774775
130
0.663194
4.419419
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/components/settings/DSLSettingsText.kt
1
3499
package org.thoughtcrime.securesms.components.settings import android.content.Context import android.text.SpannableStringBuilder import androidx.annotation.ColorInt import androidx.annotation.StringRes import androidx.annotation.StyleRes import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.util.SpanUtil sealed class DSLSettingsText { protected abstract val modifiers: List<Modifier> private data class FromResource( @StringRes private val stringId: Int, override val modifiers: List<Modifier> ) : DSLSettingsText() { override fun getCharSequence(context: Context): CharSequence { return context.getString(stringId) } } private data class FromCharSequence( private val charSequence: CharSequence, override val modifiers: List<Modifier> ) : DSLSettingsText() { override fun getCharSequence(context: Context): CharSequence = charSequence } protected abstract fun getCharSequence(context: Context): CharSequence fun resolve(context: Context): CharSequence { val text: CharSequence = getCharSequence(context) return modifiers.fold(text) { t, m -> m.modify(context, t) } } companion object { fun from(@StringRes stringId: Int, @ColorInt textColor: Int): DSLSettingsText = FromResource(stringId, listOf(ColorModifier(textColor))) fun from(@StringRes stringId: Int, vararg modifiers: Modifier): DSLSettingsText = FromResource(stringId, modifiers.toList()) fun from(charSequence: CharSequence, vararg modifiers: Modifier): DSLSettingsText = FromCharSequence(charSequence, modifiers.toList()) } interface Modifier { fun modify(context: Context, charSequence: CharSequence): CharSequence } class ColorModifier(@ColorInt private val textColor: Int) : Modifier { override fun modify(context: Context, charSequence: CharSequence): CharSequence { return SpanUtil.color(textColor, charSequence) } override fun equals(other: Any?): Boolean = textColor == (other as? ColorModifier)?.textColor override fun hashCode(): Int = textColor } object CenterModifier : Modifier { override fun modify(context: Context, charSequence: CharSequence): CharSequence { return SpanUtil.center(charSequence) } } object TitleLargeModifier : TextAppearanceModifier(R.style.Signal_Text_TitleLarge) object TitleMediumModifier : TextAppearanceModifier(R.style.Signal_Text_TitleMedium) object BodyLargeModifier : TextAppearanceModifier(R.style.Signal_Text_BodyLarge) open class TextAppearanceModifier(@StyleRes private val textAppearance: Int) : Modifier { override fun modify(context: Context, charSequence: CharSequence): CharSequence { return SpanUtil.textAppearance(context, textAppearance, charSequence) } override fun equals(other: Any?): Boolean = textAppearance == (other as? TextAppearanceModifier)?.textAppearance override fun hashCode(): Int = textAppearance } object BoldModifier : Modifier { override fun modify(context: Context, charSequence: CharSequence): CharSequence { return SpanUtil.bold(charSequence) } } class LearnMoreModifier( @ColorInt private val learnMoreColor: Int, val onClick: () -> Unit ) : Modifier { override fun modify(context: Context, charSequence: CharSequence): CharSequence { return SpannableStringBuilder(charSequence).append(" ").append( SpanUtil.learnMore(context, learnMoreColor) { onClick() } ) } } }
gpl-3.0
adba8f93c53506d3642f88ee230a4a12
34.343434
116
0.74507
4.97724
false
false
false
false
androidx/androidx
window/window/src/testUtil/java/androidx/window/layout/adapter/sidecar/SwitchOnUnregisterExtensionInterfaceCompat.kt
3
3034
/* * 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.window.layout.adapter.sidecar import android.app.Activity import android.graphics.Rect import androidx.annotation.GuardedBy import androidx.window.core.Bounds import androidx.window.layout.FoldingFeature import androidx.window.layout.adapter.sidecar.ExtensionInterfaceCompat.ExtensionCallbackInterface import androidx.window.layout.FoldingFeature.State import androidx.window.layout.FoldingFeature.State.Companion.FLAT import androidx.window.layout.FoldingFeature.State.Companion.HALF_OPENED import androidx.window.layout.HardwareFoldingFeature import androidx.window.layout.HardwareFoldingFeature.Type.Companion.HINGE import androidx.window.layout.WindowLayoutInfo import java.util.concurrent.locks.Lock import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock /** * An implementation of [ExtensionInterfaceCompat] that switches the state when a consumer * is unregistered. Useful for testing consumers when they go through a cycle of register then * unregister then register again. */ internal class SwitchOnUnregisterExtensionInterfaceCompat : ExtensionInterfaceCompat { private val lock: Lock = ReentrantLock() private val foldBounds = Rect(0, 100, 200, 100) @GuardedBy("mLock") private var callback: ExtensionCallbackInterface = EmptyExtensionCallbackInterface() @GuardedBy("mLock") private var state = FLAT override fun validateExtensionInterface(): Boolean { return true } override fun setExtensionCallback(extensionCallback: ExtensionCallbackInterface) { lock.withLock { callback = extensionCallback } } override fun onWindowLayoutChangeListenerAdded(activity: Activity) { lock.withLock { callback.onWindowLayoutChanged(activity, currentWindowLayoutInfo()) } } override fun onWindowLayoutChangeListenerRemoved(activity: Activity) { lock.withLock { state = toggleState(state) } } fun currentWindowLayoutInfo(): WindowLayoutInfo { return WindowLayoutInfo(listOf(currentFoldingFeature())) } fun currentFoldingFeature(): FoldingFeature { return HardwareFoldingFeature(Bounds(foldBounds), HINGE, state) } internal companion object { fun toggleState(currentState: State): State { return if (currentState == FLAT) { HALF_OPENED } else { FLAT } } } }
apache-2.0
36ba5cd864a83f6cdbe737803e2f72f2
36.925
97
0.75379
4.933333
false
false
false
false
lnr0626/cfn-templates
plugin/src/main/kotlin/com/lloydramey/cfn/scripting/CfnTemplateScript.kt
1
5288
/* * Copyright 2017 Lloyd Ramey <[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.lloydramey.cfn.scripting import com.lloydramey.cfn.model.Mapping import com.lloydramey.cfn.model.Output import com.lloydramey.cfn.model.Parameter import com.lloydramey.cfn.model.ParameterType import com.lloydramey.cfn.model.Template import com.lloydramey.cfn.model.functions.Condition import com.lloydramey.cfn.model.functions.ConditionFunction import com.lloydramey.cfn.model.resources.Resource import com.lloydramey.cfn.model.resources.ResourceProperties import com.lloydramey.cfn.model.resources.attributes.ConditionalOn import com.lloydramey.cfn.model.resources.attributes.ResourceDefinitionAttribute import com.lloydramey.cfn.scripting.helpers.ConditionDelegate import com.lloydramey.cfn.scripting.helpers.MappingDefinition import com.lloydramey.cfn.scripting.helpers.MappingDelegate import com.lloydramey.cfn.scripting.helpers.MetadataDelegate import com.lloydramey.cfn.scripting.helpers.OutputDefinition import com.lloydramey.cfn.scripting.helpers.OutputDelegate import com.lloydramey.cfn.scripting.helpers.ParameterDefinition import com.lloydramey.cfn.scripting.helpers.ParameterDelegate import com.lloydramey.cfn.scripting.helpers.ResourceDelegate import com.lloydramey.cfn.scripting.helpers.TemplateMetadata import org.jetbrains.kotlin.script.ScriptTemplateDefinition import kotlin.reflect.KClass import kotlin.reflect.full.isSubtypeOf import kotlin.reflect.full.memberProperties import kotlin.reflect.full.primaryConstructor import kotlin.reflect.full.starProjectedType typealias MappingInitializer = MappingDefinition.() -> Unit typealias ParameterInitializer = ParameterDefinition.() -> Unit typealias LazyCondition = () -> ConditionFunction typealias PropertyInitializer<T> = T.() -> Unit typealias OutputInitializer = OutputDefinition.() -> Unit @Suppress("unused") @ScriptTemplateDefinition( resolver = CfnTemplateDependencyResolver::class, scriptFilePattern = ".*\\.template\\.kts" ) abstract class CfnTemplateScript { protected var description: String = "" protected fun metadata(value: Any) = MetadataDelegate(value) protected fun mapping(init: MappingInitializer) = MappingDelegate(init) protected fun parameter(type: ParameterType, init: ParameterInitializer) = ParameterDelegate(type, init) protected fun condition(func: LazyCondition) = ConditionDelegate(func) protected inline fun <reified T : ResourceProperties> resource( vararg attributes: ResourceDefinitionAttribute, init: PropertyInitializer<T> ): ResourceDelegate<T> { val clazz = T::class requireDefaultNoArgConstructor(clazz) val properties = clazz.primaryConstructor!!.call() properties.init() properties.validate() return ResourceDelegate(properties, attributes.asList()) } protected fun output(condition: ConditionalOn? = null, init: OutputInitializer) = OutputDelegate(condition, init) internal fun toTemplate() = Template( description = description, parameters = parameters, metadata = metadata, mappings = mappings, conditions = conditions, resources = resources, outputs = outputs ) private val outputs: Map<String, Output> get() = getPropertiesOfAType<Output>().associateBy { it.id } private val resources: Map<String, Resource<ResourceProperties>> get() = getPropertiesOfAType<Resource<ResourceProperties>>().associateBy { it.id } private val conditions: Map<String, ConditionFunction> get() = getPropertiesOfAType<Condition>().associate { it.id to it.condition } private val parameters: Map<String, Parameter> get() = getPropertiesOfAType<Parameter>().associateBy { it.id } private val metadata: Map<String, Any> get() = getPropertiesOfAType<TemplateMetadata>().associate { it.name to it.value } private val mappings: Map<String, Mapping> get() = getPropertiesOfAType<Mapping>().associateBy { it.id } private inline fun <reified T : Any> getPropertiesOfAType(): List<T> { return this::class.memberProperties .filter { it.returnType.isSubtypeOf(T::class.starProjectedType) } .flatMap { listOf(it.call(this) as T?).filterNotNull() } } } fun requireDefaultNoArgConstructor(clazz: KClass<out ResourceProperties>) { if (clazz.primaryConstructor == null) { throw IllegalStateException("${clazz.qualifiedName} must declare a primary constructor") } if (!clazz.primaryConstructor!!.parameters.all { it.isOptional }) { throw IllegalStateException("${clazz.qualifiedName} must not have any required parameters in it's primary constructor") } }
apache-2.0
e25f6d074bd8829abe844daf6436b2cc
40.97619
127
0.757753
4.713012
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToStringTemplateIntention.kt
3
7238
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.util.PsiUtilCore import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.IntentionBasedInspection import org.jetbrains.kotlin.idea.util.application.runWriteActionIfPhysical import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class ConvertToStringTemplateInspection : IntentionBasedInspection<KtBinaryExpression>( ConvertToStringTemplateIntention::class, ConvertToStringTemplateIntention::shouldSuggestToConvert, problemText = KotlinBundle.message("convert.concatenation.to.template.before.text") ) open class ConvertToStringTemplateIntention : SelfTargetingOffsetIndependentIntention<KtBinaryExpression>( KtBinaryExpression::class.java, KotlinBundle.lazyMessage("convert.concatenation.to.template") ) { override fun isApplicableTo(element: KtBinaryExpression): Boolean { if (!isApplicableToNoParentCheck(element)) return false val parent = element.parent if (parent is KtBinaryExpression && isApplicableToNoParentCheck(parent)) return false return true } override fun applyTo(element: KtBinaryExpression, editor: Editor?) { val replacement = buildReplacement(element) runWriteActionIfPhysical(element) { element.replaced(replacement) } } companion object { fun shouldSuggestToConvert(expression: KtBinaryExpression): Boolean { val entries = buildReplacement(expression).entries return entries.none { it is KtBlockStringTemplateEntry } && !entries.all { it is KtLiteralStringTemplateEntry || it is KtEscapeStringTemplateEntry } && entries.count { it is KtLiteralStringTemplateEntry } >= 1 && !expression.textContains('\n') } @JvmStatic fun buildReplacement(expression: KtBinaryExpression): KtStringTemplateExpression { val rightText = buildText(expression.right, false) return fold(expression.left, rightText, KtPsiFactory(expression)) } private fun fold(left: KtExpression?, right: String, factory: KtPsiFactory): KtStringTemplateExpression { val forceBraces = right.isNotEmpty() && right.first() != '$' && right.first().isJavaIdentifierPart() return if (left is KtBinaryExpression && isApplicableToNoParentCheck(left)) { val leftRight = buildText(left.right, forceBraces) fold(left.left, leftRight + right, factory) } else { val leftText = buildText(left, forceBraces) factory.createExpression("\"$leftText$right\"") as KtStringTemplateExpression } } fun buildText(expr: KtExpression?, forceBraces: Boolean): String { if (expr == null) return "" val expression = KtPsiUtil.safeDeparenthesize(expr).let { when { (it as? KtDotQualifiedExpression)?.isToString() == true && it.receiverExpression !is KtSuperExpression -> it.receiverExpression it is KtLambdaExpression && it.parent is KtLabeledExpression -> expr else -> it } } val expressionText = expression.text when (expression) { is KtConstantExpression -> { val bindingContext = expression.analyze(BodyResolveMode.PARTIAL) val type = bindingContext.getType(expression)!! val constant = ConstantExpressionEvaluator.getConstant(expression, bindingContext) if (constant != null) { val stringValue = constant.getValue(type).toString() if (KotlinBuiltIns.isChar(type) || stringValue == expressionText) { return buildString { StringUtil.escapeStringCharacters(stringValue.length, stringValue, if (forceBraces) "\"$" else "\"", this) } } } } is KtStringTemplateExpression -> { val base = if (expressionText.startsWith("\"\"\"") && expressionText.endsWith("\"\"\"")) { val unquoted = expressionText.substring(3, expressionText.length - 3) StringUtil.escapeStringCharacters(unquoted) } else { StringUtil.unquoteString(expressionText) } if (forceBraces) { if (base.endsWith('$')) { return base.dropLast(1) + "\\$" } else { val lastPart = expression.children.lastOrNull() if (lastPart is KtSimpleNameStringTemplateEntry) { return base.dropLast(lastPart.textLength) + "\${" + lastPart.text.drop(1) + "}" } } } return base } is KtNameReferenceExpression -> return "$" + (if (forceBraces) "{$expressionText}" else expressionText) is KtThisExpression -> return "$" + (if (forceBraces || expression.labelQualifier != null) "{$expressionText}" else expressionText) } return "\${$expressionText}" } private fun isApplicableToNoParentCheck(expression: KtBinaryExpression): Boolean { if (expression.operationToken != KtTokens.PLUS) return false val expressionType = expression.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL).getType(expression) if (!KotlinBuiltIns.isString(expressionType)) return false return isSuitable(expression) } private fun isSuitable(expression: KtExpression): Boolean { if (expression is KtBinaryExpression && expression.operationToken == KtTokens.PLUS) { return isSuitable(expression.left ?: return false) && isSuitable(expression.right ?: return false) } if (PsiUtilCore.hasErrorElementChild(expression)) return false if (expression.textContains('\n')) return false return true } } }
apache-2.0
c57672dd5c2d82cb9d7655f4ffe85980
47.253333
158
0.627383
5.986766
false
false
false
false
GunoH/intellij-community
plugins/kotlin/compiler-plugins/parcelize/tests/testData/checker/properties.kt
8
1766
// WITH_STDLIB package test import kotlinx.parcelize.* import android.os.Parcelable @Parcelize class A(val firstName: String) : Parcelable { val <warning descr="[PROPERTY_WONT_BE_SERIALIZED] Property would not be serialized into a 'Parcel'. Add '@IgnoredOnParcel' annotation to remove the warning">secondName</warning>: String = "" val <warning descr="[PROPERTY_WONT_BE_SERIALIZED] Property would not be serialized into a 'Parcel'. Add '@IgnoredOnParcel' annotation to remove the warning">delegated</warning> by lazy { "" } lateinit var <warning descr="[PROPERTY_WONT_BE_SERIALIZED] Property would not be serialized into a 'Parcel'. Add '@IgnoredOnParcel' annotation to remove the warning">lateinit</warning>: String val customGetter: String get() = "" var customSetter: String get() = "" set(<warning descr="[UNUSED_PARAMETER] Parameter 'v' is never used">v</warning>) {} } @Parcelize @Suppress("WRONG_ANNOTATION_TARGET_WITH_USE_SITE_TARGET") class B(<warning descr="[INAPPLICABLE_IGNORED_ON_PARCEL_CONSTRUCTOR_PROPERTY] '@IgnoredOnParcel' is inapplicable to properties without default value declared in the primary constructor">@IgnoredOnParcel</warning> val firstName: String) : Parcelable { @IgnoredOnParcel var a: String = "" @field:IgnoredOnParcel var <warning descr="[PROPERTY_WONT_BE_SERIALIZED] Property would not be serialized into a 'Parcel'. Add '@IgnoredOnParcel' annotation to remove the warning">b</warning>: String = "" @get:IgnoredOnParcel var c: String = "" @set:IgnoredOnParcel var <warning descr="[PROPERTY_WONT_BE_SERIALIZED] Property would not be serialized into a 'Parcel'. Add '@IgnoredOnParcel' annotation to remove the warning">d</warning>: String = "" }
apache-2.0
b705c0b14d501ba3d80a138e61fdd7a8
46.756757
250
0.731031
4.470886
false
false
false
false
OnyxDevTools/onyx-database-parent
onyx-web-database/src/main/kotlin/com/onyx/endpoint/WebPersistenceEndpoint.kt
1
6877
package com.onyx.endpoint import com.fasterxml.jackson.databind.ObjectMapper import com.onyx.exception.EntityClassNotFoundException import com.onyx.exception.OnyxException import com.onyx.extension.* import com.onyx.extension.common.* import com.onyx.interactors.classfinder.ApplicationClassFinder import com.onyx.persistence.IManagedEntity import com.onyx.persistence.context.SchemaContext import com.onyx.persistence.manager.PersistenceManager import com.onyx.persistence.query.Query import com.onyx.request.pojo.* import java.io.IOException /** * Created by timothy.osborn on 4/8/15. * * This class handles JSON serialization for a persistence web service */ class WebPersistenceEndpoint(private val persistenceManager: PersistenceManager, private val objectMapper: ObjectMapper, private val context: SchemaContext) { /** * Save Entity * * @param request Entity Request Body * @return Managed entity after save with populated id */ fun save(request: EntityRequestBody): IManagedEntity { val clazz = ApplicationClassFinder.forName(request.type!!, context) val entity = objectMapper.convertValue(request.entity, clazz) persistenceManager.saveEntity(entity as IManagedEntity) return entity } /** * Find Entity * * @param request Entity Request Body * @return Hydrated entity */ operator fun get(request: EntityRequestBody): IManagedEntity { val clazz = ApplicationClassFinder.forName(request.type, context) var entity: IManagedEntity entity = if (request.entity == null) clazz.instance() else objectMapper.convertValue(request.entity, clazz) as IManagedEntity if (request.id != null) { val descriptor = entity.descriptor(context) entity[context, descriptor, descriptor.identifier!!.name] = request.id.castTo(descriptor.identifier!!.type) } entity = persistenceManager.find(entity) return entity } /** * Find an entity by id and partition value */ fun find(request: EntityFindRequest): IManagedEntity? { val clazz = ApplicationClassFinder.forName(request.type, context) return persistenceManager.findByIdInPartition(clazz, request.id!!, request.partitionValue ?: "") } /** * Delete Entity * * @param request Entity Request Body * @return Whether the entity was deleted or not */ fun delete(request: EntityRequestBody): Boolean { val clazz = ApplicationClassFinder.forName(request.type, context) val entity: IManagedEntity entity = objectMapper.convertValue(request.entity, clazz) as IManagedEntity return persistenceManager.deleteEntity(entity) } /** * Execute Query * * @param query Query Body * @return Query Result body */ fun executeQuery(query: Query): QueryResultResponseBody { val results = persistenceManager.executeQuery<Any>(query) return QueryResultResponseBody(query.resultsCount, results.toMutableList()) } /** * Initialize Relationship. Called upon a to many relationship * * @param request Initialize Body Error * @return List of relationship objects */ fun initialize(request: EntityInitializeBody): Any? { val clazz = ApplicationClassFinder.forName(request.entityType, context) val entity = clazz.getDeclaredConstructor().newInstance() as IManagedEntity if (request.entityId != null) { val descriptor = entity.descriptor(context) entity[context, descriptor, descriptor.identifier!!.name] = request.entityId.castTo(descriptor.identifier!!.type) } if (request.partitionId != null && request.partitionId != "") { val descriptor = entity.descriptor(context) entity[context, descriptor, descriptor.partition!!.field.name] = request.partitionId.castTo(descriptor.partition!!.field.type) } persistenceManager.initialize(entity, request.attribute!!) return entity.getObject(context.getDescriptorForEntity(entity).relationships[request.attribute!!]!!.field) } /** * Batch Save * * @param request List of entity body */ fun saveEntities(request: EntityListRequestBody) { val clazz = ApplicationClassFinder.forName(request.type, context) val javaType = objectMapper.typeFactory.constructCollectionType(List::class.java, clazz) val entities: List<IManagedEntity> entities = try { objectMapper.convertValue(request.entities, javaType) } catch (e: IOException) { throw EntityClassNotFoundException(OnyxException.UNKNOWN_EXCEPTION) } persistenceManager.saveEntities(entities) } /** * Batch Delete * * @param request Entity List body */ fun deleteEntities(request: EntityListRequestBody) { val clazz = ApplicationClassFinder.forName(request.type, context) val javaType = objectMapper.typeFactory.constructCollectionType(List::class.java, clazz) val entities: List<IManagedEntity> entities = try { objectMapper.convertValue(request.entities, javaType) } catch (e: IOException) { throw EntityClassNotFoundException(OnyxException.UNKNOWN_EXCEPTION) } persistenceManager.deleteEntities(entities) } /** * Execute Update * * @param query Entity Query Body * @return Query Result body */ fun executeUpdate(query: Query): Int = persistenceManager.executeUpdate(query) /** * Execute Delete * * @param query Entity Query Body * @return Query Result body */ fun executeDelete(query: Query): Int = persistenceManager.executeDelete(query) /** * Exists * * @param body Entity Request Body * @return Whether the entity exists or not */ fun existsWithId(body: EntityFindRequest): Boolean = find(body) != null /** * Save Deferred Relationships * * @param request Save Relationship Request Body */ fun saveRelationshipsForEntity(request: SaveRelationshipRequestBody) { val clazz = ApplicationClassFinder.forName(request.type, context) val entity = objectMapper.convertValue(request.entity, clazz) as IManagedEntity persistenceManager.saveRelationshipsForEntity(entity, request.relationship!!, request.identifiers!!) } /** * Returns the number of items matching the query criteria * * @param query Query request body * @return long value of number of items matching criteria * @since 1.3.0 Added as enhancement for git issue #71 */ fun countForQuery(query: Query): Long = persistenceManager.countForQuery(query) }
agpl-3.0
3a97dd550beebce0a35f3daec12f2971
32.710784
158
0.683147
5.001455
false
false
false
false
GunoH/intellij-community
platform/credential-store/src/kdbx/ProtectedValue.kt
2
4232
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.credentialStore.kdbx import com.intellij.configurationStore.JbXmlOutputter import com.intellij.credentialStore.OneTimeString import org.bouncycastle.crypto.SkippingStreamCipher import org.jdom.Element import org.jdom.Text import java.io.Writer import java.util.* internal interface SecureString { fun get(clearable: Boolean = true): OneTimeString } internal class ProtectedValue(private var encryptedValue: ByteArray, private var position: Int, private var streamCipher: SkippingStreamCipher) : Text(), SecureString { @Synchronized override fun get(clearable: Boolean): OneTimeString { val output = ByteArray(encryptedValue.size) decryptInto(output) return OneTimeString(output, clearable = clearable) } @Synchronized fun setNewStreamCipher(newStreamCipher: SkippingStreamCipher) { val value = encryptedValue decryptInto(value) synchronized(newStreamCipher) { position = newStreamCipher.position.toInt() newStreamCipher.processBytes(value, 0, value.size, value, 0) } streamCipher = newStreamCipher } @Synchronized private fun decryptInto(out: ByteArray) { synchronized(streamCipher) { streamCipher.seekTo(position.toLong()) streamCipher.processBytes(encryptedValue, 0, encryptedValue.size, out, 0) } } override fun getText() = throw IllegalStateException("encodeToBase64 must be used for serialization") fun encodeToBase64(): String { return when { encryptedValue.isEmpty() -> "" else -> Base64.getEncoder().encodeToString(encryptedValue) } } } internal class UnsavedProtectedValue(val secureString: StringProtectedByStreamCipher) : Text(), SecureString by secureString { override fun getText() = throw IllegalStateException("Must be converted to ProtectedValue for serialization") } internal class ProtectedXmlWriter(private val streamCipher: SkippingStreamCipher) : JbXmlOutputter(isForbidSensitiveData = false) { override fun writeContent(out: Writer, element: Element, level: Int): Boolean { if (element.name != KdbxEntryElementNames.value) { return super.writeContent(out, element, level) } val value = element.content.firstOrNull() if (value is SecureString) { val protectedValue: ProtectedValue if (value is ProtectedValue) { value.setNewStreamCipher(streamCipher) protectedValue = value } else { val bytes = (value as UnsavedProtectedValue).secureString.getAsByteArray() synchronized(streamCipher) { val position = streamCipher.position.toInt() streamCipher.processBytes(bytes, 0, bytes.size, bytes, 0) protectedValue = ProtectedValue(bytes, position, streamCipher) } element.setContent(protectedValue) } out.write('>'.code) out.write(escapeElementEntities(protectedValue.encodeToBase64())) return true } return super.writeContent(out, element, level) } } internal fun isValueProtected(valueElement: Element): Boolean { return valueElement.getAttributeValue(KdbxAttributeNames.protected).equals("true", ignoreCase = true) } internal class XmlProtectedValueTransformer(private val streamCipher: SkippingStreamCipher) { private var position = 0 fun processEntries(parentElement: Element) { // we must process in exact order for (element in parentElement.content) { if (element !is Element) { continue } if (element.name == KdbxDbElementNames.group) { processEntries(element) } else if (element.name == KdbxDbElementNames.entry) { for (container in element.getChildren(KdbxEntryElementNames.string)) { val valueElement = container.getChild(KdbxEntryElementNames.value) ?: continue if (isValueProtected(valueElement)) { val value = Base64.getDecoder().decode(valueElement.text) valueElement.setContent(ProtectedValue(value, position, streamCipher)) position += value.size } } } } } }
apache-2.0
18ecef5b7ad04922b4e1fcc4fb242b79
33.983471
131
0.711484
4.739082
false
false
false
false
GunoH/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/ExternalSystemModulePropertyManagerImpl.kt
7
7808
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.externalSystem.service.project import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.externalSystem.ExternalSystemModulePropertyManager import com.intellij.openapi.externalSystem.model.ProjectSystemId import com.intellij.openapi.externalSystem.model.project.ModuleData import com.intellij.openapi.externalSystem.model.project.ProjectData import com.intellij.openapi.module.Module import com.intellij.openapi.project.isExternalStorageEnabled import com.intellij.openapi.roots.ExternalProjectSystemRegistry import com.intellij.openapi.roots.ProjectModelElement import com.intellij.openapi.roots.ProjectModelExternalSource import com.intellij.util.xmlb.annotations.Attribute import com.intellij.util.xmlb.annotations.Transient import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty val EMPTY_STATE: ExternalStateComponent = ExternalStateComponent() /** * This class isn't used in the new implementation of project model, which is based on [Workspace Model][com.intellij.workspaceModel.ide]. * It shouldn't be used directly, its interface [ExternalSystemModulePropertyManager] should be used instead. */ @State(name = "ExternalSystem") class ExternalSystemModulePropertyManagerImpl(private val module: Module) : ExternalSystemModulePropertyManager(), PersistentStateComponent<ExternalStateComponent>, ProjectModelElement { override fun getExternalSource(): ProjectModelExternalSource? = store.externalSystem?.let { ExternalProjectSystemRegistry.getInstance().getSourceById(it) } private var store = if (module.project.isExternalStorageEnabled) ExternalStateComponent() else ExternalStateModule(module) override fun getState(): ExternalStateComponent = store as? ExternalStateComponent ?: EMPTY_STATE override fun loadState(state: ExternalStateComponent) { store = state } override fun getExternalSystemId(): String? = store.externalSystem override fun getExternalModuleType(): String? = store.externalSystemModuleType override fun getExternalModuleVersion(): String? = store.externalSystemModuleVersion override fun getExternalModuleGroup(): String? = store.externalSystemModuleGroup override fun getLinkedProjectId(): String? = store.linkedProjectId override fun getRootProjectPath(): String? = store.rootProjectPath override fun getLinkedProjectPath(): String? = store.linkedProjectPath override fun isMavenized(): Boolean = store.isMavenized override fun setMavenized(mavenized: Boolean) { if (mavenized) { // clear external system API options // see com.intellij.openapi.externalSystem.service.project.manage.ModuleDataService#setModuleOptions unlinkExternalOptions() } // must be after unlinkExternalOptions store.isMavenized = mavenized } override fun swapStore() { val oldStore = store val isMaven = oldStore.isMavenized if (oldStore is ExternalStateModule) { store = ExternalStateComponent() } else { store = ExternalStateModule(module) } store.externalSystem = if (store is ExternalStateModule && isMaven) null else oldStore.externalSystem if (store !is ExternalStateComponent) { // do not set isMavenized for ExternalStateComponent it just set externalSystem store.isMavenized = isMaven } store.linkedProjectId = oldStore.linkedProjectId store.linkedProjectPath = oldStore.linkedProjectPath store.rootProjectPath = oldStore.rootProjectPath store.externalSystemModuleGroup = oldStore.externalSystemModuleGroup store.externalSystemModuleVersion = oldStore.externalSystemModuleVersion if (oldStore is ExternalStateModule) { oldStore.isMavenized = false oldStore.unlinkExternalOptions() } } override fun unlinkExternalOptions() { store.unlinkExternalOptions() } override fun setExternalOptions(id: ProjectSystemId, moduleData: ModuleData, projectData: ProjectData?) { // clear maven option, must be first store.isMavenized = false store.externalSystem = id.toString() store.linkedProjectId = moduleData.id store.linkedProjectPath = moduleData.linkedExternalProjectPath store.rootProjectPath = projectData?.linkedExternalProjectPath ?: "" store.externalSystemModuleGroup = moduleData.group store.externalSystemModuleVersion = moduleData.version } override fun setExternalId(id: ProjectSystemId) { store.externalSystem = id.id } override fun setLinkedProjectPath(path: String?) { store.linkedProjectPath = path } override fun setRootProjectPath(path: String?) { store.rootProjectPath = path } override fun setExternalModuleType(type: String?) { store.externalSystemModuleType = type } } private interface ExternalOptionState { var externalSystem: String? var externalSystemModuleVersion: String? var linkedProjectPath: String? var linkedProjectId: String? var rootProjectPath: String? var externalSystemModuleGroup: String? var externalSystemModuleType: String? var isMavenized: Boolean } private fun ExternalOptionState.unlinkExternalOptions() { externalSystem = null linkedProjectId = null linkedProjectPath = null rootProjectPath = null externalSystemModuleGroup = null externalSystemModuleVersion = null } @Suppress("DEPRECATION") private class ModuleOptionDelegate(private val key: String) : ReadWriteProperty<ExternalStateModule, String?> { override operator fun getValue(thisRef: ExternalStateModule, property: KProperty<*>) = thisRef.module.getOptionValue(key) override operator fun setValue(thisRef: ExternalStateModule, property: KProperty<*>, value: String?) { thisRef.module.setOption(key, value) } } @Suppress("DEPRECATION") private class ExternalStateModule(internal val module: Module) : ExternalOptionState { override var externalSystem by ModuleOptionDelegate(ExternalProjectSystemRegistry.EXTERNAL_SYSTEM_ID_KEY) override var externalSystemModuleVersion by ModuleOptionDelegate("external.system.module.version") override var externalSystemModuleGroup by ModuleOptionDelegate("external.system.module.group") override var externalSystemModuleType by ModuleOptionDelegate("external.system.module.type") override var linkedProjectPath by ModuleOptionDelegate("external.linked.project.path") override var linkedProjectId by ModuleOptionDelegate("external.linked.project.id") override var rootProjectPath by ModuleOptionDelegate("external.root.project.path") override var isMavenized: Boolean get() = "true" == module.getOptionValue(ExternalProjectSystemRegistry.IS_MAVEN_MODULE_KEY) set(value) { module.setOption(ExternalProjectSystemRegistry.IS_MAVEN_MODULE_KEY, if (value) "true" else null) } } class ExternalStateComponent : ExternalOptionState { @get:Attribute override var externalSystem: String? = null @get:Attribute override var externalSystemModuleVersion: String? = null @get:Attribute override var externalSystemModuleGroup: String? = null @get:Attribute override var externalSystemModuleType: String? = null @get:Attribute override var linkedProjectPath: String? = null @get:Attribute override var linkedProjectId: String? = null @get:Attribute override var rootProjectPath: String? = null @get:Transient override var isMavenized: Boolean get() = externalSystem == ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID set(value) { externalSystem = if (value) ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID else null } }
apache-2.0
592b167cc71c416bed1b871e2338da9e
36.543269
147
0.781634
5.471619
false
false
false
false
idea4bsd/idea4bsd
plugins/settings-repository/src/git/JGitProgressMonitor.kt
30
1412
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository.git import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import org.eclipse.jgit.lib.NullProgressMonitor import org.eclipse.jgit.lib.ProgressMonitor fun ProgressIndicator?.asProgressMonitor() = if (this == null || this is EmptyProgressIndicator) NullProgressMonitor.INSTANCE else JGitProgressMonitor(this) private class JGitProgressMonitor(private val indicator: ProgressIndicator) : ProgressMonitor { override fun start(totalTasks: Int) { } override fun beginTask(title: String, totalWork: Int) { indicator.text2 = title } override fun update(completed: Int) { // todo } override fun endTask() { indicator.text2 = "" } override fun isCancelled() = indicator.isCanceled }
apache-2.0
17fe55f1e4555523980a9ceec6d74644
32.642857
156
0.76204
4.318043
false
false
false
false
siosio/intellij-community
python/src/com/jetbrains/python/refactoring/suggested/PySuggestedRefactoringSupport.kt
2
4831
// 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.refactoring.suggested import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.psi.util.hasErrorElementInRange import com.intellij.refactoring.suggested.* import com.jetbrains.python.PyNames import com.jetbrains.python.PyTokenTypes import com.jetbrains.python.psi.PyElement import com.jetbrains.python.psi.PyFunction import com.jetbrains.python.psi.PyParameter import com.jetbrains.python.psi.PyParameterList import com.jetbrains.python.psi.types.TypeEvalContext import com.jetbrains.python.pyi.PyiUtil class PySuggestedRefactoringSupport : SuggestedRefactoringSupport { companion object { internal fun isAvailableForChangeSignature(element: PsiElement): Boolean { return element is PyFunction && element.name.let { it != null && PyNames.isIdentifier(it) } && element.property == null && !shouldBeSuppressed(element) } internal fun defaultValue(parameter: SuggestedRefactoringSupport.Parameter): String? { return (parameter.additionalData as? ParameterData)?.defaultValue } internal fun isAvailableForRename(element: PsiElement): Boolean { return element is PsiNameIdentifierOwner && element.name.let { it != null && PyNames.isIdentifier(it) } && (element !is PyParameter || containingFunction(element).let { it != null && !isAvailableForChangeSignature(it) }) && !shouldBeSuppressed(element) } internal fun shouldSuppressRefactoringForDeclaration(state: SuggestedRefactoringState): Boolean { // don't merge with `shouldBeSuppressed` because `shouldBeSuppressed` could be invoked in EDT and resolve below could slow down it val element = state.restoredDeclarationCopy() return PyiUtil.isOverload(element, TypeEvalContext.codeAnalysis(element.project, element.containingFile)) } private fun shouldBeSuppressed(element: PsiElement): Boolean { if (PyiUtil.isInsideStub(element)) return true if (element is PyElement && PyiUtil.getPythonStub(element) != null) return true return false } private fun containingFunction(parameter: PyParameter): PyFunction? { return (parameter.parent as? PyParameterList)?.containingFunction } } override fun isDeclaration(psiElement: PsiElement): Boolean = findSupport(psiElement) != null override fun signatureRange(declaration: PsiElement): TextRange? = findSupport(declaration)?.signatureRange(declaration)?.takeIf { !declaration.containingFile.hasErrorElementInRange(it) } override fun importsRange(psiFile: PsiFile): TextRange? = null override fun nameRange(declaration: PsiElement): TextRange? = (declaration as? PsiNameIdentifierOwner)?.nameIdentifier?.textRange override fun isIdentifierStart(c: Char): Boolean = c == '_' || Character.isLetter(c) override fun isIdentifierPart(c: Char): Boolean = isIdentifierStart(c) || Character.isDigit(c) override val stateChanges: SuggestedRefactoringStateChanges = PySuggestedRefactoringStateChanges(this) override val availability: SuggestedRefactoringAvailability = PySuggestedRefactoringAvailability(this) override val ui: SuggestedRefactoringUI = PySuggestedRefactoringUI override val execution: SuggestedRefactoringExecution = PySuggestedRefactoringExecution(this) internal data class ParameterData(val defaultValue: String?) : SuggestedRefactoringSupport.ParameterAdditionalData private fun findSupport(declaration: PsiElement): SupportInternal? { return sequenceOf(ChangeSignatureSupport, RenameSupport(this)).firstOrNull { it.isApplicable(declaration) } } private interface SupportInternal { fun isApplicable(element: PsiElement): Boolean fun signatureRange(declaration: PsiElement): TextRange? } private object ChangeSignatureSupport : SupportInternal { override fun isApplicable(element: PsiElement): Boolean = isAvailableForChangeSignature(element) override fun signatureRange(declaration: PsiElement): TextRange? { declaration as PyFunction val name = declaration.nameIdentifier ?: return null val colon = declaration.node.findChildByType(PyTokenTypes.COLON) ?: return null return TextRange.create(name.startOffset, colon.startOffset) } } private class RenameSupport(private val mainSupport: PySuggestedRefactoringSupport) : SupportInternal { override fun isApplicable(element: PsiElement): Boolean = isAvailableForRename(element) override fun signatureRange(declaration: PsiElement): TextRange? = mainSupport.nameRange(declaration) } }
apache-2.0
a71812d48b74711a0b3f05c5333f8e08
43.330275
140
0.772718
5.200215
false
false
false
false